text:
Q: Pass Table Value from View to Controller MVC Can I pass table td values to controller?
View strongly typed:
@using (Html.BeginForm("PostClick", "Vendor", FormMethod.Post)) {

      @Html.DisplayNameFor(model => model.First().SubmittedDate)

      @Html.DisplayNameFor(model => model.First().StartDate)

      @Html.DisplayFor(modelItem => item.SubmittedDate)

      @Html.DisplayFor(modelItem => item.StartDate)

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

Contoller code:
public void PostClick(FormCollection collection)
{
   /*Some Code */
}

How to pass table value from view to controller?
Have used JasonData & Ajax call and able to send the table data to controller.
Want to know any other method can be done because FormCollection data not able to find table values

A: Your need to generate controls that post back (input, textarea or select) and generate those controls in a for loop (or use a custom EditorTemplate for type Vendor)
View
@model List<Vendor>
@using (Html.BeginForm())
{

      ....

      for(int i = 0; i < Model.Count; i++)
      {

          @Html.TextBoxFor(m => m[i].SubmittedDate)
          @Html.TextBoxFor(m => m[i].StartDate)

      }

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

Post method
public void PostClick(List<Vendor> model)
{
  /*Some Code */
}


text:
Q: help with jquery jQuery.validator.addMethod http://jsfiddle.net/nBuut/
I am trying to validate the amount fields if only the question above has a value of "yes". Say, you pick yes for question 1, it will ask for a valid number as an amount for question number1.
However, if I select no for the rest of the questions, the form won't submit because it's still asking for valid amounts for question number 2 thru number 5.
Is there a way to do this?
thanks in advance.

A: you need to define the dependency for the input field to the dropdown.
Instead of hardcoding answerYesNoText_1 to true
answerYesNoText_1: { required:true, amtGreaterThanZero:true  }

You would need something with dependancy check (Not tested code) -
answerYesNoText_1: { required: function(element) {
    if ( $('#answerYesNo_1').val() == 'Yes' ) {
        return true;
    }
  }
}

This would check the amount field only if the dropdown is marked to yes
More @ http://docs.jquery.com/Plugins/Validation/Methods/required

A: This works:
  answerYesNo_1: { required:true } ,

  answerYesNoText_1: { required: function(element) {
             return $('#answerYesNo_1').val() == 'yes';
  }, number: true },

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can html5 be used front end for an ftp server? quick question to day. I've done a little digging around on the net and i can't really find a very definitive answer.
Basically, I run my own server on a redundant dual core, 4gb ram 2Tb pc (server1)
And on here, i would like to make an FTP partition. Reason being, i would very much like to be able to transfer files back and forth work, uni and home as i please.
I also run a website from my server which allows me to stream media from my hard drive to any laptop, tablet, desktop, iphone, android.. you name it!
I would LIKE to be able to add a section on my website where by I can log in and access my files as a sort of HTMF5 Front end.
I am aware and know how to create a login with a database which has md5 hash and store cookies to stop un-authorised people accessing my ftp.
Any help or a shove in the right direction would be much appreciated! Thanks in advance :D

A: Yes it's possible. but that won't be HTML5 ftp server etc that you mentioned.
You can achieve this by installing a web server on your machine like apache and then make directories public - run Apache on some port and you will be able to access the directory. if your server is running on port 8080, URL will be like: domain.com:8080 - You can style directory using this simple script & make this password protected as well using .htaccess .

osFileManager
The other option is to use some php script. Many commercial scripts are available and as well as open source. i recommend you trying osFileManager - it has a lot of features like:

*

*Browse the directory structure

*Create files

*Upload files

*Rename files

*Move files

*Delete files

*Edit files

*Change permissions

*Change password

*Create users

Here is it's installation instructions: http://www.osfilemanager.com/osfilemanager-docs.html
or a paid HTML5 & AJAX based script can be bought for 14$ from here:
http://codecanyon.net/item/file-manager-and-backup-system/5177206


text:
Q: How to join a dictionary with same key as df index as a new column with values from the dictionary I have the following data:
A dictionary dict with a key: value structure as tuple(str, str,): list[float]
{
    ('A', 'B'): [0, 1, 2, 3],
    ('A', 'C'): [4, 5, 6, 7],
    ('A', 'D'): [8, 9, 10, 11],
    ('B', 'A'): [12, 13, 14, 15]
}

And a pandas dataframe df with an index of 2 columns that correspond to the keys in the dictionary:
df.set_index("first", "second"]).sort_index()
print(df.head(4))
==============================================
                                        tokens
first           second
 A              B                          166
                C                          128
                D                          160
 B              A                          475

I want to create a new column, numbers in df with the values provided from dict, whose key corresponds with an index row in df. The example result would be:
print(df.head(4))
========================================================================
                                        tokens          numbers
first           second
 A              B                          166          [0, 1, 2, 3]
                C                          128          [4, 5, 6, 7]
                D                          160          [8, 9, 10, 11]
 B              A                          475          [12, 13, 14, 15]

What is the best way to go about this? Keep performance in mind, as this dataframe may be 10-100k rows long

A: You can create a series from the dict, and then assign:
df['numbers'] = pd.Series(d)

Or map the index:
df['numbers'] = df.index.map(d)

Output:
              tokens           numbers
first second
A     B          166      [0, 1, 2, 3]
      C          128      [4, 5, 6, 7]
      D          160    [8, 9, 10, 11]
B     A          475  [12, 13, 14, 15]

A: Create a Series then concatenate it with dataframe:
sr = pd.Series(d, name='numbers')
out = pd.concat([df, sr], axis=1)
print(out)

# Output
     tokens           numbers
A B     166      [0, 1, 2, 3]
  C     128      [4, 5, 6, 7]
  D     160    [8, 9, 10, 11]
B A     475  [12, 13, 14, 15]


text:
Q: Is there a whereis command equivalent on PASE? The whereis command lets me find the location of a command that is on my path on linux, amongst other things. Is there an equivalent on PASE? If so, do I need a PTF?

A: According to the PASE command list, which should be available. It should do almost the same thing as whereis.
$ which ls
/bin/ls


text:
Q: JAVAFX Table View Wrapped Text Font Color private TableColumn<FundedResearch, String> makeStringColumnRes(String columnName, String propertyName, int prefWidth) {
    TableColumn<FundedResearch, String> column = new TableColumn<>(columnName);
    column.setCellValueFactory(new PropertyValueFactory<FundedResearch, String>(propertyName));
    column.setCellFactory(new Callback<TableColumn<FundedResearch, String>, TableCell<FundedResearch, String>>() {
      @Override public TableCell<FundedResearch, String> call(TableColumn<FundedResearch, String> soCalledFriendStringTableColumn) {
        return new TableCell<FundedResearch, String>() {
            private Text text;
          @Override public void updateItem(String item, boolean empty) {

            super.updateItem(item, empty);
            if (item != null) {

                text=new Text(item.toString());
                text.setWrappingWidth(column.getWidth());
                text.setStyle("-fx-font-color:#FFFFFF");
                column.setStyle("-fx-font-color:#FFFFFF");
                this.setWrapText(true);
                setGraphic(text);
                setStyle("-fx-font-color:#FFFFFF");
            }
          }
        };
      }
    });
    if(prefWidth!=0){
    column.setPrefWidth(prefWidth);
    column.setMaxWidth(prefWidth);
    column.setMinWidth(prefWidth);
    }

    return column;
  }

i have this method that is called to make table column.  i have wrapped the String to Cell to make all text visible. the problem is i cant make the font color white. Share your ideas . Thank you. :) those styles set inside the if statement is what i have tried so far. Thanks

A: The CSS property to use is not -fx-font-color:
If should be -fx-fill. You can find this information here: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html#shape (Navigate from Text to the first superclass that supports color, in this case Shape).
Also you need to handle the case when there's no item apropriately. Otherwise the text will still be displayed when the cell is empty. Furthermore it's not necessary to recreate the Text objects every time the item changes:
column.setCellFactory(new Callback<TableColumn<FundedResearch, String>, TableCell<FundedResearch, String>>() {
    @Override
    public TableCell<FundedResearch, String> call(TableColumn<FundedResearch, String> soCalledFriendStringTableColumn) {
        return new TableCell<FundedResearch, String>() {
            private Text text = new Text();

            {
                text.setStyle("-fx-fill: white;");
                text.wrappingWidthProperty().bind(this.widthProperty());
            }

            @Override
            public void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);

                if (empty || item == null) {
                    setGraphic(null);
                } else {
                    text.setText(item);
                    setGraphic(text);
                }
            }
        };
    }
});

A: this one also works fine.
text.setFill(Color.WHITE);

just got it last few hours ago


text:
Q: MapReduce with 2 values Is it possible to have two values in MapReduce?
My csv looks like this:
month,  date,  deviceCategory, totalTransactionRevenue
201608 20160801  Desktop        1000
201608 20160801  Mobile         700

I want to use MapReduce to calculate each kind of device's average revenue per month. I want the output be looks like this:
 (month, deskRev, mobileRev)

But when I code context.write(month, DesktopoutPut, MobileoutPut);in Mapper, it says cannot be applied to given types. Is it because MapReduce must in key-value pair?
Thanks!!

A: Well, according to your needs you can concatenate the month and deviceCategory.
Hence you can use this as a key (this actually forms a composite key).
This key and corresponding value will look like
<201608 Desktop , 1000>
<201608 Mobile , 700>
It requires absolute no change in your program except one line to concatenate the two fields.


text:
Q: Planned obsolescence / failure of consumer electronics / kill switch General question for those who have worked in the consumer electronics industry:
Are small rechargeable devices (like bluetooth audio devices specifically) designed to fail after a set time to force customer replacement? Is there for instance a mechanism that disables charging once the battery has totally failed or after a certain length of time?
I have heard of AC power supplies having lower-rating capacitors or something that will decrease component life and cause earlier failure.
I've experienced this perhaps 3 times:
Somewhat older electronics:

*

*Motorola HT820 stereo bluetooth headphones - model 1 failed after about 2 years. Lights up on connecting charger but will not charge or power on after being on charger.

*Motorola HT820 stereo bluetooth headphones - probably different hardware revision - Failed in same fashion after about 1 year.

Recent electronics

*

*Bose QC35 bluetooth noise cancelling headphones - $350 - Failed after 1.5 years. No lights on connecting charger. Will not charge - Details: Battery was definitely almost at end of life. Disassembled to find the lipo battery inside it. Accidentally poked battery releasing a very small spark. Used it next day until battery depleted. Tried to connect charger after that, no lights, no charge. What the heck? Battery might have been failed/dead completely at that point (0 charge due to short I created?).

On the other hand, I had a lipo based Palm Centro that lasted many many years before it started to display random glitches probably caused by hardware. It lasted clear from 2008 (new model) to about 2014-15?
I've had a lenovo thinkpad T430 that has been running great since 2011, used daily, but not transported all that much (which I think greatly increases mechanical wear on the circuits). I am only now replacing it because it can't run newer games.
So TL;DR: Do consumer electronics have actual kill circuits that make the device fail when the battery really dies or some other timeframe that makes the customer replace?

A: I've worked on countless consumer products, and I've never seen a "kill" circuit that intentionally causes the product to fail after some specified period or event.
However, consumer products are designed for a certain lifetime, with a certain number of failures in that lifetime being acceptable.  That's just a reality of the reliability of components.
The manufacturer has to balance lifetime and reliability with cost, product size, time to market and other factors.  If the product is too expensive or big compared to the competition, no one will buy it.  If it fails to early and provides a bad customer experience no one will buy the next one.
So in general manufacturers try to make a product as reliable as possible while meeting all the other product constraints.  What you hear about or remember is the time the product failed right after the warranty (or battery or whatever) expired.  The hundreds of products you have had that didn't do that don't get any "press".
If a battery is not replaceable even by the manufacturer then it may not make economic sense to make the product reliable enough to outlast the battery by a wide margin.

A: You cannot just replace the battery, you also have to reset the charge counter chip.
If you want to reach maximum charge over cycles, you should never charge a LiPo battery to more than 90% and never discharge it to less than 10% of the capacity. This measurement accuracy cannot be reached by checking the unloaded voltage of the battery pack, you have to count the charge going in and out the battery.
The downside is you have to reset the chip when you replace the battery. It may seem simple, but as you don't know how much charge is initially inside the new battery when you replace it, what's the value you should set?
If the battery is dead, the charge counter chip is set to a safe value – full – because an overcharged LiPo will catch fire pretty certainly.


text:
Q: Using an 8-way splitter, extract 1/12-th of something I have a pile of dirt. And I have an 8 way splitter.
I can split into 8 and recombine splits as many times as I wish.

What is the easiest run of splitting/combining I can do to pull out exactly 1/12th of the dirt?

A: (Not entirely serious, but too long for a comment.)
There is no solution in the strict sense, as noted in the comments already, since any legal split or recombine leaves piles which are fractions having denominators that are powers of $2\,$. Therefore, it is not possible to isolate a pile of size $1/12$ in finitely many steps.
However, assuming one has enough time and patience to work through infinitely many steps, consider that division by $4$ is available as a split-by-$8$ followed by a recombine-$2\,$. Then, first split the whole pile by $4\,$, and set $1/4$ aside. Further split one of the remaining $1/4$ piles by $4$ and add it to the $1/4$ pile previously set aside. Repeat infinitely many times (or until the atoms of dirt no longer split ;-)), then the pile which collected all the intermediate splits will have a size of:
$$
\frac{1}{4}+\left(\frac{1}{4}\right)^2+\left(\frac{1}{4}\right)^3 + \cdots \;=\; \frac{1}{4} \cdot \frac{1}{1-\cfrac{1}{4}} \;=\; \frac{1}{3}
$$
Finally, divide that pile once more by $4$ to get $\;\displaystyle \frac{1}{4} \cdot \frac{1}{3} = \frac{1}{12}\,$.

A: As noted in the comments, this is not possible in a finite number of steps. However, you can approximate $1/12$ with arbitrary accuracy using $1/8$ divisions. To see how, let's write the fraction $1/12$ in its base-$8$ expansion:
$$\left(\frac1{12}\right)_8=0.0525252...$$
Thus, you can divide your original quantity into $\frac18$'s, divide one of those $\frac18$'s into $\frac1{8^2}$'s, and start with $5$ of those. To get closer, divide a remaining $\frac1{8^2}$ into $\frac1{8^3}$'s, and take $2$ of those. Continue until you're close enough!

A: A classic move used in Factorio: take the output of two of the split belts and feed it back into the input, until the splitter runs "clean" (this is a thing that handles dirt though, so, uh, good luck).  At this point you're as close to $1/6$ in each pile as you can get.  Move the splitter, feed one of the little piles in, and four of the outputs together gives 1/12.

A: Not sure if this is the quickest, but was the most obvious to me.

*

*Pound the splitter down:  you now have 8 piles of 1/8.

*Combine three piles, then pound the splitter down. (this gives you 24s, seems like we're getting somewhere!)  Repeat this with another 3 piles.  You now have 16 piles of 1/24 and 2 piles of 1/8.

*Combine the two piles of 1/8, with 3 piles of 1/24.  Pound the splitter down on that. You now have 24 piles of 1/24.

*Combine two piles of 1/24 and you have your 1/12th.

*Eat the dirt, for extra credit.  ;-)


text:
Q: How do I populate array of twilio fax results and send via express? I am trying to get results from the twilio api like so: twilio => our secured api backend => our client app We are doing this to project our api-keys and other security based purposes.
We have sending faxes down, and also checking for single instances. I am however having a hard time getting the list of faxes we get sent back to our client app after it completes. Mainly due to the fact that it's a repeating call. This is what we have so far for this problem:
app.post('/fax', function (req, res) {
  const faxList = [];
  const getFax = client.fax.faxes.each((faxes) => {
    faxList.push(faxes);
    console.log(faxList);
  });

Right now when I run this I see the array populated one by one just like it should, but can't seem to return the final result after it completes.
From my searches online it looks like I need to utilize Promise.all to send my completed res.status(200).json(faxList); so express can send the list of faxes to our app. I'm having issues setting up the promise.all as the faxList variable is just empty. Almost as if the push done to the array doesn't last once the call completes.
Does this have something to do with the way that twilio has their fax api function set up? https://github.com/twilio/twilio-node/blob/master/lib/rest/fax/v1/fax.js or would this me not understanding how promise.all functions?
I'm newer to the node side of javascript. I have more experience with other languages so I apologize in advance.

A: I would try to get the whole list , if you have less than a page worth of faxes . (I think a page in Twilio is 50 )
like so
return new Promise((resolve) => {
    client.faxes.list().then(function(faxes){
                        if (!empty(faxes)){
                           resolve(faxes);
                        }
                       });
});


text:
Q: Plain text version of emails does not contain any links I just signed up, a day or two ago, and I've received a notification that there's something in my inbox.  Unfortunately, my email client isn't able to show me a link to my Inbox, or the message, because of the format of the email.
I normally use the email address that I gave when I signed up, just with MailWasher, which is intended to safely preview emails, as plain text, to decide whether or not to open them in a normal HTML email client.
I would be nice if that email contained a link to my inbox, which could be shown in MailWasher.  In order to collect that email in a normal email client, I'd also have to collect or delete all the other emails sent to that address.
I'm not entirely clear what's been done in that email to stop MailWasher seeing the link.  I can see a link to leave feedback, and one to unsubscribe, but not one to check my inbox.
Sure, I can live without one, but those emails would be a lot more useful to me if I could just click a link to go to my Inbox.

A: We've added written out links to the "Unread Email messages" and "Moderator Message" Plaintext emails, so that people at least know where to go.
Formatting in Plaintext emails still has some issues, those should be addressed sometime next year (since right now we're generating them from the HTML Version, and we're in the process of retooling our email system).


text:
Q: reading a file but whenever I get the Key Pair Value...unable to get rid of the quotations I'm creating a dictionary from this data set file but every time I read from the file.
for example - sample file with r extension (test.r)
#######################TEST###########################
#### 1. Test
key1 = '2022-01-01'    #random comment
key2 = 123L
key3 = 'Hello World'

# COMMAND --------

The value for the dictionary for key1 is always "'2022-01-01'" how do I get the dictionary to only be '2022-01-01'. I tried replacing the double quotes and it didn't work. This is the working code I have so far.
with open(path, 'r') as reader:
line = reader.readlines()

for text in line:
    if not text.startswith('#') and not text.startswith('\n'):
        print(text)
        result = strip_comments(text)
        print(result)
        value = result[1].strip().split()[0]
        print(value=='2022-01-01')
        break

function to do initial parsing
def strip_comments(line):
    result = line.split(' = ')
    return result

A: You already have the answer in your question: strip the inner quotation marks.
value = result[1].strip().split()[0].strip("'")


text:
Q: Array - vector multiplication in R I need a simple matrix-algebra or Kronicker product type operation to multiply an array and a vector in R to get to a specific result. Let's say I have the array:
ar<-array(c(rep(1,9),rep(10,9),rep(100,9)),dim=c(3,3,3))

And the vector c(1,2,3). Multiplying both by * multiplies each row on each slide of the array by 1,2, and 3 respectively. However, I need an operation to get to array
ar2<-array(c(rep(1,9),rep(20,9),rep(300,9)),dim=c(3,3,3))

instead. That is, is there a simple operation that would allow me to transform ar to ar2 using the vector I specified above? Thanks!

A: ar * rep(1:3, each=9) should work...
For an arbitrary sized array and an arbitrary set of multipliers, you know the dimensions of your array and the axis along which you want to perform your elementwise multiplication (in this case, the z axis):
each_arg <- prod(dim(ar)[1:2])
multipliers <- sample(1:10, 3)
ar2 <- ar * rep(multipliers, each=each_arg)

You can also look at the tensorA package


text:
Q: sudo via cron'ed ssh works in RHEL6 but not in RHE7 (/dev/tty: No such device or address) I give up:
I have a cronjob script that Ive been running for years (out of a RHEL 6.7 machine) to remote into other RHEL machines via ssh.  Works flawlessly against RHEL5 and 6 but fails against RHEL7.  At its simplest form the script breaks down like this:
ssh -tttvi /home/robot/.ssh/passwdlesskey  robot@${ThatIP} sudo -l

Across all remote machines (RHEL6 & 7), the respective sudoers file contains
Defaults    requiretty

As expected, the script executes well from commandline against RHEL7.  Again, from cron it works against RHEL 5 & 6 but fails against 7:
debug1: read_passphrase: can't open /dev/tty: No such device or address
Host key verification failed.

One peculiar thing to note is the difference in the SSH outputs when running commandline vs cron against a RHEL7 server
              C  R  O  N                                                                 C O M M A N D L I N E
------------------------------------------------------------------------+------------------------------------------------------------------------
debug1: skipped DNS lookup for numerical hostname                       | debug1: skipped DNS lookup for numerical hostname
WARNING: ECDSA key found for host 10.96.16.108                          | debug1: Host '10.96.16.108' is known and matches the ECDSA host key.
in /home/robot/.ssh/known_hosts:416                                     | debug1: Found key in /home/robot/.ssh/known_hosts:416
ECDSA key fingerprint ee:67:90:d3:c3:b8:db:c7:d3:6a:68:6a:78:fd:25:da.  | debug1: SSH2_MSG_NEWKEYS sent
+--[ECDSA  256]---+                                                     | debug1: expecting SSH2_MSG_NEWKEYS
|                 |                                                     | debug1: SSH2_MSG_NEWKEYS received
|                 |                                                     | debug1: Roaming not allowed by server
|                 |                                                     | debug1: SSH2_MSG_SERVICE_REQUEST sent
|                 |                                                     | debug1: SSH2_MSG_SERVICE_ACCEPT received
|        S=       |                                                     | debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
|       .= +      |                                                     | debug1: Next authentication method: publickey
|       ..= +...  |                                                     | debug1: Offering DSA public key: /home/robot/.ssh/passwdlesskey
|      ..+.*o=o.  |                                                     | debug1: Server accepts key: pkalg ssh-dss blen 433
|       o+*o+Eo   |                                                     | debug1: Authentication succeeded (publickey).
+-----------------+                                                     | Authenticated to 10.96.16.108 ([10.96.16.108]:22).
                                                                        | debug1: channel 0: new [client-session]
debug1: read_passphrase: can't open /dev/tty: No such device or address | debug1: Entering interactive session.
Host key verification failed.                                           | debug1: Sending command: sudo -l
------------------------------------------------------------------------+------------------------------------------------------------------------

One theory I had: similar to the way scp/sftp does not like interactive shell output, I figured the randomart displayed by the RHEL7 server is interfering with my script.  But even replacing ssh -v with -q does not help.
sshd's LogLevel is DEBUG2
Mar  9 10:51:01 rhel7test sshd[26198]: debug1: Forked child 26209.
Mar  9 10:51:01 rhel7test sshd[26209]: Set /proc/self/oom_score_adj to 0
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: rexec start in 5 out 5 newsock 5 pipe 7 sock 8
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: inetd sockets after dupping: 3, 3
Mar  9 10:51:01 rhel7test sshd[26209]: Connection from 10.96.16.148 port 55171 on 10.96.16.108 port 22
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: Client protocol version 2.0; client software version OpenSSH_5.3
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: match: OpenSSH_5.3 pat OpenSSH_5* compat 0x0c000000
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: Enabling compatibility mode for protocol 2.0
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: Local version string SSH-2.0-OpenSSH_6.6.1
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: fd 3 setting O_NONBLOCK
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: Network child is on pid 26210
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: SELinux support enabled [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: permanently_set_uid: 74/74 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: list_hostkey_types: ssh-rsa,ecdsa-sha2-nistp256,ssh-ed25519 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: SSH2_MSG_KEXINIT sent [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: SSH2_MSG_KEXINIT received [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: ssh-rsa,ecdsa-sha2-nistp256,ssh-ed25519 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: hmac-md5-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-sha1,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: hmac-md5-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-sha1,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: none,zlib@openssh.com [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: none,zlib@openssh.com [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit:  [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit:  [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: first_kex_follows 0  [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: reserved 0  [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-dss-cert-v00@openssh.com,ssh-rsa,ssh-dss [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit:  [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit:  [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: first_kex_follows 0  [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_parse_kexinit: reserved 0  [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: mac_setup: setup hmac-md5 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: kex: client->server aes128-ctr hmac-md5 none [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: mac_setup: setup hmac-md5 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: kex: server->client aes128-ctr hmac-md5 none [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: kex: diffie-hellman-group-exchange-sha256 need=16 dh_need=16 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: kex: diffie-hellman-group-exchange-sha256 need=16 dh_need=16 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: SSH2_MSG_KEX_DH_GEX_REQUEST received [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: monitor_read: 0 used once, disabling now
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: SSH2_MSG_KEX_DH_GEX_GROUP sent [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: bits set: 504/1024 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: expecting SSH2_MSG_KEX_DH_GEX_INIT [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: bits set: 532/1024 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: monitor_read: 6 used once, disabling now
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: SSH2_MSG_KEX_DH_GEX_REPLY sent [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: kex_derive_keys [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug2: set_newkeys: mode 1 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: SSH2_MSG_NEWKEYS sent [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: expecting SSH2_MSG_NEWKEYS [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: Connection closed by 10.96.16.148 [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: do_cleanup [preauth]
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: monitor_read_log: child log fd closed
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: do_cleanup
Mar  9 10:51:01 rhel7test sshd[26209]: debug1: Killing privsep child 26210

Reading similar posts, Ive already

*

*checked the permissions on /dev/tty

*made sure the password-less keys are correct

*made sure there's no conflicting entries in known_hosts file

*checked environment variables for anything strange

*kicked up debugging to level 3 on executing side (-vvv) with no new information to glean from the output.

Finally, because Im sure it will be asked, the sshd_config of RHEL6 & 7
         R H E L 7                                                                 R H E L 6
--------------------------------------------------------------------------------+---------------------------------------------------------------------
HostKey                         /etc/ssh/ssh_host_rsa_key                       |
HostKey                         /etc/ssh/ssh_host_ecdsa_key                     |
HostKey                         /etc/ssh/ssh_host_ed25519_key                   |
SyslogFacility                  AUTHPRIV                                        | AUTHPRIV
LogLevel                        DEBUG2                                          |
PermitRootLogin                 no                                              | no
StrictModes                     yes                                             |
MaxAuthTries                    3                                               |
MaxSessions                     10                                              |
PubkeyAuthentication            yes                                             |
AuthorizedKeysFile              .ssh/authorized_keys                            |
IgnoreRhosts                    yes                                             |
PermitEmptyPasswords            no                                              |
PasswordAuthentication          yes                                             | yes
ChallengeResponseAuthentication no                                              | no
GSSAPIAuthentication            yes                                             | yes
GSSAPICleanupCredentials        no                                              | yes
UsePAM                          yes                                             | yes
X11Forwarding                   yes                                             | yes
PrintMotd                       no                                              |
PrintLastLog                    no                                              |
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES   | LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT               | LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE                                     | LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS                                                            | XMODIFIERS
Subsystem               sftp  /usr/libexec/openssh/sftp-server                  | sftp  /usr/libexec/openssh/sftp-server

So Im at a loss as to what the cause of the problem is.

A: It is not sudo asking for TTY, but the ssh client, which needs from you to do the only security thing about ssh, that you have to do before establishing secure connection. It is verification of hostkey, that requires manual input from user, if it is not configured in advance. It is not related to the system version, but to the configuration.
You need to store the servers host key (public part) to the client's known_hosts. There are several possibilities how to do that:

*

*As the user (robot) who is running the cron (sudo -i -u robot), try to connect to the remote server:
ssh -i /home/robot/.ssh/passwdlesskey  robot@${ThatIP}

and manual write "yes" to the prompt

*Use ssh-keyscan tool, which does exactly the same thing, but does not have to run interactive (make sure if you run it as different user, that the target user will have correct access to that file):
ssh-keyscan {ThatIP} >> /home/robot/.ssh/known_hosts

A: As user VDR commented I need to add
-o StrictHostKeyChecking=no

as an additional option when calling ssh through cron.

A: Same scenario--I updated the target system from CentOS 6 to CentOS 7, and suddenly my cron job would get Host key validation failed errors, but if I ran it from command line, it would be fine. I was totally unaware of the ssh-keyscan tool, so thanks to @Jakuje for writing about that. In my case, running the ssh-keyscan tool output absolutely nothing, so I added -v, and got:
>ssh-keyscan -v hostname.example.com
debug1: match: OpenSSH_6.6.1 pat OpenSSH*
debug1: hostname.example.com doesn't support ssh1

Eish. Looks like SSH on the source machine doesn't support SSH2. So the I looked into the version of ssh on the source system:
>sudo yum list installed | grep ssh
openssh.x86_64                           4.3p2-82.el5                  installed
openssh-askpass.x86_64                   4.3p2-82.el5                  installed
openssh-clients.x86_64                   4.3p2-82.el5                  installed
openssh-server.x86_64                    4.3p2-82.el5                  installed

Nice. Only several years behind there. This post  http://www.jbytechnologies.com/linux/sshd-add-dsa-key.html helped me dig deeper to note that CentOS 7 disables DSA keys. Solution? Generate and enable the DSA key on CentOS 7. But, DSA keys are weaker than RSA, so that would be unhardening my new server.
Optimal solution in my case: upgrade openssh on the source machine.


text:
Q: How to get a link from a website Button in Android Java Basically what I want is. There is a button on a website that leads to a link, the link that the button leads to changes frequently, how do I get the latest link from that button that is on a website, from Android Studio. Also, I don't own that website

A: You can use Jsoup, it runs on Java 7 and up, Kotlin and Android.
follow instruction in this parse html, it show how to fetch a page from a URL; extract links, images, and other pointers; and examine their URLs and text.
You will be able to get the link each time he changed by getting to parent div of this block of html code and search the href link for example...
Good luck.


text:
Q: Analyzing Iterative Algorithms : basic operations, number of basic operations executed and class O(...) algorithms belongs to? Can someone please explain to me clearly how to answer this questions i've been straggling to understand it ?
The Question says:
Let X and Y be two arrays of n numbers. The Algorithms below calculate various expressions on the arrays. Analyze the time complexity of each algorithm and find :
i) What are the algorithm's basic operations ?
ii) How many times  are the basic operations executed ?
iii) what is the class O(..) the algorithm belongs to ?
X+Y

ALGORITHM addArrays(X[0..n-1],Y[0..n-1)

//Input: Two arrays X and Y of n numbers

//Output: Array S= X +Y

For i <--0 to n-1 do

           S[i] <-- X[u] + Y[i]
Output S[0 . . n-1]

A: i ) Adds the two input arrays and returns the sum array (S). That's the line inside the loop that adds each input array's entry on each iteration of the loop.
ii) n times as you only call upon the addition operation n times..
iii) O(n) because you're only going through n elements in total (2n accesses but that's O(n)).


text:
Q: Разделить целое число на константу с сохранением дробной части Нужно разделить целое беззнаковое число, например 12, на константу 65535 и записать как uint32. При этом сохранить дробную часть. Тип float не поддерживается процессором.
Какие есть варианты? Например до чего, я додумался - сдвинуть число на 16 позиций влево и разделить на 65535. Так вообще делается или есть другие способы?

A: Д'елите, берёте остаток , и умножаете насколько надо.
# include <stdlib.h>
# include <stdint.h>
# include <stdio.h>

int main  ( ) {
  uint32_t  a = 123456U  ;
  uint32_t  b = 789U ;
  printf  ("a = %u , b = %u\n",(unsigned int)a,(unsigned int)b);
  div_t r = div ( a , b ) ;
  printf  ("div = %u , rem = %u\n",(unsigned int)r.quot,(unsigned int)r.rem);
  printf  ("result = %u.%u\n",(unsigned int)r.quot,(unsigned int)((r.rem * 10) / b));
  }

;
> gcc -Wall -Wpedantic -std=c99 divrem.c
> ./a.out
a = 123456 , b = 789
div = 156 , rem = 372
result = 156.4


text: Q: Adaptive widgets python kivy The problem is that in my program there are widgets of different sizes on different devices, I know that the problem is in absolute sizes, but how can I write the adaptability of widgets?


text:
Q: Whatsapp Business API Developer not working I was tring to configure and setup the developer environment of a single instance of the WhatsApp Business API.I had finished #Step 5 https://developers.facebook.com/docs/whatsapp/installation/dev-single-instance#step-5--verify-containers-are-running and the docker is running.
enter image description here
Whenever I try to call https://localhost:9090 in browser but the error is  "This site can't be reached".
then i used the command docker-compose logs,the error is MySQL is not up yet - sleeping and getaddrinfo for host "db" port 3306: Name or service not known
enter image description here
Here is db.env code
WA_DB_ENGINE=MYSQL
WA_DB_HOSTNAME=db
WA_DB_PORT=3306
WA_DB_USERNAME=root
WA_DB_PASSWORD=testpass
WA_DB_CONNECTION_IDLE_TIMEOUT=180000

So anyone have idea please, thanks a lot.

A: In db name you must put the address that the docker container will have.
run command
iptables -L -n

db.env file
WA_DB_ENGINE=MYSQL
WA_DB_HOSTNAME=172.17.0.2
WA_DB_PORT=3306
WA_DB_USERNAME=userName
WA_DB_PASSWORD=Pass123
WA_DB_CONNECTION_IDLE_TIMEOUT=180000

docker-compose.yml file
environment:
     MYSQL_ROOT_PASSWORD: Pass123
     MYSQL_USER: userName
     MYSQL_PASSWORD: Pass123

A: System is not able to resolve "db" to your mysql container.
Use the name of the mysql container in WA_DB_HOSTNAME.
Alternatively, point "db" to the correct mysql container by making /etc/hosts entry.


text:
Q: Push and Pop in a single button in windows application Currently I am working in a windows application,and the requirement is I have a button so when first time i click, it need to be behave like it is pushed and when next time i will click the same button it need to be behave like pop.

A: You can create a global boolean variable that will change on Button click. Every time when button click event fires, just check for the boolean status. And the same button can work as ON/OFF mode.
Private isStarted As Boolean = False

Private Sub OnStartButtonClick(sender As System.Object, e As System.EventArgs) Handles btnStart.Click
    If (isStarted = False) Then
        isStarted = True
        btnStart.Text = "Stop"

        'DO YOUR WORK'
    Else
        isStarted = False
        btnStart.Text = "Start"

        'DO YOUR WORK'
    End If
End Sub

A: You can do it by adding condition in the same button click.
private void button1_Click(object sender, EventArgs e)
{
    if (button1.Text == "Push")
    {
        button1.Text = "Pop";
        MessageBox.Show("Data Pushed into the stack");
    }
    else
    {
        button1.Text = "Push";
        MessageBox.Show("Data Popedfrom the stack");
    }
}

Initially make button1.Text as "Push", When it is clicked, do your Push operation and change the name to "Pop",
When the button1.Text is "Pop", do your popping operation and change the name to "Push".
Hope you understand...

A: You can achieve this by using a check box and making its appearance property to button and use it as button.
I think this may help you.
private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        if (checkBox1.Checked)
        {
            checkBox1.Text = "Pop";
            MessageBox.Show("Data Pushed into the stack");
        }
        else
        {
            checkBox1.Text = "Push";
            MessageBox.Show("Data Poped from the stack");
        }
    }

This will work as you mentioned.


text:
Q: Plotting the set $\left\{ z\in \mathbb{C} : \left| z+i \right| =2\left| z \right| \right\} $ I have a question which can be simple, though I couldn't catch the idea.
Consider the Set given below:
$$E=\left\{ z\in \mathbb{C} : \left| z+i \right| =2\left| z \right|  \right\} $$
I have to find its graph to plot.
The Answer is the following: the Set $E$ is a circle, centred at $i/3$ and of radius $2/3$
I was not able of visualizing this set, I absurdly thought about a spiral. Any calculations neither didn't lead me to a solution. And especially, my conclusion was that this graph couldn't be a circle at all.
Thanks for helping me in advance.

A: Hint
Put $z=x+yi$ in given equation to get $$x^2+(y+1)^2=4(x^2+y^2)$$
$$\Rightarrow 3(x^2+y^2)-2y-1=0$$
$$\Rightarrow x^2+y^2-\frac 23 y-\frac 13=0$$
Which is the equation of required circle with centre $(0,\frac 13)$ and radius $\frac 23$ but since we are dealing in complex plane the centre is $\frac i3$

A: A good way to read an equation like this is geometrically. We want all points such that their distance from $-i$ is two times their distance from $0$. It should be clear that both $i$ and $-\frac13i$ both satisfy this condition. What ever the set looks like, it must be symmetric across the line through $-i$ and $0$, which is to say, the imaginary axis.
To see that the desired set is a circle is a little trickier. The general such problem is the Circles of Appollonius problem, which is linked in a comment under your question. A more modern approach is to follow Descartes, and write down an equation in $x$ and $y$ satisfied by points in the desired set. This equation is also given in a comment under your question.

A: Here is a "non-Cartesian" solution with a complex square completion.
The equation of a circle in the complex plane around point $a$ is:

*

*$|z-a|^2 = (z-a)(\bar z - \bar a)= |z|^2 - 2 Re(\bar a z) + |a|^2 = r^2$

Squaring the given equation:

*

*$|z|^2 - 2 Re(i z) + 1 = 4 |z|^2$

Rearranging and square completing:

*

*$|z|^2 - 2 Re(-\frac{i}{3} z) - \frac{1}{3} = |z - \frac{i}{3} |^2 - \frac{1}{9} - \frac{1}{3}= 0$
$$ \rightarrow |z -\frac{i}{3}| = \frac{2}{3}$$


text:
Q: Reading and writing specific line from csv file in Kotlin I wanted to read and write specific lines from a CSV file.
Here is an example of my CSV
ID; Code; Name
1; ABHD; Paul
2; HYDR; Arthur
3; POAJ; Jake
4; PLMH; Georges

Actually I know how to read all the file and put it into a list of lines by myFile.readLines().
But I want to read a specific line like the line with the Code ABHD, and later on modify that specific Line without reading and writing the whole file. Any idea ?
Thanks by advance.

A: A CSV file is a not a database. You can't write individual elements inside the file. You need to read the entire file and write the entire file. If the file is a reasonable size, you can read the entire file into memory, alter the data you want to change (in memory) and then write the entire file again. If the file is huge, you probably need to make your modifications "on the fly" (ie: read a line, (optionally) change it, write the line to the output file).
There are libraries that you can use to parse the data, as CSV can be complicated to parse (especially if it contains text strings).
See https://www.baeldung.com/kotlin/csv-files for some help or search for "kotlin csv parse"


text:
Q: Compress and upload multiple images I am working on a form with 8 images to be uploaded using the camera capture(in phone) / file upload(in desktop) where each image will be of minimum size 2 MB..
It takes too long to upload the file to the server. I need to upload the images through form submit and not by AJAX..
Is there any way to compress large image and then upload it to server. How can I submit the form where it should take minimum time to submit..
I came across CANVAS with HTML5 but, I don't know whether it will be used for this situation, if it can be used then please give me some example code..
Thank you..


text:
Q: Struts 2 Validation using Message Store Interceptor I have an action where I am trying to log the user in.
public class RegisteredUserAction extends ActionSupport implements SessionAware {
..
..
 public String login() throws Exception {

        DBLogic dBLogic = new DBLogic();
        RegisteredUser user = null;
        try {
            user = dBLogic.getRegisteredUser(getUserUsername(), getUserPassword());
        } catch (CredentialException e) {
            addFieldError("userUsername", e.getMessage());

            addActionError(e.getMessage());
            return INPUT;
        }

        if (user != null) {
            session.put("user", user);
            return SUCCESS;
        }

        return ERROR;
    }
}

As you can see, if the username or password is invalid, I throw a CredentialException and then populate that exceptions message in my fieldError. I even tried adding an Action Error.
With some advice and searching online, I managed to use the Message Store Interceptor using annotations in the RegisteredUserAction.action and the MainAction.action respectively storing and fetching.
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
@InterceptorRefs({
    @InterceptorRef(value = "store", params = {"operationMode", "STORE"}),
    @InterceptorRef("defaultStack"),})

AND
import org.apache.struts2.convention.annotation.InterceptorRefs;

@InterceptorRefs({
    @InterceptorRef(value = "store", params = {"operationMode", "RETRIEVE"}),
    @InterceptorRef("defaultStack"),})

This is the struts.xml file contents that are relevant:
<package name="pages" extends="struts-default" namespace="/">
        <global-results>
            <result name="displayPage">/WEB-INF/template/page.jsp</result>
            <result name="input">/WEB-INF/template/page.jsp</result>
        </global-results>
        <action name="registrationPage" class="actions.MainAction"
              method="loadRegistrationPage"></action>
        <action name="loginPage" class="actions.MainAction"
              method="loadLoginPage"></action>
</package>

<package name="operations" extends="struts-default" namespace="/">

        <action  name="userLogin" class="actions.RegisteredUserAction" method="login">
            <result type="redirect" name="input">loginPage.action</result>
            <result type="redirect" name="success">homePage.action</result>
        </action>
</package>

I am using a template based approach wherein the Middle content(in my case the LoginPage.jsp) is included into the mainpage dynamically.
My page.jsp (which includes the mainContent):
<s:include value="../%{mainContent}.jsp" ></s:include>

My login.jsp (which gets included):
<%@taglib prefix="s" uri="/struts-tags"%>

<s:form action="userLogin" method="POST">
    <s:textfield name="userUsername" />Error:<s:fielderror name="userUsername" />
    <s:password name="userPassword" />
    <s:submit />
</s:form>

The redirect works properly and the login form appears, but no errors.
I've even tried using the Message Store interceptor in the struts.xml with no luck. :(

A: Use redirectAction result instead of redirect. And try using configuration in struts.xml file instead of annotations.
<action name="userLogin" class="actions.RegisteredUserAction" method="login">
   <interceptor-ref name="store">
      <param name="operationMode">STORE</param>
   </interceptor-ref>
   <interceptor-ref name="defaultStack" />
   <result type="redirectAction" name="input">loginPage</result>
   <result type="redirectAction" name="success">homePage</result>
</action>


text:
Q: Authorization in the application deploying on the Heroku using JWT Token After completing the back-end part and testing of the application, I tried to run it on the Heroku server. Locally registration and receipt of all messages work.
My App Warbler
On the Heroku server, only registration is working, after successful registration Token is sent to the client. To receive messages, the client adds a Token to the request body.
The server replies that I am not authorized:
2019-09-24T08:22:02.047721+00:00 heroku[router]: at=info method=GET path="/api/messages" host=warbler-server-md.herokuapp.com request_id=849b48c9-caa9-4e7c-b38c-b614988b88e4 fwd="178.159.232.145,3.88.204.168" dyno=web.1 connect=1ms service=2ms status=401 bytes=293 protocol=https

The most likely problem is Token authentication:
exports.ensureCorrectUser = function(req, res, next) {
    try {
        const token = req.headers.authorization.split(' ')[1];
        jwt.verify(token, process.env.SECRET_KEY, function(err, decoded) {
            console.log("token", token);
            console.log("decoded", decoded);
            if (decoded && decoded.id === req.params.id) {
                return next();
            } else {
                console.log(err);
                return next({
                    status: 401,
                    message: 'Unauthorized'
                });
            }
        });
    } catch (error) {
        console.log('Unauthorized!');
        next({
            status: 401,
            message: 'Unauthorized'
        });
    }
};

It seems to me that this code does not start at all since the messages that I added are not displayed in the console.
What's wrong with authorization?


text:
Q: Cakephp 3.0 NotFoundException home.ctp on production server I just deployed a basic version of a CakePHP application. Nothing special or fancy here. Just a basic authorisation module and a couple of baked Controllers.
However when I try to open the website a Not Found error appears. Here is what the error log shows:
2015-04-13 21:14:07 Error: [Cake\Network\Exception\NotFoundException] Not Found
Request URL: /
Stack Trace:
#0 /home/public_html/site.com.au/vendor/cakephp/cakephp/src/View/View.php(815): include()
#1 /home/public_html/site.com.au/vendor/cakephp/cakephp/src/View/View.php(775): Cake\View\View->_evaluate('/home/pub...', Array)
#2 /home/public_html/site.com.au/vendor/cakephp/cakephp/src/View/View.php(463): Cake\View\View->_render('/home/pub...')
#3 /home/public_html/site.com.au/vendor/cakephp/cakephp/src/Controller/Controller.php(575): Cake\View\View->render('home', NULL)
#4 /home/public_html/site.com.au/src/Controller/PagesController.php(57): Cake\Controller\Controller->render('home')
#5 [internal function]: App\Controller\PagesController->display('home')
#6 /home/public_html/site.com.au/vendor/cakephp/cakephp/src/Controller/Controller.php(404): call_user_func_array(Array, Array)
#7 /home/public_html/site.com.au/vendor/cakephp/cakephp/src/Routing/Dispatcher.php(114): Cake\Controller\Controller->invokeAction()
#8 /home/public_html/site.com.au/vendor/cakephp/cakephp/src/Routing/Dispatcher.php(87): Cake\Routing\Dispatcher->_invoke(Object(App\Controller\PagesController))
#9 /home/public_html/site.com.au/webroot/index.php(37): Cake\Routing\Dispatcher->dispatch(Object(Cake\Network\Request), Object(Cake\Network\Response))
#10 {main}

Any clues? mod_rewrite is enabled. The login page is working but not the homepage.
My AppController has this filter:
public function beforeFilter(Event $event)
{
    $this->Auth->allow(array('controller' => 'pages', 'action' => 'display'));
}

Thanks!
UPDATE
In cakephp 3.0 this is the code that needs to be removed from the home.ctp file
if (!Configure::read('debug')):
  throw new NotFoundException();
endif;


text:
Q: Reformat a large text file into one line strings (via BASH) File1:
hello
- dictionary definitions:
hi
hello
hallo
greetings
salutations
no more hello for you
-
world
- dictionary definitions:
universe
everything
the globe
the biggest tree
planet
cess pool of organic life
-

I need to format this (for a huge list of words) into a term to definition format (one line per term). How can one achieve this? None of the words are the same, only the structure seen above is. The resultant file would look something like this:
hello    - dictionary definitions:    hi    hello    hallo    greetings    salutations    no more hello for you    -
world    - dictionary definitions:    universe    everything    the globe    the biggest tree    planet    cess pool of organic life    -

Awk/Sed/Grep/Cat are the usual contenders.

A: and who says only Perl can do it elegantly ? :)
$ gawk -vRS="-\n" '{gsub(/\n/," ")}1' file
hello - dictionary definitions: hi hello hallo greetings salutations no more hello for you
world - dictionary definitions: universe everything the globe the biggest tree planet cess pool of organic life

OR
# gawk 'BEGIN{RS="-\n";FS="\n";OFS=" "}{$1=$1}1'  file
hello - dictionary definitions: hi hello hallo greetings salutations no more hello for you
world - dictionary definitions: universe everything the globe the biggest tree planet cess pool of organic life

A: awk 'BEGIN {FS="\n"; RS="-\n"}{for(i=1;i<=NF;i++) printf("%s   ",$i); if($1)print"-";}' dict.txt

outputs:
hello   - dictionary definitions:   hi   hello   hallo   greetings   salutations   no more hello for you   -
world   - dictionary definitions:   universe   everything   the globe   the biggest tree   planet   cess pool of organic life   -

A: A perl one-liner:
perl -pe 'chomp;s/^-$/\n/;print " "' File1

gives
 hello - dictionary definitions: hi hello hallo greetings salutations no more hello for you
 world - dictionary definitions: universe everything the globe the biggest tree planet cess pool of organic life

This is 'something like' your required output.

A: Not sure the scripting language you will be using, pseudo code here:
for each line
 if line is "-"
  create new line
 else
  append separator to previous line
  append line to previous line
 end if
end for loop

A: Try this one liner works on a conditions that theer will always be 6 lines for a word
sed 'N;N;N;N;N;N;N;N;s/\n/ /g' test_3

A: sed -ne'1{x;d};/^-$/{g;s/\n/ /g;p;n;x;d};H'
awk -v'RS=\n-\n' '{gsub(/\n/," ")}1'


text:
Q: how to let Matlab keep a mex session alive My question is on how to program Matlab and my c++ code so that they can interact. To be more specific, I have a c++ program that process data, create an object, derive statistics of that object and write to mat file. I will then load it in matlab to do further analysis and visulization.
  However, the time it takes to process a data and create the object is enormous, while the time to derive a statistic is negligible. On the other hand, there are many statistics and different combination of them and it is difficult to anticipate what combinations we are going to use. So I hope I can run the "statistics" part interatively many times without repeating the job of processing the data.
My question is: Can I ask Matlab to: 1. call the c++ code; 2. after processing the data and creating the object, keep that object "alive" in the memory 3. call the c++ code again to ask for a statistic to be loaded into my workspace. 4. Repeat 3 with different statistics.
  Thanks

A: A further option may be to create a C++ class instance in your MEX function and return a pointer to it to MATLAB, passing the pointer to any subsequent calls. You should also create a MATLAB handle class wrapper for it if you use this approach, to allow you to clean up memory properly in its destructor. Here is a post where the poster was advised to do just that, and this is an example of the method on the Mathworks FileExchange.
The applicability of this method to your problem depends on the complexity of the problem. I would personally only go down this route if the problem is intractably complex with other approaches (e.g., you need to use a C++ class from some library and the instance must stay alive between calls, or if global variables won't do the trick as you need to keep track of a lot of instances and this is naturally represented best by an array of C++ classes where you can properly separate your concerns).

A: One way to accomplish this is to declare the variables that you want to access again as global in your c++ mex code. These variables will stay in the memory and you can access them again (when you call your mex function) until you clear that mex function or close the Matlab session. I used global variables for this purpose and it worked just fine for me.
Another option is to use persistent variables. From the documentation

Persistent variables are similar to global variables because the
  MATLAB® software creates permanent storage for both. They differ from
  global variables in that persistent variables are known only to the
  function in which they are declared. This prevents persistent
  variables from being changed by other functions or from the MATLAB
  command line.


text:
Q: Como eu pego o valor de cada checkbox que está dentro de um loop? Bom dia galera, preciso de ajuda :(
É o seguinte, eu preciso deletar vários registros de uma só vez pra isso preciso selecionar o ID de cada registro, então eu fiz um input com checkbox dentro do loop desse jeito:
<form method="POST" id="formDeletarMsg" action="deletarMsg.php">
   <input type="checkbox" name="msg[]" value="<?php echo $idMsg; ?>">
</form>

Botão submit está fora do formulário, estou usando javascript pois ele irá ficar no rodapé da section.
E estou usando um foreach para exibir os dados de cada checkbox, ele até funciona, só que exibe apenas o primeiro checkbox marcado, se eu marcar o segundo ou o terceiro não exibe nada, se eu marcar o primeiro exibe:
if(isset($_POST['msg'])){
$msg = $_POST['msg'];
foreach($msg as $key => $value){
    echo $key . "
";
    echo $value;
}
var_dump($value);
}

A: Galera, a burrada que eu fiz foi colocar o formulario dentro do while, por isso estava exibindo apenas o primeiro checkbox marcado, o formulario tem que estar fora do while mas o input tem que estar dentro. RESOLVIDO!!!
<form method="POST" id="formDeletarMsg" action="deletarMsg.php">
                <?php
                    while($row = mysqli_fetch_array($sqlMps)):
                        $idMsg = $row['idMsg'];
                        $assunto = utf8_encode($row['assunto']);
                        $usuario = $row['usuario'];
                        $visualizou = $row['visualizou'];
                        $dataMsg = utf8_encode($row['dataMsg']);

                ?>

                    <a <?php if($visualizou == 0){ echo "class='negrito'";}?> href="visualizarMp.php?id=<?php echo $idMsg; ?>"><?php echo substr($assunto, 0, 30); ?>   por <?php echo $usuario; ?> - <?php echo $dataMsg; ?>

                            <input type="checkbox" name="deletar[]" value="<?php echo $idMsg; ?>">

                <?php
                    endwhile;
                ?>
                 </form>


text:
Q: My php fetch from an SQL query doesn't return the ID My Login Function which Returns the Value $FoundAcc
function Login($Username,$Password){
    global $ConnectingDB;
    $sql = "SELECT admin FROM admin WHERE admin=:admin
    AND password=:password LIMIT 1";
    $stmt = $ConnectingDB->prepare($sql);
    $stmt->bindValue(':admin',$Username);
    $stmt->bindValue(':password',$Password);
    $stmt->execute();
    $Result = $stmt->rowcount();
    if ($Result==1){
        return $FoundAcc=$stmt->fetch();
    }else{
        return null;
    }
}

My PHP login page should save the fetched Row from my DB and save it in a Session Variable (UserID) but It doesn't, It Does however save the (Username)variable from the Row... What is wrong?
if(isset($_POST["submit"])){
    $Username=$_POST["username"];
    $Password=$_POST["password"];
   //if username/password are empty show error//
    if(empty($Username)||empty($Password)){
        $_SESSION["ErrorMessage"] = "All Fields Must Be Filled Out!";
        Redirect_to("Login.php");
    }else{
        $FoundAcc=Login($Username,$Password);
        // if account and pw found in DB complete following
        if ($FoundAcc){
            //save variables from DB row to session variables
        $_SESSION["UserID"]=$FoundAcc["id"];
        $_SESSION["Username"]=$FoundAcc["admin"];
            //show toast
        $_SESSION["SuccessMessage"] = $_SESSION["UserID"]." Has Successfully Logged In ";
        Redirect_to("Login.php");
        }else{
            $_SESSION["ErrorMessage"] = "Incorrect Username or Password!";
        Redirect_to("Login.php");
        }
    }
}

A: The sql query should be like this:
 $sql = "SELECT * FROM admin WHERE admin=:admin AND password=:password LIMIT 1";


text:
Q: years difference date from field php I'm trying to make the form that does not accept a member below 20 years old so I'm trying to do this code but it gives me an error
$dob=$_POST["date"];
$today =date_create(date('YYYY-MM-DD'));
        $db=create_date(date($dob));
        $diff=date_diff($db,$today,true);

A: First here is the date_create function definition :
DateTime date_create ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

As you can see, the default time is now, so you can save up a few characters.
Then, if $dob is in a valid format (see http://php.net/manual/en/datetime.formats.php), here is your solution:
$today = date_create();
$db = date_create($dob);
$diff = date_diff($db, $today, true);

Happy coding!


text:
Q: Update css for Modal dynamically backbone.js I am new to backbone and am trying to debug an issue. I have a Modal which is rendering as follows:
render: function() {
            this.$el.html(Modal.TEMPLATE);
            this.$(Modal.HEADER_TITLE_SELECTOR).html("Edit"));
            this.$(Modal.BODY_SELECTOR).append(this.myView.render().el);
            this.$(Modal.FOOTER_SELECTOR).append(Modal.BUTTON_DONE);
        },

The 'myView' is associated with a class (with display: block) which I want to override with (display: inline-block). How can I do that?

A: render: function() {
            this.$el.html(Modal.TEMPLATE);
            this.$(Modal.HEADER_TITLE_SELECTOR).html("Edit"));
            this.$(Modal.BODY_SELECTOR).append(this.myView.render().el);
            this.myView.$el.css("display", "inline-block");
            //or this.$(this.myView.$el).css("display", "inline-block")
            this.$(Modal.FOOTER_SELECTOR).append(Modal.BUTTON_DONE);
        },

A: This fixed the issue:
$(this.myView.$el).css({display: 'inline-block'});


text:
Q: How do you get and set keys using Google Cloud MemCache (node js)? I'm using node.js and google app engine. My understanding is that memcache is some shared memory where you can store keys.
docs: https://cloud.google.com/nodejs/docs/reference/memcache/latest
The docs say, install the memcache api:
npm install "@google-cloud/memcache".

And then get a memcache instance like this:
const {CloudMemcacheClient} = require('@google-cloud/memcache');

// Creates a client
const cmc = new CloudMemcacheClient();

But then what?
How do I get and set keys? The documentation just seems to end.
Hope some kind person knows how this is supposed to work.


text:
Q: tableone package : How to get the odds ratio and the confidence interval from a svydesign object? I routinely use the 'weightit' package for propensity score , then I use the 'tableone' package to compare my variables after adjustment.
For exemple,
 wgt = weightit(formula = var ~ var1 + var2 +var3 , data = df, method = "ps",estimand = "ATO" )
'var' is a binary variable
design <- svydesign(~1, weights = wgt$weights, data = df)
tabel <- svyCreateTableOne(vars=  list_var   ,strata = "var", data = design)
This gives me a table with the mean values (or percentage) with the p-value.
How is it possible to get the confidence interval for each variable from a svydesign object ? And how is it possible to obtain the odds ratio as well as the p-value and the confidence interval of the odds ratio
I would like to get a result like this :
non adjusted vs adjusted


text:
Q: Creating a python loop where the input is a random number This is my code so far:
    import bcrypt
    import random

    def PRG():
        print(random.randint(1,100000))

    For i in range(1,3):
        print(bcrypt.gensalt(PRG()))

Which gives the output:
    77494
    $2a$04$2tpKWJxtsBAK1FYdM.6MSe
    87956
    $2a$04$4ag2YmOBFSFRR3Lu0RgQ8.

I'm just trying to make a loop that gives a bunch of salts based on what random number PRG() outputs. I'm not sure if the hash is the hash of the number output by PRG() because bcrypt output isn't fixed, and if someone could tell me how to remove the numeric output I'd really appreciate it.

A: replace print(random.randint(1,100000)) with return random.randint(1,100000)


text:
Q: Including a condition dynamically in sql(oracle) I have a query as below
select --------
from table a
left outer join ....c
where
(a.column='123') and (c.column='456')

I would like to

include "(c.column='456')" only when (c.column='456') is not null

how do I do that in a single query ? or do I need to write two separate queries ?
I tried (a.column='123') and (c.column is null), did not work

A: try:
select --------
from table a
left outer join ....c
where
((a.column='123') and (c.column='456'))
or c.column is not NULL

A: Try putting the check for null and the value 456 in the same set of parenthesis:
select --------
from table a
left outer join ....c
where
(a.column='123') and (c.column is not null and c.column='456')


text:
Q: Error - ORA00918: Column ambiguously defined PLSQL-PIVOT The outcome is,
PartNo InventorySiteCCC PurchaseSiteCCC Supplier_PurchaseSiteCCC
XXX             1           1                      1
My query looks like this,
SELECT *
FROM (
SELECT A.part_no,  I.contract, I.part_no,
       P.contract, P.part_no, SP.contract, SP.part_no, SP.vendor_no
FROM PART_CATEGORY A
LEFT JOIN INVENTORY_PART I ON I.part_no = A.part_no
LEFT JOIN PURCHASE_PART P ON P.part_no = A.part_no
LEFT JOIN PURCHASE_PART_SUPPLIER SP ON SP.part_no = A.part_no AND (SP.vendor_no IS NOT NULL AND SP.PRIMARY_VENDOR_DB = 'Y')
ORDER BY A.part_no
)
PIVOT
(
  COUNT(I.contract) AS Inventory,
  COUNT(P.contract) AS Purchase,
  COUNT(SP.contract) AS Supplier_Purchase
  FOR (contract) IN ('CCC' AS SiteCCC, 'SSS' AS SiteSSS)
)[enter image description here][1]
ORDER BY A.part_no;

A: The error is raised because you have four columns named the same.
Columns: SP.part_no,A.part_no, I.part_no and P.part_no will have same column name resulting in column name: part_no.
If you give different aliases to these columns the problem should disappear.
The same goes for contract column.
Your query after correction could look like:
SELECT *
FROM (
SELECT A.part_no as part_no_a,
       I.contract as contract_i,
       I.part_no as part_no_i,
       P.contract as contract_p,
       P.part_no as part_no_p,
       SP.contract as contact_sp,
       SP.part_no as part_no_sp,
       SP.vendor_no
FROM PART_CATEGORY A
LEFT JOIN INVENTORY_PART I ON I.part_no = A.part_no
LEFT JOIN PURCHASE_PART P ON P.part_no = A.part_no
LEFT JOIN PURCHASE_PART_SUPPLIER SP ON SP.part_no = A.part_no AND (SP.vendor_no IS NOT NULL AND SP.PRIMARY_VENDOR_DB = 'Y')
ORDER BY A.part_no
)
PIVOT
(
  COUNT(contract_i) AS Inventory,
  COUNT(contract_p) AS Purchase,
  COUNT(contract_sp) AS Supplier_Purchase
  FOR (put_here_correct_contract_column) IN ('CCC' AS SiteCCC, 'SSS' AS SiteSSS)
)[enter image description here][1]
ORDER BY A.part_no;


text:
Q: Split dictionary items containing nested lists and map elements of one list I currently have a dictionary of lists that i am trying to map each list element to a customer id and by brand id.
So far, this is what I come up with - the issue is that i am missing the mapping between brand id and customer ids.
Apologies for not sharing the full inputs for replication as it contains api keys/secrets.
The goal is to have a dictionary per customer id belonging to the same brand id.
Currently, the loop is iterating over the length of brand ids so coercing customer id into a nested list. Attached are also snippet of current versus desired output.
*df_dict below is a dictionary of dataframes per brand id
df_dict = {}
for brand, values in reduced_df_send_message_now.groupby('brand_id'):
    df_dict.update({'brand_' + str(brand) : values.reset_index(drop=True)})

customers = [['1704283852'], ['1542053114', '1268330200', '1006435031']]
casino_ids = [['2000'], ['2080', '2080', '2080']]
batch_list = []
for c, i in enumerate(df_dict):
    batch = Batch()
    batch.user_identities = {'customer_id': customers[c]}
    batch.user_attributes = {
        'casino_id': casino_ids[c]
        }
    print(batch)
    batch_list.append(batch)

# current vs target split records

current = dict(
    {'api_key': None,
     'application_info': None,
     'consent_state': None,
     'context': None,
     'deleted_user_attributes': None,
     'device_info': None,
     'environment': None,
     'events': None,
     'ip': None,
     'mp_deviceid': None,
     'mpid': None,
     'schema_version': None,
     'source_request_id': None,
     'user_attributes': {'brand_id': ['2080', '2080', '2080']},
     'user_identities': {'customer_id': ['1542053114', '1268330200', '1006435031']}
     }
    )

target = dict(
    {'api_key': None,
     'application_info': None,
     'consent_state': None,
     'context': None,
     'deleted_user_attributes': None,
     'device_info': None,
     'environment': None,
     'events': None,
     'ip': None,
     'mp_deviceid': None,
     'mpid': None,
     'schema_version': None,
     'source_request_id': None,
     'user_attributes': {'brand_id': '2080'},
     'user_identities': {'customer_id': '1542053114'}
     }
    )

target2 = dict(
    {'api_key': None,
     'application_info': None,
     'consent_state': None,
     'context': None,
     'deleted_user_attributes': None,
     'device_info': None,
     'environment': None,
     'events': None,
     'ip': None,
     'mp_deviceid': None,
     'mpid': None,
     'schema_version': None,
     'source_request_id': None,
     'user_attributes': {'brand_id': '2080'},
     'user_identities': {'customer_id': '1268330200'}
     }
    )

target3 = dict(
    {'api_key': None,
     'application_info': None,
     'consent_state': None,
     'context': None,
     'deleted_user_attributes': None,
     'device_info': None,
     'environment': None,
     'events': None,
     'ip': None,
     'mp_deviceid': None,
     'mpid': None,
     'schema_version': None,
     'source_request_id': None,
     'user_attributes': {'brand_id': '2080'},
     'user_identities': {'customer_id': '1006435031'}
     }
    )

A: I think i figured it out - results match what i was trying to achieve (in the post). below is the code i used to split customer dictionary by brand id -
** the following was also fixed by last line**: only issue is that the function has to be called at the end with the brand id as argument (i am only working with 3 brand ids for now) but feel free to suggest a dynamic way of looping through brand ids to catch new ones (that are currently not part of the pull).
df_dict = {}
for brand, values in reduced_df_send_message_now.groupby('brand_id'):
    df_dict.update({str(brand) : values.reset_index(drop=True)})

# function to transforme each column needed to a list so that we can include them as lists to dicts in batch further below
def col_to_list(df):

    if df.shape[0] > 0:
    # customers = df[['customerid', 'brand_id']].values.tolist()
        customers = df['customerid'].values.tolist()
        brand_ids = df['brand_id'].values.tolist()
        casino_ids = df['signup_casino_id'].values.tolist()
        balances = df['total_balance'].values.tolist()
        free_bet_cash_balance = df['free_bet_cash_balance'].values.tolist()
        bet_churn_cat = df['bet_churn_category'].values.tolist()
        bet_churn_score = df['customer_lapsing_factor'].values.tolist()
        login_churn_cat = df['login_churn_category'].values.tolist()
        login_churn_score = df['login_churn_score'].values.tolist()
        group_type = df['group_type'].values.tolist()
        api_key = df['key'].values.tolist()
        api_secret = df['secret'].values.tolist()

        return customers, brand_ids, casino_ids, balances, free_bet_cash_balance, bet_churn_cat,\
            bet_churn_score, login_churn_cat, login_churn_score, group_type, api_key, api_secret
    else:
        None

def return_needed_lists_by_brand(brand_id):

    list_names = ['customer_id', 'casino_id', 'balances']

    if len(df_dict.keys()) == 0:
        return
    if brand_id not in df_dict.keys():
        return
    else:
        customers = col_to_list(df_dict[brand_id])[0]
        casino_ids = col_to_list(df_dict[brand_id])[2]
        balances = col_to_list(df_dict[brand_id])[3]

    return dict(zip(list_names, [customers, casino_ids]))

def upload_brand(brand_id):
    batch_list = []
    if  brand_id not in df_dict.keys():
        return
    for i in range(len(return_needed_lists_by_brand(brand_id)['customer_id'])):
        batch = Batch()
        try:
            batch.user_identities = {'customer_id': return_needed_lists_by_brand(brand_id)['customer_id'][i]}
            batch.user_attributes = {
            'casino_id': return_needed_lists_by_brand(brand_id)['casino_id'][i]
             }
            print(batch)
        except:
                pass
        batch_list.append(batch)

#upload_brand("213")

# final upload
for i in brand_id_list:
    upload_brand(str(i))


text:
Q: .htaccess or VirtualHost to block website from direct IP access, yet allow from URL only I have blocked direct access to my site using IP via virtual host. However, i am not able to use 403 error template defined as error.php
Since error.php is located at /var/www/html/error.php, so its blocked automatically and it errors out Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

Below is my 000-default.conf
ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php
ErrorDocument 404 /error.php
ErrorDocument 500 /error.php

<VirtualHost *:80>
        ServerName subdomain.example.com
        ServerAlias www.subdomain.example.com
        DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:80>
        ServerName 1.1.1.1
        ServerAlias 2001:2001:2001:2001:2001:2001:2001:2001
        DocumentRoot /var/www/html
        <Location />
            Require all denied
        </Location>
</VirtualHost>

So later i tried to achieve same using .htaccess (after removing the block from 000-default.conf ofcourse), I encountered same error. Can't select custom 403 template because path seems to be blocked. Below were .htaccess contents placed at /var/www/html/
RewriteCond %{HTTP_HOST} ^1\.1\.1\.1$
RewriteRule .* - [F,L]
#RewriteCond %{HTTP_HOST} !^2001\:2001\:2001\:2001\:2001\:2001$

Running Apache/2.4.38

A: Managed to sort it out. Sharing if it could help someone facing similar issue.
<VirtualHost *:80>
        ServerName 1.1.1.1
        ServerAlias 2001:2001:2001:2001:2001:2001:2001:2001
        DocumentRoot /var/www/html
        <Directory /var/www/html>
            Order deny,allow
            Deny from all
            Options FollowSymLinks
            <Files error.php>
                Order allow,deny
                Allow from all
            </Files>
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>


text:
Q: npm run-script flow is not working I created a react native project, and I want to enable flow for my project.
I have flow-bin installed by
npm install --save flow-bin

However, it returns
missing script: flow

when I run
npm run-script flow

Anyone got any idea? Thanks!

A: npm run-script flow will not execute the flow command, but will just look into the scripts entry in the package.json file and execute the command under the flow entry (see the documentation for more information). This has the advantage that it will include binaries located in your dependencies (a.k.a. binaries inside the node_modules folder), which is something you usually do not have in your $PATH, avoiding the need to configure that for every project. Make sure that your package.json looks something like this:
//...
"scripts":{
    //...
    "flow": "flow; test $? -eq 0 -o $? -eq 2"
}
//...

Source: docs

A: Add "flow": "flow" as a new entry under "scripts" in your package.json file:
  ...
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "flow": "flow"
  },
  ...

The tutorials I was following seem to skip this step but the Facebook github repo has it: https://facebook.github.io/create-react-app/docs/adding-flow


text:
Q: function to determine if a number is in the fibonacci or not in sml? I need to write a function in sml that takes a number and determines if it is or not a fibonacci number.
I have already done the fibonacci func
fun fib 1=0
  | fib 2=1
  | fib n= fib (n-1)+fib(n-2);

but i cannot figure out first one? Do you have any ideas?

A: This may help you out.
fun isfib 0 = true
  | isfib x =
    let
      fun help (i,j) = if j >= x then x = j else help (j,j+i)
    in
      help (0,1)
    end

I created a helper function that forward generates the sequence until i see a number greater than or equal to the number i am interested in.  Then I test to see if that fibonacci number is equal to x.


text:
Q: How to check my current azure function version? Here I can see the latest azure function version is 4.x -> https://learn.microsoft.com/en-us/azure/azure-functions/functions-versions?tabs=v4&pivots=programming-language-csharp
I also would like to use version 4.x of the azure function, but i am not able to use it.
I checked it over here, function app > configurations. I can only see ~3 in run time version not ~4

Also, the version specified in host.json is 2.x.
// host.json
{
    "version": "2.0",
}

Setup

*

*Azure function premium plan

*Deployed on docker - https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-function-linux-custom-image?tabs=in-process%2Cbash%2Cazure-cli&pivots=programming-language-javascript
I tried setting the version in host.json to 4.0 but having the following issue in vscode.

Which one is the actual azure function version that is being used in my case, and how to upgrade it to version 4.x?
Reference
How to find the version of an azure Function App?

A:
How to check my current azure function version?

In portal you can check as below:

Alternatively, I have reproduced in my environment and got expected results as below and I followed Microsoft-Document:
Below is my script which got my function apps run time version which i executed in Azure PowerShell:
$Subscription = 'Azure cc'
Set-AzContext -Subscription $Subscription | Out-Null
$FunctionApps = Get-AzFunctionApp
$res =@{}
foreach ($x in $FunctionApps)
{
$res= $x.Name + $x.ApplicationSettings.FUNCTIONS_EXTENSION_VERSION
$res
}

This way you can get to know which version you are using.


text:
Q: How to get the "calculated" path in PHP? $p = '/var/www/domain/a/b/../..';

How to write such a function func so that func($p) equals to '/var/www/domain/' ?

A: Use realpath().
Example:
$p = '/var/www/domain/a/b/../..';
$q = realpath($p); // will result in /var/www/domain or FALSE on failure

Cases in which realpath() returns false, as quoted from the manual:

realpath() returns FALSE on failure,
  e.g. if the file does not exist.
Note:
The running script must have
  executable permissions on all
  directories in the hierarchy,
  otherwise realpath() will return
  FALSE.


text:
Q: How to apply a jquery zoom function to local Storage I am using Ng-Storage. Right now I am using sessionStorage to remember a users selected object. I need to add localStorage to remember a users browsers window zoom level. I have a jquery function that zooms in and out but I do not know how to save it with the angular Storage.
plunkr
var testapp = angular.module('testApp', ['ngStorage']);

 testapp.controller('controller1', ['$scope', '$rootScope', '$sessionStorage','$localStorage', function($scope, $rootScope,$sessionStorage,$localStorage) {

$scope.selectedJob = $sessionStorage.$default($scope.jobs[1]);
$scope.selectJob = function(job) {
  angular.extend($scope.selectedJob, job);
};

 }]);

$(document).ready(function ($) {
var currFFZoom = 1;
var currIEZoom = 100;
$('#plusBtn').on('click', function () {
    var step = 2;
    currIEZoom += step;
    $('body').css('zoom', ' ' + currIEZoom + '%');
});
$('#minusBtn').on('click', function () {
    var step = 2;
    currIEZoom -= step;
    $('body').css('zoom', ' ' + currIEZoom + '%');
});

  });


text:
Q: Android NoSuchMethodException thrown when using extends I have an Activity CropActivity, that uses my own written View CropView.
CropView extends SelectorView (also selfwritten), and SelectorView extends ImageView.
When starting the CropActivity, a NoSuchMethodException is thrown.
When using the SelectorView for the CropActivity, no error is thrown, any ideas?
The Cropview class
public class CropView extends SelectorView {
public CropView(Context context) {
    super(context);
    initCropView();
}

private void initCropView() {
    setmPaintColor(Color.WHITE);
    setsMinimumSize(metrics.densityDpi);
    setsTouchBuffer(metrics.densityDpi / 3);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (getmLeftTop().equals(0, 0))
        resetPoints();
    // draw the points on the screen; one in every corner and one in the center
    canvas.drawRect(getmLeftTop().x, getmLeftTop().y, getmRightBottom().x, getmRightBottom().y,
            getmPaint());
    canvas.drawCircle(getmLeftTop().x, getmLeftTop().y, 40, getmPaint());
    canvas.drawCircle(getmLeftTop().x, getmRightBottom().y, 40, getmPaint());
    canvas.drawCircle(getmRightBottom().x, getmLeftTop().y, 40, getmPaint());
    canvas.drawCircle(getmRightBottom().x, getmRightBottom().y, 40, getmPaint());
    canvas.drawCircle(getmCenter().x, getmCenter().y, 10, getmPaint());
}

Selectorview snippet
public SelectorView(Context context) {
    super(context);
    initSelectorView();
}

public SelectorView(Context context, AttributeSet attrs) {
    super(context, attrs, 0);
    initSelectorView();
}

public SelectorView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    initSelectorView();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
}

/**
 * Initializes the cropview and variables.
 */
private void initSelectorView() {
    mPaint.setStyle(Style.STROKE);
    mPaint.setStrokeWidth(5);
    mLeftTop = new Point();
    mRightBottom = new Point();
    mCenter = new Point();
    mScreenCenter = new Point();
    mPrevious = new Point();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    int eventaction = event.getAction();
    switch (eventaction) {
    // set the touch point
        case MotionEvent.ACTION_DOWN:
            mPrevious.set((int) event.getX(), (int) event.getY());
            break;

oncreate from CropActivity
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_crop);

    mContext = this;
    mCropView = new CropView(this);
    mFile = new File(getIntent().getStringExtra("imgpath"));
    mBitmaps = new ArrayList<Bitmap>();
    mTasks = new ArrayList();
    mNumberOfCores = Runtime.getRuntime().availableProcessors();
    mProgressDialog = new ProgressDialog(mContext);
    mProgressDialog.setTitle("Enhancing image");
    mBitmapDrawable = null;
    mBitmapDrawable = (BitmapDrawable) Drawable.createFromPath(mFile.getAbsolutePath());

    mCropView = (CropView) findViewById(R.id.image_preview);
    mCropView.setImageDrawable(mBitmapDrawable);

    mCropButton = (Button) findViewById(R.id.button_crop);

A: Custom views inflated via XML need the following constructors:
ViewName(Context)
ViewName(Context, AttributeSet)
ViewName(Context, AttributeSet, int)

You only have the first one and I guess the exception is about the second one being missing in your CropView.


text:
Q: Select form using option values from NodeJS database this sounds like a dumb question but.. I'm starting in JS/MySQL and I'm using a front-end reactJS and back-end nodeJS. I'm trying to make a select form using the  values from a table in MySQL database. This should be possible right?
here's my code (using a react component, semantic-ui forms)

class FormulaireCreerCollection extends Component {

  constructor() {
    super();

    this.state = {
      categories: []
    }
  }

  async componentDidMount() {
    const response = await fetch('http://localhost:3004/getCategories');
    const newList = await response.json();
    this.setState(previousState => ({
      ...previousState,
      categories: newList,
    }));
  }

  createOptions() {
    return this.state.categories.map((categorie, index) => <option key={index} value={index}>{categorie}</option>);

  }

  state = {}

  handleChange = (e, { value }) => this.setState({ value })

  render() {
    const { value } = this.state
    return (
      <Form>
        <Form.Group widths='equal'>
          <Form.Field id='categories' fluid label='Catégories' control='select'>
              {this.createOptions()}
          </Form.Field>
          <Form.Input id='objet'fluid label="Nom de l'objet" placeholder="Nom de l'objet"  />
          <Form.Input id='image' fluid label="Image de l'objet" placeholder="Image de l'objet"  />

        </Form.Group>

        <Form.TextArea id='descObj' label="Description de l'objet" placeholder="Dites-en nous plus sur l'objet.." />
        <Form.Button onClick={this.handleClick}>Ajouter l'objet à la collection</Form.Button>

      </Form>
    )
  }
}

export default FormulaireCreerCollection;

What I would like to do is for example option {first value from table}
then option {second value from table} etc..
This sounds really dumb but I haven't found my answer yet. Can anyone help me ?
Here's my json ouput:
[{"nom_categorie":"Alimentation"},{"nom_categorie":"Autres"},{"nom_categorie":"Cartes"},{"nom_categorie":"CD / DVD"},{"nom_categorie":"Consoles"},{"nom_categorie":"Images"},{"nom_categorie":"Informatique"},{"nom_categorie":"Jeux Vidéos"},{"nom_categorie":"Livres"},{"nom_categorie":"Moyens de locomotion"},{"nom_categorie":"Outillage"},{"nom_categorie":"Son"},{"nom_categorie":"Vêtements"}]

A: I have shown some basic ideas below. Adapt into your own use.
(Also, I believe you are using Express and mysql.js in the backend)

// in React
class WhatEver {
  constructor() {
    this.state = {
      categories: []
    }
  }

  componentDidMount() {
    // do AJAX call here
    someAjaxCall(..., (results) => {
      // This only shows the idea, do your own result processing instead and then setState
      this.setState({
        categories: results
      }) // triggers rerender
    })
  }

  createOptions = () => {
    return this.state.categories.map((e) => <option value={e} key={/* some unique key */}>{/* some name */}</option>)
  }

  render() {
    return (
      <Form.Field id='categories' fluid label='Catégories' control='select'>
        {this.createOptions() /* spread array elements in this way */}
      </Form.Field>
    )
  }
}

A:
I'm trying to make a select form using the values from a table in MySQL database. This should be possible right?

Yes this is very possible.
You have most of the pieces you need to make it work but the thing you're missing is the network request from the client (i.e. the browser + react code) to your server (i.e. node + express).

your server code is completely fine as is:
app.get('/getCategories', function (req, res) {
    connection.query('SELECT nom_categorie FROM categories', function (error, results) {
      if (error) throw error;
     res.json(results);
  });
});

You should test to see if this works by calling your endpoint in your browser (e.g. http://localhost:8080/getCategories). You should see plain JSON in your browser. If you don't, troubleshoot why. If this doesn't work then your app won't load data.

Your client code is where you're missing the call to the server to get that data (remember, there are two parts to a full stack web application).
I would do something like this:
import * as React from 'react';

// you need a stateful component somewhere to fetch and update your data in app.
class MyForm extends React.Component {
  constructor() {
    super({});

    // give your component a default state
    this.state = {
      items: [],
    };
  }

  // use the componentDidMount hook to run as soon as the component is mounted to the DOM
  async componentDidMount() {
    // use the fetch API to make the call from client to server
    const response = await fetch('/getCategories');
    const newList = await response.json();
    this.setState(previousState => ({
      ...previousState,
      list: newList,
    }));
  }

  render() {
    return <Form.Field id='categories' fluid label='Catégories' control='select'>
      {this.state.items.map(obj => obj.nom_categorie).map((item, index) => <option
        key={index}
        value={index}
      >{item}</option>)}
    </Form.Field>;
  }
}

So the strategy is:

*

*ensure your endpoint works by testing in your browser

*create a stateful react component with an initial state with an empty array

*create a render function that uses this.state.items to map the items array to react DOM nodes

*use the componentDidMount lifecycle hook to call your service using the fetch API and update the state of the component when it finishes.

Hopefully that helps. Good luck!