text:
Q: Read value of an evaluation returning an array from PHP-JS I've recently started using this PHP-JS library.
It's basically a php wrapper over Google's V8 javascript engine.
The main reason of using it is that it can run isolated javascript code.
And return the outcome.
It's no problem for int and string values. Those are returned as-is.
But I found myself creating an array and i need to return it.
I get:

PHP Fatal error:  Cannot use object of type JS\Object as array

I'm doing this simple script:
<?php
$context = new JS\Context();
$script = "var arr = ". json_encode([2,3]).";x = arr.length";
var_dump($context->evaluate($script));
// int(2) - which is correct

But if I want to get the arr returned:
<?php
$script = "var arr = ". json_encode([2,3])."; arr;";
var_dump($context->evaluate($script));
// class JS\Object#1 (0) {}

Note: evaluate($stuff) returns the last variable in the script.
Is there any nice way of returning that value?

Update: After some digging, I've found a way to access data. What it does is encapsulate the array into a stdClass object:
$result = $context->evaluate($script);
echo $result->{0}; // outputs 2
// also works for ->{1}

But it's still way too ugly to use in real-life

A: Figured out a way to extract array results of the evaluation:
$script = "var arr = ". json_encode([2,3]).";x = JSON.stringify(arr);";

At this point, x is a string:
var_dump($context->evaluate($script)); // string(5) "[2,3]"

Now all I needed to do is 'reverse' the JSON.stringify():
var_dump(json_decode($context->evaluate($script),true));
// array(2) {
//   [0] => int(2)
//   [1] => int(3)
// }

Update

Arrays returned as JS\Object are iterable. So this is valid:
$script = "var arr = ". json_encode([2,3]).";arr";
foreach($obj as $key=>$val){
    print_r($key);echo " => ";print_r($val);echo "\n";
}
// output
// 0 => 2
// 1 => 3

It's not that nice when the return array is nested:
$script = "var arr = ". json_encode([2,3,[1,4]]).";arr";
$obj = $c->evaluate($script);
foreach($obj as $key=>$val){
    print_r($key);echo " => ";print_r($val);echo "\n";
}
// output
// 0 => 2
// 1 => 3
// 2 => JS\Object Object() <- this needs looping too

For the second example a recursive method is required to parse all levels.
So I'm sticking with the JSON.stringify and json_decode($r, true);


text:
Q: Link to blank page and addition new condition in php code I'd like to add condition to my code so that after click on label it link me to other page. Now this code link to other article on the website. So I guess what should I add to get from my label to other page.
Thank you for answers!
My code is below:

    <?php foreach ($this->items as $key=>$item ){

       if($item['children']){ ?>
          <li role="presentation" class="<?php if($item['menu']->id==$this->pageId || $item['menu']->id==$this->parentId){ echo 'active'; } ?>"><a href="#about-us-page-<?php echo $item['menu']->id;?>" aria-controls="about-us-page-<?php echo $item['menu']->id;?>" role="tab" data-toggle="tab"><?php echo $item['menu']->title;?>

      <?php }else{ ?>
              <li role="presentation" class="<?php if($item['menu']->id==$this->pageId || $item['menu']->id==$this->parentId){ echo 'active'; } ?>"><a href="<?php echo $item['menu']->path;?>" aria-controls="about-us-page-<?php echo $item['menu']->id;?>"><?php echo $item['menu']->title;?>

        <?php } ?>
<?php } ?>

A: All this start/stop of PHP code hurts my eyes! Anyways, linking to other pages is done with  tags. Not quite sure I understand your question, but you could (if you mean labels for form elements) do something like this;
  Something Meaningful

I'm sorry, but I took the liberty to clean up your code a little. Hopefully this will make it more readable;

<?php

foreach ($this->items as $key=>$item ){

    $active = NULL;
    if($item['menu']->id==$this->pageId || $item['menu']->id==$this->parentId){
        $active = 'active';
    }

    $menu = NULL;
    if($item['menu']->id==$this->pageId || $item['menu']->id==$this->parentId){
        $menu = 'active';
    }

    if($item['children']){
        echo'

                id.'" aria-controls="about-us-page-'.$item['menu']->id.'" role="tab" data-toggle="tab">'.$item['menu']->title.'

';

    }else{
        echo'

                path.'" aria-controls="about-us-page-'.$item['menu']->id.'">'.$item['menu']->title.'

';
    }
}

?>

For your comment question, if you know what item needs a different value, it could be the title f.ex. then you can check against that value and change the output of your element. Maybe something like;
if($item['children']){

    if($item['title'] == 'Unique Identifier for your element') {
        // In here you could manipulate the output of that one item you want to exclude/change

    } else {
        // Your normal output
        echo'

                    id.'" aria-controls="about-us-page-'.$item['menu']->id.'" role="tab" data-toggle="tab">'.$item['menu']->title.'

';

}else{ ... }

And even better would be to perform the check beforehand, so maybe something like;
$link = '#about-us-page-'.$item['menu']->id;
if($item['title'] == "That identifier") {
    $link = 'somethingElse';
}

and then change the value of your href tag to;
 id.'" role="tab" data-toggle="tab">'.$item['menu']->title.'

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to properly implement voting on decision tree bagging method with for loop? I am new to python and machine learning I've tried to look at at sklear documentation for voting classifier and to be quite hones I was bot lost.
I have performed bagging for a decision tree inside a for loop, however I am stuck where I have to perform Voting to make the final decision on
each data sample, and then calculate the accuracy on the final results.
I get TypeError: zip argument #1 must support iteration.
Below is my code
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.utils import resample

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.35, random_state=3)

predictions = []

for i in range(1,20):
bootstrap_size = int(0.8*len(X_train))
x_bag, y_bag = resample(X_train,y_train, n_samples = bootstrap_size , random_state=i , replace = True)
Base_DecisionTree = DecisionTreeClassifier(random_state=3)
Base_DecisionTree.fit(x_bag, y_bag)
y_predict = Base_DecisionTree.predict(X_test)
accuracy = accuracy_score(y_test, y_predict)
predictions.append(accuracy)

from sklearn.ensemble import RandomForestClassifier, VotingClassifier
votingClass = VotingClassifier(predictions)
#print(votingClass)
votingClass.fit(X_train, y_train)
confidence = votingClass.score(X_test, y_test)
print('accuracy:',confidence)

A: I  looked into the VotingClassifier from my understanding the function accepts  a set of classifier while in your case you are giving a list of accuracy. Please find a example code from the documentation of sklearn (https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.VotingClassifier.html)
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier, VotingClassifier

clf1 = LogisticRegression(solver='lbfgs', multi_class='multinomial',random_state=1)
clf2 = RandomForestClassifier(n_estimators=50, random_state=1)
clf3 = GaussianNB()

X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
y = np.array([1, 1, 1, 2, 2, 2])
eclf1 = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='hard')
eclf1 = eclf1.fit(X, y)
print(eclf1.predict(X))
#[1 1 1 2 2 2]
np.array_equal(eclf1.named_estimators_.lr.predict(X), eclf1.named_estimators_['lr'].predict(X))
#True
eclf2 = VotingClassifier(estimators=[ ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='soft')
eclf2 = eclf2.fit(X, y)
print(eclf2.predict(X))
#[1 1 1 2 2 2]
 eclf3 = VotingClassifier(estimators=[ ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='soft', weights=[2,1,1], flatten_transform=True)
eclf3 = eclf3.fit(X, y)
print(eclf3.predict(X))
#[1 1 1 2 2 2]
print(eclf3.transform(X).shape)
#(6, 6)

EDIT
So I don't think that the function VotingClassifier is the right path to solve your task.
What you have to do is to collect all the y_predict from your for loop.
This will give you a prediction for each sample.
once that for each sample (e.g. ) you have all the predictions (e.g  ) you can compute the vote. The result will be the final label of the prediction (= Vote()).
The accuracy is given comparing the labels predicted from the vote with the ground truth.


text:
Q: Bigint Multiplication Help C++ Here I've got a bigint calculator that uses a safearray class(not shown) to store large numbers and do arithmetic operations on them. I've got add and subtract working but when I try multiplication it compiles and runs but nothing happens. Could someone help me fix this? Thanks
int size = 100;

class bigint
{
    SafeArray<int> *arr;
public:
    char sign;
bigint()                                                   //initializes to zero
    {
        arr = new SafeArray<int>;
        for(int i =0;i < size; i++)
            arr->set(i,0);
    }

void print()                                               //prints numbers without zeroes in front
    {
        bool start_num=false;
        for(int i = 0;i <arr->get_size() ;i++)
        {
            if(arr->get(i)!=0 && start_num==false )
            {start_num=true;
                cout << arr->get(i);}
         else if(start_num==true)
             cout<<arr->get(i);

        }

       cout<<endl;
    }

void assign(const bigint &A)                             //
    {
        for(int i=0;i<arr->get_size();i++)
        {                                                            //Ways to initialize stuff
            arr->set(i,A.arr->get(i));
        }

    }

void assign(int num)                                     //
    {
        for(int i = arr->get_size()- 1; i >= 0; i--)
        {
            arr->set(i,num%10);
            num /=10;
        }

    }

void assign(string num)                                  //
    {
        long len = num.length();
        int j=arr->get_size()-1;
        for(long i=len-1;i>=0;i--)
        {
            arr->set(j,num[i]-48);
            j--;
        }
    }

void add_pos(const bigint &A)                                //add big ints
    {
        int carry=0;
        for(int i=size-1;i>=0;i--)
           {
               int result = arr->get(i)+A.arr->get(i)+carry;
               arr->set(i,result%10);
               carry=result/10;
           }
    }

    void  multiply(bigint &A)
    {
        bigint temp;

        for(int i=0;i<size;i +=1)
        {
            temp.arr->set(i,arr->get(i));
            arr->set(i,0);
        }
        int i1, i2;
        for(i2=0; i2<size; i2++)
        {
            int borrow =0;
            for(i1=0;i1+i2<size;i1++)
            {
                int total=temp.arr->get(i1)*A.arr->get(i2);
                int totalsum=total+arr->get(i1+i2)+borrow;
                arr->set(i1+i2,totalsum%10);
                borrow = totalsum/10;
            }
        }

};
int main()

{

    bigint a, b, c;
    a.assign("2543281");
    b.assign("3434");
    a.mulitply(b);
    a.print();
return 0;
}

A: The result of multiplication of two bigint numbers of size = 100 certainly needs more than 100 digits, perhaps 200?
For minimal modification, you may pass size as constructor argument to bigint. Ideally, bigint may use a vector so that the digit array can grow dynamically in a convenient and flexible way.
class bigint {
  std::vector<int8_t> digits_;   // each digit must be in 0-9 range
  ...

A: These were lil complicated so I came up with this:
InfInt InfInt::operator*(const InfInt& a) const{

InfInt final = 0;
std::string result;
InfInt* temp;

int carry;
int current;

//fast mult algorithm. the same we were taught in elementary.
for(long i=length() - 1;i >= 0; i--){
    carry = 0;
    result = "";
    for (long j=a.length() - 1; j >= 0; j--){
        current = (value[i] - '0') * (a.value[j] - '0') + carry;
        result = (char)(current % 10 + '0') + result;
        carry = current / 10;
    }

    if (carry > 0)
        result = (char)(carry + '0') + result;

    temp = new InfInt(result);
    final += *new InfInt(temp->alignLeft(length() - i - 1));
}

final.setSign(sign ^ a.sign);
return final;
}

Hope it helps


text:
Q: why I can't access my application inside my AndroidViewModel class? I am new in Android development especially using MVVM pattern. I need context in my viewModel, so I use AndroidViewModel to get context through application, but I don't know why I can't access the application
class CreateEventViewModel(application: Application) : AndroidViewModel(application) {

    fun checkIfItHasInternetConnection() {

        if (InternetConnection.checkConnection(application)) {

        }

    }

}

A: Just try to call getApplication<Application>(). This is a method in AndroidViewModel to get the application :) No need to store application as a field.

A: use private val application:Application in primary constructor
below example :
try this way
class CreateEventViewModel(private val application: Application) : AndroidViewModel(application) {

fun checkIfItHasInternetConnection() {

    if (InternetConnection.checkConnection(application)) {

    }

}
}

A: Try this
class CreateEventViewModel(private val application: Application) : AndroidViewModel(application) {

    fun checkIfItHasInternetConnection() {

        if (InternetConnection.checkConnection(application)) {

        }

    }

}

A: updated code:
data class CreateEventViewModel(val application: Application) : AndroidViewModel(application) {

    fun checkIfItHasInternetConnection() {

        if (InternetConnection.checkConnection(application)) {

        }

    }

}


text:
Q: EclipseLink : Criteria Builder API and NOT IN clause I'm working with a criteria builder query and having an issue with including a 'not in' clause.  Here's my code:
CriteriaBuilder cb = AppUtils.EMF.PU_ROSTER.getEntityManager().getCriteriaBuilder();

    CriteriaQuery<Members> cq = cb.createQuery(Members.class);

    Root<Members> root = cq.from(Members.class);
    Expression<Integer> idExp = root.get(Members_.memberId);

    if (currentFlag) {
        Predicate p = idExp.in(getCurrentUserList());
        cq.where(cb.and(p));
    } else {
        Predicate p = idExp.in(getCurrentUserList());
        cq.where(cb.not(cb.and(p)));

    }

    cq.where(cb.and(root.get(Members_.refMemberStatus).get(RefMemberStatus_.id).in(AppUtils.MEMBER_STATUS_ACTIVE)));

    List<Order> orderList = new ArrayList();
    orderList.add(cb.asc(root.get(Members_.lastName)));
    orderList.add(cb.asc(root.get(Members_.firstName)));

    cq.orderBy(orderList);

    Query q = AppUtils.EMF.PU_ROSTER.getEntityManager().createQuery(cq);

    return q;
}

the getCurrentUserList() function returns a List<Integer> collection.  My issue is regardless of whether my 'currentFlag' is true or false, I get the same result set.  Looking at the queries in the debugger they look exactly the same.  I put a breakpoint on currentFlag and it has the proper value and the appropriate code is in fact processed based on it's value, yet the queries are identical.
[EL Fine]: sql: 2016-06-06 07:41:34.26--ServerSession(845434732)--Connection(733865607)--SELECT MEMBER_ID, ALT_PHONE, CDATE, CITY, DEGREE, DEPARTMENT, EDATE, EMAIL, FAX, FIRST_NAME, INSTITUTION, LAST_NAME, MIDDLE_NAME, MOBILE_PHONE, MODIFIER, PAGER, PASSWORD, PHONE, PHONE_EXT, RAW_PASSWORD, STATE, STREET1, STREET2, USERNAME, ZIP, MEMBER_STATUS_ID FROM ROSTER.MEMBERS WHERE (MEMBER_STATUS_ID IN (?)) ORDER BY LAST_NAME ASC, FIRST_NAME ASC

[EL Fine]: sql: 2016-06-06 07:42:09.191--ServerSession(845434732)--Connection(733865607)--SELECT MEMBER_ID, ALT_PHONE, CDATE, CITY, DEGREE, DEPARTMENT, EDATE, EMAIL, FAX, FIRST_NAME, INSTITUTION, LAST_NAME, MIDDLE_NAME, MOBILE_PHONE, MODIFIER, PAGER, PASSWORD, PHONE, PHONE_EXT, RAW_PASSWORD, STATE, STREET1, STREET2, USERNAME, ZIP, MEMBER_STATUS_ID FROM ROSTER.MEMBERS WHERE (MEMBER_STATUS_ID IN (?)) ORDER BY LAST_NAME ASC, FIRST_NAME ASC

I've tried putting my cb.not clause in various places, but it never seems to make a difference.
As per the comment below (thank you Neil Stockton), I updated part of the above code with the following:
if (currentFlag) {
        Predicate p = idExp.in(getCurrentUserList());
        cq.where(p);
    } else {
        Predicate p = idExp.in(getCurrentUserList());
        cq.where(cb.not(p));

    }

with no change in resultset or generated query..

A: Ok, thank you again, Neil!!  You got me thinking more about it, and I figured out what was going on..  Here's my solution:
CriteriaBuilder cb = AppUtils.EMF.PU_ROSTER.getEntityManager().getCriteriaBuilder();

    CriteriaQuery<Members> cq = cb.createQuery(Members.class);

    Root<Members> root = cq.from(Members.class);

    Expression<RefMemberStatus> activeExp = root.get(Members_.refMemberStatus);
    Expression<Integer> idExp = root.get(Members_.memberId);

    Predicate activePredicate  = activeExp.in(AppUtils.MEMBER_STATUS_ACTIVE);

    if (currentFlag) {
        Predicate p = idExp.in(getCurrentUserList());
        cq.select(root).where(p, activePredicate);
    } else {
        Predicate p = idExp.in(getCurrentUserList());
        cq.select(root).where(cb.not(p), activePredicate);

    }

    List<Order> orderList = new ArrayList();
    orderList.add(cb.asc(root.get(Members_.lastName)));
    orderList.add(cb.asc(root.get(Members_.firstName)));

    cq.orderBy(orderList);

    Query q = AppUtils.EMF.PU_ROSTER.getEntityManager().createQuery(cq);

    return q;

It turns out when I set the where clause, it does not append to the property with new, but completely overwrites the value (Duh!)...  So I created the appropriate predicates for all of my criteria, and watched it work.  If there is a more dynamic way to do this, please feel free to let me know.  I'm just figuring this stuff out...


text:
Q: PHP MySQL - Am I doing anything wrong? For two hours now, I'm trying to insert a value into a table. I don't get any error and I can't find out the problem!
The value that I'm trying to insert:
$query = "INSERT INTO banlist (banid, active, ip, by, date, reason) VALUES (NULL, 1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')";
mysql_query($query);

An example value that works perfectly:
$query = "INSERT INTO accounts (username, password, email, regdate) VALUES ('test', 'test', 'test@test.test', 't-t-t t:t:t')";
mysql_query($query);

I can't find the problem! Am I missing anything? Both tables exist.

A: The issue is that the name you've chose for a field "by" is a reserved word. You'll have to update it to a word that's not on this list.
Also, in future you can easily see what's wrong by checking if mysql_query() returned false, and then calling mysql_error() for an error message.

A: Try this:
    CREATE TABLE ban (
    banid int auto_increment primary key,
    active int,
    ip varchar (20),
    `by` varchar (20),
    `date` varchar(8),
    reason varchar(20)
        );

    INSERT INTO ban (active, ip, `by`, `date`, reason)
    VALUES
    (1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')
    ;

    SELECT * FROM ban;

http://www.sqlfiddle.com/#!2/1959f/1
Some remarks:
Like several others (e.g. @wintercounter, @user1909426 ) have pointed out you are using restricted words in MySQL. If you do use a restricted word then use `` (back ticks) or just use them on every column.
I think that using a null in your first part of you insert gives a problem. This column is probably an integer column with auto_increment. See @wintercounter answer.
Fortunately date is not a restricted name. B.T.W. you could use use a date value instead of you varchar value now.
With regard to the comments from @tadman using mysql instead of mysqli or PDO is not recommended. The mysql library is depreciated from version PHP 5.5 onwards, see the php manual. You will also need to include error handling.
For completeness sake, this is the php code when using MySQLi:
  $link = mysqli_connect($hostname, $username, $password, $database);
  if (!$link){
  echo('Unable to connect to database');
  }

  else{
  mysqli_query("INSERT INTO ban (active, ip, `by`, `date`, reason) VALUES (1,'10.25.47.88', 'AUTOBAN', '12-12-45', 'test'))", $link);
  }

  mysqli_close($link);

For mysql version:
  $hostname = "hostname";
  $username = "username";
  $username = "password";
  $database = "database";

  $link = mysql_connect($hostname, $username, $password);
  mysql_database ($database)
  if (!$link){
  echo('Unable to connect to database');
  }

  else{
  mysql_query("INSERT INTO ban (active, ip, `by`, `date`, reason) VALUES (1,'10.25.47.88', 'AUTOBAN', '12-12-45', 'test')");
  }

  mysql_close($link);

A: use mysql error statement in each variable for know which line your mistake occured.

A: The query probably doesn't display an error because error_reporting is turned of in your php.ini:
try setting error_reporting to E_ALL.
Also the query might not work because you are sending "NULL" as value for banid which is probably a either a primary key or a foreign key / index that doesn't allow a NULL value.

A: Try this:
INSERT INTO `banlist` (`banid`, `active`, `ip`, `by`, `date`, `reason`) VALUES ('', 1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')

As stated, 'by' is reserved keyword, but you can help to MySQL in the parse so it'll know if it's a field name or a command.
EDIT:
I've changed NULL to ''. I'm not sure in this, never tried, but if it's an AI field, maybe you can't use NULL there, just use an empty content as a placeholder for ID field.

A: Just try this:
INSERT INTO banlist VALUES (NULL, 1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')


text:
Q: Java - delay between events after entering the value into JTextArea I prepared a simple form (javax.swing.JFrame) on which JTextArea is located.
After entering the "TAB" value, I would like to see a visible JPanel on the form for a few seconds. Unfortunately, when I have the following events:

JPanel.setVisible (true);

TimeUnit.SECONDS.sleep (3);

JPanel.setVisible (false);

in keyPressed for JTextArea.KeyListener ()

they don't execute one after another - first I get sleep, then JPanel.setVisible (true) and JPanel.setVisible (false)
public class Form1 extends JFrame {

    JTextArea txt1 = new JTextArea();
    JPanel pnl2 = new JPanel();

    public Form1() {

        txt1.setLocation(10, 10);
        txt1.setSize(100, 30);
        txt1.addKeyListener(new KeyListener() {

            @Override
            public void keyPressed(KeyEvent e
            ) {
                if (e.getKeyCode() == KeyEvent.VK_TAB) {
                    e.consume();

                    pnl2.setVisible(true);
                    try {
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Form1.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    pnl2.setVisible(false);
                }
            }

            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyReleased(KeyEvent e
            ) {
            }
        });
        add(txt1);

        pnl2.setLayout(null);
        pnl2.setLocation(10, 150);
        pnl2.setSize(100, 100);
        pnl2.setBorder(BorderFactory.createEtchedBorder());
        pnl2.setVisible(false);
        add(pnl2);
    }
}

Main class:
public class Main {

    public static void main(String[] args)  {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                Form1 f = new Form1()
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setSize(500, 400);
                f.setLocationRelativeTo(null);
                f.setResizable(false);
                f.setLayout(null);
                f.setVisible(true);
            }
        }
        );
    }
}

How can I get the effect of showing the panel on the form for a few seconds after entering the "TAB" button on TextArea?

A: Don't block the AWT Event Dispatch Thread (EDT).
Instead, set a javax.swing.Timer (get the package right - not the other one!). The Swing Timer may create another thread to do the timing, but posts the event back through the EDT (via java.awt.EventQueue.invokeLater or similar). The code executed after the sleep should be move to an action listener.
                pnl2.setVisible(true);
                javax.swing.Timer timer =
                    new javax.swing.Timer(3000, event -> {
                        pnl2.setVisible(false);
                    });
                timer.setRepeats(false);
                timer.start();

(I have used the fully qualified name to emphasize the right Timer. Sometimes I forget that by default it will repeat, which would be confusing.)


text:
Q: Azure function app - Data automatically escaping quotes and throwing errors I'm working with an Azure Function app that is connected to salesforce. There is a step that grabs a string of values from a field in salesforce and composes it into a value that I am sending to my on-prem service.
The problem is my List is trying to escape the quotes in the output and it's messing up my data on the back end.
The first step returns the fields as below
"Get_Provider_Types": {
        "inputs": {
            "host": {
                    "connection": {
                                    "name": "@parameters('$connections')['salesforce']['connectionId']"
                                }
                            },
        "method": "get",
        "path": "my SF connection string",
        "queries": {
            "$select": "Provider_Types__c"
        }
    },
    "runAfter": {},
    "type": "ApiConnection"
}

The output runs successfully and appears as below
[
  "Field 1",
  "Field 2",
  "Field 3"
]

The next step is to compose a JSON message with the values from the previous step
"Compose_Message": {
        "inputs": {
                "Provider_Types__c": "@{body('Get_Provider_Types')?['Provider_Types__c']}"
        },
        "runAfter": {
                "Get_Provider_Types":
                    [
                        "Succeeded"
                    ]
        },
"type": "Compose"
}

The values from @{body('Get_Provider_Types')?['Provider_Types__c']} are returning but it appears to be trying to escape the quotes which throws an error on the back end.
"Provider_Types__c": "[\"Field 1\",\"Field 2\",\"Field 3\"]"

How can I get my data to look like the first step above?
Thanks!

A: Luckily I figured out my problem pretty quickly! The {} in logic apps automatically serializes data.
I had to change
"@{body('Get_Provider_Types')?['Provider_Types__c']}"

to
"@body('Get_Provider_Types')?['Provider_Types__c']"

Only had to remove the {}. Very subtle change, hopefully this helps someone in the future.


text:
Q: Fitting a 3d point cloud with a polynomial surface I have 3D point cloud and I would like to fit a polynomial surface to it.
    Could anybody please explain the step by step process to that.
Thanks a lot.


text:
Q: Taking formatted input : sscanf not ignoring white spaces I have to find out the input hours and minutes after taking inputs from the user of the form :
( Number1 : Number2 )

eg: ( 12 : 21 )
I should report 12 hours and 21 minutes and then again wait for input. If there is a mismatch in the given format, I should report it as invalid input. I wrote this code :
#include<stdio.h>
int main()
{
    int hourInput=0,minutesInput=0;
    char *buffer = NULL;
    size_t size;

    do
    {
        puts("\nEnter current time : ");
        getline ( &buffer, &size, stdin );

        if ( 2 == sscanf( buffer, "%d:%d", &hourInput, &minutesInput ) && hourInput >= 0 && hourInput <= 24 && minutesInput >=0 && minutesInput <= 60  )
        {

            printf("Time is : %d Hours %d Minutes", hourInput, minutesInput );
        }

        else
        {
            puts("\nInvalid Input");
        }
    }

    while ( buffer!=NULL && buffer[0] != '\n' );

    return 0;
}

Q. if someone gives spaces between the number and :, my program considers it as invalid input, while I should treat it as valid.
Can someone explain why it is happening and any idea to get rid of this issue ? As far as I understand, sscanf should ignore all the white spaces ?

A: To allow optional spaces before ':', replace
"%d:%d"

with
"%d :%d"

sscanf() ignores white space where its format directives tell it to ignore, not everywhere.  A whitespace character in the directive such as ' ' will ignore all white spaces.  %d as well as other integer and floating point directives will ignore leading white space.  Thus a space before %d is redundant.
C11 7,21,6,2,8 Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier.)

Additional considerations include using %u and unsigned as an alternate way to not accept negative numbers.  strptime() is a common function used for scanning strings for time info.

A: Avoid comparing sscanf() return value. In your case, it is always depends on the user input. If user gives spaces between input this value changes.

A: I think if you put a space before and after the colon, it will ignore any whitespace and still work when they don't put spaces before and after the colon.
Like this:
sscanf( buffer, "%d : %d", &hourInput, &minutesInput )

A: use "%d : %d" as format string. it will work with and without spaces.

A: 1st thing allocate memory before using buffer
2nd is this a C++ program or C as getline is not a C standard function.
Check this
int main()
{
        int x=0,y=0;
        char bff[]="7        8";
        sscanf(bff,"%d%d",&x,&y);
        printf("%d %d",x,y);
}

o/p-7 8

A: On sscanf man pagez
RETURN VALUE OF SSCANF -

These functions return the number of input items assigned.  This can
  be
       fewer than provided for, or even zero, in the event of a matching fail-
       ure.  Zero indicates that, although there was input available, no conver-
       sions were assigned; typically this is due to an invalid input character,
       such as an alphabetic character for a `%d' conversion.  The value EOF is
       returned if an input failure occurs before any conversion such as an end-
       of-file occurs.  If an error or end-of-file occurs after conversion has
       begun, the number of conversions which were successfully completed is
       returned.

Now,

if someone gives spaces between the number and :, my program considers
  it as invalid input

Yes , it should consider it wrong because the sscanf reads the from the buffer in exactly the same way as %d:%d,but if a character in the input stream conflicts with format-string, the function ends, ending with a matching failure.
Characters outside of conversion specifications are expected to match the sequence of characters in the input stream; the matched characters in the input stream are scanned but not stored. (Please see the emphasis on the sentence in bold)
i.e, sscanf while writing to the memory ignores whitespaces.


text:
Q: How to stop puppeteer from overwriting duplicate? I have to write a program as a schoolproject which automaticly screenshots the gasprices from 10 locations for 2 months . I used puppeteer and it works. However if i start it again it overwrites the files because they have the same name. I locked for solutions but couldnt find something that works. Does someone know a solution.
    const puppeteer = require ('puppeteer');
    async function start() {
    const browser = await puppeteer.launch({
        defaultViewport: {width: 1920, height: 1080}
    });
    await page.goto("https://spritpreisalarm.de")

    await page.type("#searchform > table > tbody > tr > td:nth-child(1) > input[type=text]","Leipzig");
    await page.click("#searchform > table > tbody > tr > td:nth-child(4) > input");

    await page.goto('https://spritpreisalarm.de/preise/station/7450/LEIPZIG/1/1', {waitUntil: 'domcontentloaded'});
    await page.screenshot({path:"Leipzig/totalLE.png"});

    await page.goBack('https://spritpreisalarm.de/preise')

    await page.goto('https://spritpreisalarm.de/preise/station/8731/LEIPZIG/1/1', {waitUntil: 'domcontentloaded'});
    await page.screenshot({path:"Leipzig/ARALMstr.png"});
    await page.goBack('https://spritpreisalarm.de/preise');

    await page.goto('https://spritpreisalarm.de/preise/station/7977/LEIPZIG/1/1', {waitUntil: 'domcontentloaded'});
    await page.screenshot({path:"Leipzig/ARALMaxistr.png"});
    await page.goBack('https://spritpreisalarm.de/preise');

    await page.goto('https://spritpreisalarm.de/preise/station/15601/LEIPZIG/1/1', {waitUntil: 'domcontentloaded'});
    await page.screenshot({path:"Leipzig/JETrustr.png"});
    await page.goBack('https://spritpreisalarm.de/preise');
    await page.goBack('https://spritpreisalarm.de');

    await page.goto('https://spritpreisalarm.de/preise/station/13865/04683/1/5' , {waitUntil: 'domcontentloaded'});
    await page.screenshot({path:"Naunhof/STARbrandisstr.png"});
    await page.goBack('https://spritpreisalarm.de/preise');

    await page.goto('https://spritpreisalarm.de/preise/station/1893/BERLIN/1/1', {waitUntil: 'domcontentloaded' });
    await page.screenshot({path:"Berlin/ARALHolzmarktstr.png"});
    await page.goBack('https://spritpreisalarm.de');

    await page.goto('https://spritpreisalarm.de/preise/station/3091/BERLIN/1/1', {waitUntil: 'domcontentloaded' });
    await page.screenshot({path:"Berlin/TotalHolzmarkstr.png"});
    await page.goBack('https://spritpreisalarm.de/preise');

    await page.goto('https://spritpreisalarm.de/preise/station/5045/GRIMMA/1/5', {waitUntil: 'domcontentloaded'});
    await page.screenshot({path:"Grimma/AutobahntankstelleGrimma.png"})

    await browser.close()
}
start()

A: It makes sense to create a new subfolder for your screenshots every time u start the script. Use a unique name for that for example the current timestamp:

const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');
const currentDate = new Date();
const timestamp = currentDate.getTime()+'';
const screensDir = path.resolve(path.join(__dirname, timestamp, 'Leipzig'));

if (!fs.existsSync(screensDir)) {
    fs.mkdirSync(screensDir, {recursive: true});
}

async function start() {
    const browser = await puppeteer.launch({
        defaultViewport: {width: 1920, height: 1080}
    });

    page = await browser.newPage();

    await page.goto("https://spritpreisalarm.de")

    await page.type("#searchform > table > tbody > tr > td:nth-child(1) > input[type=text]","Leipzig");
    await page.click("#searchform > table > tbody > tr > td:nth-child(4) > input");

    await page.goto('https://spritpreisalarm.de/preise/station/7450/LEIPZIG/1/1', {waitUntil: 'domcontentloaded'});
    await page.screenshot({path: screensDir + '/totalLE.png'});

    await page.goBack('https://spritpreisalarm.de/preise')

    await page.goto('https://spritpreisalarm.de/preise/station/8731/LEIPZIG/1/1', {waitUntil: 'domcontentloaded'});
    await page.screenshot({path: screensDir + '/ARALMstr.png'});
    await page.goBack('https://spritpreisalarm.de/preise');

    //...

    await browser.close()
}
start()

A: I would simply add the date to the file name so you can do two actions in one ;p.

*

*have the date

*no overwriting

let date = new Date().toJSON().slice(0,10)
    await page.screenshot({path: screensDir + `/${date}ARALMstr.png`});
    await page.goBack('https://spritpreisalarm.de/preise');

I didn't run it, but you understand the idea.


text:
Q: is there a developer api for pandora on android? I was looking around but couldnt find one, was wondering if anybody knows of such an api?
basically I want to be able to switch songs and play songs on pandora from my application on android.

A: There is no api from pandora available.

A: Unofficially there is actually:
http://pan-do-ra-api.wikia.com/wiki/Json/5
This is the JSON version

A: As of KitKat you can use the RemoteController class to control andy media play that has a registered client like Pandora.
http://developer.android.com/reference/android/media/RemoteController.html

A: There is.
https://6xq.net/pandora-apidoc/
But I've read that Pandora changes it up sometimes to discourage people from writing their own (probably ad-free) clients, so there's no guarantee that it will last.


text:
Q: Error parsing header X-XSS-Protection: 1; mode=block; estoy intentando adjuntar a mi web un simple iframe sacado de youtube.
El tema es que (trabajo con wordpress), lo haga desde el codigo o lo haga a travez de custom fields con un editor, o directo en un post me da el siguiente problema.
Error parsing header X-XSS-Protection: 1; mode=block; report=https://www.google.com/appserve/security-bugs/log/youtube: insecure reporting URL for secure page at character position 22. The default protections will be applied.

Alguien sabe de que manera puedo solventar este problema?
Gracias de antemano

A: No tiene nada que ver con tu sitio, es un bug de Google Chrome: https://bugs.chromium.org/p/chromium/issues/detail?id=807304
Para que desaparezca alcanza con actualizar a la última versión. A partir de la 66.0.3336.0 está corregido.
Edit: Corrijo, la versión 66 de Chrome todavía está Canary. Cuando salga va a dejar de aparecer.


text:
Q: Error Analysis in ANN (modeling) I am using Artificial Neural Networks (FFBP, RBF, GRN) and Multi Linear Regression techniques to model a real world case study.
I have a small list of records (60 data items).
I am using 48 of 60 as my training data set and the remaining 12 as my testing data set.
I have two diagrams: one is based on actual observations for my test set (49 to 60), the other diagram is based on the estimations from the models for my test set (49 to 60).
I have three questions:

*

*What is the best error range for this models (short record data)?

*How can I calculate the error amount that can be added and subtracted with observation to form the error range?

*What is the level of confidence?
I would appreciate if you can direct me to similar examples (or some tutorial) where I can learn to find the answers to my questions.


text:
Q: Is there a list of all embedding techniques used in all applications of Machine learning? I started to learn embedding techniques used in machine learning and allied fields. There are word embeddings, graph embeddings, and network embeddings. I was overwhelmed by the various embedding techniques as I googled. Is there a good repository or book or resource that starts with the need for embedding and slowly moves onto different advanced embedding techniques in NLP, Computer Vision, Knowledge Graphs etc.
I need an organic development of the subject so that I can think in different directions and to b able to come up with my own techniques in the embedding space.


text:
Q: Limit array size in cookie I have the following function to set a cookie on each indiviual product page a user visits on my website.
function setcookie() {

    $entry_id = '787';

    if (isset($_COOKIE['recently_viewed'])) {

        $currentSession = unserialize($_COOKIE['recently_viewed']);

        if (!in_array($entry_id, $currentSession)) {

            if (count($currentSession) > 5) {
                unset($currentSession[0]);
            }

            $currentSession[] = $entry_id;

        } else {}

        $currentSession = serialize($currentSession);
        setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');

    } else {

        $recently_viewed[] = $entry_id;
        $currentSession = serialize($recently_viewed);
        setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');

    }

}

In this function I am trying to limit the number of items stored in the cookies array.
When the cookies array has 6 items in it, I want to remove the first (oldest) item in that array and then add the new item (so there is never more than 6 items, but always adds the new one).
I have used the following, but it doesn't always seem to work. Sometimes it removes the first item when there are more than 5, but other times it just keeps adding them so there are more than 6.
if (count($currentSession) > 5) {
    unset($currentSession[0]);
}

Can anyone tell me if there is a better way to achieve this?

A: You definitely should use session.
session_start();
$entry_id = '788';
if (!is_array($_SESSION['recently_viewed'])) {
    $_SESSION['recently_viewed'] = array();
}
//  add the item to the begining
array_unshift($_SESSION['recently_viewed'], $entry_id);
// ensure unique entries
$_SESSION['recently_viewed'] = array_unique($_SESSION['recently_viewed']);
// keep first 5 entries
$_SESSION['recently_viewed'] = array_slice($_SESSION['recently_viewed'], 0, 5);
echo 'recent: ' . print_r($_SESSION['recently_viewed'], true);

A: if (count($currentSession) > 5) {
    $arr = array_shift($currentSession);
}


text:
Q: How do i save a single user's daily input separately, so that it can be accessed later on a database? Basically i have built a diary-like website which stores whatever the user types, into a database colomn. i want it to be like an actual diary where the user logs in and writes his thoughts each day, and can later access all pages he has written.
Right now i have just one diary colomn in the row of the database allotted one per user. making one table per user would be inefficient.
So how can i store user's input with a date to be accessed later?
colomns in database: id (AI, int), email (text), password (text), diary(text), date (date).

A: Your setup should be normalized.  What I mean:

*

*Create a table for users.

*Create a table for diary entries.

*The diary table links each entry to one of the users.

Ex.:
Table Users
    ID: auto-increment id
    EmailAddress: string
    Password: string

Table diary_entries
    ID: auto-incremnt id
    UserId: foreign key to table Users, ID field
    Entry: the diary entry itself
    Date: the date when the entry was added.  This could be set to NOW() when you do the insert.

*

*This way each diary entry is linked to 1 users, and has a date.

*You can then search per date, per user, per date AND per user.

*If you had kept it all in a single table, you would have had to put in the user's password in every line, for every entry.  How would you know which password is good?

*That is what normalization does, it ensures your database design is not blocking you or creating problems later.  Forms 1, 2 and 3 are the usual forms applied.  The higher ones are more exotic and not always required for a small project.

As to implementing that, you will have to provide some code, do research, and later post a specific question if your research does not help you.  But do not ask "how to" questions, they will get flagged quickly on SO.


text:
Q: Django static files not coming through when deployed to Heroku My static files are not coming through when I am deploying to Heroku. It works fine when I running on my local.
Its not a 404 error, on the network tab it seems like its not even requesting the static files at all.
I have followed this solution on Heroku's website: https://devcenter.heroku.com/articles/django-assets but still not working.
I looked at other solutions and I am already using WhiteNoise.
Here is the relevant code from my settings.py
import os
import environ
import django_heroku

env = environ.Env(
    # set casting, default value
    DEBUG=(bool, False)
)

environ.Env.read_env()

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = (env('DEBUG_VALUE') == "True")

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    #my own apps
    'corsheaders',
    'rest_framework',
    'paintings',
    'storages',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True

ROOT_URLCONF = 't_and_b_website.urls'

WSGI_APPLICATION = 't_and_b_website.wsgi.application'

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles')

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'staticfiles'),
]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

#MEDIA_ROOT is for directory for any media that our users upload
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media_cdn')
MEDIA_URL = '/media_cdn/'

CORS_URLS_REGEX = r'^/api.*'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
    '*',
    'your-domain.com',
    'your-bucket-here.s3-us-west-2.amazonaws.com',
)

AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME')

AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

Here is my wsgi.py
import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "t_and_b_website.settings")

application = get_wsgi_application()

In my Heroku logs gives me this warning, so I am not sure if its picking up my Heroku environment variables:
/app/.heroku/python/lib/python3.6/site-packages/environ/environ.py:630:
UserWarning: /app/src/t_and_b_website/.env doesn't exist -
if you're not configuring your environment separately, create one.

Thanks so much in advance!

A: Sorry guys - stupid mistake on my part. Turns out the problem was I gitignored my own staticfiles folder.


text:
Q: Add Text to jQuery slider I'd like to customise my Slider. It currently works like this: http://ryrych.github.com/rcarousel/examples/gotopage.html.
However, I was wondering, is it possible to associate a piece of text with each "slide".
So when you click the circle button to navigate, a new piece of text fades in (bottom left) and the old text fades out. Is this possible?
Many thanks for any pointers here.

A: I actually found a solution which works better: Malsup.

http://www.malsup.com/jquery/cycle2/demo/caption.php


text:
Q: Is there anyway to increase the size of an input.text element? I want to increase the size of the input box so when I email it it's actually usable for users to enter info, this is the best I could come up with but it's not changing size. I think it's not even possible?

{

    "type": "AdaptiveCard",
    "version": "1.0",
    "body": [
        {
            "type": "Container",
            "items": [
                {
                    "type": "Input.Text",
                    "id": "multilineInputId",
                    "placeholder": "enter comment",
                    "isMultiline": true,
                    "value": "EDITABLE TEXT",
                    "height":"auto"
                }
            ]
        }
    ],
    "actions": [
        {
            "type": "Action.Http",
            "title": "Click me!",
            "method": "POST",
            "url": "https://contoso.com/api/...",
            "body": "<body of the POST request>",
            "headers": [
                {
                    "name": "Content-Type",
                    "value": "application/json"
                }
            ]
        }
    ]
}

A: This was being worked on by the Adaptive Cards team, but I can't recall the exact timeline. See the Feb community call for more info: https://youtu.be/SEsjrFIf110
It's not clear if this will adjust the textboxes as well, or just the card size itself, but in either case, make sure you adaptive card itself is at least 1.2 (it's current version 1.0)


text:
Q: statfs /storage/sdcard0 failed, errno: 13 receiving this error in logcat with illegal argument exception
statfs /storage/sdcard0 failed, errno: 13
My code is
public double totalStorage() throws Exception {

        **stat = new StatFs(Environment.getExternalStorageDirectory().getPath());**
        return ((double) stat.getBlockSize()
                * (double) stat.getBlockCount());
    }

Please help

A: Errno 13 indicates  "permission denied", meaning that you have insufficient privileges.


text:
Q: Problems with environment variables Since the last time I updated my computer, my environment variables got screwed for some reason(the PATH variable didn't exist), and I set them back for java and maven. The tools that I currently use, and I have a problem with all other variables such as ping, rm,copy etc. How do I get these standard commands back?

A: According to Wikipedia and vlaurie.com, the default value is:
C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem
But that doesn't include modifications by third-party apps.


text:
Q: Google App Engine Python Authentication from API I'm currently building a Python webapp on the Google App Engine and I want to expose various parts of my application via a JSON API. This API may be used in the form of a mobile client, or (for the purposes of testing) a headless Python script.
I need to be able to authenticate users before they perform operations on the API. I notice that the Users API does not support simple authentication [in the form of authenticate(username, password)] so merely sending the username/password to a URL and then later using some given token would not work.
Ultimately, I would like the application to use Facebook Connect in addition to its own logins.
Could somebody please suggest how is the best way to authenticate users in this situation, using a remote JSON API and the Google App Engine?
Cheers

A: You might want to check out the recently released oauth support. Failing that, you can implement your own authentication, for example by using simple or digest authentication.

A: Just for the record, I ended up going with the wonderful Tipfy framework in the end.


text:
Q: How can i see how many times a specific customer has ordered in total? I am giving the full code of the program so you can see its concept. I am new to Python, and I am trying to learn
import uuid                #GET A RANDOM ID FOR THE CUSTOMER
from datetime import date  #GET CURRENT DATE
TodayDate= date.today()
place=-1
SpecificCustomerOrders=0
AfterOrder=True
TotalOrders=0
NameCustomerList=[]
AddressCustomerList=[]
CustomerIDList=[]

FirstEmployeeAccountUsername="coffee1"
FirstEmployeeAccountPassword="coffeeshop1"
SecondEmployeeAccountUsername="coffee2"
SecondEmployeeAccountPassword="coffeeshop2"
ThirdEmployeeAccountUsername="coffee3"
ThirdEmployeeAccountPassword="coffeeshop3"

print("Welcome to our coffee shop!")
print("Login")

#EMPLOYEE LOGIN PROCCESS STARTS
LoginEnter=True
while LoginEnter:
    username=input("Username: ")
    password=input("Password: ")
    if username==FirstEmployeeAccountUsername and password==FirstEmployeeAccountPassword or username==SecondEmployeeAccountUsername and password==SecondEmployeeAccountPassword or username==ThirdEmployeeAccountPassword and password==ThirdEmployeeAccountPassword:
        print("Login Successful")
        LoginEnter=False
    else:
        print("Invalid Login. Try again")
#EMPLOYEE LOGIN PROCCESS ENDS

#PROCCESS AFTER ORDER PLACEMENT STARTS

while AfterOrder:
    place+=1
    CustomerName=input("Customer's Name:")
    CustomerAddress=input("Customer's Address:")
    NameCustomerList.append(CustomerName)
    AddressCustomerList.append(CustomerAddress)

This is where I try to get how many times a specific customer has
ordered in total but I cant figure it out.

    if CustomerName==NameCustomerList[place] and CustomerAddress==AddressCustomerList[place]:
        SpecificCustomerOrders+=1
        if SpecificCustomerOrders==1:
            print("This customer has ordered",SpecificCustomerOrders," time")
        else:
            print("This customer has ordered",SpecificCustomerOrders," times")
        TotalOrders+=1
        CustomerID=uuid.uuid1()
        CustomerIDList.append(CustomerID)
        print("Current Date is:" , TodayDate)
        OrderPrice=input("Total amount of order:")

A: May I suggest a different approach
import uuid  # GET A RANDOM ID FOR THE CUSTOMER
from datetime import date  # GET CURRENT DATE

TodayDate = date.today()

Customers = {}

FirstEmployeeAccountUsername = "coffee1"
FirstEmployeeAccountPassword = "coffeeshop1"
SecondEmployeeAccountUsername = "coffee2"
SecondEmployeeAccountPassword = "coffeeshop2"
ThirdEmployeeAccountUsername = "coffee3"
ThirdEmployeeAccountPassword = "coffeeshop3"

print("Welcome to our coffee shop!")
print("Login")

# EMPLOYEE LOGIN PROCCESS STARTS
LoginEnter = True
while LoginEnter:
    username = input("Username: ")
    password = input("Password: ")
    if username == FirstEmployeeAccountUsername and password == FirstEmployeeAccountPassword or username == SecondEmployeeAccountUsername and password == SecondEmployeeAccountPassword or username == ThirdEmployeeAccountPassword and password == ThirdEmployeeAccountPassword:
        print("Login Successful")
        LoginEnter = False
    else:
        print("Invalid Login. Try again")
# EMPLOYEE LOGIN PROCCESS ENDS

# PROCCESS AFTER ORDER PLACEMENT STARTS

while True:
    CustomerName = input("Customer's Name:")
    CustomerAddress = input("Customer's Address:")

    if CustomerName in Customers:
        Customers[CustomerName]['Orders'] += 1
    else:
        Customers[CustomerName] = {}
        Customers[CustomerName]['Address'] = CustomerAddress
        Customers[CustomerName]['ID'] = uuid.uuid1()
        Customers[CustomerName]['Orders'] = 1

    print("This customer has ordered {} time(s)".format(Customers[CustomerName]['Orders']))

    print("Current Date is: {}".format(TodayDate))
    OrderPrice = input("Total amount of order:")


text: Q: I can't use fingerprint sensor in ubuntu 22.04 on yoga c940 I can't find fingerprint sensors settings in Ubuntu 22.04 installed on my lenovo yoga c940 . I've tried "settings > Users", but there is no fingerprint option there. Do I have to install separately or it is provided by Ubuntu 22.04?


text:
Q: Leetcode 413: Arithmetic slices Python Hi I'm trying to solve Leetcode 413: Arithmetic slices. I'm trying to start with a brute force recursive solution.
 def numberOfArithmeticSlices(self, nums: List[int]) -> int:
      def slices(nums: List[int], i: int):
          if (i < 2):
              return 0
          if nums[i] - nums[i-1] == nums[i-1] - nums[i-2]:
              return 1 + slices(nums, i -1)
          else:
              return slices(nums, i-1)
        if len(nums) < 3:
            return 0
        return slices(nums, len(nums)-1)

This doesn't work for the test case [1,2,3,4] (it returns 2 instead of 3). In my head I know it doesn't work because when the function is called, 1 + slices([1,2,3], 2) returns 2. How can I fix my code to get the arithmetic slice coming from the entire array [1,2,3,4]?

A: For solving this problem you have to take two steps.

*

*First you have to find all possible contiguous sub-arrays

*You have to check them, if they are arithmetic slices.
An understandable solution which is not memory and time efficient is as below:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
    if len(nums) <= 2:
        return 0
    sub_arrays = self.contiguous_subarray(nums)  # type List[List[int]]  all contiguous sub arrays with length 3 or more
    count = 0
    for subset in sub_arrays:
        count = count + self.is_arithmetic_subset(subset)
    return count

@staticmethod
def is_arithmetic_subset(subset):
    if len(subset) <= 2:
        return 0
    diff = subset[1] - subset[0]
    for i in range(2, len(subset)):
        if subset[i] - subset[i - 1] != diff:
            return 0
    return 1

@staticmethod
def contiguous_subarray(nums):
    return [nums[i:i + j] for i in range(0, len(nums)) for j in range(3, len(nums) - i + 1)]

But a solution that is little more harder to grasp but is memory and time efficient is as bellow(You could still replace the recursive call with a loop and I think you would get better results doing so):
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
    array_len = len(nums)
    if array_len <= 2:
        return 0
    count = self.numberOfArithmeticSlices(nums[:array_len - 1])
    diff = nums[array_len - 1] - nums[array_len - 2]
    for i in range(2, array_len):
        if nums[array_len - i ] - nums[array_len - i - 1] == diff:
            count += 1
        else:
            break
    return count


text:
Q: java code to execute commands I want to execute tabula tool commands,from within the java program. The code that I am trying is:
System.setProperty("user.dir", "C:\\Program Files");
String command ="\\tabula\\tabula-0.9.0-SNAPSHOT-jar-with-dependencies.jar "+"D:\\sample.pdf"+" -o "+"D:\\sampleeeee.csv";
Process p = Runtime.getRuntime().exec(command);

it is not working,any help would be appreciated.
this command need to be executed from java

A: You can specify the working directory when calling exec:
Path workingDir = Paths.get("C:\\Program Files\\tabula");

String[] command = {
    "tabula-0.9.0-SNAPSHOT-jar-with-dependencies.jar",
    "sample.pdf",
    "-o samk.csv"
};

Process p = Runtime.getRuntime().exec(command, null, workingDir.toFile());

A: Try this to set the working directory where the command will run.
https://stackoverflow.com/a/8405745/1364747
Process p = null;
ProcessBuilder pb = new ProcessBuilder("java","-jar","tabula-0.9.0-SNAPSHOT-jar-with-dependencies.jar", "D:\\sample.pdf", "-o", "D:\\sampleeeee.csv");
pb.directory("C:\\Program Files\\tabula");
p = pb.start();


text:
Q: Can I pass the viewbag value to the jQuery in mvc2 I need to pass the value to jQuery in the view using viewbag. What I want to achieve is pass the null or some value and then jQuery should hide or show the div depending on the value passed for instance something like below:
viewbag.testNumber = null;
 $('#showdiv').hide();
  $('viewbag.testNumber').value == someinteger{

    $("#showdiv").show();
    else
    $("#showdiv").hide();
});

 Some Calculation

Also I want to disable the viewbag in the view if the value is null , because it gives null error

A: If you are using MVC3 (Doesn't work with 2) you can easily use ViewBag as below, but remember two points that are easy to forget and can cause headache:

*

*Never put semicolon at the end of @ViewBag.myVariable

*If you are passing string put " before and after your @ViewBag.myVariable. For example:

This is right:
$(function () {
    var path = "@ViewBag.helpPath"
    path = "@Url.Content("~/route/action/")" + path;
    $('#help-content').load(path);

});

However if you use:
$(function () {
    var path = @ViewBag.helpPath
    path = "@Url.Content("~/route/action/")" + path;
    $('#help-content').load(path);

});

MVC changes this to:
$(function () {
    var path = c:\\doc\\path
    path = "@Url.Content("~/route/action/")" + path;
    $('#help-content').load(path);

});

Which JavaScript cannot parse it, and the result would be some ugly bug. Just something I did and wasted my time thought to share it.

A: ViewBag is only in ASP.NET MVC 3 so you can't use that, but you can use ViewData:
    $('#showdiv').hide();
      if ($("#" + '<%=ViewData["testNumber"]').value == someinteger){
         $("#showdiv").show();
       }
        else {
            $("#showdiv").hide();
        }
    });

 Some Calculation

A: in razor you'd just do @ViewBag.Variable_Name . I do it in my code.

A: You could do that in your View:
$('#showdiv').hide();
  $('@Viewbag.testNumber').value == someinteger{

    $("#showdiv").show();
    else
    $("#showdiv").hide();
});

 Some Calculation

A: For your MVC2 JavaScript just write the variable straight out, obviously you cant use ViewBag so:
var testNumber = <%:ViewData["VariableName"]%>;


text:
Q: Passing setState hooks as props in React, using typescript I have an error: Expected 0 arguments, but got 1 from typescript for the following code:
child component:
onChange={(e) => {
                            setBrandSelectionObjectState((prev) => {
                                const newObj = {};
                                Object.keys(prev).forEach((keyTypeId) => {
                                    newObj[keyTypeId] = e.target.checked;
                                });
                                return newObj;
                            });
                        }}

The error is concerning the setBrandSelectionObjectState() function. I'm guessing the 1 argument that the error is referring to is the (prev).
I'm receiving the above setBrandSelectionObjectState() into my child component as follows:
child component:
interface SelectGarmentTypesParams {
    setTeeTypeSelectionObjectState: Dispatch<SetStateAction<SelectionObjectBooleans>>;
}

export function SelectGarmentTypes({
    setTeeTypeSelectionObjectState,
}: SelectGarmentTypesParams): JSX.Element {
...

I am passing the setBrandSelectionObjectState() function from a parent component:
parent component:

export interface NewTeeTypesObject {
    newteetypes_id: number;
    manufacturer: string;
    description: string;
    availablecolors: string[];
    imageurls: string[];
    availablecountries: string[];
    notavailablecountries: string[];
    garmenttype: string;
    yearsavailable: number[];
    materials: { [key: string]: number }[] | null;
    weight: number;
}

const [brandSelectionObjectState, setBrandSelectionObjectState] = useState<SelectionObjectBooleans>(...)

But I'm unsure where in my code I've gone wrong or what to change?


text:
Q: How to locate a value based on another value within the same key? Python & JSON I'm a new programmer and whilst I've searched for similar questions, I may need some direct help on this problem of mine.
I have a data structure which is being returned in Python from an API I'm interacting with.
The data structure is like this:

{
  "account": "asdljasdjflallasjadsfkjlaasfd",
  "amount": [
    {
      "unit": "1019238741092834",
      "quantity": "1"
    },
    {
      "unit": "4893024890324830",
      "quantity": "2"
    },
    {
      "unit": "8374928483847485",
      "quantity": "3"
    },
    {
      "unit": "6574820387498457",
      "quantity": "4"
    }
  ],
  "subaccount": null,
  "type": "normal",
  "discrepancy": false
}

Is anyone able to tell me how to store the value "3" from "quantity": if all I know is "unit": "4893024890324830" which corresponds to it?
At the moment, I'm using json_object = json.loads(response.txt) and I can print and store values using json_object['amount'][1]['unit'] but that presumes I know the key/order of where the quantity I want is located within.
The above is just a snippet, I have a large list including 1000 entries.
Thank you very much for your support in advance. First time using StackOverflow.
Cheers.

A: If you know the unit value for e.g. "4893024890324830", then you can loop through the amount array and find the corresponding quantity using the unit value. Like this:
def storeQuanity(myval):
    for val in data["amount"]:
        if(val["unit"]==myval):
            print(val["quantity"])
storeQuanity("6574820387498457")


text:
Q: how to create dynamic test case in pytest (python) lets say i have a dataframe which is returning from a module after certain computation
module name is cmpt.py
def main():
    # performing certain computation and returning a dataframe
    return df_cmpt

the df_cmpt contain data as below
edate,id,cap_p,cap_i,dump_p,dump_i,flag_ap
2021-03-01,101,0.124233,0.124226,0.899764,0.899264,1
2021-03-01,102,0.423322,0.423352,0.353543,0.353443,0
2021-03-01,103,0.233234,0.233234,0.747447,0.747247,1
2021-03-01,104,0.534223,0.534323,0.722727,0.722727,0
2021-03-02,104,0.124233,0.124226,0.899764,0.899264,1
2021-03-02,105,0.423322,0.423352,0.353543,0.353443,0
2021-03-02,102,0.233234,0.233234,0.747447,0.747247,1
2021-03-02,107,0.534223,0.534323,0.722727,0.722727,0
2021-03-03,401,0.124233,0.124226,0.899764,0.899264,1
2021-03-03,402,0.423322,0.423352,0.353543,0.353443,0
2021-03-03,503,0.233234,0.233234,0.747447,0.747247,1
2021-03-03,404,0.534223,0.534323,0.722727,0.722727,0
2021-03-04,131,0.124233,0.124226,0.899764,0.899264,1
2021-03-04,142,0.423322,0.423352,0.353543,0.353443,0
2021-03-04,113,0.233234,0.233234,0.747447,0.747247,1
2021-03-04,144,0.534223,0.534323,0.722727,0.722727,0

now i am calling this module in test_cmpt.py
import numpy as np
from compt import main as ownmain

df_cmpt = ownmain()

currently i am segregating  data as below
df_cmpt_2021-03-01_ap = df_cmpt[(df_cmpt['edate']=='2021-03-01') & (df_cmpt['flag_ap']==1)]
df_cmpt_2021-03-01_non_ap = df_cmpt[(df_cmpt['edate']=='2021-03-01') & (df_cmpt['flag_ap']==0)]
df_cmpt_2021-03-02_ap = df_cmpt[(df_cmpt['edate']=='2021-03-02') & (df_cmpt['flag_ap']==1)]
df_cmpt_2021-03-02_non_ap = df_cmpt[(df_cmpt['edate']=='2021-03-02') & (df_cmpt['flag_ap']==0)]
df_cmpt_2021-03-03_ap = df_cmpt[(df_cmpt['edate']=='2021-03-03') & (df_cmpt['flag_ap']==1)]
df_cmpt_2021-03-03_non_ap = df_cmpt[(df_cmpt['edate']=='2021-03-03') & (df_cmpt['flag_ap']==0)]
df_cmpt_2021-03-04_ap = df_cmpt[(df_cmpt['edate']=='2021-03-04') & (df_cmpt['flag_ap']==1)]
df_cmpt_2021-03-04_non_ap = df_cmpt[(df_cmpt['edate']=='2021-03-04') & (df_cmpt['flag_ap']==0)]

then creating the manual test cases
def test_cap_2021-03-01_ap():
    np.testing.assert_array_almost_equal(df_cmpt_2021-03-01_ap['cap_p'], df_cmpt_2021-03-01_ap['cap_i'], decimal=3, err_msg='', verbose=True)

def test_cap_2021-03-01_ap():
    np.testing.assert_array_almost_equal(df_cmpt_2021-03-01_ap['dump_p'], df_cmpt_2021-03-01_ap['dump_i'], decimal=3, err_msg='', verbose=True)

def test_cap_2021-03-01_non_ap():
    np.testing.assert_array_almost_equal(df_cmpt_2021-03-01_non_ap['cap_p'], df_cmpt_2021-03-01_non_ap['cap_i'], decimal=3, err_msg='', verbose=True)

def test_cap_2021-03-01_non_ap():
    np.testing.assert_array_almost_equal(df_cmpt_2021-03-01_non_ap['dump_p'], df_cmpt_2021-03-01_non_ap['dump_i'], decimal=3, err_msg='', verbose=True)

def test_cap_2021-03-02_ap():
    np.testing.assert_array_almost_equal(df_cmpt_2021-03-02_ap['cap_p'], df_cmpt_2021-03-02_ap['cap_i'], decimal=3, err_msg='', verbose=True)

def test_cap_2021-03-02_ap():
    np.testing.assert_array_almost_equal(df_cmpt_2021-03-02_ap['dump_p'], df_cmpt_2021-03-02_ap['dump_i'], decimal=3, err_msg='', verbose=True)

def test_cap_2021-03-02_non_ap():
    np.testing.assert_array_almost_equal(df_cmpt_2021-03-02_non_ap['cap_p'], df_cmpt_2021-03-02_non_ap['cap_i'], decimal=3, err_msg='', verbose=True)

def test_cap_2021-03-02_non_ap():
    np.testing.assert_array_almost_equal(df_cmpt_2021-03-01_non_ap['dump_p'], df_cmpt_2021-03-02_non_ap['dump_i'], decimal=3, err_msg='', verbose=True)

and so on for other dates..
now i am running pytest from consol using command py.test -v -s --html=test_report.html capture= fd
which is generating html report of above test cases
now what i needed, instead of manually drafting the test case i can creating them dynamically by using loops
ls_date = df_cmpt['edate'].unique()
ls_measure = ['cap','dump']
ls_flag = ['ap','non_ap']

for date in ls_date:
    for measure in ls_measure:
        for flag in ls_flag:
            def 'test_'+measure+'_'+date+'_'+flag():
                 np.testing.assert_array_almost_equal(df_cmpt_+'date'+'_'+is_flag['cap_p'], df_cmpt_+'date'+'_'+is_flag['cap_i'], decimal=3, err_msg='', verbose=True)

i know this implementation is wrong but i want something like this so that i could save my manual effort of creating test case for larger dataset


text:
Q: Power divider coefficients I'm new to power dividers component and I'm facing some doubts.
I should simulate a power divider in ADS of which I can consult the datasheet.
In ADS the power divider has the following parameters:

In the datasheet of the power divider only the insertion loss (the additional loss after the splitting) and the return loss plots are available. Is it possible from this only 2 parameters (insertion loss and return loss) to derive $$S_{21} S_{31}$$ and the isolation? Or should the coefficients be a standard value since the energy should be equally distributed between the power divider inputs, e.g. 0.707 (3 dB)?
Thanks in advance


text:
Q: Do Kubernetes persistent volume claims bind again if the persistent volume is being deleted and recreated? I have the following pvc (Persistent Volume Claim):
piVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: test-claim-web
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi

and the Google Cloud-backed pv (Persistent Volume):
apiVersion: v1
kind: PersistentVolume
metadata:
  name: test-pv-1
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  gcePersistentDisk:
    pdName: test-1
    fsType: ext4

and the Disk in Google cloud that exists.
If I create first the pv and after the pvc, kubectl get pvc,pv will show:
NAME                                STATUS                                VOLUME            CAPACITY     ACCESSMODES              AGE
test-claim-web                      Bound                                 test-pv-1         10Gi         RWO                      15s
NAME                                CAPACITY                              ACCESSMODES       STATUS       CLAIM                    REASON    AGE
test-pv-1                           10Gi                                  RWO               Bound        default/test-claim-web             25s

But if I delete and recreate the pv, kubectl get pvc,pv will show:
NAME                                STATUS                                VOLUME            CAPACITY     ACCESSMODES              AGE
test-claim-web                      Bound                                 test-pv-1         10Gi         RWO                      3m
NAME                                CAPACITY                              ACCESSMODES       STATUS       CLAIM                    REASON    AGE
test-pv-1                           10Gi                                  RWO               Available                                       18s

*

*Why is the pvc still Bound?

*Doesn't the pvc (re-)bind automatically? (I also observed that creating the pv after the pvc makes the pvc wait forever with Pending status.)

I use the following Kubernetes version:
Client Version: version.Info{Major:"1", Minor:"2", GitVersion:"v1.2.4", GitCommit:"3eed1e3be6848b877ff80a93da3785d9034d0a4f", GitTreeState:"clean"}
Server Version: version.Info{Major:"1", Minor:"2", GitVersion:"v1.2.4", GitCommit:"3eed1e3be6848b877ff80a93da3785d9034d0a4f", GitTreeState:"clean"}

A:
if I delete and recreate the pv, kubectl get pvc,pv will show [bound].
  Why is the pvc still Bound?

That's bug in Kubernetes 1.2, it will be fixed in 1.3. Both PV and PVC should get Bound eventually.
However, deleting a bound PV is very bad idea, as the PVC may be used in a running pod and the pod suddenly looses storage underneath. You should never touch bound PVs!

I also observed that creating the pv after the pvc makes the pvc wait forever with Pending status

It won't wait forever, it should get bound after 10 minutes. Use kube-controller-manager --pvclaimbinder-sync-period=15s to shorten it to 15 seconds. Again, this will be better in Kubernetes 1.3, 15 seconds will be default there.


text:
Q: trouble reading structure from stream, or bytes rather I'm trying to read a LAS File 1.3 Header from a file.
In every single header that I've seen, The first thing i expect to read is the Format Signature which is always "LASF".
When i try and read the file, All I'm seeing is 'ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ'
I know the header size is 227, I tried to even just read a length of 227 straight from the file but i still don't read what I'm supposed to. I hope this makes sense.
this is what i've tried:
typedef struct Header
{
    char File_Signature[4];
    USHORT SourceID;
    USHORT Reserved1;
    UINT GUID1;
    USHORT GUID2;
    USHORT GUID3;
    char GUID4[8];
    BYTE VersionMajor;
    BYTE VersionMinor;
    char SystemID[32];
    char GeneratingSoftware[32];
    USHORT DOY;
    USHORT YEAR;
    USHORT HeaderSize;
    UINT PointOffset;

    INT NumberOfVariableLengthRecords;
    BYTE PointDataFormatID;
    USHORT PointDataRecordLength;
    INT NumberOfPointRecords;
    UINT NumberofPointsByReturn1;
    UINT NumberofPointsByReturn2;
    UINT NumberofPointsByReturn3;
    UINT NumberofPointsByReturn4;
    UINT NumberofPointsByReturn5;

    double XScaleFactor;
    double YScaleFactor;
    double ZScaleFactor;
    double Xoffset;
    double Yoffset;
    double Zoffset;
    double MaxX;
    double MinX;
    double MaxY;
    double MinY;
    double MaxZ;
    double MinZ;
} LasHeader;

void OpenLasFile()
{

    //THIS DOES NOT WORK
    char buffer[227];
    ifstream myFile ("C:\atlass\area_cov.las");
    myFile.read (buffer, 227);

    //NOT WORK, TRIED THIS TOO
    ifstream input_file("C:\atlass\area_cov.las", ios::binary);
    LasHeader header;

    input_file.read((char*)&header, sizeof(header));
    input_file.close();

    //ALL DATA OUTPUT'ed ARE 'ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ'
}

This is a block of binary from the file I'm trying to read.
4C4153460000000001000000020003003132333435363738010241746C6173732041746C6173436F72652020202020202020202020202020202041746C6173436F726520202020202020202020202020202020202020202020201E01DC07E300E300000000000000011C0014012F0014012F0000000000000000000000000000000000FCA9F1D24D62503FFCA9F1D24D62503FFCA9F1D24D62503F00000000B05320410000000024FF53410000000000000000E7B3FA8388A920411B5611E9BC1B20417710D27C2711544114A5EC807EF45341C520B072685D684037894160E5D012C021BE92FF06661701A9600000D803C902E2000100AC7136BDE325044137

My question is: Why am i Reading garbage values, what have i done wrong?
-------------------- UPDATE --------------------------
I tested this and it worked, So it must be a problem reading the file, can anyone help?
what worked was:
unsigned char rawData[552] =
{
    0x4C, 0x41, 0x53, 0x46, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x03, 0x00,
    0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x01, 0x02, 0x41, 0x74, 0x6C, 0x61, 0x73, 0x73,
    0x20, 0x41, 0x74, 0x6C, 0x61, 0x73, 0x43, 0x6F, 0x72, 0x65, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
    0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x41, 0x74, 0x6C, 0x61, 0x73, 0x43,
    0x6F, 0x72, 0x65, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
    0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x1E, 0x01, 0xDC, 0x07, 0xE3, 0x00,
    0xE3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x1C, 0x00, 0x14, 0x01, 0x2F, 0x00, 0x14,
    0x01, 0x2F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0xFC, 0xA9, 0xF1, 0xD2, 0x4D, 0x62, 0x50, 0x3F, 0xFC, 0xA9, 0xF1, 0xD2, 0x4D,
    0x62, 0x50, 0x3F, 0xFC, 0xA9, 0xF1, 0xD2, 0x4D, 0x62, 0x50, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xB0,
    0x53, 0x20, 0x41, 0x00, 0x00, 0x00, 0x00, 0x24, 0xFF, 0x53, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0xE7, 0xB3, 0xFA, 0x83, 0x88, 0xA9, 0x20, 0x41, 0x1B, 0x56, 0x11, 0xE9, 0xBC,
    0x1B, 0x20, 0x41, 0x77, 0x10, 0xD2, 0x7C, 0x27, 0x11, 0x54, 0x41, 0x14, 0xA5, 0xEC, 0x80, 0x7E,
    0xF4, 0x53, 0x41, 0xC5, 0x20, 0xB0, 0x72, 0x68, 0x5D, 0x68, 0x40, 0x37, 0x89, 0x41, 0x60, 0xE5,
    0xD0, 0x12, 0xC0, 0x21, 0xBE, 0x92, 0xFF, 0x06, 0x66, 0x17, 0x01, 0xA9, 0x60, 0x00, 0x00, 0xD8,
    0x03, 0xC9, 0x02, 0xE2, 0x00, 0x01, 0x00, 0xAC, 0x71, 0x36, 0xBD, 0xE3, 0x25, 0x04, 0x41, 0x37,
    0xB9, 0x92, 0xFF, 0x77, 0x58, 0x17, 0x01, 0xD7, 0x60, 0x00, 0x00, 0xE2, 0x0A, 0xC9, 0x02, 0xE2,
    0x00, 0x01, 0x00, 0x4B, 0x90, 0x11, 0x90, 0xE3, 0x25, 0x04, 0x41, 0x00, 0xBF, 0x92, 0xFF, 0x98,
    0x3A, 0x17, 0x01, 0x2B, 0x62, 0x00, 0x00, 0x23, 0x0A, 0x49, 0x02, 0xE4, 0x00, 0x01, 0x00, 0xBF,
    0xF5, 0x61, 0xBD, 0xE3, 0x25, 0x04, 0x41, 0x1A, 0xBD, 0x92, 0xFF, 0x30, 0x11, 0x17, 0x01, 0xE4,
    0x62, 0x00, 0x00, 0xDF, 0x08, 0x49, 0x02, 0xE4, 0x00, 0x01, 0x00, 0xF8, 0x6E, 0xF3, 0xA6, 0xE3,
    0x25, 0x04, 0x41, 0x01, 0xBE, 0x92, 0xFF, 0x67, 0xE7, 0x16, 0x01, 0x83, 0x63, 0x00, 0x00, 0xCB,
    0x06, 0x49, 0x02, 0xE5, 0x00, 0x01, 0x00, 0x0B, 0xF3, 0x1E, 0xA7, 0xE3, 0x25, 0x04, 0x41, 0xF2,
    0xBB, 0x92, 0xFF, 0x99, 0xD9, 0x16, 0x01, 0x6D, 0x63, 0x00, 0x00, 0x03, 0x09, 0x49, 0x02, 0xE5,
    0x00, 0x01, 0x00, 0x82, 0x1C, 0x94, 0x90, 0xE3, 0x25, 0x04, 0x41, 0xFA, 0xBE, 0x92, 0xFF, 0x98,
    0xBE, 0x16, 0x01, 0x13, 0x63, 0x00, 0x00, 0xFF, 0x08, 0x49, 0x02, 0xE5, 0x00, 0x01, 0x00, 0xE5,
    0xF0, 0x49, 0xA7, 0xE3, 0x25, 0x04, 0x41, 0xEE, 0xBC, 0x92, 0xFF, 0xDE, 0xB0, 0x16, 0x01, 0x04,
    0x63, 0x00, 0x00, 0x8E, 0x0B, 0x49, 0x02, 0xE5, 0x00, 0x01, 0x00, 0x95, 0xA0, 0xBF, 0x90, 0xE3,
    0x25, 0x04, 0x41, 0xD2, 0xBD, 0x92, 0xFF, 0x19, 0x88, 0x16, 0x01, 0xA9, 0x63, 0x00, 0x00, 0xD1,
    0x08, 0x49, 0x02, 0xE7, 0x00, 0x01, 0x00, 0xA7, 0x24, 0xEB, 0x90, 0xE3, 0x25, 0x04, 0x41, 0xA8,
    0xBE, 0x92, 0xFF, 0x29, 0x64, 0x16, 0x01, 0x97, 0x63, 0x00, 0x00, 0xFD, 0x04, 0x49, 0x02, 0xE7,
    0x00, 0x01, 0x00, 0xC4, 0xF0, 0x11, 0x91, 0xE3, 0x25, 0x04, 0x41, 0x79, 0xD0, 0x92, 0xFF, 0xD0,
    0x70, 0x17, 0x01, 0x30, 0x61, 0x00, 0x00, 0x60, 0x02, 0xC9, 0x02, 0xE2, 0x00, 0x01, 0x00, 0x91,
    0x65, 0xC1, 0x44, 0xE4, 0x25, 0x04, 0x41, 0x12, 0xC7, 0x92, 0xFF, 0x02, 0x5E, 0x17, 0x01, 0x79,
    0x61, 0x00, 0x00, 0x79, 0x05, 0xC9, 0x02, 0xE2,
} ;

LasHeader test;

memcpy(&test, rawData, sizeof(test));

A: The issue is here:
    ifstream myFile ("C:\atlass\area_cov.las");

Backslash is a special character in C strings that forms escape sequences. In this particular case, \a is replaced by a bell character (0x0B), so it is trying to open the wrong path and failing.
Instead, you need to escape all the backslashes that occur in the path by doubling them:
    ifstream myFile ("C:\\atlass\\area_cov.las");


text:
Q: Using contractions correctly in Grammar like the word "weren't" when asking a question Are the two example questions correct or is there a rule that applies when using and not using contraction words?

*

*"weren't you able to log into your online account?"

*"were not you able to log into your online account?"

A: In speech, the contraction would be the everyday version. The full version would be used for emphasis of the negative, and stressed to match...
It would also move... 'were not you' just doesn't work.
"Weren't you able to log into your online account?" is light & colloquial. The contraction placing were & not together is acceptable & commonplace.
"Were not you able to log into your online account?" is grammatically incorrect.
"Were  you not able to log into your online account?" would be the more formal expression, though in speech emphasises the inability - perhaps with an element of disbelief that something so apparently simple could not be achieved.
The same rules would apply to couldn't/could not.

A: Although -n't was originally a clitic, a reduced form of not, in Present-Day English it has become an inflectional suffix that attaches to auxiliary verbs.  In other words, the negative auxiliary weren't is a single word, and it undergoes subject–auxiliary inversion like any other auxiliary:

1a. You weren't able to log into your online account.
  1b. Weren't you able to log into your online account?

In example 1a the main clause is declarative.  In example 1b, the subject you is inverted with the negative auxiliary weren't, marking the main clause as interrogative.
If you start with an uncontracted example, not doesn't move; it's a separate word and not part of the auxiliary:

2a. You were not able to log into your online account.
  2b. Were you not able to log into your online account?

Again, in example 2a the main clause is declarative.  In example 2b, the subject you is inverted with the auxiliary were, marking the main clause as interrogative.
Not cannot move with were:

3. *Were not you able to log into your online account? (ungrammatical)

This example is ungrammatical in Present-Day English, but it's a common mistake among English language learners.
Note that if the subject noun phrase is particularly "heavy" (lengthy or syntactically complex), it can be moved to the right of its basic position, reuniting the auxiliary and negator after inversion, but that doesn't apply in your example, as the subject you is not particularly heavy.


text:
Q: Wordpress define('COOKIE_DOMAIN',false) implications I have a Wordpress multisite which uses two different domains e.g:

*

*www.test.com - primary site

*www.example.com

In order to get the login to work on the non primary site I have had to add the following line in my wp-config.php file
define('COOKIE_DOMAIN',false);

This allows any of the WordPress Domains to set the Cookie and in turn allows a user to login on the secondary site. My question is what are the security implications to effectively wildcarding the Cookie domain?


text:
Q: How much does the moon change in diameter as the gravity of the planets and sun act on it? What is the maximum distortion of the moon? Is it measured in centimetres  or metres or kilometres?

A: The Moon has a "tidal bulge" of about 50 cm due to the Earth's gravity.  This was measured in 2014 via data from the Lunar Reconnaissance Orbiter.

[T]here is enough force to raise a bulge about 20 inches (51 centimeters) high on the near side of the moon and similar one on the far side.  The position of the bulge actually shifts a few inches over time. Although the same side of the moon constantly faces Earth, because of the tilt and shape of the moon's orbit, the side facing Earth appears to wobble. From the moon's viewpoint, Earth doesn't sit motionless but moves around within a small patch of sky. The bulge responds to Earth's movements like a dance partner, following wherever the lead goes.

For more information, see Marazico et al., "Detection of the lunar body tide by the Lunar Orbiter Laser Altimeter", Geophysical Research Letters 41 (7), 2282-2288 (2014).
The tidal effects from any other body in the solar system would be much smaller, since they fall off proportionally to the cube of the distance.   The tidal effects of the Sun on the Moon are about 0.6% the size of the Earth's effects on the Moon, and everything else in the solar system would have even less of an effect.


text:
Q: Как поменять значение QCombobox который создается в итерации без имени в QTableWidget по нажатию кнопки в другом окне, зная номер строки, где менялся У меня создается по нажатию кнопки в итерации строки в таблице QTableWidget и в этих строках так же создается QCombobox со значениями «Продано» и «В наличии».
При выборе пользователем в любом QCombobox значения «В наличии», появляется окно, и я пытаюсь, когда пользователь в окне нажал «Ок», то значение в QCombobox возвращалось обратно в «Продано».
Я знаю, как установить значение, если при создании QCombobox указать явное имя экземпляру класса (QCombobox.setCurentIndex()).
Но, я не понимаю, как обратится QCombobox который создается в итерации без явного указания имени, в QTableWidget.
Вот мой код. В методе show_message() по нажатию кнопки я хочу вернуть значение QCombobox обратно в "Продано".
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, \
QVBoxLayout, QMessageBox

class MyWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__()
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        self.row_count = 1
        self.table_index = 0

        self.tableWidget = QtWidgets.QTableWidget()
        self.tableWidget.setRowCount(0)
        self.tableWidget.setColumnCount(2)

        self.button = QtWidgets.QPushButton('Добавить строки таблицы')
        self.button_1 = QtWidgets.QPushButton('Вывести значение ячейки')

        self.layout = QVBoxLayout(self.centralWidget)
        self.layout.addWidget(self.tableWidget)
        self.layout.addWidget(self.button)

        self.button.clicked.connect(self.add_cells)

    def add_cells(self):
        row = self.tableWidget.rowCount()

        self.tableWidget.setRowCount(self.row_count)
        self.tableWidget.setItem(self.table_index, 0, QtWidgets.QTableWidgetItem(f'Nokia {self.table_index}'))

        combobox = QtWidgets.QComboBox()
        combobox.addItem('Продано')
        combobox.addItem('В наличии')

        combobox.currentTextChanged.connect(lambda text, row=row: self.show_message(text, row))

        self.tableWidget.setCellWidget(self.table_index, 1, combobox)
        self.row_count += 1
        self.table_index += 1

    def show_message(self, text, row): # всплывающее окно который принимает текст кнопки, и номер строки и выводит в сообщение
        if text == 'В наличии':
            msg = QMessageBox()
            msg.setInformativeText(f'Вернуть значение в строке {row} обратно?')
            msg.exec_()

if __name__ == '__main__':
  app = QApplication(sys.argv)
  w = MyWindow()
  w.show()
  sys.exit(app.exec_())

A: Я увидел вашу задачу так:
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, \
    QVBoxLayout, QMessageBox

class MyWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__()
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        self.row_count = 1
        self.table_index = 0

        self.tableWidget = QtWidgets.QTableWidget()
        self.tableWidget.setRowCount(0)
        self.tableWidget.setColumnCount(2)

        self.button = QtWidgets.QPushButton('Добавить строки таблицы')
        self.button_1 = QtWidgets.QPushButton('Вывести значение ячейки')

        self.layout = QVBoxLayout(self.centralWidget)
        self.layout.addWidget(self.tableWidget)
        self.layout.addWidget(self.button)

        self.button.clicked.connect(self.add_cells)

    def add_cells(self):
        row = self.tableWidget.rowCount()
        self.tableWidget.setRowCount(self.row_count)
        self.tableWidget.setItem(
            self.table_index,
            0,
            QtWidgets.QTableWidgetItem(f'Nokia {self.table_index}')
        )

        combobox = QtWidgets.QComboBox()
        combobox.addItem('В наличии:')                            # +++
        combobox.addItem(f'Nokia_{self.table_index}_1')           # +++
        combobox.addItem(f'Nokia_{self.table_index}_2')           # +++
        combobox.addItem(f'Nokia_{self.table_index}_3')           # +++

        combobox.currentTextChanged.connect(
            lambda text, row=row, cb=combobox: self.show_message(text, row, cb))
# +++                             ^^^^^^^^^^^                               ^^
        self.tableWidget.setCellWidget(self.table_index, 1, combobox)
        self.row_count += 1
        self.table_index += 1

    # всплывающее окно который принимает текст кнопки, номер строки
    # и cb выводит в сообщение
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
# +++                                 vv
    def show_message(self, text, row, cb):
        if text != 'В наличии:' and text != 'Продано':               # +++
            msg = QMessageBox()
            msg.setInformativeText(f'Вы хотите купить {text} ?')     # +++
            msg.addButton(QMessageBox.Yes)                           # +++
            msg.addButton(QMessageBox.No)                            # +++
            bttn = msg.exec_()                                    # +++ bttn

            if bttn != QMessageBox.Yes:
                return

            row = cb.model().rowCount()
            for i in range(cb.model().rowCount()):
                t = cb.model().item(i, 0).text()
                if t == text:
                    cb.model().item(i, 0).setText('Продано')
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

if __name__ == '__main__':
  app = QApplication(sys.argv)
  w = MyWindow()
  w.show()
  sys.exit(app.exec_())


text:
Q: CakePHP Helper Auto-Completion in Netbeans 6.8 Can anyone please tell me how I can "enable" CakePHP's Helper auto-completion in CakePHP? Essentially so when, for instance, I type $form-> it gives me a list of $form's methods and variables.
I have read http://bakery.cakephp.org/articles/view/model-based-code-insight-and-completion-in-netbeans and also tried to implement comment #3. When I try that it still fails to auto complete in either a Controller or View.
Do any Netbeans & CakePHP users out there have any tips, tricks, or hacks that can get this working? Thanks!

A: You can enable almost full support for CakePHP in NetBeans 6.8 just try this http://www.tiplite.com/cakephp-support-in-netbeans/

A: In Netbeans 6.8 there is a confirmed bug that makes the "comment #3"-method not working.
http://netbeans.org/bugzilla/show_bug.cgi?id=180239
It seems to be resolved in version 6.9. Haven't confirmed it myself, though.


text:
Q: Display selected filters in a text box in cognos Can someone please explain how can I display selected filters in a text box in Cognos ? I am preparing this report in cognos report studio

A: // , Use the following function call:
ParamDisplayValue(?paramname?)

From the documentation:

ParamDisplayValue
  Returns a string that is the parameter display value
  of "parameterName". This function appears in the Recruitment Report
  sample report in the GO Data Warehouse (analysis) package.
Syntax
  ParamDisplayValue ('parameterName')

Reference:
https://ots.iit.edu/sites/ots/files/elements/training-and-consulting/pdfs/Cognos%20Report%20Studio%20user%20guide.pdf
http://www.howtocognos.com/show-prompt-value-report


text:
Q: jQuery event affecting only this instance of the element I have more than one element with the same class name, ideally they will be seven, so, on pageload they will be hidden and then I want to show the extra text when clicking on the anchor, but only for that very instance of the div, my jQuery code is currently removing hidden in all instances of the div, I am guessing the solution would be to add this somewhere. Thanks!

$(".show-more").click(function() {
  return $(".extra-text").toggleClass("hidden");
});
.hidden {
  display: none;
}

Text

More text

  Show more..

Text

More text

  Show more..

A: You need to traverse the DOM to find the .extra-text element related to the one which raised the event.
To do this you can use the this keyword which will refer to the element that raised the click event. Try this:
$(".show-more").click(function() {
    $(this).closest('div').find(".extra-text").toggleClass("hidden");
});

A: Use .prev() in this context.
$(".show-more").click(function(e) {
   e.preventDefault();
   $(this).prev().toggleClass("hidden");
});

Fiddle

A: .extra-text is sibling to .show-more, so u can use siblings() method to get adjacent sibling element

$(".show-more").click(function() {
  $(this).siblings(".extra-text").toggleClass("hidden");
});
.hidden {
  display: none;
}

Text

More text

  Show more..

Text

More text

  Show more..


text:
Q: C# Date (server) => Json date/time (browser) => C# date/time with time portion (server) issue Context information: PST timezone, Asp.net Mvc legacy app with WebApi 2.x that uses json.net for serializing/deserialization to json, Chrome/FF browsers. The app is configured with:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Unspecified;

A tester reported an issue related to this date: 1977-04-15. Here is the flow:

*

*C# 1977-04-15 => Serialized to json as "1977-04-15T00:00:00" due to the use of Unspecified.

*In the browser (in the PST timezone) this is parsed as:

var dt = new Date("1977-04-15T00:00:00")
dt
Output: Date Fri Apr 15 1977 00:00:00 GMT-0800 (Pacific Standard Time)

*

*Serialized back to the C# WebApi service:

JSON.stringify(dt);
Output: "\"1977-04-15T08:00:00.000Z\""

*

*Back in the C# world this becomes (I used linqpad):

Console.WriteLine(DateTime.Parse("1977-04-15T08:00:00.000Z"));
Output: 1977-04-15 01:00:00

It seems that C# used a different offset than the browser for the PST timezone at that date. I tested it in FF & Chrome. Is this normal?
What would be the best way to fix this?
One way would to configure the DateTimeZoneHandling to Newtonsoft.Json.DateTimeZoneHandling.Local but I am reluctant to do this on the existing app.
If I use local I have:
c#:
var date = new DateTime(1977, 04, 15); //, 0, 0, 0, DateTimeKind.Local);

JsonSerializerSettings settings = new JsonSerializerSettings
{
  DateTimeZoneHandling = DateTimeZoneHandling.Local
};
Console.WriteLine(JsonConvert.SerializeObject(date, settings));
Ouput: "1977-04-15T00:00:00-07:00"

In the Javascript land:
"1977-04-15T00:00:00-07:00"
dt
Output: Date Thu Apr 14 1977 23:00:00 GMT-0800 (Pacific Standard Time)
JSON.stringify(dt)
Output: "\"1977-04-15T07:00:00.000Z\""

Back in the C# land:
Console.WriteLine(DateTime.Parse("1977-04-15T07:00:00.000Z"));
Output:1977-04-15 00:00:00

This seems to work, the dates match.
Update:
After more testing we have in C# (linqpad):

var date = new DateTime(1977, 04, 03, 0, 0, 0, DateTimeKind.Local);
date.ToLongDateString().Dump();
date.ToUniversalTime().Dump();
date = new DateTime(1977, 04, 04, 0, 0, 0, DateTimeKind.Local);
date.ToLongDateString().Dump();
date.ToUniversalTime().Dump();
Output:
Sunday, April 03, 1977
1977-04-03 08:00:00
Monday, April 04, 1977
1977-04-04 07:00:00

While in JavaScript (FF) we have:
var dt = new Date(1977, 3, 24);
dt.toGMTString()
var dt = new Date(1977, 3, 25);
dt.toGMTString()
Output:
"Sun, 24 Apr 1977 08:00:00 GMT"
"Mon, 25 Apr 1977 07:00:00 GMT"

There seems to be a discrepancy in the DST time tables.
I was curios about the Java world, so I ran this in scala:
scala> ZonedDateTime.of(1977, 4, 24, 0, 0, 0, 0, ZoneId.of(ZoneId.SHORT_IDS.get("PST")))
res8: java.time.ZonedDateTime = 1977-04-24T00:00-08:00[America/Los_Angeles]

scala> ZonedDateTime.of(1977, 4, 25, 0, 0, 0, 0, ZoneId.of(ZoneId.SHORT_IDS.get("PST")))
res9: java.time.ZonedDateTime = 1977-04-25T00:00-07:00[America/Los_Angeles]

It looks like C# is wrong. I have tested on a Windows 7 VM with .Net framework 4.8 (528049).
Update 2:
This is getting interesting. I tested F# on MacOs with .net core sdk 2.1.
    let mutable dt = System.DateTime(1977, 04, 24, 0, 0, 0, System.DateTimeKind.Local)
    printfn "%s" (dt.ToLongDateString())
    printfn "%A" (dt.ToUniversalTime())
    let dt = System.DateTime(1977, 04, 25, 0, 0, 0, System.DateTimeKind.Local)
    printfn "%s" (dt.ToLongDateString())
    printfn "%A" (dt.ToUniversalTime())
Output:
Sunday, April 24, 1977
4/24/77 8:00:00 AM
Monday, April 25, 1977
4/25/77 7:00:00 AM

Note the DST offset change.

A: <rant>I have found using DateTime for dates frustrating</rant>
One way to deal with your issue is to extract the .Date (EDIT: or new Date(orig.Year, orig.Month, orig.Day)) part at some point to loose the time part.

Edit: re: comments:
This is a hack that could help. Ultimately each element of the pipeline needs to work correctly.
I find that the best way is to use either a string ("yyyy-MM-dd") or ints for the 3 parts.