text:
Q: SARSA with Linear Function Approximation weight overflow I'm trying to solve the CartPole problem, implemented in OpenAI Gym.
In each state the agent is able to perform one of 2 actions move left or right.
The reward is always +1. The epsiode ends after 500 steps or when the pole falls over. The state consists of 4 values the cart's position, velocity, the pole angle
and the angleRate (I'm not quite sure what the last one means).
I've omitted the position because it makes no difference where the cart is except for some rare edge cases, when the cart would go out of bounds.
I tried to solve this problem by approximating the state action value $Q(s,a)$ with SARSA and a linear function for each action. The problem is that the algorithm is able to learn how to balance the pole for 500 steps but then it jumps back to around 100. It proceeds to cycle while the weights start to grow rapidly until they overflow.

The state contains no information about the amount of steps until the episode ends and maybe because of that it starts to approximate an infinite reward. But even with the time included the weights overflow.
I've also tried to use the sklearn LinearRegressor to check if my regression implementation is wrong. The Regressor didn't overflow but it did not even come close to a reward of 500.
The last thing I tried was to use combined states like $positon * velocity$ and $velocity * pole angle$ etc. But that didn't fix the overflowing it just helped to reach the reward of 500 more often.
So I'm out of ideas why my weights keeps overflowing. Below is a shorter but working version of my code. I do not think that there is a problem with my code but it seems like I'm doing something fundamentaly wrong.
import random as rand
import numpy as np
import gym
import sys

class SemiGradientSarsaAgent:

    def __init__(self, stateSize, actions, explorationRate, stepSize, rewardDiscount):
        self.actions = np.array(actions)
        self.weights = np.zeros((len(actions), stateSize), dtype=np.float32)
        self.explorationRate = explorationRate
        self.stepSize = stepSize
        self.rewardDiscount = rewardDiscount

    def chooseAction(self, state):
        return self.__chooseActionInternal__(state)[1]

    def learn(self, state, action, newState, reward, done):
        prevQValue = self.__getQValue__(state, action)
        if done:
            step = self.stepSize * (reward - prevQValue)
        else:
            nextQValue = self.__chooseActionInternal__(newState)[0]
            step = self.stepSize * (reward + self.rewardDiscount * nextQValue - prevQValue)

        # Gradient descent: The Gradient for the weights is the state itself
        gradient = state
        self.weights[action] += step * gradient

    def __chooseActionInternal__(self, state):
        # Epsilon Greedy
        qValues = np.array([self.__getQValue__(state, action) for action in self.actions])
        if rand.random() < self.explorationRate:
            index = rand.choice(range(len(self.actions)))
        else:
            index = np.argmax(qValues)

        return (qValues[index], self.actions[index])

    # Calculate the QValue with a linear function
    def __getQValue__(self, state, action):
        return np.sum(state * self.weights[action])

def trainAgent(agent, episodes = 1):
    env = gym.make('CartPole-v1')
    totalRewards = []
    for i in range(episodes):
        sys.stdout.write("\rEpisode {}\\{}".format(i + 1, episodes))
        state = env.reset()
        # throw out the position
        state = np.array([*state[1:]])
        totalReward = 0
        # Run one episode and train the agent
        while True:
            action = agent.chooseAction(state)
            newState, reward, done, _ = env.step(action)
            # throw out the position
            newState = np.array([*newState[1:]])

            totalReward += reward
            agent.learn(state, action, newState, reward, done)

            if done:
                break

            state = newState

        totalRewards.append(totalReward)

    return totalRewards

agent = SemiGradientSarsaAgent(3, np.array([0, 1]), 0.1, 0.8, 1)
rewards = trainAgent(agent, 3000)


text:
Q: Set Global Parameters Symfony2 I am using Symfony2. For my application I need to set some global parameters for this.
I have defined parameter in my parameters.ini file as:
#app/config/parameters.ini

[parameters]
    mailer_auth_mode="login"
    user_thumbnail_path="images/user/thumbnail"

I am able to access this in my controller with the following code:
$this->container->getParameter('user_thumbnail_path');

As I am using FOSUserBundle and I have override ProfileHandler class and in this class I want to use the parameter but I don't know how.

A: Create your own hander or extends the one that you want.
Register it as a service.
my.handler:
    class: Acme\MyBundle\Form\Handler\MyHandler
    arguments: ...

Then set the service id as the handler for the form you want to handle.
fos_user:
    ...
    registration:
        form:
           handler: my.handler

redpajama_set_name: RedPajamaStackExchange


text:
Q: kubernetes cannot resolve domain properly After I upgraded Kubernetes to v1.7, the the domains in Nginx config and other MySQL connection fails.
this log is from Nginx:
nginx: [emerg] host not found in upstream "subdomain.domain.com"

this log is from a python app:
OperationalError: (_mysql_exceptions.OperationalError) (2005, "Unknown MySQL server host 'rm-xxxxxxxxxx.mysql.rds.provider.com' (110)")

And another connection with pymongo timed out.
All I mentioned above worked fine when I was using v1.6 or without kubernetes. I wonder if there were any differences between kubernetes v1.6 and v1.7 could result in this problem? kube-proxy should be blamed for this in my opionion, but I cannot figure it out.

A: I have not enough reputation to add comment ,
can you check your kube-dns is running well?
and you can enter in the pod to set the resolv.conf of the nameserver 8.8.8.8, try it check use other dns can work


text:
Q: Code for DisplayAlerts No Longer Working VBA I wrote a VBA code to import data from other excel sheets and also close out of those when I no longer need them. It used to run without the annoying pop ups asking me if I want to keep the copied values to paste later but all of the sudden this window started popping up again. I'm not sure what happened. My display alerts are off. Any advice? Below is a copy of my code.

Option Explicit
    Dim FileToOpen As Variant
    Dim Openbook As Workbook
    Dim LastRow As Long

Sub Entry_Point()
    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .Calculation = xlCalculationManual
        .StatusBar = "Your Assistant is Busy Working"
    End With
End Sub

Sub Exit_Point()

With Application
    .ScreenUpdating = True
    .DisplayAlerts = True
    .Calculation = xlCalculationAutomatic
    .CutCopyMode = False
    .StatusBar = ""
End With

End Sub

Sub Import_Data()

Call Entry_Point
Call Get_FastTrack
Call Get_Balance
FTPay.Activate
Call Exit_Point

End Sub

Sub Get_FastTrack()

    FTPay.Range("a8:I10004").Clear
    FTPay.Range("M8:N100").Clear

    'Select import file for the FT import Data tab

    MsgBox "Select file for the Fast Track Draw Import"

    FileToOpen = Application.GetOpenFilename(Title:="Select file for the Fast Track Draw Import")

        If FileToOpen <> False Then
            Set Openbook = Application.Workbooks.Open(FileToOpen)

            'Select range to copy
            LastRow = Range("A" & Rows.Count).End(xlUp).Row
            Openbook.Sheets(1).Range("A2:I" & LastRow).Copy
            FTPay.Range("a8").PasteSpecial xlPasteValuesAndNumberFormats
            Openbook.Close False
        MsgBox "Fast Track Draw has been imported.", vbInformation, Title:="Import Complete"

        Else
        MsgBox "Fast Track Data not imported.", vbCritical, Title:="Import Fail"
        End If

  End Sub

Sub Get_Balance()

    Balance.Range("B4:J100").Clear

    'Select import file for the Rep/Sup Draw Balance Data tab

    MsgBox "Select file for the Rep/Sup Draw Balance Import"

    FileToOpen = Application.GetOpenFilename(Title:="Select file for the Rep/Sup Draw Balance Import")

        If FileToOpen <> False Then
            Set Openbook = Application.Workbooks.Open(FileToOpen)

            'Select range to copy
            LastRow = Range("A" & Rows.Count).End(xlUp).Row
            Openbook.Sheets(1).Range("A2:I" & LastRow).Copy
            Balance.Range("B4").PasteSpecial xlPasteValuesAndNumberFormats
            Openbook.Close False
        MsgBox "Rep/Sup Draw Balance has been imported.", vbInformation, Title:="Import Complete"

        'Filter totals smallest to largest

            With ActiveSheet.Sort
            .SortFields.Add Key:=Range("J3"), Order:=xlAscending
            .SetRange Range("B3:J100")
            .Header = xlYes
            .Apply
End With
        Else
        MsgBox "Rep/Sup Draw Balance not imported.", vbCritical, Title:="Import Fail"
        End If
End Sub


text:
Q: Filter array of paths to keep only the shallowest paths Given an array of randomly sorted paths, I'd like to filter it so only the shallowest paths stay in the array. Any sub-paths should be removed.
My attempt below does filter some paths, but the end result is wrong and should be an array containing only these:
[ '/video', '/audio', '/code', '/images', '/test/noparent' ]
var paths = [
  '/code/client/images',
  '/code/client/templates/views',
  '/code/another/templates/views',
  '/code/client/svg',
  '/images',
  '/code/another',
  '/code/client',
  '/audio/asdasd',
  '/audio/asd',
  '/code/client/html',
  '/video',
  '/code/client/templates',
  '/audio/asd/asdasd',
  '/code/another/html',
  '/code/another/images',
  '/code/another/svg',
  '/code/another/templates',
  '/code',
  '/audio',
  '/test/noparent'
];

// prepare by sorting paths by number of slashes
paths.sort(function (a, b) {
  return a.match(/\//g).length - b.match(/\//g).length;
});

// filter (this fails)
paths.filter(function (path) {
  var keep = true;
  paths.forEach(function (another) {
      if (another.indexOf(path) === 0 && another !== path) keep = false;
  });
  return keep;
});

Maybe there's a solution that doesn't iterate more than once?

A: You need to reverse the existence of the strings. Check if the current path is a one which no other path fits (indexOf) inside of it.
paths.filter(function (path) {
  var keep = true;
  paths.forEach(function (another) {
      if (path.indexOf(another) === 0 && another !== path) keep = false;
  });
  return keep;
});

A: Here's the solution I just camp up with:
paths.filter(function (path) {
  return paths.every(function (another) {
     return another === path || path.indexOf(another) !== 0;
  });
});


text:
Q: How to implement Slide Effect in bxslider for Ajax generated li's content Currently I am implemented a bxslider with ajax generated li's. Everything is fine in ajax requests & content is fetching fine. I also added bxslider navigation code in to ajax navigation.
My problem is that: While using ajax navigation buttons, slider effect of bxslider is not working.
My bxslider code is here:
     $(document).ready(function(){
           myReadyFunction();
     });

function myReadyFunction(){

        var slider = $('#moreStories').bxSlider({
                             mode: 'horizontal',
                             speed:900,
                             controls: true,
                             pager: false,
                             displaySlideQty: 3,
                             moveSlideQty:1,
                             ticker: false,
                      });

       $('#go_prev').live("click", function(){
           ///alert("prev");
               slider.goToPreviousSlide();
            return false;
      });

      $('#go_next').live("click", function(){
        //alert("next");
        top.window.close();
        slider.goToNextSlide();
        return false;
      });

}

And below is my code to access ajax content via jquery:
function loadData(page)
{
     loading_show();
     $.ajax({
               type: "POST",
       url: "load_page.php",
       data: "page="+page,
       success: function(msg){
          $(".ajaxBased").ajaxComplete(function(event, request, settings){
            loading_hide();
            $(".ajaxBased").html(msg);
          });
         }
      });
}
    loadData(1);  // For first time page load default results
    $('.ajaxBased #navigation a.active').live('click',function(){
        var page = $(this).attr('p');
        loadData(page)
    });

Can anybody help me to get out this slider problem, I have also search the forum, but could't find exact solution.


text:
Q: Should an SQL Union or Join be used? I'm trying to get the zip codes and the # of calls for that zip code for 2 tables I have, patients and physicians. I'm getting the #of calls by counting the zip code, like if there are 5 patients with zip code 79555 then the count would be 5. If patients table has 3 people with that zip and physicians table has 4, it should return the zip code and 7. I tried the union below. At first glance it looks like it does what I want, but I want duplicate zip codes to be summed up, can I use the sum function in a union? Or do I have to create a join?
SELECT zip_code, COUNT(zip_code) AS Num_Patient_Calls FROM patients GROUP BY zip_code
UNION ALL
SELECT zip_code, COUNT(zip_code) AS Num_Physician_Calls FROM physicians GROUP BY zip_code

EDIT: Solution
I used the responses from Gordon and dweiss to produce this SQL code. It does what I want, which is take two fields from unrelated tables which may or may not have the same value, count the number of records which have that value in each of the tables, then sum the results from both tables. Example: 6 instances of the zip code 99709 in patients table, 1 in physicians table, value displayed is 99709 - 7.
SELECT zip_code, SUM(Patient_Calls) FROM (
    SELECT zip_code, COUNT(zip_code) AS Patient_Calls FROM patients GROUP BY zip_code
    UNION ALL
    SELECT zip_code, COUNT(zip_code) AS Physician_Calls FROM physicians GROUP BY zip_code
) AS new_table
GROUP BY zip_code ORDER BY `new_table`.`zip_code`

A: As these are unrelated tables, you want to use a UNION.  Also, COUNT and SUM are different functions, and in this case you're looking for COUNT.  SUM will add all the values up whereas COUNT will give you the number of times the row is found in a GROUP.
How about something like this?
SELECT zip_code,COUNT(*) FROM (
SELECT zip_code AS Num_Patient_Calls FROM patients
UNION ALL
SELECT zip_code AS Num_Physician_Calls FROM physicians
) AS new_table
GROUP BY zip_code

A: In order to answer your question, you need either a UNION ALL or FULL OUTER JOIN, because you may have zip codes with only one type of call.
I would structure the results as such:
select zip_code, sum(Patient_Call) as Num_Patient_Calls,
       sum(Physician_Call) as Num_Physician_Calls,
       sum(Patient_Call + Physician_Call) as Num_Calls
from
(
  (SELECT zip_code, 1 AS Patient_Call, 0 as Physician_Call
   FROM patients
  )
  UNION ALL
  (SELECT zip_code, 0 AS Patient_Call, 1 as Physician_Call
   FROM physicians
  )
) calls
GROUP BY zip_code

If you are running this query multiple times, you can experiment with aggregating within each subquery, to see if that is faster (for instance, if there is an index on zip_code, then it may be faster).


text:
Q: $http request with a $scope value included in url say i am making a $http request
    $http.get('http://api.worldweatheronline.com/free/v2/weather.ashx?q=Manchester&format=json&num_of_days=5&key=1e9bfc54489901fe117e6f2877018')
.success(function(response) {
    $scope.worldweather = response;
});

but i want to replace the city name in the url with a scope value, i figured id be able to do it like this but alas no. Any suggestions?
$scope.city = 'Manchester';

    $http.get('http://api.worldweatheronline.com/free/v2/weather.ashx?q=' + city + '&format=json&num_of_days=5&key=1e9bfc54489901fe117e6f2877018')
.success(function(response) {
    $scope.worldweather = response;
});

A: city is a variable in the current context. $scope.city is a property on the $scope object. They are not the same thing. Try:
    $http.get('http://api.worldweatheronline.com/free/v2/weather.ashx?q=' + $scope.city + '&format=json&num_of_days=5&key=1e9bfc54489901fe117e6f2877018')

But in general, it may be easier to use params to $http for the query string rather than building it manually
 $http.get('http://api.worldweatheronline.com/free/v2/weather.ashx',{
   params: {
    q:$scope.city,
    format:json,
    num_of_days:5,
    key: 1e9bfc54489901fe117e6f2877018
   })


text:
Q: Relation Conditions with Variables I have the following models:
class Publication < ActiveRecord::Base
  has_many :reviews
  has_many :users, :through => :owned_publications
  has_many :owned_publications
end

class User < ActiveRecord::Base
  has_many :publications, :through => :owned_publications
  has_many :owned_publications
end

class OwnedPublication < ActiveRecord::Base
  belongs_to :publication
  belongs_to :user
  has_one :review, :conditions => "user_id = #{self.user.id} AND publication_id = #{self.publication.id}"
end

In the third model, I'm trying to set a condition with a pair of variables. It seems like the syntax works, except that self is not an instance of OwnedPublication. Is it possible to get the current instance of OwnedPublication and place it into a condition?

A: The solution requires the use of :through and :source options, as well as a proc call:
has_one :review, :through => :publication, :source => :reviews,
  :conditions => proc { ["user_id = ?", self.user_id] }

Proc is the trick to passing in dynamic variables to ActiveRecord association conditions, at least as of Rails 3.0. Simply calling:
has_one :conditions => proc { ["publication_id = ? AND user_id = ?",
  self.publication_id, self.user_id] }

will not work, though. This is because the association will end up searching the reviews table for a 'reviews.owned_publication_id' column, which does not exist. Instead, you can find the proper review through publication, using publication's :reviews association as the source.

A: I think your best bet is to just have the Review record belong_to an OwnedPublication, and setup your Publication model to get the reviews via a method:
def reviews
  review_objects = []
  owned_publications.each do |op|
    review_objects << op
  end
  review_objects
end

Might be a more efficient way if you use a subquery to get the information, but it removes the concept of having unnecessary associations.


text:
Q: How to read in XML from web service and query rowset attributes in C#? Here is the sample XML that I am receiving from the web service.
<xml xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'
xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
xmlns:rs='urn:schemas-microsoft-com:rowset'
xmlns:z='#RowsetSchema'>
<s:Schema id='RowsetSchema'>
<s:ElementType name='row' content='eltOnly'>
    <s:AttributeType name='NAME' rs:number='1'>
        <s:datatype dt:type='string' rs:dbtype='str' dt:maxLength='25'
         rs:maybenull='false'/>
    </s:AttributeType>
    <s:AttributeType name='DESCRIPTION' rs:number='2' rs:nullable='true'
         rs:writeunknown='true'>
        <s:datatype dt:type='string' rs:dbtype='str' dt:maxLength='80'/>
    </s:AttributeType>
    <s:extends type='rs:rowbase'/>
</s:ElementType>
</s:Schema>
<rs:data>
<z:row NAME='JOE BLOW' DESCRIPTION='PROGRAMMER'/>
<z:row NAME='ANN SMITH' DESCRIPTION='FRONT DESK'/>
<z:row NAME='STEVE JOHNSON' DESCRIPTION='TESTER'/>
</rs:data>
</xml>

I'm not sure how to go about getting to the <rs:data> node. I eventually want to enumerate through each <z:row> and get the attributes NAME and DESCRPTION. The webservice returns this to me as a string so I load the string into an XMLDocument like this:
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xmlString);

Now, I'm not sure if I need to use a XmlNamespaceManager in order to tel my xDoc to import the <s:Schema>
I've tried to select a single node with an XPath with no luck because of the prefix rs.
XmlNode xNode = xDoc.SelectSingleNode("/rs:data");

If there is any further information needed, please ask.

A: If you are taking the xml as a string try parsing it like instead of using Load()
var xml = XDocument.Parse(xmlstring);

You have to use the namespace to get hold of the data properly.
XNamespace ns = "#RowsetSchema";

foreach (var element in xml.Descendants().Elements(ns + "row"))
{
    Console.WriteLine ("Name = " + element.Attribute("NAME").Value + ", " + "Description = " + element.Attribute("DESCRIPTION").Value);
}

A: Here's some classes for handling your xml, using these extensions: http://searisen.com/xmllib/extensions.wiki
public class Test
{
    XElement self;
    public Test(XElement self)
    {
        this.self = self;
    }

    public RSDataRow[] DataRows
    {
        get
        {
            if (null == _DataRows)
            {
                _DataRows = self.GetEnumerable("rs:data/z:row", xrow => new RSDataRow(xrow)).ToArray();
            }
            return _DataRows;
        }
    }
    RSDataRow[] _DataRows;
}

[DebuggerDisplay("{Name}")]
public class RSDataRow
{
    XElement self;
    public RSDataRow(XElement self)
    {
        this.self = self;
    }

    public string Name
    {
        get { return self.Get("NAME", string.Empty); }
    }

    public string Description
    {
        get { return self.Get("DESCRIPTION", string.Empty); }
    }
}

You use it like:
Test test = new Test(XElement.Parse(xmlstring));
foreach (RSDataRow row in test.DataRows)
{
    string name = row.Name;
    string desc = row.Description;
}

A: Using xml with linq it can be done like this:
XDocument xmlDoc = new XDocument();
xmlDoc = XDocument.Parse(xml);

XNamespace ns = "#RowsetSchema";

var namesDescs = from namesDesc in xmlDoc.Descendants().Elements(ns + "row")
    select new
    {
       name = namesDesc.Attribute("NAME").Value,
       description = namesDesc.Attribute("DESCRIPTION").Value,
    };


text:
Q: Random forest model in r Is there any way, where we can create multiple random forest models by fine-tuning hyper parameters on train data and check the test data performance against all models and store it in a csv file?
For ex:- i have one model with mtry is 6, nodesize is 3, and another model where mtryis 10 and nodesize is 4 What i need to do is to test these two models performance on test data and store the key model metrics like confusion matrix, sensitivity, and specificity.
i have tried the following code
train_performance <- data.frame('TN'=0,'FP'=0,'FN'=0,'TP'=0,'accuracy'=0,'kappa'=0,'sensitivity'=0,'specificity'=0)
modellist <- list()

for (mtry in c(6,11)){
  for (nodesize in c(2,3)){
    fit_model <- randomForest(dv~., train_final,mtry = mtry, importance=TRUE, nodesize=nodesize,
                                sampsize = ceiling(.8*nrow(train_final)), proximity=TRUE,na.action = na.omit,
                            ntree=500)
      Key_col <- paste0(mtry,"-",nodesize)
      modellist[[Key_col]] <- fit_model

      pred_train <- predict(fit_model, train_final)
      cf <- confusionMatrix(pred_train, train_final$DV, mode = 'everything', positive = '1')
      train_performance$TN <- cf$table[1]
      train_performance$FP <- cf$table[2]
      train_performance$FN <- cf$table[3]
      train_performance$TP <- cf$table[4]
      train_performance$accuracy=cf$overall[1]
      train_performance$kappa=cf$overall[2]
      train_performance$sensitivity=cf$byClass[1]
      train_performance$specificity=cf$byClass[2]
      train_performance$key=Key_col
    }
  }

A: Below is sample method using caret package on how to tune and train your random forest model which outputs accuracy parameters for all models:
library(randomForest)
library(mlbench)
library(caret)

# Load Dataset
data(Sonar)
dataset <- Sonar
x <- dataset[,1:60]
y <- dataset[,61]

# Create model with default paramters
control <- trainControl(method="repeatedcv", number=10, repeats=3)
seed <- 7
metric <- "Accuracy"
set.seed(seed)
mtry <- sqrt(ncol(x))
tunegrid <- expand.grid(.mtry=mtry)
rf_default <- train(Class~., data=dataset, method="rf", metric=metric, tuneGrid=tunegrid, trControl=control)
print(rf_default)

output:
Resampling results

  Accuracy   Kappa      Accuracy SD  Kappa SD
  0.8138384  0.6209924  0.0747572    0.1569159

Tune Using Caret:
Random Search:
One search strategy that we can use is to try random values within a range.
# Random Search
control <- trainControl(method="repeatedcv", number=10, repeats=3, search="random")
set.seed(seed)
mtry <- sqrt(ncol(x))
rf_random <- train(Class~., data=dataset, method="rf", metric=metric, tuneLength=15, trControl=control)
print(rf_random)
plot(rf_random)

output:
Resampling results across tuning parameters:

  mtry  Accuracy   Kappa      Accuracy SD  Kappa SD
  11    0.8218470  0.6365181  0.09124610   0.1906693
  14    0.8140620  0.6215867  0.08475785   0.1750848
  17    0.8030231  0.5990734  0.09595988   0.1986971
  24    0.8042929  0.6002362  0.09847815   0.2053314
  30    0.7933333  0.5798250  0.09110171   0.1879681
  34    0.8015873  0.5970248  0.07931664   0.1621170
  45    0.7932612  0.5796828  0.09195386   0.1887363
  47    0.7903896  0.5738230  0.10325010   0.2123314
  49    0.7867532  0.5673879  0.09256912   0.1899197
  50    0.7775397  0.5483207  0.10118502   0.2063198
  60    0.7790476  0.5513705  0.09810647   0.2005012

Grid Search:
Another search is to define a grid of algorithm parameters to try.
control <- trainControl(method="repeatedcv", number=10, repeats=3, search="grid")
set.seed(seed)
tunegrid <- expand.grid(.mtry=c(1:15))
rf_gridsearch <- train(Class~., data=dataset, method="rf", metric=metric, tuneGrid=tunegrid, trControl=control)
print(rf_gridsearch)
plot(rf_gridsearch)

output:
Resampling results across tuning parameters:

  mtry  Accuracy   Kappa      Accuracy SD  Kappa SD
   1    0.8377273  0.6688712  0.07154794   0.1507990
   2    0.8378932  0.6693593  0.07185686   0.1513988
   3    0.8314502  0.6564856  0.08191277   0.1700197
   4    0.8249567  0.6435956  0.07653933   0.1590840
   5    0.8268470  0.6472114  0.06787878   0.1418983
   6    0.8298701  0.6537667  0.07968069   0.1654484
   7    0.8282035  0.6493708  0.07492042   0.1584772
   8    0.8232828  0.6396484  0.07468091   0.1571185
   9    0.8268398  0.6476575  0.07355522   0.1529670
  10    0.8204906  0.6346991  0.08499469   0.1756645
  11    0.8073304  0.6071477  0.09882638   0.2055589
  12    0.8184488  0.6299098  0.09038264   0.1884499
  13    0.8093795  0.6119327  0.08788302   0.1821910
  14    0.8186797  0.6304113  0.08178957   0.1715189
  15    0.8168615  0.6265481  0.10074984   0.2091663

There are many other methods to tune your random forest model and store the results of these models, above two are the most widely used methods.
Moreover, you can also manually set these parameters up and train and tune the model.


text:
Q: Initializing matrix python3 I don't know whether this is a bug, or I got a wrong semantic meaning of the * token in arrays:
>>> arr = [None] * 5    # Initialize array of 5 'None' items
>>> arr
[None, None, None, None, None]
>>> arr[2] = "banana"
>>> arr
[None, None, 'banana', None, None]
>>> # right?
...
>>> mx = [ [None] * 3 ] * 2     # initialize a 3x2 matrix with 'None' items
>>> mx
[[None, None, None], [None, None, None]]
>>> # so far, so good, but then:
...
>>> mx[0][0] = "banana"
>>> mx
[['banana', None, None], ['banana', None, None]]
>>> # Huh?

Is this a bug, or did I got the wrong semantic meaning of the __mult__ token?

A: You're copying the same reference to the list multiple times. Do it like this:
matrix = [[None]*3 for i in range(2)]


text:
Q: What is the proper way to remove a key-value pair in typescript I conducted the following experiment, and discovered that 'delete' can be used to remove a key-value pair. My question is: is this the 'proper' way to do it?
let myMap:{[key:string]:string} = {};

myMap["hello"] = "world";
console.log("hello="+myMap["hello"]); // it prints 'hello=world'

delete myMap["hello"];
console.log("hello="+myMap["hello"]); // it prints 'hello=undefined'

A:
My question is: is this the 'proper' way to do it?

This is the accurate way of doing it, but there are two caveats

*

*unless the property is non-configurable

*property is inherited
For example you cannot delete href property of location
delete location.href //returns false since this property cannot be deleted

Demo

var b = {
  a: 1,
  b: 2
};
Object.defineProperty(b, "c", {
  enumerable: true,
  configurable: false,
  writable: true,
  value: 3
});
delete b.c;
console.log(b); //all properties intact


text:
Q: What is modeling language in Blockchain? Where it is use? Where we need to use modeling language in Blockchain?
Permissions.acl file use which language?
.cto file use which language? is it modeling language?
I know that logic.js file use the JavaScript language.
Please clear me about Modeling Language.
Thanks in Advance.

A: From Wiki: https://en.wikipedia.org/wiki/Modeling_language
Modeling Language: A modeling language is any artificial language that can be used to express information or knowledge or systems in a structure that is defined by a consistent set of rules. The rules are used for interpretation of the meaning of components in the structure.
From Hyperledger Github: https://github.com/hyperledger/composer/blob/master/packages/composer-website/jekylldocs/reference/cto_language.md
The Hyperledger Composer modeling language is an object-oriented language which defines the business network model containing assets, participants, and transactions.
You can also see this tutorial. This tutorial will help to develop a project using Hyperledger Composer.
https://www.youtube.com/watch?v=S2S5cEcmx7Q

A: From The https://hyperledger.github.io/composer/latest/reference/cto_language
Hyperledger Composer includes an object-oriented modeling language that is used to define the domain model for a business network definition.
A Hyperledger Composer CTO model file is composed of:

*

*A single namespace. All resource declarations within the file are
implicitly in this namespace.

*A set of resource definitions, encompassing assets, transactions,
participants, and events.

*Optional import declarations that import resources from other
namespaces.
And From the https://hyperledger.github.io/composer/latest/reference/acl_language.html
Hyperledger Composer includes an access control language (ACL) that provides declarative access control over the elements of the domain model. By defining ACL rules you can determine which users/roles are permitted to create, read, update or delete elements in a business network's domain model.


text:
Q: css styling in knockout js for dynamic binding Here is my code:

This will create the 6 divs and 6 anchors dynamically using template.

I have a set of 6 divs and 6 anchors respectively. I tried float:left ,
display:block and other types of styling, but I'm not sure how to display the six blocks continuously, with each block containing a div and an anchor.

A: You want to iterate through the data and then reference each iteration within the template as $data.
Working fiddle: http://jsfiddle.net/mtalley/2o3hfvfd/6/
The view...

and the viewmodel...
jQuery(function ($) {
  var ViewModel = function () {
    var self = this;

    self.data = ko.observableArray([
        {
        text: 'Google',
        url: 'http://www.google.com'
      },
      {
        text: 'Yahoo',
        url: 'http://www.yahoo.com'
      },
      {
        text: 'New York Times',
        url: 'http://www.nytimes.com'
      },
      {
        text: 'Reddit',
        url: 'http://www.reddit.com'
      },
      {
        text: 'JS Fiddle',
        url: 'http://www.jsfiddle.net'
      },
      {
        text: 'Stackoverflow',
        url: 'http://www.stackoverflow.com'
      }
    ]);

    self.sample = function(){};
  }

  ko.applyBindings(new ViewModel());

});


text:
Q: javascript can't delete object key when not in quotes I've come across an issue while trying to remove keys from a json object:
var doc = this.data;
  Object.keys(doc).forEach(function(key) {
      if (isPropertyEmpty(doc[key])){
        delete doc[key];
      };
  });

The following loop passes over a JSON object which is formatted like this:
{ notes: [],
 isHostessGift: false,
  playbook: {},
  location: {},
  wine: { ingredient: false, pairing: false },
  coupons: [],
  ingredients: [{ item: 'e' }],
  categories: { dishType: ["Beverage"], mainIngredient: ["e"] },
  directions: [{ step: 'e' }],
  headline: 'jnj' }

It should remove the keys with empty arrays: coupons and notes
For some reason it isn't, but when I hard-coded the data, adding quotes around the keys:
{ "notes": [],
isHostessGift: false,
  playbook: {},
  location: {},
  wine: { ingredient: false, pairing: false },
  "coupons": [],
  ingredients: [{ item: 'e' }],
  categories: { dishType: ["Beverage"], mainIngredient: ["e"] },
  directions: [{ step: 'e' }],
  headline: 'jnj' }

They are removed. Is there any reason for the difference in functionality?
function isPropertyEmpty(obj) {

for (var key in obj) {
    if (hasOwnProperty.call(obj, key)){
       if(typeof obj === 'function') return false;
       if (obj == null)       return true;
       if (obj.length === 0)  return true;
       if(_.isEmpty(obj))     return true;
       if (obj.length > 0)    return false;
    };
    return false;
}

 }

A: As I said before problem in isPropertyEmpty, for empty arrays it returns undefined, I've rewritten it and seems works fine

var doc = {
    "notes": [],
 isHostessGift: false,
    playbook: {},
    location: {},
    wine: { ingredient: false, pairing: false },
    "coupons": [],
    ingredients: [{ item: 'e' }],
    categories: { dishType: ["Beverage"], mainIngredient: ["e"] },
    directions: [{ step: 'e' }],
    headline: 'jnj'
};

Object.keys(doc).forEach(function(key) {
    if (isPropertyEmpty(doc[key])) {
        delete doc[key];
    };
});

function isPropertyEmpty(obj) {
    var hasOwnProperty = Object.prototype.hasOwnProperty;

    if (obj === null || obj.length === 0) {
        return true;
    }

    if (typeof obj === 'function' || typeof obj === 'boolean') {
        return false;
    }

    if (obj.length > 0) {
        return false;
    }

    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) {
            return false;
        }
    }

    return true;
}

console.log(doc);


text:
Q: How do I specify what computers can connect to my public facing Windows 2008 R2 server? How do I lock down my Windows 2008 R2 Server so only certain computers can connect to it? I would ideally like to use some sort of certificate rather than an IP as my IP changes. I've done this in Linux, but I don't know where to start with Windows.
Thanks!

A: If by 'other computers' you mean 'other Windows computers' you can use IPSec policies to determine who is allowed to talk to the machine. IPSec policies use a pre-shared key (not quite a certificate) between various stations to allow/disallow contact. Unfortunately, I haven't actually used them for this purpose, I just know it can be done.


text:
Q: Does a loop invariant need to be defined both before and after the loop? I've been really confused so far about loop invariants and their specific properties. Do they need to be true both BEFORE and AFTER the loop? Or just at some point in the loop body itself?
For example:
int sum = 0;
for (int = 0; i < 10; i++) {
    sum += i
}

The invariant would be that sum is equal to 0 + 1 + 2 + ... + i. You could say at the end of the second iteration where i = 1, sum = 1. That works, but the invariant needs to be valid in the beginning of the iteration too - and it isn't. Sum is 0 before the loop starts, violating that invariant. Is that correct?

A: Yes, the loop invariant needs to be defined and true both before and after the loop.
Here is the fully annotated code. We have turned the for loop to a while, for clarity. We define an empty sum (i-1<0) to be 0:
int sum = 0;
// sum == 0
int i= 0;
// Loop invariant: sum == 0 + 1 + ... i-1
while (i < 10) {
    // Loop invariant: sum == 0 + 1 + ... i-1
    sum += i;
    // sum == 0 + 1 + ... i
    i++;
    // Loop invariant: sum == 0 + 1 + ... i-1
}
// Loop invariant: sum == 0 + 1 + ... i-1, and i == 10 => sum == 0 + 1 + ... 9

As you see, the loop invariant is sum == 0 + 1 + ... i-1. It is (trivially) established before the loop, modified then restored in the loop, and true after the loop. Together with the loop exit condition (i == 10), it ensures the correctness (sum == 45).

A: A loop invariant does not belong to the whole loop, but to one specific point in the loop. You'd write one loop invariant that is true just before the sum is increased, one that is true just after the sum is increased, one just after i is increased.
As you go through the statements of the loop, you get different invariants. The one at the end of the loop should then lead to the one at the start of the loop being correct when you re-enter the loop.


text:
Q: AAC license required for iPhone app? AAC is an audio codec which was "Designed to be the successor of the MP3 format, AAC generally achieves better sound quality than MP3 at similar bit rates." (AAC on Wikipedia).
However, similarly to MP3, parts of the AAC codec are patented, which means you can't simply use these codecs in all situations without making sure you are licensed to do so.
This is also true if you developed your own encoder or decoder. This is because writing an own encoder or decoder frees you only from copyright issues and software licenses (because you hold the copyright), but it doesn't free you from requirements imposed on you by patents.
Do I need to acquire a license for my iPhone app, which can encode and/or decode AAC files?

This question is helpful to many developers, but it is not a good
  example of an appropriate question for Stackoverflow. Read and learn
  from this post, but please do not use it as evidence that you can ask
  similar questions.
See About Stackoverflow for more information.

A: As long as you use the integrated encoders and/or decoders, you do not need to acquire your own license for using the AAC codec on the iPhone.
I've contacted vialicensing.com about this and they replied:

If your app uses the integrated decoder of the iPhone, no license is
  required. If however, you are providing a separate decoder as part of
  your product you will need to obtain a license for every unit shipped.

Moreover, also about encoders:

that also applies to recording using the integrated encoder of the
  iPhone. Providing an encoder and/or decoder is what requires the
  patent license. If a product relies on the integrated encoder/decoder
  in a device it is the device brand owner which is required to fulfill
  the license obligation.

Still, because this is a legal topic rather than a programming topic, you should contact via licensing if you have any uncertainties about your specific app.


text:
Q: Want to change color of 100 buttons on hover in tkinter import tkinter as tk

def on_enter(e):
    year_btn.config(background="orange",foreground="white")

def on_leave(e):
    year_btn.config(background="white", foreground="black")

window = tk.Tk()
yearnumber=1

for i in range(10):
    window.rowconfigure(i,weight=1,minsize=40)
    window.columnconfigure(i,weight=1,minsize=40)
    for j in range(10):
        frame = tk.Frame(padx=5,pady=5)
        frame.grid(row=i,column=j,sticky="nsew")
        year_btn = tk.Button(text=f"{yearnumber}", master=frame, activebackground="red", activeforeground="white")
        year_btn.pack(padx=1, pady=1,fill="both",expand="true")
        #year_btn.grid(sticky="nsew")
        yearnumber+=1
        year_btn.bind('<Enter>', on_enter)
        year_btn.bind('<Leave>',on_leave)

window.mainloop()

So, I created hundred buttons over here and wanted them to change color when the mouse hovers over them, I did this as per the internet to create events and bind them with the buttons.
My problem is I created hundred buttons using for-loop, so I added the binding code in the loop. The result of this was that if I hover the mouse over any Button only the 100th hover changes color. I also placed the hovering code outside the loop but that does nothing
How do I change color of button over hover for each button in this case.
Thank you

A: The event object that is passed to the bound function has a reference to the widget that received the event, under the attribute widget. You can use that to change the attribute of the button.
def on_enter(e):
    e.widget.config(background="orange",foreground="white")
    #^^^^^^^

def on_leave(e):
    e.widget.config(background="white", foreground="black")
    #^^^^^^^


text:
Q: Extract column from csv data in PHP I have csv data in PHP such as the following (note, it's text with new line characters in it, not a file):
$data = 'A,B,C,D,E,F,G,H
    1,1,2014-12-10,5,1,2,0,2
    2,7,2014-12-09,9,0,,7,2';

How can I extract a column as an array that excludes the headers? For example, if I wanted to extract the 4th column, it would include 5 and 9.
UPDATE: I have tried
$te = array_column($data,'D');

and I get the error: Warning: array_column() expects parameter 1 to be array,

A: You can use str_getcsv() to read each row as an array (discarding the first to skip headers). Then just keep the relevant column, e.g.:
$lines = preg_split("/(?:\r?\n|\r\n?)/", $data); // Split lines
array_shift($lines);                             // Discard header

$result = array();
foreach ($lines as $csv) {
    $row = str_getcsv($csv);
    $result[] = $row[3];
}
var_dump($result);

As per cHao suggestion in the comment below, if you need a more robust support of generic CSV data, you can dump the string to a virtual file and use fgetcsv() instead (which already handles parsing of multiple lines of input correctly):
$fp = fopen('php://temp', 'r+');
fputs($fp, $data);
fseek($fp, 0);

$result = array();
fgetcsv($fp);
while (false != ($row = fgetcsv($fp))) {
    $result[] = $row[3];
}
fclose($fp);
var_dump($result);

A: If this a comma delimited string, you could use str_getcsv() in this case:
// load the string and explode, then apply str_getcsv
$data = array_map('str_getcsv', explode("\n", $request->getResponseBody()));
array_shift($data); // remove the header
$fourth_column = array();
foreach($data as $line) {
    if(!empty($line[3])) {
        $fourth_column[] = $line[3]; // indices start at zero
    }
}


text:
Q: How does .NET optimise properties with operations? For discussion, I have this class with properties
public class Intresting
{
   decimal _mQty, _mSpareQty;

   public Qty { get { return _mQty; } set { _mQty = value; } }
   public SpareQty { get { return _mSpareQty; } set { _mSpareQty= value; } }
   public SparePercentage
   {
     get { return _mQty == 0 ?  0 : _mSpareQty / _mQty; }
     set { _SpareQty = Qty * value; }
   }
}

I am concern If I have 1,000,000 Interesting objects displayed in a custom GridView in a read only situation which shows SparePercentage via the property, the SparePercentage will be calculated over and over again or will there be optimised for example using a third _mSpareQtyPercentage which gets recalculated when Qty and SpareQty is set?

A: I very much doubt that there's anything in the JIT which would perform that optimization for you - after all, that requires more work each time Qty and SpareQty are set, and more space per object. That's not a trade-off the JIT should be doing for you. You could do that yourself, of course - just don't expect either the C# or JIT compiler to do it for you.
I would expect the JIT compiler to inline your trivial properties - which can be written as automatically implemented properties as of C# 3:
public decimal Quantity { get; set; }
public decimal SpareQuantity { get; set; }

(Note the changes to make the names more readable at the same time, by the way.)

A: The JIT will do nothing in particular to optimize this property and it will hence be re-evaluated in full every time it's asked for.  However I doubt this would ever show up as a source of performance problems in your application.  I certainly wouldn't go thruogh the troulbe of caching the result myself until a profile noted that as a problem in my application.
Note: It's also odd to have a property which has a get which is a calculation and has a set at all.  When there is a calculation in the getter I usually prefer to avoid a setter entirely and instead force the caller to mutate the underlying values that are a par of the calculation

A: No, it will perform the calculation every time it is called.  If you want to avoid that, you will have to implement your own cacheing.
.NET doesn't "optimize" properties any more than it optimizes any other functions.

A: This is one reason it is not recommended to put more than a getter to the backing field. If there is an operation to be performed, it should occur in a method. There is nothing in the compiler that would make an assumption about how the code should be executed.
The sample will execute the formula every time that getter is called. OT, but in a threaded environment, I would expect that the only way I could get the value would be to call a method.


text:
Q: Trying to create a drop-down of form fields, that is based on a number Good afternoon!
I am building a contact form in Contact Form 7 in Wordpress. And I need a functionality where one of the form fields is a number selector (for example, 1-10) and I need the number that is selected to be calculated and drop down the number of fields to be inputted.
I'll try to explain the best I can. So if someone types in the 4...I need a drop down of four input fields.
I have looked for some jquery script for this functionality, but I'm basically at a deadend. If anyone has any suggestions, I would much appreciate it!

A: You would use javascript, I wrote a simple sample for you. I haven't ever worked with wordpress, but this just works on it's own, and I would think you should be able to just put it in.
Javascript

HTML
<form>
    Number: <input type="number" name="number" id="number" onblur="thing();">
    <select id="select">
        <option value="no">Enter a number first</option>
    </select>
    <input type="submit" value="Submit">
</form>

Also, instead of using onblur, you could use onkeyup or something. onblur is for when it loses focus.

A: Here's an option using jQuery (jsFiddle)
HTML
Number of inputs:
<select class="numInputs" onChange="buildInputs(this);">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

Javascript (jQuery)
$(document).ready(function () {
    // set onchange event for the select box.
    $('.numInputs').change(function () {
        // clear any inputs added to the div.
        $('.inputs').empty();
        // get number of inputs to add from select box.
        var num = $('.numInputs option:selected').text();
        // build the inputs.
        for (var i = 1; i <= num; i++) {
            $('<input type="text"/>
').appendTo('.inputs');
        }
    })
});


text:
Q: Winform (.Net) databind and selection problem It was a looooooong time since I did a winform desktop application in .Net and I wanted to do some selections based on listboxes. The problem is that any item I select in a listbox also changes the selection of the other listboxes bound to the same data. I tried to find people who have had the same problem but couldn't find any so I guess I'm doing something fundamentally wrong. Anyone have any hints? See below for the basic code.
Class for handling data (to which I later use as DataSource in listboxes).
public class Registry
{
    public ICollection<Data.Vertice> Vertices { get; set; } = new List<Data.Vertice>();
}

How I set the data source to a listbox
listBox1.DataSource = null;
listBox1.DataSource = _registry.Vertices;
listBox1.DisplayMember = "Title";

A: Reza Aghai Solved the problem by finding a a post which I had missed in my search.
Basically a single BindingManagerBase is created and reused if you use the same DataSource. This can be solved by creating a new DataSource by for example doing the following:
DataSource = yourList.ToList()


text:
Q: Magento 2 - auto select Review tab by default on product page I would like the review tab on the product page to be active and expanded by default.
I tried achieving this by using jQuery to click on the review tab. This works however the actual reviews are not loaded because the tab is not 'active'.
How do I get the review tab selected and the actual reviews loaded?
I'm on a Magento 2.4.0 installation and using the Magento 2 Porto theme.
This is the current details.phtml:
<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php if ($detailedInfoGroup = $block->getGroupChildNames('detailed_info', 'getChildHtml')):?>
<?php
    $porto_helper = $this->helper('Smartwave\Porto\Helper\Data');
    $_helper = $this->helper('Smartwave\Porto\Helper\Customtabs');
    $product_config = $porto_helper->getConfig('porto_settings/product');
    $static_block_tab = $product_config['custom_block_next_tab'];
    $custom_block = $this->getLayout()->createBlock('Magento\Cms\Block\Block');
    $_product = \Magento\Framework\App\ObjectManager::getInstance()->get(\Magento\Framework\Registry::class)->registry('product');
    $page_type = $_product->getData('product_page_type');
    if(!$page_type)
        $page_type = isset($_config['product_page_type'])?$_config['product_page_type']:'';
    if($custom_block) {
        $custom_block->setBlockId($static_block_tab);
    }
    $tab_style = "";
    if(isset($product_config['tab_style']) && $product_config['tab_style'])
        $tab_style = $product_config['tab_style'];
    if($page_type == 'wide_grid')
        $tab_style = 'vertical';
?>
    <?php if($product_config['tab_full_background']):?>

            <div class="<?php if(!$page_type && $custom_block && $static_block_tab):?>col-md-9<?php else:?>col-md-12<?php endif;?>">
    <?php endif;?>
                <div class="product info detailed <?php echo $tab_style; ?> <?php if($page_type == 'sticky_right'): ?>fullwidth-row<?php endif; ?>">
                <?php $layout = $block->getLayout(); ?>
                <?php if(!$tab_style || $tab_style != "sticky"): ?>
                    <div class="product data items <?php if($page_type == 'sticky_right'): ?>container<?php endif; ?>" data-mage-init='{"tabs":{"openedState":"active", "active": 0}}'>
                        <?php foreach ($detailedInfoGroup as $name):?>
                            <?php
                            $html = $layout->renderElement($name);
                            if (!trim($html)) {
                                continue;
                            }
                            $alias = $layout->getElementAlias($name);
                            $label = $block->getChildData($alias, 'title');
                            ?>
                            <div class="data item title"
                                 aria-labeledby="tab-label-<?php /* @escapeNotVerified */ echo $alias;?>-title"
                                 data-role="collapsible" id="tab-label-<?php /* @escapeNotVerified */ echo $alias;?>">
                                <a class="data switch"
                                   tabindex="-1"
                                   data-toggle="switch"
                                   href="#<?php /* @escapeNotVerified */ echo $alias; ?>"
                                   id="tab-label-<?php /* @escapeNotVerified */ echo $alias;?>-title">
                                    <?php /* @escapeNotVerified */ echo $label; ?>

                            <div class="data item content" id="<?php /* @escapeNotVerified */ echo $alias; ?>" data-role="content">
                                <?php /* @escapeNotVerified */ echo $html; ?>

                        <?php endforeach;?>
                        <?php
                        if($custom_cms_tabs = $_helper->getCustomTabs($_product)) {
                            $i = 1;
                            foreach($custom_cms_tabs as $_item) {
                                ?>
                                <div class="data item title"
                                     aria-labeledby="tab-label-<?php /* @escapeNotVerified */ echo "custom-".$i;?>-title"
                                     data-role="collapsible" id="tab-label-<?php /* @escapeNotVerified */ echo "custom-".$i;?>">
                                    <a class="data switch"
                                       tabindex="-1"
                                       data-toggle="switch"
                                       href="#<?php /* @escapeNotVerified */ echo "custom-".$i; ?>"
                                       id="tab-label-<?php /* @escapeNotVerified */ echo "custom-".$i;?>-title">
                                        <?php /* @escapeNotVerified */ echo $_item['tab_title']; ?>

                                <div class="data item content" id="<?php /* @escapeNotVerified */ echo "custom-".$i; ?>" data-role="content">
                                    <?php /* @escapeNotVerified */ echo $_item['tab_content']; ?>

                                <?php
                                $i++;
                            }
                        }
                        ?>

                <?php elseif($tab_style && $tab_style == "sticky"): ?>

                        <?php foreach ($detailedInfoGroup as $name):?>
                            <?php
                            $html = $layout->renderElement($name);
                            if (!trim($html)) {
                                continue;
                            }
                            $alias = $layout->getElementAlias($name);
                            $label = $block->getChildData($alias, 'title');
                            $alias = str_replace(".","_",$alias);
                            ?>
                            <div class="data item title <?php if($alias == 'reviews'):?>active<?php endif; ?>" aria-labeledby="tab-label-<?php /* @escapeNotVerified */ echo $alias;?>"
                            data-role="collapsible" id="tab-label-<?php /* @escapeNotVerified */ echo $alias;?>">
                                <a class="data switch" href="#<?php /* @escapeNotVerified */ echo $alias; ?>">
                                    <?php /* @escapeNotVerified */ echo $label; ?>

                        <?php endforeach;?>
                        <?php
                        if($custom_cms_tabs = $_helper->getCustomTabs($_product)) {
                            $i = 1;
                            foreach($custom_cms_tabs as $_item) {
                                ?>

                                    <a class="data switch" href="#<?php /* @escapeNotVerified */ echo "custom-".$i; ?>">
                                        <?php /* @escapeNotVerified */ echo $_item['tab_title']; ?>

                                <?php
                                $i++;
                            }
                        }
                        ?>
                        <?php foreach ($detailedInfoGroup as $name):?>
                            <?php
                            $html = $layout->renderElement($name);
                            if (!trim($html)) {
                                continue;
                            }
                            $alias = $layout->getElementAlias($name);
                            $label = $block->getChildData($alias, 'title');
                            $alias = str_replace(".","_",$alias);
                            ?>
                            <div class="data item content" id="<?php /* @escapeNotVerified */ echo $alias; ?>">
                                <?php /* @escapeNotVerified */ echo $html; ?>

                        <?php endforeach;?>
                        <?php
                        if($custom_cms_tabs = $_helper->getCustomTabs($_product)) {
                            $i = 1;
                            foreach($custom_cms_tabs as $_item) {
                                ?>
                                <div class="data item content" id="<?php /* @escapeNotVerified */ echo "custom-".$i; ?>">
                                    <?php /* @escapeNotVerified */ echo $_item['tab_content']; ?>

                                <?php
                                $i++;
                            }
                        }
                        ?>

                <?php endif; ?>

    <?php if($product_config['tab_full_background']):?>

            <?php if(!$page_type && $custom_block && $static_block_tab):?>

                    <?php echo $custom_block->toHtml(); ?>

            <?php endif;?>

    <?php endif;?>
<?php endif; ?>

I've disabled the jQuery click for now. I also set the active tab to '0' because the Review tab is the first one in the list.

A: Go to your theme directory and check this path :

app/design/frontend/<vendor_name>/<theme_name>/Magento_Catalog/templates/product/view/details.phtml

If details.phtml file exist, then replace this below line :
From :

To :

Now, Just clean cache and check it. Review tab will be active by default when page load.


text:
Q: Getting first and second row with ArcPy searchcursor? I have a shapefile with only 4 rows in it. I already could filter it so I have only 2 left. I need these sorted by the 'length' field, then take the first and second row to save in to individual files. Here is the code for sorting:
import arcpy
fc = 'C:\\Users\\test.shp'
fields = ['length', 'FID']
expression = arcpy.AddFieldDelimiters(fc, "length") + " > 1000"
for row in sorted(arcpy.da.SearchCursor(fc, fields,)):
    print('{0}, {1}'.format(row[0], row[1]))

For saving in to the new file:
arcpy.FeatureClassToFeatureClass_conversion(?, outLocation,
                                            outFeatureClass,)

How can I make the search cursor to show first only the lower value row, then the higher one? (order doesn't matter)
How can I select the number 1 row, then the number 2 row?

A: You do not state what your license level is; this is always important as it dictates the solution.  Having said that, consider using the Sort tool (which requires an Advanced license). More information can be found here.

A: I'd have an end goal of creating an sql query with the OIDs of the two features.
Create a sorted list of tuples of lengths and oids from your features. Pull out the first two oids from your sorted list and create an sql from the oids. You can then apply the sql when you copy your features.
import arcpy
fc = 'C:\\Users\\test.shp'
expression = arcpy.AddFieldDelimiters(fc, "length") + " > 1000"

#sorted list of tuples of length and oid
lis = sorted ([(length, oid) for length, oid in
                arcpy.da.SearchCursor
                (fc, ["length", "OID@"],
                 expression)])

#get top two oids
twoOids = [str (oid) for length, oid in lis] [:2]

#sql expression
oidStr = ", ".join (twoOids)
oidFld = arcpy.Describe (fc).OIDFieldName
delimOidFld = arcpy.AddFieldDelimiters (fc, oidFld)
sql = "{0} IN ({1})".format (delimOidFld, oidStr)

#export with sql
arcpy.FeatureClassToFeatureClass_conversion(fc, outLocation, outFeatureClass, sql)

A: i think you are asking about how to select just the first and second records of a search cursor.
i was looking into this same activity recently and came across the several options, all using variations of "next"  function, depending on the cursor type (arcpy.SearchCursor vs. arcpy.da.SearchCursor).
Perhaps more saavy ArcPy and Python folks will be able to explain more.
references:

*

*http://forums.esri.com/Thread.asp?c=93&f=1729&t=129511

*How to get values of last row in table with ArcPy/SearchCursor?
snippet:
    for row in cursorA:
        #row = next(cursorA)   # get first record option 1
        #row = cursorA.next()   # get first record option 2
        next(cursorA)   # get first record option 3


text:
Q: Auto generate properties when creating object I have classes that have lots of properties, I was wondering that is there any way for Visual Studio, Resharper or other tool to create the syntax for calling the properties, when I create the object. So I dont have to go through all of properties the myself, just set the value and that's it. Something like this.
Object foo = new Object{
    prop1 = ,
    prop2 = ,
    prop3 = };

I don't know if people understood the question. I want Visual Studio to create the setter for the property when I create the object. Not the property itself.

A: You could use named parameters in your constructor:
http://geekswithblogs.net/michelotti/archive/2009/01/22/c-4.0-named-parameters-for-better-code-quality.aspx
For example:
Person person = new Person(firstName: "John", lastName: "Smith", dateOfBirth: new DateTime(1970, 1, 1));

A: Edit
Misunderstood the question
I have a macro which from this line
MyClass x = new MyClass();

generates
x.StrProp = "string";
x.IntProp = 0;

I use it to generate test code but you can just change the PrintMemberAssignment function to present the result as you like:
The macro looks like this (assign it to a keyboard shortcut)
Private mUsings As New HashSet(Of String)

Sub InitializeAllMembers()
    Try
        Dim assignmentPattern As New Regex("(?<Indent>\s*)(?:(?<DeclaredType>\S+)\s+)?(?<VariableName>[\S=]+)\s*=\s*(?<new>new)?\s*(?<CreatedType>[^\s\(]+)")
        Dim selection As EnvDTE.TextSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection)
        Dim editPoint As EditPoint = selection.BottomPoint.CreateEditPoint

        ' Get info from current line in editor
        editPoint.StartOfLine()
        Dim match As Match = assignmentPattern.Match(editPoint.GetText(editPoint.LineLength))
        If Not match.Success Then
            MessageBox.Show("No assignment on row")
            Exit Sub
        End If
        Dim foundDeclaredType As Boolean = match.Groups("DeclaredType").Success AndAlso match.Groups("DeclaredType").Value <> "var"
        Dim foundCreatedType As Boolean = match.Groups("new").Success

        If Not (foundDeclaredType OrElse foundCreatedType) Then
            MessageBox.Show("Can't find type on row")
            Exit Sub
        End If

        Dim typeToExpand As String = If(foundDeclaredType, match.Groups("DeclaredType"), match.Groups("CreatedType")).Value

        ' Traverse upwards in current file and record all using statements
        Dim currentFunction As CodeElement = FindCodeElement(selection.ActivePoint, DTE.ActiveDocument.ProjectItem.FileCodeModel.CodeElements)
        If currentFunction Is Nothing Then
            MessageBox.Show("Can't find current function")
            Exit Sub
        End If
        mUsings.Clear()
        FindAllUsings(currentFunction)

        ' Loop all projects in solution to find requested type
        Dim classType As CodeElement = DTE.Solution.Projects.Cast(Of Project) _
                                                            .Select(Function(x) FindClassInProjectItems(x.ProjectItems, typeToExpand)) _
                                                            .FirstOrDefault(Function(x) x IsNot Nothing)
        If classType Is Nothing Then
            MessageBox.Show("Can't find type in solution: " & typeToExpand)
            Exit Sub
        End If

        PrintMemberAssignments(editPoint, match.Groups("Indent").Value & match.Groups("VariableName").Value, GetMembers(classType))

    Catch objException As System.Exception
        MessageBox.Show(objException.Message)
    End Try
End Sub

' Records all using statements active for a codeelement
Sub FindAllUsings(ByVal elem As Object)
    If TypeOf elem Is CodeFunction Then
        FindAllUsings(CType(elem, CodeFunction).Parent)
    ElseIf TypeOf elem Is CodeClass Then
        mUsings.Add(CType(elem, CodeClass).FullName)
        FindAllUsings(CType(elem, CodeClass).Parent)
    ElseIf TypeOf elem Is CodeStruct Then
        mUsings.Add(CType(elem, CodeStruct).FullName)
        FindAllUsings(CType(elem, CodeStruct).Parent)
    ElseIf TypeOf elem Is CodeNamespace Then
        mUsings.Add(CType(elem, CodeNamespace).FullName)
        For Each ns As String In CType(elem, CodeNamespace).Members.OfType(Of CodeImport) _
                                                                   .Select(Function(x) x.Namespace)
            mUsings.Add(ns)
        Next
        FindAllUsings(CType(elem, CodeNamespace).Parent)
    ElseIf TypeOf elem Is FileCodeModel Then
        For Each ns As String In CType(elem, FileCodeModel).CodeElements.OfType(Of CodeImport) _
                                                                        .Select(Function(x) x.Namespace)
            mUsings.Add(ns)
        Next
    End If
End Sub

' Find code element (i.e. function) for current line
Public Function FindCodeElement(ByVal caretPosition As TextPoint, ByVal elems As CodeElements) As CodeElement
    If elems Is Nothing Then Return Nothing
    Return elems.Cast(Of CodeElement) _
                .Where(Function(x) x.StartPoint.LessThan(caretPosition) AndAlso _
                                   x.EndPoint.GreaterThan(caretPosition)) _
                .Select(Function(x) If(FindCodeElement(caretPosition, GetMembers(x)), x)) _
                .FirstOrDefault()
End Function

Public Sub PrintMemberAssignments(ByVal editPoint As EditPoint, ByVal prefix As String, ByVal members As CodeElements)
    For Each member As CodeElement In members
        Dim text As String
        If TypeOf member Is CodeProperty Then
            If CType(member, CodeProperty).Setter Is Nothing Then Continue For
            If CType(member, CodeProperty).Setter.Access <> vsCMAccess.vsCMAccessPublic Then Continue For
            If CType(member, CodeProperty).Setter.IsShared Then Continue For
            text = MemberAssignment(prefix, member.Name, CType(member, CodeProperty).Type)
        ElseIf TypeOf member Is CodeVariable Then
            If CType(member, CodeVariable).Access <> vsCMAccess.vsCMAccessPublic Then Continue For
            If CType(member, CodeVariable).IsConstant Then Continue For
            If CType(member, CodeVariable).IsShared Then Continue For
            text = MemberAssignment(prefix, member.Name, CType(member, CodeVariable).Type)
        Else
            Continue For
        End If
        editPoint.EndOfLine()
        editPoint.Insert(ControlChars.NewLine)
        editPoint.Insert(text)
    Next
End Sub

Private Function MemberAssignment(ByVal prefix As String, ByVal membername As String, ByVal typeref As EnvDTE.CodeTypeRef) As String
    Dim typekind As EnvDTE.vsCMTypeRef = typeref.TypeKind
    Dim value As String
    If typekind = vsCMTypeRef.vsCMTypeRefArray Then
        value = "{0}.{1} = new {2}[1];"
        If typeref.ElementType.TypeKind = vsCMTypeRef.vsCMTypeRefCodeType Then
            value = value & ControlChars.NewLine & "{0}.{1}[0] = new {2}();"
        End If
        Return String.Format(value, prefix, membername, TrimKnownNamespace(typeref.ElementType.AsString))
    ElseIf typekind = vsCMTypeRef.vsCMTypeRefBool Then
        value = "false"
    ElseIf typekind = vsCMTypeRef.vsCMTypeRefChar Then
        value = "'x'"
    ElseIf typekind = vsCMTypeRef.vsCMTypeRefDecimal Then
        value = "0.00m"
    ElseIf typekind = vsCMTypeRef.vsCMTypeRefDouble Then
        value = "0.00"
    ElseIf typekind = vsCMTypeRef.vsCMTypeRefInt Then
        value = "0"
    ElseIf typekind = vsCMTypeRef.vsCMTypeRefLong Then
        value = "0"
    ElseIf typekind = vsCMTypeRef.vsCMTypeRefShort Then
        value = "0"
    ElseIf typekind = vsCMTypeRef.vsCMTypeRefByte Then
        value = "0"
    ElseIf typekind = vsCMTypeRef.vsCMTypeRefString Then
        value = """" & membername & """"
    ElseIf typekind = vsCMTypeRef.vsCMTypeRefArray Then
        value = "new " & TrimKnownNamespace(typeref.ElementType.AsString) & "[1]"
    ElseIf typekind = vsCMTypeRef.vsCMTypeRefCodeType AndAlso _
            typeref.AsString = "System.DateTime" Then
        value = String.Format("new DateTime({0:yyyy},{0:%M},{0:%d})", DateTime.Today)
    Else
        value = "new " & TrimKnownNamespace(typeref.AsString) & "()"
    End If
    Return String.Format("{0}.{1} = {2};", prefix, membername, value)
End Function

Private Function TrimKnownNamespace(ByVal fullName As String) As String
    Return fullName.Substring(mUsings.Where(Function(x) fullName.StartsWith(x) AndAlso _
                                                        fullName.Length > x.Length AndAlso _
                                                        fullName(x.Length) = "."c) _
                                     .Select(Function(x) x.Length + 1) _
                                     .DefaultIfEmpty(0) _
                                     .Max())
End Function

Private Function FindClassInProjectItems(ByVal nprojectItems As ProjectItems, ByVal classname As String) As CodeElement
    If nprojectItems Is Nothing Then Return Nothing
    For Each nprojectitem As ProjectItem In nprojectItems
        Dim found As CodeElement
        If nprojectitem.Kind = EnvDTE.Constants.vsProjectItemKindPhysicalFile Then
            If nprojectitem.FileCodeModel Is Nothing Then Continue For
            found = FindClassInCodeElements(nprojectitem.FileCodeModel.CodeElements, classname)
            If found IsNot Nothing Then Return found
        End If
        If nprojectitem.SubProject IsNot Nothing Then
            found = FindClassInProjectItems(nprojectitem.SubProject.ProjectItems, classname)
            If found IsNot Nothing Then Return found
        End If
        found = FindClassInProjectItems(nprojectitem.ProjectItems, classname)
        If found IsNot Nothing Then Return found
    Next
End Function

Private Function FindClassInCodeElements(ByVal elems As CodeElements, ByVal classname As String) As CodeElement
    If elems Is Nothing Then Return Nothing
    For Each elem As CodeElement In elems
        If IsClassType(elem) Then
            If classname = elem.Name Then Return elem
        ElseIf Not TypeOf elem Is CodeNamespace Then
            Continue For
        End If
        If mUsings.Contains(elem.FullName) Then
            Dim found As CodeElement = FindClassInCodeElements(GetMembers(elem), classname)
            If found IsNot Nothing Then Return found
        End If
    Next
    Return Nothing
End Function

Private Function GetMembers(ByVal elem As CodeElement) As CodeElements
    If TypeOf elem Is CodeClass Then
        Return CType(elem, CodeClass).Members
    ElseIf TypeOf elem Is CodeNamespace Then
        Return CType(elem, CodeNamespace).Members
    ElseIf TypeOf elem Is CodeStruct Then
        Return CType(elem, CodeStruct).Members
    ElseIf TypeOf elem Is CodeInterface Then
        Return CType(elem, CodeInterface).Members
    End If
    Return Nothing
End Function

Private Function IsClassType(ByVal elem As CodeElement) As Boolean
    Return TypeOf elem Is CodeClass OrElse TypeOf elem Is CodeStruct OrElse TypeOf elem Is CodeInterface
End Function

A: You can use anonimous objects:
var foo = new { one = 1, two = 2, three = 3};

In this case would be created new object with properties one, two and three

A: Doesn't Intellisense do the most work for you anyway? Normaly it should present you a list of all properties as soon as you open the { an press space.


text:
Q: JavaScript trouble detecting mouse wheel event I'm trying to capture the mouse event. Here is the code I'm trying:
if(window.addEventListener) { document.addEventListener('DOMMouseScroll', zoom_handler, false); }
else { document.onmousewheel = zoom_handler; }

alert("test"); //I see this alert so I assume the code above it is run

//...
function zoom_handler(event) {

    var delta = 0;

    if (!event) event = window.event;
    // normalize the delta
    if (event.wheelDelta) {
        // IE and Opera
        delta = event.wheelDelta / 60;
    } else if (event.detail) {
        // W3C
        delta = -event.detail / 2;
    }

    alert("Delta: " + delta);

}

Except the problem is I see nothing when I try wheeling up and down on my page, so I guess I'm not capturing the event properly. For reference, I've been trying to follow this tutorial: http://viralpatel.net/blogs/2009/08/javascript-mouse-scroll-event-down-example.html
Thanks for any help.

A: I guess that the way you implemented it, is going to work only in some browsers, not in Chrome for example. Did you try to put the
document.onmousewheel = zoom_handler;

outside the else statement?
Doing so, makes it work on my Chrome Browser running on OSX Lion (Mac).
This is how I tested on my computer:
if(window.addEventListener) { document.addEventListener('DOMMouseScroll', zoom_handler, false); }
document.onmousewheel = zoom_handler;

alert("test"); //I see this alert so I assume the code above it is run

Hope that fixes it.


text:
Q: ARCORE: Sceneform 1.16 issue with rendering I am using Sceneform 1.16 and andriod studio 4.1,
I am trying to render but it is not working.
Issue:
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment android:name="com.google.ar.sceneform.ux.ArFragment"  <======Error ArFragment must be a fragment >
        android:id="@+id/ux_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

*MainActivity.java.
public class MainActivity extends AppCompatActivity {
 private ArFragment arFragment;
 private ModelRenderable modelRenderable;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.ux_fragment);

Error:
Inconvertible types; cannot cast 'androidx.fragment.app.Fragment' to 'com.google.ar.sceneform.ux.ArFragment'

we followed the steps in :
https://github.com/google-ar/sceneform-android-sdk
--Getting started with Sceneform 1.16.0
Can you please tell what is the issue.
Build gradle file
apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "30.0.1"

    defaultConfig {
        applicationId "com.examples.myapplication"
        minSdkVersion 24
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions{
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    api project(":sceneformux")

}

A: You should edit the settings.gradle file. Add these lines:
include ':sceneform'
project(':sceneform').projectDir = new File('sceneformsrc/sceneform')

include ':sceneformux'
project(':sceneformux').projectDir = new File('sceneformux/ux')

A: Do you have a Fragment class that extends the ArFragment? I had it like
<fragment android:name="com.example.zzz.FaceARFragment"
    android:id="@+id/face_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

It was a class FaceARFragment extends ArFragment used for configuration only. And in activity:
FaceARFragment arFragment = (FaceARFragment) getSupportFragmentManager().findFragmentById(R.id.face_fragment);

That worked for me. Also you can try using Sceneform 1.17, I tried using 1.16, but 1.17 worked better for me as I was using .glb models.


text:
Q: C# Regex Validating Mac Address I am trying to validate mac addresses. In this instance there is no - or : for example a valid mac would be either:
0000000000
00-00-00-00-00-00
00:00:00:00:00:00

However I keep getting false when run against the below code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace parsingxml
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Give me a mac address: ");

            string input = Console.ReadLine();
            input = input.Replace(" ", "").Replace(":","").Replace("-","");

            Regex r = new Regex("^([:xdigit:]){12}$");

            if (r.IsMatch(input))
            {
                Console.Write("Valid Mac");
            }
            else
            {
                Console.Write("Invalid Mac");
            }
            Console.Read();
        }
    }
}

OUTPUT: Invalid Mac

A: Try this regex instead:
^(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}|(?:[0-9a-fA-F]{2}-){5}[0-9a-fA-F]{2}|(?:[0-9a-fA-F]{2}){5}[0-9a-fA-F]{2}$
Matches:

*

*12-23-34-45-56-67

*12:23:34:45:56:67

*122334455667

But not:

*

*12:34-4556-67

Edit: Your code works for me.

A: .NET regex does not have support for POSIX character class. And even if it does support, you need to enclose it in [] to make it effective, i.e. [[:xdigit:]], otherwise, it will be treated as a character class with the characters :, x, d, i, g, t.
You probably want this regex instead (for the MAC address after you have cleaned up the unwanted characters):
^[a-fA-F0-9]{12}$

Note that by cleaning up the string of space, - and :, you will allow inputs as shown below to pass:
   34:   3-342-9fbc: 6:7

DEMO

A: Seems like you could just do this:
Regex r = new Regex("^([0-9a-fA-F]{2}(?:(?:-[0-9a-fA-F]{2}){5}|(?::[0-9a-fA-F]{2}){5}|[0-9a-fA-F]{10}))$");

Or this, which is a lot simpler and would be a little more forgiving:
Regex r = new Regex("^([0-9a-fA-F]{2}(?:[:-]?[0-9a-fA-F]{2}){5})$");

A: I'd use a regular expression like this one, myself:
Regex rxMacAddress = new Regex( @"^[0-9a-fA-F]{2}(((:[0-9a-fA-F]{2}){5})|((:[0-9a-fA-F]{2}){5}))$") ;

6 pairs of hex digits, separator either by colons or by hyphens, but not a mixture.

A: Your regex isn't good. Here you got a good one:
public const string ValidatorInvalidMacAddress = "^([0-9A-Fa-f]{2}[:-]?){5}([0-9A-Fa-f]{2})$";

A: Correct Regex expression that worked for me and accept either macaddress with either all - or all : separation is :- "^[0-9a-fA-F]{2}(((:[0-9a-fA-F]{2}){5})|((-[0-9a-fA-F]{2}){5}))$"

A:         using System.Net.NetworkInformation;
        try{
            PhysicalAddress py = PhysicalAddress.Parse("abcd");
        }catch(Exception){
            Console.WriteLine("Mac address not valid");
        }


text: Q: Livewire detected in Chrome but cannot use tools I am using Laravel 6.20 along with Livewire 1.3.9, and I receive this message when I try to debug a component. I'm not sure what setting it is that is preventing the tools from appearing - my config files all say debug/development mode. Any ideas?


text:
Q: how to style such component in material UI in reactjs
I am trying to make such kind of setup using material UI but am unable to do it properly using material UI.
I am not able to add the product add and remove setup below which should be below product name and price as shown in image.

A: If it is vital to use material-ui for positioning your elements and it expected to be responsive for different screen resolutions you could use https://material-ui.com/components/grid/
Otherwise, you can just use flexbox https://css-tricks.com/snippets/css/a-guide-to-flexbox/
There is a link to codesandbox for expamle made via MU Grids https://codesandbox.io/embed/material-demo-dvhfy?fontsize=14&hidenavigation=1&theme=dark


text:
Q: how to write to database after javascript client side photo resize and upload I have found a script online which resizes an image client side and then uploads the image to server. This works fine but what I need is to write the image name to mysql database. I know how to do it, but its not working and I think it has something to do with the fact that the script runs client side.
Can anyone look at the following and see where to put the mysql statement. Or if there is a better way of doing it altogether.
upload-form.php

<form enctype="multipart/form-data" method="post" onsubmit="uploadphoto()">

      Select Files to Upload

      <input type="file" name="filesToUpload[]" id="filesToUpload" multiple="multiple" />
      <output id="filesInfo"></output>

      <input type="submit" value="Upload" />

</form>

upload-resized-photo.php
<?php
    if ($_POST)
    {
        define('UPLOAD_DIR', 'uploads/');
        $img = $_POST['image'];
        $img = str_replace('data:image/jpeg;base64,', '', $img);
        $img = str_replace(' ', '+', $img);
        $data = base64_decode($img);
        $file = UPLOAD_DIR . uniqid() . '.jpg';
        $success = file_put_contents($file, $data);

        // I did have the mysql insert here but it didnt even execute. Think it is due to xhr.open post method.
    }
?>

A: I test the following code on my computer:
if ($_POST)
{
    define('UPLOAD_DIR', 'uploads/');
    $img = $_POST['image'];
    $img = str_replace('data:image/jpeg;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.jpg';
    $success = file_put_contents($file, $data);

    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "INSERT INTO images (image_name)
    VALUES ('{$file}')";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "
" . $conn->error;
    }

    $conn->close();
}

check your folder permissions, see the following images (Mysql + Files)

A: This function check all input[type=file]
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
    var oInput = arrInputs[i];
    if (oInput.type == "file") {
        var sFileName = oInput.value;
        if (sFileName.length > 0) {
            var blnValid = false;
            for (var j = 0; j < _validFileExtensions.length; j++) {
                var sCurExtension = _validFileExtensions[j];
                if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                    blnValid = true;
                    break;
                }
            }

            if (!blnValid) {
                alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                return false;
            }
        }
    }
}

return true;
}

you should call that function in:
function uploadphoto(oForm)
{
if(!Validate(oForm)){
    return false;
}
if (window.File && window.FileReader && window.FileList && window.Blob)
{
    var files = document.getElementById('filesToUpload').files;
    for(var i = 0; i < files.length; i++)
    {
        resizeAndUpload(files[i]);
    }
}
else
{
    alert('The File APIs are not fully supported in this browser.');
}
return false;
 }

and in your form pass the form as parameter:
<form enctype="multipart/form-data" method="post" onsubmit="return uploadphoto(this)">

Good luck


text:
Q: Why use canvas for animation in html5? I'm new to html5 and have been playing around with the canvas. I'm wondering when the canvas would really be necessary/useful? i.e. when is it meant to be used?
If i need to do simple animation, like move tags around, do i really need a canvas or is it better/easier to just use jquery/js?

A: With help of canvas you can create 2D graphic applications, animations, simple transformation of images (like rotating them), GUI etc. Some examples:

*

*Asteroids game

*jigsaw puzzle

*About GUI, unfortunately I can't load a site, no idea why... it was called  iWidgets.com, the only thing I've found is a screenshot. You can see blue pipeline there, they bound elements. It was done with help of canvas; while moving elements, pipelines also were redrawing; when you change active element all its connections changes color to yellow (so you see dependencies). Nice project, I hope it is not accessible just for a while...

Good article about how to use it is here
From "An insight into the HTML5 Canvas Element":

The canvas element is interesting and
  worthy of focus because it enables,
  for the first time, direct drawing of
  graphics within a browser without the
  use for an external plugin like Flash
  or Java. The beauty of canvas is that
  it's controlled entirely via simple
  JavaScript code, meaning it builds on
  the powerful functionality JavaScript
  already provides and doesn't require a
  crazy learning curve to use.
Choosing to experiment with canvas
  over other new elements was simply
  down to it's functionality as a
  graphics platform, which inherently
  makes it a potentially interesting and
  rich platform to play with. It was
  decided that pushing the flexible
  canvas element would produce the most
  interesting results that we can use in
  the application.
Another deciding factor for choosing
  canvas was to test the animation
  capabilities and the possibility of it
  being a potential Flash replacement.
  Now Flash obviously has features that
  canvas could never emulate, however
  it's an exciting concept nonetheless
  to see exactly what could be achieved
  with canvas that would normally be
  done by reaching for Flash.

read that article to get more useful information
PS. If your animation is about tags moving (like parts of your page), then canvas does not fit. Canvas is for graphic rendering. So in that case you will use jquery or other JS libraries.

A: Here's the best practices for deciding when to use CSS3 Transitions / Animations or Canvas.  Keep in mind that if you're using jQuery, under the covers they will be using CSS3 transitions or animations when possible.
CSS3 Translations / Animations - use these if you're animating DOM element styles, such as position and size
Canvas animations - use canvas animations if you're animating something more complex, like if you're creating an online game or building a physics simulator.  If you're animating 3-d models, you'll definitely want to use canvas so that you can leverage WebGL

A: Canvas gives you access to the pixel level of the graphics. If you wanted to do a checkerboard transition you could do that with a script in canvas but not in jquery.
For a few examples of what is possible (already been done) see http://www.netzgesta.de/transm/


text:
Q: How do I find the code executed when wp_head() is called? I am working on editing the header.php file and I am a bit confused.
I am editing the header.php file and I see a call in it to wp_head();
I know that it calls a "callback function" with something like this:
add_action('wp_head' , 'callback_function');

But I am not sure how to find that. Where should I look for it?
Basically I need to edit how the  tag is configured there.
EDIT:
This is the full header:
<?php
/**
 * Core header file, invoked by the get_header() function
 *
 * @package Suffusion
 * @subpackage Templates
 */

global $suffusion_unified_options, $suffusion_interactive_text_fields, $suffusion_translatable_fields, $suffusion_skin_dependence, $suf_color_scheme;
if (function_exists('icl_t')) {
    foreach ($suffusion_unified_options as $id => $value) {
        /**
         * Some strings are set interactively in the admin screens of Suffusion. If you have WPML installed, then there may be translations of such strings.
         * This code ensures that such translations are picked up, then the unified options array is rewritten so that subsequent calls can pick it up.
         */
        if (function_exists('icl_t') && in_array($id, $suffusion_translatable_fields) && isset($suffusion_interactive_text_fields[$id])) {
            $value = wpml_t('suffusion-interactive', $suffusion_interactive_text_fields[$id]."|".$id, $value);
        }
        global $$id;
        $$id = $value;
        $suffusion_unified_options[$id] = $value;
    }
}

$queried_id = get_queried_object_id();
$hidden_elements = array();
if ($queried_id != 0) {
    $hide_top_navigation = suffusion_get_post_meta($queried_id, 'suf_hide_top_navigation', true);
    if ($hide_top_navigation) {
        add_filter('suffusion_can_display_top_navigation', 'suffusion_disable_component_for_view');
        $hidden_elements[] = 'no-top-nav';
    }
    $hide_main_navigation = suffusion_get_post_meta($queried_id, 'suf_hide_main_navigation', true);
    if ($hide_main_navigation) {
        add_filter('suffusion_can_display_main_navigation', 'suffusion_disable_component_for_view');
        $hidden_elements[] = 'no-main-nav';
    }
    $hide_header = suffusion_get_post_meta($queried_id, 'suf_hide_header', true);
    if ($hide_header) {
        add_filter('suffusion_can_display_header', 'suffusion_disable_component_for_view');
        $hidden_elements[] = 'no-header';
    }
    $hide_footer = suffusion_get_post_meta($queried_id, 'suf_hide_footer', true);
    if ($hide_footer) {
        add_filter('suffusion_can_display_site_footer', 'suffusion_disable_component_for_view');
        $hidden_elements[] = 'no-site-footer';
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>>

    <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
    <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />

<?php
    suffusion_document_header();
    $suffusion_pseudo_template = suffusion_get_pseudo_template_class();
    if (is_singular()) {
        wp_enqueue_script('comment-reply');
    }
    $skin = isset($suf_color_scheme) ? $suf_color_scheme : 'light-theme-gray-1';
    $extra_classes = $suffusion_pseudo_template;
    if (isset($suffusion_skin_dependence[$skin])) {
        $extra_classes = array_merge($extra_classes, $suffusion_skin_dependence[$skin]);
    }
    $extra_classes[] = $skin;
    $extra_classes = array_merge($extra_classes, $hidden_elements);
    wp_head();
?>

<body <?php body_class($extra_classes); ?>>
    <?php suffusion_before_page(); ?>
        <?php
            suffusion_before_begin_wrapper();
        ?>

        <?php
            suffusion_after_begin_wrapper();
        ?>

                <?php
                    suffusion_after_begin_container();
                ?>

Thank you!

A: since you want to edit title attribute.

*

*goto functions.php and search wp_title, on line 277 you find add_filter('wp_title', 'suffusion_modify_title', 10, 3);

*search for callback fx suffusion_modify_title in /suffusion/functions/filters.php, on line 664 you find suffusion_modify_title fx which i think
handle titles.


text:
Q: Will and would difference
1) Having faster computers would make for a more efficient system.
2) Having faster computers will make for a more efficient system

What is the difference in meaning between these two sentences?
Does the first question means that if we had computers (we don't have them now), it would make for a more efficient system?
And does the second sentence mean that we have computers and they are going to make our system more efficient?

A: I interpret it as :
1 - A hypothetical. If we were to have faster computers, then they would make the system more efficient
2 - More certain. We are going to have faster computers and they will make the system more efficient
Having said that, they are very similar, and even #2 doesn't mean that it's 100% certain. But #1 is always hypothetical.
It's not really about if we have the computers currently (future vs present). It's more about the certainty/likelihood of getting the computers in the future.


text:
Q: Nodejs Mysql connection best practice What is the best practice when we want to create MySql connection in nodejs.

*

*Create a global connection and use it for all queries

*Open a new connection for each query and close it after the query is done.

A: Connection pooling will handle your requests automatically.
This article covers the topic and might be helpful - https://medium.com/@mhagemann/create-a-mysql-database-middleware-with-node-js-8-and-async-await-6984a09d49f4

A: Define Global connection variable and use it in the whole project.

// only use when you have not setup app.set('con',con);
// global.con;

dbConnection = () => {

  // MYSQL database connection start
  let con = mysql.createPool('database Config obj here');

  // if you want use global.con variable
  // con = mysql.createPool(databaseConfig);

  con.getConnection((err) => {
    if (err) {
      //- The server close the connection.
      if (err.code === "PROTOCOL_CONNECTION_LOST") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Connection in closing
      else if (err.code === "PROTOCOL_ENQUEUE_AFTER_QUIT") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Fatal error : connection variable must be recreated
      else if (err.code === "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Error because a connection is already being established
      else if (err.code === "PROTOCOL_ENQUEUE_HANDSHAKE_TWICE") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Anything else
      else {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      setTimeout(dbConnection, 5000);
    } else {

      // you can also set the con varibale by calling below set method or else use global.con ;
      app.set('con', con);

      // rest of the code will goes here
    }
  });
}

dbConnection();

let con = app.get('con');
// => will have connection varibale here