text:
Q: Proving $z^{-1}\int_{0}^{\infty}\cos(k x)e^{-z x}dx = \int_{0}^{\infty}\frac{\sin(k x)}{k}e^{-z x}dx$ I'm looking for a real analytic proof for the below identity
$$z^{-1}\int_{0}^{\infty}\cos(k x)e^{-z x}dx = \dfrac{1}{z^2 + k^2} =\int_{0}^{\infty}\frac{\sin(k x)}{k}e^{-z x}dx$$
I am working on this problem for a long time and found a very naive approach. I was wondering if there's a nice way to prove the required without using complex analysis and residue theorem. I highly appreciate your time and efforts. Thanks!

A: $$\int e^{ax}\sin(bx)dx = \frac{e^{ax}}{a^2+b^2}[a\sin(bx)-b\cos(bx)]$$
$$\int e^{ax}\cos(bx)dx = \frac{e^{ax}}{a^2+b^2}[a\cos(bx)+b\sin(bx)]$$
Using these,
$$\begin{align}z^{-1}\int_0^\infty e^{-zx}\cos(kx)dx &= \frac{z^{-1}}{z^2+k^2}\bigg[e^{-zx}(-z\cos(kx)+k\sin(kx))\bigg]_{x=0}^{\infty} \\&=\frac{z^{-1}}{z^2+k^2}(0-1(-z)) =\frac{1}{z^2+k^2}\end{align}$$
and
$$\begin{align}\frac1k\int_0^\infty e^{-zx}\sin(kx)dx &= \frac{1/k}{z^2+k^2}\bigg[e^{-zx}(-z\sin(kx)-k\cos(kx))\bigg]_{x=0}^{\infty} \\&=\frac{1/k}{z^2+k^2}(0-1(-k)) =\frac{1}{z^2+k^2}\end{align}$$

A: Let
$$C =\frac1z \int_{0}^{\infty}\cos(k x)e^{-z x}dx, \>\>\>\>\>
S = \frac1k\int_{0}^{\infty}{\sin(k x)}e^{-z x}dx
$$
Then
$$ kz C-kz S  = \int_{0}^{\infty}[{k \cos(k x)}- z \sin (kx)]e^{-z x}dx
={\sin(k x)}e^{-z x}\bigg|_{0}^{\infty}=0
$$
$$ z^2 C+k^2 S  = \int_{0}^{\infty}[z\cos (kx) +{k \sin(k x)}]e^{-z x}dx
=-{\cos(k x)}e^{-z x}\bigg|_{0}^{\infty}=1
$$
which yield
$$C=S = \dfrac{1}{z^2 + k^2}$$


text:
Q: How to add a good email in sendgrid api in nodejs I'm sending some emails via sendgrid and nodejs. I have a content to sent, but i'm unable to add a good body like below
Body:

Hi
You are receiving this email as a reminder to enter time for the day.
Best Regards, Operations Team

I'm able to send mail with the message only and couldn't find a way to add the "Best Regards,
Operations Team" lines. Please give an insight.
my code,
  sgmail.setApiKey(process.env.API_KEY);
      const msg = {
        to: '########', // Change to your recipient
        from: "######", // Change to your verified sender
        subject: `Reminder for Time Entry`,
        text: "Hi You are recieving this email as a reminder to enter time for the day.",
        html: "
 Hi You are recieving this email as a reminder to enter time for the day.
",
    }
    sgmail.send(msg);

A: In plain text you can add line breaks and they will display in the email. Note that you can use backticks (`) to write multiline strings in JavaScript. For HTML emails, you should wrap different lines in different paragraph (
) tags. Try the following:
sgmail.setApiKey(process.env.API_KEY);

const textMessage = `Hi

You are receiving this email as a reminder to enter time for the day.

Best Regards, Operations Team`;

const htmlMessages = `
Hi

You are receiving this email as a reminder to enter time for the day.

Best Regards, Operations Team
`;

const msg = {
    to: '########', // Change to your recipient
    from: "######", // Change to your verified sender
    subject: `Reminder for Time Entry`,
    text: textMessage,
    html: htmlMessage,
}
sgmail.send(msg);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Blank logs on error with Verbose 4 using PowerShell Invoke-Sqlcmd -InputFile Can someone please help me understand why the second Invoke-SqlCmd doesn't log anything even though it encounters an error?
I am using PowerShell.
What can be done to overcome this?
Log file:

*

*(Invoke-Sqlcmd -Query "PRINT 'Hello World!';" -ServerInstance $Server -verbose) 4>> 'C:\Users\Username\Execute Config\MyResultFile.txt'
No Errors

*(Invoke-Sqlcmd -InputFile 'C:\Users\Username\Execute Config\ABC.sql' -ServerInstance $Serve -verbose) 4>> 'C:\Users\Username\MyResultFile.txt'
Error:


text:
Q: How to replace a space exactly by "\_" in java String? I have a string with space and I want that space replace by "\_"
. For example here is my code
String example = "Bill Gates";
example = example.replaceAll(" ","\\_");

And the result of example is: "Bill_Gates" not "Bill\_Gates". When I try to do like this
String example = "Bill Gates";
example = example.replaceAll(" ","\\\\_");

The result of example is: "Bill\\_Gates" not "Bill\_Gates"

A: You need to use replaceAll(" ","\\\\_") instead of replaceAll(" ","\\_"). Because '\\' is a literal. It will be compiled as '\' single slash. When you pass this to replaceall method. It will take first slash as escaping character for "_". If you look inside replaceall method
    while (cursor < replacement.length()) {
        char nextChar = replacement.charAt(cursor);
        if (nextChar == '\\') {
            cursor++;
            if (cursor == replacement.length())
                throw new IllegalArgumentException(
                    "character to be escaped is missing");
            nextChar = replacement.charAt(cursor);
            result.append(nextChar);
            cursor++;

When it finds a single slash it will replace next character of that slash. So you have to input "\\\\_" to replace method. Then it will be processed as "\\_". Method will look first slash and replace second slash. Then it will replace underscore.

A: Try:
String example = "Bill Gates";
example = example.replaceAll(" ","\\\\_");
System.out.println(example);

A: public static void main(String[] args) {
        String example = "Bill Gates";
        example = example.replaceAll(" ", "\\\\_");
        System.out.println(example);
    }

output
Bill\_Gates


text:
Q: How to search in a huge unix mailbox archive on Windows I have a standard unix mailbox archive. It is a huge text file, containing tens of thousands of email messages including headers. I would like to search in this file for specific emails on particular topics.
So far I've found a tool named MailNavigator. It allows me to view the emails in the archive, but in the demo version, filtering and searching is only possible in very small archives.
Are there any open source / free alternatives?
The archive is not only of personal interest. Its content is from a specific XML-related Yahoo group. Searching the group pool currently returns nonsense results because, since a few weeks, all XML tags are stripped from the content. Therefore, finding a local solution to this problem is one thing. But a way to convert this content and make it available on a public server again would be even better.

A: Perhaps you could use NoPriv.py to create an HTML archive of your inbox for viewing on Windows using a standard web browser.
Screenshot of main page

Screenshot of Inbox


text:
Q: Authentication with using abstract classes asp.net mvc4 please any help or tutorial about developping an authentication with using many user , i have a class named USER and then i have 3 abstract classes Administrator,Secretary,Responsable , i want to develop an authentication method with using abstract classes , any help or tutorial pleaase .

A: I think this may help you.
http://pluralsight.com/training/Player?author=scott-allen&name=mvc4-building-m7-security&mode=live&clip=0&course=mvc4-building
And you can get more resources about asp.net mvc security here.
http://www.asp.net/mvc/overview/security


text:
Q: In what $precise$ sense is Minkowski space asymptotically flat? I've brought this question over from the physics stack exchange, where it didn't generate interest.

We say a manifold $(M,g)$ is conformally compact if it is the interior of some $(\overline M, \overline g)$, such that
$$g = r^{-2}\overline g|_M,\quad \mathcal Z(r) = \partial M,\quad \text{and}\quad \mathrm{d}r_p \neq 0\ \text{for any}\ p\in \partial M.$$
Moreover, we say a conformally compact manifold is asymptotically flat if $|\mathrm{d} r|^2_{\overline g}\equiv 0$ on the boundary. (i.e. the first derivative of the defining function is null on the boundary.)
It is "well known" that Minkowski space is an asymptotically flat manifold - Penrose's famous compactification supposedly shows this. However, in his compactification, there are two points on the boundary for which $\mathrm{d}r_p = 0$: namely spacelike and timelike infinity. I've made my own coordinate free compactifications of Minkowski space, but they also have some singularities at conformal infinity.
How is this formalised? When people say "conformally compact" in literature, do they just mean "there is a dense subset of the boundary satisfying the above conditions"?

A: The definition I would give of asymptotic flatness is the following:
A time-orientable spacetime $(M,g)$ is asymptotically flat at null infinity if there exists a spacetime $(\bar{M},\bar{g})$ such that,

*

*there exists a positive function $\Omega:M\rightarrow \mathbb{R}$ such that $(\bar{M},\bar{g})$ is an extension of the spacetime $(M,\Omega^2g)$. Hence if we regard $M\subset \bar{M}$ then $\bar{g}=\Omega^2g$ on $M$.

*within $\bar{M}$, M can be extended to a manifold with boundary $\partial M$.

*$\Omega$ can be extended to a function on $\bar{M}$ such that $\Omega|_{\partial M}=0$ and $d\Omega \neq 0$ on $\partial M$.

*$\partial M=\mathcal{I}^+\sqcup \mathcal{I}^-$ where $\mathcal{I}^{\pm}$ are diffeomorphic to $\mathbb{R}\times \mathbb{S}^2$.

*No past (future) directed causal curve starting in $M$ intersects $\mathcal{I}^+$ ($\mathcal{I}^-$) respectively.

*$\mathcal{I}^{\pm}$ are complete: under the gauge condition $(\nabla_a\nabla_b\Omega)=0$ on $\mathcal{I}^{\pm}$, the generators of $\mathcal{I}^{\pm}$ are complete. ($\nabla_{a}$ is the Levi-Civita associated to $\bar{g}$).
It should be relatively easy to show the conformal compactification of Minkowski spacetime satisfies the definition I gave here.
A point of interest, it can be shown that a spacetime which satisfies this definition 'looks like' Minkowski spacetime 'far away'. I.e. if you work out the metric in a neighborhood of null infinity then the leading order contribution looks like the Minkowski spacetime. This is the statement that this definition formalizes.
Please note that this definition is semi-lifted from Harvey Reall's Black Hole lecture notes which in turn are largely based on Wald and Hawking and Ellis. I believe this definition is in Wald.


text:
Q: Failed to set iTunes track properties using Powershell I used to use vbscripts to automate tasks such as adding mp3, changing genre, comments for tracks in iTunes.
I am now trying to create powershell scripts to do the same. I can added mp3 to iTunes, but I failed to change the properties of the track.... I don't know what I've missed.... The following is a sample of the powershell codes to change the Genre and the error said the property "genre" does not exist.
$iTunes = New-Object -com "iTunes.Application"
$library = $iTunes.LibraryPlaylist
$iTrack = $library.addfile("c:\temp\test.mp3")
$iTrack.tracks.Genre = "test"

However, I can see the property using $iTrack.tracks | get-member
Genre              Property   string Genre () {get} {set}

Thanks to anyone who could help..

A: I found two ways (there's more) to set properties.

*

*Force the track to an array and set the properties of the first item
@($iTrack.Tracks)[0].Genre = "test"

*Set properties by item name (which is kind of occurred when the object you have is already the one you want to set)
$iTrack.Tracks.ItemByName('song name').Genre = "test"


text:
Q: While loop runs when false I've tried everything to I can find to get this to work. I've researched this an extensive amount and have tried every possible solution that I can find. I'm using QtCreator and coding in c++.
int main() {
    int Die1, Die2;
    cout << "Die 1: ";
    cin >> Die1;
    cout << "Die 2: ";
    cin >> Die2;
    while ( (Die1+Die2 != '2')||(Die1+Die2 != '3')||(Die1+Die2 != '5')||(Die1+Die2 != '7')||(Die1+Die2 != '9')||(Die1+Die2 != '11')) {
        cout << "You Rolled a " <<Die1<< " and " <<Die2<< " for a Total of " <<Die1 + Die2<<". Please Roll Again\n";
        cout << "Die 1: ";
        cin >> Die1;
        cout << "Die 2: ";
        cin >> Die2;
    }

A: Your code:
(Die1+Die2 != '2') ||
(Die1+Die2 != '3') ||
(Die1+Die2 != '5') ||
(Die1+Die2 != '7') ||
(Die1+Die2 != '9') ||
(Die1+Die2 != '11')

Will evaluate to:
A.
( 1+1 != 2 ) = false
( 1+1 != 3 ) = true
break;

B.
( 1+2 != 2 ) = true
break;

C.
( 1+3 != 2 ) = true
break;

...
( 1 + ( x>2 ) != 2 ) = true

Your logic here is inherently flawed, in that it will always evaluate to true.
edit
As it has been pointed out by others, you are also trying to compare these integers to their char values, which will not align how you expect them to.
'0' = (hex)0x30 = (int)48
'1' = (hex)0x31 = (int)49
'2' = (hex)0x32 = (int)50
...

To fix this, you should be doing your comparisons to the actual number:
( Die1 + Die2 != 2 )

A: You might want to check your while condition!
Since the conditions are in the negation, you would use AND ( && ) instead of OR (||) to combine them.
EDIT:
And as pointed out, you ought to be comparing Die1 and Die2 to numbers. If you'd like to keep the characters as is, you could add character '0' to the sum of Die1 and Die2.
This seems to work fine:
#include <bits/stdc++.h>

using namespace std;

int main() {
    int Die1, Die2;
    cout << "Die 1: ";
    cin >> Die1;
    cout << "Die 2: ";
    cin >> Die2;
    while ( (Die1+Die2 != 2)&&(Die1+Die2 != 3)&&(Die1+Die2 != 5)&&(Die1+Die2 != 7)&&(Die1+Die2 != 9)&&(Die1+Die2 != 11)) {
        cout << "You Rolled a " <<Die1<< " and " <<Die2<< " for a Total of " <<Die1 + Die2<<". Please Roll Again\n";
        cout << "Die 1: ";
        cin >> Die1;
        cout << "Die 2: ";
        cin >> Die2;
    }

}


text:
Q: Check that item exists in a dictionary of OrderedDict I can't see to get this working, having key error so was wondering if anyone could let me know what I'm doing wrong.
Here is the code:
>>> from collections import OrderedDict
>>> people = OrderedDict()
>>> people['Depark'] = 'Jaipor'
>>> people['James'] = 'Walubi'
>>>
>>> work = OrderedDict()
>>> work['Train drive'] = 'Big_train'
>>> work['Teacher'] = 'Maths_teacher'
>>>
>>>
>>> def props():
...    d = dict()
...    d['people'] = people
...    d['work'] = work
...    return d

>>> test = props()
>>> if test['people']['Mandeep']:
...     print 'We have Mandeep'
... else:
...    print 'No one by that name'

This is the error message:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Mandeep'

I was expecting it to print 'No one by that name' as we don't have Mandeep as a key.
Any help would be appreciated.

A: test['people']['Mandeep'] is evaluated before the if condition is processed. Unsurprisingly, it raises KeyError. One Pythonic solution is to use a try / except construct:
try:
    test['people']['Mandeep']
    print('We have Mandeep')
except KeyError:
    print('No one by that name')

If you want to use an if / else clause, you can check if the key exists in your sub-dictionary:
if 'Mandeep' in test['people']:
    print('We have Mandeep')
else:
    print('No one by that name')

A: Alternatively, you can use .get(key, [default_value]) to check if the item exists in OrderedDict. Details can be found in Python documentation on get method.
from collections import OrderedDict

people = OrderedDict()
people['Depark'] = 'Jaipor'
people['James'] = 'Walubi'

work = OrderedDict()
work['Train drive'] = 'Big_train'
work['Teacher'] = 'Maths_teacher'

def props():
    d = dict()
    d['people'] = people
    d['work'] = work
    return d

test = props()

if test['people'].get('Mandeep'):
    print('We have Mandeep')
else:
    print('No one by that name')

Output:
No one by that name

Explanation:
Here, we are searching for the name Mandeep in our OrderedDict people and if it is not found, it is set to None. Thus if the key is not found the else block is executed.
References:

*

*Python documentation on get method


text:
Q: Embedding binary data into an executable using LLVM tools In the past I have embedded resource files (images) into programs by first converting them to .o files using the GNU linker. For example:
ld -r -b binary -o file.o file.svg

Starting with FreeBSD 12, the default linker has changed from GNU's to LLVM's. Although the linker appears to understand the command line options, it results in an error. For example:
ld -r -b binary -o file.o file.svg
ld: error: target emulation unknown: -m or at least one .o file required

Also tried using the command line options from the ld.lld(1) manual page:
ld --relocatable --format=binary -o file.o file.svg
ld: error: target emulation unknown: -m or at least one .o file required

Am I using the correct tool? Do I need to specify a value for the -m option?

A: It seems you need to add -z noexecstack (This was added for ELF binaries as well in LLD 7.0.0). The default is to have an executable stack region which is vulnerable to exploitation via stack memory. Your binary image does not have an executable stack and I believe that is why it fails. The error throws you off as it asks you to tell what target emulation to use for your stack (which you do not have).
David Herrmann did all the hard work and have found a cross platform solution which covers:

*

*GNU-ld

*GNU-gold

*GNU-libtool

*work with cross-compiling

*work with LLVM

*do not require any external non-standard tools

The magic invocation is then:
$(LD) -r -o "src/mydata.bin.o" -z noexecstack --format=binary "src/mydata.bin"

And most often you want that binary segment to be read-only:
$(OBJCOPY) --rename-section .data=.rodata,alloc,load,readonly,data,contents "src/mydata.bin.o"

UPDATE:
I could not test as my system was:
$ uname -r
11.2-STABLE
$ ld -V
GNU ld 2.17.50 [FreeBSD] 2007-07-03
  Supported emulations:
   elf_x86_64_fbsd
   elf_i386_fbsd

I spun up a VM with FreeBSD 12.0 to test this out and found this:
$ uname -r
12.0-RELEASE
$ ld -V
LLD 6.0.1 (FreeBSD 335540-1200005) (compatible with GNU linkers)

The -z noexecstack was only added in 7.0.0 and it is not listed in the man page for 6.0.1. More annoyingly specifying unsupported values for -z does not trigger an error!
I have not upgraded to LLVM 7 to test if that does the trick. @Richard Smith found a proper solution himself by specifying the emulation with -m in another answer. That route would be so much easier if LLD listed supported emulations with -V.
If you use the file command on file.o you will see it identifies as SYSV ELF. This might be good enough for you. But if you want the exact samme as the system then use elf_amd64_fbsd which is an alias for elf_x86_64_fbsd. Annoyingly ld -V does not output supported emulations with LLD as GNU ld does.
$ file /bin/cat
/bin/cat: ELF 64-bit LSB executable, x86-64, version 1 (FreeBSD), dynamically linked, interpreter /libexec/ld-elf.so.1, for FreeBSD 12.0 (1200086), FreeBSD-style, stripped
$ ld -r -b binary -m elf_amd64 -o data.o data.bin
$ file data.o
data.o: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped
$ ld -r -b binary -m elf_amd64_fbsd -o data.o data.bin
$ file data.o
data.o: ELF 64-bit LSB relocatable, x86-64, version 1 (FreeBSD), not stripped

elf_amd64_fbsd is an alias for elf_x86_64_fbsd (see D7837 and D24356). Hopefully LLD will add the emulations to the -V output.

A: After looking through the source, the correct target emulation for my platform is elf_amd64. So the conversion from binary to object file works using:
ld -r -b binary -m elf_amd64 -o file.o file.svg

A: Is it really worth the trouble? That wasn't portable in the first place.
You should better convert your .svg to a C char array; Example:
$ cat Makefile
.SUFFIXES: .svg
.svg.c:
        od -tx1 $< | sed 's/ /,0x/g;s/[^,]*//;1s/,/char $*[]={/;$$s/$$/};/' > $@

$ make file.o
od -tx1 file.svg | sed 's/ /,0x/g;s/[^,]*//;1s/,/char file[]={/;$s/$/};/' > file.c
cc    -c -o file.o file.c
rm file.c

Of course, you can set the name of the array to something different / more robust (eg. char $(subst /,_,$*)[] = ... instead of char $*[] = ... with GNU make). Also, you could build an ad-hoc bin2c converter written in C instead of that horrible od+sed combo.


text:
Q: Error in displaying values from database on table I am doing a Birthday remainder Application by using SQLITE database.I am saving values in database . I displayed first name On the table view so that if i click that i can see that person entire details. For example i saved some 5 person details in database.
When i close that application and run again i am not able to display that saved values in the table view.But i am getting that saved values only i am not able to display that first name which i saw previously when i am closing that application.
When i run the application for the first time i am not able to go to this method (cellForRowAtIndexPath:) in tale view. When i add details then its going to this (cellForRowAtIndexPath:) method.
Can any one help me in this. Thanks!

A: You need to connect to your data source (database) and return the proper values for
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

and
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

once you return these values properly based on your datasource then cellForRowAtIndexpath will get called.
Of course you should ensure that your viewcontroller is properly designated as the tableview's delegate and datasource.


text:
Q: properties cannot be applied to '(groovy.lang.Closure)' I am unable to fix these warning for the following code:
properties cannot be applied to '(groovy.lang.Closure)
property in 'org.gradle.api.Task' cannot be applied to '(java.lang.String, java.lang.String)
  sonarqube {
        properties {
            property "sonar.host.url", "http://localhost:9000"
            property "sonar.jdbc.driverClassName", "com.mysql.jdbc.Driver"
            property "sonar.jdbc.driverClassName", "com.mysql.jdbc.Driver"
        }
    }

tried all the solution mentioned below but non is working.
'dependencies' cannot be applied to '(groovy.lang.Closure)'
anyone know the cause.
Thanks in advance.
edit
import org.gradle.internal.os.OperatingSystem

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'findbugs'
apply from: '../jacoco.gradle'
apply plugin: 'spoon'
apply plugin: 'org.sonarqube'
apply plugin: 'net.researchgate.release'
apply plugin: 'io.fabric'
apply from: 'versioning.gradle'
apply plugin: 'maven-publish'

ext {
    appName = "xxxx"
    appDesc = "xxxx"
}

android {
    compileSdkVersion 24
    buildToolsVersion '24.0.1'
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.eurocarparks.exemption"
        minSdkVersion 19
        targetSdkVersion 24
        versionCode buildVersionCode()
        versionName version
    }

    signingConfigs {
        release {

        }
    }

    productFlavors {
        demo {

        }
        tst {

        }
        uat {

        }
        production {

        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
        debug {
            debuggable = true
            testCoverageEnabled = true
        }
    }

    lintOptions {
        abortOnError false
    }

    packagingOptions {
        exclude 'NOTICE'
        exclude 'LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
    }

    dexOptions {
        incremental true
        javaMaxHeapSize "5g"
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:support-v4:24.1.1'
    compile 'com.android.support:appcompat-v7:24.1.1'

    // JSON
    compile 'com.fasterxml.jackson.core:jackson-core:2.6.3'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.6.3'
    compile 'com.fasterxml.jackson.core:jackson-annotations:2.6.3'
    // RESTful
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.4.0'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.4.0'
    compile 'com.squareup.retrofit:converter-jackson:1.9.0'
    compile('com.squareup.retrofit:converter-simplexml:1.6.1') {
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax'
        exclude group: 'xpp3', module: 'xpp3'
    }
    // Utilities
    compile 'com.google.guava:guava:19.0'
    // Event bus
    compile 'de.greenrobot:eventbus:2.4.0'
    // Database
    compile 'com.couchbase.lite:couchbase-lite-android:1.1.0'
    // Dependency injection
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.google.dagger:dagger:2.0.1'
    apt 'com.google.dagger:dagger-compiler:2.0.1'
    provided 'org.glassfish:javax.annotation:10.0-b28'
    // Commons IO
    compile 'commons-io:commons-io:2.4'
    // Unit test
    testCompile 'org.robolectric:robolectric:3.0'

    testCompile 'org.robolectric:shadows-support-v4:3.0'

    testCompile 'junit:junit:4.12'

    testCompile 'org.mockito:mockito-core:2.0.89-beta'
    testCompile 'org.assertj:assertj-core:1.7.1'
    testCompile 'com.google.dagger:dagger:2.0.1'
    testCompile 'org.skyscreamer:jsonassert:1.2.3'
    if (OperatingSystem.current().isMacOsX()) {
        println "OS: MacOsX"
        testCompile 'com.couchbase.lite:couchbase-lite-java-native-macosx:1.1.0'
    } else if (OperatingSystem.current().isLinux()) {
        println "OS: Jenkins"
        testCompile 'com.couchbase.lite:couchbase-lite-java-native-jenkins:1.1.0'
    } else if (OperatingSystem.current().isWindows()) {
        println "OS: Windows"
        testCompile 'com.couchbase.lite:couchbase-lite-java-native-windows:1.1.0'
    }
    testCompile('com.couchbase.lite:couchbase-lite-java:1.1.0') {
        exclude module: "couchbase-lite-java-native"
        exclude group: "com.fasterxml.jackson.core"
        exclude group: "commons-logging"
    }
    // Instrumentation test
    androidTestCompile 'junit:junit:4.12'
    androidTestCompile 'org.assertj:assertj-core:1.7.1'
    androidTestCompile 'com.jayway.android.robotium:robotium-solo:5.6.0'
    androidTestCompile('com.squareup.spoon:spoon-runner:1.6.1') {
        exclude group: "commons-logging"
        exclude group: 'com.google.code.gson'
        exclude module: 'guava'
    }
    androidTestCompile('com.squareup.spoon:spoon-client:1.1.10') {
        exclude group: 'com.google.code.gson'
    }

    // Monitoring
    compile('com.crashlytics.sdk.android:crashlytics:2.5.2@aar') {
        transitive = true;
    }

}

spoon {
    debug = true
    if (project.hasProperty("spoonDeviceSerials")) devices = [spoonDeviceSerials]
}

sonarqube {
    properties {
        property "sonar.host.url", "http://localhost:9000"
        property "sonar.jdbc.driverClassName", "com.mysql.jdbc.Driver"
        property "sonar.jdbc.driverClassName", "com.mysql.jdbc.Driver"

    }
}

release {
    preTagCommitMessage = '[Release] - pre tag commit: '
    tagCommitMessage = '[Release] - creating tag: '
    newVersionCommitMessage = '[Release] - new version commit: '
    buildTasks = ['assembleTst', 'assembleUat', 'assembleProduction']
    git {
        requireBranch = ''
        pushToCurrentBranch = true
    }
}

afterReleaseBuild.dependsOn publish

publishing {
    repositories {    }
}


text:
Q: UISplitViewController display wrong ViewController on launch I have a fully functional Address book app (from Lynda.com called iOS Address Book App: Hands On) that utilizes a UISplitViewController.
I want to implement this Address Book app into my existing Tab bar app.
I have moved all over and the most all runs well. (Storyboard items and all ViewControllers, except the AppDelegate).
The only issue I have is when I select the Address Book Tab (on home screen), it displays the detailsViewController as the default view.  I can hit the back button that takes me to the Master screen and all works fine.  I just need it to display the Master View as the initial screen.
Clearly, it is a setting issue as it works fine as a stand alone.
Willing to post any code necessary to help, but not sure which VC to post.
Here are some images to show what I am referring to:
Tab bar

Selecting "Buddies" takes me here, to the DetailViewConroller

Instead of here, the MasterViewController

Hopefully, someone has seen this before.
MasterViewController

A: Found it.  Posting in case someone stumbles across this same issue.  Apparently, the DetailViewController is the default view while in portrait (I assume non iPad portrait).  To change the initial screen do the following to the MasterViewController.swift (or the view controller you use to control the UITableView)
class MasterViewController: UITableViewController, UISearchResultsUpdating, UISplitViewControllerDelegate {

    private var collapseDetailViewController = true

override func viewDidLoad() {
    super.viewDidLoad()

    splitViewController?.delegate = self

}

func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
    return collapseDetailViewController
}


text:
Q: Pandas not dropping rows and columns that meet criteria I am trying to make a regression model in order to predict ratings (1-5) based on words that appear (the regression doesn't have to perform well per se, it's more about the methodology applied).
I created a term frequency matrix with this code:
bow = df.Review2.str.split().apply(pd.Series.value_counts)

which look like this:

I am now interested in deleting columns (words) that rarely appear throughout the reviews. Moreover, I want to iterate through only the reviews (rows) that have a Rating value which is not NaN.
here is my attempt:
# Delete row if Rating less than 1
for index, row in df.iterrows():
    if (df.Rating[index] < 1):
        bow.drop(bow.index[index], axis=0, inplace = True)

# Delete column if word occurs less than 50 times
sum1 = bow.sum(axis=0)
cntr = 0
for i in sum1:
    if (i < 50):
        bow.drop(bow.index[cntr], axis=1, inplace = True)
    cntr += 1

This doesn't seem to do the work as it leaves words that occur only once.

EDIT:
This is my sparse dataframe containing occurrences of words.
Col -> words;
Rows -> sentences (item's reviews) (I have 1.5k items, thus 1.5k rows)
     hi this are just some random words  I  don t      ...  zing  zingy zingzang
0   1.0 NaN  1.0 1.0  1.0   NaN   NaN   NaN NaN NaN    ...  NaN    NaN    NaN
1   NaN NaN  NaN NaN  NaN   NaN   NaN   NaN NaN NaN    ...  NaN    NaN    NaN
2   NaN NaN  NaN NaN  NaN   NaN   NaN   NaN NaN NaN    ...  NaN    NaN    NaN
3   NaN NaN  NaN NaN  NaN   NaN   NaN   NaN NaN NaN    ...  NaN    NaN    NaN
4   NaN NaN  NaN NaN  NaN   NaN   NaN   NaN NaN 1.0    ...  NaN    NaN    NaN

Rating is a single column of my original dataframe containing integers in the [1,5] range or NaN

A: You can use vectorised operations instead of manual iteration:
# filter out rows where Rating < 1
bow = bow[~(bow['Rating'] < 1)]

# filter out columns where sum < 50
bow = bow.loc[:, ~(bow.sum(0) < 50)]

Or simultaneously:
# filter rows and columns with Boolean series
bow = bow.loc[~(bow['Rating'] < 1), ~(bow.sum(0) < 50)]

A: I made this working toy example:
import pandas as pd
import numpy  as np

# Create a toy daframe
df = pd.DataFrame(np.arange(12).reshape(3,4),columns=['A', 'B', 'C', 'D'])

print(df)
#   A   B  C  D
#-------------
# 0  0  1  2  3
# 1  4  5  6  7
# 2  8  9 10 11

# Sum all the values for each column
column_sum = df.sum(axis=0)
print(column_sum)
# A    12
# B    15
# C    18
# D    21

# Iterate over Columns name and sum value
for key,value in zip(df.keys(),sum1):
    if(value < 16):
        df.drop(columns=key, axis=1, inplace = True)

print(df)

#    C  D
# 0  2  3
# 1  6  7
# 2 10 11

so I guess that if you change your code to:
for key,value in zip(df.keys(),sum1):
    if(value < 50):
        bow.drop(columns=key, axis=1, inplace = True)

it should get the job done.


text:
Q: Problema con Visual Studio Code Tengo problemas con Visual Studio Code, cuan termino de escribir la sintaxis, estoy trabajando con react, me corre toda la sintaxis haciendo ilegible el código. Por ejemplo " <
h2>{name} <
/h2>" Me lo va dejando así, cuando le pongo guardar

A: Revisa que extenciones tienes instaladas en VSCode, si no es nada de ello revisa las ultimas librerias adjuntas, sino reinicia tu VSCode y si el problema persiste reinstala la libreria de React...! Suerte en tu proyecto


text:
Q: Firefox Add-on SDK: how to make Panel transparent Developing a Firefox Add-on. Anyone can please help to figure out how to make a Panel transparent.
Here is the code to show a panel:
    var panel = require("sdk/panel").Panel({
    width: 570,
    height: 250,
    contentURL: require("sdk/self").data.url("test.html")
    });
    panel.show();

A: I found a solution, but it isn't pretty since sdk/panel.js doesn't seem to expose the raw Panel object in order to tweak/extend or compose a another Panel from the existing one.
Here goes:
(1) Get the source for sdk/panel.js here:  panel.js (raw) or from within sdk folder found in your addon xpi.
(2) Add it to your addon package as a new file.
(3) Change the requires parameters of this cloned file (lines 16-24) so that they point to the correct location from your addon.
example:
change
const { validateOptions: valid } = require('./deprecated/api-utils');
to
const { validateOptions: valid } = require('sdk/deprecated/api-utils');
(4) Find line 137, and modify the variable css to your liking.  Like so:
...
let css = [
  ".panel-inner-arrowcontent, .panel-arrowcontent {padding: 0;}",  //original css rule
  ".panel-inner-arrowcontent, .panel-arrowcontent  {opacity: 0.50; border-radius: 0.35in;}"  //additional css rules:  semi-transparent panel with rounded borders.
].join(" ");
...

(5) Use the modified version of panel.js instead of the one that came with the sdk.
That should be it.  Like I said, it isn't particularly elegant.


text:
Q: Restar horas al GETDATE() Necesito hacer una query que me muestre un conteo de todos los registros que existen en un rango de tiempo determinado.
Por ejemplo que me diga cuantos registros existen en la tabla tomando la fecha actual de hoy (GETDATE() fecha actual es 2019-08-07 09:03:00) restando le 3 horas (quedando 2019-08-07 06:03:00).
si ejecuto la consulta solo con la fecha actual me trae 200 registros que contienen fecha desde el 2019-08-07 00:00:00 hacia adelante. (no es como debería ser)
Si ejecuto la consulta con la misma fecha anterior pero restando le 3 horas (fecha actual 2019-08-07 09:03:00) quedaría 2019-08-07 06:03:00 me trae 100 registros que comienzan desde 2019-08-07 06:03:00 hacia adelante.
¿Como lo hago en una query?

A: En primera instancia probé con la siguiente query
SELECT COUNT(*) AS [TotalRows]
FROM [mi_db].[dbo].[mi_tabla] WHERE EventDate > CONVERT (DATE, GETDATE())

Me traía los 200 registros contando desde la fecha actual (2019-08-07 00:00:00)
Finalmente lo solucione de la siguiente forma:
SELECT COUNT(*) AS [TotalRows]
FROM [mi_db].[dbo].[mi_tabla] WHERE EventDate > DATEADD(HH, -3, GETDATE())

Esto hace que a la fecha actual que recupera desde el GETDATE() le evaluamos las HH para finalmente restarle 3 horas

A: habrá algo así para mongodb? resulta que al momento de guardar un registro eran las 19:30 y se guardó con 5 horas mas y cambió la fecha al día siguiente. A mi nueva consulta quiero agregarle 5 horas mas para que me devuelva ese dato,quiero poner la fecha real que guardé el registro y no poner la fecha del día siguiente. ayudaaaa please!!


text:
Q: Way of saying 'washes hands of it' but implies physical Looking for a non-crappy way of describing someone doing that washing hand motion you do to clear your hands of dust or dirt, but without saying 'washing hand motion'.  I feel like there's a good way of describing it, a stock phrase of some kind, but I can't remember it.  Tip of the tongue, and it's driving me mad.

A: If you mean running one's hands over each other, not when you're washing but when you are distressed or worried that's wringing one's hands
http://www.oxforddictionaries.com/definition/english/wring-one%27s-hands

A: It's a bit archaic but how about Lave?
e.g. She laved her hands.

Lave [leyv]
verb (used with object), laved, lav·ing.
1.to wash; bathe.
2.(of a river, sea, etc.) to flow along, against, or past; wash.
3.Obsolete . to ladle; pour or dip with a ladle.
verb (used without object), laved, lav·ing.
4.Archaic. to bathe.

A: How about rub/scrub/brush one's hands clean?

He vigorously rubbed his hands clean under the sink water.

Alternately, consider scrub up.

scrub up: (of a surgeon) to wash the hands and arms thoroughly before operating.


text:
Q: Error from Gracenote EyeQ Web API I'm trying to figure out how to use the Gracenote web API for EyeQ. What I want is to get TV listings for a danish provider, but for now I'm just trying to make anything work. As far as I can understand I have to use the "TVCHANNEL_LOOKUP" and for that I need the correct DVB Triplet. For now I've found a triplet for a dutch provider, I think and I'm just using that for test purposes. But when ever I make the following call:
<QUERIES>
  <AUTH>
    <CLIENT>xxxxx</CLIENT>
    <USER>xxxxxx</USER>
  </AUTH>
  <LANG>ger</LANG>
  <QUERY CMD="TVCHANNEL_LOOKUP">
    <MODE>DVBIDS</MODE>
    <DVBIDS>
      <ONID>500</ONID>
      <TSID>16<TSID>
      <SID>16003</SID>
     </DVBIDS>
   </QUERY>
 </QUERIES>

I get the following response:
<RESPONSES>
  <MESSAGE>Could not parse query: String could not be parsed as XML</MESSAGE>
  <RESPONSE STATUS="ERROR" />
</RESPONSES>

I'm just using a rest plugin for chrome to test
Is there any way I can get the correct dvb triplet for the danish providers?
Kind regards
Thomas

A: You're missing a "/" in the ending TSID tag.
<TSID>16<TSID>

Should be
<TSID>16</TSID>

That should get you the right response from API.


text:
Q: What does "probe_score" means from ffprobe output? Given a media file, after running ffprobe -i input.mp4 -show_format -print_format json, I got something like this:
{
    "format": {
        "filename": "ooxx.mp4",
        "nb_streams": 2,
        "nb_programs": 0,
        "format_name": "mov,mp4,m4a,3gp,3g2,mj2",
        "format_long_name": "QuickTime / MOV",
        "start_time": "0.000000",
        "duration": "231.210000",
        "size": "65133325",
        "bit_rate": "2253650",
        "probe_score": 100,
        "tags": {
            "major_brand": "isom",
            "minor_version": "512",
            "compatible_brands": "isomiso2avc1mp41",
            "encoder": "Lavf55.33.100",
        }
    }
}

I'm wondering what does probe_score mean here? How does it get calculated?

A: An input (a file in this case) can have an extension (say ".avi") and be of a different format (a wav file for example). FFmpeg can detect the real format of an input (with ffprobe).
In order to do this, it opens the file and read it (the first 5 seconds, set by option analyzeduration if I recall correctly). Then, it assign a score to each format: a low score if the data have nothing to do with the input, a high score if the format seems the right one.
The format returned is the one with the highest score. probe_score is this score.
100 is the maximum score, meaning that FFmpeg is sure that the format is the real one. With a score below 25, it is recommanded to increase probe duration.


text:
Q: weird gcc behavior with unsigned ints #include <iostream>

#include <cstdint>
#include <cstdio>

using namespace std;

int main()
{
    uint16_t ii;
    std::cin >> ii;
    printf("%d\n", ii);
}

When I give input 5 the output is also 5. But when I change the type of ii to uint8_t, I do not get 5 but 53 which seems to be the ASCII value of 5. Is this expected?

A: uint8_t is allowed (but not required) to be a typedef for char (if it happens to be unsigned) or unsigned char. And input of those is done as characters not numbers. So this is valid but not required behaviour.


text:
Q: Degrees of freedom of a line segment in 3D Suppose there is a line segment of fixed length $l$ in 3$D$. THen How many degrees of freedom does it have ?
To specify the line segment first we need to specify one endpoint which requires 3 parameters. Now the other endpoint lies in the circumference of the sphere of radius $l$ whose centre is the first end point. Now to choose the second endpoint we still need all 3 parameters ($r,\theta,\phi$) because for a specific $\theta,\phi$ there can be two solutions in which specifying $r$ makes it clear. Hence a line segment should have 6 degree of freedoms.
Am I right ?

A: Okay so think about it like this: You specify one point $p$ as the start for your line. As you noted you can define the other point as laying on the sphere or radius $l$ around $p$ - so naturally in this spherical coordinate system you'll only need two parameters to describe the other point and thus end up with $5$ degrees of freedom.
Another way (it's very similar though) to arrive at this answer is the following:
Lets first disregard that you want to fix the length. Note that the general parametrisation for a line is $\gamma : \Bbb R \to \Bbb R^3, t \mapsto t v + a$ for some $a, v \in \Bbb R^3$. You can easily pick out a (directed) segment by restricting the domain (requiring two parameters for a total of 6), or by fixing the length of $v$ to some value and fixing the domain of $\gamma$ to $[0,1]$. So a directed line segment is uniquely identified by the parametrisation
$$
\gamma : [0, 1] \to \Bbb R^3, t \mapsto t v + a, \quad \text{for }a,v\in \Bbb R^3.
$$
So we have three degrees of freedom for $a$ and three for $v$ for a total of $6$. By specifying the length we drop one degree of freedom and end up with $5$ - we can achieve the same by restricting $v$ to $lS^2 \subseteq \Bbb R^3$.
Note that for any such $\gamma$ the function $\widetilde{\gamma}(t) = t (-v) + \gamma(1)$ will be the same line segment, just traversed backwards. But this doesn't change the number of degrees of freedom (see linked post).


text:
Q: Set ACL while uploading a file to S3 using AWS short term credentials(AWS STS) I am using AWS STS Federation Token to get temporary credentials, with below statement.
Statement putStatement = new Statement(Statement.Effect.Allow)
        .withId("TempCreds")
        .withActions(S3Actions.PutObject)
        .withResources(new S3ObjectResource(bucketName, "*"));

Now I am able to get temp creds, but when I am uploading a file using PutObjectRequest:
s3Client.putObject(new PutObjectRequest(bucketName, keyName, file));

but this is default PRIVATE ACL.
Question is how to set PUBLIC ACL?
because when i use below code,
s3Client.putObject(new PutObjectRequest(bucketName, keyName, file)
                        .withCannedAcl(CannedAccessControlList.PublicRead));

the upload fails.
If in the above statement for Getting federation token, I add ACL like below
Statement putStatement = new Statement(Statement.Effect.Allow)
        .withId("TempCreds")
        .withActions(S3Actions.PutObject)
        .withResources(new S3ObjectResource(bucketName, "*"))
        .withConditions(S3ConditionFactory.newCannedACLCondition(CannedAccessControlList.PublicRead));

the upload still fails.
So how to set Public ACL when using Short term credentials?
I have given below policy to the IAM User, which is going to generate STS.
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1507714071000",
            "Effect": "Allow",
            "Action": [
                "sts:GetFederationToken"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}


text:
Q: Unbounded hierarchical routes I'd like to use webapi to expose a hierarchical key-value data structure like this:
http://www.whatever.com/api/root/level1/level2/leveln

Is this possible with webapi? And if so, how?

A: WebApi can expose almost any URI you like - it comes down to how you configure the routes, and how you interpret the method arguments once they've been extracted from the URL.
To map an unbounded hierarchical route, I'd map everything after the /api/root/ to a single variable, and then explicitly parse and interpret that method in custom logic in your controller, or a dedicated service.
The trick to having the match include forward slashes is to add a * at the start:
config.Routes.MapHttpRoute(
    name: "KeyValueHierarchy",
    routeTemplate: "api/test/root/{*keyLevels}",
    defaults: new { controller = "Hierarchy" }
);

Then in the controller
public class HierarchyController : ApiController
{

    public IHttpActionResult Get(string keyLevels)
    {
        var keys = keyLevels.Split('/');

        // ... do stuff with your keys

        return Ok(keys);
    }

}

A quick test:
GET /api/test/root/foo/5/bar/10/foobar
returned:
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <string>foo</string>
  <string>5</string>
  <string>bar</string>
  <string>10</string>
  <string>foobar</string>
</ArrayOfstring>


text:
Q: CakePHP: Transport config "gmail" is missing I'm using CakePHP 3.0.15 so I had to use Cake\Network\Email\Email; instead of use Cake\Mailer\Email;. Anyways, I have my EmailTransport in app.php configured like this:
'EmailTransport' => [
    'gmail' => [
        'className' => 'Smtp',
        'host' => 'ssl://smtp.gmail.com',
        'port' => 465,
        'timeout' => 30,
        'username' => 'examplesender@gmail.com',
        'password' => 's2d5f8t9',
        'client' => null,
        'tls' => null,
    ]
],

And have this in my controller:
    $email = new Email();
    $email->transport('gmail')
        ->to('examplereveiver@gmail.com', 'Example Receiver')
        ->from('examplesender@gmail.com', 'Example Sender')
        ->subject('Test Subject')
        ->send('Message!!!!!');

Then it gives me the error:
Transport config "gmail" is missing.

However, when I configure the transport in my controller, just before using it, like this:
    Email::configTransport('gmail', [
        'host' => 'ssl://smtp.gmail.com',
        'port' => 465,
        'username' => 'examplesender@gmail.com',
        'password' => 's2d5f8t9',
        'className' => 'Smtp'
    ]);

It works and sends the email. Still, I'd like to configure the transport in app.php so I would be able to use the same transport config multiple times.
Thanks!!!


text:
Q: .htaccess 301 with querystring and special characters I've looked around the site for answers and followed a few examples but i'm still drawing a blank with this one.
I'm trying to get the following to redirect.
www.mydomain.com/?s=flat+roof+specifier+checklist
to
www.mydomain.com/resources/flat-roof-checklist/
My rewrite rule is below.
RewriteCond %{QUERY_STRING} s=flat+roof+specifier+checklist
RewriteRule ^(.*)$ /resources/flat-roof-checklist/? [L,R=301]

I think the issue im having is the "+" character.
if i change my URL to:
www.mydomain.com/?s=flat%20roof%20specifier%20checklist
and my rewrite condition to:
RewriteCond %{QUERY_STRING} s=flat%20roof%20specifier%20checklist
It works fine.
The problem with that is, the URL HAS to be www.mydomain.com/?s=flat+roof+specifier+checklist (with the + characters in there) as the business has already sent out communications with that particular url, so unfortunately i can't change it.
Am i missing some sort of regx to format my url beforehand.?
There's already a 301 redirect plugin running on the site but it doesn't work with that either.
Apologies as i'm fairly new to php,wordpress,htaccess etc.
Any help will be great appreciated.

A: You can place the pattern into a regex capture group and escape the plus signs, tested and working on my test server with the following
RewriteCond %{QUERY_STRING} (s=flat\+roof\+specifier\+checklist)
RewriteRule ^(.*)$ /resources/flat-roof-checklist/? [L,R=301]


text:
Q: How to get *every* products (in stock, out of stock, enabled, disabled, etc..) I've been trying to figure this out for too many hours now...
How can I fetch every products from the database?
I've tried a lot of different method of getting the products, but all of them either don't work at all or only return products in stock.
This is what I'm using at the moment and it returns every products in stock (5 products out of the ~50 products that I can see in the admin):
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->load();

foreach ($collection->getItems() as $productItem) {
    $product = $productItem->getData();
    echo $product['name'].'<br>';
}

If it matters, my goal is to update these products (name, description, stock, price...).

A: You can apply status and visibility filter in collection to fetch all Products:
/**
 * @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
 * @param \Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus
 * @param \Magento\Catalog\Model\Product\Visibility $productVisibility
 * @throws \Magento\Framework\Exception\LocalizedException
 */
public function __construct(
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    \Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
    \Magento\Catalog\Model\Product\Visibility $productVisibility
) {
    $this->productCollectionFactory = $productCollectionFactory;
    $this->productStatus = $productStatus;
    $this->productVisibility = $productVisibility;
}

/**
 * @return \Magento\Framework\DataObject[]
 * @throws \Magento\Framework\Exception\LocalizedException
 */
public function getProducts()
{
    /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
    $collection = $this->productCollectionFactory->create();
    $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner');
    $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');
    $collection->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])
        ->addAttributeToFilter('visibility', ['in' => $this->productVisibility->getVisibleInSiteIds()]);

    return $collection->getItems();
}

You can check more on below links:
How to get a list of all products in Magento 2?
How to get only out of stock products in magento 2

A: I found the solution with the help of Pankaj Pareek.
I just added $collection->setFlag('has_stock_status_filter', false); and now I get every products.

A: You can update product name,description, stock etc by using csv also, export product form admin
Login To Admin
Go To System => Export =>
Select Option As per Below and export product
Entity Type => Products

https://prnt.sc/i2yvjl
https://prnt.sc/i2yvhb

Form CSV you can remove extra fields and you can update name ,description etc by using SKU
In CSV Fileds like
sku,name,description,price


text:
Q: C# import excel filesheet to sql database error I have met the error: Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done. I'm using SQL Server 2005 and Visual Studio 2005.
I met this error during the import of an excel filesheet to a table in my sql table. Below is my code:
#region Using directives
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
#endregion Using directives

namespace CSASPNETExcelImportExport
{
public partial class ExcelImport : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    // Get the row counts in SQL Server table.
    protected int GetRowCounts()
    {
        int iRowCount = 0;

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=<IP>;Initial Catalog=SOD;Persist Security Info=True;User ID=<username>;Password=<password>"].ToString()))
        {
            SqlCommand cmd = new SqlCommand("select count(*) from <database>", conn);
            conn.Open();

            // Execute the SqlCommand and get the row counts.
            iRowCount = (int)cmd.ExecuteScalar();
        }

        return iRowCount;
    }

    // Retrieve data from the Excel spreadsheet.
    protected DataTable RetrieveData(string strConn)
    {
        DataTable dtExcel = new DataTable();

        using (OleDbConnection conn = new OleDbConnection(strConn))
        {
            // Initialize an OleDbDataAdapter object.
            OleDbDataAdapter da = new OleDbDataAdapter("select * from <database>", conn);

            // Fill the DataTable with data from the Excel spreadsheet.
            da.Fill(dtExcel);
        }

        return dtExcel;
    }

    // Import the data from DataTable to SQL Server via SqlBulkCopy
    protected void SqlBulkCopyImport(DataTable dtExcel)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=<ip>;Initial Catalog=SOD;Persist Security Info=True;User ID=<username>;Password=<password>"].ToString()))
        {
            // Open the connection.
            conn.Open();

            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
            {
                // Specify the destination table name.
                bulkCopy.DestinationTableName = "<database>";

                foreach (DataColumn dc in dtExcel.Columns)
                {
                    // Because the number of the test Excel columns is not
                    // equal to the number of table columns, we need to map
                    // columns.
                    bulkCopy.ColumnMappings.Add(dc.ColumnName, dc.ColumnName);
                }

                // Write from the source to the destination.
                bulkCopy.WriteToServer(dtExcel);
            }
        }
    }

    protected void btnImport_Click(object sender, EventArgs e)
    {
        // Before attempting to import the file, verify
        // that the FileUpload control contains a file.
        if (fupExcel.HasFile)
        {
            // Get the name of the Excel spreadsheet to upload.
            string strFileName = Server.HtmlEncode(fupExcel.FileName);

            // Get the extension of the Excel spreadsheet.
            string strExtension = Path.GetExtension(strFileName);

            // Validate the file extension.
            if (strExtension != ".xls" && strExtension != ".xlsx")
            {
                Response.Write("<script>alert('Please select a Excel spreadsheet to import!');</script>");
                return;
            }

            // Generate the file name to save.
            string strUploadFileName = "~/UploadFiles/" + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;

            // Save the Excel spreadsheet on server.
            fupExcel.SaveAs(Server.MapPath(strUploadFileName));

            // Generate the connection string for Excel file.
            string strExcelConn = "";

            // There is no column name In a Excel spreadsheet.
            // So we specify "HDR=YES" in the connection string to use
            // the values in the first row as column names.
            if (strExtension == ".xls")
            {
                // Excel 97-2003
                strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 8.0;HDR=Yes;\"";

                //if the above doesn't work, you may need to prefix OLEDB; to the string, e.g.
                //strExcelConn = "OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<URL>" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 8.0;HDR=Yes;\"";
            }
            else
            {
                // Excel 2007
                strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<URL>" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
            }

            DataTable dtExcel = RetrieveData(strExcelConn);

            // Get the row counts before importing.
            int iStartCount = GetRowCounts();

            // Import the data.
            SqlBulkCopyImport(dtExcel);

            // Get the row counts after importing.
            int iEndCount = GetRowCounts();

            // Display the number of imported rows.
            lblMessages.Text = Convert.ToString(iEndCount - iStartCount) + " rows were imported into Person table";

            if (rblArchive.SelectedValue == "No")
            {
                // Remove the uploaded Excel spreadsheet from server.
                File.Delete(Server.MapPath(strUploadFileName));
            }
        }
    }
}
}

Is it because my connectionstring error?

I have changed my connection strings as of what Nathan suggested. Now I met the following error:

http://i.stack.imgur.com/nWyte.png
What error is it this time? D:

A: It looks like you actually have several things wrong with your connection strings.  For one thing, Excel connection strings should not include an "Initial Catalog", and they should include a Data Source referring to the file, not a server.
Try this instead:
        // There is no column name In a Excel spreadsheet.
        // So we specify "HDR=YES" in the connection string to use
        // the values in the first row as column names.
        if (strExtension == ".xls")
        {
            // Excel 97-2003
            strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 8.0;HDR=Yes;\"";

            //if the above doesn't work, you may need to prefix OLEDB; to the string, e.g.
            //strExcelConn = "OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 8.0;HDR=Yes;\"";
        }
        else
        {
            // Excel 2007
            strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
        }

Fyi, http://connectionstrings.com is a good resource for these kind of things.

A: Try removing "Persist Security Info=True" from your connection strings.
http://support.microsoft.com/kb/269495


text:
Q: Center columns inside Grid Layout I've started to learn grid system (display:grid) and I have the following code, but I don't know how to center last two columns (4 and 5) without add more columns in grid-template-columns and use grid-column-start and grid-column-end in the columns. Is it possible?:
HTML:

      1

        2

        3

        4

        5

CSS:
body {
    margin: 0;
}

.grid-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 20px;
}

.grid-item {
    padding: 10px;
    background: skyblue;
}

JSFiddle: https://jsfiddle.net/3b5Lxujh/
What I have:

What I want:

A: You should add columns if you are using CSS girds - you use a 6-column grid for this using grid-template-columns: repeat(6, 1fr) with each item spanning two grid columns - and place the last row to the center by using grid-column rule - see demo below:

body {
  margin: 0;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-gap: 20px;
}

.grid-item {
  padding: 10px;
  background: skyblue;
  grid-column: span 2;
}

.grid-item:nth-last-child(2) {
  grid-column: 2 / 4;
}

.grid-item:last-child {
  grid-column: 4 / 6;
}

1

2

3

4

5

Flexbox Solution
For this layout flexbox is more suited - and normally I'd use a flexbox using flex-basis (with calc to create the grid gaps) like this:

body {
  margin: 0;
}

.grid-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.grid-item {
  padding: 10px;
  background: skyblue;
  margin: 10px;
  flex-basis: calc(33.33% - 40px);
}

1

2

3

4

5


text:
Q: apex:iframe doesn't allow display-capture Can you tell me please how to enable display-capture in Visualforce page?
HTML
<apex:outputPanel layout="block">
        <apex:iframe src="" html-allow="camera; microphone; fullscreen; display-capture" scrolling="true" id="obIframe" height="1200px" width="100%"
        html-sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-pointer-lock allow-top-navigation" />
</apex:outputPanel>

JS
const iframePermissionsParameter = '?iframe_allow=' + encodeURIComponent("geolocation *; camera *; microphone *; fullscreen *; display-capture *");

const url = `${Endpoint}/auth/${launchToken}/${credentials.siteId}/${iframePermissionsParameter}`;
document.getElementById("obIframe").src = url;

When I run my component, I see in the console that the wrapper aloha-page:iframe has no display-capture permission =>
<iframe force-alohapage_alohapage="" height="100%" width="100%" scrolling="yes" allowtransparency="true" name="vfFrameId_1651674422240" title="accessibility title" allowfullscreen="true" lang="en-US" allow="geolocation *; microphone *; camera *" tabindex="0"></iframe>


text:
Q: Do these two Java generic methods accept the same data types? I'm new to Java and I'm trying to learn about generics. I tried to implement a simple version of binarySearch() method that is also found in the Collections class. I looked up the method signature and it's something like this:
public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) {
  // definition
}

I was wondering if the method above still accepts the same data types if you were to change the method definition to this:
public static <T extends Comparable<? super T>> int binarySearch(List<T> list, T key) {
  // definition
}

If not, what are the differences between the two? Thank you!

A: Consider these classes:
class A extends Comparable<A> { /* ... */ }
class B extends A { /* ... */ }

Now define a key and a list with these types:
A key = new B();
List<B> list = List.of(key);

You can invoke  the first form with these arguments, but not the second.

A: For example:
static class NonComparable {

}

static class MyComparable implements Comparable<NonComparable> {
    @Override
    public int compareTo(NonComparable o) {
        return 0; // irrelevant for the example
    }
}

And then declare the parameters:
List<MyComparable> list = Arrays.asList(new MyComparable());
NonComparable  nonComparable = new NonComparable();
binarySearch(list, nonComparable);

One of your method definitions allows an invocation, the other does not.


text:
Q: Send a message with SockJS to Spring Websocket handler over RabbitMQ I'm developing message-broker communication between 2 applications: Grails client and Spring Boot micro service.
To make my client-side updated in long-polling manner I use WebSockets.
I've successfully configured Grails and Spring Boot to use web sockets over RabbitMQ broker.
Grails client gets all publications from Spring Boot as expected.
But I faced a problem to send message from my JS code on Grails side to Spring Boot handler on server side.
I follows all default configuration from: https://github.com/zyro23/grails-spring-websocket/blob/010ea1fb3557a63b6ce0d87a0b055f6cbc7df319/README.md
The same config I used to write on Spring Boot side:
  @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableStompBrokerRelay("/topic", "/queue")
                .setRelayHost(brokerRelayHost)
                .setSystemLogin(brokerRelayUsername)
                .setSystemPasscode(brokerRelayPassword)
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/stomp").withSockJS()
    }

My client code call:
client.send("/app/hello", {}, JSON.stringify("world"));

But annotation @MessageMapping("/hello") doesn't work on my Spring boot handler methods.
Another one strange thing that when I enable Grails handlers with the same annotation they works good and receives all messages.
I've monitored RabbitMQ admin console and seems like in case with Spring Boot handlers client never send message to broker.
Did anybody find the same issue with cross-application web socket message sending?
Thanks in advance!


text:
Q: python pandas select rows where two columns are (not) equal hsp.loc[hsp['Len_old'] == hsp['Len_new']]

I try this code, it's working.
But I tried these three
hsp.loc[hsp['Type_old'] == hsp['Type_new']]
hsp.loc[hsp['Type_old'] != hsp['Type_new']]
hsp.loc[hsp['Len_old'] != hsp['Len_new']]

They are not working.
My data table hsp is like
id  Type_old  Type_new  Len_old  Len_new
1    Num       Num       15       15
2    Num       Char      12       12
3    Char      Num       10       8
4    Num       Num       4        5
5    Char      Char      9        10

Is there a better approach to select rows where two columns are not queal.

A: Your code, as piRSquared said, had an issue with types.
Besides that, you could use comparing methods, in this case pd.Series.ne
Using your data:
hsp.loc[hsp['Type_old'].ne(hsp['Type_new'])]

But again, as piRSquared mentioned, because of dtypes it didn't work.
Just in case, you have to take care about NaN/None values at your data... such:
hsp.loc[ ( hsp['Type_old'].ne(hsp['Type_new']) ) && (hsp['Type_old'].notna())]

In this case, .ne has another argument, fill_value, which fill missing data.

In addition, you could use "compare" method to show difference between two series (or DataFrames)
hsp.Len_old.compare(hsp.Len_new)

And it might return (if columns were of the same dtype):
   self  other
2  10.0    8.0
3   4.0    5.0
4   9.0   10.0

But just force to have another dtype:
hsp.Len_old.compare(hsp.Len_new.astype('str')) # string type new column

It will return all rows:
   self other
0   15  15
1   12  12
2   10  8
3   4   5
4   9   10

A: Use the complement operator ~
hsp.loc[~(hsp['Type_old'] == hsp['Type_new'])]

which gives:
   id Type_old Type_new  Len_old  Len_new
1   2      Num     Char       12       12
2   3     Char      Num       10        8

When dealing with Boolean operations, the complement operator is a handy way to invert True with False

A: Ways to be confused by == versus != when comparing pd.Series
As expected
df[['Len_old', 'Len_new']].assign(NE=df.Len_old != df.Len_new)

   Len_old  Len_new     NE
0       15       15  False
1       12       12  False
2       10        8   True
3        4        5   True
4        9       10   True

But if one of the column's values were strings!
df[['Len_old', 'Len_new']].assign(NE=df.Len_old.astype(str) != df.Len_new)

   Len_old  Len_new    NE
0       15       15  True
1       12       12  True
2       10        8  True
3        4        5  True
4        9       10  True

Make sure both are the same types.

A: You can also use query here:
In [7]: hsp.query('Type_old != Type_new')
Out[7]:
   id Type_old Type_new  Len_old  Len_new
1   2      Num     Char       12       12
2   3     Char      Num       10        8


text:
Q: discord.js get message's id and delete it When a user joins the server, the bot sends a welcome message, i want to take that welcome message's ID and make the bot delete it if the users leaves after he joins. I tried to save the message's id in a variable and make the bot delete the message when the user leaves but without success. I already took a look at the docs, but I really can't understand how to make it.

A: To do this you would have to store the id of the welcome message and the user that it is tied to (ideally put this in an object). And when the user leaves you would use those values to delete that message.
Example code:
const Discord = require('discord.js');
const client = new Discord.Client();
const welcomeChannel = client.channels.find("name","welcome"); // Welcome is just an example
let welcomes = [];

client.on('message', (message) => {
    if(message.channel.name === 'welcome') {
        const welcomeObj = { id: message.id, user: message.mentions.users.first().username };
        welcomes.push(welcomeObj);
    }
});

client.on('guildMemberRemove', (member) => {
    welcomes.forEach(welcome, () => {
        if(welcome.user === member.user.username) {
            welcomeChannel.fetchMessage(welcome.id).delete();
        }
    });
});

This only works if the welcome message includes a mention to the user so make sure that's in the welcome message.
Also I can't test this code myself at the moment so let me know if you encounter any problems.

A: *

*Define an object to hold the welcome messages by guild and user. You may want to use a JSON file or database (I'd highly recommend the latter) to store them more reliably.

*When a user joins a guild...

*

*Send your welcome message.

*Pair the the message's ID with the user within the guild inside of the object.

*When a member leaves the guild...

*

*Fetch their welcome message.

*Delete the message from Discord and the object.

Example setup:
const welcomeMessages = {};

client.on('guildMemberAdd', async member => {
  const welcomeChannel = client.channels.get('channelIDHere');
  if (!welcomeChannel) return console.error('Unable to find welcome channel.');

  try {
    const message = await welcomeChannel.send(`Welcome, ${member}.`);

    if (!welcomeMessages[member.guild.id]) welcomeMessages[member.guild.id] = {};
    welcomeMessages[member.guild.id][member.id] = message.id;
  } catch(err) {
    console.error('Error while sending welcome message...\n', err);
  }
});

client.on('guildMemberRemove', async member => {
  const welcomeChannel = client.channels.get('channelIDHere');
  if (!welcomeChannel) return console.error('Unable to find welcome channel.');

  try {
    const message = await welcomeChannel.fetchMessage(welcomeMessages[member.guild.id][member.id]);
    if (!message) return;

    await message.delete();
    delete welcomeMessages[member.guild.id][member.id];
  } catch(err) {
    console.error('Error while deleting existing welcome message...\n', err);
  }
});


text:
Q: How to determine whether data is slightly or extremely non-normally distributed? I'm a PhD student and doing a research on regression analysis.
My question is how to determine whether the data is slightly, moderately or extremely non-normally distributed?

TQ to all responses of my question. But, may be my question is not so clear.
Ok, let say i have some different values of skewness and kurtosis (for example: skewness = 1.5, kurtosis = 2.0). So my question is, from the values of skewness and kurtosis, what is the type of data distribution? is it moderately non-normal, or extremely non-normal or what?

A: The sample skewness $$\gamma=\frac{\sum_{i=1}^n(x_i-\bar{x})^3}{\Big(\sum_{i=1}^n(x_i-\bar{x})^2\Big)^{3/2}}$$ and the sample (excess) kurtosis $$\kappa=\frac{\sum_{i=1}^n(x_i-\bar{x})^4}{\Big(\sum_{i=1}^n(x_i-\bar{x})^2\Big)^{2}}-3$$ are often used as measures of non-normality.
The sample skewness measures the asymmetry of the empirical distribution. If it is far from $0$, the distribution is not very symmetric. Since the normal distribution is symmetric, a sample from the normal distribution should be close to $0$.
The sample kurtosis measures the "peakedness" of the distribution. If it is much greater than $0$, then the distribution is more peaked than the normal distribution, which typically means that it has heavier tails. If it is less than $0$ it is less peaked, which typically means that the distribution is bimodal. The sample kurtosis is bounded from below by $-2$ (a value that is obtained for a two-point distribution, which of course is extremely bimodal).!
Here are two examples (normal distribution in grey, other distributions in red):

The skew distribution has theoretical skewness $1.6$ whereas the kurtotic distributions has theoretical (excess) kurtosis $1.5$. As you can see, the kurtotic distribution has heavier tails than the normal distribution.
So, why use skewness and kurtosis as quantifications of non-normality? The main reason is that they affect the asymptotics of the central limit theorem, which as you may know often can be used to motivate the use of a statistical procedure (that is based on normality) even if the data does not come from a normal distribution, given that you have a "large enough" sample. If either the skewness or the kurtosis is high, larger sample sizes are needed for such motivations to be valid.
For some inferential procedures you need to worry more about skewness, and for some you need to worry about heavy tails (kurtosis). I've written more about that elsewhere on this site.

A: I think the other answers really address methods for deciding non-normality.  But I think the OP asks a different question.  Basically he is asking about how to decide once normality is rejected how do you determine the severity?  If it is mild perhaps the deviation can be ignored.  Skewness and kurtosis can be looked at as measures of non-normality but I think it comes down to a subjective decision as to how large a difference should be to call it, mild, moderate or large.  I think the point is that this decision can be made by looking at histograms, qq plots, or the magnitude of the skewness and kutosis.  But this is going to be subjective and not formal.

A: Although a wikipedia link might be not considered extremely helpful, the list of methods for testing normality is quite long.
The methods range from (already mentioned) histograms and qq-Plots if you want to stay on the graphical side over more lets say "empirical tests" (multiple sigma events in relation to sample size) to parametric and nonparametric statistical tests. A complete review of these would be, in my opinion, out of scope here (and for some methods definitely also out of my scope) so I will be quite frank here.
Since you were mentioning regression analysis I guess you want to test the normality of the residuals. Just use one of the normality tests on the wiki page. The more popular variants compare skewness and kurtosis to that of a normal distribution. The nonparametric versions are Kolmogorov-Smirnov type of tests that use the empirical cumulative distribution function of your data (probably the residuals). Just look at the wiki page. The standard tests are quite simple to implement.

A: The Skewness of the Normal distribution is 0. The Kurtosis of the Normal distribution is 0. Those two statistics are concrete measures of distribution characteristics as opposed to subjective plot interpretation. Of course the question remaining is how far from Normal your distribution is for $n$ points and some value of Kurtosis and Skewness.
Hence you will be better off by running some Normality Tests. The Shapiro-Wilk is a sensible choice for univariate data.
If you use R you will find the function shapiro.test() in the stats package useful. The moments package includes the functions skewness() and kurtosis() plus jarque.test() if you want a second opinion after the results of the Shapiro-Wilk test.

A: Here I found some rules of thumb on how to evaluate.
If skewness is:

*

*less than −1 or greater than +1, the distribution is highly skewed.

*between −1 and −½ or between +½ and +1, the distribution is moderately skewed.

*between −½ and +½, the distribution is approximately symmetric.


text:
Q: ¿Cómo mockear una property de un objeto mockeado con Python 2.7? Estoy haciendo un unittest y quiero mockear un objeto. Este objeto tiene un método que tiene el decorador @property y cuando se usa quiero que me devuelva algo especifico.
¿Cuál es la mejor manera de configurar el return_value de esa property? En la documentacion oficial aparece algo raro con type:
type(m).foo = p

Pero no me queda muy claro porqué hay que hacer eso. ¿Alguien tiene una idea de cómo encarar el asunto?

A: Suponiendo que tienes la siguiente clase:
class Algo:
    @property
    def nombre(self):
        return 'Soy la clase Algo'

Simplemente reemplazando el valor debería funcionar, no necesitas usar return_value:
import mock
import unittest

import ruta.hacia.la.clase

@mock.patch('ruta.hacia.la.clase.Algo')
class testAlgo(unittest.TestCase):
    def test_algo_nombre(self, algo):
        algo().nombre = 'Diferente'

        self.assertEquals('Diferente', algo().nombre)


text:
Q: Delete child table data in ruby on rails I have three table like, user, article, saved_article,
User
has_many : saved_articles, dependent: :destroy

Article
has_many : saved_articles, dependent: :destroy

SavedArticle
 id | article_id | user_id | #-> Table

belongs_to :user
belongs_to :article

SavedArticle creating success fully but problem is when I try to delete,
My deleting action:
def remove
  current_user.saved_articles.find(params[:id]).destroy
  redirect_to home_path
end

Remove form:
<%= form_for :remove, url: home_remove_path(id: current_user.saved_articles.id), method: :delete, remote: true  do |f| %>
  <%= f.button 'Remove'.html_safe, data: {disable_with: " Deleting..."}, :class => 'btn btn-default btn-delete' %>
<% end %>

Showing based on upper code :

undefined method `id' for #SavedArticle::ActiveRecord_Associations_CollectionProxy:0x00000016fddd90

When I debug like below:
<%= debug current_user.saved_articles %> then showing all attribute inside the table.
my question is how can I delete my specific attribute  from saved_articles table.
Thanks

A: Form is not required to delete an saved article, Just use the following code in your views,
<%= link_to 'Remove'.html_safe, "#{url_path_for_delete}?id=#{saved_article.id}", data: { confirm: 'Are you sure?', remote: true } %>

Pass in the saved_article's id in the above link and replace the url with the delete method url for the controller method.
Make sure the controller routes are of method 'delete' in routes.rb

A: You can try this
in views
<% current_user.saved_articles.pluck(:id).each do |aid| %>
<%= form_for :remove, url: home_remove_path(aid), method: :delete, remote: true  do |f| %>
  <%= f.button 'Remove'.html_safe, data: {disable_with: " Deleting..."}, :class => 'btn btn-default btn-delete' %>
<% end %>
<% end %>

And in controller you get the id one by one on each request.
if you want to delete all save articles by one click
then
<%= form_for :remove, url: home_remove_path, method: :delete, remote: true  do |f| %>
  <%= f.button 'Remove'.html_safe, data: {disable_with: " Deleting..."}, :class => 'btn btn-default btn-delete' %>
<% end %>

and in controller
def remove
  current_user.saved_articles.destroy_all
  redirect_to home_path
end

A: In your saved_article controller, add before_action :authenticate_user! (if you are using devise). This will ensure that in whatever you are doing, the current user has to be available. Then put this in your destroy action

def destroy
  @saved_article = SavedArticle.find(params[:id])
  @saved_article.destroy
  redirect_to ..., notice: ...
end

Then add a link in your view to delete the saved_article
<%= link_to 'Delete', @saved_article, method: :delete, data: { confirm: 'Are you sure?' }
Don't forget to have your routes set


text:
Q: Calculate the difference in hours between two String dates in MySQL? I have two String columns in MySQL database. Those two columns were populated from a Java program in following way:
System.currentTimeMillis(); //first column
System.currentTimeMillis(); + someStringHours //second column; the String, someStringDays reprensents some number of days, let's say 5 hours in millis...

Which function in MySQL can be used to calculated the difference to get number of hours between these two columns?

A: You call them string dates but they are actually UNIX timestamps in milliseconds (also called Javascript timestamps). That's what System.currentTimeMillis() generates. It's a Java long data item, and a MySQL BIGINT data item. You can store it in a string.  (You can store it that way if you must, but searching and sorting numbers stored as strings is an unreliable mess; beware!)
A typical Javascript timestamp (or UNIX timestamp in milliseconds) is a big integer like 1600858176374456. 1 600 858 176 374 456.
You can convert such a timestamp to a MySQL TIMESTAMP value with FROM_UNIXTIME() like this
    FROM_UNIXTIME(column * 0.001)

Why multiply the column value by 0.001 (that is, divide it by 1000)? Because FROM_UNIXTIME() takes the timestamp in seconds, whereas System.currentTmeMillis() generates it in milliseconds.
Then you can use DATEDIFF() like this
    DATEDIFF(FROM_UNIXTIME(laterTs*0.001),FROM_UNIXTIME(earlierTs*0.001))

This gives an integer number of days.
If you need the time difference in some other unit, such as hours, minutes, or calendar quarters, you can use TIMESTAMPDIFF(). This gives you your difference in hours.
TIMESTAMPDIFF(HOUR,
              FROM_UNIXTIME(laterTs*0.001),
              FROM_UNIXTIME(earlierTs*0.001));

You can use SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR as the time unit in this function.
Pro tip: Use your DBMS's date arithmetic functions if you possibly can. They've worked out all sorts of edge cases for you already.
And, by the way, if you declare your columns like this (Timestamp with a millisecond precision: How to save them in MySQL):
laterTs    TIMESTAMP(3),
earlierTs  TIMESTAMP(3),

You'll have an easier time indexing on and searching by these times.

A: SELECT (1600858176374-1600944576374)/(24*60*60*1000) as Days

Where  (1600858176374-1600944576374) are timestamps and (246060*1000) is a mills in day


text:
Q: Python 3 (CherryPy) Server Not Working on Other Computer I would like to access my CherryPy site on a different computer, but I have tried the answers form here and here, but neither have worked. I am using a Mac with OSX El Capitan, Python 3.5.2, and I believe, the latest version of CherryPy. This is my current code, I do not care what the address is, just that it works. Thanks for any help!
import cherrypy
class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

# bind to all IPv4 interfaces
cherrypy.config.update({'server.socket_host': '0.0.0.0'})
cherrypy.quickstart(HelloWorld())

EDIT:
I can access the site from localhost:8080 127.0.0.1 and 0.0.0.0. The console output is this:
[26/Jul/2016:19:10:26] ENGINE Listening for SIGTERM.
[26/Jul/2016:19:10:26] ENGINE Listening for SIGHUP.
[26/Jul/2016:19:10:26] ENGINE Listening for SIGUSR1.
[26/Jul/2016:19:10:27] ENGINE Bus STARTING

Warning (from warnings module):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/cherrypy/_cpchecker.py", line 105
    warnings.warn(msg)
UserWarning: The Application mounted at '' has an empty config.
[26/Jul/2016:19:10:27] ENGINE Started monitor thread '_TimeoutMonitor'.
[26/Jul/2016:19:10:27] ENGINE Started monitor thread 'Autoreloader'.
[26/Jul/2016:19:10:27] ENGINE Serving on http://0.0.0.0:8080
[26/Jul/2016:19:10:27] ENGINE Bus STARTED

I run my file using IDLE, and I am not using a firewall.

A: The solution is mentioned in comments below the question so this answer is just for marking this question as answered.
Solution: If you want to see your cherrypy application from another computer, find out an IP address on computer where cherrypy is running, using ifconfig on Unix/Linux or ipconfig on Windows. Then set this IP address to your cherrypy config instead of 127.0.0.1 or 0.0.0.0.
cherrypy.config.update({'server.socket_host': '192.168.1.123'})

As long as you're on the same network, you should be able to access the application on that IP/port that you set: http://192.168.1.123:8080/ (or similar)
If you need to change IP and port, use this:
cherrypy.config.update({
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 9090,
})


text:
Q: Emulator internal memory size is automatically changing to 384MB     emulator: WARNING: VM heap size set below hardware specified minimum of 192MB
 emulator: WARNING: Setting VM heap size to 384MB

I am using android studio 2.0 in windows 10 , Internal memory size automatically getting changed to 384 Mb even if I have specified 1Gb in ADB configuration..
How i can increase my emulator Internal Memory Size ?
This is my AVD configuration
show my emulator pic having 533 MB internal memory
Sorry I am not able to embedded pics due to <10 reputation..

A: Open AVD Manager, select your AVD. Under 'Action' column click the edit button (pencil icon). Go to Show Advanced settings and scroll down to VM heap and increase the MB to however much you need.

The above steps should stop the emulator warnings.
I cant see any problems with the screen shots you have provided. I can only recommend creating a new Virtual Device and or checking for Android Studio Updates. Sry I cant be of more help...


text:
Q: Multiple background worker in chain i have a sequence of 3 time consuming functions, i would like to execute them in background worker or whatever else tool, my problem is that each function should wait for the precedent function to complete, so this is my pseudo-code :
open_session() // during the execution of this function i like to display a loading-window

open_session() //this function opens a process another windows app , while opening this app i would like to keep the current app responsive.

close_session()// during the execution of this function i like to display a loading-window

i imagined to do this using background worker, but do function are asynchrounous.
Any help please

A: Just start each consecutive worker in the RunWorkerCompleted event handler of the previous one...
Adressing the downvotes: note that it's a possibility. Whether or not it's a good choice, obviously depends on the context, like always. I don't believe in golden rules such as "it's better to just only use one BGW". I can imagine plenty of circumstances, under which using a single BW for all tasks wouldn't simplify matters (for example, if each operation requires ProgressChanged to be handled differently).
The OP asked about multiple background workers, not having given enough context to judge what approach is best - for all I know, he could be just theoretically wondering how one can "chain" BWs, in order to gain a better understanding of how BW works.

A: Why not execute all three of them sequencially in the same background worker? So, your backgroundworker work event would look like this:
private void yourBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    open_session();
    open_session();
    close_session();
}

That way, the backgroundworker itself is async, but the three methods that you want to run sequentially are still run sequentially within the context of the async method.


text:
Q: why does the slope of a vertical tangent equal $ \infty $ or $ - \infty $? we know that for any point on a curve, the slope of its tangent is m:
$$ m = \lim_{h \to 0} \frac{f(x+h)-f(x)}{h} $$
But i can't understand that for a point which has a vertical tangent, why does the slope  of its tangent be $ \infty $ or  $  - \infty $?
They both are this case: as the denominator $h$ becomes close to $0,$ the numerator $f(x+h)-f(x)$ also becomes close to $0.$
But why does m for the point which has a non-vertical tangent equals a number, but for the point which has a non-vertical tangent equals  $ \infty $ or  $  - \infty $ ?

A: $y-b=m(x-a)$ is the general equation of a line in 2D. When the slope  $m=\pm \infty,$ we can write
$x-a=(y-b)/m \implies x=a$, a vertical line.

A: To answer your question, we first have to understand the definition of the gradient of a line.
The gradient is simply defined as the change in $y$ over the change in $x$ i.e. $m = \frac {\Delta y} {\Delta x}$. It can also be defined as the 'steepness' of a line. The formula for the gradient of a slope is often referred to as 'rise over run', where the 'rise' refers to the change in $y$ and the 'run' refers to the change in $x$.
With a vertical line, the change in $x$ is $0$. When this is the case, the gradient of the tangent line is undefined (since we cannot divide by 0). The gradient of the tangent line is instead $-\infty$ or $+\infty$ (depending on which side you approach it from), which tells us the tangent line is indeed vertical.
It might be helpful to look at an example.

Given the curve $y = x^{1/5}$, find the gradient of the tangent line at $x = 0$.

Using the following formula, the gradient of the tangent can be found:
$$m = \lim_{\Delta x \to 0} \frac{f(c + \Delta x) - f(c)} {\Delta x}$$
Thus, the gradient is as follows:
$$m = \lim_{\Delta x \to 0} \frac{(0 + \Delta x)^{1/5} - (0)^{1/5}} {\Delta x}$$
$$m = \lim_{\Delta x \to 0} \frac{(\Delta x)^{1/5}} {\Delta x}$$
$$m = \lim_{\Delta x \to 0} \frac{1} {\Delta x^{4/5}} = +\infty $$
As you can see above, as $\Delta x$ approaches $0$, $\frac{1} {\Delta x^{4/5}} \ $ approaches $+\infty$.
We can further expand this by approaching the point from a certain side, as follows:
$$m = \lim_{\Delta x \to 0^-} \frac{1} {\Delta x^{4/5}} = +\infty$$
In the above scenario, we are approaching the point from the left side i.e. using values that are negative. Raising a negative value to an even power results in a positive value. Thus, the limit approaches $+\infty$.
The same concept can be applied when approaching the point from the right side i.e. using values that are positive.
$$m = \lim_{\Delta x \to 0^+} \frac{1} {\Delta x^{4/5}} = +\infty$$
In the above scenario, raising a positive value to an even power results in a positive value. Thus, the limit approaches $+\infty$ as well.
It might be helpful to watch this video on vertical tangent lines (the source of this example).
I hope that helps!


text:
Q: how to disable pagination programmatically in Drupal 8 i need to disable the pagination for the view also the items per page.
i have tried this code below but nothing happend, no erros,nothing being changed.

   $view = Views::getView($view->id());
   $view->setDisplay('default');
   $pager = $view->display_handler->getOption('pager');
   $pager['type'] = 'none';
   $view->display_handler->setOption('pager', $pager);
   $view->display_handler->options['pager']['type'] = 'none';

the pagination should not be shown.


text:
Q: How to add curvatures on bars in Chart.js v2.0 I've tried all resources online and they apply to version 1.6. Also went through the code, but wasn't able to find something in regards to the bar style...has anyone solved this? thanks
var data = {
    labels: ["T", "Last Week", "S"],
    datasets: [
        {
            label: "Today",
            backgroundColor: ["#FFB800", "#5D3CC5", "#30B200"],
            borderColor: ["#C89100", "#22008E", "#268B00"],
            borderWidth: 2,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: [65, 59, 49]
        }
    ]
};

var ctx = this.$el.getContext("2d");

var myBarChart = new Chart(ctx, {
    type: 'horizontalBar',
    data: data,
    options: {

        legend: {
            display: false
        },

        scales: {
            yAxes: [{
                display: false
                // ticks: {
                //     beginAtZero: true
                // }
            }],

            xAxes: [{
                //display: false,
                ticks: {
                    beginAtZero: true
                }
            }]

        },

        gridLines: {
            display: false
        },

        tooltips: {
            cornerRadius: 6
        }

    }

});