Q:

Чистка /var/tmp + /var/cache

В общем, острая нехватка места в системном каталоге. Из 42 Гб доступно 2,2 Гб. Сносил, что только мог и что пока не нужно. dnf autoremove и т.д. - не помогло, высвободилось немного места и стало доступно 2,5 Гб.

Если кратко:
20G /var
20G вместе
9,9G /var/tmp
6,9G /var/cache
2,4G /var/log
....

9,9G    /var/tmp
9,9G    вместе
9,1G    /var/tmp/rMD-session-2835
501M    /var/tmp/abrt
205M    /var/tmp/dnf-ekkl-azt2a45o
11M /var/tmp/kdecache-ekkl

/var/cache:
]# du . -hcd 1 | sort -hr
6,9G    загалом
6,9G    .
5,5G    ./PackageKit
1,2G    ./yum
189M    ./dnf
14M     ./cups
6,6M    ./man
6,5M    ./akmods
1,5M    ./app-info
160K    ./ldconfig
128K    ./ibus
36K     ./php-pear
8,0K    ./realmd
8,0K    ./libX11
8,0K    ./krb5rcache
8,0K    ./httpd
8,0K    ./abrt-di
4,0K    ./lightdm
4,0K    ./gdm
4,0K    ./alchemist

/var/tmp:
]# du . -hcd 1 | sort -hr
9,9G    загалом
9,9G    .
9,1G    ./rMD-session-2835
501M    ./abrt
205M    ./dnf-ekkl-azt2a45o
11M ./kdecache-ekkl
6,6M    ./rMD-session-2888
5,4M    ./rMD-session-3075
8,0K    ./systemd-private-56b851ee533342d39646787ad77e8b09-rtkit-daemon.service-1ouSYT
8,0K    ./systemd-private-56b851ee533342d39646787ad77e8b09-httpd.service-8HMA06
8,0K    ./systemd-private-56b851ee533342d39646787ad77e8b09-colord.service-ObUKI0
8,0K    ./systemd-private-56b851ee533342d39646787ad77e8b09-chronyd.service-dFVQFX
4,0K    ./mc-root
4,0K    ./mc-ekkl

Что можно почистить и как?
Остальное не так критично. Ну ещё и /var/log 2.4 Гб.

A:

Поиски дали вот что
]# du . -hcd 1 | sort -hr
....
9,1G    ./rMD-session-2835
6,6M    ./rMD-session-2888
5,4M    ./rMD-session-3075
....

./rMD-session-XXXX это временные директории (содержат много файлов) программы RecordMyDesktop. В силу каких-то причин они не удалились самой программой и легко удаляются вручную из-под обычного пользователя.
Кеш установочных пакетов, накопленных после многократных обновлений/переустановок чистятся так
]# pkcon refresh force -c -1

Ну а логи можно почистить, например так:
]# journalctl --vacuum-time=1d  # Где 1d означает сохранить логи за 1 день


Q:

How many different axes of rotation can coexist?

I have questions about rotation.
There is a sphere in space.  I can apply a force to cause the sphere to rotate around a central axis.   An infinite number of possible central axes can be drawn.

Can I apply a force and then another force such that the sphere will rotate around 2 different central axes at the same time?  I think yes.
Is there an upper limit to how many different axes of rotation a sphere can have at the same time?  Or do various axes (all axes?) somehow cancel out or add up, like linear vector addition - even though 3 different forces contributed to my linear motion the net effect on me can be expressed by a single vector.
If 1 is true, and there are no external influences (whatever force got sphere rotating has stopped) will motion of the sphere change such that rotation is just around just one axis over time?

A:

Can I apply a force and then another force such that the sphere will rotate around 2 different central axes at the same time?

No, this is not the case. Any rigid body, at any time, can only be rotating about one instantaneous axis of rotation. If you apply additional torques this axis can shift, but there's no such thing as having more than one axis of rotation.
Now, that said, if the body is asymmetric, like, say, a slab of wood, then you can think about spinning it quickly about its long axis and then more slowly about an axis orthogonal to that, but even then that's an illusion: at any given time, the block is undergoing an instantaneous rotation about a single axis, with the funky property that this axis will shift position with respect to both the body and the inertial laboratory frame.
In general, the rotational motion of the body is described by the direction $\hat{\mathbf n}$ of this axis and the angular velocity $\omega$ of the rotation, which get combined into a single vector $\boldsymbol{\omega}=\omega \hat{\mathbf n}$ for convenience. In the absence of torques, this angular velocity vector is not conserved; instead, the body rotates with constant angular momentum
$$
\mathbf L=I\boldsymbol\omega,
$$
where $I$ is the moment of inertia matrix for the body; the rotational motion also conserves the rotational kinetic energy $E=\frac12 \boldsymbol{\omega}\cdot \mathbf L=\frac12 \boldsymbol{\omega}\cdot I \boldsymbol{\omega}$. That's about all that you can say in the general case, though if you move to a body-fixed frame you can analyze the motion a bit more understandably: there the angular momentum moves about (because the frame is not inertial) but it conserves both the energy and the total angular momentum $L^2$, which confines it to well-defined curves as described previously here and here on this site.
For the specific case of a sphere, then yes - when free of torques, both $\mathbf L$ and $\boldsymbol\omega$ will stay constant and the sphere will rotate with constant angular velocity about a fixed axis.

A:

No. If you try to rotate a sphere already rotating around a central axis (spinning) by applying another (tangential) force, it will assume a new central axis of spinning. A body cannot spin around two axes at the same time.
There is no upper limit on the number of rotational axes apart from the number of spatial dimensions. For a simplistic example, a body spinning about the x-axis can revolve around a non-central y-axis and this whole system can revolve around another non-central z-axis. An infinite number of these combinations are possible.
See 1.


Q:

call a function class php

I created a class that has 2 functions that deal with the connection to the database and to make a questy. One of these calls the other.
This is my code, but it gives me error .... sure something wrong in calling the function.
Can anyone help me?
class DB{

public function connect(){
    session_start();
    include_once('libs/Smarty.class.php');
    $smarty = new Smarty();
    $smarty->setTemplateDir('templates/');
    $smarty->setCompileDir('templates_c/');
    $smarty->setConfigDir('configs/');
    $smarty->setCacheDir('cache/');

    $host = "localhost";
    $user = "root";
    $pass = "pass";
    $tablename = "table";

    return $connect = mysql_connect($host, $user, $pass);
    mysql_select_db($tablename, $connect) or die(mysql_error());
}

public function do_query($query){
    echo DB::connect();
     if(mysql_query($query,DB::connect())){
         $message="Annuncio inserito correttamente!!";
         echo $message;
     }else{
         $message="Error insert data into DB: ";
         echo $message. mysql_error();
     }
}

}

A:

Your return the $connect ... but you might want to return the mysql_select_db
$connect = mysql_connect($host, $user, $pass);
return mysql_select_db($tablename, $connect) or die(mysql_error());

EDIT:
I was answering to "sure something is wrong ..." as it was an obvious mistake that the last statement isn't executed.
But if you want to use the connect you need to return it, sure!
$connect = mysql_connect($host, $user, $pass);
mysql_select_db($tablename, $connect) or die(mysql_error());
return $connect;


Q:

how to use jquery to fade out anything but the selected element?

i have a few li elements created like this:
echo '
';
foreach ($test as $value){
echo '
.$value['name'].
';
}
echo '
';

this will give me:

name1

name2

name3

...

what i want to do is when i hover over a li element all other li elements to fade out about 50%.
i could have 2 classes and use jquery to change them:
.li_class{
background: #ccc;
}

.fade{
opacity: .5;
}

bur i don't know how to tell jquery to add the .fade class to all other li but not the one i am hovering with the mouse.
any ideas? is there another way of doing this?

edit:
thanks to you all i came up with this:
$(document).ready( function () {
    $('.li_class').hoverIntent(function(){
         $(this).removeClass('fade').siblings().animate({ opacity: 0.5 }, 500);
    },function(){
         $(this).siblings().andSelf().animate({ opacity: 1 }, 100);
    });
});

using the  hoverIntent plugin.

A:

Try this.
$('.li_class').hover(function(){
     $(this).removeClass('fade').siblings().addClass('fade');
},function(){
     $(this).siblings().andSelf().removeClass('fade');
})

A:

$('.li_class').hover(function() {
    $(this).siblings().addClass('fade');
}, function() {
    $(this).siblings().removeClass('fade');
});

JSFiddle DEMO


Q:

Swift(UI) Error: Cannot use mutating member on immutable value: 'self' is immutable

Basically what i want to do is if you press the Button then entries should get a new CEntry. It would be nice if someone could help me out. Thanks!
struct AView: View {

   var entries = [CEntries]()

   var body: some View {
       ZStack {
           VStack {
               Text("Hello")
               ScrollView{
                   ForEach(entries) { entry in
                       VStack{
                        Text(entry.string1)
                        Text(entry.string2)
                    }
                }
            }
        }
        Button(action: {
            self.entries.append(CEntries(string1: "he", string2: "lp")) <-- Error
        }) {
            someButtonStyle()
        }
    }
}

}

The Class CEntries
 class CEntries: ObservableObject, Identifiable{
    @Published var string1 = ""
    @Published var string2 = ""

    init(string1: String, string2: String) {
        self.string1 = string1
        self.string2 = string2
    }
}

A:

Views are immutable in SwiftUI. You can only mutate their state, which is done by changing the properties that have a @State property wrapper:
@State var entries: [CEntries] = []

However, while you could do that, in your case CEntries is a class - i.e. a reference type - so while you could detect changes in the array of entries - additions and removals of elements, you won't be able to detect changes in the elements themselves, for example when .string1 property is updated.
And it doesn't help that it's an ObservableObject.
Instead, change CEntries to be a struct - a value type, so that if it changes, the value itself will change:
struct CEntries: Identifiable {
    var id: UUID = .init()
    var string1 = ""
    var string2 = ""
}

struct AView: View {

   @State var entries = [CEntries]()

   var body: some View {
       VStack() {
          ForEach(entries) { entry in
             VStack {
                Text(entry.string1)
                Text(entry.string2)
             }
          }
          Button(action: {
            self.entries.append(CEntries(string1: "he", string2: "lp"))
          }) {
              someButtonStyle()
          }
      }
   }
}


Q:

Why does my Arxiv paper not show my affiliation?

I am a graduate student and have just submitted one pre-print to Arxiv. However, there is no organization name before the author name although
the Arxiv endorsement system automatically accepted my submission due to my .edu email address.
How can I fix this?

A:

By default, the Arxiv does not show affiliations of paper authors on its webpages. You apparently can add them by adding them in parentheses behind your name. See the help pages:

If you wish to include author affiliations, put them in parentheses. Do not put a full mailing address. At most, include a city and country (no zip codes, postal codes, or street addresses). If you have several authors from the same institution, you can use a footnote style for the affiliations. Here is an example (be sure to do it in the form presented here, including all parentheses, and using numbers and not letters):
  Authors: Author One (1), Author Two (1 and 2), Author Three (2)
          ((1) Institution One, (2) Institution Two)

However, this feature is rarely used in my experience.
However, on the actual preprint (i.e., the PDF, PS, or whatever), you can show affiliations as you like (well, they should be correct). These are not automatically added by the Arxiv; you have to do this yourself. The content and layout of the actual preprint is controlled by you (except for a watermark from the Arxiv).


Q:

Make UIImage clipsToBound over UITableViewCell

I have a UITableViewController with a static table cell.
And I'm trying to make a cell With UIImageView and this image clipToBounds to this cell but it's not working.
This is a sample that I want to do.

But when I make a UITableView and set UIImage clipToBounds to TRUE
the result is :

Am I just need a way to make UIImageView like the first image anyway to do that with UITableView Cell?
And this is my UIImageView Constraints :

and here's my code :
class ProfileTableViewController: UITableViewController {

    @IBOutlet weak var userImage: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()

        // image view

       self.userImage.layer.cornerRadius = self.userImage.frame.width / 2
       self.userImage.clipsToBounds = true

    }

// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 3
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    var number = 0

    if section == 0
    {
        number = 1
    }else if section == 1
    {
        number = 4
    }else if section == 2
    {
        number = 1
    }

    return number
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 100
}

}

A:

I Found the solution when i added this method and add custom Section header
and give it clipToBounds = false
problem solved
i'm just added :
  override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.clipsToBounds = false

        return view
    }

and it's working perfectly :))
thanks all for trying to help me


Q:

Objective C / iPhone - How does the Date Time Picker format its dates (e.g. strips YYYY) AND how do I retrieve these formats?

When using the Date/Time picker on the iPhone/iPad, the year (yyyy) is stripped from the Date formatting in order to make room for the time.
How does it accomplish this based on the default unicode formats stored by the region format?
The formats do not necessarily match any of the following:
NSDateFormatterLongStyle
NSDateFormatterShortStyle
NSDateFormatterMediumStyle
NSDateFormatterFullStyle
Take the Bulgarian region format for instance.  The formats are (respectively):
dd MMMM y
dd.MM.yy
dd.MM.yyyy
dd MM y, EEE
And United States:
MMMM d, y
M/d/yy
MMM d, y
EEEE, MMMM d, y
A Bulgarian date time picker displays:

e.g. 06 10 cp
Where the United states display:

e.g. Wed Oct 06
There is no Bulgarian format where the day name comes last, neither is there a format where the day name comes first in the US formats.  This makes me wonder about languages where there are character following years and months.

How the heck does the date picker
parse out the year properly given the
formatting information available?
And how does it know where to stick
the day name?
Are there other date formats stored
in the operating system (based on the
user-selected region) that the date
time picker retrieves?

Most importantly, how do I retrieve these dates formats from the locale?
I do not want to just throw in some ad-hoc format string - I need to extract the existing ones.
Thanks!
This is a follow up question after find out how to retrieve the actual unicode formats:
Objective C / iPhone: How do I extract the actual unicode date format strings for the current region?

A:

You can specify date format by a string and then you can get relatively good results.
For example:

    NSDateFormatter *timeFormat = [[[NSDateFormatter alloc] init] autorelease];
    [timeFormat setDateFormat:@"HH:mm:ss"];
    NSString *theTime = [timeFormat stringFromDate:[datePickerView date]];

The only difference is when you use US settings the first day is Sunday for EU it is monday
bu you can handle that by NSCalendar firstWeekDay.
Hope it can help.
a: AM/PM
A: 0~86399999 (Millisecond of Day)

c/cc: 1~7 (Day of Week)
ccc: Sun/Mon/Tue/Wed/Thu/Fri/Sat
cccc: Sunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday

d: 1~31 (0 padded Day of Month)
D: 1~366 (0 padded Day of Year)

e: 1~7 (0 padded Day of Week)
E~EEE: Sun/Mon/Tue/Wed/Thu/Fri/Sat
EEEE: Sunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday

F: 1~5 (0 padded Week of Month, first day of week = Monday)

g: Julian Day Number (number of days since 4713 BC January 1)
G~GGG: BC/AD (Era Designator Abbreviated)
GGGG: Before Christ/Anno Domini

h: 1~12 (0 padded Hour (12hr))
H: 0~23 (0 padded Hour (24hr))

k: 1~24 (0 padded Hour (24hr)
K: 0~11 (0 padded Hour (12hr))

L/LL: 1~12 (0 padded Month)
LLL: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec
LLLL: January/February/March/April/May/June/July/August/September/October/November/December

m: 0~59 (0 padded Minute)
M/MM: 1~12 (0 padded Month)
MMM: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec
MMMM: January/February/March/April/May/June/July/August/September/October/November/December

q/qq: 1~4 (0 padded Quarter)
qqq: Q1/Q2/Q3/Q4
qqqq: 1st quarter/2nd quarter/3rd quarter/4th quarter
Q/QQ: 1~4 (0 padded Quarter)
QQQ: Q1/Q2/Q3/Q4
QQQQ: 1st quarter/2nd quarter/3rd quarter/4th quarter

s: 0~59 (0 padded Second)
S: (rounded Sub-Second)

u: (0 padded Year)

v~vvv: (General GMT Timezone Abbreviation)
vvvv: (General GMT Timezone Name)

w: 1~53 (0 padded Week of Year, 1st day of week = Sunday, NB: 1st week of year starts from the last Sunday of last year)
W: 1~5 (0 padded Week of Month, 1st day of week = Sunday)

y/yyyy: (Full Year)
yy/yyy: (2 Digits Year)
Y/YYYY: (Full Year, starting from the Sunday of the 1st week of year)
YY/YYY: (2 Digits Year, starting from the Sunday of the 1st week of year)

z~zzz: (Specific GMT Timezone Abbreviation)
zzzz: (Specific GMT Timezone Name)
Z: +0000 (RFC 822 Timezone)

A:

Are there other date formats stored in
  the operating system (based on the
  user-selected region) that the date
  time picker retrieves?

Yes. From the UIDatePicker class documentation for the local property:

The default value is nil. which tells
  the date picker to use the current
  locale as returned by currentLocale
  (NSLocale) or the locale used by the
  date picker’s calendar. Locales
  encapsulate information about facets
  of a language or culture, such as the
  way dates are formatted.


Q:

MS Outlook Integration using C#

I've already added the COM library of Outlook into my references. The problem is I don't know which version of Outlook the client has installed on his workstation. If I add Outlook 2007 DLL (outlook 12.0 library) then the client who has Outlook 2003 (outlook 11.0 library) can't access my application. It will throw exceptions. How can I fix this problem? Can I add Outlook references dynamically based on the currently installed Outlook version?

A:

You should use Outlook 2003 interop lib. It works for all versions higher than 2003. Or you can implement your own object model for Outlook and use late binding for Outlook.


Q:

Need help understanding the results of the unit function

I want to get Limit of the following function at $T\to 0$.
$$
Eig=\frac{8 (\eta +J \sinh (2 \beta  \eta ) \sinh (2 \beta  J)+\eta  \cosh (2 \beta  \eta ) \cosh (2 \beta  J))}{\eta  Z^2}
$$
where $Z=2 (\cosh (2 \beta  \eta )+\cosh (2 \beta  J))$, $\eta =\sqrt{B^2+J^2}$, and $\beta =\frac{1}{T}$. Both $J, B$ are reals.
I used
Z = 2 (Cosh[2 β J] + Cosh[2 β η]);
η = Sqrt[B^2 + J^2];
β = 1/T;
Eig = (8 (η + η Cosh[2 β η] Cosh[2 β J] +
    J Sinh[2 β η] Sinh[2 β J]))/(Z^2 η)
Limit[Eig, T -> 0]

But I can't understand the output.

A:

I get 0 for several cases.
Z = 2 (Cosh[2 β J] + Cosh[2 β η])
η = Sqrt[B^2 + J^2]
β = 1/T
Eig = (8 (η + η Cosh[2 β η] Cosh[2 β J] +
      J Sinh[2 β η] Sinh[2 β J]))/(Z^2 η)

$Assumptions = J ∈ Reals && B ∈ Reals

Limit[Eig, T -> 0] // Simplify
(*ConditionalExpression[0, J > 0 && Sqrt[B^2 + J^2] < 3 J && Sqrt[B^2 + J^2] > J]*)

So the limit is 0 for the above conditions.  The last condition seems like a safe bet if J != 0.   So try Sqrt[B^2 + J^2] > 3 J
$Assumptions = J ∈ Reals && B ∈ Reals && Sqrt[B^2 + J^2] > 3 J

Limit[Eig, T -> 0] // Simplify
ConditionalExpression[0, J < 0 && Sqrt[B^2 + J^2] + J > 0 && Sqrt[B^2 + J^2] + 3 J > 0]

The limit is still 0, but it wants J to be negative in this case.  Try it the other way.
$Assumptions = J > 0 && B ∈ Reals && Sqrt[B^2 + J^2] > 3 J

Limit[Eig, T -> 0] // Simplify
(*0*)

And we get 0 with no further conditions.  So it looks like Mathematica thinks the limit is 0.  You might to think of other conditions that I haven't thought of.


Q:

Close Browser Window after Form Post

Here's my situation.
I have a button on my ASP.NET webform. This button creates a new browser window pointing to a page which has a lot of hidden fields (which are dynamically generated). This form submits itself to SQL Reporting Services on the bodies onload event. This works fine and the report is displayed in this new window.
However, now I want to still POST a form to SQL Reporting services but I want to get back an excel spreadsheet. So I add another hidden input with a name of rs:Format and value of Excel. This works and the user gets the option to download the excel file.
However they are now stuck with the extra window that was created. How do I get around this? I've tried creating the dynamic form and POST in the same window, but then they see the (empty) page with the form, and not the page they generated the report from. I've tried closing the window that I've created but I don't know where to put the javascript to do this. If I put it on the onload, then the window closes without the form being submitted.
Any ideas for what to do here?
Edit: What I was doing here wasn't the best way of getting the result I needed. I ended up using a WebRequest to get the excel report from Reporting Services instead posting a form, therefore I didn't need the second window afterall.

A:

Don't close the browser.  It belongs to the user, even if you opened it.  Closing it can make them mad.
Do redirect to a page the communicates to the user that you're done with the window.  There you can provide a (javascript-based) link that make closing the browser a little easier if you want, though closing a browser window is generally pretty easy.


Q:

Creating function to rename columns in pandas dataframe

I have dataframe as below:
df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})

I tried creating a function which allow to change the column name dynamically where I can just input the old column name and new column name in the function as below:
def rename_column_name(df, old_column, new_column):
    df = df.rename({'{}'.format(old_column) : '{}'.format(new_column)}, axis=1)
    return df

This function is only applicable if I only have one input as below:
new_df = rename_column_name(df, '$a' , 'a')

which give me this new_df as below:
new_df = pd.DataFrame({'a':[1,2], '$b': [10,20]})

However, i wanted to create a function that allow me to make changes on multiple/one column depending on my preference as such:
new_df = rename_column_name(df, ['$a','$b'] , ['a','b'])

And get the new_df as below
new_df = pd.DataFrame({'a':[1,2], 'b': [10,20]})

So, how do I make my function more dynamic to allow me the freedom to enter multiple/one column names and rename them?

A:

You don't need a function, you can do this using dict comprehension:
In [265]: old_names = df.columns.tolist()

In [266]: new_names = ['a','b']

In [268]: df = df.rename(columns=dict(zip(old_names, new_names)))

In [269]: df
Out[269]:
   a   b
0  1  10
1  2  20

Function that OP needs:
In [274]: def rename_column_name(df, old_column_list, new_column_list):
     ...:     df = df.rename(columns=dict(zip(old_column_list, new_column_list)))
     ...:     return df
     ...:

In [275]: rename_column_name(df,old_names,new_names)
Out[275]:
   a   b
0  1  10
1  2  20

You need to pass a list of columns to this function. It can be multiple columns or a single column. This should do what you were looking for.


Q:

Newspaper library

As an absolute newbie on the topic of using python, I stumbled over a few difficulties using the newspaper library extension. My goal is to use the newspaper extension on a regular basis to download all new articles of a German news website called "tagesschau" and all articles from CNN to build a data stack I can analyze in a few years.
If I got it right I could use the following commands to download and scrape all articles into the python library.
import newspaper
from newspaper import news_pool

tagesschau_paper = newspaper.build('http://tagesschau.de')
cnn_paper = newspaper.build('http://cnn.com')

papers = [tagesschau_paper, cnn_paper]
news_pool.set(papers, threads_per_source=2) # (3*2) = 6 threads total
news_pool.join()`

If that's the right way to download all articles, so how I can extract and save those outside of python? Or saving those articles in python so that I can reuse them if I restart python again?
Thanks for your help.

A:

The following codes will save the downloaded articles in HTML format. In the folder, you'll find. tagesschau_paper0.html, tagesschau_paper1.html, tagesschau_paper2.html, .....
import newspaper
from newspaper import news_pool

tagesschau_paper = newspaper.build('http://tagesschau.de')
cnn_paper = newspaper.build('http://cnn.com')

papers = [tagesschau_paper, cnn_paper]
news_pool.set(papers, threads_per_source=2)
news_pool.join()

for i in range (tagesschau_paper.size()):
    with open("tagesschau_paper{}.html".format(i), "w") as file:
    file.write(tagesschau_paper.articles[i].html)

Note: news_pool doesn't get anything from CNN, so I skipped to write codes for it. If you check cnn_paper.size(), it results to 0. You have to import and use Source instead.
The above codes can be followed as an example to save articles in other formats too, e.g. txt and also only parts that you need from the articles e.g. authors, body, publish_date.


Q:

How do I dynamically update the name of a worksheet in Excel?

I have an Excel spreadsheet which is being used to specify filesystem build information for our Unix team.
This worksheet would have different information depending on the system to be built.  For example, a production system would have many filesystems, whereas a development system only one or two.
So based on user input, we would populate one or other of the two input worksheet formats ("dev","prod") but the destination worksheet will be always be the same.  Only one of the dev or prod worksheets would be visible and active for users to input data at any given time.
How do we tell Excel to use a particular input worksheet to calculate another output worksheet?
My initial idea was that, for simplicity's sake, the "output" worksheet would take its data from an "input" worksheet, and that we would dynamically make either the "dev" or "prod" template become the "input" worksheet.  Is this the right way to do this, or is there some better method?

A:

There's a few ways depending on the complexity of the sheet:

If you only have a few worksheets, and users would just select "Production" or "Test", you could set up the conditional logic in the formulas.  For example:  =if(A1="Test",TestSheet!A1 + TestSheet!A2, ProdSheet!A1 + ProdSheet!A2)
You could utilize the same type of idea as above, but add more complexity using vlookup tables
Your VBA code could create the entire Excel spreadsheet dynamically based on the user input


Q:

how to define key bindings for both GNU Emacs and Aquamacs?

I use both GNU Emacs for OSX and Aquamacs. I like to define key bindings that utilize the Mac command key ⌘.
Unfortunately, the syntax for specifying the ⌘ key is different for each.
In Aquamacs, it looks like this:
(define-key osx-key-mode-map (kbd "A-h") 'replace-string)

In GNU Emacs for OSX, it looks like this:
(define-key key-minor-mode-map (kbd "s-h") 'replace-string)

Is there a way to specify these key bindings in a way that both GNU Emacs and Aquamacs will understand, so that I don't have to maintain and update two separate .emacs files every time I add a new key binding?

A:

Based on lawlist suggestion, you could even define a function to do it:
(defvar gnuemacs-flag (string-match "GNU" (emacs-version)))
(defvar aquamacs-flag (string-match "Aquamacs" (emacs-version)))

(defun define-hyper-key (key fun)
  (cond
   (aquamacs-flag
    (define-key osx-key-mode-map (kbd (concat "A-" key)) fun))
   (gnuemacs-flag
    (define-key key-minor-mode-map (kbd (concat "s-" key)) fun))))

;; The aquamacs/gnuemacs keybindings:
(define-hyper-key "h" 'replace-string)


Q:

Multiple @ManagedProperty of same Type

I have a manged bean where I use another managed bean:
@ManagedProperty(value="#{tableActions}")
private TableActions table1;

that works fine.
Now I need to use another instance of it:
@ManagedProperty(value="#{tableActions}")
private TableActions table1;

@ManagedProperty(value="#{tableActions}")
private TableActions table2;

However, now table2 is the same as table1. How can I create a separate instance?

A:

Make it a @NoneScoped bean.
You only need to make sure you access it in view via #{yourParentBean.table1} and not via #{tableActions}.
See also:

what is none scope bean and when to use it?
How to choose the right bean scope?


Q:

.htaccess : Location not allowed here

I am getting a "Location not allowed here" error with this .htaccess.
Does anyone have any idea on how I should fix this?
<Files 'login'>
    AuthName NTLM
    AuthType NTLM
    NTLMAuth on
    NTLMAuthoritative on
    NTLMServer <censored>
    NTLMBackup <censored>
    NTLMLockfile <censored>
    require valid-user
    Satisfy all
</Files>
<Location /alarms/[0-9]+/acknowlege>
    Order deny,allow
    Deny from all
    Allow from localhost
</Location>

A:

Location isn't valid in .htaccess
See:

http://httpd.apache.org/docs/2.2/mod/core.html#location
http://httpd.apache.org/docs/2.2/mod/core.html#files

Notice how Files says that you can have it in .htaccess, but Location doesn't... You'll need to add your Location to either the server config or a virtual host.


Q:

Meaning of 閒日 (cantonese)

In the sentence 唔知佢點解，佢閒日唔會打電話嚟。
What is the meaning of 閒日？
The official translation given by my reference is “weekdays”, but when i searched this in the dictionary, the meaning given is “free time”.
Which is it? Is it a cultural difference?

A:

Words.hk defines it as:

名詞
  星期一至五, 唔屬於星期六日或公眾假期嘅日子（量詞：個）
  weekdays: Monday,Tuesday,Wednesday, Thursday or Friday; usually with the restriction of a non-holiday

And they give the example:

閒日飲茶有折喎！
  haan4 jat2 jam2 caa4 jau5 zit3 wo3!
  Discount for dim-sum on weekdays!

——
閒日 is literally made up of the characters for idle + day. Why weekdays are idle days could only be explained by slow business - because business is would, assumably, be good on the weekends and holidays. But you’d never hear this usage in Mandarin where it just simply means “off day,” i.e.: a day where one doesn’t work.
——
Guangzhouhua-Putonghua gives it a different Cantonese definition:

背集；不逢集的日子。

“Non-market days.”
CCCanto’s definition is also similar:

free time or off day


Q:

Mod_rewrite, $_GET does not pass along the variable

I'm trying to make
domain.com/notalone/viewpost/5/

act as
domain.com/notalone/viewpost.php?id=5

My current .htaccess is this:
RewriteEngine On

RewriteRule ^notalone/viewpost/([0-9]+)/?$ /viewpost.php?id=$1 [QSA]

Currently, the page loads properly when you visit /notalone/viewpost/5/ but it does not pass $_GET['id']
Things I've Tried:

Adding Options -Multiviews ---> Results in a 404
Using Rewritebase / ---> No effect
RewriteRule ^viewpost/([0-9]+)/?$ /viewpost.php?id=$1 [QSA] ---> No effect

A:

Solved the issue. The problem was evidently an issue with my directories, because when I moved the website to it's own host (its own root directory instead of the notalone subdirectory), everything seemed to work like a charm.


Q:

try to get the first attributes from the 1st store in python 3

i'm trying to get the 1st store attributes, from a specific page,
until now, i can't reach it , because i think it's kind of an array of store - how can i get only the first one ?
import urllib.request
import requests
from bs4 import BeautifulSoup

with urllib.request.urlopen('https://www.zap.co.il/') as response:
html = response.read()
check ='https://www.zap.co.il/search.aspx?keyword='+'20KN0061IV'
r = requests.get(check)
html = requests.get(r.url)
bsObj = BeautifulSoup(html.content,'xml')
price = bsObj.find('div',attrs={'class':'StoresLines'})
print(price)

im getting all the stores - but i want only the first store - how to do that ?

A:

To access the top store (the store before the break) you can replace
price = bsObj.find('div',attrs={'class':'StoresLines'})

with:
price = bsObj.select_one('div.StoreLine')

If you wanted to get the top store from the bunch of lines below the break, replace the same line with:
price = bsObj.select_one('div.StoresLines div.StoreLine')

Hope this helps!
Output of the last suggestion:

67 חוות דעת בשנה האחרונה
1134 בסך הכל

Lenovo E480 20KN0061IV יבואן רשמי במלאי

מחיר:
                        2,609 ₪

                                משלוח:
                            חינם

זמן אספקה:
                            יומיים

מחיר סופי:

2,609 ₪

                            לקנייה

                ב-שניידר

where:
price.select_one('.FinalPrice .PriceNum').text

returns:
'2,609 ₪ '


Q:

Is there a way to prevent text from becoming gray when I disable a button?

When I set my buttons to disabled, the text becomes gray (was black before).
In my window, the result is that the text is not readable when button is disabled.
I looked all over in the documentation of NSButton/NSButtonCell/NSCell/NSControl, but I did not find any way to keep the text black. Do you know how I can do that?

A:

You can set buttons properties (font, colors) for each state in IB. So would setting its text color for the disabled state to black help?


Q:

Playing Chess via SMS Messaging

I know there are some pretty nice open-source chess engines with powerful AI, like Crafty, that also have a nifty command line interface.
I also know that I can send e-mails with my SMS-capable phone, and that I can reply to such an e-mail, and it will be sent to my phone as a SMS text message.
Is there any way I can combine the two?  For example, text message a command like "Nd3" to an e-mail monitored by a computer, which sends the command to Crafty, and e-mails back the response?
I wasn't sure which site to post this one on; hopefully this is appropriate.

A:

Instead of parsing emails back and forth, you could use one of the SMS gateways out there like Twilio that supports sending and receiving messages via HTTP POST requests. I don't know of any free ones off hand that do it this way, but using regular ol' HTTP could save you a lot of time fussing with email servers and such.
Full disclosure: I work at Twilio.


Q:

PropertyChangedEventHandler always null in silverlight binding

I've been trying to resolve this issue for some time.
I'm trying to bind a TextBlock's text to a string property using the INotifyPropertyChanged interface. For some reason the PropertyChangedEventHandler is always null when the value of the property is changed thus the target never gets updated...
Any suggestions?
Code below:
XAML code:
<UserControl x:Class="MoleDashboard.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
xmlns:datacontrols="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
xmlns:primitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"
xmlns:prop="clr-namespace:MoleDashboard"

<UserControl.Resources>
<prop:YearScreen x:Key="YearScreenProps"/>
</UserControl.Resource>

<TextBlock Margin="10 5" x:Name="DataGridLabel" Visibility="Visible" Text="{Binding   YearProperty, Source={StaticResource YearScreenProps}, Mode=OneWay}"/>

Bound property code:
public class YearScreen : INotifyPropertyChanged
{
    private string metricProperty;

    private string yearProperty;

    public event PropertyChangedEventHandler PropertyChanged;

    public YearScreen()
    {
    }

    public string YearProperty
    {
        get { return yearProperty; }
        set { yearProperty = value; this.OnPropertyChanged("YearProperty"); }
    }

    public string MetricProperty
    {
        get { return metricProperty; }
        set { metricProperty = value; this.OnPropertyChanged("MetricProperty"); }
    }

    public void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }

}

A:

This is based on the comments provided and not just the question above.
Basically the problem is that you are creating updating a second instance of your ViewModel (called a YearScreen in your code) and updating that.
A YearScreen is already being created and bound to your Xaml, by the inclusion of:
<UserControl.Resources>
    <prop:YearScreen x:Key="YearScreenProps"/>
</UserControl.Resource>

You are then creating a second ViewScreen elsewhere in code (via new ViewScreen()) and updating that, however there is no connection between the 2 ViewScreen instances, so nothing will update in the Xaml page.
One Possible (quick) solution:
Create your YearScreen as a singleton. That is add a static accessor of type YearScreen in the class and set it from the constructor.
    public class YearScreen : INotifyPropertyChanged
    {
        private static YearScreen _This;

        public static YearScreen This { get { return _This; } }

[snip]

        public YearScreen()
        {
            _This = this;
        }

The you can access the "single" instance of your YearScreen from elsewhere using the static singleton accessor e.g.:
YearScreen.This.YearProperty = DateTime.Now.ToString():

There are better patterns for sharing ViewModels than singletons, but that will get you going.
The pattern you started with is ViewFirst creation (the view creates the ViewModel). ModelFirst does the opposite, but is bad as the model knows how it is displayed. Using a controller object to create the View and ViewModel and connect them is a better alternative, but that is then getting quite complicated. Using injection of single instance objects is a better option, but involves a whole load of new concepts. Lookup Silverlight Prism after you solve your current problems.


Q:

Correct way to use Task.Run and Wait

I have the below block of code that is being launched by a timer:
private void CheckForScheduleItemsTimerOnElapsed(Object sender, ElapsedEventArgs elapsedEventArgs)
{
    if (CurrentlyProcessingMsgs)
        return;

    CurrentlyProcessingMsgs = true;

    var task = Task.Run(() => {
            CheckForScheduleItems.Process(_cancellationToken);
        }, _cancellationToken);

    task.Wait(_cancellationToken);

    CurrentlyProcessingMsgs = false;
}

Now the problem that I am having is that in some cases, the line
CurrentlyProcessingMsgs = false;

is not getting called.   It was my understanding that the Task.Wait was supposed to wait for the task to complete, then continue on, thereby resetting that flag.   But in some cases, that is not happening.   (Note: this timer is being managed by a service.)  What is happening is that the in the shutdown, I am checking the value of CurrentlyProcessingMsgs and sometimes it's still true after the task has completed.
The goal for this is to have multiple timers that are being fired off like the one shown above.   Each timer will do processing similar to what is shown above and I would like to run each process in a separate thread.   I was mistaken on my understanding of the CancellationToken, so in this instance, what would be the correct way to setup the timers and Tasks to run through these methods and have each on a separate thread?

A:

If _cancellationToken is canceled a exception will be raised. If you want to make sure the flag is changed even if it is canceled or some other exception is raised by Process put the CurrentlyProcessingMsgs = false; in a try/finally block
private void CheckForScheduleItemsTimerOnElapsed(Object sender, ElapsedEventArgs elapsedEventArgs)
{
    if (CurrentlyProcessingMsgs)
        return;

    CurrentlyProcessingMsgs = true;
    try
    {
        var task = Task.Run(() => {
                CheckForScheduleItems.Process(_cancellationToken);
            }, _cancellationToken);

        task.Wait(_cancellationToken);
    }
    finally
    {
        CurrentlyProcessingMsgs = false;
    }
}

P.S. There is almost never a good reason to do a Task.Run then immediately wait on it. It would be a lot less overhead to just do the following which should have very similar logic.
private void CheckForScheduleItemsTimerOnElapsed(Object sender, ElapsedEventArgs elapsedEventArgs)
{
    if (CurrentlyProcessingMsgs)
        return;

    CurrentlyProcessingMsgs = true;
    try
    {
        _cancellationToken.ThrowIfCancellationRequested();
        CheckForScheduleItems.Process(_cancellationToken);
    }
    finally
    {
        CurrentlyProcessingMsgs = false;
    }
}

Here is a updated version with catching the exception.
private void CheckForScheduleItemsTimerOnElapsed(Object sender, ElapsedEventArgs elapsedEventArgs)
{
    if (CurrentlyProcessingMsgs)
        return;

    CurrentlyProcessingMsgs = true;
    try
    {
        _cancellationToken.ThrowIfCancellationRequested();
        CheckForScheduleItems.Process(_cancellationToken);
    }
    catch (OperationCanceledException ex)
    {
        //If the task was canceled for some other reason than our token raise the exception.
        if(ex.CancellationToken != _cancellationToken)
            throw;
    }
    finally
    {
        CurrentlyProcessingMsgs = false;
    }
}


Q:

JsonCpp: How to get en empty object in a Json::Value?

I have an external library that receive a Json::Value as a parameter. It will then output a string containing a JSON structure with my passed Json::Value somewhere in that structure.
I'm trying to put an empty object {} in that Json::Value with JsonCpp.
Ultimately I'm trying to parse that empty JSON object from a std::string that contain "{}" and I need that in a Json::Value.
When I declare a Json::Value and do nothing with it and pass it to my library, I get NULL instead of {}...

A:

Sample:
Json::Value root;
Json::Reader reader;
reader.parse("{}", root);
assert(root != Json::nullValue);
std::string someStr = Json::FastWriter().write(root);
assert(someStr == "{}\n");

All of the assertions pass, so the parsed object doesn't have a null value and when you write it back to string you get your empty object "{}" back. Did this not work for you?

A:

It may be helpful for someone:
In current ver. that i'm using - 1.8.2, you can get empty Object like this:
Json::Value root;
root = Json::objectValue;


Q:

Get range of dates for movie rental

I have a movie rental application. The company would enter the movie rent date and movie rent end date. Dates can overlap (as you can have many customers). The data in the db is stored as
RecordID    FromRentDate            ToRentDate
   1      2016-10-06 18:00:00.000   2016-10-06 20:00:00.000
   2      2015-10-06 18:00:00.000   2015-10-06 20:00:00.000
   3      2015-09-29 16:00:00.000   2015-09-30 17:00:00.000
   4      2015-09-11 00:00:00.000   2015-09-11 00:00:00.000
   5      2015-09-09 10:00:00.000   2015-09-09 14:30:00.000

When the user selects a date (using standard .Net controls) the following code is called
        IEnumerable<Event> LiveDates = DataContext.Events.Where(d => d.StartDate.Value >= DateTime.Now);
        IEnumerable<DateTime> AllLiveDates = null;

        if (LiveDates != null && LiveDates.Count() > 0)
        {
            DateTime FromRentDate = LiveDates.Where(f => f.StartDate.HasValue).Min(f => f.StartDate).Value;
            DateTime ToRentDate = LiveDates.Where(t => t.EndDate.HasValue).Max(f => f.EndDate).Value;

            AllLiveDates = Enumerable.Range(0, int.MaxValue)
                         .Select(x => FromRentDate.Date.AddDays(x))
                         .TakeWhile(x => x <= ToRentDate.Date)
                         .Where(x => DataContext.Events.Any(c => x >= c.StartDate && x <= c.EndDate));
        }

        return AllLiveDates.ToList();

What i would like to happen is when a user selects a date, it gets all the dates from the selected date, to the end date including any inclusive dates where the movie is also out so using the above data, if i select todays date I should get all records back and the dates should be listed as:
2015-09-09
2015-09-11
2015-09-29
2015-09-30
2015-10-06 .... etc

Notice how 2015-09-29, 2015-09-30 are included but 2015-09-30 is not a start date. This is because the length of this movie rental is for 2 days (29 and 30 September).
The problem i am experiencing with the above code is that it only returns 1 date. Debugging it it seems to go into AllLiveDates code and something is removing the other dates but not sure what?

A:

The issue appears to be that you are comparing a date value with a date and time.
Take for example the date 2015-09-09.  When you compare that to the DateTime values in your table you should get zero matches, because the DateTime value 2015-09-09 00:00:00.0000 does not lie between the start and end DateTime values of any of your data points.
You will need to strip the time portions of your data points to get the comparison to work the way you want.  Fortunately LINQ to SQL supports the .Date property of DateTime values, so this should work:
Try this:
AllLiveDates = Enumerable.Range(0, int.MaxValue)
    .Select(x => FromRentDate.Date.AddDays(x))
    .TakeWhile(x => x <= ToRentDate.Date)
    .Where(x => DataContext.Events.Any(c => x >= c.StartDate.Value.Date && x <= c.EndDate.Value.Date));

Just don't look at the generated SQL... it's not pretty.


Q:

Should we use an outside CMS?

I work at a web design/development shop.  Everything we do is centered around the Joomla! CMS.  I'm a bit worried-if anything goes wrong with Joomla (major security flaw revealed, Joomla folds and ceases development) we're sunk.
I'm meeting with the CEO to plan the next few steps for our company.  Should I recommend that we create our own in-house CMS or am I just being paranoid about a single point of failure?

A:

I wouldn't create an in-house CMS unless your company has plenty of time and money to burn (as tsOverflow already said in his answer - creating a CMS is a huge task).
Plus, Joomla is open source, so it's very unlikely that it will cease development anytime soon.
I'd be worried if my whole company was centered around a closed source commercial product, because if the company that makes it closes or just decides to drop the product, then I would have a problem.
Even if a big company like Microsoft won't close tomorrow - of course they can decide to drop a product anytime, especially if it's not one of their flagship products like Windows (think VB 6, FoxPro...).
But any community-driven open source project with a large user base (like Joomla) won't likely die.
Even if the whole core development team would stop working on Joomla tomorrow, there are so many people who depend on it that some of them would have formed a new core development team (or forked the project and continued with a new name) after a few days.
Things like this happen in the OSS world all the time - Joomla itself was "created" that way, too.

A:

I think you are just being too paranoid. Creating your own CMS is not like creating a Hello World program - it will require a significant effort to create one as well as maintaining, adding new features, etc.
Your fear can also be put in the context of say, jQuery - our website is heavily reliant on jQuery - what if jQuery dies? Should we just write our own extensive js library? Likewise to any programming language. Likewise to any tool that you use. What if Microsoft fails, should we write our own Outlook to make sure our email communication will not cease to exist?


Q:

Converting C# app to Android - How to extend List<>

I'm converting an app someone else wrote to Android.
One of the classes is declared like so:
public class PowerList : List<PowerEvent>

How would I do this in Java for Android? If I do this:
public class PowerList extends List<PowerEvent>

I get errors -
"The type List<PowerEvent> cannot be the superclass of PowerList; a superclass must be a class"

A:

List is an interface in Java. You could use ArrayList<T> which is an implemented class of List

A:

List is an interface rather than an extendable class. You could try extending ArrayList instead.


Q:

How to display the value of a cookie in a .html file

I have this jquery: https://github.com/carhartl/jquery-cookie (jquery.cookie.js)
And this is my cookie:
$(document).ready(function(){

    //hide all divs just for the purpose of this example,
    //you should have the divs hidden with your css

    //$('.picture.1').hide();
    //check if the cookie is already setted
    if ($.cookie("currentDiv")===undefined){
            $.cookie("currentDiv",1);
    } else{ //else..well
            //get and increment value, let's suppose we have just 8 divs

            var numValue = parseInt($.cookie("currentDiv"));
            numValue = numValue + 1;
            if (numValue>8){
            //restart to 1
                $.cookie("currentDiv",1);
            }
            else{ //no issues, assign the incremented value
                $.cookie("currentDiv",numValue.toString());
            }

            //show the div
            $('.picture.'+$.cookie("currentDiv")).show(0);
    }
});

The cookie called currentDiv has a number from 1 to 8 and changes every reload and reset when the value is higher as 8
How can I display the cookie (called currentDiv) with his current value?
Like:
The installed cookies are:
   currentDiv with the value (for example 5)

A:

you can do this to list all the pages cookies:

jsfiddle:http://jsfiddle.net/5p34S/


Q:

Capacitors with same voltage, same capacitance, same temp, different diameter?

I recently had an old LCD monitor power supply go bad and figured I would try replacing the caps, all four of these were bulged and or leaking. They are all rated to 105 degrees C, all 1000uF and 25V yet two of them are much higher diameter. In my experience with a physically larger capacitor, you either get more voltage (more plate separation?) or more capacitance (more plates?), why are these caps different diameter?

Side question, the board had more than enough space for the larger caps everywhere, why not use the large (or small) caps everywhere for higher quantity discounts.

A:

The answer lies in the datasheet and the designer requirements for cost, space, reliability, cost and temperature rating.  There are many choices. (Did I say cost;)
http://www.capxongroup.com/prodsearch.aspx?lc=1&siteid=&ver=&usid=&mnuid=2082&modid=16&mode=
The Part Number defines;   e.g. KF102M025I200A

KF Family construction of foil film and dielectric, there are many others
xxe value 102 for C in uF with exponents 10 00 uf
M = 20 % tolerance on C
xxx voltage rating
A letter code for Case Dia & radial lead space
xxx height xx.x mm

The height and Voltage reduce ESR while the diameter affects everything.
The parameters for selection of these low ESR caps are;

C, Vdc, Size, max temp range, xxxx Hrs Endurance of accelerated MTBF at extreme temp & RMS ripple current
the electrical variables for these choices are % DF at 120Hz, Ripple current @ 100kHz,  @ 10kHz, ESR

I don't know the formula, but the diameter is determined by foil area, thickness, turns, ESR,and temp rise due to ripple current rating at max temp for xxxx hours due to thermal conductance and  temp rise above max ambient rating and Arrhenius effects on Endurance.

A:

Either they had different ESR ratings, as @hacktastical suggests, or the bigger ones are just an older design and/or the board manufacturer buys whatever is cheaper at the moment, then throws them into one bin.  Cap manufacturers are getting better at making smaller caps, they're getting better at reducing manufacturing variations so that they can consistently hit ratings with not-quite-as-good caps, and some of them just plain lie.


Q:

org.gradle.tooling.BuildException: java.io.IOException: Failed to generate v1 signature

From time to time my project fails to RUN at this very moment (it rebuilds successfully but can't run):
Unfortunately i am not skilled in gradle stuff yet, please help Q_Q
:app:mergeDebugJniLibFolders    4ms
:app:transformNativeLibsWithMergeJniLibsForDebug    359ms
:app:processDebugJavaRes
:app:transformResourcesWithMergeJavaResForDebug 436ms
:app:validateSigningDebug   1ms
:app:packageDebug   428ms (leads to error):
Execute taskAction  421ms
it says: Caused by: java.lang.IllegalArgumentException: Mandatory Manifest-Version attribute missing
Here's manifest file contents:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.c7j.wna">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <application
        android:name="net.c7j.wna.MyApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <uses-library android:name="com.google.android.maps" />

        <service android:name="net.c7j.wna.presentation.service.ForegroundService"/>
        <receiver android:name="net.c7j.wna.presentation.service.MyAlarmReceiver">
            <intent-filter>
                <action android:name="com.example.helloandroid.alarms" />
            </intent-filter>
        </receiver>

        <service android:name="net.c7j.wna.presentation.bootservice.AlarmSetService"/>
        <receiver android:name="net.c7j.wna.presentation.bootservice.BootReceiver" android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="@string/google_maps_api_key" />

        <activity
            android:name="net.c7j.wna.presentation.view.ActivityPlay"
            android:windowSoftInputMode="adjustResize"
            android:screenOrientation="portrait"
            android:launchMode="singleTask"
            >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Here is build gradle file:

apply plugin: 'com.android.application'
apply plugin: 'com.jakewharton.butterknife'
apply plugin: 'me.tatarka.retrolambda'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "net.c7j.wna"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"

        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/services/javax.annotation.processing.Processor'
        pickFirst 'META-INF/*'
    } // for butterknife
    lintOptions {
        disable 'ContentDescription'
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

def ver = [:]
ver.butterknife = "8.8.1"
ver.constraint = "1.0.2"
ver.glide = "3.8.0"
ver.okhttp_logging_interceptor = "3.9.0"
ver.picasso = "2.71828"
ver.retrofit2 = "2.3.0"
ver.room = "1.1.0-beta2"
ver.rx_java2 = "2.1.3"
ver.rx_android2 = "2.0.1"
ver.stetho = "1.5.0"
ver.support = "27.1.0"
ver.play_services = "12.0.1";
//

dependencies {
    implementation "com.google.firebase:firebase-core:$ver.play_services"
    implementation "com.google.android.gms:play-services-ads:$ver.play_services"
    implementation "com.google.android.gms:play-services-maps:$ver.play_services"
    implementation "com.android.support:appcompat-v7:$ver.support"
    implementation "com.android.support:recyclerview-v7:$ver.support"
    implementation "com.android.support:design:$ver.support"
    implementation "com.android.support.constraint:constraint-layout:$ver.constraint"
    implementation "com.jakewharton:butterknife:$ver.butterknife"
    annotationProcessor "com.jakewharton:butterknife-compiler:$ver.butterknife"
    implementation "com.squareup.picasso:picasso:$ver.picasso"
    implementation "io.reactivex.rxjava2:rxjava:$ver.rx_java2"
    implementation "io.reactivex.rxjava2:rxandroid:$ver.rx_android2"
    implementation "com.squareup.retrofit2:retrofit:$ver.retrofit2"
    implementation "com.squareup.retrofit2:converter-gson:$ver.retrofit2"
    implementation "com.squareup.retrofit2:adapter-rxjava2:$ver.retrofit2"
    implementation "android.arch.persistence.room:runtime:$ver.room"
    implementation "android.arch.persistence.room:rxjava2:$ver.room"
    annotationProcessor "android.arch.persistence.room:compiler:$ver.room"
    implementation "com.facebook.stetho:stetho:$ver.stetho"
}

//gradle assemble --stacktrace
//Don't move this apply plugin above or project will fail to build
apply plugin: 'com.google.gms.google-services'

Root build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'
        classpath 'com.google.gms:google-services:3.2.0'
        classpath 'me.tatarka:gradle-retrolambda:3.7.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

After running gradle assemble --stacktrace :
Error:FAILURE: Build failed with an exception.

What went wrong:
Task 'gradle' not found in root project 'wna3'.
Try:
Run gradle tasks to get a list of available tasks. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
Exception is:
org.gradle.execution.TaskSelectionException: Task 'gradle' not found in root project 'wna3'.
at org.gradle.execution.TaskSelector.getSelection(TaskSelector.java:116)
at org.gradle.execution.TaskSelector.getSelection(TaskSelector.java:81)
at org.gradle.execution.commandline.CommandLineTaskParser.parseTasks(CommandLineTaskParser.java:42)
at org.gradle.execution.TaskNameResolvingBuildConfigurationAction.configure(TaskNameResolvingBuildConfigurationAction.java:44)
at org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
at org.gradle.execution.DefaultBuildConfigurationActionExecuter.access$000(DefaultBuildConfigurationActionExecuter.java:25)
at org.gradle.execution.DefaultBuildConfigurationActionExecuter$1.proceed(DefaultBuildConfigurationActionExecuter.java:54)
at org.gradle.execution.DefaultTasksBuildExecutionAction.configure(DefaultTasksBuildExecutionAction.java:44)
at org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
at org.gradle.execution.DefaultBuildConfigurationActionExecuter.access$000(DefaultBuildConfigurationActionExecuter.java:25)
at org.gradle.execution.DefaultBuildConfigurationActionExecuter$1.proceed(DefaultBuildConfigurationActionExecuter.java:54)
at org.gradle.execution.ExcludedTaskFilteringBuildConfigurationAction.configure(ExcludedTaskFilteringBuildConfigurationAction.java:47)
at org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
at org.gradle.execution.DefaultBuildConfigurationActionExecuter.select(DefaultBuildConfigurationActionExecuter.java:36)
at org.gradle.initialization.DefaultGradleLauncher$CalculateTaskGraph.run(DefaultGradleLauncher.java:268)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
at org.gradle.initialization.DefaultGradleLauncher.constructTaskGraph(DefaultGradleLauncher.java:175)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:130)
at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:109)
at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:53)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:47)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:57)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:69)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:30)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:45)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Get more help at https://help.gradle.org

BUILD FAILED in 3s
Full stack trace:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:packageDebug'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:60)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:97)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:87)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:626)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:581)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.tooling.BuildException: java.io.IOException: Failed to generate v1 signature
    at com.android.build.gradle.internal.scope.OutputScope.lambda$parallelForEachOutput$10(OutputScope.java:241)
    at java.util.ArrayList.forEach(ArrayList.java:1251)
    at com.android.build.gradle.internal.scope.OutputScope.parallelForEachOutput(OutputScope.java:236)
    at com.android.build.gradle.internal.scope.OutputScope.parallelForEachOutput(OutputScope.java:197)
    at com.android.build.gradle.internal.scope.OutputScope.parallelForEachOutput(OutputScope.java:181)
    at com.android.build.gradle.tasks.PackageAndroidArtifact.doFullTaskAction(PackageAndroidArtifact.java:471)
    at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:46)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
    ... 32 more
Caused by: java.lang.RuntimeException: java.io.IOException: Failed to generate v1 signature
    at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1431)
    at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
    at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Caused by: java.io.IOException: Failed to generate v1 signature
    at com.android.apkzlib.sign.SigningExtension.onOutputZipReadyForUpdate(SigningExtension.java:297)
    at com.android.apkzlib.sign.SigningExtension.access$200(SigningExtension.java:55)
    at com.android.apkzlib.sign.SigningExtension$1.lambda$beforeUpdate$2(SigningExtension.java:175)
    at com.android.apkzlib.zip.ZFile.notify(ZFile.java:2099)
    at com.android.apkzlib.zip.ZFile.update(ZFile.java:871)
    at com.android.apkzlib.zip.ZFile.close(ZFile.java:1161)
    at com.android.apkzlib.zfile.ApkZFileCreator.close(ApkZFileCreator.java:189)
    at com.google.common.io.Closer.close(Closer.java:216)
    at com.android.builder.internal.packaging.IncrementalPackager.close(IncrementalPackager.java:332)
    at com.android.build.gradle.tasks.PackageAndroidArtifact.doTask(PackageAndroidArtifact.java:700)
    at com.android.build.gradle.tasks.PackageAndroidArtifact.splitFullAction(PackageAndroidArtifact.java:522)
    at com.android.build.gradle.internal.scope.OutputScope.lambda$parallelForEachOutput$6(OutputScope.java:186)
    at com.android.build.gradle.internal.scope.OutputScope.lambda$parallelForEachOutput$7(OutputScope.java:203)
    at com.android.build.gradle.internal.scope.OutputScope.lambda$null$8(OutputScope.java:225)
    at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
    ... 4 more
Caused by: java.lang.IllegalArgumentException: Mandatory Manifest-Version attribute missing
    at com.android.apksig.internal.jar.ManifestWriter.writeMainSection(ManifestWriter.java:47)
    at com.android.apksig.internal.apk.v1.V1SchemeSigner.generateManifestFile(V1SchemeSigner.java:363)
    at com.android.apksig.internal.apk.v1.V1SchemeSigner.sign(V1SchemeSigner.java:253)
    at com.android.apksig.DefaultApkSignerEngine.outputJarEntries(DefaultApkSignerEngine.java:372)
    at com.android.apkzlib.sign.SigningExtension.onOutputZipReadyForUpdate(SigningExtension.java:295)
    ... 18 more

A:

packagingOptions {
        exclude 'META-INF/services/javax.annotation.processing.Processor'
        pickFirst 'META-INF/*'
    } // for butterknife

This lines was the reason. Removed and all's fine.


Q:

How to use onclick in JavaScript

I need to know how to use onclick so that it allows me to reuse the onclick method of a div over and over again and not have to add an infinite amount of them.
  I don't want to have to do this:

But instead do something like this in JavaScript if possible:
div = document.getElementById("allPurposeDiv").onclick...

I'm not exactly sure what would come after onclick is the problem.
Any help is appriciated, Thanks!

A:

onclick is case sensitive. So it is onclick. It expects a callback function to be assigned to it, which will be called.
document.getElementById("div1").onclick = divFunction;

If you are trying to add more events, then you need a event listener like what adeneo has suggested.


Q:

searching and sorting through huge array of latitude and longitude

so I have an array of latitude/longitude (it's fake latitude/longitude as you can see, but just to illustrate the point & the original array size is MUCH larger than this):
<?php
$my_nodes = array(
1=> array(273078.139,353257.444),
2=> array(273122.77,352868.571),
3=> array(272963.687,353782.863),
4=> array(273949.566,353370.127),
5=> array(274006.13,352910.551),
6=> array(273877.095,353829.704),
7=> array(271961.898,353388.245),
8=> array(272839.07,354303.863),
9=> array(273869.141,354417.432),
10=> array(273207.173,351797.405),
11=> array(274817.901,353466.462),
12=> array(274862.533,352958.718),
13=> array(272034.812,351852.642),
14=> array(274128.978,354676.828),
15=> array(271950.85,354370.149),
16=> array(275087.902,353883.617),
17=> array(275545.711,352969.325)));

?>

I want to be able to find the closest node (in this case a node is either 1,2,3, 4,5, ...) for a given latitude X and latitude Y. I know the easiest way to do this is to do a for loop and then do a margin error difference (abs(latitude_X - latitude_X_array) + abs(latitude_Y - latitude_Y_array)) but this will be very inefficient as the size of the array grows.
I was thinking of doing a binary search, however the array needs to be sorted first in a binary search, however it's hard to sort latitude/longitude and in the end we're finding the CLOSEST latitude/longitude in the array for a given lat X, long Y. What approach should I take here?
UPDATE:
Mark has a valid point, this data could be stored in a database. However, how do I get such info from the db if I want the closest one?

A:

Have a read of this article which explains all about finding the closest point using latitude and longitude from records stored in a database, and also gives a lot of help on how to make it efficient.... with PHP code examples.


Q:

IntelliJ Ideas, how to jump to the definition and jump back?

On Mac, how to jump to the definition of a function and jump back to the previous position in IntelliJ Ideas, with keymap preference Mac OS X 10.5 +?

A:

command + b to go to the definition, command + [ to go back.


Q:

Building opencv_contrib on Windows: "CMake Error at cmake/OpenCVDetectPython.cmake:78"

It's my fist time using cmake-gui to make the source code of opencv_contrib. And I get an error below. I've searched for it for many times,but do not get any useful help. Even I don't know what the error means. I'm not sure whether merely copying some lines of the error to Google to search is right. I'm sincerely hoping your help.
The error is :
CMake Error at cmake/OpenCVDetectPython.cmake:78 (if):
  if given arguments:

    "NOT" "optimized" "C:/Program Files/Python35/libs/python35.lib" "debug" "C:/Program Files/Python35/libs/python35_d.lib" "EQUAL" ""

  Unknown arguments specified
Call Stack (most recent call first):
  cmake/OpenCVDetectPython.cmake:219 (find_python)
  CMakeLists.txt:562 (include)

The cmake/OpenCVDetectPython.cmake:73-80 is
 if(_found)
    set(_version_major_minor "${_version_major}.${_version_minor}")
    if(NOT ANDROID AND NOT APPLE_FRAMEWORK)
      ocv_check_environment_variables(${library_env} ${include_dir_env})
      if(NOT ${${library_env}} EQUAL "")
          set(PYTHON_LIBRARY "${${library_env}}")
      endif()

note:

I get the source code (cmake/OpenCVDetectPython.cmake:73-80) from my own file. And the error comes when I try to click the generate button.
My environment is :

CPU                  : Intel Pentium 2020E(64X)
OS                   : Windows10(64X)
opencv_version       : 3.1.0
cmake_version        : 3.7.2(win-64X)
python_version       : 3.5
VisualStudio_version : 2015

Drives me mad.....

A:

It seems that code in cmake/OpenCVDetectPython.cmake is incorrect. (It isn't corrected in the repo too).
Proper way for check variable's non-emptiness:
if(NOT "${VAR}" STREQUAL "")

In your case original lines in cmake/OpenCVDetectPython.cmake:
if(NOT ${${library_env}} EQUAL "")
      set(PYTHON_LIBRARY "${${library_env}}")

should be rewritten as:
if(NOT "${${library_env}}" STREQUAL "")
      set(PYTHON_LIBRARY ${${library_env}})

Explanations are below.

The line, to which error message refers
if(NOT ${${library_env}} EQUAL "")

is a part of function's definition find_python(), and library_env is the parameter of this function.
The function is called twice: one for Python2 and one for Python3. According to error message, it is second call which fails, and it passes PYTHON3_LIBRARY as library_env argument.
So errorneous line can be read as:
if(NOT ${PYTHON3_LIBRARY} EQUAL "")

It tries to check, whether variable is not empty ... but does this wrong:

If the variable is actually empty, CMake completely omits its dereference, so the line would be read as
if(NOT EQUAL "")

which is incorrect call to if() command.
In you case, content of the variable PYTHON3_LIBRARY is a list:
optimized "C:/Program Files/Python35/libs/python35.lib" debug "C:/Program Files/Python35/libs/python35_d.lib"

It is valid value for a library, as long as it linked using target_link_libraries command.
But again, in case of list, the if() line becomes incorrect. That is why you get the error message.
Finally, EQUAL compares integers, but strings are compared with STREQUAL.

Both 1 and 2 problems can be fixed by adding qoutes around variable's dereference.
As for assignment
set(PYTHON_LIBRARY "${${library_env}}")

it incorrectly process list variables, which is exactly you case. List variables should be referenced without quotes around them:
set(A_list ${B_list})


Q:

SelectModelImpl Non-Serializable Prevents Session Replication in Cluster

I'm working on clustering an application using Tapestry 5.3.3. Clustering is accomplished by replicating the HttpSession to all nodes in the cluster. The replication occurs by serializing the HttpSession. When the container attempts to serialize the session a NotSerializableException is thrown because org.apache.tapestry5.internal.SelectModelImpl is not serializable. Tapestry adds this class to the session through the ClusteredSessionImpl class. So it does appear Tapestry wants to be cluster friendly by saving relevant information to the session. Any thoughts on how to get around this exception?

A:

The Tapestry user mailing list provided some good suggestions. Evidently, persisting a SelectModel to the session should be avoided. Here's a couple of responses -

Is it your custom code that is @Persist ing the SelectModel? If so, you could @Persist the underlying Collection instead and build the SelectModel in the UI each time. You should remember that HTTPSession usage should be kept to a minimum, especially in a clustered environment. HTTPSession usage doesn't scale well.
Do you really need to persist a list in the session? Could you instead just store a user id (or other filter parameter) in the session and look up the list each time it is needed from a service? If you find later that the lookup is expensive, you could look at caching at the service level.
You should read this:
http://tapestry.apache.org/performance-and-clustering.html

Don't @Persist or @SessionState SelectModel. That's a bad idea. As Lance said, if you really need to persist it somehow, persist a List that is used to create the SelectModel, not the SelectModel itself.


Q:

Identify this game questions based solely on music

Is it valid to ask for identification of a game just from a piece of music? A certain level of detailed information is clearly required for a good identify question. However, virtually all of us at some point have heard a piece of videogame music out of context somewhere like a Youtube video that we've recognised, but couldn't remember the game source. This'd make a great place to ask for music IDs, but if we can't provide any info other than the track it technically might not meet criteria for a question.
Personally I don't see a problem if the excerpt is long enough for a good ID, but I've never seen an identify-this-music question and wondered what other viewpoints might be on this..

A:

Speaking as someone who has had an interest in game music for over a decade, I could see where this could come in handy.
Heck, maybe we could even pull in new users for this kind of question.  I could even use my own pulpit to advertise/suggest this.

A:

I see absolutely no problem with this, and indeed I've asked a couple of these myself. 1, 2.
Such an ITG would actually be above average in terms of quality, as it would not be based on possibly-erroneous data based on somebody's nebulous recalling (such as this), but on actual and honest-to-goodness facts. We had no problem with accepting an ITG question based on a screenshot, after all.


Q:

Random Querystring to avoid IE caching

It is a well known problem that IE caches too much of html, even when giving a Cache-Control: no-cache or Last-Modified header to everypage.
This behaiviour is really troubling when working with querystrings to get dynamic information, as IE considers it to be the same page (i.e.: http://example.com/?id=10) and serves the cached version.
I've solved it adding either a random number or a timestring to the querystring (as others have done) like this http://example.com/?id=10&t=2009-08-06_13:12:56 that I just ignore serverside.
Is there a better option? Is there another, cleaner way to acomplish this? I'm aware that POST isn't cached, but it is semanticaly correct to use GET here.

A:

Assuming you are using jQuery, instead of using $.get or $.getJson, use the more generic $.ajax and explicitly set the cache value to false. The following is an example:
$.ajax({
        url: "/Controller/Action",
        cache: false,
        type: "GET",
        dataType: "json",
        success: function(data, textStatus) {
                         alert("success");
                 }
    });

A little more code required (not much though) than using .getJson or .get but will solve the problem cleanly without appending random numbers.

A:

You could also use the current Unix Time in milliseconds to avoid the problem of many requests in one second (it is much less likely to have multiple requests in one millisecond)
var url = "http://whatever.com/stuff?key=value&ie=" + (new Date()).getTime();

A:

So, in the end, the only reliable way to do this (thanks to IE6) is using a
random,
or
time bound
querystring.
You could use a
time bound querystring
that only changes every 15 seconds (or any other amount of time), so you'd lower the server hit count, as you'd see locally cached content for those 15 seconds.
If you have
a
standard
compliant
browser, you can get away with only using
ETags.


Q:

Interpretation of dfm_weight(scheme='prop') with groups (quanteda)

I'm looking at the different weighting options using the dfm_weight. If I select scheme = 'prop' and I group textstat_frequency by location, what's the proper interpretation of a word in each group?
Say in New York the term career is 0.6 and and in Boston the word team is 4.0, how can I interpret these numbers?
    corp=corpus(df,text_field = "What are the areas that need the most improvement at our company?") %>%
  dfm(remove_numbers=T,remove_punct=T,remove=c(toRemove,stopwords('english')),ngrams=1:2) %>%
  dfm_weight('prop') %>%
  dfm_replace(pattern=as.character(lemma$first),replacement = as.character(lemma$X1)) %>%
  dfm_remove(pattern = c(paste0("^", stopwords("english"), "_"), paste0("_", stopwords("english"), "$")), valuetype = "regex")
freq_weight <- textstat_frequency(corp, n = 10, groups = c("location"))

ggplot(data = freq_weight, aes(x = nrow(freq_weight):1, y = frequency)) +
  geom_bar(stat='identity')+
  facet_wrap(~ group, scales = "free") +
  coord_flip() +
  scale_x_continuous(breaks = nrow(freq_weight):1,
                     labels = freq_weight$feature) +
  labs(x = NULL, y = "Relative frequency")

A:

The proper interpretation is that this is the sum of the original term proportions within document, but summed by group.  This is not a very natural interpretation, since it sums proportions and you do not know on how many terms the proportion was based (in absolute frequency) before it was summed.
quanteda < 1.4 disallowed this, but following a discussion we enabled it (but let the user beware).
library("quanteda")
#> Package version: 1.4.3
corp <- corpus(c("a b b c c",
                 "a a b",
                 "b b c",
                 "c c c d"),
               docvars = data.frame(grp = c(1, 1, 2, 2)))
dfmat <- dfm(corp) %>%
    dfm_weight(scheme = "prop")
dfmat
#> Document-feature matrix of: 4 documents, 4 features (43.8% sparse).
#> 4 x 4 sparse Matrix of class "dfm"
#>        features
#> docs            a         b         c    d
#>   text1 0.2000000 0.4000000 0.4000000 0
#>   text2 0.6666667 0.3333333 0         0
#>   text3 0         0.6666667 0.3333333 0
#>   text4 0         0         0.7500000 0.25

Now we can compare the textstat_frequency() with and without groups.  (Neither makes too much sense.)
# sum across the corpus
textstat_frequency(dfmat, groups = NULL)
#>   feature frequency rank docfreq group
#> 1       c 1.4833333    1       3   all
#> 2       b 1.4000000    2       3   all
#> 3       a 0.8666667    3       2   all
#> 4       d 0.2500000    4       1   all

# sum across groups
textstat_frequency(dfmat, groups = "grp")
#>   feature frequency rank docfreq group
#> 1       a 0.8666667    1       2     1
#> 2       b 0.7333333    2       2     1
#> 3       c 0.4000000    3       1     1
#> 4       c 1.0833333    1       2     2
#> 5       b 0.6666667    2       1     2
#> 6       d 0.2500000    3       1     2

If what you wanted was the relative term frequencies after grouping, then you can first group the dfm and then weight it, like this:
dfmat2 <- dfm(corp) %>%
    dfm_group(groups = "grp") %>%
    dfm_weight(scheme = "prop")

textstat_frequency(dfmat2, groups = "grp")
#>   feature frequency rank docfreq group
#> 1       a 0.3750000    1       1     1
#> 2       b 0.3750000    1       1     1
#> 3       c 0.2500000    3       1     1
#> 4       c 0.5714286    1       1     2
#> 5       b 0.2857143    2       1     2
#> 6       d 0.1428571    3       1     2

Now, the term frequencies sum to 1.0 within group, making their interpretation more natural because they were computed on grouped counts, not grouped proportions.


Q:

MySQL Join horizontal with vertical table

I have the following structure:
CREATE TABLE person {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL,
    email VARCHAR(30) NOT NULL UNIQUE
}

CREATE TABLE field {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL
}

CREATE TABLE fieldPerson {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    fieldId INT(11) UNSIGNED,
    personId INT(11) UNSIGNED,
    value VARCHAR(30) NOT NULL,
    FOREIGN KEY (fieldId) REFERENCES field(id),
    FOREIGN KEY (personId) REFERENCES person(id)
}

This is well summed up. Basically we have the default fields name and email, and we have the option to create custom fields, such as telephone, address, etc.
We can have n fields. I'm trying to figure out a way to do a SELECT query that returns all fields without making use of subqueries or extra work outside the database (it's ok using joins though).
Example (telephone is a custom field):
TABLE person:

id    name       email
1     Test 1     test1@gmail.com

----

TABLE field:

id    name
1     telephone
2     address

----

TABLE fieldPerson:

id    fieldId    personId    value
1     1          1           +1 555 555 555
2     2          1           First St.

----

RESULTING QUERY

personId   name          email            telephone       Address
1          Test 1        test1@gmail.com  +1 555 555 555  First St.

Is that possible?
Thanks.
EDIT:
If not possible, you may suggest a optimal solution using subqueries, only with SQL though.

A:

So, depending on how much control you have over the query generation, if you can generate the SELECT columns in the same order as the PRIMARY KEY of field, you could try the following. I'm envisioning something where you know there's 2 keys in field, and what they are in advance (from an earlier query?).
SELECT fp.personId,p.name,p.email,fp.value as telephone,fp2.value as Address
    FROM fieldPerson fp INNER JOIN person p ON p.id = fp.personId
                        INNER JOIN field f ON f.id = fp.fieldId
                        INNER JOIN fieldPerson fp2
    WHERE fp.fieldId = 1 and fp2.fieldId = 2;

This gives me the result, given the sample data in the question:
personId | name   | email           | telephone      | Address   |
       1 | Test 1 | test1@gmail.com | +1 555 555 555 | First St. |

This hinges on the notion that you've avoided the sub-query by doing an initial query earlier to know the arbitrary fields defined in the fields table. You didn't specify how dynamic this table is expected to be, so this may not be an unreasonable simplifying assumption to make.
Barring that, you can try something like:
SELECT fp.personId,p.name,p.email,fp.value as telephone,fp2.value as Address
    FROM fieldPerson fp INNER JOIN person p ON p.id = fp.personId
                        INNER JOIN field f ON f.id = fp.fieldId
                        INNER JOIN fieldPerson fp2
    WHERE fp.fieldId != fp2.fieldId LIMIT 1,1;

This gives me the same output without having to know the field id numbers, but I do need to know the names of the fields to generate the column names. The LIMIT is there to remove one of the JOIN products, and has a distinctly unholy feeling to it, I agree. I feel like there's not too much advantage to approach 2, since you have to know the column names anyways.
I would agree with @Mojtaba, however, that if you can't live with a pre-query to know the dynamic field names and ids, then I believe you're going to have to put sub-SELECT statements in there to pull those at query time.

A:

SELECT p.*
     , group_concat(CASE f.name WHEN 'telephone' THEN fp.value END) telephone
     , group_concat(CASE f.name WHEN 'address'   THEN fp.value END) address
  FROM person p
  JOIN field f
    LEFT JOIN fieldPerson fp
      ON    fp.personId = p.id
        AND fp.fieldId = f.id
  GROUP BY p.id


Q:

How to overload a parentheses operator for both get and set?

I am trying to overload a getter and setter using parentheses operator. When I try to use
double& my_vector::operator()(size_t index){
    return array[index]
}

This single operator overloading works for both the case:
eg: my_vector(1) = 4.01; & double x = my_vector(1);
But now I want to make getter as const and setter and non-const since I will be using const getter in another const function. I do
getter as  double& my_vector::operator()(size_t index) const;
setter as double& my_vector::operator()(size_t index);
I get
Error: functions that differ only in their return type cannot be overloaded.
I think I know what the error is talking about but I am not sure how to rectify it.

A:

Here's a complete example which demonstrates how it works; (You can run this here http://ideone.com/kO0Rf1 )
#include <iostream>
using namespace std;

class my_vector {
public:
    double data[6] = {1,2,3,4,5,6};
    double & operator()(size_t i) {
        std::cout<<"Calling non-const ()"<<std::endl;
        return data[i];
    }
    double operator()(size_t i) const {
        std::cout<<"Calling const ()"<<std::endl;
        return data[i];
    }
};

void withConst(const my_vector &v) {
    double vv = v(0);
    std::cout<<"v(0) = "<<vv<<std::endl;
    // v(0) = 4.0; // Does not compile
}

void withNonConst(my_vector &v) {
    v(0) = 4.0;
    double vv = v(0);
    std::cout<<"v(0) = "<<vv<<std::endl;
}

int main() {
    my_vector vec;
    withConst(vec);
    withNonConst(vec);
    return 0;
}


Q:

Spring data JPA findBy returns null

I am using a spring data JPA and getting a weird issue.
Method findBY.. and findOne() returns null value whereas findAll() returns all the record present in the database.
Entity class:
@Entity
public class Person {
private String name;
@Id
private String nino;
private Integer employerId;
private Integer employmentLevel;

Repository class
public interface PersonRepository extends  JpaRepository<Person, String>{

    Person findByNino(String nino);
}

Service class
@Transactional(readOnly = true)
    private Person fetchPerson(String nino)
    {
        return personRepository.findByNino(nino);
    }

Could anyone please help me?

A:

The issue which I figured out was :
I was hitting the service http://localhost:8080/getPerson?nino= "AB"&id=1 from the postman.
Double quotes were the issue. It should be http://localhost:8080/getPerson?nino= AB&id=1