text:
Q: Validating Field Of Edittext in Android when i am giving validation to field it does not validate proper.
and when fields are blank it only shows the red mark not show error when i am clicking on edittext then it will display the error.
    nameValidate = "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$";
    mobile = "^[2-9]{2}[0-9]{8}$";
    passwordpattern = "((?=.*[a-z])(?=.*\\d)(?=.*[A-Z])(?=.*[@#$%!]).{8,40})";

    //registration button code
    btn_registration = (Button) findViewById(R.id.buttonRegister);
    btn_registration.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            uname = edittext_username.getText().toString();
            password = edittext_Password.getText().toString();
            phone = edittext_phone.getText().toString();
            if (uname.equals("") || uname.length() <= 3 || uname != nameValidate) {
                if (uname.equals("")) {
                    edittext_username.setError("Name cannot be Blank");
                } else {
                    edittext_username.setError("Enter Valid Name");
                }
            }

            //Toast.makeText(getApplicationContext(), "Please enter username upto 6char", 1000).show();

            if (password.equals("") || password.length() < 3) {
                // Toast.makeText(getApplicationContext(), "please enter password upto 6char ", 1000).show();
                edittext_Password.setError("Password cannot be blank");

            }

            if (phone.equals("") || phone.length() < 10) {
                edittext_phone.setError("Invalid mobile number");
                //Toast.makeText(getApplicationContext(), "please entermobile number must be 10 digit", 1000).show();
            }
            if (uname == null && uname.equals(nameValidate) || password == null || phone == null) {
                confirmOtp();
            }

        }
    });
}

A: try this my friend
        btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(phone.getText().toString().length() <10){
                phone.setError("Please enter valid phone number");
                phone.requestFocus();
            }
            if(phone.getText().toString().trim().equals("")){
                phone.setError("Please enter phone number");
                phone.requestFocus();
            }
            if(pass.getText().toString().trim().length() <6){
                pass.setError("password must contain 6 character");
                pass.requestFocus();
            }
            if(pass.getText().toString().trim().equals("")){
                pass.setError("Please enter pass ");
                pass.requestFocus();
            }

            if(username.getText().toString().trim().equals("")){
                username.setError("Please enter user name");
                username.requestFocus();
            }

            if(!username.getText().toString().trim().equals("")&&
                    !pass.getText().toString().trim().equals("")&&
                    pass.getText().toString().length() ==10 &&
                    !phone.getText().toString().trim().equals("")&&
                    phone.getText().toString().length() ==10){
                // do your action here your validation are complete
            }
        }
    });

change your xml controll like this
 <EditText
    android:id="@+id/username"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
    android:gravity="center"
    android:hint="user name"
    android:maxLines="1" />

<EditText
    android:id="@+id/pass"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:hint="password"
    android:inputType="textPassword"
    android:maxLines="1" />

<EditText
    android:id="@+id/phone"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:hint="phone number"
    android:inputType="number"
    android:maxLength="10"
    android:maxLines="1" />


text:
Q: How to use systemless root on android I have an app that helps locate your lost android phone and for rooted phones I have a one click convert to system app feature (so it will survive a factory reset).
Now some of my users complains and say it no longer works on devices that uses systemless root. So questions of the day are:

*

*how do I detect if a user has systemless installed programmatically?

*how do I use systemless? I guess it is not through the normal SU command

BR. Theis

A: *

*Well, I had one of my users do some tests on his phone and a simple call like this will tell you if the user has su installed:
which su

*Yes, the new systemless root also uses "su" as a command. Details can be found on XDA

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change validation requirements in contact form What to change in the code below (.js from contact form) so that "nazwisko" field is not a required field? This is one file from .php contact form. I was checking some options but I`m not so familiar with .js. Is it enough to just erase this "nazwisko" line from the code or should I just put "false" next to the requirements?
Thank you for your support!
$(document).ready(function(){

/***************************************/
/* Form validation */
/***************************************/
$( '#j-forms' ).validate({

    /* @validation states + elements */
    errorClass: 'error-view',
    validClass: 'success-view',
    errorElement: 'span',
    onkeyup: false,
    onclick: false,

    /* @validation rules */
    rules: {
        nazwisko: {
            required: true
        },
        dataur: {
            required: true
        },
        email: {
            required: true,
            email: true
        },
        'imiona-rodzice': {
            required: true
        },
        telefon: {
            required: true
        },
        klasa: {
            required: true
        },
        szkola: {
            required: true
        },
        adres: {
            required: true
        },
        telkur: {
            required: true
        }
    },
    messages: {
        nazwisko: {
            required: 'Podaj swoje Imię i Nazwisko'
        },
        dataur: {
            required: 'Podaj swoją datę urodzenia'
        },
        'imiona-rodzice': {
            required: 'Podaj imiona rodziców'
        },
        telefon: {
            required: 'Podaj telefon do rodziców'
        },
        klasa: {
            required: 'Podaj swoją klasę'
        },
        szkola: {
            required: 'Podaj swoją szkołę'
        },
        adres: {
            required: 'Podaj swój adres'
        },
        telkur: {
            required: 'Podaj swój telefon'
        },
        email: {
            required: 'Podaj adres email',
            email: 'Niepoprawny format'
        },

    },
    // Add class 'error-view'
    highlight: function(element, errorClass, validClass) {
        $(element).closest('.input').removeClass(validClass).addClass(errorClass);
        if ( $(element).is(':checkbox') || $(element).is(':radio') ) {
            $(element).closest('.check').removeClass(validClass).addClass(errorClass);
        }
    },
    // Add class 'success-view'
    unhighlight: function(element, errorClass, validClass) {
        $(element).closest('.input').removeClass(errorClass).addClass(validClass);
        if ( $(element).is(':checkbox') || $(element).is(':radio') ) {
            $(element).closest('.check').removeClass(errorClass).addClass(validClass);
        }
    },
    // Error placement
    errorPlacement: function(error, element) {
        if ( $(element).is(':checkbox') || $(element).is(':radio') ) {
            $(element).closest('.check').append(error);
        } else {
            $(element).closest('.unit').append(error);
        }
    },
    // Submit the form
    submitHandler:function() {
        $( '#j-forms' ).ajaxSubmit({

            // Server response placement
            target:'#j-forms #response',

            // If error occurs
            error:function(xhr) {
                $('#j-forms #response').html('An error occured: ' + xhr.status + ' - ' + xhr.statusText);
            },

            // Before submiting the form
            beforeSubmit:function(){
                // Add class 'processing' to the submit button
                $('#j-forms button[type="submit"]').attr('disabled', true).addClass('processing');
            },

            // If success occurs
            success:function(){
                // Remove class 'processing'
                $('#j-forms button[type="submit"]').attr('disabled', false).removeClass('processing');

                // If response from the server is a 'success-message'
                if ( $('#j-forms .success-message').length ) {

                    // Remove classes 'error-view' and 'success-view'
                    $('#j-forms .input').removeClass('success-view error-view');
                    $('#j-forms .check').removeClass('success-view error-view');

                    // Reset form
                    $('#j-forms').resetForm();

                    // Prevent submitting the form while success message is shown
                    $('#j-forms button[type="submit"]').attr('disabled', true);

                    setTimeout(function(){
                        // Delete success message after 5 seconds
                        $('#j-forms #response').removeClass('success-message').html('');

                        // Make submit button available
                        $('#j-forms button[type="submit"]').attr('disabled', false);
                    }, 5000);
                }
            }
        });
    }
});
/***************************************/
/* end form validation */
/***************************************/

A: as @Amit said:
Only change this one line in rules section.
Not necessary to change or delete the message in message part itself.
/* @validation rules */
rules: {
    nazwisko: {
        required: false
    },


text:
Q: Plot a best fit line R Right now i have a large data set with temperature going up and down all the time.
I want to smoothen my data and plot the best fit line with all the temperature,
Here is the data:
weather.data
    date        mtemp
1   2008-01-01  12.9
2   2008-01-02  12.9
3   2008-01-03  14.5
4   2008-01-04  15.7
5   2008-01-05  17.0
6   2008-01-06  17.8
7   2008-01-07  20.2
8   2008-01-08  20.8
9   2008-01-09  21.4
10  2008-01-10  20.8
11  2008-01-11  21.4
12  2008-01-12  22.0

and so on............... til 2009 Dec 31
My current graph looks like this and my data fit a regression like either the running average or loess:

However, when I tried to fit it with the running average, it became like this:

Here is my code.
plot(weather.data$date,weather.data$mtemp,ylim=c(0,30),type='l',col="orange")
par(new=TRUE)

Could anyone give me a hand?

A: Depending on your actual data and how you want to smooth it, and why you want to smooth it there are various options.
I am showing you examples with linear regression (first and second order) and local regression (LOESS). These may or may not be the good statistical models to use for your data, but it is difficult to tell without seeing it. In any case:
time <- 0:100
temp <- 20+ 0.01 * time^2 + 0.8 * time + rnorm(101, 0, 5)

# Generate first order linear model
lin.mod <- lm(temp~time)

# Generate second order linear model
lin.mod2 <- lm(temp~I(time^2)+time)

# Calculate local regression
ls <- loess(temp~time)

# Predict the data (passing only the model runs the prediction
# on the data points used to generate the model itself)
pr.lm <- predict(lin.mod)
pr.lm2 <- predict(lin.mod2)
pr.loess <- predict(ls)

par(mfrow=c(2,2))
plot(time, temp, "l", las=1, xlab="Time", ylab="Temperature")
lines(pr.lm~time, col="blue", lwd=2)

plot(time, temp, "l", las=1, xlab="Time", ylab="Temperature")
lines(pr.lm2~time, col="green", lwd=2)

plot(time, temp, "l", las=1, xlab="Time", ylab="Temperature")
lines(pr.loess~time, col="red", lwd=2)

Another option would be to use a moving average.
For instance:
library(zoo)
mov.avg <- rollmean(temp, 5, fill=NA)
plot(time, temp, "l")
lines(time, mov.avg, col="orange", lwd=2)


text:
Q: Condition on Datatables or where database and Laravel 5.5 I have a laravel project, I want to create condition if or where database if user login have my id, then to show the main content is created.
this is my javascript on my View

this is my api.row_cosos on my Controller
Option 1: This is way to create with where('users.id', '=', 1) --> Success
public function getCososData()
    {
        $cosos = DB::table('cosos')
        ->join('users', 'cosos.quanly_id', '=', 'users.id')
        ->select('cosos.id', 'cosos.tencoso','cosos.chucoso','cosos.dkkd','cosos.sdt','cosos.ghichu','cosos.diachi','users.name','cosos.created_at','cosos.updated_at')
        ->where('users.id', '=', 1)
        ->get();
    return Datatables::of($cosos)
    ->addColumn('action', function ($cosos) {
        return 'id.'/edit" class="btn btn-success btn-xs"> Sửa  Xóa';
    })
    ->editColumn('cosos.id', '{{$id}}')
    ->removeColumn('cosos.updated_at')
    ->setRowId('cosos.id')
    ->setRowClass(function ($coso) {
        return $coso->id % 2 == 0 ? 'alert-success' : 'alert-warning';
    })
    ->setRowData([
        'cosos.id' => 'test',
    ])
    ->setRowAttr([
        'color' => 'red',
    ])
    ->make(true);
}

Option 2: This is way to create with where('users.id', '=', Auth:id()) and I login with user id = 1--> Error no data
public function getCososData()
        {
            $cosos = DB::table('cosos')
            ->join('users', 'cosos.quanly_id', '=', 'users.id')
            ->select('cosos.id', 'cosos.tencoso','cosos.chucoso','cosos.dkkd','cosos.sdt','cosos.ghichu','cosos.diachi','users.name','cosos.created_at','cosos.updated_at')
            ->where('users.id', '=', Auth:id())
            ->get();
        return Datatables::of($cosos)
        ->addColumn('action', function ($cosos) {
            return 'id.'/edit" class="btn btn-success btn-xs"> Sửa  Xóa';
        })
        ->editColumn('cosos.id', '{{$id}}')
        ->removeColumn('cosos.updated_at')
        ->setRowId('cosos.id')
        ->setRowClass(function ($coso) {
            return $coso->id % 2 == 0 ? 'alert-success' : 'alert-warning';
        })
        ->setRowData([
            'cosos.id' => 'test',
        ])
        ->setRowAttr([
            'color' => 'red',
        ])
        ->make(true);
    }

Please help me, thank you

A: write Auth::user()->id,It will access the user table and point to the id of user table.And you will get the data.


text:
Q: how to use 'GROUP BY' function with below query In the below code I want to apply group function only on three columns as given in group by condition. But it is giving error, wrong number of arguments.
select a.id,a.name,
       c.code,
       a.active_dt,
       a.inactive_dt,
       b.category,
       count(a.id,a.name,c.code) count
from student a,class b, descrip c
where a.id=b.id
and a.id=c.id
group by a.id,a.name,c.code
    having count(a.id,a.name,c.code) >1;

A: Do you mean like this?
SELECT * FROM (
    SELECT
        a.id,
        a.name,
        c.code,
        a.active_dt,
        a.inactive_dt,
        b.category,
        COUNT(1) OVER(PARTITION BY a.id, a.name, c.code) AS CNT
    FROM
        student a,
        class b,
        descrip c
    WHERE
        a.id=b.id AND
        a.id=c.id
)
WHERE CNT > 1

A: If I understand well, you simply need this:
select a.id,a.name,
       c.code,
       a.active_dt,
       a.inactive_dt,
       b.category,
       count(*) count
from student a,class b, descrip c
where a.id=b.id
and a.id=c.id
group by a.id,a.name,c.code
    having count(*) >1;

A small example of how count() ad group by work:
create table testGroup(a, b, c) as (
select 1, 2, 3 from dual union all
select 1, 2, 3 from dual union all
select 5, 6, 7 from dual union all
select 5, 6, 7 from dual union all
select 5, 6, 9 from dual union all
select 1, 2, 9 from dual
)

The number of columns you need to use in your group does not affect the way you use the count; say you need to group by 3 columns:
SQL> select a, b, c, count(*)
  2  from testGroup
  3  group by a, b, c
  4  having count(*) > 1;

         A          B          C   COUNT(*)
---------- ---------- ---------- ----------
         5          6          7          2
         1          2          3          2

And if you only need to aggregate by 2 columns:
SQL> select a, b, count(*)
  2  from testGroup
  3  group by a, b
  4  having count(*) > 1;

         A          B   COUNT(*)
---------- ---------- ----------
         5          6          3
         1          2          3

This assumes that you need to count the rows, no matter if the values are null or not.

A: Try this:
SELECT a.id, a.name, c.code, a.active_dt, a.inactive_dt, b.category,
       count(DISTINCT a.id,a.name,c.code) [count]
FROM student a
INNER JOIN class b
    ON a.id=b.id
INNER JOIN descrip c
    ON a.id=c.id
GROUP BY a.id, a.name, c.code, a.active_dt, a.inactive_dt, b.category
HAVING count(a.id,a.name,c.code) > 1


text:
Q: What is the meaning of an expression "Tufted titmouse"? I watch the show "The Good Doctor". It was used in season 2 episode 4. In flashbacks, Shawn had with his mother/caregiver (couldn't quite figure it out), she was dying and he had to move. They used it three times in this episode. I know its a bird, but what is the idiom behind that?

A: We used tough titmouse  in southwestern PA to mean tough luck back in the 1960's and probably taught it to our kids and grandkids by now.  The show the Good Doctor's setting is in Pittsburgh and takes in some of our colloquial.

A: Internet searches for "tough titmouse" produce very little of substance aside from discussions of episode 4 of season 2 of The Good Doctor, which is titled "Tough Titmouse" and initially aired on October 15, 2018. A recap of the episode on CelebDirtyLaundry.com indicates that the expression was used in a character's foster family, twice by the foster mother and once by the foster son:

The psychiatrist meets with Claire, Morgan and Dr. Lim, trying to figure out what is best for Kitty. Outside, Max apologizes to Shaun for hitting him and they talk about what do they think about when they are scared. Max says "teaser". Shaun flashes back to his foster home, where his foster mom used the term "tough titmouse" and told him to get dressed and he's going to go to school and face the horse's ass!
...
Nicole learns her wounds will heal, but Alex tells her they know Max caused her injury. She insists Max has never hurt anyone, but when she sees the bruise on Shaun's face, Alex says she needs to find a place for Max and there is no shame in finding help for her and Max. She fears Max will hate her. Shaun remembers the moment his foster mom tells him, he has to move out because she is very sick. Shaun tells her, "tough tit mouse!" Shaun is able to tell Nicole that he won't hate her, he will just be scared. Melendez feels she will find the strength to keep going.
...
Nicole explains to Max what is going to happen, as Melendez and Alex find it difficult to watch. Shaun remembers moving out of his foster home, admitting he is scared to leave and she tells him, "tough titmouse!' After he leaves, his foster mom tears up.

You can view the third instance noted above in a brief Facebook video excerpt, but be prepared for community-theater-level dramatic acting.
In each of these instances, "tough titmouse" doesn't allude to a proverb or other cultural back story involving a tufted (or any other species of) titmouse; it is just a quasi-euphemism for a cruder expression that is itself simply a dismissive expostulation. Presumably, the foster mother in The Good Doctor settled on "tough titmouse" as being more presentable than "tough titties," which, as Jason Bassford points out in a comment above, is (or was) a fairly common rude dismissive remark in parts of North America.
"Tough titmouse" is thus somewhat similar to the expression "tough snot"—which is a poorly disguised euphemism for the cruder but equally dismissive "tough shit." (In Texas in the 1960s, "tough snot" was fairly popular among English speakers in the 10-to-13-year-old cohort: it was rude enough to please a sixth-grader dismissing a peer's concerns or objections, without incurring the full wrath of any adult who might overhear.) The main difference is that "tough titmouse" is a bit cleverer because of its play on "tufted titmouse," a chickadee-like bird that lives in much the eastern half of the United States (and a bit of southeastern Canada).
Dianne Porter, a blogger at birdwatching.com posted an item called "Tough Titmouse" back in 2006, but her post seems to have nothing to do with the euphemism used in The Good Doctor. Instead, it focuses on the persistent aggressive behavior of a male tufted titmouse that lived near her house and spent months challenging mirror images of itself in her house's windows and her car's side mirrors and chrome trim. The wordplay here seems limited to tough and tufted.
A Google search turns up very few published instances of "tough titmouse," including just one in a book—in Kieran Crowley, Shoot: An F.X. Shepherd Novel (2016)—where it appears to rather ludicrous effect:

"That's off the record," I told Mel. "They don't want that out."
"Tough titmouse," Mel snarked. "If we got it, the Mail will get it soon. Frigate—we're going with the soaking story."
He was gone. I gave the bad news to Izzy, who relayed it to his boss, who went, well, ballistic.

I have no doubt that "tough titmouse" as a euphemism has some following in North America and may go back decades in some areas, but there is nothing more to it than the convenient similarity of the words to something naughtier—not unlike "particularly nasty weather" in the old joke.

A: I've heard the expression "tough titmouse" numerous times growing up (and I'm in my late 40s) so the writers of The Good Doctor didn't make it up.  I'm not sure what the origin of the saying is however.

A: a.) An insincere or sarcastic way of saying "that's too bad", or "deal with it"
b.) Short version of the phrase "'Tough titty', said the kitty, when the milk went dry."
e.g.
Child: But Mom... I don't want to mow the yard!
Mom: Well, tough titty. You're going to do it anyway.
c)small, active bird, expressing something small.


text:
Q: Update SQLite column with text of maximum length from same row I have an (Android) SQLite table with two columns, Col1 and Col2, containing text. I want to update Col1 to contain the text with the maximum length out of Col1 and Col2 from the same row. I already have a working query but that query takes pretty long to execute on a large data set.
Example data:
| Col1 | Col2 | ...
---------------
| AB   | A    |
| A    | ABC  |
| AB   | ABCD |

Expected update result:
| Col1 | ...
--------
| AB   |
| ABC  |
| ABCD |

Working (but slow and hard to read) query:

UPDATE table
SET Col1 = (
    SELECT Col2
    FROM table AS innerTable
    WHERE table.ROWID = innerTable.ROWID)
WHERE length(Col1) < length(Col2)

I am basically looking for something like this, without nested queries:
UPDATE table SET Col1 = maxLengthString(Col1, Col2)

Is there any existing function I have overlooked? Note that this is SQLite, so I can not use CREATE FUNCTION.
Thank you for your help!

A: I think that it is as simple as that:
update tablename
set col1 = col2
where length(col2) > length(col1);

Only the rows where the length of col1 is less than the length of col2 will be updated.
See the demo.
Results:
| Col1 | Col2 |
| ---- | ---- |
| AB   | A    |
| ABC  | ABC  |
| ABCD | ABCD |


text:
Q: Remote IP for pptpd server I'm trying to set up a VPN server with pptpd, and I'm having trouble determining what range of IP addresses I should pass to it's remoteip configuration option. I can connect just fine to the VPN, but when I try to use the connection to make requests, it does not resolve.
Here's my pptpd.conf file:
###############################################################################
# $Id$
#
# Sample Poptop configuration file /etc/pptpd.conf
#
# Changes are effective when pptpd is restarted.
###############################################################################

# TAG: ppp
# Path to the pppd program, default '/usr/sbin/pppd' on Linux
#
#ppp /usr/sbin/pppd

# TAG: option
# Specifies the location of the PPP options file.
# By default PPP looks in '/etc/ppp/options'
#
option /etc/ppp/pptpd-options

# TAG: debug
# Turns on (more) debugging to syslog
#
debug

# TAG: stimeout
# Specifies timeout (in seconds) on starting ctrl connection
#
# stimeout 10

# TAG: noipparam
#       Suppress the passing of the client's IP address to PPP, which is
#       done by default otherwise.
#
#noipparam

# TAG: logwtmp
# Use wtmp(5) to record client connections and disconnections.
#
logwtmp

# TAG: bcrelay <if>
# Turns on broadcast relay to clients from interface <if>
#
#bcrelay eth1

# TAG: localip
# TAG: remoteip
# Specifies the local and remote IP address ranges.
#
#       Any addresses work as long as the local machine takes care of the
#       routing.  But if you want to use MS-Windows networking, you should
#       use IP addresses out of the LAN address space and use the proxyarp
#       option in the pppd options file, or run bcrelay.
#
# You can specify single IP addresses seperated by commas or you can
# specify ranges, or both. For example:
#
#   192.168.0.234,192.168.0.245-249,192.168.0.254
#
# IMPORTANT RESTRICTIONS:
#
# 1. No spaces are permitted between commas or within addresses.
#
# 2. If you give more IP addresses than MAX_CONNECTIONS, it will
#    start at the beginning of the list and go until it gets
#    MAX_CONNECTIONS IPs. Others will be ignored.
#
# 3. No shortcuts in ranges! ie. 234-8 does not mean 234 to 238,
#    you must type 234-238 if you mean this.
#
# 4. If you give a single localIP, that's ok - all local IPs will
#    be set to the given one. You MUST still give at least one remote
#    IP for each simultaneous client.
#
# (Recommended)
localip 192.168.0.1
remoteip 192.168.0.170-180,192.168.0.245
# or
#localip 192.168.0.234-238,192.168.0.245
#remoteip 192.168.1.234-238,192.168.1.245

# Use Google's DNS
ms-dns 8.8.8.8
ms-dns 8.8.4.4

I tried to follow this tutorial.
When I connect to the VPN, and then try to ping, I get the following:
$ ping google.com
ping: cannot resolve google.com: Unknown host

A: First off, I suggest you drop PPTP as it is provably insecure and should not be relied upon for privacy, replace it with either OpenVPN or IPsec depending on the network environment/restrictions of the client systems.
Understanding this, if you wish to continue with PPTP:
Try ping 8.8.8.8 to rule out a dns issue.
If that doesn't work (and if you're forwarding all traffic through the VPN, which is a client option), you probably don't have IPv4 Forwarding enabled in your pptp server's linux(I'm assuming here) kernel.
To do so immediately:
# sysctl -w net.ipv4.ip_forward=1

Then to make that configuration permanent edit /etc/sysctl.conf and find the section referencing net.ipv4.ip_forward and un-comment(remove # at start of line) it.
If you have any firewall rules check that they allow for masqueraded/NAT traffic.

A: The pptpd package for Ubuntu only support i386 architecture – I was using a x86 version of Ubuntu.


text:
Q: Angular JS- Dreamfactory - Unable to connect : 403 Forbidden error I am on Amazon Cloud EC2 DSP 1.8.0.
Following their docs on AngularJS this is how I am declaring my constants:-
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services','**ngDreamFactory**'])
      .constant('DSP_URL', 'http://***-**-**-***-**.ap-southeast-1.compute.amazonaws.com/')
      .constant('DSP_API_KEY', 'sql')

The URL above is the ec2 instance address.
This is the error I get in the console when the app starts:
- GET http://***-**-**-***-**.ap-southeast-1.compute.amazonaws.com/rest/api_docs 403 (Forbidden)

undefined : undefined http://***-**-**-***-**.ap-southeast-1.compute.amazonaws.com/rest/api_docs

The above error comes, even though I have not yet made any call to the DSP, so I assume it must be the framework making this call. I see this "/rest/api_docs" is getting added in the JS file added as a part of Angular SDK.
Just to confirm that my DSP is set up correctly and my URL is correct, this is what I get when I paste this in the browser:
- http://***-**-**-***-**.ap-southeast-1.compute.amazonaws.com/rest/api_docs?app_name=sql

{
  "swaggerVersion":"1.2",
  "apiVersion":"1.0",
  "authorizations":{
      "apiKey": {
          "type":"apiKey",
          "passAs":"header"
       }
   },
"info": {
    "title":"DreamFactory Live API Documentation",
    "description":"",
    "contact":"support@dreamfactory.com",
    "license":"Apache 2.0",
    "licenseUrl":"http://www.apache.org/licenses/LICENSE-2.0.html"},
    "events":[
       "swagger.cache_cleared",
       "swagger.cache_rebuilt"
    ],
    "apis":[
       {
          "path":"/user",
          "description":"User session and profile"
       },
       {
          "path":"/system",
          "description":"System configuration"
       },
       {
          "path":"/db",
          "description":"Local database access"
       },
       {
          "path":"/email",
          "description":"Email utility access"
       },
       {
          "path":"/files",
          "description":"Local file storage access"
       },
       {
          "path":"/sql",
          "description":"Amazon RDS Sql"
       }
   ]
}

Therefore, I assume the set up is correct.
At the DSP end:-
1) I have defined a role, as "Amazon RDS" and have given service access of 'sql' to this role. Also, tried giving system access. Still not working.
2) In the CORS access inside Config, I have added * in the Host and selected all the HTTP verbs and enabled the same.
3) Checked the "Allow Guest Users" and also Selected the role "Amazon RDS" for guest users.
So, when I make this call later in my code:- DreamFactory.api.db.getRecords
I get the error:
- TypeError: Cannot read property 'getRecords' of undefined

Because the setup service itself is not getting instantiated properly.
Any help in this regard would be helpful.

A: A 403 means you don't have access to the app.  This can happen if you haven't created the app yet or your role doesn't have permission to access that app.  Check out this link for more info.
http://community.dreamfactory.com/t/unable-to-access-dsp-from-angularjs-mobile-app/478/14


text:
Q: JSON.Parse is duplicating the ID field I am passing the following JSON from a webservice:
{
"selList": [
    {
        "id": "selBaMbReasonExempt",
        "value": "Confidential Contract|Customer in migration to automation|Missing contract|Non-English contract|Non-Standard way of ordering|Other (please specify in comments)|",
        "html": "Confidential Contract|Customer in migration to automation|Missing contract|Non-English contract|Non-Standard way of ordering|Other (please specify in comments)|",
        "key": null,
        "optRate": null,
        "optDate": null
    },
    {
        "id": "selBaMbInvoiceCurrency",
        "value": "BRL|",
        "html": null,
        "key": "BR|",
        "optRate": "0.57833555028627600000|",
        "optDate": "01-Feb-2012"
    },
    {
        "id": "selBaMbContractCurrency",
        "value": "BRL|USD|",
        "html": null,
        "key": "BR|BR|",
        "optRate": "0.57833555028627600000|1.00000000000000000000|",
        "optDate": "01-Feb-2012"
    }
    ]
}

function getSelLists() {
    var wkError = false;
    var serverResponse;
    var ss;
    MbrtUtil.disableAjaxNotifier();
    jQuery.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "Webservices/TemplateBA.asmx/GetSelLists",
        data: "{'noOp': 'noOp'}",
        success: function (msg, status) {
            serverResponse = JSON.parse(msg);
            ss = msg;
        },
        error: function (request, status, error) {
            wkError = true;
        },
        complete: function (msg) {
            if (wkError == true) {
                alert('Error in getSelLists');
            }
            else {
                MbrtUtil.processServerData(serverResponse);
                if ('sdkList' in serverResponse) {
                    alert('selList is in serverResponse');
                    var selList = serverResponse.sdkList;
                    wklen = selList.length;
                    for (var i = 0; i < wklen; i++) {
                        //  if (selList[i].id == 'selBaCsInvoiceCountry') { MODba.invoiceCountryList = selList[i]; }
                        //   if (selList[i].id = 'selBaCsPaymentTerms') { MODba.paymentTermsList = selList[i]; }
                        if (selList[i].id = 'selBaMbInvoiceCurrency') { MODba.invoiceCurrencyList = selList[i]; }
                        if (selList[i].id = 'selBaMbContractCurrency') { MODba.contractCurrencyList = selList[i]; }

                        if (selList[i].id == 'selBaMbReasonExempt') {
                            alert('exempt list');
                            MODba.reasonExempt = selList[i];
                            if (wkOpt == 2) {
                                buildReasonExemptList();
                            }
                        }
                    }
                    var valList = MODba.reasonExempt.value.split("|");  //delete this
                    if (wkOpt == 1) {
                        buildRequestorLists();
                    }
                }
                MbrtUtil.enableAjaxNotifier();
            }
        }
    });
}

I checked the syntax through JSONLint.  I have a jQuery ajax call to the webservice.  On completion, the message looks like the code shown above.  After running serverResponse = JSON.parse(msg), serverResponse contains three selList objects.  Everything looks fine on them EXCEPT the "id" field of all three contains "selBaMbContractCurrency".  Any ideas?

A: Use double '=', when comparing:
if (selList[i].id == 'selBaMbContractCurrency')

In such cases, it is better to use switch:
for (var i = 0; i < wklen; i++) {
     switch(selList[i].id){
         case 'selBaMbInvoiceCurrency':
             MODba.invoiceCurrencyList = selList[i];
             break;
         case 'selBaMbContractCurrency':
             MODba.contractCurrencyList = selList[i];
             break;
         case 'selBaMbReasonExempt':
             alert('exempt list');
             MODba.reasonExempt = selList[i];
             if (wkOpt == 2) {
                 buildReasonExemptList();
             }
             break;
     }
}

It is more readable, and obvious.


text:
Q: How to pluck aliased column from joined tables in rom-sql? I cannot find how to pluck aliased column using rom-sql.
Given relations users and avatars (user has many avatars).
# works
users.join(:avatars).select { |r| r.avatars[:id] }.pluck(:id)

# does not work
users.join(:avatars).select { |r| r.avatars[:id].as(:avatar_id) }.pluck(:avatar_id)
# NoMethodError: undefined method `[]' for nil:NilClass
# from /usr/local/bundle/gems/rom-core-4.2.1/lib/rom/schema.rb:195:in `[]'

# more examples
users.join(:avatars).select{|r| r.avatars[:id].as('avatar_id')}
#=> #<Persistence::Relations::Users name=ROM::Relation::Name(users) dataset=#<Sequel::Postgres::Dataset: "SELECT \"avatars\".\"id\" AS \"avatar_id\" FROM \"users\" INNER JOIN \"avatars\" ON (\"users\".\"id\" = \"avatars\".\"user_id\") ORDER BY \"users\".\"id\"">>

users.join(:avatars).select{|r| r.avatars[:id].as('avatar_id')}.to_a
#> Dry::Struct::Error: [Entities::User.new] :avatar_id is missing in Hash input

users.join(:avatars).select{|r| r.avatars[:id].as('avatar_id')}.with(auto_struct: false).to_a
#=> [{:avatar_id=>88}, {:avatar_id=>89}]

A: It's impossible to suggest any solution if the version of the used libraries is not specified. For rom-sql 2.4.0 it just works:
#!/usr/bin/env ruby

# frozen_string_literal: true

require 'bundler/inline'

gemfile(false) do
  source 'https://rubygems.org'

  gem 'sqlite3'
  gem 'rom-sql', '2.4.0'
  gem 'rspec'
end

require 'rspec'
require 'rspec/autorun'

require 'dry-types'
require 'rom-sql'
require 'sqlite3'

RSpec.describe do
  let(:uri) { 'sqlite::memory' }
  let(:conn) { Sequel.connect(uri) }
  let(:conf) { ROM::Configuration.new(:sql, conn) }
  let(:container) { ROM.container(conf) }

  let(:avatars) { container.relations[:avatars] }
  let(:users) { container.relations[:users] }

  before do
    conn.create_table(:avatars) do
      primary_key :id
      Integer :user_id
      String :url
    end

    conn.create_table(:users) { primary_key :id }

    conf.relation(:avatars) do
      schema(infer: true) do
        associations do
          belongs_to :user
        end
      end
    end

    conf.relation(:users) do
      schema(infer: true) do
        associations do
          has_many :avatars
        end
      end
    end
  end

  subject(:relation) do
    users.join(:avatars).select { relations[:avatars][:url].as(:avatar_url) }
  end

  it do
    users.insert
    avatars.insert(user_id: 1, url: 'avatars/1')
    avatars.insert(user_id: 1, url: 'avatars/2')

    expect { relation.pluck(:avatar_url) }.not_to raise_error
    expect(relation.pluck(:avatar_url)).to eq ['avatars/1', 'avatars/2']
  end
end


text:
Q: Command to convert hexdump back to text I am using Catfish to find files containing certain text. Some of the files found instead of plain text contain something which looks like a hex dump:
3c3f 7068 700a 0a66 756e 6374 696f 6e20
7573 6572 5f65 7869 7374 7328 2475 6e29
207b 0a09 7265 7475 726e 2074 7275 653b
0a7d 0a0a 0a3f 3e00 0000 0000 0000 0000

I.e. always 8 columns and each row containing 16 bytes. Line one above should be

<?php
function

Is there a command to unhex the file and print the content?

A: Use xxd with the revert option -r
xxd -p -r file.txt

gives a result of
<?php

function user_exists($un) {
        return true;
}

?>

A: With bash:
for block in $(cat file); do
  [[ $block =~ (..)(..) ]] && echo -en "\x${BASH_REMATCH[1]}\x${BASH_REMATCH[2]}"
done

Output:
<?php

function user_exists($un) {
        return true;
}

?>

A: echo -e "$(sed -r 's@\s*([a-f0-9][a-f0-9])\s*@\\U\1@g' < test.txt | tr -d '\n')"

The sed regex capture couple of two hexadecimal characters and zero or more spaces from the begin and from the end of the match and convert it to unicode character removing spaces (g is global sostitution and -r enable extended regex).
tr remove line feed present in the file
echo -e translate unicode to ascii character


text:
Q: How to clear PHP $_SESSION by apache? I restarted apache,but the session doesn't expire!

A: Why not use session_destroy() to destroy the client's session?

A: If you have:
session.save_handler = files

in your php.ini file, which I believe you will by default, then session data will be stored in files. Therefore bouncing the server won't destroy them.

A: What I ussually do when I'm developing, I create a page that unsets and destroys all sessions. So everytime I need to destoy the sessions I run the script. eg. www.example.com/destroySession.php
destroySession.php contains something like (only an example)
session_start();
unset($_SESSION['name']); //If only one session variable is used
session_destroy();

A: Delete all files in the temporary directory defined in php.ini.


text:
Q: Adding a Menu Item to Netbeans platform Menu Bar I'm trying to create a mock menu for a module of my netbeans platform project (which I'm starting).
I want to create a new entry "New" in "File" that would have "New Project" and "New Module".
In Important Files -> Xml Layer -> this layer in context -> Menu Bar -> File I've created a new folder "New", and it displays as it should.
Then I've added two empty files, "New Project" and "New Module", but they don't show.
Here's layer.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 1.2//EN" "http://www.netbeans.org/dtds/filesystem-1_2.dtd">
<filesystem>
    <folder name="Actions">
        <folder name="File"/>
    </folder>
    <folder name="Menu">
        <folder name="File">
                            <folder name="New">
                <file name="New Module" url="New Module_2">
                    <attr name="requireProject" boolvalue="false"/>
                    <attr name="position" intvalue="800"/>
                </file>
                <file name="New Project" url="New Project_3">
                    <attr name="requireProject" boolvalue="false"/>
                    <attr name="position" intvalue="600"/>
                </file>
            </folder>
        </folder>
    </folder>
</filesystem>

I've deleted and created these files several times, hence the suffixes. The only thing I've added is positions.
I guess I'm either missing something or I misinterpreted something. I've read the documentation, but cannot find the answer.
So, how do I add and display a Menu Item?

A: I think that your <file name should point to instances of Action. For example:
<file name="org-netbeans-core-actions-SystemExit.shadow">
    <attr name="originalFile" stringvalue="Actions/System/org-netbeans-core-actions-SystemExit.instance"/>
    <attr name="position" intvalue="2600"/>
</file>

From NetBeans documentation:

The main menu of the application is composed by reading Menu/ folder in the layer. A sub folder is treated as a sub menu. Instances of individual files (usually .instance or .shadow) may then represent Action or JMenuItem or JSeparator.

source: http://bits.netbeans.org/dev/javadoc/layers.html
Also here:
http://wiki.netbeans.org/DevFaqSystemFilesystem
You can easily create actions with the wizard.


text:
Q: Adding HTML to Wordpress CSS Stylesheet Is is possible to add an html code to a css style sheet? like setting an css code to work with the html to pass through?

A: I'm not sure what it is you're trying to do...
but, as far as I know html can not be placed inside style tags or in external style sheets.
Are you trying to do an inline style? like this:

Hello World?

What have you tried?

A: Try this:


text:
Q: Disable round-robin message consumption on MassTransit I have created a basic demo pub/sub application which works on localhost with MassTransit.
What I want to achieve is to publish a message and all the subscribers should receive the message.
At the moment, in my environment I start one publisher app and two subscriber apps. But when I publish a message the subscribers receive the message in turns.
My pub/sub code:
Publish:
var bus = Bus.Factory.CreateUsingRabbitMq(config =>
{
  config.Host(new Uri("rabbitmq://localhost/"), h => { });
  config.ExchangeType = ExchangeType.Fanout;
});
var busHandle = bus.Start();
bus.Publish<SomethingHappened>(message);

Subscribers use this code:
var bus = Bus.Factory.CreateUsingRabbitMq(config =>
{
  var host = config.Host(new Uri("rabbitmq://localhost/"), h => { });
  config.ReceiveEndpoint(host, "MassTransitExample_Queue", e => e.Consumer<SomethingHappenedConsumer>());
});

var busHandle = bus.Start();
Console.ReadKey();
busHandle.Stop();

A: When reading the article below I found that the queue name must be unique
https://www.maldworth.com/2015/10/27/masstransit-send-vs-publish/

When building your bus and registering an endpoint like so:
  sbc.ReceiveEndpoint(...), one has to be sure that the queueName
  parameter is unique.

So my subscribers code looks like this now:
var bus = Bus.Factory.CreateUsingRabbitMq(config =>
{
  var host = config.Host(new Uri("rabbitmq://localhost/"), h => { });
  config.ReceiveEndpoint(host, "MTExQueue_" + Guid.NewGuid().ToString(), e => e.Consumer<SomethingHappenedConsumer>());
});

var busHandle = bus.Start();
Console.ReadKey();
busHandle.Stop();


text:
Q: How to ignore certain fetch requests in cypress cy.visit When calling cy.visit("https://my-page.com") my page will fetch a number of external libraries/scripts. One of them is for sentry.io. Sometimes this particular fetch will just hang forever. The website is perfectly usable without it. Is there a way to make cy.visit not wait for these fetch requests from certain domains?

A: Some things to try, depends on how the app responds
Controlling the response

req.destroy() - destroy the request and respond with a network error

cy.intercept('https://sentry.io/*', req => req.destroy())

req.reply() - stub out a response requiring no dependency on a real back-end

cy.intercept('https://sentry.io/*', {})  // stubbed, never goes to the server

You may have to tweak {} to include fake properties if the app expects them.


text:
Q: How do I force Mathematica to include user defined functions in Simplify and FullSimplify? Let's say I have a relation r^2 = x^2 + y^2. Now suppose after a calculation i get a complicated output of x and y, but which could in theory be simplified a lot by using the above relation. How do I tell Mathematica to do that?
I'm referring to situations where replacement rules x^2+y^2 -> r^2 and using Simplify/FullSimplify with Assumptions won't work, e.g. if the output is x/y + y/x = (x^2+y^2)/(xy) = r^2/(xy).
Simplification works really well with built in functions but not with user defined functions! So essentially I would like my functions to be treated like the built in functions!

A: I believe you are looking for TransformationFunctions.
f = # /. x^2 + y^2 -> r^2 &;

Simplify[x/y + y/x, TransformationFunctions -> {Automatic, f}]

(* Out=  r^2/(x y)  *)

A: In the example you give
(x/y + y/x // Together) /. {x^2 + y^2 -> r^2}

==> r^2/(x y)

works. But I've learned that in many occasions replacements like this don't work. A tip I once got was to replace this replacement with one which has a more simpler LHS like: x^2 -> r^2-y^2 (or even x->Sqrt[r^2-y^2] if you know that the values of x and y allow this).


text:
Q: Proper indentation for using scanf("%[^\n]%*c", s) statement to get string I use scanf("%[^\n]%*c", s) statement to get string, but what is the proper indentation to print this string?
I am a beginner and overall confused with string input-output instructions. Some tips on this topic would be helpful...!


text:
Q: How can I write to JSON file, without deleting all the content in it? import json
f = open("filename.json", "w")
data = {"username": "justausername"}
json.dump(data, f)

When I run this code, all the data in the "filename.json" is replaced by "{'username': 'justausername'}". Please help!

A: *

*Read the file

*Parse the JSON to a data structure

*Modify the data structure instead of creating a new one

*Serialise the data structure back to JSON

*Write it to the file

Consider using a real database instead so that you get benefits like automatic protection for concurrent edits. SQLite is a good choice if you want a single file to store the data in.

A: import json

with open("filename.json", "r") as f:  # reading a file
    data = json.load(f)  # deserialization

data["username"] = "justausername"  # modifying the python object

with open("filename.json", "w") as f:
    json.dump(data, f)  # serializing back to the original file


text:
Q: LibGDX scale a slider, HOW? How can I scale a slider in LibGDX?
Im trying to scale a slider with:
slider.scale(10); (for example)
but when I try that i cant interact with the slider that leads to me thinking that the slider ist scaled but rendered normally. I render it with slider.draw(batch, 1);
Has anyone got an idea?

A: For performance reason most scene2d.ui groups have transform set to false by default.
For more detail you can check

https://github.com/libgdx/libgdx/wiki/Scene2d.ui#rotation-and-scale
If you want to scale you can use Container which is useful for setting the size and alignment of a single widget.
@Override
public void create() {
    stage=new Stage();
    Skin skin=new Skin(Gdx.files.internal("skin/uiskin.json"));

    Slider slider=new Slider(0,100,1,false,skin);

    Container<Slider> container=new Container<Slider>(slider);
    container.setTransform(true);   // for enabling scaling and rotation
    container.size(100, 60);
    container.setOrigin(container.getWidth() / 2, container.getHeight() / 2);
    container.setPosition(100,200);
    container.setScale(3);  //scale according to your requirement

    stage.addActor(container);
}

@Override
public void render() {
    super.render();

    Gdx.gl.glClearColor(1,1,1,1);
    gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    stage.draw();
    stage.act();
}


text:
Q: It is not possible to set size from iPhone to iPad Full Screen I developed an iPhone app and want to extend this app for the iPad. Therefore I copied the XIBs and changed the document type from com.apple.InterfaceBuilder3.CocoaTouch.XIB to com.apple.InterfaceBuilder3.CocoaTouch.iPad.XIB and named the XIBs as follows: "UIFile.xib" as "UIFile~iPad.xib" …
Now I tried to change the size from the views inside the attribute inspector from "iPhone" to "iPad Full Screen". It worked for the launch screen, but not for the localized XIBs. I can change the values directly in the source code, but it has no affect for the graphical view inside the Interface Builder. They just have the same sizes as for the iPhone XIBs. Now it is difficult to place the view components like buttons at new position.
How can I resize the View to "iPad Full Screen"?

A: You can use in each class
- (void) viewDidLayoutSubviews
    {
    if ([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad) {
    CGRect viewBounds = self.view.bounds;
    CGFloat topBarOffset = self.topLayoutGuide.length;
    viewBounds.origin.y = topBarOffset * -1;
    self.view.bounds = viewBounds;
    }
}

A: Think I have to use the Size Classes. After activating the Size Classes it is possible.


text:
Q: The common practice to share file for all users on the same machine? There is a server with several users.
A user may want to read another user's files (few gigabytes) and may want to put processed files in other's directory.
What's the common practice to do it? I can think of create a /share folder and make it rwx to all. Is this the common practice?

A: For occasional use, the common practice is that each user creates files in their own home directory. ~/pub is a common name of a directory for files all other users are supposed to be able access. If only a subset of users may access certain files, use groups or access control lists to manage permissions.
For more advanced use, when multiple users may work on the same file, use a version control system. There's no really standard place to store the (master) repository; I've seen repositories under ~someuser/$project, /net/repositories/$project, /srv/repositories/$project, /var/www/$project, /home/$project, etc.

A: I think you are searching for /usr/local/share/ but it is hard to answer since this depends on what kind of file your are planning to "share" between users.
But if we are talking about office files or something like that maybe you should use use some kind of revision system like subversion or git. And then the users will have a checkout/clone in their homedir.

Update: A way to make this a little bit better could would be that every user gets it's own subdir in the shared folder. He is allowed to write in his own folder but not the other subfolders. And all users are allowed to read from all the directories. That way you don't have to think about file collisions if two users use the same filename, or deletes the colleges files by mistake.
Btw the idea behind /usr/ is described in the Filesystem Hierarchy Standard ( http://www.pathname.com/fhs/2.2/fhs-4.1.html )
-"/usr is shareable, read-only data."
So I would probably use a dir in either /home/ or /var/ instead...


text:
Q: Waterline in SailsJS doesn't seem to catch unique constraint In SailsJS, when I have an attribute on a model like:
email: { type: 'email',  unique: true}

For some reason, Waterline doesn't catch duplicates, but of course Mongo does.  It throws a Mongo error, but Waterline never catches it with WLValidationError.
Anyone having this error?  I can't seem to get WLValidationError to work.
Thanks

A: I've had this problem too, to overcome I added this to the User model.  I do not like this implementation, but it worked for me when nothing else did.
beforeCreate: function(values, cb) {
    User.findOne({email : values.email}, function(err, user){
        if(user){
            return cb('E-mail address already existis');
        } else {
            cb();
        }
    });
}

Docs here:
https://github.com/balderdashy/waterline#lifecycle-callbacks


text:
Q: How to convert bytes to dictionary? I need to convent bytes to dict.
I requested some content from a website and got back a bytes list as a response. I need is as a dict to parse it.
My code:
import ast

data= requests.get('blahblahblah.com')

The data received in bytes looks like this:
b'{"response": {"message": null, "data": [{"friendly_name": "Local", "user_id": 0}, {"friendly_name": "cinematopiamedia2", "user_id": 25431133}, {"friendly_name": "Aknight2015", "user_id": 23505515}, {"friendly_name": "aloyisunique", "user_id": 7332509}, {"friendly_name": "Alwaysbhere", "user_id": 23060332}, {"friendly_name": "Bastarded", "user_id": 25476710}, {"friendly_name": "bellmatsu", "user_id": 11768932}, {"friendly_name": "Calibear14", "user_id": 22882269}, {"friendly_name": "cbjay45820@gmail.com", "user_id": 25740986}, {"friendly_name": "ChocoboBurger", "user_id": 24689117}, {"friendly_name": "CrayPharma", "user_id": 14869791}, {"friendly_name": "cree23", "user_id": 24241253}, {"friendly_name": "crystaljock", "user_id": 24618156}, {"friendly_name": "dared24", "user_id": 25194790}, {"friendly_name": "DarkWolfNine", "user_id": 1132520}, {"friendly_name": "DennyCrane12", "user_id": 20646060}, {"friendly_name": "devharding", "user_id": 24244101}, {"friendly_name": "ElJeppy", "user_id": 11420141}, {"friendly_name": "emilstricker", "user_id": 268195}, {"friendly_name": "fjones1979", "user_id": 36905}, {"friendly_name": "frikkels123", "user_id": 12222188}, {"friendly_name": "graciesusan", "user_id": 24818998}, {"friendly_name": "Greenwo0d", "user_id": 1548410}, {"friendly_name": "grttinp", "user_id": 20628044}, {"friendly_name": "Hassled1", "user_id": 2877418}, {"friendly_name": "imdragon", "user_id": 13954870}, {"friendly_name": "iviogle08@gmail.com", "user_id": 17549794}, {"friendly_name": "jay.tyu", "user_id": 14055795}, {"friendly_name": "jefnull", "user_id": 3303610}, {"friendly_name": "jingkoo", "user_id": 14512376}, {"friendly_name": "jkind73", "user_id": 179199}, {"friendly_name": "jojoplatinum", "user_id": 25436659}, {"friendly_name": "jumur", "user_id": 24982579}, {"friendly_name": "kantarin", "user_id": 21578150}, {"friendly_name": "Killfury13", "user_id": 283266}, {"friendly_name": "licquyd", "user_id": 10814806}, {"friendly_name": "LinuxOS", "user_id": 25246528}, {"friendly_name": "login123", "user_id": 9769776}, {"friendly_name": "Lokanas", "user_id": 8194426}, {"friendly_name": "Looser2786", "user_id": 24536524}, {"friendly_name": "mcmcguirl", "user_id": 3138953}, {"friendly_name": "ndiniwacho", "user_id": 1534152}, {"friendly_name": "nemethmm", "user_id": 3196505}, {"friendly_name": "nicholasalan126", "user_id": 4627399}, {"friendly_name": "ossinova", "user_id": 6572284}, {"friendly_name": "Phoenixfighter65", "user_id": 24399546}, {"friendly_name": "Pirate_321", "user_id": 23574312}, {"friendly_name": "poplida", "user_id": 18469171}, {"friendly_name": "Quzehh", "user_id": 4026309}, {"friendly_name": "RubberDucky25", "user_id": 23209468}, {"friendly_name": "saotome128", "user_id": 16655435}, {"friendly_name": "scatterscott", "user_id": 1080098}, {"friendly_name": "sfaze", "user_id": 24123475},
{"friendly_name": "shawnieb", "user_id": 346644}, {"friendly_name": "Sid87", "user_id": 25570077}, {"friendly_name": "SilentSlayerOWI", "user_id": 13376510}, {"friendly_name": "SpeedyAus", "user_id": 23313023}, {"friendly_name": "Srmouzon", "user_id": 22870338}, {"friendly_name": "StandardSushi", "user_id": 24112439}, {"friendly_name": "tatui101", "user_id": 23966159}, {"friendly_name": "TPSeer", "user_id": 19499153}, {"friendly_name": "treyseaboldt", "user_id": 13511995}, {"friendly_name": "tripredagus", "user_id": 25044787}, {"friendly_name": "tulpam16", "user_id": 24237322}, {"friendly_name": "underlow", "user_id": 15606369}, {"friendly_name": "WhiteBoy84", "user_id": 21068833}, {"friendly_name": "wyofreeride", "user_id": 3727029}, {"friendly_name": "Zoophy", "user_id": 3835968}],
"result": "success"}}'

A: You can use requests's .json():
requests.get('blahblahblah.com').json()


text:
Q: Source of qt5 cmake Config-file Packages Trying to build qt5 with buildroot. I need to download the source so that everything is compiled through the cross-compiler.
One of my project relies on the 'Config-file Packages' (CMake helper config file) provided by Qt5 in the binary tarball at this location Qt5.8.0/5.8/gcc_64/lib/cmake.
Problem: I can't find that folder anywhere in the source. When I take one example file  (e.g. Qt5Config.cmake), I can't find any git repo hosting it.
Had a look at Ubuntu packages and it is being distributed in qtbase5-dev. When I look at this package documentation, it says it is using qtbase-opensource-src 5.5.1+dfsg-16ubuntu7.4 as the source package. Had a look at the source package for 5.8 but the cmake files are not there.
I could upload those files in an ad-hoc git repo, but that just seems weird that those files are not hosted by the qt repo.
What am I missing?

A: The cmake files are generated while build. On Linux the results are installed to qt/lib/cmake.


text:
Q: Time Out when Executing a SQL Query. Any Solution? We use a google script to get data from a SQL database into a spreadsheet. There is a time-driven trigger for the function.
Every time I run the function, there is a time out.

Exception: The query has timed out

When I run the function a second time, it usually works fine. Does anybody has a solution for that?
The address and password of the Database is not shown here.
function onOpen() {
var spreadsheet = SpreadsheetApp.getActive();

var menuItems = [
    {name: 'JTL Import', functionName: 'readData'}
];
spreadsheet.addMenu('JTL-Import', menuItems);
}

// Replace the variables in this block with real values.
var address = 'XXXX'; //ex. '10.1.1.1:1433'
var user = 'TAXDOO';
var userPwd = 'XXX';
var db = 'eazybusiness';

var dbUrl = 'jdbc:sqlserver://' + address + ';databaseName=' + db;

function StockUnitsSold30days() {
 var conn = Jdbc.getConnection(dbUrl, user, userPwd);

 var stmt = conn.createStatement();

 var results = stmt.executeQuery("SELECT a.cArtNr SKU, aaI18n.cwertvarchar [Cut_ID], CONVERT(FLOAT, ISNULL(wmsLager.fbestand, 0)) [Stock_WMS], CONVERT(FLOAT, ISNULL(StreckenLager.fbestand, 0)) [Stock_Streckenlager], CONVERT(FLOAT, ISNULL(fba.fanzahlfba, 0)) [Stock_FBA], CONVERT(FLOAT, ISNULL(PendingLager.fbestand, 0)) [Stock_Pending], CONVERT(FLOAT, ISNULL(WmsAusgang.Anzahl, 0)) [Units_WMS_Outgoing], CONVERT(FLOAT, ISNULL(fbaAusgang.SumAnzahl, 0)) [Units_FBA_Outgoing],CONVERT(FLOAT, ISNULL(MengeAufWarenEingang.fAnzahlAktuell,0)) [Stock_Wareneingangsplatz] FROM dbo.tartikel a INNER JOIN dbo.tartikelattribut aa ON aa.kartikel = a.kartikel INNER JOIN dbo.tartikelattributsprache aaI18n ON aaI18n.kartikelattribut = aa.kartikelattribut AND aaI18n.ksprache = 0 INNER JOIN dbo.tattributsprache attributI18n ON attributI18n.kattribut = aa.kattribut AND attributI18n.ksprache = 0 AND attributI18n.cname = 'CutDesign_ID' LEFT OUTER JOIN dbo.vlagerbestandfba fba ON a.kArtikel = fba.kartikel LEFT OUTER JOIN dbo.vlagerbestandprolageralle wmsLager ON wmsLAger.kartikel = a.kArtikel AND wmsLager.kwarenlager = 4 LEFT OUTER JOIN dbo.vlagerbestandprolageralle StreckenLager ON StreckenLager.kartikel = a.kArtikel AND Streckenlager.kwarenlager = 5 LEFT OUTER JOIN dbo.vlagerbestandprolageralle PendingLager ON PendingLager.kartikel = a.kArtikel AND PendingLager.kwarenlager = 7 LEFT OUTER JOIN (SELECT a.kArtikel, SUM(wla.fAnzahl) Anzahl FROM   dbo.tBestellung b JOIN dbo.tbestellpos bp ON bp.tBestellung_kBestellung = b.kBestellung JOIN dbo.trechnung r ON r.tBestellung_kBestellung = b.kBestellung JOIN dbo.tLieferschein l ON l.kBestellung = b.kBestellung JOIN dbo.tLieferscheinPos lp ON lp.kBestellPos = bp.kBestellPos JOIN dbo.tWarenLagerAusgang wla ON wla.kLieferscheinPos = lp.kLieferscheinPos JOIN dbo.tArtikel a ON bp.tArtikel_kArtikel = a.kArtikel WHERE  DATEDIFF(dd, b.derstellt, GETDATE()) <= 30 GROUP BY a.kArtikel ) AS WmsAusgang ON WmsAusgang.kArtikel = a.kArtikel LEFT OUTER JOIN (SELECT map.kArtikel, SUM(abp.nQuantityPurchased) SumAnzahl FROM   dbo.pf_amazon_bestellung ab JOIN dbo.pf_amazon_bestellungpos abp ON abp.kAmazonBestellung = ab.kAmazonBestellung JOIN dbo.tBestellung b ON b.cInetBestellNr = ab.cOrderId JOIN dbo.trechnung r ON r.tBestellung_kBestellung = b.kBestellung JOIN dbo.pf_amazon_angebot_mapping map ON map.cSellerSKU = abp.cArtNr WHERE  nFBA = 1 AND cOrderStatus = 'Shipped' AND DATEDIFF(dd, b.derstellt, GETDATE()) <= 30 GROUP BY map.kArtikel) FbaAusgang ON FbaAusgang.kArtikel = a.kArtikel LEFT OUTER JOIN (SELECT DISTINCT ta.kArtikel, twle.fAnzahlAktuell FROM dbo.tArtikel ta JOIN dbo.tWarenLagerEingang twle ON twle.kArtikel = ta.kArtikel JOIN dbo.tWarenlagerPlatz twlp ON twle.kWarenLagerPlatz = twlp.kWarenLagerPlatz WHERE twlp.cName    = 'Wareneingangsplatz') MengeAufWarenEingang ON MengeAufWarenEingang.kArtikel = a.kArtikel");
 var metaData=results.getMetaData();
 var numCols = metaData.getColumnCount();

 var spreadsheet = SpreadsheetApp.getActive();
 var sheet = spreadsheet.getSheetByName("Test");
 //you can use the following line to get the active sheet
 //var sheet = SpreadsheetApp.getActiveSheet();

 sheet.clearContents();

 var arr=[];

 for (var col = 0; col < numCols; col++) {
  arr.push(metaData.getColumnName(col + 1));
 }

 sheet.appendRow(arr);

 while (results.next()) {
  arr=[];

  for (var col = 0; col < numCols; col++) {

   arr.push(results.getString(col + 1));
  }
 sheet.appendRow(arr);

}

results.close();
stmt.close();

sheet.autoResizeColumns(1, numCols+1);

}```

A: Runs slow first time and then fast right after can be a sign of a poorly optimized query.
If there' a table scan, the data might be loaded into cache the first time. It's in cache the second time.
That's a lot of JOINS and a big query.  I would recommend a stored procedure if it's an option. The query plan might indicate missing indexes.  It should also show the most expensive operations.
If 30 days is is a small fraction of the data and derstellt has an index, then compare the column directly to a date.  Wrapping a DATEDIFF around the column prevents effective use of the index on that column.
DECLARE @TodayMinus29DaysMidnight datetime = CAST(GETDATE() - 29 as date)
SELECT...
WHERE b.derstellt < @TodayMinus29DaysMidnight
I would also verify the derived table with the DISINCT.  Would a GROUP BY be better?


text:
Q: Scale svg content to fit page size (or vice versa) without inkscape I want to scale an SVG image to fit the page size (or vice versa: crop the page to fit is contents). This can be done using inkscape as described here. However, there seems to be no way of doings this without gui. Using actions and verbs via the command line will always require GUI. Is there an alternative way of archieving this?

A: Your question is not very clear as to what you wish to ask specifically, I am answering if you wish to
Scale Svg to ft the page size in HTML document
If you change the viewBox property of SVG to a different ratio than the height and width ratio of the image than the SVG will not fit the page as by default there is a property to <svg> tag called PreserveAspactRatio that is set to meet by default. You will have to change this property to clip so that the SVG fills the complete viewport.
The image will distort if you define different aspect ratio than the ratio of height and width of SVG but it will fill the page nontheless.
Just add this code in  tag and you're good.
preserveAspectRatio = "xMinYMin slice"

It can have different arguments before slice namely
none

Do not force uniform scaling. Scale the graphic content of the given element non-uniformly (without preserving aspect ratio) if necessary such that the element's bounding box exactly matches the viewport rectangle.
xMinYMin

Force uniform scaling.
Align the  of the element's viewBox with the smallest X value of the viewport.
Align the  of the element's viewBox with the smallest Y value of the viewport.
xMinYMid

Force uniform scaling.
Align the  of the element's viewBox with the smallest X value of the viewport.
Align the midpoint Y value of the element's viewBox with the midpoint Y value of the viewport.
xMaxYMax

Force uniform scaling.
Align the + of the element's viewBox with the maximum X value of the viewport.
Align the + of the element's viewBox with the maximum Y value of the viewport.
etc..
For more details, you can refer to this article if your problem is related to web specifically.


text:
Q: How to set authentication headers dynamically in soapUI? I have around 50 test steps included in my test suite. Currently I am setting the authentication headers (auth_token, id_token and nonce) values for each test step manually. How can I set the values for all the test steps at once?
It would be great if you could help me set the dynamic headers in test suite level.

A: If the values are the same for each test step, you could set custom properties at the the test suite level and refer to the properties in your headers:

See Working with Properties for more details.


text:
Q: Creating a loop in R which also changes the column name I am attempting to loop a command based upon a list (fish_species). And while I've found plenty of examples, I haven't found one that also includes changing the column name as part of the loop.  I have figured out how to get the desired result for an individual species (lines 10-13), but in the actual dataset I have ~500 species, and I'd prefer not to repeat this command 500+ times. Is there a way to substitute the values from a list where it says variable?
Fishdata$variable <- ifelse(fishdata$Species== "variable",fishdata$Number,0)

I know how to do this is ArcGIS, but I am trying to expand my horizons and learn R. This is also my first post, so please excuse any screw ups.
Thank you for any help you can provide.
fishdata <-c()
fishdata$Site <-c(1,1,1,2,2,2)
fishdata$Species <- c("one_fish", "two_fish", "two_fish", "red_fish", "blue_fish", "blue_fish")
fishdata$Number <- c(1,1,1,1,1,1)
fishdata$one_fish <-0
fishdata$two_fish <-0
fishdata$red_fish <-0
fishdata$blue_fish <-0
fish_list <- c("one_fish","two_fish", "red_fish", "blue_fish")
fishdata$one_fish <- ifelse(fishdata$Species=="one_fish",fishdata$Number,0)
fishdata$two_fish <- ifelse(fishdata$Species=="two_fish",fishdata$Number,0)
fishdata$red_fish <- ifelse(fishdata$Species=="red_fish",fishdata$Number,0)
fishdata$blue_fish <- ifelse(fishdata$Species=="blue_fish",fishdata$Number,0)

A: You can use sapply to iterate over species,
sapply(fishdata$Species, function(i)ifelse(fishdata$Species== i, fishdata$Number,0))

#     one_fish two_fish two_fish red_fish blue_fish blue_fish
#[1,]        1        0        0        0         0         0
#[2,]        0        1        1        0         0         0
#[3,]        0        1        1        0         0         0
#[4,]        0        0        0        1         0         0
#[5,]        0        0        0        0         1         1
#[6,]        0        0        0        0         1         1

A: $ is just an alternative to the [] operator:
a$x
a["x"]

So you can do:
fishdata[species] <- ifelse(fishdata$Species == species, fishdata$Number, 0)

for (species in fish_species) {
    fishdata[species] <- ifelse(fishdata$Species == species, fishdata$Number, 0)
}


text:
Q: OpenGL: Use of multiple programs -> nothing drawn anymore I've generated multiple objects that are drawn properly with one program (i.e. one vertex shader and one fragment shader), which all run in the same context. I now wanted to add another object and I wanted to use it with a different program.
So, before calling glActiveTexture(), glBindTexture(),glBindBuffer(), glBufferData(), glEnableVertexAttribArray(), glVertexAttribPointer() and a few uniform commands, I call glUseProgram() with the appropriate programID.
The result is that nothing is drawn, when both kinds of objects are to be drawn. If I deactivate the objects that work with the first program, the new object is drawn properly and vice versa.
What are the things to bear in mind when switching programs.
Thanks.
Edit: When I investigated further, I noticed that an OpenGL error was thrown that I overlooked as it was consumed and not printed (grrr). As it turned out it wasn't an OpenGl mistake at all, but a rubymotion issue. (Didn't thought that at first.) Rubymotion garbage collected my OpenGL program, because I allocated it locally and only accessed it later over the glUseProgram(GLuint x). So I just made the program global in ruby and all the programs are working properly now. Thanks for the comments, though. You couldn't have known, my mistake, sry.


text:
Q: Relation between Areas Given a quadrilateral $ABCDEF$, where $B$ is the midpoint of $\overline{AC}$ and $E$ is the midpoint of $\overline{FD}$, prove the relation $$a+d = c+b,$$ where $a$, $b$, $c$, $d$ denote the respective areas of triangle as denoted by the following figure:

A: Let $O_1$ be $AE$ intersect $BF$, $O_2$ be $BD$ intersect $CE$.
$$S_{FO_1A}+S_{DO_2C}=S_{BO_1E}+S_{BO_2E} \Leftrightarrow$$
$$S_{FO_1A}+S_{O_1AB}+S_{DO_2C}+S_{O_2BC}=S_{BO_1E}+S_{O_1AB}+S_{BO_2E}+S_{O_2BC}
 \Leftrightarrow$$ $$ S_{FAB}+S_{DBC}=S_{AEC}$$
Let $FH_1, EH_2, DH_3$ be perpendiculars, dropped onto line $AC$. Then we need to prove only $FH_1+DH_3=2EH_2$ and it holds because of $EH_2$ being midline of $FH_1H_3D$.


text:
Q: Call url with axios.get with multiple params Vuejs I'm trying to call an api which have 2 params.
thi is the axios call
getData: function (id) {
    let subsidiary = this.$route.query.subsidiaryId;

    axios.get("https://localhost:44391/api/ContractType/ContractTypePhos?
subsidiaryId =& contractType=", { params: { subsidiaryId: subsidiary, contractTypeId: id }
})
        .then((res) => {
        if (res.data == "No Pho Founds") {
            swal(res.data);
            this.showGrid = true;
        } else { this.enabledPhos = res.data; }
    })
}

but it didn't work

A: I believe you have to remove everything after the '?' in the url, so your code will look like this:
getData: function (id) {
  let subsidiary = this.$route.query.subsidiaryId;

  axios.get(
    "https://localhost:44391/api/ContractType/ContractTypePhos",
    { params: {
      subsidiaryId: subsidiary,
      contractTypeId: id
    }})
    .then((res) => {
        if (res.data == "No Pho Founds") {
            swal(res.data);
            this.showGrid = true;
        } else { this.enabledPhos = res.data; }
    })
}

You shouldn't have spaces in your url strings. The browser will convert them to '%20' which will cause errors.


text:
Q: Can I use SQLCipher for commercial applications that users need to buy from Google APP I am developing application for commercial use. This APP will be made available in Google App for certain cost. I want to use SQLCipher to store encrypted data. Can I use SQLCipher for commercial applications?

A: Yes, SQLCipher can be used in commercial applications, but you must abide by the terms of the license, including reproduction of the copyright statements.

A: Yes, Even I am confused. I have used SQLCipher in iOS app and there is not any compliance issue. But in case of android, people are saying it it mandatory.
Related Link - https://discuss.zetetic.net/t/export-requirements-for-applications-using-sqlcipher/47


text:
Q: MySQL dirty reads vs dirty reads defined in SQL standard From MySQL manual:

READ UNCOMMITTED
SELECT statements are performed in a nonlocking fashion, but a possible earlier version of a row might be used. Thus, using this isolation level, such reads are not consistent. This is also called a dirty read. Otherwise, this isolation level works like READ COMMITTED.

The bolded part is confusing me. "Earlier version of a row might be used"? Used where? And how this can be called a "dirty read"?
SQL standard says dirty read contains data that has never existed:

P1 ("Dirty read"): SQL-transaction T1 modifies a row. SQL-transaction T2 then reads that row before T1 performs a COMMIT. If T1 then performs a ROLLBACK, T2 will have read a row that was never committed and that may thus be considered to have never existed.

Is MySQL manual wrong here or what?

A: The MySQL definition is one case of dirty read: The case when the row already exists (but is being updated by T1) and T2 reads it. Then if T1 rolls back, T2 may have performed wrong calculations with it. Ugly.
The SQL definition cover more cases. For example when the rows is being created for the first time by T1 (but not yet committed), and then is read by T2. In this case, if the transaction T1 is rolled back, it's like the row never existed.... but T2 is using it already for who knows what purposes. Ugly.
In sum, both cases are ugly and can lead to inconsistencies. The SQL Definition is more comprehensive, than MySQL's.


text:
Q: MySQL only return user from tableA if no specific value status in tableB? I have a table of user (table users) and a log table (table logs) with serval logs about the user. Now I'm looking for a way to return me a list of user where a specific value in the logs is missing.
Lets have the following example:
  table users        table logs
----------------   -----------------------------
| id | user    |   | id | user_id | status     |
----------------   -----------------------------
|  1 | user1   |   |  1 |       2 | send       |
----------------   -----------------------------
|  2 | user2   |   |  2 |       1 | send-error |
----------------   -----------------------------
|  3 | user3   |   |  3 |       3 | status-x   |
----------------   -----------------------------
                   |  4 |       1 | send       |
                   -----------------------------
                   |  5 |       3 | send-error |
                   -----------------------------

The following join returns me a list of all users and there logs:
SELECT u.id, u.name, l.status
FROM users u
LEFT JOIN logs l ON u.id = t.user_id
How can I select only the ones which have not the status 'send'? In this example it should just return id=3, user=user3.

A: SELECT u.id, u.name, l.status
FROM   users u
LEFT JOIN logs l ON u.id = l.user_id
WHERE  NOT EXISTS (SELECT 1 FROM logs g
                   WHERE  u.id = g.user_id
                   AND    g.status = 'send')

Basically, check out NOT EXISTS for queries like the one you want.  If the subquery would return no rows, the NOT EXISTS condition holds, and the row is returned.
Edit:
If you only wish to see which users do not have a status of "send" in the logs table:
SELECT u.id, u.name
FROM   users u
WHERE  NOT EXISTS (SELECT 1 FROM logs l
                   WHERE  u.id = l.user_id
                   AND    l.status = 'send')

This query avoids the need for GROUP BY just to get one user per row, if that is all you are trying to do.

A: SELECT u.id, u.user, l.status
FROM users u
LEFT JOIN logs l ON u.id = l.user_id
WHERE l.status not like '%send%'

You are already performing the left join (assuming that you want all users and those log entries where the user ID matches).  It's a simple matter then to check the status field for the absence of the word 'send'.


text:
Q: How to locate and click the textarea element using Selenium and Python I'm using Selenium with python and have been trying to click a text box, and input a message.
The text box's HTML looks like this:

            <textarea data-a-target="chat-input" data-test-selector="chat-input" class="tw-block tw-
            border-radius-medium tw-font-size-6 tw-full-width tw-textarea tw-textarea--no-resize"
            autocomplete="Messenger-chat" maxlength="500" placeholder="Send a message" rows="1"
            style="padding-right: 3.5rem;"></textarea>

I have been trying to select it by css selector with this code:
time.sleep(3)
input_box = browser.find_element_by_css_selector(".textarea")
input_box.click()
for ch in message:
    input_box.send_keys(ch)
input_box.send_keys(Keys.ENTER)

It keeps giving me a NoSuchElement. As you can see I don't really know what I am really doing- please help thanks :)

A: .texarea is not going to find any element:
. indicates that the selector should look for the proceeding value in the className of an element.
So, you are telling the selector to look for an element with className textarea.
You are confusing className selector with a tagname selector. If you want to get it by tagname, you just use the tagname without any dot(.), so:
find_element_by_css_selector("textarea")

This would return the first textarea element it finds, which may or may not be what you want. To make it more precise you can do:
find_element_by_css_selector("textarea.tw-block.tw-
        border-radius-medium.tw-font-size-6.tw-full-width.tw-textarea.tw-textarea--no-resize")

Notice how in the second version there are multiple dots(.) in the selector, telling the engine to search for an element of tagname textarea with classNames: tw-block tw-
            border-radius-medium tw-font-size-6 tw-full-width tw-textarea tw-textarea--no-resize. Each individual className is seperated by a space in the Html markup, so you use a dot(.) to tell the selector to chain those classNames together.
If by chance you have multiple textarea's with all the same classNames as above, you'd need to find some kind of unique identifier for the textarea you want. So the selector provided by KunduK is a good example of that.
Perhaps this link will help you to learn more about css selectors: (https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors)

A: As per the HTML the element is a <textarea> element. So to identify the element the relevant code would have been either of the following:

*

*browser.find_element_by_tag_name("textarea")

*browser.find_element_by_css_selector("textarea[attribute_name='attribute_value']")
Solution
Ideally, to identify and click within the desired element you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following  Locator Strategies:

*

*Using CSS_SELECTOR:
input_box = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "textarea[data-a-target='chat-input'][data-test-selector='chat-input'][placeholder='Send a message']")))
input_box.click()

*Using XPATH:
input_box = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//textarea[@data-a-target='chat-input' and @data-test-selector='chat-input'][@placeholder='Send a message']")))
input_box.click()

*Note : You have to add the following imports:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

A: Your css selector is wrong .textarea in css selector identify the class name.
Try below css selector.
input_box = browser.find_element_by_css_selector("textarea[data-a-target='chat-input']")


text:
Q: Broken images marker on leaflet map Good afternoon everyone, I think a screenshot will tell better than words:
I would like a real marker instead of what is actually printed...
Here is the corresponding server.R part of the code (where fixed_points is a nrow(fixed_points) x 2 matrix with lat/lon coordinates
library(shiny); library(rCharts); library(leaflet)
output$baseMap  <- renderMap({
  baseMap <- Leaflet$new()
  baseMap$setView(c(lng = 2.812500, lat = 46.732331), zoom = 6)
  baseMap$tileLayer(provider = "Stamen.TonerLite")
  for (i in 1:nrow(fixed_points)) {baseMap$marker(c(fixed_points[i, "lat"], fixed_points[i, "lon"]))}
  baseMap$fullScreen(TRUE)
  baseMap
})

and the ui.R
showOutput("baseMap", "leaflet") // or chartOuput(...), it works the same

Thanks in advance!


text:
Q: Cannot setState after receiving user from service provider I am receiving the user properly from my provider but for some reason the state does not change with the user object.
This returns the user object properly:
console.log(receivedUser);

However, after I try to do this, there's no object:
setUser(receivedUser);
  console.log(user);

What seems to be the issue here guys? Why doesn't the state change at all?
Full code:
const [user, setUser] = useState({})

// this prevents this providerValue changing unless value or setValue changes
const providerValue = useMemo(() => ({user, setUser}), [user, setUser])

  useEffect(() => {
    async function fetchUser(){
    const receivedUser = await AuthService.getCurrentUser();
    if (receivedUser) {
      // console.log(receivedUser);
      setUser(receivedUser);
      console.log(user);
    } else {
      console.log("user not logged in");
    }
    }
    fetchUser();
  }, []);

A: updation of state is asynchronous. you need to use useEffect to console out the value of state. A seperate useEffect can be created which would be triggered every time the user in the state changes
const [user, setUser] = useState({})

// this prevents this providerValue changing unless value or setValue changes
const providerValue = useMemo(() => ({user, setUser}), [user, setUser])

  useEffect(() => {
    async function fetchUser(){
    const receivedUser = await AuthService.getCurrentUser();
    if (receivedUser) {
      // console.log(receivedUser);
      setUser(receivedUser);
      console.log(user);
    } else {
      console.log("user not logged in");
    }
    }
    fetchUser();
  }, []);

    useEffect(()=> {
        console.log('user',user)
    }, [user])

A: You can do it like that, first setUser is an async.
You have to understand the life circle of useState
Will give you an example how to handle this right and wrong..
see below to example..

const [text, setText] = useState("default");

useEffect(() => {
  setText("test");

  console.log(text) // this will print defult
}, [])

useEffect(() => {
  console.log(text) // this will print test
}, [text])

A: setUser it's kind of asynchronous function. State of user doesn't change immediately after you call this function. If you want to handle when user state change add another on useEffect which checking if user state change:
useEffect( () => {
   /* this will be call any time user state change */
   if ( user ) {
       /* do something if user was fetched */
   }
}, [user])


text:
Q: WCF: Programmatic Setting Endpoint I am trying to programmatic set the end point for a WCF connection.
I have not been able to, below is the code I am using code someone help identify what is wrong?
        Uri wsBaseAddress = new Uri("http://localhost:27198/");

        ServiceHost host = new ServiceHost(typeof(ServiceClient), wsBaseAddress);

        WSHttpBinding wshttpbinding = new WSHttpBinding();

        host.AddServiceEndpoint(typeof(IService), wshttpbinding, "ServiceClient");
        host.AddServiceEndpoint(typeof(IService), wshttpbinding,
           "http://localhost:27198/Service.svc");

        host.Open();

EDIT:

Error: HTTP could not register URL "http://+:27198/" because TCP port
  27198 is being used by another application."

Thank you

A:
HTTP could not register URL "http://+:27198/" because TCP port 27198 is being used by another application."

This pretty much says it all. There is another application that is currently listening on that port, and since only one application can bind to a given port and IP at a given moment, your program can't.
Execute netstat -abn in cmd to see which program that is, most probable the ASP.NET Development Server.
If no other program is bound to that port, you can try running Visual Studio as administrator.

A: The statement below you are not providing the service name though it is not used in last statement with adding endpoint
 Uri wsBaseAddress = new Uri("http://localhost:27198/");

it should be
 Uri wsBaseAddress = new Uri("http://localhost:27198/Service");

You have to provide the service name instead of service file name with extension
Change
host.AddServiceEndpoint(typeof(IService), wshttpbinding,
           "http://localhost:27198/Service.svc");

to
 host.AddServiceEndpoint(typeof(IService), wshttpbinding,
           "http://localhost:27198/Service");


text:
Q: How to use c# inside mvc razor pages I'm new to asp.net core.
I want to display max 4 items per row, and using c# in razor views to manipulate dom.
however at some points the c# code seems faded and the code does not work.
below is an image to show you what I mean.
if I put a @ sign in front of the ifs it works however this time at the last If statement it gives an error to the div statement, It requires me to have an opening div tag however that tag is in the first if. any help is much appreciated

A: Generally you should not put closing tags in conditional statements.
In this case you should move both opening and closing tags of container out of conditional statements.

A: If you want to do something like this you need to use @helper.
https://learn.microsoft.com/en-us/aspnet/web-pages/overview/ui-layouts-and-themes/creating-and-using-a-helper-in-an-aspnet-web-pages-site
Razor needs to know that the div will get closed, if you're adding conditions then there's no guarantee that it will.


text:
Q: How to add #region when Implementation Interface? In Visual Studio 2017. How can I achieve it?
   public class Test : IFace
{
    #region IFace implementation

How can I add this #region when Auto-Generate?
    public void DoSomething()
    {
        //TODO...
    }
    #endregion
}


text:
Q: Initializing a member class of an object using a non-default constructor in C++ I have a specific situation where I've got an object that I want to use the boost random number generators on, and it has lead to a greater question which I cannot seem to answer.  Here is the example code of what I'm trying to produce.
First, my header:
Class MyObject {

 protected:
    double some variable;
    boost::random::mt19937 rgenerator;
    boost::uniform_real<double> dist_0_1;
    boost::variate_generator< boost::mt19937&, boost::uniform_real<double> > rand01
}

Now what I want to do is:
Class MyObject {

 protected:
    double some variable;

    boost::random::mt19937 rgenerator(std::time(0)); //initialize to a "random" seed
    boost::uniform_real<double> dist_0_1(0,1); //set the distribution to 0-1
    boost::variate_generator< boost::mt19937&, boost::uniform_real<double> > rand01(rgenerator, dist_0_1);//tell it to use the above two objects
}

But this doesn't work because it is in a header.  I thought I could use the constructor of MyObject to somehow call the constructors on the various sub-objects (distribution, generator, but I can't figure out how.  By the time the constructor of MyObject is called, the sub-objects' default constructors have already been called, and I haven't found that they have member methods to reset these properties... besides which, that isn't the point where I am confused.  Now maybe there are too many things going on and I'm confusing issues, but as far as I can tell, my problem reduces to this following, childish example:
Class Tree {

    Tree();
    Tree(int);

    protected:

        fruit apples(int);
}

Tree::Tree() {
    apples(0); //won't work because we can't call the constructor again?
}

Tree::Tree(int fruit_num) {
    apples(fruit_num); //won't work because we can't call the constructor again?
}

Class Fruit {

    public:
        Fruit();
        Fruit(int);

    protected:
        int number_of_fruit;

}

Fruit::Fruit() {

    number_of_fruit = 0;
}

Fruit::Fruit(int number) {

    number_of_fruit = number;

}

I'm sure this is second nature to everyone else out there, but I can't find an article that talks about the best practice for initializing member objects of an object to a non-default constructor value.

A: What you want is an initializer list. For example:
Tree::Tree(int fruit_num)
    : apples(fruit_num) // Initializes "apple" with "fruit_num"
{
}

You simply add a colon (:) after the constructor parameters and before the opening brace {. You can separate different member constructors with commas (,). Example:
Tree::Tree(int fruit1, int fruit2) : apples(fruit1), bananas(fruit2) {
}

A: The answer to this question is relatively straightforwards. You use initializer lists.
Here's an example:
class MyClass {
private:
     SomeOtherType sot;
public:
    MyClass() : sot(parametersForConstructorOfSOT) {}
};

You can extend this to multiple member objects, of course; it can also be used to call the constructor of a parent class to initialize private entries in a parent class if you need to do something like that.

A: You're so close! Just use the initialiser list syntax:
Tree::Tree() : apples(0) {
    // ...
}

Tree::Tree(int fruit_num) : apples(fruit_num) {
    // ...
}


text:
Q: Symfony2, Forms - unset post values after form is valid I'm trying to unset in Symfony2 values in form fields after validation is correct. I have something found on the net, like $form->setName(null); but I'm not sure, if this is the most effective way, also unset($_POST);.
Is there any way, how to unset posted values via form after $form->isValid() at once?
PS: I don't think that source codes are needed in this question.
EDIT:
If I try use $form->setData(null) in isValid() i'll get message of You cannot change the data of a submitted form.

A: try this :
unset($_POST[$form->getName()]);


text:
Q: Nanpy Servo Control *Nanpy allows for a Raspi to have an Arduino slave through python
Right now I'm having extreme difficulty in using the nanpy Servo package, and I cant get it to run correctly. I'm using it to make a robot that is wirelessly controlled from a computer, this is what I have for code:
from nanpy import (ArduinoApi, SerialManager)
import pygame
from nanpy import Servo
import time
pygame.init()

a=0
d=0

window = pygame.display.set_mode((800,600))

pygame.display.set_caption("Console")

try :
    connection = SerialManager()
    ard = ArduinoApi(connection = connection)
    run = True
except:
    print("Connection Failed!")

servoA = Servo(2)
servoD = Servo(4)
while run :
      for event in pygame.event.get():
                     keys = pygame.key.get_pressed()
           # if (event.type==pygame.KEYDOWN):

                     if keys[pygame.K_s] and keys[pygame.K_a]:
                            a=a-1
                            servoA.write(a)
                     elif keys[pygame.K_s] and keys[pygame.K_d]:
                            d=d-1
                            servoD.write(d)

                     elif keys[pygame.K_w]:
                            a=a+1
                            d=d+1
                            servoD.write(d)
                            servoA.write(a)

                     elif keys[pygame.K_s]:
                            a=a-1
                            d=d-1
                            servoD.write(d)
                            servoA.write(a)

                     elif keys[pygame.K_d]:

                            d=d+1
                            servoD.write(d)

                     elif keys[pygame.K_a]:
                            a=a+1
                            servoA.write(a)

                     elif keys[pygame.K_t]:
                            run=False

pygame.quit()

This is the error the python shell throws:
Traceback (most recent call last):
  File "/home/pi/Desktop/nanpy/RobotCode.py", line 28, in <module>
    servoA = Servo(2)
  File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/servo.py", line 9, in __init__
    self.id = self.call('new', pin)
  File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 150, in call
    return _call(self.namespace, self.id, args, self.connection)
  File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 47, in _call
    ret = return_value(connection)
  File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 18, in return_value
    return serial_manager.readline().replace('\r\n', '')
  File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/serialmanager.py", line 101, in readline
    raise SerialManagerError('Serial timeout!')
nanpy.serialmanager.SerialManagerError: Serial timeout!

How can I fix this, and/or what am I doing wrong?

A: You need to specify the port of the Arduino. So could you try:
connection = SerialManager(device='/dev/ttyACM0')
or whatever port you are using.

A: update the configuration file to use the servo and upload it to arduino using the IDE then run this program.
you can find the cfg.h file in nanpy-firmware/nanpy folder.


text:
Q: Extracting Text Box data from multiple Microsoft Word files I have a folder with 40-50 Microsoft Word documents.
Each Word document is structured as follows:
- There are multiple tables with two columns
- The second column contains the question, and at the end of each question there is a unique identifier (such as "<#Q123#>")
- In the same cell that contains the question, there is a text box after the unique identifier which contains the answer to the question
I am trying to develop a macro in Microsoft Word that will open each Word document in the folder, search for the text box that is immediately after the specified unique identifier, and paste it into the new file that has the macro.
If it were possible to extract the data from within the text boxes into an Excel file rather then copying and pasting the text boxes into a Word document, that would be preferrable, but I wasn't sure if that were possible (since some of the text boxes might contain

A: The answers listed here and here can show you how to get all the files in your folder.
The following VBA code can be used to retrieve the text in the 2nd column of the table, as well as the text in the shape(textbox) that is in that same cell.  The On Error Resume Next statement is in place to keep the code running if no shape(textbox) is found in the table cell.
Dim cll As Cell
Dim question As String
Dim answer As String
Dim tbl As Table

'Gets the first table in the active document.
'In your code you would assign the Word document that you have
'just opened to a document variable.
Set tbl = ActiveDocument.Tables(1)

On Error Resume Next
For i = 1 To tbl.Rows.Count
    Set cll = tbl.Cell(i, 2)

    question = cll.Range.Text
    answer = cll.Range.ShapeRange.TextFrame.TextRange.Text

    'Once you have these two strings, you can do whatever you want with them.
Next


text:
Q: Role Limit (Internal + External) in a single Org How many Roles (Internal and External) can a single org have? I can't find this documented clearly without references to Territory count.
We know that Internal Roles and Account Roles are all stored in the UserRole table. Easy enough to query:
SELECT Id, Name, PortalType From UserRole

Internal Roles have a PortalType of 'None', Partner or Customer have their own respective PortalTypes. Simple.
What is the max we can store in this table?
Documentation for Account Role limits...
- Default for new orgs: up to 5k
- Open a Case w/ SFDC: up to 100k
- SFDC Approval Required: up to 500k
Documentation for Internal Roles...
- Default for new orgs: up to 500
Additional Documentation for Internal Roles... while this article is muddled up with legacy Territory Management, this is the only place I could find clear upper limits defined for Internal Roles:
- By default, a Salesforce org can have up to 500 Roles or Territories.
- The current Maximum is 10000.
- A documented business case, including the specific amount of roles or territories needed, is required when requesting a higher limit.
At this point I infer - based on the above - that AT MOST a single org could have at most 510k roles... 500k (external) + 10k (internal). But this is a theoretical upper limit, as Salesforce Approval would be required.
Am I thinking about this right? Is this better documented anywhere?

A: Internal and external Roles will affect the org in the same way. Roles are Roles whether they're internal or external. Regardless of where they're used, the more you use, the slower things will get. I would not make the assumption that 510k is the max, but instead would conclude the max is 500k.
Remember you need to provide a Business Use case justification for the total roles in your org to be extended to 500K. Why would Salesforce give you an extra 10k Roles without asking you justify that as well? Instead, if you needed that many roles, I'd expect you to running multiple instances of Salesforce.


text:
Q: Python - Why does using map cost more time than iterating through the list? from timeit import Timer
def m1():
    l = range(100000)
    for i in l:
        l[i] *= 2

def m2():
    l = range(100000)
    l = map(lambda i:i*2,l)

if __name__ == '__main__':

    t1 = Timer('m1()','from __main__ import m1')
    print t1.timeit(100)

    t2 = Timer('m2()','from __main__ import m2')
    print t2.timeit(100)

the time m2 cost is more than m1 cost, could you explain why?
and what the implementation of map function, does it use iterator?
Thanks

A: In m2 the computation is performed via a function call to the lambda function. Even though it is a single line, it still qualifies as a function and thus has the cost of the function call.

Additionally the m2 creates a new list and assigns it to the variable l, the cost of the creation of that new list also needs to be taken into account.

In m1 there is simply the cost of the computation, hence m1 ends up faster.

m1 steps :

*

*Create list in variable l

*Multiple each item in list l with 2

m2 steps :

*

*Create list in variable l

*Create new list via lambda function calls iterating through list l

*Assign the new list to variable l


text:
Q: Is $q\to (p \vee \neg r)$ equivalent to $q \to p$? I am hesitating if the following is correct:

*

*$q\to (p \vee \neg r)$ Assume this is a premise

*Therefore $q \to (\neg r \vee p)$

*Therefore $q \to (r \to p)$

*Therefore $q \to p$ - if this is correct, by which axiom/rule?

A: It is not correct, because the inference from step 3 to step 4 does not follow.
If $q\to r$ and $r\to p$, then we have $q\to p$. But this is not the same as $q\to(r\to p)$.
As a concrete example, let $q$ be "It is raining", $r$ be "I do not bring my umbrella", and $p$ be "I get wet". If $q$ is true, then indeed $r\to p$ (if I leave my umbrella behind I will get wet), but it is not true that $q\to p$: it could rain without me getting wet (namely, if I remember my umbrella!).
This example suggests where the equivalence fails: if $q$ is true, $r$ is false, and $p$ is false. Indeed, you can check that the two expressions have different values in this case.