text:
Q: Working with multiple custom variables on Google Analytics I am a bit of a novice to Google Analytics and I have been trying to figure out the following problem for far too long now. So perhaps you can help me. Any asstitance would greatly be appreciated.
I have one website, powered by Fork CMS, with one blog section. Within the blog section there are, practically speaking, 4 different blogs, marked by four different categories. On the page 'Blogs' four links are provided, each to a page on which all the blogposts from one category are displayed.
The four categories are 'Painters' 'Fine Art Photographers', 'Visual Artists' and 'Multimedia Artists'.
What I would like to see in Google analytics is
1) an overview of all traffic on the site minus all the trafic to the blogs,
2) an overview of all the traffic to the blog 'Painters',
3) an overview of all the traffic to the blog 'Fine Art Photographers',
4) an overview of all the traffic to the blog 'Visual Artists'
5) an overview of all the traffic to the blog 'Multimedia Artists'
I think I have figured out how to do 2-5, but I do not have a clue about the first one. How can I create a custom variable which takes all site traffic - 2 to 5...?
My GAcode right now:
   <script>
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-xxxxxxxx-1']);

    //custom variable for categories
    _gaq.push(['_setCustomVar',1,'Painters','3'],
    ['_setCustomVar',2,'Fine Art Photographers','3'],['_setCustomVar',3,'Visual
    Artists','3'],['_setCustomVar',4,'Multimedia Artists','3']);

    _gaq.push(['_trackPageview']);

    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-xxxxxxxx-1', 'mydomain.com');
    ga('send', 'pageview');
    </script>

Thanks in advance!

A: The short answer would be to use a different scope, i.e.:
_gaq.push(['_setCustomVar',1,'Overview',2],

refer to:

from GA Link


text:
Q: How to paste image in chrome, then upload it to a server with PHP I actually want to upload an image to a server.
To achieve this, i want the user just paste the image into chrome (the image is a print screen in fact), and then i post the stream to a php page, convert the stream as an image, and then upload it.
How can i achieve this web application ?
Today i have develop some differents parts :
I used this script, and i create the Upload.php page which gets the post variable and try to Create and image.
The problem i have, is that when i post the data, i only get a blob. I would like to get a base64 stream.
Can you help me ?
Thanks in advance.

A: I'm not sure why you are specifically looking for a "base 64 stream".  If you are sending the Blob to your server via ajax, as far as your server is concerned, it's a file.  Treat it no different than any other upload server-side.  A Blob is a File without a name property.  That's perhaps a bit overly-simplistic, but my point is that, again, this is really nothing more than a file as far as your server knows.
Assuming you are sending a multipart-encoded request, I'd like to point out that most user agents will set the filename property of the item's Content-Disposition header in the request to "blob" when the item you are uploading is a Blob instead of a file.  It is possible to change this value in some browsers via the 3rd argument in FormData's append method, but I wouldn't rely on this just yet.
Also note that, if you are interested in a library that handles all of this already, I maintain, Fine Uploader which natively supports uploading images via paste in Chrome.

A: To answer this old question: Posting an image from clipboard with chrome is pretty much the same as posting a dropped file - except that the image/blob doesn't have the properties "name" and "lastModified".
var entry = items[i].webkitGetAsEntry();
if (!entry) entry = items[i].getAsFile();

if (entry instanceof Blob) /** CHROME pastet Bilder als Blob **/
{
    entry.isFile = true;
    entry.lastModifiedDate = new Date();
    entry.name = ""+new Date().getTime()+"."+entry.type.split('/')[1];
}

if (entry.isFile)
{
//handle dropped file
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: passwords changing on export/import of database I have a linux shared hosting with phpmyadmin and MySQL
I run a wamp server without any amends. MOstly it works fine.
However when I export out a database from the wamp and then export it into the Linux the passwords change and I have to go in and reset them.
What's going on please?
    --
-- Table structure for table `pfd8x_users`
--

CREATE TABLE IF NOT EXISTS `pfd8x_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL DEFAULT '',
  `username` varchar(150) NOT NULL DEFAULT '',
  `email` varchar(100) NOT NULL DEFAULT '',
  `password` varchar(100) NOT NULL DEFAULT '',
  `block` tinyint(4) NOT NULL DEFAULT '0',
  `sendEmail` tinyint(4) DEFAULT '0',
  `registerDate` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `lastvisitDate` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `activation` varchar(100) NOT NULL DEFAULT '',
  `params` text NOT NULL,
  `lastResetTime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Date of last password reset',
  `resetCount` int(11) NOT NULL DEFAULT '0' COMMENT 'Count of password resets since lastResetTime',
  `otpKey` varchar(1000) NOT NULL DEFAULT '' COMMENT 'Two factor authentication encrypted keys',
  `otep` varchar(1000) NOT NULL DEFAULT '' COMMENT 'One time emergency passwords',
  PRIMARY KEY (`id`),
  KEY `idx_name` (`name`),
  KEY `idx_block` (`block`),
  KEY `username` (`username`),
  KEY `email` (`email`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=401 ;

--
-- Dumping data for table `pfd8x_users`
--

INSERT INTO `pfd8x_users` (`id`, `name`, `username`, `email`, `password`, `block`, `sendEmail`, `registerDate`, `lastvisitDate`, `activation`, `params`, `lastResetTime`, `resetCount`, `otpKey`, `otep`) VALUES
(400, 'Super User', 'NAME', 'fred@email.com', '$P$D5YNEQ62cnGZy0cFTL/x49uBSkdWU80', 0, 1, '2014-04-01 14:59:48', '2014-05-01 16:49:46', '0', '{"admin_style":"","admin_language":"","language":"","editor":"","helpsite":"","timezone":""}', '0000-00-00 00:00:00', 0, '', '');

-- --------------------------------------------------------


text:
Q: Chrome suddenly won't play MP3 files in-tab For years it seems I've relied on this feature, to play podcasts, etc, in a chrome tab by opening an mp3 URL.
Suddenly today, every time I try it loads the file then immediately crashes (Aw, Snap).
I've updated Chrome to the newest version and relaunched but it doesn't fix anything. I'm running on OSX 10.10.5 but my system hasn't changed since yesterday when it was working fine.
I'm also getting it on some pages with media e.g. video. The front page of this site crashes every time, after about a second... if I'm very quick I can click on a link to a different section and that loads fine https://pulmanusedcars.co.uk/ Making me think it's the page content somehow...

A: I just had this same issue. I could not find any other working solution but to re-encode all my files. It seems to be a Chrome "feature".
Use VLC to do it. By using VLC's default settings I got a working file with the following properties:
General
Complete name                            : demo1.mp3
Format                                   : MPEG Audio
File size                                : 14.6 MiB
Duration                                 : 15 min 55 s
Overall bit rate mode                    : Constant
Overall bit rate                         : 128 kb/s
Writing library                          : LAME3.99.5

Audio
Format                                   : MPEG Audio
Format version                           : Version 1
Format profile                           : Layer 3
Format settings                          : Joint stereo / MS Stereo
Duration                                 : 15 min 55 s
Bit rate mode                            : Constant
Bit rate                                 : 128 kb/s
Channel(s)                               : 2 channels
Sampling rate                            : 44.1 kHz
Frame rate                               : 38.281 FPS (1152 SPF)
Compression mode                         : Lossy
Stream size                              : 14.6 MiB (100%)
Writing library                          : LAME3.99.5

In VLC

*

*Go to File > Convert / Stream...

*Drag and drop your file on the window

*Under "Choose Profile" select "Audio - MP3"

*Choose a file destination

*And click the Save button

Try to open your new file with Chrome. It should work.


text:
Q: Show that $\overline{R}(X,Y)Z=\nabla_X\nabla_YZ-\nabla_{[X,Y]}Z=-\Theta$. Exercise
I am tasked with showing the following (Exercise 2.6.13.4 in Cartan For Beginners by Ivey and Landsberg):

For $X,Y,Z\in\Gamma(TM)$, define
  $$
\overline{R}(X,Y)Z=\nabla_X\nabla_YZ-\nabla_Y\nabla_XZ-\nabla_{[X,Y]}Z.
$$
  Show that $\overline{R}$ is a tensor, i.e., it is $C^\infty(M)$-linear in all three factors, and that $\overline{R}=-\Theta$.

Definitions
After looking into it, I've noticed our text has defined some things differently than the standard definitions, so I will go over these now. (Bear with me, I probably have some gaps in understanding which will become evident here.)
1. Let $M$ be a Riemannian manifold. We define the covariant derivative of a vector field $X=x^ie_i$ to be
\begin{equation}
\nabla X:=e_i\otimes(dx^i+x^j\overline{\eta}^i_j)\in\Omega^1(M,TM)=\Gamma(TM\otimes T^*M),
\end{equation}
where (I believe) $\overline\eta^i$, $\overline\eta^i_j$ are the pullbacks of the tautological forms and their associated connection forms on $M$ through a section of the orthonormal frame bundle. Further, for $Y\in\Gamma(TM)$ we define
$$
\nabla_YX:=Y\lrcorner\nabla X=(dx^i+x^j\overline{\eta}^i_j)(Y)e_i.
$$
2. If $\eta^i$, $\eta^j$ are the tautological forms on the orthonormal frame bundle $\mathcal{F}_{\text{on}}(M)$ to $M$, we define $\tilde{\Theta}^i_j:=d\eta^i_j+\eta^i_k\wedge\eta^k_j\in\Omega^2(\mathcal{F}_{\text{on}}(M))$,
$$
\tilde{\Theta}:=\tilde{\Theta}^i_j\otimes\eta^j\otimes e_i\in\Omega^2(\mathcal{F}_{\text{on}}(M),\pi^*(\text{End}(TM))),
$$
where $\pi:\mathcal{F}_{\text{on}}(M)\to M$ is the associated projection of the frame bundle $\mathcal{F}_{\text{on}}(M)$, and lastly define $\Theta\in\Omega^2(M,\text{End}(TM))$ to be the form such that $\tilde{\Theta}=\pi^*(\Theta)$.
If there is ambiguity here that needs explaining, please let me know and I will happily do my best to clear it up.
Problems
I think it should be simple enough to show that $\overline{R}$ is a tensor (let me know if it is not), so I'm putting most of my energy into showing $\overline{R}=-\Theta$.
1. There is a hint given with this exercise which states:

Differentiating $\nabla X=e_i\otimes(dx^i+x^j\overline{\eta}^i_j)$, with $Z$ in place of $X$, gives a relationship between $\Theta$ and the second derivatives of $Z$.

I don't quite know what is meant by "differentiate." It's a one form, so does it mean to take the exterior derivative? Does it mean to take the covariant derivative again? If the latter, How would I go about doing this?
2. I've attempted to dig into definitions to hopefully find something there, but I haven't found anything, and frankly I'm not very confident that I'm doing everything correctly. This is my attempt:

Let $X=x^ie_i$, $Y=y^ie_i$, and $Z=z^ie_i$. Note
  \begin{align*}
\nabla_X\nabla_YZ&=\nabla_X\left((dz^i+z^j\eta^i_j)(Y)e_i\right)=\left(dz^j\wedge\eta^i_j+z^jd\eta^i_j+(dz^i+z^j\eta^i_j)\eta^i_j\right)(Y)(X)e_i,\\
\nabla_Y\nabla_XZ&=\nabla_Y\left((dz^i+z^j\eta^i_j)(X)e_i\right)=\left(dz^j\wedge\eta^i_j+z^jd\eta^i_j+(dz^i+z^j\eta^i_j)\eta^i_j\right)(X)(Y)e_i,
\end{align*}
  so
  $$
\nabla_X\nabla_YZ-\nabla_Y\nabla_XZ=-\left(dz^j\wedge\eta^i_j+z^jd\eta^i_j+(dz^i+z^j\eta^i_j)\eta^i_j\right)\big([X,Y]\big)e_i.
$$
  Now
  \begin{align*}
\overline{R}(X,Y)Z&=-\left(dz^j\wedge\eta^i_j+z^jd\eta^i_j+(dz^i+z^j\eta^i_j)\eta^i_j\right)\big([X,Y]\big)e_i-(dz^i+z^j\eta^i_j)\big([X,Y]\big)e_i.
\end{align*}

If correct so far (which I doubt) I don't quite know where to go next. I feel like I would be futile to spend all day working with arithmetic I'm not even confident in, so here I am. This is a homework assignment, so posting full answers would be unethical, but any comments/help/hints are greatly appreciated. Thanks in advance for even reading this post in its entirety.
EDIT:
Following Jesse Madnick's suggestion, I computed
$$
\overline{R}(e_A)(e_B)e_C=-2d\eta^C_j(e_A)(e_B)e_C,
$$
which seems to be on the right track. However, I've having trouble computing $\tilde{\Theta}=\tilde{\Theta}^i_j\otimes\eta^j\otimes e_i$; mostly, I don't understand how the tensor product $\tilde{\Theta}^i_j\otimes\eta^j$ acts on two vectors $e_A,e_B$, since $\tilde{\Theta}^i_j$ is two form and $\eta^j$ is a one form. Is it wrong to say
$$
\theta^C_j\otimes\eta^j(e_A)(e_B)=\theta^C_j(e_A)(e_B)\eta^j(e_B)?
$$
(It probably is.) Again, any clarification is greatly appreciated.

A: Here are a few tips.

*

*Once you show that $\overline{R}$ is $C^\infty(M)$-linear, then you know that
$$\overline{R}(X,Y)Z = x^i y^j z^k \overline{R}(e_i, e_j)e_k.$$
Of course, $-\Theta$ is also $C^\infty(M)$-linear.  So, it suffices to prove that $\overline{R}(e_i, e_j)e_k = -\Theta(e_i, e_j)e_k$.

In other words, you should try to compute both $\overline{R}(e_i, e_j)e_k$ and $-\Theta(e_i, e_j)e_k$.

*

*In computing $-\Theta$, it might be helpful to remember that sections $s$ satisfy $\pi \circ s = \text{Id}$, so that $\Theta = s^*(\tilde{\Theta})$.  Also useful are pullback rules like, say, $s^*(\alpha \wedge \beta) = s^*\alpha \wedge s^*\beta$ and $s^*(d\alpha) = d(s^*\alpha)$.

*A formula that may or may not be useful is the following: for any $1$-form $\alpha$ and vector fields $X,Y$, we have:
$$d\alpha(X,Y) = X\alpha(Y) - Y\alpha(X) - \alpha([X,Y]).$$


text:
Q: Generating a key for brute force I am trying to decrypt a file via brute-force. I am only worried about the ASCII characters 32-127(All possible keyboard characters). The key needs to be a two character key. I am starting my for-loop like this:
    for(int i = 32; i < 128; i++){
        //Key is a string already declared further up.
        key = Character.toString((char) i);
    }

I have printed that and it gives me all keys on the keyboard. I am stuck on how to make the two character string,
I have a few ideas in mind but they do not work. I thought about trying to just do something similar to this:
if(key.length() > 2)
     key = "";
else
     key += key(i);

but I think that will only give me characters that are "back-to-back" to each other.
I need to test for like 32 with 33-127 and so on and so for. Any insight would be highly appreciated. Thank you.

A: The best way to brute force this would be a nested for loop
for(int i = 32; i < 128; i++){
        //Key is a string already declared further up.
        for(int j = 32; j < 128; j++){
             key = Character.toString((char) i) + Character.toString((char) j);

        }
    }

This says for every character, pair it with every character, so you would get all combinations of 2 character codes. You can do the checking right after you set the key

A: Did you try double for loop, something like this:
String key;
for(int i = 32; i < 128; i++){
    for(int j = 32; j < 128; j++){
        //Key is a string already declared further up.
        key = (char)i+""+(char)j;
        System.out.println("Key: " + key + ", " + key.length());
    }
}


text:
Q: JSTL  body content exact specification can someone suggest how possible to interpret <c:set> body?

*

*<c:set var="movieList">One,Two,Three</c:set>

*<c:set var="movieList">"One","Two","Three"</c:set>
in the first case movieList is a string and in the second it is an array {"One", "Two", "Three"}
what is movieList in these examples:

*

*<c:set var="movieList">"On"e","Tw"o","Thr"ee"</c:set>

*<c:set var="movieList">"On\"e","Tw"o","Thr\"ee"</c:set>

A: There's no difference in the interpreted Java type of the c:set's body. It are in all cases just String.
Even when you set a non-String type as c:set's body using EL such as
<c:set var="foo">${bean.someInteger}</c:set>

it'll be converted to String anyway by String#valueOf().
Only when you process the variable afterwards, there may be difference, depending on how you processed it. For example,
<c:set var="movieList">One,Two,Three</c:set>
<c:set var="realMovieArray" value="${fn:split(movieList, ',')}" />

will result ${realMovieArray} being a String[] with values of One, Two and Three.

A: <c:set var="alphabet">A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z</c:set>

<c:forTokens items="${alphabet}" delims="," var="letter">
    ${letter}
</c:forTokens>


text:
Q: Двумерные массивы, в матрице все списки принимают одни значения Решал задачу на проекте Эйлера(https://projecteuler.net/problem=15)
При работе с матрицей входящие в нее массивы принимают одни значения.
Что я делаю не так ?
тут код для квадрата 3х3.
mas = [[0] * 3] * 3
mas[0] = [1, 1, 1]
for i in range(3):
    mas[i][0] = 1

for l in range(3):
    for j in range(3):
        if mas[l][j] == 0:
            mas[l][j] = mas[l-1][j] + mas[l][j-1]
            print(mas[l-1][j] + mas[l][j-1])

изначально матрица выглядит так:
[1, 1, 1]
[1, 0, 0]
[1, 0, 0]

после должно получиться такое:
[1, 1, 1]
[1, 2, 3]
[1, 3, 6]

НО получается,что массив номер 1 (после[1,1,1]),присваиваит свои значения другим и на выходе получаем:
[1, 1, 1]
[1, 2, 3]
[1, 2, 3]

A:

mas = [[0 for l in range(3)] for j in range(3)]
mas[0] = [1, 1, 1]
for i in range(3):
    mas[i][0] = 1
print(mas)

for l in range(3):
    for j in range(3):
        if mas[l][j] == 0:
            mas[l][j] = mas[l-1][j] + mas[l][j-1]
            print(mas[l-1][j] + mas[l][j-1])
print(mas)

Ошибка в способе задания матрицы. 2-я и 3-я строки матрицы у вас являются ссылками на 1-ю строку.


text:
Q: I have a structure variables with similar names, how to print them out in c I have similar struct variables. How to print their data using loops.

struct employee{
int cardNo;
char name[20];
char surname[20];
long salary;
int age;
};
struct employee emp1={1,"abc","xyz",70,000,30}; //I have similar variables named emp2, emp3.....till emp20

int main()
{
   //i need to print the salary of all 20 employees using a loop. How to do it?
    return 0;
}

A: Instead of having a separate variable for each employee, make an array of them:
struct employee emps[] = {
    {1,"abc","xyz",70,000,30},
    {2,"def","zzz",60,400,20},
    ...
}

And loop through them.

A: You can define an array of structures so that you can do this in the loop. However, it may be easier to write a print function instead of doing this.
#include <stdio.h>

typedef struct employee
{
    int cardNo;
    char name[20];
    char surname[20];
    long salary;
    int age;
}Employee;

void print_employee_information(const struct employee *p)
{
    printf("%d %s %s %ld %d\n", p->cardNo, p->name, p->surname, p->salary, p->age);
}

int main()
{

    struct employee emps[] = {
        {1, "abc", "xyz", 70, 000},
        {2, "def", "zzz", 60, 400},
    };

    for(int i = 0; i < 2; ++i) {
        Employee *p = (emps+i);
        print_employee_information(p);
    }
    return 0;
}

A: Store them in array, like this:
struct employee emps[] = {
    { 1, "abc", "def", 20, 000 },
    { 2, "ghi", "jkl", 20, 001 },
    ...
};

or like this
struct employee emps[] = {
    emp1,
    emp2,
    ...
};

and then you can go through them like this:
for(i = 0; i < empLastIndex; i++)
{
    ...
    emps[i]
    ...
}


text:
Q: Python, finding the max value of an array above a specific value and it's index New to python, I need to find the maximum value of an array above a lower bound,
example [1,2,3,4,5 6] find max value above 3 and what's it index position. In reality, I have one column with wavelength/energy(eV) and another (several columns) with intensity and I am trying to figure out what is the maximum intensity and it wavelength position, ignoring the laser peak which is a certain wavelength below the true data.
I tried something like this
df=pandas read file ['....']

column_names = ['a','b',....]

def find_max(x, y, xMax):
    return np.max(y[x < xMax])

xMax = 1.9

for i in range(len(column_names)):
    max_int_val = find_max(df['eV'], df[column_names[i]], xMax)
    max_wav_index = df[column_names[i]].idxmax(max_int_val)
    max_wav_val = df["Wavelength"].iloc[max_wav_index]
    max_eV_val = df["eV"].iloc[max_wav_index]

yet the max_int_val seems to be correct but the max_wav_index, max_wav_val and max_eV_val appear to be wrong.
I believe what is happening is that the index is using the entire column and not the truncated one when finding the index.

A: I'm not sure if I understood your issue but i've came up with this
def findMax(tab,maxColumn,minimum): #maxColumn is the column you want to use,intensity in your case
    maximum=minimum
    index=-1#if it's still -1 no element was found
    for i in range(0, len(tab[maxColumn])):
        if tab[maxColumn]>maximum :
            maximum=tab[maxColumn]
            index=maxColumn
    return(maximum, index)

#then you can use index to get the wavelength with something like that : tab[wavelengthColumn][index]

if you have multiple intensity columns you can call this function for each and buil an array with the results that you will send again to this function
Something like that :
array=[........]
intensityColumns=1
maximums=[[][]]
for i in range (0,intensityColumns):
    maximum,index=findMax(array,FIRST_INTENSITY_COLUMN+i,MINIMUM)#here I suppose every intensity column is following the first one
    maximums[0].append(array[wavelengthColumn][index])
    maximums[1].append(maximum)
resultMax,resultIndex=findMax(maximums,1,MINIMUM)

A: We can find by:

*

*Finding list of indexes in sequence which are above threshold

*Finding max of values in these indexes

Code
import pandas as pd
import numpy as np

def find_max(a, lower_bound):
    ' Finds max above threshold '

    # Find indexes which are above threshold
    valid_idx = np.where(a >= lower_bound)[0]

    if valid_idx.size > 0:
        # Find maximum from these indexes
        max_idx = valid_idx[a[valid_idx].argmax()]
        return max_idx, a[max_idx]     # return index and max value

Test
data = [(1, 1), (2, 0), (10, 2), (5, 0)]
df = pd.DataFrame(data, columns  = ['a','b'])
print("DataFrame\n", df)
print()

# Find max in each column of DataFrame above lower bound
lower_bound = 8
for (column_name, column_data) in df.iteritems():
    found_max = find_max(column_data, lower_bound)
    if found_max:
        print(f'Column {column_name}: max index {found_max[0]}, max_value: {found_max[1]}')
    else:
        print(f'Column {column_name}: No max found')

Output
DataFrame
     a  b
0   1  1
1   2  0
2  10  2
3   5  0

Column a: max index 2, max_value: 10
Column b: No max found


text:
Q: FTP does not work properly when connected to OpenVPN I am connected to an OpenVPN server and would like to list all files on a FTP server.
ftp> ls
500 I won't open a connection to 10.125.1.20 (only to 31.x.x.100)
ftp: bind: Address already in use
ftp>

The tun interface has the IP 10.125.1.20 and it seems my FTP client (which is the ftp command in Linux) reports that IP to the FTP server and not the IP provided by the OpenVPN server.
Can I make something with iptables forwarding to get it working?

A: It seems you're running your FTP client on an host that is connected to an OpenVPN server and your traffic is routed inside the VPN (so, for the external world, your source IP address is the one of the external interface of your OpenVPN server).
Is it true?
If no.... please give us details.
If yes, than your problem relates exactly to the OpenVPN "box" that:

*

*is correctly NATting your "standard" IP connections (and, in fact, you're able to succesfully connect to the remote FTP server)

*is NOT properly NATting the FTP protocol (that, unfortunatly, is not much NAT-friendly and, to be NATted, require special treatments).
To solve your problem you should ensure that proper kernel-module is loaded on your NAT box (OpenVPN). In my Ubuntu (and probably also on CentOS 6):
 # modprobe nf_conntrack_ftp

Such module will carefully watch all the traffic flowing along FTP "control" connection (the one you're able to establish, to authenticate and to "launch" file trasnsfers) to check what client-ports your FTP client has declared to use for file-trasfers and properly "mangling" control-connection (to "fake" such ports, by imposing NAT box ones).
In other words:

*

*without above modules:

*

*1) FTP client establish FTP connection to remote-server;

*2) FTP client want to start a file-transfer (a simple "ls"). As such...

*3) ...FTP client "open" a TCP port so for the FTP server to connect back to such port to transmit contents;

*4) ...FTP client "tell" FTP server which port has been opened, using the control-connection established at point 1)

*5) unfortunatly, without "special treatment", your remote FTP server, that is correctly reading/writing along the connection established at point 1), receive the couple IP/PORT specified at step 4) that contains your "private" IP address.

*6) so the FTP server see that control connection comes from an IP while data-connection relates to a different IP. It (correctly) dislike such a scenario, as it could lead to some reflection/DDOS scenario. As such, it sends you the error message you see.

.

*

*with above module loaded

*

*everything is like above, except for step 5. Such step became...

*5) your NAT-box, thanks to the conntrack_ftp module, open an own TCP PORT (on the external interface) and gets ready to receive back FTP data-traffic on such ports. Once received it relay such traffic back to your FTP client. Also, the "control-connection" is mangled, so to replace the couple IP/PORT sent by your client with the IP/PORT of the NAT-box.

*...and thanks to this, everything should work smoothly :-) (...or, at least, I hope).


text:
Q: Is datalog more efficient than SQL for column oriented databases? Both Cascalog and Datomic have chosen to use Datalog (over SQL) as their query engine.
Dave Thomas made the claim:

Datalog is better than SQL for large queries in small amounts of space.

My question is: Is datalog more efficient than SQL for column oriented databases?


text:
Q: формат Json и MySQL Всем привет.
На главной странице есть скрипт, который прогружает файл do_rating.php, который создает/пересоздает и заполняет json файл данными от запроса.
(Файл всегда пустой, но данные есть, делал запрос в workbench MySqL)
Скрипт

А вот и содержание do_rating.php...
<?php
require_once 'connection.php';
$link = mysqli_connect($host, $user, $password, $database)
or die ("Не могу создать соединение");

$query = "select
                categories.name as category,
                count(goods.id) as numbers
          from
                categories left join goods on categories.id = goods.id_category
          group by
                categories.name
          order by
                numbers desc;";

$result = mysqli_query($link, $query)
or die("Не могу выполнить запрос");

if($result) {
    $json_result = [];  // массив для данных, полученных из запроса
    $rows = mysqli_num_rows($result); // количество полученных строк

    for ($i = 0 ; $i < $rows ; ++$i) {
        $row = mysqli_fetch_row($result);
        array_push($json_result, ['category'=>$row[0], 'numbers'=>$row[1]]);
    } // for

    // кодировать массив в формат JSON
    $json_res = json_encode($json_result);
    file_put_contents('../json/goods_rating.json', $json_res);

    // очищаем результат
    mysqli_free_result($result);
} // if

mysqli_close($link);
?>

У других людей код работает, у меня же - нет.
Все же логично, данные с запроса json_encod-ю в строку формата json, сохраняю в файл, а на главной странице идет считывание этого файла через getJSON в строки таблицы...но пустота...Помогите пожалуйста.
Добавил
Jquery подключен, но phpstorm не видит метод $.post, все остальное прекрасно понимает, может, в интерпретаторе дело?


text:
Q: How to skip protected and blocked Twitter accounts (Twitter API, Tweepy) I don't have much coding experience so bear with me. I'm trying to collect tweets from a list of accounts using the Twitter API but I have the issue of my python program stopping every time it runs into a Tweepy 401 unauthorized errors due to protected or blocked accounts.
Originally, I would just remove the account from the list and re-run the program. This is very inefficient so I'm looking for a work around for the program to keep running after it runs into the 401 error.
This is what my code looks like:
import csv
import pandas as pd
####input your credentials here
consumer_key = '####################'
consumer_secret = '####################'
access_token = '######################'
access_token_secret = '#############################'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True,)
# Open/Create a file to append data
csvFile = open('ab.csv', 'a', encoding='utf-8_sig')
#Use csv Writer
csvWriter = csv.writer(csvFile)
# Pulling individual tweets from specified screen name
for tweet in api.user_timeline(screen_name='USER1', tweet_mode='extended', count=1):
    print (tweet.created_at, tweet.user.screen_name, tweet.full_text, tweet.user.protected)
    csvWriter.writerow([tweet.created_at, tweet.user.screen_name, tweet.full_text])
for tweet in api.user_timeline(screen_name='USER2', tweet_mode='extended', count=1):
    print (tweet.created_at, tweet.user.screen_name, tweet.full_text, tweet.user.protected)
    csvWriter.writerow([tweet.created_at, tweet.user.screen_name, tweet.full_text])
for tweet in api.user_timeline(screen_name='USER3', tweet_mode='extended', count=1):
    print (tweet.created_at, tweet.user.screen_name, tweet.full_text)

When the program runs into a protected or blocked account it gives the following errors and stops running.
ERROR 1:
Traceback (most recent call last):
  File "C:\Users\cosmi\OneDrive\Documents\Twitter API\Twitter API\tweet collector (skiptest) - Copy - Copy.py", line 20, in <module>
    for tweet in api.user_timeline(screen_name='USER1', tweet_mode='extended', count=1):
  File "C:\Users\cosmi\AppData\Roaming\Python\Python310\site-packages\tweepy\api.py", line 33, in wrapper
    return method(*args, **kwargs)
  File "C:\Users\cosmi\AppData\Roaming\Python\Python310\site-packages\tweepy\api.py", line 46, in wrapper
    return method(*args, **kwargs)
  File "C:\Users\cosmi\AppData\Roaming\Python\Python310\site-packages\tweepy\api.py", line 571, in user_timeline
    return self.request(
  File "C:\Users\cosmi\AppData\Roaming\Python\Python310\site-packages\tweepy\api.py", line 257, in request
    raise Unauthorized(resp)
tweepy.errors.Unauthorized: 401 Unauthorized
136 - You have been blocked from viewing this user's profile.

ERROR 2:
Traceback (most recent call last):
  File "C:\Users\cosmi\OneDrive\Documents\Twitter API\Twitter API\tweet collector (skiptest) - Copy - Copy.py", line 20, in <module>
    for tweet in api.user_timeline(screen_name='USER2', tweet_mode='extended', count=1):
  File "C:\Users\cosmi\AppData\Roaming\Python\Python310\site-packages\tweepy\api.py", line 33, in wrapper
    return method(*args, **kwargs)
  File "C:\Users\cosmi\AppData\Roaming\Python\Python310\site-packages\tweepy\api.py", line 46, in wrapper
    return method(*args, **kwargs)
  File "C:\Users\cosmi\AppData\Roaming\Python\Python310\site-packages\tweepy\api.py", line 571, in user_timeline
    return self.request(
  File "C:\Users\cosmi\AppData\Roaming\Python\Python310\site-packages\tweepy\api.py", line 257, in request
    raise Unauthorized(resp)
tweepy.errors.Unauthorized: 401 Unauthorized
Not authorized.

How do I alter my code so that my program will skip any protected and/or blocked accounts and continue running until the end of my user list. Like I said, I have very little coding experience and am trying to figure this out myself so the simplest solution that doesn't require rewriting my code much is what I'm looking for.
Any and all help is appreciated. Thank you.


text:
Q: FD Leak, how should I refactor code? I have read the post
My service code like the following:
type httpResponse struct {
    StatusCode int
    Header     http.Header
    Body       []byte
}

var client *http.Client

func init() {
    client = &http.Client{
        Transport: &http.Transport{
            Proxy: http.ProxyFromEnvironment,
            DialContext: (&net.Dialer{
                Timeout:   30 * time.Second,
                KeepAlive: 30 * time.Second,
            }).DialContext,
            MaxIdleConns:          100,
            MaxIdleConnsPerHost:   100,
            IdleConnTimeout:       90 * time.Second,
            TLSHandshakeTimeout:   10 * time.Second,
            ExpectContinueTimeout: 3 * time.Second,
        },
    }
}

func sendRequest(url string) (httpResponse, error) {
    var res httpResponse
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return res, err
    }
    resp, err := client.Do(req)
    if resp != nil {
        res.StatusCode = resp.StatusCode
        res.Header = resp.Header
    }
    if err != nil {
        return res, err
    }
    defer resp.Body.Close()
    res.Body, err = ioutil.ReadAll(resp.Body)
    if err != nil {
        return res, err
    }
    return res, nil
}

func InteractByKey(key string) (Info, error) {
    host := "http://test.baidu.com"
    url := fmt.Sprintf("%s/test/2.0/info?method=select&key=%s", host, key)

    for intRetry := 0; intRetry < 3; intRetry++ {
        resp, err := sendRequest(url)
        if err != nil {
            continue
        }
        if resp.StatusCode >= 500 {
            continue
        }
        if resp.StatusCode >= 400 && resp.StatusCode < 500 {
            continue
        }
        arrRes, err := unpackInfo(resp.Body)
        return arrRes[0], err
    }
    return Info{}, &ErrGetInfoFailed
}

And my client code like the following using Python, the InteractByKey of service is visited by client and one request at a time:
#!/usr/bin python
#coding=utf-8

import requests

# address is the ip of machine A
url = "http://10.95.35.14:8099/test/2.0/check?method=InteractByKey&key="

def _send_request(url):
    session = requests.Session()
    session.keep_alive = False

    resp = None
    try:
        resp = session.get(url)
    except:
        if resp is not None:
            resp.connection.close()
            return (False, url)
    if resp is None or resp.status_code != 200:
        if resp is not None:
            resp.connection.close()
        return (False, url)
    try:
        data = resp.json()
    except:
        if resp is not None:
            resp.connection.close()
            return (False, url)
    if resp is not None:
        resp.connection.close()
    try:
        if data['result'][0]['mark_result']['success'] is False:
            return (False, data)
    except:
        return (False, url)
    return (True, data)

with open('test.txt') as f:
    for line in f:
        key = line.strip()
        urls = url + key
        res = _send_request(urls)
        if res[0] is True:
            print "OK " + key + " " + str(res[1])
        else:
            print "Error " + key + " " + str(res[1])

Machine A run my service program(Go language), and machine B run my client program(Python language).
When I send request by client program to service, my fd of service(Go) machine will always add, like this:
$ lsof -p 18464 | wc -l
182
$ lsof -p 18464 | wc -l
199
$ lsof -p 18464 | wc -l
876
$ lsof -p 18464 | wc -l
1580
$ lsof -p 18464 | wc -l
2107
$ lsof -p 18464 | wc -l
2709
$ lsof -p 18464 | wc -l
2910

When the number reach about 8000, sendRequest will timeout, it can not run or restart my service program.
So, how should I rewrite my code?


text:
Q: Timout between Web and WCF calls My question is if I make a call from my web front-end to the wcf to execute some database logic but it times out from the web front-end, does the database still continue executing the query?

A: If it times out from the web front-end, then the database will still continue to execute the query.
To make it clearer if your web front-end has a timeout set to 30 seconds and your database call has a timeout set to 60 seconds, there is a high chance that your front-end will result in a timeout, but your database operation would be completed in about 45 seconds.
I have faced a similar issue in a Android app facing a timeout and the called REST service still completed the operation.


text:
Q: fibonacci! if goes false all time I made a program to find if a number belongs to fibonacci series or not and if it does whats its position.Whenever i type a number the if Condition goes wrong.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(void)
{
    int i,x=1,y=1,z,num;
    clrscr();
    printf("Enter a number to find in fibonacci series:");
    scanf("%d",&num);
    /*to find if the number is a part of fibonacci series or not*/
    if((isdigit(sqrt(5*num*num+4)))||(isdigit(sqrt(5*num*num-4))))  //<-- this if!
    {//belongs to fibo!
        for(i=1;    ;i++)
        {
            if(x==num)
            break;
            z=x+y;
            x=y;
            y=z;
        }
        printf("%d is the %d term of fibonacci series.",num,i);
    }
    else
        printf("Dear user,The entered number is not a part of the fibonacci series.");

    getch();
}

A: You're misunderstanding the isDigit function.
isDigit takes an ASCII character code and returns true if it represents a decimal digit.
You want to check whether the double returned by sqrt is an integer.

A: There's an obvious error in your use of isdigit(). That function (usually macro) is used to tell if a character is one of the characters 0..9 - certainly your code is dealing with numbers consistently and there's no need for character checking.
You'll want to take a closer look at what you're trying to accomplish. You're welcome to ask us which C functions might be suitable.

EDIT:
Ah, you want to know if that funky expression is an integer value. Alas, there's no built-in function for that. I haven't tested this, but I'd write
double a = (funky expr);
if (a == rint(a)) ...

... where rint() is a function that returns the double that's the nearest integer value to the given argument.

A: Why are you using isdigit? The result of sqrt is a double - you need to check that value directly.

A: You want to check if 5 * num * num + 4 or 5 * num * num - 4 is a perfect square.  A function that will do this is:
int is_perfect_sq(double d)
{
    double sqroot = rint(sqrt(d));

    return (sqroot * sqroot) == d;
}

Note - this is a good disproof of the notion that you should never compare floating point numbers for equality.  In this case, it is fine, since a "perfect square" must be an integer.


text:
Q: GCC - shouldn't a warning be issued when assigning an int to a char? I've recently set up a MinGW + MSYS environment on my laptop to check how things are with Netbeans C/C++ support. Everything seems to work fine, however, during my testing I have noticed a difference between GCC and Microsoft's cl.exe compiler.
Here's a sample program:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main(void) {
    int i_max = INT_MAX;
    char c_max = CHAR_MAX, c;

    c = i_max;
    printf("i_max: %d, c_max: %d, c: %d\n", i_max, c_max, c);
    return EXIT_SUCCESS;
}

The output is:
i_max: 2147483647, c_max: 127, c: -1

As you can see in the code above, I assign an int to a char. Shouldn't this produce a warning that a possible data loss may occur? Microsoft's compiler (which I have configured to be very strict) does issue the warning while GCC doesn't.
Here are the GCC options I use:
-g -Werror -ansi -pedantic -Wall -Wextra

Am I missing some GCC option to make the compile time checks even stricter?

A: You're looking for
-Wconversion

You'd have to ask a gcc developer for the specific reasons why some warnings aren't included in -Wall or -Wextra.
Anyway, these are the flags I use:
-Wall -Wextra -Wmissing-prototypes -Wmissing-declarations -Wshadow
-Wpointer-arith -Wcast-align -Wwrite-strings -Wredundant-decls -Wnested-externs
-Winline -Wno-long-long -Wconversion -Wstrict-prototypes

As other's have pointed out, the behaviour of -Wconversion changed with version 4.3 - the old warning about prototypes forcing a type conversion is now available as -Wtraditional-conversion.

A: -Wall doesn't quite mean -Wall, -Wextra is already under fire for being a little overly pedantic.
As Christoph said, you are looking for -Wconversion. Its good to really dig in to what -Wall and -Wextra actually turn on, and just specify the -W flags you want in your make file, especially if treating warnings as errors.

A: Theres a little nuance in your question that is not immediately obvious to me from the way it is worded.
If you think GCC (specifically GCC) should issue a warning here, then some compiler options might possibly help (see other replies).
If you think any compiler should issue a warning here (and I seem to read that sentiment in your question), then... well, "warnings" are not in any way mandatory or even de-facto unified. There's no "should" here. Assigning a larger-typed integer value to a smaller type without an explicit cast is pefectly legal in C. Overflow on conversion, produces implementation-defined behavior (it is not even UB :))

A: I didnt get a warning/error with -Wconversion either. However, if you give a pass with something like splint you get three warnings:
file.c: (in function main)
file.c:9:5: Assignment of int to char: c = i_max
  To make char and int types equivalent, use +charint.
file.c:10:52: Format argument 2 to printf (%d) expects int gets char: c_max
   file.c:10:32: Corresponding format code
file.c:10:59: Format argument 3 to printf (%d) expects int gets char: c
   file.c:10:39: Corresponding format code

Finished checking --- 3 code warnings

If you are serious about catching all errors you should use more than one tool.

A: In C, assigning an int to a char is legal.
As it's legal (but possibly dodgy) the different compiler vendors do different things when they encounter this code.
I guess MS is just being extra pedantic while the GCC guys have decided that it's not even worth a warning.

A: I think it falls under the "Usual arithmetic conversions" (6.3.1.8) or "integer promotion rules" (5.1.2.3 (?)), but I can't find the specific text that says the behaviour you're seeing is expected.


text:
Q: Ubuntu Studio 20.10: Audio Drivers not playing well together ft. Alsa, Jack, and Pulseaudio I've done a lot of searches and read a lot of man pages before coming here but I must not be asking the right questions in my searches and evidently have a lot to learn about these audio controls.
My question is, how do I route audio to my headphones? When I searched for this issue online I found a lot of situations where people were able to fix it with something simple using:
alsactrl
jack_control
or something similar. All of which did nothing to help my situation.
I don't really need to route audio in such a complex way at this point. I understand it helps with music production by decreasing the latency but another solution would be to remove Jack altogether. However, when I removed Pulse the first time I had to reinstall it just to configure audio at all since apparently the pulseaudio package contains Studio Settings where I can configure bridges and such. I'm scared of having to do a fresh install again though so now I'm here.
Upon checking the Jack audio website, I see it's not recommended that you use Pulse and Jack together. Well, Ubuntu Studio 20.10 ships with them both installed. I'm on my second fresh install, this time on my ssd because it seemed more important than Windows.
I should note, this is my first post and I'm a full-time BioE student so I apologize if I've either neglected to honor etiquette or if I didn't spend enough time searching this. Time is sacred and headphones are very useful for these classroom Zoom meetings.


text:
Q: Open Video From Intent Xamarin I can't run an intent to play a video from a folder saved in external storage specifically in DCMI/subdirectory.
Using this code I get the error:
'file:///storage/emulated/0/DCIM/subdirectory/video-213102-113126.mp4 exposed beyond app through Intent.getData()'

Java.IO.File file = new Java.IO.File(file_path);
Intent intent = new Intent();
intent.AddFlags(ActivityFlags.NewTask);
intent.SetAction(Intent.ActionView);
intent.SetDataAndType(Android.Net.Uri.FromFile(file), "video/mp4");
Xamarin.Forms.Forms.Context.StartActivity(intent);

Reading I saw that I have to use a Fileprovider so I tried with this code:
Java.IO.File file = new Java.IO.File(file_path);
Android.Net.Uri photoURI = AndroidX.Core.Content.FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".provider", file);
Android.Content.Intent intent = new Android.Content.Intent(Android.Content.Intent.ActionView);
intent.SetDataAndType(photoURI, "video/*");
Xamarin.Forms.Forms.Context.StartActivity(intent);

AndroidManifest:
<application android:label="MYAPP.Android" android:theme="@style/MainTheme" android:requestLegacyExternalStorage="true">
        <activity android:name=".MainActivity"
            android:screenOrientation="portrait"
            android:configChanges="keyboard|keyboardHidden|orientation" />

        <activity android:name=".CameraActivity"
            android:screenOrientation="portrait"
            android:configChanges="keyboard|keyboardHidden|orientation" />

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>

    </application>

provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>

In debugging I see that the file variable is /storage/emulated/0/DCIM/subdirectory/video-213703-033712.mp4}
and photoURI is {content://com.companyname.myapp.provider/external_files/DCIM/subdirectory/video-213703-033712.mp4}
Intent is launched but the video is not played probably because it does not find the file in the path


text:
Q: includeInDownload not work - Supplemental Document I have an envelope with some documents, and one of them I do not want to be concatenated when you download the documents using the combined option. By reading the documentation, I found the includeInDownload attribute that can be passed to the documents when creating an envelope. But when I am creating the envelope, it seems that this attribute is being ignored, because after creating the envelope, I search the documents and the includeInDownload attribute is true. The envelope creation JSON:
{
  "status": "created",
  "emailSubject": "Example envelope",
  "emailBlurb": "Example",
  "documents": [{
    "documentId": "1",
    "name": "Test 1",
    "remoteUrl": "URL"
  },
  {
    "documentId": "2",
    "name": "Test 2",
    "remoteUrl": "URL",
    "includeInDownload": "false"
  }],
  "recipients": {
    "signers": [{
      "name": "Lisa Simpson",
      "email": "lisa@email.com",
      "recipientId": "1",
      "clientUserId": "1"
    }]
  }
}

A: You need to use the 'display' attribute as well for what we call "supplemental" documents.
If  display=modal, the associated document is a supplement.
If display=inline, it's not a supplement.


text:
Q: how to send one component form input data to my parent component to submit the form I have three child component with form in each and one parent component, i want to inject all three child component forms to my parent component and do a submit.My goal is to display all three form data in json format.
Child 1:
import React, { Component } from 'react';
import { PropTypes } from 'react'

class Input extends Component {

  constructor(props){
    super(props);

    this.state = {
      id: '',
      inputType: '' ,
      inputFilePath: '',
      inputSchemaFilePath: '' ,
      streamName: '',
      processor: '',
      unit: ''
    }
    this.handleInputChange = this.handleInputChange.bind(this)
    //this.handleSubmit = this.handleSubmit.bind(this)
}

handleInputChange = e => {
    console.log(e.target.value);
    //this.setState({[e.target.name] : e.target.value});
    this.setState({
      id: e.target.value,
      inputType: e.target.value,
      inputFilePath: e.target.value,
      streamName: e.target.value,
      processor: e.target.value,
      unit: e.target.value
    });

  };

  render() {

    return (
      <form>

Input:

 Id : <input type="text" size="100" name="id" value={this.state.id} onChange={this.handleInputChange} />

 InputType : <input type="text" size="100" name="inputType" value={this.state.inputType} onChange={this.handleInputChange} />

 InputFilePath : <input type="text" size="100" name="inputFilePath" value={this.state.inputFilePath} onChange={this.handleInputChange}/>

 InputSchemaFilePath : <input type="text" size="100" name="inputSchemaFilePath" value={this.state.inputSchemaFilePath} onChange={this.handleInputChange}/>

 StreamName : <input type="text" size="100" name="streamName" value={this.state.streamName} onChange={this.handleInputChange}/>

 Processor : <input type="text" size="100" name="processor" value={this.state.processor} onChange={this.handleInputChange} />

 Unit : <input type="text" size="100" name="unit" value={this.state.unit} onChange={this.handleInputChange} />

          <button> +</button>
          <button> -</button>

      </form>
    );
  }
}
export default Input

Child 2
import React, { Component } from 'react';
import { PropTypes } from 'react'

class Output extends Component {

   constructor(props){
    super(props);

    this.state = {
      id: '',
      outputType: '' ,
      saveMode: '',
      outputFilePath: '' ,
      outputSchemaFilePath: '',
      dependentIds: '',
      outputPartitionKeys: '',
      processor: ''
    }
    this.handleOutputChange = this.handleOutputChange.bind(this)
    //this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleOutputChange = e => {
    console.log(e.target.value);
    this.setState({
      id: e.target.value,
      outputType: e.target.value,
      saveMode: e.target.value,
      outputFilePath: e.target.value,
      outputSchemaFilePath: e.target.value,
      dependentIds: e.target.value,
      processor: e.target.value
    });
  };
  render() {

    return (
      <form>

Output:

 Id : <input type="text" size="100" name="id" value={this.state.id} onChange={this.handleChange} />

 OutputType : <input type="text" size="100" name="outputType" value={this.state.outputType}  onChange={this.handleChange}/>

 SaveMode : <input type="text" size="100" name="saveMode" value={this.state.saveMode} onChange={this.handleChange} />

 OutputFilePath : <input type="text" size="100" name="outputFilePath" value={this.state.outputFilePath} onChange={this.handleChange} />

 OutputSchemaFilePath : <input type="text" size="100" name="outputSchemaFilePath" value={this.state.outputSchemaFilePath} onChange={this.handleChange} />

 DependentIds : <input type="text" size="100" name="dependentIds" value={this.state.dependentIds} onChange={this.handleChange} />

 OutputPartitionKeys : <input type="text" size="100" name="outputPartitionKeys" value={this.state.outputPartitionKeys} onChange={this.handleChange} />

 Processor : <input type="text" size="100" name="processor"  value={this.state.processor} onChange={this.handleChange}/>

            <button> +</button>
            <button> -</button>

        </form>
    );
  }
}

export default Output

similarly there is one more component .
Parent Component :
import React, { Component } from 'react';

import Input from './input';
import Transformation from './transformation';
import Output from './output';
import JSONPretty from 'react-json-pretty';
import { PropTypes } from 'react'

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
        };
        this.handleSubmit = this.handleSubmit.bind(this);

      }

  handleSubmit(values) {
    console.log(values)

    this.setState({ values })
    //code
  }

  render() {
     return (

Header

        Please fill all the required fields marked with *

<Input />

<Transformation />

<Output />

              <button onClick={this.handleSubmit.bind(this)}>Show JSL</button>
          <JSONPretty id="json-pretty" data={this.data}></JSONPretty>

        );
    }
}export default Parent

Can anyone suggest what code should go to in parent component ??

A: If your goal is to retrieve the input data from Child1 and Child2 in Parent component you will have to manage their state in the Parent component. You can then pass it down as Props to Child1 and 2
This will allow you to validate your Child's logic inside handleSubmit(values) {...}  in the Parent component


text:
Q: Fast calculation of Fibonacci numbers
*

*I was wondering how can i find $n$-th Fibonacci number using the recurrence equation
$F(n)=F(n-1)+F(n-2)$

*if starting $a$,$b$ is given some different random number say $a=5$,$b=8$ than $c=a+b$

*than it follows $5,8,13,21,34$.

*After googling, I came to know about Binet's formula but it is not appropriate
for values of $n>79$. And also it's for Fibonacci series starting from $0,1,1,2$ so on.

*Is there way to calculate it fast like a mathematical formula.

*[Edit] I tried using computer to calculate using dynamic programming, but it is taking long for say $n=2000000$.

A: Given $F_n$ and $F_{n+1}$, you can "double" the index by using the formulas $$\begin{cases}
F_{2n}=F_{n}(2F_{n + 1} - F_{n}) \\
F_{2n + 1} =F_{n}^2 + F_{n + 1}^2.
\end{cases}$$
More details can be find here: Fast doubling.

A: Binet's formula is fine for any $n$.  If it overflows on your computer, you need to have some way to handle large numbers.  Python switches over to arbitrary precision integers automatically.
If you use different starting numbers, the constants multiplying $\phi^n$ and $\psi^n$ change, but the basic formula does not.  Your formula will be $a\phi^n+b\psi^n$ and you can evaluate $a,b$ from your starting numbers.


text:
Q: How to check if css_selector currently exist in selenium python I'm having a struggle making a code having a loop, and sometimes it give me an error so I have to exit the site and reenter, so I want a code that checks if the error is there(the css_selector exists)

A: Try and Except can be used to check whether element exist or not
Create some module like common.py and place the method or you can write it in same file. depend on you
from selenium.common.exceptions import NoSuchElementException

def is_element_exist(driver, locator):
    try:
        driver.find_element_by_css_selector(locator)
        return True
    except NoSuchElementException:
        return False

Now call it from where you require to check whether element exist or not
if is_element_exist(driver, 'css_locator'):
    print('element exist')
else:
    print("element doesn't exist")


text:
Q: drawString in if statment not working in java got some simple brick breaker game code here. When the player loses im tring to get 2 messages to appear. In the if statment, the rest of the code works as expected but the 2 strings dont appear. Any help would be appriciated thanks.
public void paint(Graphics g) {
        //background
        g.setColor(Color.black);
        g.fillRect(1, 1, 692, 592);
        //drawing map
        map.draw((Graphics2D) g);
        //borders
        g.setColor(Color.yellow);
        g.fillRect(0, 0, 3, 592);
        g.fillRect(0, 0, 692, 3);
        g.fillRect(681, 0, 3, 592);
        //scores
        g.setColor(Color.white);
        g.setFont(new Font("serif", Font.BOLD, 25)); //this shows
        g.drawString(""+score, 500,30);
        //paddle
        g.setColor(Color.green);
        g.fillRect(playerX, 550, 100, 8);
        //ball
        g.setColor(Color.yellow);
        g.fillOval(ballposX, ballposY, 20, 20);
        g.dispose();
        if(ballposY > 550) {
            play = false;
            ballXdir = 0;
            ballYdir = 0;
            g.setColor(Color.RED);
            g.setFont(new Font("serif", Font.BOLD, 30));
            g.drawString("Game Over, your score is: ", 200, 200); // this dosent

            g.setFont(new Font("serif", Font.BOLD, 20));
            g.drawString("Press Enter to Restart", 230, 250); //this dosent

        }

    }


text:
Q: Simple iteration on 100 object to create id list is super slow I'm using pymongo to retrieve a cursor of 100 objects. The object only contain one key because I filter it and the mongodb query is fast enough.
The problem is that the result is a cursor of objects looking like this:
{'id': 1588697856264716288}
My goal is to have a list of 'id' but only interested in the value, so something like this:
[1588697856264716288,1588697856264716289,...]
In the code below, assume that idd is our cursor containing 100 object. It takes almost 20 second to eventually print mylist
mylist=[]
for idd in ids:
    mylist.append(idd["id"])
print(mylist)

Why is it so slow and how can I speed this up? I'm using Python3.10
I'm trying to create a list of id from a cursor faster. I tried using a simple for loop and maps but it always takes 15-20 seconds
Edit: I just realized what made it slow is the query (eventhough the cursor is returned really fast)
The query is something like this:
ids=mycol.find({"timestamp_ms": {"$gt":"1670979659"}}).limit(100)

In my database timestamp_ms is a string... I guess this is my problem. Should I convert it to a date to make it faster?

A: For debugging purposes do this:
from time import perf_counter

duration = None
mylist = []
start = perf_counter()
for idd in ids:
    if duration is None:
        duration = perf_counter() - start
        print(f'Duration={duration:.4f}s')
    mylist.append(idd['id'])

If the query is handled lazily - i.e., not until you first try to enumerate the cursor, then this will tell you how long the query takes

A: If I remember correctly, list comprehension is faster than a for loop in Python (for some cases).
You could try the following solution:
ids = [{'id': 1}, {'id': 2}]

mylist = [id['id'] for id in ids]
print(mylist)

The official docs for list comprehension: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions


text:
Q: automatic rota system based on special conditions I am trying to create system for assigning tasks to a team using existing sequence. I have four separate columns:
Column A – Indicates the given sequence of operators
Column B – Indicates number of current tasks per operator (imported from another file by vlookup)
Column C – Indicates the name of the operator that was assigned to the last task (imported from another file by vlookup)
Column D – Indicates whether any of the operators are currently on holiday (check/uncheck check box (TRUE/FALSE logic)

I would like to automate the system so that the next operator that is due to receive tasks is displayed, however the operator must not have more than 4 tasks already assigned to him/her and must be present (not on holiday).
The selection process must repeat taking into consolidation the given sequence until the name is selected, hence if the last name in the sequence is not the exact match the system must start with the first name in the sequence.
Could someone be able to figure this out please as I am completely stock.
Currently, I have the following, column with the following =IF(B2<=4,A2,"N/A") and another column with the following =IF(E2=FALSE,F2,"N/A"). And one more column with =INDEX(SQESequence,MATCH(C2,SQESequence,0)+1,1), however that  is not fully automated.

A: I think that I understand your problem / question and have come up with a solution. A more elegant formula solution may exist, will play with it more if I have time.
{=IFERROR(INDEX(INDIRECT("A"&MATCH(C2,A2:A5)+1&":A5"),MATCH(1,(INDIRECT("A"&MATCH(C2,A2:A5)+1&":A5")<>$C$2)*(INDIRECT("B"&MATCH(C2,A2:A5)+1&":B5")<4)*(INDIRECT("D"&MATCH(C2,A2:A5)+1&":D5")=FALSE),0)),INDEX($A$2:$A$5,MATCH(1,($A$2:$A$5<>$C$2)*($B$2:$B$5<4)*($D$2:$D$5=FALSE),0)))}

Enter CTRL SHIFT ENTER to set as an array formula, each function then returns an array of values rather than just a single value. You know you have set as an array formula when you see the { } 's
They say that a picture is worth 1000 words....so here are three!


text:
Q: 10 fold cross validation: taking the average of the test error or taking the sum? I have two probabilistic model, $A$ and $B$.
I am using MLE to estimate the parameters in both models.
Then I run the following 10-fold cross validation.
I randomly chopped the data set into 10 chunks, in each iteration, I use MLE to fit the 2 models on the training data set and get my estimates, so I will have 2 training Loglikihoods for 2 models. Then, I apply these 2 models with their estimates of the parameters to the test data set and get 2 test loglikihoods.
I go through all 10 iterations, then I could (1) take the average of 10 test loglikihoods for each model, then compare these 2 average; Or I could (2) sum all the 10 test loglikihoods for each model, then compare the sum.
I think in order to tell one model is better than the other, both of these 2 methods are equivalent. However, I feel that the first one, i.e., take the average is more meaningful, while the 2nd one (i.e., take the sum) is just mathematically equivalent but not very meaningful. But I couldn't tell why.
Can someone provide some comments?

A: Mathematically, this is equivalent since the number of folds is the same for both models.
log likelihoods are per se not a very intuitive (though in some cases valid) scale for comparison of models. Therefore, it does not matter very much in your case I would think.
In other cases, it is plain misleading to sum performance metrics over cross validation folds. 10 error rates of 2% in each fold are not a 20% error rate on the data set and ten 98% accuracies are not one 980% accuracy.


text:
Q: Class and object Inheritance UPDATED
Ok so I am playing around with classes and inheritance and I am trying to do something I have seen done before in a game whose source code is C++ and I was wondering if someone here could help me to understand how I would do it with C#.
What I want to do is two things:
First When I create an object of a certain class I want to pass an integer to the constructor and that integer to determine what sublcass will be initialized.
like so: Vocation newVoc = new Vocation(1);
and the 1 would choose the first sublcass or subclass with that VocationId.
Second thing, I already have a Player Class that inherits fine from Creature Class, but I want the Player Class itself to contain a Vocation object. So I can set the vocation, and when I do the properties change and the player has different properties... Here is example code to try to go with what I'm saying, hopefully someone understands what I mean.
Ok so I am now getting an error. Cannot implicitly convert type Mage' toVocation'
this is what I got...
Vocation.cs
using UnityEngine;
using System.Collections;

public enum VocationType { Mage, Warrior }

public class Vocation
{

}

public static class VocationFactory
{
    public static Vocation CreateVocation(VocationType type)
    {
        switch (type)
        {
            case VocationType.Mage:
                {
                    return new Mage();
                    break;
                }
        }
    }
}

public class Mage
{
    public string Name = "Mage";

    public Mage()
    {

    }
}

Player.cs
using UnityEngine;
using System.Collections;

public class Player : Creature
{
    public uint Level {get; set; }
    public uint Dexterity {get; set; }
    public uint Vitality {get; set; }
    public uint Intelligence {get; set; }
    public uint Strength {get; set; }
    public ulong Experience {get; set;}

    public Player()
    {
        var voc = VocationFactory.CreateVocation(VocationType.Mage);
        Level = 1;
        Health = 500;
        MaxHealth = 100;
        Mana = 50;
        MaxMana = 100;
        Experience = 0;
        Dexterity = 0;
        Vitality = 0;
        Intelligence = 0;
        Strength = 0;
    }
}

A: You shouldn't create objects from a base class. Use a factory instead, and maybe a enum to define the type.
If you start off with Dmitry's answer on your previous question, you can create a factory class that instantiates the objects. For example:
public enum VocationType { Mage, ... }

public static class VocationFactory
{
    public static Vocation CreateVocation(VocationType type)
    {
        switch (type)
        {
            case VocationType.Mage:
                {
                    return new Mage();
                    break;
                }
        }

        throw new Exception($"You did not implement type '{type}'.");
    }
}

Then call it like this:
var voc = VocationFactory.CreateVocation(VocationType.Mage);

A: I presume you don't want a Vocation to be a subtype of Player, but rather something a Player has. A Player may even have more than one vocation. This reflects the code you have shown.

This cannot be done, but there are ways around it.
The constructor requires a type to be specified, and you cannot specify an ancestor, you must specify the actual type you want to instantiate. So a new Vocation(1) will create just that, a Vocation instance, and never a subclass.
A way around this is to use a case statement:
switch (vocation)
{
    case 1:
        return new Mage();
    case 2:
        return new Sorceror();
}

But this is not good design, I wouldn't do that. In C# you have enums, so at least use those:
enum VocationType
{
    Mage,
    Sorceror
}

switch (vocation)
{
    case Mage:
        return new Mage();
    case Sorceror:
        return new Sorceror();
}

This is still not good. The problem here is that what you are looking for really is a creational pattern, not a programming trick.
What you really want is a factory that can create any type of player you want.
The better (maybe still not best) way to do that in c# would be a generic that has a factory method to which you pass the actual Type you want to instantiate, much like this:
public class PlayerFactory
{
    public Player Create<V>()
        where V : Vocation
    {
        Player p;
        p = new Player();
        p.SetVocation<V>();

        return p;
    }
}

The SetVocation<V>() method whould be:
public class Player : Creature
{
    private Vocation ChosenVocation;

    public Player()
    {
    }

    public void SetVocation<V>()
        where V : Vocation
    {
        ChosenVocation = new V();
    }
}

You can now create those instances as follows:
switch (vocation)
{
    case Mage:
        return PlayerFactory.Create<Mage>();
    case Sorceror:
        return PlayerFactory.Create<Sorceror>()
}

Why all this fuss?
You want to remove yourself from codes like 1 or Vocation.Mage and so on as soon as possible and to switch to an actual type (that is, implemented code). The method above allows you to extend your code easily by:

*

*adding a vocation to the Vocation enum;

*adding the case to the switch();

*implementing the vocation (e.G. the Sorceror class).

A: For the second point simply create a Player and a new Vocation (based on the answer of Patrick):
var player = new Player { Vocation = VocationFactory.CreateVocation(VocationType.Mage) };

This assumes you have a property Vocation on your Player-class:
class Player : Create
{
    public Vocation Vocation { get; set; }
}

A: For the First requirement you can have constructor with one parameter and call the class whichever you feel like in the implementation of the constructor.
public class Class1
{
   public Class1(int i)
   {
       // Your implementation logic goes here
   }
}

Below is the updated code of yours which I think will fulfill your Second requirement.
public class Vocation
{
    public Vocation()
    {

    }
    public Vocation(int i)
    {

    }
}

public class Player : Creature
{
    Vocation v;
    public Player(int i)
    {

    }

    public void SetVocation(int value)
    {
        // if you wanna set it to value
        v = new Vocation(value);
    }
}


text:
Q: Instruments for memory leaks with Xcode 4.3.2 quits unexpectedly I recieved "recieved memory warning" when I was debugging my application via Xcode Device Debugger. My app doesn't seem to be consuming that much memory, so I wanted to look at Instruments tool for the first time.
My project is on my iphone device. (Generated by xcode when I debugged)
I am currently using Xcode 4.3.2.
BaseSDK: 5.0.1(Latest)
Target Deployment: 5.0
Device Software: 5.0.1 (9A405)
Steps I follow (don't know If I am doing it right though)
I open Instruments Tool, Select Memory Leaks Scheme for iOS, Choose Target (my device), again choose target and my application (which is created by xcode from last build). When I press record button, application launches with no problem, but when application is launching up, Instruments tool quits.(application on my device keeps on running).
I feel that I am not doing something properly. And one more question. My baseSDK is 5.1 but I am targeting on a 5.0.1 device. Is this also a problem?
Profiling works great on iOS Simulator 5.1, but not on my iPhone.
Edit:
I have also tried profile launch, both set to debug and release. Both crushes the Instruments Tool as well.


text:
Q: Username and Password Authentication for WCF Hosted in Azure I would like to use the Authorization in WCF Hosted in Azure. At this stage I'm thinking of using username and password using asp membership provider.
Are there any better options available in Azure for Authentication?
Thank you

A: although you can use the asp membership provider, there are other options you might want to consider. First, if you go for the aspnet membership provider and you use sql azure you'll need to run a different set of scripts, explained here:
http://support.microsoft.com/kb/2006191
next you could aslo use the Access Control Service to secure your service in a 'truly' azure fashion. please take a look at
http://www.microsoft.com/windowsazure/appfabric/ and then access control..
Kr.
Didier


text:
Q: New to callback functions (passing a callback as parameter)(Javascript) Newbie question here.
I am trying to understand callback functions better.  Reading about them here, i though i grasped the idea.

    function greeting (name, callback){
      console.log(`Greetings ${name}`);
      callback();
    };

    function timeOfDay (time){
      console.log(`How are you this fine ${time}?`);
    };

    greeting ('Brad', timeOfDay('evening') );

Output
How are you this evening?
Greetings Brad
Uncaught TypeError: callback is not a function

Can  someone please explain why the output is in this order?  What does this error refer to and why does it appear even though the code has finished?
I first did a simple callback function along the same structure and it worked fine.
Thanks in advance
Brad

A: You were close, but when passing timeOfDay("evening"), you aren't actually passing that function as the callback. That is a function invocation and it runs immediately and whatever the return value of that is, is what is passed to the greeting function invocation as the second argument. Since timeOfDay doesn't return anything, you are passing undefined to greeting.
The solution is to pass an actual function, not the result of invoking one (unless that result is, in fact, another function), to greeting, and one way we can do that is by wrapping the timeOfDay() function call in an anonymous function declaration, like this:

function greeting (name, callback){
  console.log(`Greetings ${name}`);
  callback();
};

function timeOfDay (time){
  console.log(`How are you this fine ${time}?`);
};

greeting ('Brad', function() { timeOfDay('evening') } );

Another technique is to use the Function.bind() method, which returns a copy of the function you've called it on, but the context that the function will execute in is configurable by you, based on the first argument you pass to .bind(). This is a very useful technique, but requires a good knowledge and understanding of scope and context, which you can read more about in another answer of mine:

function greeting (name, callback){
  console.log(`Greetings ${name}`);
  callback();
};

function timeOfDay (time){
  console.log(`How are you this fine ${time}?`);
};

greeting ('Brad', timeOfDay.bind(this,'evening') );

A: As said in the comments, when you do something like this:
greeting ('Brad', timeOfDay('evening') );
you will be calling the timeOfDay function instantaneously.
To avoid that you can use one of these options:

*

*Wrap your function call in an anonymous function, like said in another answers.

*You can omit/remove the parenthesis, like this greeting('Brad', timeOfDay); (this avoid instant function call, but you'll lose your parameter "evening" and the error will persist).

*You can .bind() a context to the function, in the example below, I'm binding this as the context to the function, that way it's not going to call the function instantaneously.
take a look:

function greeting (name, callback){
  console.log(`Greetings ${name}`);
  callback();
};

function timeOfDay (time){
  console.log(`How are you this fine ${time}?`);
};

greeting ('Brad', timeOfDay.bind(this, 'evening') );

Further reading:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind


text:
Q: How to add a sub parent class inside the parent class using Jquery Hi I want to add a sub parent class to my parent class using jQuery.
Previously I've tried this:

$('.my-parent').wrap('

');

1

2

3

4

But this one inserts the class outside of my parent, not inside.
What I want to achieve is like this html structure:

Is this achievable? Any help would be great. Thanks.

A: You need wrapInner function.

$('.my-parent').wrapInner('

');

1

2

3

4

For more resources.
https://api.jquery.com/wrapinner/


text:
Q: Get data from a api service without refreshing the browser I use a spring boot with angular .right now is i have a method which allows to bring the data from api service every second but but a message that is displayed:

core.js:6185 ERROR TypeError: You provided 'undefined' where a stream
  was expected. You can provide an Observable, Promise, Array, or
  Iterable.

//service
    ListAutombilesAuto(){
        let headers=new HttpHeaders({'Authorization':this.jwt});
      return this.fiches=this.http.get(this.BaseUrl+'/Automobiles',{headers:headers}).pipe
      (
        merge(this.fiches, interval(1000).pipe(switchMap(() => this.fiches)))
      );

      }

    //component
    ListAuto(){

        this.auth.ListAutombilesAuto().subscribe(data=>{
          this.fiches=data;
          console.log(this.fiches);
        }) // api call

    }

is there any solutions?
thank you for help

A: You are referencing this.fiches within its first assignment, therefore its value is still undefined.
Try fix your code as following:
ListAutombilesAuto() {
  let headers = new HttpHeaders({ 'Authorization': this.jwt });

  this.fiches = this.http.get(this.BaseUrl + '/Automobiles', { headers: headers });

  return this.fiches.pipe
    (
      merge(this.fiches, interval(1000).pipe(switchMap(() => this.fiches)))
    );
}

But actually why not keep it simple:
 ListAutombilesAuto() {

   let headers = new HttpHeaders({ 'Authorization': this.jwt });

   return timer(0, 1000)
     .pipe(
       switchMap(() => this.http.get(this.BaseUrl + '/Automobiles', { headers }))
     )

 }


text:
Q: AngularJS - Using $resource -- Why are there so many entries in my console log? I am new to AngularJS and working with $resource.  I am writing out log statements to my console and am confused because I see multiple entries.
My HTML looks like this:

                {{brand}}

            {{myData.brand}}

        <button ng-controller="ctrl1" ng-click="deleteBrand('apple')">delete</button>

And my js looks like this:

    var app = angular.module('myApp', ['ngResource', 'myAppControllers', 'myAppServices']);

    var services = angular
        .module('myAppServices', [])
        .factory('api', function ($resource) {
            return $resource('/api/Brand/:id',
                { id: '@id' }
            );
        });

    var controllers = angular
        .module('myAppControllers', [])
        .controller('ctrl1', [
            '$scope', 'api', function ($scope, api) {
                $scope.myData = {
                    brandList: [],
                    brand: {},
                };

                $scope.setBrandList = function () {
                    console.log("setBrandList");
                    api.query().$promise.then(function (response) {
                        console.log("setBrandList - success");
                        $scope.myData.brandList = response;
                    },
                        function (errResponse) {
                            console.log("setBrandList - error");
                        });
                };

                $scope.setBrand = function () {
                    console.log("setBrand");
                    api.get({ id: "minolta" }).$promise.then(function (response) {
                        console.log("setBrand - success");
                        $scope.myData.brand = response;
                    },
                        function (errResponse) {
                            console.log("setBrand - error");
                        });
                };

                $scope.deleteBrand = function (id) {
                    console.log("deleteBrand (" + id + ")");
                    api.delete({ id: id }).$promise.then(function (response) {
                        console.log("deleteBrand - success");
                        $scope.setBrandList();
                    },
                        function (errResponse) {
                            console.log("deleteBrand - error");
                        });
                };

                $scope.setBrand();
                $scope.setBrandList();
            }
        ]);

</script>

When I am running this simple example, I see three calls / responses to setBrand and setBrandList.  (See attached image)
Am I simply misunderstanding something?  Or am I defining something improperly?  My belief would be that setBrand and setBrandList would only be called once each.
Thanks in advance.

A: That's because you are defining your controller 3 times in your template. You just need the ng-controller directive in your first div.


text:
Q: How to ensure that formatted date time is shown in different language in Laravel Good day to all, I want to make sure that the formatted date time is displayed in different language except for default English, say, in French. The code:
<small> {{$income->created_at->format('F jS, Y')}}</small>.
How is it possible to achieve?

A: Laravel uses Carbon under the hood for date operations. Carbon has several functions to localize datetime formats for different languages.
What you are looking for is isoFormat. This function expects the same parameters as php's own strftime function.

A: You can use locale method to set the localization in your app.
{{$income->created_at->locale('fr_FR')->format('F jS, Y')}}

For more information have a look on the API
https://carbon.nesbot.com/docs/#api-localization

The ->locale() method only change the language for the current instance and has precedence over global settings.

You can also try
{{Carbon\Carbon::parse($income->created_at)->locale('fr_FR')->format('F jS, Y')}}


text:
Q: REST resource collection with different entity types It is stated in REST philosophy that if you have different types in the same resource(/ads) collection, list only same columns.

    {
        "ads": {
            "meta" {
                "count": 1899
            },
            "data" [
                {
                    "type": "tractor",
                    "make": "Ford"
                    "model": "",
                    "moto_hours": "50"
                },
                {
                    "type": "car",
                    "make": "Audi"
                    "model": "A4"
                    "moto_hours": ""
                 }
            ]
        }
    }

However i have a question, maybe it is valid to do and this way?

    {
        "ads": {
            "meta" {
                "count": 1899
            },
            "data" [
                {
                    "type": "tractor",
                    "make": "Ford"
                    "moto_hours": "50"
                },
                {
                    "type": "car",
                    "make": "Audi"
                    "model": "A4"
                 }
            ]
        }
    }


text:
Q: Subgroup analysis results are different if I conducted each subgroup separately in metarate in R I am doing a single arm meta-analysis of incidence rate using Poisson regression and doing subgroup analysis using meta and metafor packages in R.
Upon reviewing subgroup analysis results, I noticed it is different if I conducted each subgroup separately. If there is any possible explanation for that, it will be greatly appreciated.
Furthermore, I need  to know what the used statistical test to get the interaction-P value or subgroup difference P value is (which is 0.0432 in the following dataset (in random effect model)).
I reviewed this link but I couldn't get what I need there.
Here is my code and sample dataset
library(meta); library(metafor)
data<-read.table(text="studlab  Subgroup_2gps   Mean.FU popXFU  event
DeBonis.2014    Adult   11.5    1552.5  13
Fucci.2007  Adult   6.5 416 4
Ram.2020    Pediatrics  5.583333    290.33333   4
Kadirogullari.2019  Pediatrics  1.616667    90.53333    2
Kashiyama.2014  Pediatrics  3.275   180.125 1
Tomita.2005 Pediatrics  6.708333    134.16667   1
Lawrie.2006 Pediatrics  3.1 291.4   16
Maeda.2019  Pediatrics  5.5 203.5   1
Zussa.1997  Pediatrics  3.05    350.75  2
Murashita.2013  Pediatrics  7.5 562.5   6
David.2013  Pediatrics  10.1    1070.6  30
Bourguignon.2016    Pediatrics  3.4 98.6    3
Phillips.2000   Pediatrics  0.9 66.6    5
Pfannmuller.2013    Pediatrics  4.3 498.8   5
Totaro.1999 Adult   3.833333    199.33333   3
", sep="\t", header=T)

mr <- metarate(event,popXFU, data= data,# subset= data$Subgroup_2gps== "Neochords " ,
               studlab = studlab, method = "GLMM",model.glmm = "CM.EL",method.ci = "Poisson",   irscale = 1000)
mr2<- update (mr, byvar=Subgroup_2gps);forest(mr2); mr2

# Results for subgroups (random effects model):
#   k  events             95%-CI  tau^2    tau
# Subgroup_2gps = Adult        3  9.3998 [ 6.0643; 14.5697]      0      0
# Subgroup_2gps = Pediatrics  12 18.6089 [11.3291; 30.5666] 0.4500 0.6708
#
# Test for subgroup differences (random effects model):
#   Q d.f. p-value
# Between groups   4.09    1  0.0432

## It gave me IR of 18.6089 [11.3291; 30.5666] for random effect for Pediatrics subgroup

#============================================================================================
mr <- metarate(event,popXFU, data= data, subset= data$Subgroup_2gps== "Pediatrics" ,
               studlab = studlab, method = "GLMM",model.glmm = "CM.EL",method.ci = "Poisson",   irscale = 1000);mr
## It gave me IR of 15.9876 [ 9.5438; 26.7820] for random effect

Any guidance will be greatly appreciated.


text:
Q: Visual Studio - Runtime impact of conditional and disabled breakpoints After spending a little time wondering why my app was running a particular scenario very slowly with the debugger attached, I discovered that this was due to having a conditional breakpoint (whose condition was never being met).  This seems reasonable, as the CPU would signal the breakpoint and VS would need to evaluate the condition before allowing execution to continue.  These transitions must be costly.
I assume that a breakpoint in a code path that is not executed has no runtime impact.
So my question is twofold:

*

*Are there any resources that can quantify the cost associated with conditional breakpoints, and if so is there anything one can do to reduce their runtime evaluation cost?

*Is there any cost associated with a 'disabled' breakpoint?  By disabled I mean that VS displays the breakpoint marker in the gutter with a hollow circle.

Of course if anything I've mentioned above doesn't make sense, then please point me in the right direction.

A: It's hard to quantify the cost of a conditional breakpoint.  The expression in a conditional breakpoint is evaluated using the exact same semantics as if you had typed it into the watch or immediate window.  Expressions of this nature are not actually executed in the client program but instead handled by the language specific expression evaluator.  It's not really possible to profile these types of evaluations in a meaningful way.
However I can list a few things that are known to be slower in a debug window eval

*

*Function Calls: They are the slowest thing you can do because the function call requires the debuggee process to be restarted so that the func eval can occur in the process

*String comparison: Under the hood these go back to func evals

As for disabled breakpoints, no they do not affect the running of the application.

A: One thing to watch out for (which I learned the hard way) is to make sure you put == when comparing a variable to a value and not the single =
The breakpoint editor doesn't warn you but when the breakpoint is evaluated, the variable is altered! Took me a while to debug my code with that one!
Also, if I really need the conditional breakpoint to bebug code; I add the condition to the the code, then add something like string stop = "here"; and put a normal breakpoint there - I find the code runs faster then.

A: I read somwhere that there is hardware support for these breakpoints, so that using fewer than x conditional breakpoints of a certain kind is essentially free, but above that, it needs to use more software. (OTOH, that was for native apps, not sure about these newfangled JIT things.)
Disabled breakpoints should take affect things at all, they just occopy some memory and GUI resources in IDE.

A: *

*Try putting the breakpoint in your
code to test the performance.  E.G.
Stopwatch st = new Stopwatch();
st.Start();
if(my condition)
{
  st.Stop();
  Debugger.Break();
}

No, not exactly the same but close enough.

*No - a disabled breakpoint is not
present in the executing program.
It is just stored in the VS metadata
for your convenience.

A: I have also noticed that conditional breakpoints are expensive and came to the same conclusion as you.  I can't imagine any reason that a disabled breakpoint would cause any slowdown since I would expect it to be an editor only thing, a shortcut for turning on a breakpoint should you need it.
What I do when I am in a situation like yours is make an assert macro. (you can use the assert macro that visual studio provides, but I dont like it).  Have your macro check the condition you want and then call DebugBreak if it fails.  In the realease, or non-checked build of your application, have assert evaluate to nothing, so your code is not impacted.
A simple assert macro can look like:
#ifdef _DEBUG
#define assert(x)\
do{\
  if(!(x)){DebugBreak();}\
}while(0)
#else
#define assert(x)
#endif

and call it like:
assert(pValue != NULL && "A bad parameter was passed to the function");

You can put more code in the failure before DebugBreak (like printing out the condition that failed with #x, and/or the line/file number with ____FILE____ and ____LINE____ so you can double click on the message).  You can write messages to the debug log with OutputDebugString and even check to see if a debugger is attached with IsDebuggerPresent to tailor your assert even more.  I also like to use the && string format to give a bit more information on the particular assert.
There are a few things to be careful of when using assert.  First, do not put any code that MUST be run in the macro, since it will be stripped in a non debug build.  For the same reasons, don't put in code that has side effects.  Also, you do not want to call DebugBreak() when a debugger is not attached because it essentially throws an exception, which if not caught, will terminate the application.


text:
Q: Space in path name causing "Warning: invalid package" on install. R When running R-3.4.4 (on Windows 7, RStudio):
install.packages("ggplot2", destdir = "C:/Program Files/R/R-3.4.4/library/temp")

I get the following warning (presumably from the space in the path):
installing the source package 'ggplot2'

trying URL 'https://cran.rstudio.com/src/contrib/ggplot2_3.2.1.tar.gz'
Content type 'application/x-gzip' length 3204655 bytes (3.1 MB)
downloaded 3.1 MB

Warning: invalid package 'C:/Program'
Warning: invalid package 'Files/R/R-3.4.4/library/temp/ggplot2_3.2.1.tar.gz'
Error: ERROR: no packages specified
In R CMD INSTALL
Warning in install.packages :
running command '"C:/Program Files/R/R-3.4.4/bin/x64/R" CMD INSTALL -l "C:\Program Files\R\R-3.4.4\library" C:/Program Files/R/R-3.4.4/library/temp/ggplot2_3.2.1.tar.gz' had status 1
Warning in install.packages :
installation of package 'ggplot2' had non-zero exit status

Although, trying to circumvent it using:
install.packages("ggplot2", destdir = "C:/Temp")

leads to:
* installing *source* package 'ggplot2' ...
** package 'ggplot2' successfully unpacked and MD5 sums checked
** R
** data
*** moving datasets to lazyload DB
** inst
** preparing package for lazy loading
Error in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]) :
  there is no package called 'pillar'

where
.libPaths()
[1] "C:/Program Files/R/R-3.4.4/library"

Again, trying to solve that warning with:
install.packages("pillar", destdir = "C:/Temp")

leads to
** testing if installed package can be loaded
Fatal error: cannot open file 'C:\Users\Mary': No such file or directory

The full path is C:\Users\Mary Surname\etc\etc... Which brings it back to the first problem where there is a space between "FirstName" and "Surname" in the path.
Any way to correct the incorrect interpretation of the space. Note, the download is fine but it falls over trying to find the zip file it had only just downloaded.


text:
Q: How to use this char function with the 'populate function'? So I have to create some random sentences using certain words from text file. The char ** populate is creating a sentence using the "*currentsize" when the size of word is less than *maxsize. However, the maxsize is only able to take limit of 5 strings. Hence, I have to use the bottom function 'doubleit'  when the words from text file is more than 5 char (since maxsize's limit is 5). But I am not sure how to implement/ add it to the populate function.
char ** populate(char ** words, FILE *fptr, int *currentsize, int *maxsize)
  // to store line or word from file
    char *line;
    line = (char *)malloc(sizeof(char *) * LIMIT);

    // reading file using fgets(buffer, limit, inputstram)
    while(fgets(line, LIMIT-1, fptr))
    {
        // if currentSize is less than maxsize then add because we can't go beyond maxsize specified in main function
        if (*currentsize < *maxsize)
        {
            // allocate memory to store the word, using constant LIMIT
            words[*currentsize] = malloc(sizeof(char *) * LIMIT);

            // add this line(word) to words, used strncopy to copy characters excluding \n and \0
            strncpy(words[*currentsize], line, strlen(line)-2);

            // terminate the line with \0
            words[*currentsize][strlen(line)] = '\0';

            // increment currentsize
            ++*currentsize;
        }
        if(*currentsize > *maxsize){
            strncat (** temp);
        }

    }

    // free memory used to store temp line
    free(line);

    // return
    return words;
}

char ** doubleIt(char **arr, int *maxsize)
{
    // create a **temp, double sized array
    char ** temp = (char ** )malloc(sizeof(char *) * *maxsize * 2);

    // copy elements from **arr to ** temp
    for (int i = 0; i < *maxsize ; i++)
    {
        // locate memory to store string at arr[i] in temp
        temp[i] = malloc(sizeof(char) * LIMIT);
        // copy arr[i] in temp[i]
        strncpy(temp[i], "  ", 1);
        temp[i][strlen(temp[i])] = '\0';
        strcpy(temp[i], arr[i]);
        // add \0 to temp[i]
        temp[i][strlen(temp[i])] = '\0';
    }

    // double *maxsize
    *maxsize = *maxsize * 2;
    // return new pointer to new memory location
    return temp;
}

I am not allowed to use realloc for this particular project.


text:
Q: Can't capture the output of rg/ag/pt with org-babel on OS X I'm trying to capture the output of rg but I'm getting no output (I'm getting the message "Code block produced no output" in the minibuffer.
I've also tried ag and pt which don't work either. It works with grep but this is too slow for my use-case.
Example:
#+BEGIN_SRC shell
mkdir -p myproject
pushd myproject
echo "something" > something.txt
rg something
popd
#+END_SRC

#+RESULTS:

I've tried the solutions from these similar questions, but they're not working here:

*

*Capturing the output of "diff" with org-babel

*Capture output from a shell command with babel in org-mode