text:
Q: Feynman amplitude $\mathcal{M}$ for non-physical processes in QED I know $e^-e^+\rightarrow\gamma$ is an example of a non physical process in QED because it violates four-momentum conservation. For that reason, the Feynman amplitude $\mathcal{M}$ is never written or calculated explicitly in the bibliography, so I don't really know if it is assumed that it is zero or if it doesn't make sense calculating $\mathcal{M}$ for such a process.
I've tried to perform such a calculation for $e^-e^+\rightarrow\gamma$ following  the Feynman rules and got $$i \mathcal{M} = (-ie)u^s(p)\gamma^{\mu} \bar{v}^{s'}(p')\epsilon_{\mu}^{\lambda^*}(k)$$ where $u^s(p)$ represents the incoming electron, $\bar{v}^{s'}(p')$ the incoming positron and $\epsilon_{\mu}^{\lambda^*}(k)$ the outgoing photon.
I doesn't look like $\mathcal{M} = 0$ here. Should it not vanish? It seems to me that it should be zero for a process that can never occur.
I've used an example to clarify my question, but I would also like to know if the amplitudes for all other non-physical processes should be zero or not and why.

A: Your initial approach is correct for finding the QED current of the vertex. However, the amplitude of a Feynman diagram (and therefore a particular interaction) is found by integrating over the momenta of the virtual bosons in the diagram, which couple to currents to make amplitudes. Neglecting the fact that there aren't any virtual bosons in the non-physical process you describe, as Vladimir mentioned, you would also need to include a term $2\pi\delta(p+p'-k)$ in the integral which maintains four-momentum conservation. Since four-momentum isn't conserved in the process described, this delta function would vanish.


text:
Q: Logic implication with first degree equation and a sentence My sister got a great math test back but had some errors with the logic equivalences.
For example:
$x - 17 = 2 \iff x = 2 + 17 \iff x = 19$
Now, the teacher took some points for forgetting the last equivalence. That's correct.
But another question: Search the number which subtracted with $23$, equals $-8$
She wrote:
$\iff$ $x - 23 = -8 \iff x = -8 + 23 \iff x = 15$
He did the same thing to take some points for forgetting the last equivalence. But he also took points for adding the first equivalence. In my eyes, the equation she wrote and the questions, implicate each other so that quivalence is not wrong.
What are you thoughts on this one?

A: Note that if this is what your sister wrote for the second answer:
$$\iff x - 23 = -8 \iff x = -8 + 23 \iff x = 15$$
...then indeed, the instructor look off points for having used the first "$\iff$" symbol at the start of the string of equivalences, since it is meaningless, and at worse states that $$\text{nothing} \iff x - 23 = -8$$
An equation is true or false, depending on $x$ in this case.  The left hand side ("nothing") is neither true nor false. The right hand side is either true or false, depending on $x$. The two cannot be equivalent.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ruby omniauth facebook stopped working all of a sudden All of a sudden, it got impossible for anyone to login into my website using facebook.
I really don't get it as I didn't change anything on my ends.
I suspected my token would have expired or something like that, but apparently facebook app token don't expire.
Any idea ? Here is what I get back from the omniauth call :
    Started GET "/users/auth/facebook/callback?code=AQDE-eQkHGXsonQb9cNONr0dhCH6sDRniGh5bLBT3b52rtzOrPWkNgQWeORECn_aaX9vhIcrQP-4Psa91vPblNdXghzPYaauzp1ljzXBUzFsdD3nbwPzjRi7HbagODS6hLE0rHY3saPxf5JGV4t4it87u3B-FeQ4R4JZFMwGubqgxzRmbimdRiotcBzfloqVGU9c_m4cK48hihhNraCNUvC-eL-mD1wkJ-s1zxRooiBQdoyZbWoniVd53MJJUf17nXTH6CSXq1ba57t_jlTAPZNLIkHrXVWD6UA0YJcakZAM&state=5fad05a6b5c1aa578feaf1bfbc60ae6ab722883e62fddb71" for 127.0.0.1 at 2017-04-09 11:22:49 +0200
(facebook) Callback phase initiated.
(facebook) Authentication failure! invalid_credentials: OAuth2::Error, :
{"access_token":"EAAPhpHRqK0cBAHsTlcFbnkEUlk6cREnOUGN3VebSUfMZAYccJ6UTeMZBfFCXRcf2RJSsQa0c2ZAsIcM595n8TG5wHWtIJPvLjSpmh36Th4WgTThZAvO8eFaHwitKEZD","token_type":"bearer","expires_in":5182389}

  Processing by Users::OmniauthCallbacksController#failure as HTML
  Parameters: {"code"=>"AQDE-eQkHGXsonQb9cNONr0dhCH6sDReORECn_aaX9vhIcrQP-4Psa91vPblNdXghzPYaauzp1ljzXBUzFsdDlQhhrpL5qSqp9333nbwPzjRi7HbagODS6hLE0rHY3saPxf5JGV4t4it87u3B-FeQ4R4JZFMwGubqgxloqkJs1zxRooiBQdoyZbWoniVd53MJJUf17nXTH6CSXq1ba57t_jlTAPZNLIkHrXVWD6UA0YJcakZAM", "state"=>"5fad05a6b5c1aa52883e62fddb71"}
:
{"access_token":"EAAPhpHRqK0cBUTeMZBfFCXRcf2RJSsQa0c2ZAsIcM59uMakbUTq42b79lq7E5n8TG5wHWtIJPvLjSpmh36Th4WgTThZAvfmpB04q00uP","token_type":"bearer","expires_in":5182389}

Thanks


text:
Q: PayPal: After Check whether subscriber is paid for subscription I'm creating website using reactjs for frontend and for backend I'm using c# asp .net mvc. I have already integrated paypal subscription in whichevery month fixed amount deducted form his account(which I have already done) by following this link https://medium.com/analytics-vidhya/paypal-subscription-in-react-1121c39b26be. and here is my code.
window.paypal.Buttons({
            style: {
                shape: 'rect',
                color: 'gold',
                layout: 'vertical',
                label: 'subscribe'
            },
            createSubscription: function(data, actions) {
              return actions.subscription.create({
                'plan_id': 'my-plan-id'
              });
            },
            onApprove: function(data, actions) {
              alert(data.subscriptionID);
              console.log(data)
            },
            onError: (err) => {
                console.log(err)
            }
        }).render(paypal.current)

but my requirement is when user login first time user must provide his paypal account details and after providing paypal account info check user has sufficient amount in his account proceed to dashboard. But my problem is how to handle if user has no balance in his account or unpaid and in this case after login user redirected to specific page not dashboard.
In short: how to check user is paid or unpaid if paid proceed to dashboard else redirect to specific page.

A:
how to check user is paid or unpaid if paid proceed to dashboard else redirect to specific page.

The answer to this is to consult your database, which should have this information stored (whether a payment has been made, or whether the subscription is current) and allow you to determine what to do based on the information you have.
So your real question must be how to receive notifications from PayPal that a subscription payment has been made. For that, I will refer you to the answer in here: How do you know if a user has paid for a subscription
As for how to match subscription payments to users -- when a subscription is created, you can store its ID associated with your user, which is easiest to do if you activate the subscription from the server as discussed above.  You can also pass a custom_id field during subscription creation, which can contain your own user ID for reconciliation.


text:
Q: Eclipse Luna ant editor gives error when I add includeAntRuntime attribute I'm running eclipse luna (Eclipse IDE for Java Developers, Version: Luna Service Release 1a (4.4.1), Build id: 20150109-0600).
When the compile target runs, it gives me a warning about missing the includeAntRuntime attribute.  So I added the attribute setting it to false as the ant documentation suggests.  The editor underlines the whole target element in red and says the includeAntRuntime attribute is unexpected.
<target name="compile" depends="init" includeAntRuntime="false" >
    <javac srcdir="${src}" destdir="${build.classes}" classpathref="compile.classpath"/>
</target>

I figured out that eclipse is using ant 1.9.2 whereas I'm using ant 1.9.4.  I changed the Ant home to point to 1.9.4 using Window>Preferences>Ant>Runtime dialog.
I restarted eclipse and its made no difference.  I'm still getting the same warning.  How can I get past this error?

A: includeAntRuntime is an attribute of the javac task not target:
<target name="compile" depends="init" >
    <javac includeAntRuntime="false" srcdir="${src}" destdir="${build.classes}" classpathref="compile.classpath"/>
</target>


text:
Q: Git is not showing all branches on local I forked a repo from Github. On doing git remote -v it displays:
origin  https://github.com/myusername/moodle.git (fetch)
origin  https://github.com/myusername/moodle.git (push)
upstream    https://github.com/moodle/moodle.git (fetch)
upstream    https://github.com/moodle/moodle.git (push)

The moodle.git has about 10 branches, but the repo shows only 2 of them. On doing git branch -a (show all branches) I get:
  MOODLE_24_STABLE// just these two on local..how?
* master//
  origin/MOODLE_13_STABLE
  origin/MOODLE_14_STABLE
  origin/MOODLE_15_STABLE
  origin/MOODLE_16_STABLE
  origin/MOODLE_17_STABLE
  origin/MOODLE_18_STABLE
  origin/MOODLE_19_STABLE
  origin/MOODLE_20_STABLE
  origin/MOODLE_21_STABLE
  origin/MOODLE_22_STABLE
  origin/MOODLE_23_STABLE
  origin/MOODLE_24_STABLE
  origin/master
  upstream/MOODLE_13_STABLE
  upstream/MOODLE_14_STABLE
  upstream/MOODLE_15_STABLE
  upstream/MOODLE_16_STABLE
  upstream/MOODLE_17_STABLE
  upstream/MOODLE_18_STABLE
  upstream/MOODLE_19_STABLE
  upstream/MOODLE_20_STABLE
  upstream/MOODLE_21_STABLE
  upstream/MOODLE_22_STABLE
  upstream/MOODLE_23_STABLE
  upstream/MOODLE_24_STABLE
  upstream/master

How do I resolve my problem without any loss of data or any irregularities?

A: Some times , if you havn't pulled the latest code, you wont be allowed to checkout the newly created branch.Because your changes are not in synch.
So first
-pull the latest
-checkout from newly created branch

A: Cloning a repo won't duplicate all the remote branches on the local repo: for a large remote repo with a lot of branches, that would pollute your local namespace with tons of branches.
I have a one-liner command in order to create local branches tracking all the remote branches of a remote repo, but this is usually not needed.
You only create a local branch tracking a remote one when needed.
git checkout -b aBranch --track origin/aBranch

# or, shorter:
$ git checkout --track origin/aBranch
Branch aBranch set up to track remote branch refs/remotes/origin/aBranch.
Switched to a new branch "aBranch"

# even shorter at the end of this answer.

Adding a --track allows for setting up the configuration to mark the start-point branch as "upstream" from the new branch.
This configuration will tell git to show the relationship between the two branches in git status and git branch -v.
Furthermore, it directs git pull without arguments to pull from the upstream when the new branch is checked out.

kostix mentions that --track is implied when forking a branch off a remote branch (unless branch.autosetupmerge is set to false)
This could be enough
git checkout aBranch

The exact explanation from git checkout man page is:

If <branch> is not found but there does exist a tracking branch in exactly one remote (call it <remote>) with a matching name, treat as equivalent to:

$ git checkout -b <branch> --track <remote>/<branch


text:
Q: Android (Xamarin): BottomNavigationView not appearing in the right place I am trying to implement a bottom navigation bar for my Android application (API 30), using the BottomNavigationView class from the Android.Support.Design.Widget namespace (Xamarin.Android.Support.Design library, version 28.0.0.3).
I am following the explanation from here: https://devblogs.microsoft.com/xamarin/exploring-androids-bottom-navigation-view/
This is what the layout file looks like:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schema.android.com/apk/res/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
    <FrameLayout android:id="@+id/content"
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"
                 android:layout_above="@+id/navigator"/>
    <android.support.design.widget.BottomNavigationView android:id="@+id/navigator"
                                                        android:layout_width="match_parent"
                                                        android:layout_height="64dp"
                                                        android:layout_gravity="bottom"
                                                        android:background="@android:color/white"
                                                        app:elevation="16dp"
                                                        app:menu="@menu/navigator"/>
</RelativeLayout>

And this is the menu file:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/home"
          android:icon="@drawable/home"
          android:title="Home"
          android:enabled="true"
          app:showAsAction="ifRoom"/>
    <item android:id="@+id/library"
          android:icon="@drawable/library"
          android:title="Library"
          android:enabled="true"
          app:showAsAction="ifRoom"/>
    <item android:id="@+id/search"
          android:icon="@drawable/search"
          android:title="Search"
          android:enabled="true"
          app:showAsAction="ifRoom"/>
</menu>

The problem is that while it's visible, it appears at the top of the screen rather than at the bottom, which is the exact opposite of what a bottom navigation bar is supposed to do.
Furthermore, it doesn't show the icons. It just appears as a blank white bar at the top of the page.
What am I doing wrong and how do I fix it?

A: <com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="0dp"
    android:layout_marginStart="0dp"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation"
    android:layout_gravity="bottom"
    android:visibility="visible" />


text:
Q: If a vampire would stand inside a house when it was built would he be able to leave? Take a vampire from a series that can't enter a house without permission, for example, The Vampire Diaries and True Blood, what would happen if it was standing inside the house while it was being built?

A: Since the restriction is on entering a house, not leaving it, there's no reason he wouldn't be able to leave.


text:
Q: Install Github Python Package in R Reticulate I'm trying to install the magpie_python package from github in an R environment, but I am running into numerous errors using traditional reticulate methods. None of them are working. I've not seen anything about installing github packages with reticulate yet so any help would be awesome.
Whenever I run the line
py_run_string("import magpie_python.attributes.generators.composition.ElementalPropertyAttributeGenerator")kd

I get a ValueError: attempted relative import beyond top-level package
Any help in figuring this out would be great


text:
Q: Creating snapshot reports when subreports require parameters? My situation is this - I'm using SSRS to create a "cascading" report set. The top-level report pulls all of the data from a table that capture our deployment/release activity. This data includes the property that executed a release, the organization to which that property belongs, the scheduled and actual start and end times of the release (and its constituent deployments), etc., etc., etc., and in the report I aggregate the data by time windows (Fiscal Year, then Quarter, then Month). So, at the top level, the user sees a report that shows how many deployments and releases we executed, how long they were expected to take, and how long they actually took, over the last twelve months, grouped, again, by Fiscal Year, then Quarter, than Month.
Now, the next level of detail the user wants to see is for a given month. When he or she clicks on the link to run that particular sub-report, they now get the same information (number of deployment, number of releases, scheduled and actual durations, etc.) grouped by organization, for that particular month.
Here's my dilemma - the initial report takes a LONG time to render. I would like to create snapshot report to reduce this render time, but my sub-report uses the Month from the top-level report as a parameter. In other words, when I click on the link to the sub-report, the Action setting in SSRS says to use the Month that I clicked on as a parameter to generate the sub-report, and the query in the sub-report filters off of that parameter with the following query condition:
AND FiscalQuarter IN (@Quarter)
So, the reporting works fine, but I am wondering - is there some way that I can get ALL of the data, for ALL quarters, into the sub-report in a snapshot report, and then just generate that snapshot but filtered out for the quarter value that I pass from the top-level report as a parameter?

A: yes you can, by creating a snapshot for sub report for all values.
and the parameter defined on the subreport should be a dataset filter not a query parameter .
Now when you pass parameter from main report to subreport , it will filter it accordingly on the sub report snapshot without having to execute the costly sql

A: Alas, reporting services does not provide what you need. Caching reports will create a cached version of the report per distinct combination of parameter values, and a similar situation holds for cached datasets.
You have roughly two options left it seems:

*

*Use a cached dataset, have the subreport use the cached dataset but only use the parameter to filter the data once it's retrieved (e.g. in a tablix)

*Resort to a more database-oriented caching-like or performance enhancing strategy such as for example indexed views for your queries


text:
Q: Google App Script - How to get a usage report of Group Mail I am trying to generate a usage report from my domain on all my group emails like num_emails_received in the last 3 months. But it seems Google only support to generate a usage report all my users with AdminReports.UserUsageReport.
Please help me with some ideal. Thanks.

A: You can pass gmail:num_emails_sent as a parameter inside the Optional query parameters of your UserUsageReport: get request.
The syntax for this request in Apps Script is
AdminReports.UserUsageReport.get(userKey, date, {parameters:'gmail:num_emails_sent'})

Please refer to the Admin SDK Reports Service for further documentation about implementation of the REPORTS API in Apps Script including sample code.


text:
Q: Solidity save complex object in the contract I have this usecase where I need to persist the following sample data in my contract.
{
    Linkage : {"4" : "1", "77" : "59", "5" : "64", "4" : "464", "455" : "364", "25" : "364", "25" : "164", "55" : "8684", "85" : "864"},
    UserId : "Some Id",
}

The dictionary is obviously expandable (root And Linkage).
I want to send the data and retreive it as an object (c# and Java style). So when I communicate from WEB3 I can pass json.
Is that possible?
This is where I got stuck...
pragma solidity ^0.4.13;

contract Test{
  struct UserProfile{
    string UserId;
  }

  UserProfile public Profile;

  function setProfile(UserProfile newProfile) public {
    Profile  = newProfile;
  }
}

A: You can't pass objects when initiating a transaction (yet). You can only pass in/return a struct through internal function calls (see Solidity FAQ).
You'll have to pass in your data using primitive types and add them to your internal struct:
pragma solidity ^0.4.13;

contract Test {
  struct UserProfile {
    string userId;
    mapping(uint256 => uint256) linkage;
  }

  UserProfile public profile;

  function addLinkage(uint256 id, uint256 value) public {
    profile.linkage[id] = value;
  }
}

Note, if you want to pass in your linkages in bulk, you can use addLinkage(uint256[] ids, uint256[] values).

A: You can serialize your object into a string, solidity has no object primitive and probably never will because of the nature of the Ethereum vm.


text:
Q: How do I configure vsftpd to use a GoDaddy SSL certificate bundle? I have an Ubuntu 16.04.3 AWS EC2 instance running vsftpd 3.0.3.  Plain FTP works just fine, but I need to enable TLS so my clients can use sftp to upload files.
I have researched this for hours, but everything I find shows how to configure a self-generated certificate.  I want to use my wildcard SSL certificate that was purchased from GoDaddy. (the same one I'm using on my AWS Elastic Load Balancer).
I have the .key file, and the two .crt files that I downloaded from GoDaddy.  I can't figure out how to put those three files in a format that vsftpd can understand.  I get no errors from vsftpd, but when I connect using FileZilla I get this response:
Status: Connecting to <my ftp subdomain>.<my domain>.com...
Status: Skipping non-existing key file "C:\Users\<some local file1>.ppk"
Status: Skipping non-existing key file "C:\Users\<some local file2>.ppk"
Status: Skipping non-existing key file "C:\Users\<dome local file3>.ppk"
Response:   fzSftp started, protocol_version=8
Command:    open "<username>@<my ftp subdomain>.<my domain>.com" 22
Error:  Disconnected: No supported authentication methods available (server sent: publickey)
Error:  Could not connect to server

I have already confirmed that port 22 is open in the firewall.
BTW, my ultimate goal is for clients to connect without getting any sort of "do you trust this certificate" message during their first connection.  Please tell me if I'm on the wrong track.

A: For port 22, you're typically using SFTP and not FTPS. The difference is FTPS uses an SSL public/private key pair to secure the FTP transactions and still requires you to authenticate via username and password. With SFTP you're using a public/private keypair you generate yourself and is tied to a specific user to use for authentication. The public key is stored in the vsftp server for the user while the client you're connecting from presents the server with the private key. I think your issue is that the two are being confused as the error logs are looking for ppk files to present to the server for authenticating the user.
To clarify for you, port 22 is already open through the EC2 instance so you actually don't need vsftp, but instead just use the private key provided by AWS when you created the instance and you should be good. You don't want to use vsftp to use port 22 as then you will have no way to ssh into your instance without changing the port SSH runs on. the OpenSSH server that's there by default already gives you sftp functionality. If you specifically want to use FTPS then you'll need to connect to the port you defined in your vsftp configuration and open up any necessary firewall ports in the security group the EC2 instance uses.

A: OK, it took a while, but I finally got all of the pieces put together and it works now!

*

*I had to concat my certificate, key, and intermediate certs into a single .pem file as described here: http://www.terminalinflection.com/solaris/vsftpd-configuration/

*Then I had to setup the sftp subsystem of sshd as described in this EXCELLENT article: https://www.thegeekstuff.com/2012/03/chroot-sftp-setup/

*Add the following to my vsftpd.conf file:
force_local_logins_ssl=NO
force_local_data_ssl=NO

Now I can use plain ftp for my old users, while requiring sftp for my new users.


text:
Q: How to select upcoming dates from mysql from following date format? How to select upcoming date?
datetime
01/24/2020 6:15 PM,
01/39/1994 12:04 AM,
01/29/1994 12:04 AM,
01/30/2020 6:15 PM,
07/19/1994 12:04 AM

A: Are you looking to turn these strings to dates? You can use str_to_date() for this:
str_to_date(mycol, '%m/%d/%Y %k:%i %p')

Once this is done, you can filter on future dates like so:
select *
from mytable
where str_to_date(mycol, '%m/%d/%Y %k:%i %p') > current_timestamp

Note that this is an unefficient method: the database needs to convert each and every string to a date before being able to compare it (an index is of no use here).
As a priority, you should consider fixing your data model to store dates in the relevant datatype (MySQL has datetime or timestamp).


text:
Q: Could "Give in" mean "Hand over"? Give in = hand in but does give in = hand over? and which of them are equal? and what's the differences?

A: "give in" does not = "hand in"
nor does "give in" = "hand over"

*

*HAND IN is what students would do with a completed assignment. Suppose the teacher "handed out" question sheets to all the students. Then when they had filled in answers, they would "hand in" the completed sheets to the teacher. She first spread them "out" (to students), then gathered them "in" (to herself).

*HAND OVER is what you would do if a robber confronted you:  "Hand over all your money or I'll shoot!"  However, it need not be violent; you could choose to "hand over" a task to someone. So it means giving something that you own, to someone else, willingly or unwillingly.

*if you already started a task, you might say you were HANDING {IT} OFF to someone—like a relay runner passing a baton to the next runner. (This act is called a "handoff") .

*GIVE IN is an idiom for letting the other person have his way.

*If you have been fighting (physically or verbally), then quit fighting and surrender, you are GIVING UP. (This is intransitive as well as transitive; you can "give up the fight" or just "give up".) However, you can also voluntarily give something up, such as giving up your place in line, or giving up your seat on a bus, to an elderly or handicapped person. But if you "give up the ghost" it means you died!
So, if someone persuades you to give them something of yours, you might "give in" and "hand it over".  If he tries to wrestle you to take it away, and he's standing over you with his boot on your neck, you might "give up" and "hand it over".
If you are an escaped murderer, and the police surround your house, they might shout "GIVE UP and come out with your HANDS UP!"
And then there are "hands off", "hands down", "hand-me-downs" "off-hand", and more. But those are other questions; I've gone on long enogh here.


text:
Q: R: combine lists of interest I have a list like df_all (see below).
A = matrix( ceiling(10*runif(8)), nrow=4)
colnames(A) = c("country", "year_var")
dfa = data.frame(A)

df1 = dfa[1,]
df2 = dfa[2,]
df3 = dfa[3,]
df4 = dfa[4,]
df_all = list(df1, df2, df3, df4)
df_all

Now I want to combine the list of interest by using variable a.
a <- "2,3,4"
b <- strsplit(a, ",")[[1]]

To combine this lists, I use the folling loop:
for (i in 1:length(b)){
c<-b[i]
aa <- df_all[c:c]
print(aa)
}

Now my question is, How can I combine this result and save this as as variable?
Thanks!

A: Would this work for you:
basnum<-as.integer(b)
do.call(rbind, df_all[basnum])

Through df_all[basnum], a list with only the relevant data.frames is created.
do.call takes a function and a list as parameters (and some more but not relevant right now). The items of the list are then passed on as parameters to the function.
So in this case, the above is the equivalent to calling:
rbind(df_all[[2]], df_all[[3]], df_all[[4]])

And this produces one data.frame holding all the rows of interest.


text:
Q: Get Navigation Controller from Tabbar Controller I am trying to achieve to two things right now:
1) Have a tabbar controller inside a navigation controller
2) Depending on the selected tab, some Navigation buttons change, and I want to push some views into the navigation controller, while staying inside the currently selected tab.
Right now, I push the Navigation Controller like this:
GenericAddViewController *vc = [[GenericAddViewController alloc]init];
UINavigationController *navigationController = [[UINavigationController alloc]initWithRootViewController:vc];
navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:navigationController animated:YES completion: nil];

Then, inside the GenericAddViewController.m I have:
@interface GenericAddViewController ()
@property (strong, nonatomic) UITextField *titleTextField;
@property (nonatomic, strong) UITabBarController *tabBarController;

@end

@implementation GenericAddViewController

-(void)loadView
{
[super loadView];

TabOneController *tabOneController = [[TabOneController alloc]init];
tabOneController.title = @"Steps";

TabTwoController *tabTwoController = [[TabTwoController alloc]init];
tabTwoController.title = @"More Information";

NSArray *controllers = [NSArray arrayWithObjects:tabOneController, tabTwoController, nil];

self.tabBarController = [[UITabBarController alloc]init];
self.tabBarController.view.frame = CGRectMake(0, 0, 768, 1004);
self.tabBarController.viewControllers = controllers;
self.tabBarController.delegate = self;

}

This works. The only problem is for example in the TabOneController, I can't do any of these:
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(isDone:)];
[self.navigationItem setRightBarButtonItem:doneButton animated:NO];

Nor
    [self.navigationController push...]
Shouldn't be that complicated no?!
Thanks a lot!


text:
Q: How to wrap a C struct that contains a C++ object in python ctypes I have a C/C++ structure which contains an object (an STL container, for example.)  I would like to access this from Python using ctypes.  For example,
C/C++:
struct Foo {
  int bar;
  vector<int> baz;
  double quxx;
}

Python ctypes:
from ctypes import *

class Foo(Structure):
  _fields_ = [
    ("bar", c_int),
    ("baz", ???),  <--- what do i put here?
    ("quxx", c_double),]

I realize I can't access STL containers using ctypes without creating wrapper functions, but it'd be nice to be able to access "bar" and "quxx."  The only way I've been able to do this is to only deal with opaque pointers and wrapper functions, e.g.
C/C++:
int Foo_bar(*Foo foo) { return foo->bar; }
...

Python
class Foo_p(c_void_p): pass
my_Foo_p = ... somehow get a Foo pointer ...
bar = mylib.Foo_bar(my_Foo_p)

This seems clumsy.  Is there a way to create a ctypes.Structure for C structs which contain C++ objects?  Maybe using sizeof?

A: If it contains a C++ class as a member, it is not a C-struct. struct and class are identical keywords except that struct defaults to public for all members rather than private.
That said, if you're willing to risk nasal demons if you get it wrong, you could use hidden knowledge. In both of the major libraries used on unixy platforms, vector internally contains three pointers, so you could use that. I have no idea what Windows implementations use, but Windows doesn't have a stable ABI anyway.


text:
Q: How to make an infinite horizontal container with fixed height I have built the following webpage:
http://tarjom.ir/demo/niazer/
Then What do I need?
as you see the last part of the page is a row of Icons and thumbnails that when you hover your mouse [the hovered item] expands. I need at least ten more thumbnails to be there which causes the display to break to next line and makes it two rows of thumbnails (which could break to three and more even with more thumbs).
I want a container which displays 1200px of width but contains elements to an infinite width (8000px or more). How should I achieve this?
Here is the CSS for these elements:
Main horizontal wrapper, each thumnbail wrapper
.main-cat-wrapper
{
  float: left;
   margin-right: 15px;
  margin-bottom: 50px;
  width: 100px;
  overflow: hidden;
  height: 105px;
}
.main-cat-wrapper:hover
{
    border-right: 1px #CCC dotted;
    cursor: pointer;
     background-color: #F9F9F9;
     box-shadow: 1px 1px 1px rgba(0,0,0,0.05);
}
.main-cat-wrapper img
{
    display: block;
    float: left;
}
.main-cats
{

    height: 150px;
    position: absolute;
    left: 22.5%;

}

.main-cats is the wrapper responsible for holding all thumnails.

A: You can try this :
.main-cats {
  width:1200px;
  overflow: hidden;
  white-space:nowrap;
}

And instead of float use display:inline-block:
.main-cat-wrapper {
  display:inline-block;
}

Review this demo http://jsfiddle.net/WFW25/3/ I set overflow:auto only to see the other elements in the block.

A: Maybe something like this:
var eleWidth = 0;
$('.inner div').each(function(){
    eleWidth += $(this).width()
}).hover(function(){
    $('.inner').width(eleWidth+50)
}, function(){
    $('.inner').width(eleWidth)
})

$('.inner').width(eleWidth)

Demo
You can tweak it to your needs.


text:
Q: Querying a field for empty value I'm trying to query for an empty field.  In SQL parlance, I would do the following:
 select * from cars where cartype="Auto" and make="Ferrari" and color="" and model="" and seats in ["", "bench"]

I'm doing the following, but I'm getting an error
 {
     "query": {
         "bool": {
             "must": [
                 {
                     "match": {
                         "CarType": "Auto"
                     }
                 },
                 {
                     "match": {
                         "Make": "Ferrari"
                     }
                 }
             ],
             "must_not": [
                 {
                     "existence": true,
                     "field": "Color",
                     "null_value": true
                 },
                 {
                     "existence": true,
                     "field": "Model",
                     "null_value": true
                 }
             ]
         }
     }
 }

But I get the following:  "Parse Failure [Failed to parse source .... nexted:  query malformed"
I'm following the example here

A: try like this
{
"query": {
    "bool": {
        "must": [

                {
                 "match": {
                     "CarType": "Auto"
                 }
                }
          ,
          {
                 "match": {
                     "Make": "Ferrari"
                 }

           }
        ], "must_not": [
           {
              "missing":{
                        "field":"Model",
                         "existence":true,
                          "null_value":true
                         }
           },
            {
              "missing":{
                        "field":"Color",
                         "existence":true,
                          "null_value":true
                         }
           }
        ]
    }
}
}


text:
Q: Is there a "programming culture" explanation for why FF returns long fraction from measureText method? All browsers except Firefox return a number without a fraction part from the Canvas element's measureText() method.  FF returns values like 26.45682955697084.  Since the measurement is said to be in pixels, I am wondering why the fraction in FF?
So that my question is not shut down by overzealous moderators, please do not argue for or against the behavior! I simply want to know if there was a rationale for the behavior, and if so, what it was. Maybe there are nuances to rendered glyph measurements in the Canvas that I should be aware of?

A: It seems that Firefox is doing the right thing. The spec says that width is returned as a double. http://dev.w3.org/html5/2dcontext/#textmetrics .
Also note that the canvas supports rendering fractions of a pixel, in which case it uses some kind of  interpolation to make your image blurry and render slowly. ;-) I found http://sebleedelisle.com/2011/02/html5-canvas-sprite-optimisation/ to be very informative about this.


text:
Q: CleanCSS warning when finds Import statements I have the following file:
styles.css
@import url("https://fonts.googleapis.com/css2?family=Oxygen:wght@300;400;700&display=swap");

html,
body {
  height: 100%;
}
body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  justify-content: flex-start;
  overflow-x: hidden;
  padding: 0;
  margin: 0;
  -webkit-text-size-adjust: none;
  font: normal normal normal 16px Oxygen;
  letter-spacing: 0px;
  color: #1b1018;
  background-repeat: no-repeat;
  background-size: cover;
}
body > header {
  flex-shrink: 0;
  color: #fff;
  background: #69b684;
  text-align: center;
  padding: 20px;
}
body > main {
  margin: 0 auto;
  max-width: 1150px;
  text-align: center;
  padding: 50px 10px;
  max-width: 860px;
  background: #ffffff 0% 0% no-repeat padding-box;
  border: 9px solid #ffffff53;
}

which I want to minify with: CleanCSS.
For that, I did the following:
$ npm install clean-css-cli -g
$ cleancss --output styles.min.css styles.css

But when executing the command, I get the following warning:
WARNING: Skipping remote @import of "https://fonts.googleapis.com/css2?family=Oxygen:wght@300;400;700&display=swap" as resource is not allowed.

Is there any way to get rid that warning?
The output file is fine for me, though:
styles.min.css
@import url(https://fonts.googleapis.com/css2?family=Oxygen:wght@300;400;700&display=swap);body,html{height:100%}body{display:flex;flex-direction:column;min-height:100vh;justify-content:flex-start;overflow-x:hidden;padding:0;margin:0;-webkit-text-size-adjust:none;font:normal normal normal 16px Oxygen;letter-spacing:0;color:#1b1018;background-repeat:no-repeat;background-size:cover}body>header{flex-shrink:0;color:#fff;background:#69b684;text-align:center;padding:20px}body>main{margin:0 auto;max-width:1150px;text-align:center;padding:50px 10px;max-width:860px;background:#fff 0 0 no-repeat padding-box;border:9px solid #ffffff53}

Thanks in advance!


text:
Q: How can I pass/create a fake media stream to Edge/IE WebDriver? There are some flags to create a fake media stream for web camera recording. For example:
'--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream' (Chrome);
'make.navigator.streams.fake' (Firefox).
Are there any flags for Edge/IE browser to pass them to WebDriver capability (Selenium::WebDriver.new :remote, { url: url, desired_caps: caps })?

A: Currently, there is no such BrowserStack specific custom capability to pass fake media stream on IE and edge. However, you can use the same on chrome and firefox as you have mentioned above. The Chrome Option 'use-fake-device-for-media-stream' is used to grant camera access. However, you can use the 'use-fake-ui-for-media-stream' Chrome Option that will handle the scenarios for 'use-fake-device-for-media-stream' as well('Use you Microphone' OR 'Use your camera' popup).


text:
Q: Can't define 2 functions in the same matlab file I'm trying to join 2 functions together in one matlab file it simply says

"function result = DTFMdetect(filenumber), Error: Function definitions are not permitted in this context"

The code where working earlier when I had the 2 functions in separate files and called detectSK in the other one, but now when I try to get them together, I get this error. Does anyone here know what it's about or have ran into it and can help maybe?
Thanks in advance
       function result = DTMFdetect(filenumber)
    %
    % Funktion som avkodar DTMF signaler
    %
    % Funktionen generate_secret_data.p samt DTMFgen.m måste finnas i samma
    % filkatalog som denna funktionen (eller i path)
    %
    % Insignaler
    %    filenumber = signalfilsnummer (0-99)
    %
    % Utsignal
    %    Sträng-array med detekterade symboler
    %    ex. result(3,2) är 2:a symbolen som detekterades i 3:e signalen

    signals = generate_secret_data(filenumber);

    for sig_idx = 1:6, % 6 signaler ska analyseras
        figure;
        plot(signals(:,sig_idx));
        signals(:,sig_idx);

        detected_symbol = detectSK(signals(:,sig_idx)); % Dålig algoritm som alltid gissar 'A'!
        for sym_idx=1:4, % varje signal innehåller 4 symboler

            % Här fyller du i din detektionsalgoritm för symbol sym_idx
            % i signal sig_idx
            %
            % signals(:,sig_idx) är signalvektorn med alla 4 symboler

            result(sig_idx,sym_idx) = detected_symbol(sym_idx); % tilldela resultat

        end
    end
    end

    function detectedSignals=detectSK(data)

    % Vårat program delar in inkommande data till en array med signalerna
    % uppdelade
    %Sedan filtrerar den signalerna med motsvarande bandpassfilter för
    %frekvenserna och behåller sådan de frekvenser där den hittade mest data,
    %dessa används sedan för att jämföra med vilken symbol kombinationen
    %motsvarar. Brus är inte riktigt tagit i beaktning utan vi resonarade att

  %in a perfect world så filtreras orelevant brus bort och vi kan med denna
    %metod fortfarande få ut rätt data.

    % data=DTMFgen('16544',40,40,0.5);                  %% Läser in data
    numberOfTones=(length(data)-320)/640;       %%Räknar ut hur många toner det är, tar bort de första 40ms då det verkar vara en väntedel
    individualSignals=zeros(numberOfTones,320); %%Variabel för att hålla de olika signalerna
    IndividualSymbols=[];
    %booleans för att hålla värdena för hittade frekvenser
    B1209=false;
    B1336=false;
    B1477=false;
    B1633=false;
    B697=false;
    B770=false;
    B852=false;
    B941=false;

    % Forloop som itererar genom signalen för att dela upp den
    for i=1:1:numberOfTones
        for k=1:1:320;
            individualSignals(i,k)=data((320+(i-1)*640)+(k-1));
        end
    end

    for i=1:1:numberOfTones
        % 697Hz-Bandpass filter
        Fs = 8E+3; Fc1 = 687; Fc2 = 707; Fs1 = Fc1*0.8; Fs2 = Fc2/0.8; Rp = 1; Rs = 20;

        [n,Wn]  = buttord([Fc1 Fc2]/4000, [Fs1 Fs2]/4000, Rp, Rs);
        [b,a]   = butter(2*n,Wn);
        [sos,g] = tf2sos(b,a);
        data697=filtfilt(sos,g,individualSignals(i,:));%filtrerar datan

        N=length(data697);%längden på signalen
        Y=fft(data697);%fft:ar den
        P2=abs(Y);%hela spektrumet (negativa OCH positiva)
        P1=P2(1:N/2+1);%ser till att vi endast tittar för positiva frekvenser
        P1(2:end-1)=2*P1(2:end-1);%gångrar den med 2?
        f=8000*(0:(N/2))/N;%definerar frekvensspektrumet
        value697=sum(P1);

        % 770Hz-Bandpass filter
        Fs = 8E+3; Fc1 = 760; Fc2 = 780; Fs1 = Fc1*0.8; Fs2 = Fc2/0.8; Rp = 1; Rs = 20;

        [n,Wn]  = buttord([Fc1 Fc2]/4000, [Fs1 Fs2]/4000, Rp, Rs);
        [b,a]   = butter(2*n,Wn);
        [sos,g] = tf2sos(b,a);
        data770=filtfilt(sos,g,individualSignals(i,:));

        N=length(data770);%längden på signalen
        Y=fft(data770);%fft:ar den
        P2=abs(Y);%hela spektrumet (negativa OCH positiva)
        P1=P2(1:N/2+1);%ser till att vi endast tittar för positiva frekvenser
        P1(2:end-1)=2*P1(2:end-1);%gångrar den med 2?
        f=8000*(0:(N/2))/N;%definerar frekvensspektrumet

        value770=sum(P1);
        % 852Hz-Bandpass filter
        Fs = 8E+3; Fc1 = 842; Fc2 = 862; Fs1 = Fc1*0.8; Fs2 = Fc2/0.8; Rp = 1; Rs = 20;

        [n,Wn]  = buttord([Fc1 Fc2]/4000, [Fs1 Fs2]/4000, Rp, Rs);
        [b,a]   = butter(2*n,Wn);
        [sos,g] = tf2sos(b,a);
        data852=filtfilt(sos,g,individualSignals(i,:));

        N=length(data852);%längden på signalen
        Y=fft(data852);%fft:ar den
        P2=abs(Y);%hela spektrumet (negativa OCH positiva)
        P1=P2(1:N/2+1);%ser till att vi endast tittar för positiva frekvenser
        P1(2:end-1)=2*P1(2:end-1);%gångrar den med 2?
        f=8000*(0:(N/2))/N;%definerar frekvensspektrumet

        value852=sum(P1);
        % 941Hz-Bandpass filter
        Fs = 8E+3; Fc1 = 931; Fc2 = 951; Fs1 = Fc1*0.8; Fs2 = Fc2/0.8; Rp = 1; Rs = 20;

        [n,Wn]  = buttord([Fc1 Fc2]/4000, [Fs1 Fs2]/4000, Rp, Rs);
        [b,a]   = butter(2*n,Wn);
        [sos,g] = tf2sos(b,a);
        data941=filtfilt(sos,g,individualSignals(i,:));

        N=length(data941);%längden på signalen
        Y=fft(data941);%fft:ar den
        P2=abs(Y);%hela spektrumet (negativa OCH positiva)
        P1=P2(1:N/2+1);%ser till att vi endast tittar för positiva frekvenser
        P1(2:end-1)=2*P1(2:end-1);%gångrar den med 2?
        f=8000*(0:(N/2))/N;%definerar frekvensspektrumet

        value941=sum(P1);
        % 1209Hz-Bandpass filter
        Fs = 8E+3; Fc1 = 1199; Fc2 = 1219; Fs1 = Fc1*0.8; Fs2 = Fc2/0.8; Rp = 1; Rs = 20;

        [n,Wn]  = buttord([Fc1 Fc2]/4000, [Fs1 Fs2]/4000, Rp, Rs);
        [b,a]   = butter(2*n,Wn);
        [sos,g] = tf2sos(b,a);
        data1209=filtfilt(sos,g,individualSignals(i,:));

        N=length(data1209);%längden på signalen
        Y=fft(data1209);%fft:ar den
        P2=abs(Y);%hela spektrumet (negativa OCH positiva)
        P1=P2(1:N/2+1);%ser till att vi endast tittar för positiva frekvenser
        P1(2:end-1)=2*P1(2:end-1);%gångrar den med 2?
        f=8000*(0:(N/2))/N;%definerar frekvensspektrumet
        value1209=sum(P1);

        % 1336Hz-Bandpass filter
        Fs = 8E+3; Fc1 = 1326; Fc2 = 1346; Fs1 = Fc1*0.8; Fs2 = Fc2/0.8; Rp = 1; Rs = 20;

        [n,Wn]  = buttord([Fc1 Fc2]/4000, [Fs1 Fs2]/4000, Rp, Rs);
        [b,a]   = butter(2*n,Wn);
        [sos,g] = tf2sos(b,a);
        data1336=filtfilt(sos,g,individualSignals(i,:));

        N=length(data1336);%längden på signalen
        Y=fft(data1336);%fft:ar den
        P2=abs(Y);%hela spektrumet (negativa OCH positiva)
        P1=P2(1:N/2+1);%ser till att vi endast tittar för positiva frekvenser
        P1(2:end-1)=2*P1(2:end-1);%gångrar den med 2?
        f=8000*(0:(N/2))/N;%definerar frekvensspektrumet

        value1336=sum(P1);
        % 1477Hz-Bandpass filter
        Fs = 8E+3; Fc1 = 1467; Fc2 = 1487; Fs1 = Fc1*0.8; Fs2 = Fc2/0.8; Rp = 1; Rs = 20;

        [n,Wn]  = buttord([Fc1 Fc2]/4000, [Fs1 Fs2]/4000, Rp, Rs);
        [b,a]   = butter(2*n,Wn);
        [sos,g] = tf2sos(b,a);
        data1477=filtfilt(sos,g,individualSignals(i,:));

        N=length(data1477);%längden på signalen
        Y=fft(data1477);%fft:ar den
        P2=abs(Y);%hela spektrumet (negativa OCH positiva)
        P1=P2(1:N/2+1);%ser till att vi endast tittar för positiva frekvenser
        P1(2:end-1)=2*P1(2:end-1);%gångrar den med 2?
        f=8000*(0:(N/2))/N;%definerar frekvensspektrumet

        value1477=sum(P1);
        % 1633Hz-Bandpass filter
        Fs = 8E+3; Fc1 = 1623; Fc2 = 1643; Fs1 = Fc1*0.8; Fs2 = Fc2/0.8; Rp = 1; Rs = 20;

        [n,Wn]  = buttord([Fc1 Fc2]/4000, [Fs1 Fs2]/4000, Rp, Rs);
        [b,a]   = butter(2*n,Wn);
        [sos,g] = tf2sos(b,a);
        data1633=filtfilt(sos,g,individualSignals(i,:));

        N=length(data1633);%längden på signalen
        Y=fft(data1633);%fft:ar den
        P2=abs(Y);%hela spektrumet (negativa OCH positiva)
        P1=P2(1:N/2+1);%ser till att vi endast tittar för positiva frekvenser
        P1(2:end-1)=2*P1(2:end-1);%gångrar den med 2?
        f=8000*(0:(N/2))/N;%definerar frekvensspektrumet

        value1633=sum(P1);

        big=sort([value1209 value1336 value1477 value1633]);
        small=sort([value697 value770 value852 value941]);

        if value1209==big(4)
            B1209=true;
        else B1209=false;
        end
        if value1336==big(4)
            B1336=true;
        else B1336=false;
        end

        if value1477==big(4)
            B1477=true;
        else B1477=false;
        end

        if value1633==big(4)
            B1633=true;
        else B1633=false;
        end

        if value697==small(4)
            B697=true;
        else B697=false;
        end

        if value770==small(4)
            B770=true;
        else B770=false;
        end

        if value852==small(4)
            B852=true;
        else B852=false;
        end

        if value941==small(4)
            B941=true;
        else B941=false;
        end

        % Kollar vilka siffror det motsvarar
        if B1209 & B697
            Digit1=true;
        else
            Digit1=false;
        end

        if B1209 & B770
            Digit4=true;
        else
            Digit4=false;
        end

        if B1209 & B852
            Digit7=true;
        else
            Digit7=false;
        end

        if B1209 & B941
            DigitStar=true;
        else
            DigitStar=false;
        end

        if B1336 & B697
            Digit2=true;
        else
            Digit2=false;
        end

        if B1336 & B770
            Digit5=true;
        else
            Digit5=false;
        end

        if B1336 & B852
            Digit8=true;
        else
            Digit8=false;
        end

        if B1336 & B941
            Digit0=true;
        else
            Digit0=false;
        end

        if B1477 & B697
            Digit3=true;
        else
            Digit3=false;
        end

        if B1477 & B770
            Digit6=true;
        else
            Digit6=false;
        end

        if B1477 & B852
            Digit9=true;
        else
            Digit9=false;
        end

        if B1477 & B941
            DigitSharp=true;
        else
            DigitSharp=false;
        end

        if B1633 & B697
            DigitA=true;
        else
            DigitA=false;
        end

        if B1633 & B770
            DigitB=true;
        else
            DigitB=false;
        end

        if B1633 & B852
            DigitC=true;
        else
            DigitC=false;
        end

        if B1633 & B941
            DigitD=true;
        else
            DigitD=false;
        end

        if Digit1
            individualSymbols(i)='1';
        end

        if Digit2
            individualSymbols(i)='2';
        end
        if Digit3
            individualSymbols(i)='3';
        end
        if Digit4
            individualSymbols(i)='4';
        end
        if Digit5
            individualSymbols(i)='5';
        end
        if Digit6
            individualSymbols(i)='6';
        end
        if Digit7
            individualSymbols(i)='7';
        end
        if Digit8
            individualSymbols(i)='8';
        end
        if Digit9
            individualSymbols(i)='9';
        end
        if Digit0
            individualSymbols(i)='0';
        end
        if DigitA
            individualSymbols(i)='A';
        end
        if DigitB
            individualSymbols(i)='B';
        end
        if DigitC
            individualSymbols(i)='C';
        end
        if DigitD
            individualSymbols(i)='D';
        end
        if DigitSharp
            individualSymbols(i)='#';
        end
        if DigitStar
            individualSymbols(i)='*';
        end
    end

    detectedSignals=individualSymbols;

A: You need to either close all functions with end or omit the end from all function definitions. Now you are mixing the syntax for defining functions (i.e. closing the first function with end but not the second function).
In code:
% This is valid

function res = main()
res = secondary(1);

function res2 = secondary(i)
res2 = i*2;

And:
% This is also valid

function res = main()
res = secondary(1);
end

function res2 = secondary(i)
res2 = i*2;
end

However:
% This is NOT valid

function res = main()
res = secondary(1);
end

function res2 = secondary(i)
res2 = i*2;

Error: File: main.m Line: 9 Column: 1
The function "main" was closed with an 'end', but at least one other function definition was not. To avoid confusion when using nested functions, it is
illegal to use both conventions in the same file.

A: Remove the end before the code line
function detectedSignals=detectSK(data)


text:
Q: PyCharm f-string usage in a class displays warning (Unresolved attribute reference '__name' for class...) (short version of code)
class Animal:
    __name = ""
    __gender = "unknown"
    __height = 0
    __weight = 0
    __hungry = False

    def __init__(self, name, gender, height, weight):
        self.__name, self.__gender, self.__height, self.__weight = name, gender, height, weight

    def toString(self):
        return f'{self.__name} is a {self.__gender}, {self.__height} m tall and weights {self.__weight} kg.'

PyCharm warns me: Unresolved attribute reference '__name' for class 'Animal'
The code is still working as intended. Why does this warning pop up?
f-strings seem a cleaner version of str.format for me and they are also faster.
PS. As I'm a newbie to Python, please feel free to bring out all the stylish errors or what could and should be done better :)
Python version: 3.6.4
PyCharm Community version: 2017.3.1
Picture of the code and the error

A: There is this post from about a year ago and also this. It seems like it could be an issue with PyCharm.
However, if you remove the double underscores within the f string, the linter no longer complains.
Calling ''.format() with the dunder prefixed attribute seems to not produce errors or warnings either.
As @kindall stated above prefixing with the double underscore invokes name mangling.
class Animal:
    __X = 'y'

    def __init__(self, name="", gender="", height=0, weight=0, hungry=False):
        self.name = name
        self.gender = gender
        self.height = height
        self.weight = weight
        self.hungry = hungry

    def to_string(self):
        return f'{self.name} is a {self.gender}, {self.height} m tall and weights {self.weight} kg.'

    def to_string_format(self):
        return '{}'.format(self.__X)

Also they seem to know about bugs pertaining to this issue. I would bring it up; it would be good for them to get some more information.


text:
Q: Change support ActionBar tabs indicator color This is a follow up question to this question:
ActionBar AppCompat change Tab indicator color
I'm using the support action bar and adding tabs to it. I want to change the indicator color. What I've tried doing is this:
 <style name="CustomActivityTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
            <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/MyActionBar</item>
        <item name="android:actionBarTabStyle">@style/MyActionBarTabViewStyle</item>
        <item name="actionBarTabStyle">@style/MyActionBarTabViewStyle</item>
    </style>

<style name="MyActionBarTabViewStyle" parent="@android:style/Widget.Holo.Light.ActionBar.TabView">
        <item name="android:background">@color/White</item>
    </style>

This changes the entire tab's color, but I want to change the indicator's color only. What am I doing wrong here?

A: Try this:

*

*Create the theme for the app, the action bar, and the tabs. We need
to set the background for the tabs to the "tab_bar_background"
drawable.
in res/values/styles.xml
<style name="FindMyTrain" parent="Theme.Sherlock">
    <item name="android:actionBarTabStyle">@style/FindMyTrain.ActionBar.Tab</item>
    <item name="actionBarTabStyle">@style/FindMyTrain.ActionBar.Tab</item>
</style>

<style name="FindMyTrain.ActionBar.Tab">
    <item name="android:background">@drawable/tab_bar_background</item>
</style>

*in res/drawable/tab_bar_background add a color state list
 <?xml version="1.0" encoding="utf-8"?>

<selector
xmlns:android="http://schemas.android.com/apk/res/android">   <item
android:state_focused="false" android:state_selected="false"
android:state_pressed="false"
android:drawable="@color/transparent"/>   <item
android:state_focused="false" android:state_selected="true"
android:state_pressed="false"
android:drawable="@drawable/tab_bar_background_selected"/>   <item
android:state_selected="false" android:state_pressed="true"
android:drawable="@color/tab_highlight"/>   <item
android:state_selected="true" android:state_pressed="true"
android:drawable="@drawable/tab_bar_background_selected_pressed"/>
</selector>

here you can customize tab bar pressed and selected state color.

*in res/drawable/tab_bar_background_selected
 <?xml version="1.0" encoding="utf-8"?>
 <layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:top="-5dp" android:left="-5dp" android:right="-5dp">
            <shape android:shape="rectangle">
                <stroke android:color="#ff4ba587" android:width="5dp"/>
            </shape>
        </item> </layer-list>

*Now apply the theme:
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/FindMyTrain"
    android:name=".FindMyTrainApplication" >

Output:

For detail documentation see this Link

A: You can use this to change your indicator color.
TabLayout.setSelectedTabIndicatorColor(int color)


text:
Q: How to access ajax response data outside ajax function in angularjs I am fetching some data via http get ajax.
$.ajax({
    type: "GET",
    url: "/userdata/",

    success: function(response){
        $scope.steps = response.no_of_steps;
        $scope.calories = response.calories;
    },

    error: function(){
        alert("error");
    }
});

If i print it on console from inside the success function, it prints the value like:
    success: function(response){
        var $scope.steps = response.no_of_steps;
        var $scope.calories = response.calories;
        console.log($scope.steps, $scope.calories);
    },

But if i print it on colsole outside my ajax request, it print undefined. how is that so?
$.ajax({
    ...
});
console.log($scope.steps, $scope.calories);

A: this is continuation of my comment on your post above
you could do that by using $scope.$emit("custom-event-name"); of angular,
here you are actually watching $scope.steps and $scope.calories for change once your ajax call completes signify this by using $emit of angular
and then listen for that event by $scope.$on("custom-event-name", function(){})
and log it there, Please do make sure your "custom-event-name" is same in $emit and $on
in success callback : initialize the value and use $emit to emit an event named initialized as :-
$scope.steps = response.no_of_steps;
$scope.calories = response.calories;
$scope.$emit("initialized");

and then listen for that event initialized
$scope.$on('initialized', function () {
  console.log($scope.steps + ' and ' + $scope.calories);
});

A: Couple of mistakes here.... use $http instead of $ajax, secondly you are defining your variables inside your success function so the scope is limited once it comes out of it... define your function globally in your controller and then access it inside your success function.
var $scope.steps => wrong way
$scope.steps = "something"; => right way.

You don't need to append var keyword with $scope in angularjs.
$scope.steps;
$scope.calories;

$.ajax({
    type: "GET",
    url: "/userdata/",

    success: function(response){
        $scope.steps = response.no_of_steps;
        $scope.calories = response.calories;
    },

    error: function(){
        alert("error");
    }
});

Use $scope variables if you want to bind to the view and var does not and is local to the function it was declared in.

A: This works for me, i want to recommend you not to make use of $.ajax in angular js its a jquery function; i heard $http is faster than $.ajax function.
Hope this works for you if didnot work please inform me
//$scope.tablerows defined outside the function
$scope.tablerows;
module='user';
url=siteurl+"/admin/"+module+"/list";
BlockUi();
// $http is ajax call in angular js which is equivalent to $.ajax();
$http({
    url     :   url,
    method  :   "GET",
    data    :   "",
    headers : { 'Content-Type':undefined,
                'Access-Control-Allow-Origin' : '*',
                'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
              }
    //responseText is the output of success call
    }).then(function(responseText){
        // assigning the response text on the variable
        $scope.totaltablerows=responseText.data.response_data;
        $scope.tablerows=$scope.totaltablerows;
        UnblockUi();
    },function(error){
        //alert(JSON.stringify(error));
        UnblockUi();
        UnknownError(JSON.stringify(error));
    });


text:
Q: Add Custom Domain in Azure blob storage Error creating Custom Domain in Azure
Hi, I am trying to link a custom domain to my static website that is located on my blob storage account. When creating the custom domain these are the azure instructions "Create a CNAME record with the DNS provider that points the domain (eg, www.contoso.com) to blobstorage.blob.core.windows.net or blobstorage.z13 .web.core.windows.net and then specify your domain. This method is simpler, but causes a short downtime while Azure checks the domain registration. "
In my godaddy account I have created a new CNAME record as follows Type: CNAME, name: www.mydomain.com, value: blobstorage.z13.web.core.windows.net.Y when trying to specify the custom domain in azure (mydomain.com) generates the following error: "Could not update storage account 'XXXX'. Error: The custom domain name could not be verified. CNAME mapping from mydomain.com to any of ..... does not exist "
I do not understand what I am doing wrong, I am very new in the subject and I really appreciate the help you can give me. Thank you very much

A: Be sure you have the CNAME record set correctly in the DNS settings for your domain name, then give it some time to update. DNS doesn't update immediately, it can take some time for the update to sync through all the DNS server between your registrar and Azure or your local ISP. This is especially the case when you test and it fails, then you need to wait at minimum the TTL (time-to-live) time that is set on the DNS records updated before you'll be able to test again.
On an aside, I'd recommend setting the TTL on the DNS records to 1/2 hour, then when everything's working you can go update it to a longer TTL. This will help when you need to update things and retest again to get it working.

A: I could already make the configuration I was looking for by configuring a CDN. this is the link learn.microsoft.com/en-us/azure/storage/blobs/… Thanks everybody fot your answers and comments –


text:
Q: Printing data variable I am trying to print data() variable. I am not getting output in HTML template.
<template>

{{app_skills}}

</template>

A: Your code worked exactly as expected when I tried it (with a few environment-related changes):
<template>

{{app_skills}}

</template>

All I changed was including the axios library, changing the URL to pull from, and changing the response.data key to pull. It all works as expected. Perhaps you have an issue somewhere else in your surrounding code?


text:
Q: How do I write 'decimal to Binary convertion ' in Latex?
How can I make like this...plz help!

A: Try
\documentclass{article}

\usepackage{expl3}

\ExplSyntaxOn
\cs_new:Npn \displayasdecimal#1 {(#1) \sb {10}}
\cs_new:Npn \displayasoctal #1 {(\int_to_oct:n{#1}) \sb 8}
\cs_new:Npn \displayasbinary #1 {(\int_to_bin:n{#1}) \sb 2}
\ExplSyntaxOff

\begin{document}

$\displayasdecimal{311}=\displayasoctal{311}=\displayasbinary{311}$

\end{document}

This gets you

If you actually want to do the calculation automatically and dislay it as in the top of your picture then that would be possible too using expl3.


text:
Q: LOG/print mongo options of mongoclient created using spring For a spring based project I am  using mongoTemplate to query mongo DB.
For this I have used systemProperties to configure mongo options  .
Now I want to print the value of these mongo options in my server's LOG, but unable to find a suitable way to do this. Kindly suggest. Following is my spring mongo xml.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd">

<!-- Mongo Template for Test -->
<mongo:mongo replica-set="#{systemProperties['mongoTest.replicaset']}" id="mongoCocofs">
    <mongo:options auto-connect-retry="true" connections-per-host="#{systemProperties['mongoTest.connPerHost']?:'80'}" threads-allowed-to-block-for-connection-multiplier="#{systemProperties['mongoTest.threadAllowedForConnMultiplier']?:'5'}" slave-ok="true"/>
</mongo:mongo>

<mongo:db-factory dbname="test" mongo-ref="mongoTest" id="mongoDbFactoryTest" />

<bean id="mongoTemplateTest" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="mongoDbFactoryCocofs" />
</bean>

<context:annotation-config />

A: Solved it.
We can print it by calling following functions on a mongoTemplate bean:
mongoTemplate.getDb().getMongo().getMongoOptions()


text:
Q: Error in date while formatting in iphone? Hi I am trying to format date which I m getting from server. I have tryed like this
NSString *dateStr =@"2012-5-21";
    // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-mm-dd"];
    NSDate *date = [dateFormat dateFromString:dateStr];

    // Convert date object to desired output format
    [dateFormat setDateFormat:@"dd MMM yyyy"];
                                dateStr = [dateFormat stringFromDate:date];
    finalDate.text=dateStr;

    [dateFormat release];

but in place of 21 May 2012. I am getting 21 Jan 2012

A: you are using wrong format first time. mm is for Minutes , replace it with capital MM -
[dateFormat setDateFormat:@"yyyy-MM-dd"];

A: USe Capital MM for month format representaion
 [dateFormat setDateFormat:@"yyyy-MM-dd"];


text:
Q: express without a template Is there a reason why I should avoid doing this?
app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set("view options", {layout: false});
  app.use(express.static(__dirname + '/views'));
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

var html_dir = './views/';

app.get('/', function(req, res){
    res.sendfile(html_dir  + "login.html");
});

A: you need to use res.write and res.end() and just read the content's of the file vis the core require('fs') you can use res.set(field, [value]) for the headers
full docs


text:
Q: Different Aspect Ratio for Laptop + External Monitor I'm looking at buying a Dell XPS which has a 16:10 aspect ratio for its screen.
My current monitors are 16:9.
Will Ubuntu be able to display both screens at once correctly if they require different aspect ratios?
I have 2 monitors so the laptop screen should be at 1920-1200 and the two monitors at 1920-1080
Thanks

A: Yes, for each monitor you can specify whatever supported resolution you require.


text:
Q: How to stop service while running the service? In my application i am running the service in the background by using the following code.
Service myser=new Intent(EmailRegistrationActivity.this, BackgroundService.class);
startService(myser);

And in my service class i am using AsyncTask class. In that AsyncTask class i have to get the sms and mms from the device and posting to my local server.In between the process,the user want to sign out.So in that sign out method i want to stop the service.
And this is the service class
public class BackgroundService extends Service{
@Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
@Override
    public void onCreate() {
        super.onCreate();
}
 @SuppressLint("NewApi")
    public int onStartCommand(Intent intent, int flags, int startId) {

        if(startId>1)
        {
            if(CheckInternetConnection.isOnline(BackgroundService.this))
            {
         dob=new Doinback();
         dob.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }else{
            //check2=preferences.
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("checkbackground", true);
        editor.commit();

        }
        }

      return 1;
    }
    public void onStart(Intent intent, int startId) {

    }
    public IBinder onUnBind(Intent arg0) {
        return null;
    }

    public void onStop() {

        this.stopSelf();

    }
    public void onPause() {

    }

    @Override
    public void onDestroy() {

         super.onDestroy();

         Log.e("Destroy=======@@@@@@@","method calling");
         dob.cancel(false);

          while(strtId>0){
              this.stopSelf(strtId);
              strtId--;
          }

         onStop();
    }

    @Override
    public void onLowMemory() {

    }
}

And this is the asynctask class
class Doinback extends AsyncTask<URL, Integer, Long>{
    protected void onPreExecute()
    {

    }
    protected Long doInBackground(URL... arg0) {

    if(!isCancelled())
    {
    try {
        strResLastmessage_time = UrltoValue.getValuefromUrl(DataUrls.lastmessage_time + "userid="+strUserId);
        JSONObject jsonObj = new JSONObject(strResLastmessage_time);
        strLastMessage_time = jsonObj.getString("lastdatetime");
        preferences = PreferenceManager.getDefaultSharedPreferences(BackgroundService.this);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putLong("msgtime", Long.parseLong(strLastMessage_time));
        editor.commit();
        } catch (Exception e) {
    //      e.printStackTrace();
        }
        messages.clear();
        readSmsFromDevice();
        checkMessages();
     }
     return null;
    }
    protected void onCancelled() {
    }

    protected void onPostExecute(Long result) {
        //check=preferences.getBoolean("checkbackup", true);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("checkbackup", true);
        editor.putBoolean("checkbackground", true);
        editor.commit();
    }
}//async class

And in this asyntask class i am using readsmsfromdevice method and checkmessages method to get the data from device and post to to service.But my requirement is whenever user want to logout, the service have to stop.So that i am using the following code to stop service and also stopped asynctask.
BackgroundService.dob.cancel(true);
getActivity().stopService(new Intent(getActivity(), BackgroundService.class));

But it not working,still in background the proceess is continue.Please suggest me how to stop this service.Thanks In Advance...

A: You are calling the right method "this.stopSelf()". I once had this problem and after adding return Service.START_NOT_STICKY it worked. Could you just add this code on onStartCommand method and check if it works:
return Service.START_NOT_STICKY;

A: What you need is IntentService.From docs:

IntentService is a base class for Services that handle asynchronous
  requests (expressed as Intents) on demand. Clients send requests
  through startService(Intent) calls; the service is started as needed,
  handles each Intent in turn using a worker thread, and stops itself
  when it runs out of work.

Refer this link on how to use IntentService:
http://code.tutsplus.com/tutorials/android-fundamentals-intentservice-basics--mobile-6183


text:
Q: Copy in insert mode with mouse I'm using vsvim, sometimes I highlight code in insert mode with my mouse and want to copy or cut it out. But I don't know-how. Instead, I have to change back to normal mode, highlight it again then cut it. I tried to Ctrl+O but it would get rid of the highlight. Does anyone know how to solve this?
highlighted text in insert mode

A: I have not used this extension, but when running vim natively, if you highlight stuff in insert mode, you can right-click and click on copy. Not sure whether this works in Visual Studio. However, reading the docs in GitHub I see there is a vim.handleKeys setting, that you can set in settings.json and you could specify C-c and C-v to be false in order to support Ctrl+c and Ctrl+v natively. The doc provides this example:
"vim.handleKeys": { "<C-f>": false }

which in your case would look like this:
"vim.handleKeys": {
    "<C-c>": false,
    "<C-d>": false
}


text:
Q: How to capture captcha image object with DotNetBrowser The website we have shown on DotNetBrowser contains a captcha image element. What is the method of capturing this element image type in code element?
Web site address: https://paydas.its.gov.tr/hesap_yonetimi/giris
browserView = new WinFormsBrowserView(BrowserFactory.Create(BrowserType.LIGHTWEIGHT));
//...
browserView.Browser.SetSize(1024, 768);
Bitmap screenshot = browserView.Browser.ImageProvider.GetImage() as Bitmap;
DOMElement captchaElement = browserView.Browser.GetDocument().GetElementById("imgCaptcha");
pictureBox1.Image = screenshot?.Clone(captchaElement.BoundingClientRect, screenshot.PixelFormat);

This method does not work healthy.

A: I found a solution.
I've added the following code snippet after creating the Browser object.
int viewHeight = 20000;
            string[] switches = {
                    "--disable-gpu",
                    "--max-texture-size=" + viewHeight
            };
BrowserPreferences.SetChromiumSwitches(switches);


text:
Q: Python: check every word in each line of a list, and check that word is the same as a key in a dictionary this is my basic code.
for key in dictionary: #Here key is the actually variable defined in key:value pair
  for line in list:
    if key in line:
        print key

error value I get in return is
if key in line:
TypeError: coercing to Unicode: need string or buffer, int found
I used this to encode Non-ascii values
unicode = u"\xc3\x81"
encoded= unicode.encode('utf-8')

I noticed that some of the type(key) were int so I hope to above code fixed that.
I have look through many resources and haven't been convinced of a way to check each word in a list for the keyword string in a dictionary.
Also I have been told not to make the dictionary a list via dictionary.keys()
or vice versa with the list.

A: It appears there is some code missing. Most likely what is happening is that somewhere in your code you are concatenating a unicode string and an int:
a = u"unicode str"
b = 5

print(a + b)

On a side note - regarding the code:
unicode = u"\xc3\x81"
encoded= unicode.encode('utf-8')

This doesn't look right. Your first line is definitely not unicode - it's probably UTF-8, and you want to decode instead.
unicode = "\xc3\x81"
encoded = unicode.decode('utf-8')
print encoded  # prints Á

A: Assuming you have something like:
mydict = {"is": 1, "the": 2}

and
list = ["Line is the first", "Line is the second",]

You should try:
>>> for line in list:
    for w in line.split(" "):
       print("Word", w, " in key list:", w in mydict.keys())

('Word', 'Line', ' in key list:', False)
('Word', 'is', ' in key list:', True)
('Word', 'the', ' in key list:', True)
('Word', 'first', ' in key list:', False)
('Word', 'Line', ' in key list:', False)
('Word', 'is', ' in key list:', True)
('Word', 'the', ' in key list:', True)
('Word', 'second', ' in key list:', False)
>>>

Usually Python will handle the unicode for you so that you should be able to compare the strings without you having to worry.


text:
Q: Fréchet derivative of the total variation norm for measures on a manifold Let $\Theta$ be a compact $d$-dimensional Riemannian manifold without boundary and $M(\Theta)$ (resp. $M_+(\Theta)$) denote the set of signed (resp. nonnegative) finite Borel measures on $\Theta$.

What is the Fréchet derivative of the total variation norm given below?
$$
\| \cdot \|_{\text{TV}} \colon M(\Theta) \to \mathbb{R}_{\ge 0}, \qquad
\mu \mapsto \| \mu \|_{\text{TV}}
$$
Is it even differentiable in $\mu = 0$?

Context: in the paper L. Chizat - Sparse Optimization on Measures with Over-parametrized Gradient Descent the following setting (A1) is considered:
Let $F$ be a Hilbert space and $\phi \colon \Theta \to F$ and $R \colon F \to \mathbb{R}$ each be twice Fréchet differentiable with locally Lipschitz second order derivatives such that $\nabla R$ is bounded on sublevel sets.
(Does this mean on the sublevel sets of $R$?)
Chizat claims on page 5 that

the objective
\begin{equation*}
J \colon M_+(\Theta) \to \mathbb R, \qquad
    \nu \mapsto R\left(\int_{\Theta} \phi(\theta) \text{d}\nu(\theta)\right) + \lambda \| \nu \|_{\text{TV}},
\end{equation*}
which can easily be extended to $M(\Theta)$ (see Appendix A in that paper, which is also available on arXiv), is Fréchet differentiable and its differential at $\nu \in M(\Theta)$ can be represented by
$$
J^{'}_{\nu} \colon \Theta \to \mathbb{R}, \qquad
\theta \mapsto \left\langle \phi(\theta), \nabla R\left(\int_{\Theta} \phi(\theta) \text{d}\nu(\theta)\right) \right\rangle_{F} + \lambda
$$
in the sense that $\frac{d}{d \varepsilon} J(\nu + \varepsilon \sigma) \bigg|_{\varepsilon = 0} = \int_{\Theta} J_{\nu}^{'}(\theta) \text{d}\sigma(\theta)$.

Using that the Fréchet derivative is linear and just focussing on the second term (with $\lambda$), this would imply that $D \| \cdot \|_{\text{TV}}(\nu)[\sigma] = \| \sigma \|_{\text{TV}}$, where $D f(x)[h] \in Y$ is the Fréchet derivative of $f \colon X \to Y$ at $x \in X$ in direction $h \in X$.

We have that if $f$ is linear, then $D f(x)[h] = f(h)$ for all $x, h \in X$.
Does the converse also hold? If yes, this would imply that the total variation norm is linear, which is surely not true.

A: What you've written here is inconsistent with what I remembered from the paper. So I followed both links (Springer & arXiv). Your definition for $J$ here is not what's in the paper.
First, $J$ in page 5 of arXiv or 6 of Springer is defined on $M$ not $M_+$ ($M_+$ would be wrong here since it's not a vector space but $M$ is.) It's the optimization that is over $M_+$.
Second, the last term in $J$ is the total mass $\nu(\Theta)$ not $||\nu||$. The norm in a Banach space is not in general Fréchet differentiable. There it is differentiating $\nu\mapsto \nu(\Theta)$, not the total variation $\nu\mapsto ||\nu||$, w.r.t to $\nu$, which is 1. That is for $J(\nu)=\nu(\Theta)=\int_\Theta d\nu(\Theta)$, $J$ is linear on $M$ so its derivative is itself; $dJ_\nu(\sigma)=\sigma(\Theta)=\int_\Theta 1 d\sigma(\Theta)$, compare that with the definition of $J'_\nu(\Theta)$, you get $J'_\nu(\Theta)=1$.


text:
Q: Can't install nvidia-driver-455 (upgrade from 450 version) I have a Linux Mint 20 Cinnamon Nvidia-based (GTX 1060) system and would like to install the latest Nvidia drivers now when I noticed they're out.
However, I can't seem to be able to install it with:
apt-get --dry-run install nvidia-driver-455

which throws up the following:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 nvidia-driver-455 : Depends: libnvidia-extra-455 (= 455.38-0ubuntu0.20.04.1) but it is not going to be installed
                     Depends: nvidia-compute-utils-455 (= 455.38-0ubuntu0.20.04.1) but it is not going to be installed
                     Depends: libnvidia-encode-455 (= 455.38-0ubuntu0.20.04.1) but it is not going to be installed
                     Depends: nvidia-utils-455 (= 455.38-0ubuntu0.20.04.1) but it is not going to be installed
                     Depends: xserver-xorg-video-nvidia-455 (= 455.38-0ubuntu0.20.04.1) but it is not going to be installed
                     Depends: libnvidia-ifr1-455 (= 455.38-0ubuntu0.20.04.1) but it is not going to be installed
                     Recommends: libnvidia-compute-455:i386 (= 455.38-0ubuntu0.20.04.1)
                     Recommends: libnvidia-decode-455:i386 (= 455.38-0ubuntu0.20.04.1)
                     Recommends: libnvidia-encode-455:i386 (= 455.38-0ubuntu0.20.04.1)
                     Recommends: libnvidia-ifr1-455:i386 (= 455.38-0ubuntu0.20.04.1)
                     Recommends: libnvidia-fbc1-455:i386 (= 455.38-0ubuntu0.20.04.1)
E: Unable to correct problems, you have held broken packages.

I don't have any held packages, nor do I have any residual configurations.

Currently, I am running version 450 without any problems on kernel 5.4.0-54-generic. So, what should I do now? How to investigate this?

A: Issue resolved, for some reason, there remained installed a meta-package of previously installed version: nvidia-driver-440. Reproduced on 3 laptops already, the offending package stays the same and is blocking the Nvidia from updating.

After updating the OS as a whole, I rebooted, and issued:
apt-get purge nvidia-driver-440

with result:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED:
  nvidia-driver-440*
0 upgraded, 0 newly installed, 1 to remove and 1 not upgraded.
After this operation, 19.5 kB disk space will be freed.
Do you want to continue? [Y/n]
(Reading database ... 438621 files and directories currently installed.)
Removing nvidia-driver-440 (450.80.02-0ubuntu0.20.04.2) ...

Now the dry run above seems to be Ok. The installation as root with:
apt-get --install-recommends install nvidia-driver-455

went smoothly and my system booted up without any problem now.

Visual proof (Mint's Driver Manager):


text:
Q: Sequelize - MySQL error: SELECT list is not in GROUP BY clause I have this function which returns the categories containing the product with the lowest price.
async getAllWithMinPrice(req, res, next) {
  try {
    const categories = await Category.findAll({
      attributes: ["id", "name"],
      group: ["products.id"],
      include: [
        {
          model: Product,
          attributes: [
            "id",
            "name",
            "pluralName",
            "description",
            "image",
            [Sequelize.fn("MIN", Sequelize.col("price")), "minPrice"],
          ],
          include: [
            {
              model: Type,
              attributes: [],
            },
          ],
        },
      ],
    });
    return res.json(categories);
  } catch (e) {
    return next(ApiError.badRequest(e.message ? e.message : e));
  }
}

But I am getting an error: "Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'fotoluks.category.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by".
On my test server, I just disabled ONLY_FULL_GROUP_BY in MySQL, but I don't have permission to do so on the current server.
As far as I understand, to solve this problem, you need to use any_value, but I just can't figure out how to do it in Sequelize.
P.S. In a similar function, I had exactly the same error, then I solved it by simply adding attributes: [], but in this case I can't do it.

A: you need to include those attributes in group by:
      where: { //condition },
      attributes: [
       "provider_id",
       "product_id",
       "quantity",

      [Sequelize.fn("sum", Sequelize.col("product_price")),"total_amount"],

  ],

  group: ["provider_id", "product_id", "quantity"],


text:
Q: Meaning of Trending and Most Viewed I can't seem to figure it out  how files are actually classified based on these two options.
I guess the files the are mostly open go under most viewed. What about trending items ?
Does anyone have more information on how data gets categorized based on these two Standards?

A: Popularity Trending is used to identify at what times activity is high or low, it's more of a time range activity at different levels - Site Collection, Site and Library/List Item. The reports are formed daily or monthly.
Most Viewed is focused on items at List/Library level. You can sort the list by Recent (the last 14 days), or Ever.
References.
Popularity Trends and Most Popular Items reports in SharePoint 2013.
View Popularity Trends and Most Popular Items.


text:
Q: Deploying some files in .gitignore to AWS Elastic Beanstalk Knowing that eb deploy will deploy anything in your git repo, what is the best way to include files in that are included in .gitignore? I.e. config scripts with credentials etc.
Thanks in advance!

A: The answer is creating an .ebignore file. Here is how it works:
If you have my_keys.php in your .gitignore because you don't want to commit it because of sensitive info, create an .ebignore file and only add files that you don't want to be distributed to your instances.
If you don't add my_keys.php to your .ebignore, it will compile it and distribute while .gitignore will keep it out of your remote repo.
This behavior is explained in AWS docs:

If .ebignore isn't present, but .gitignore is, the EB CLI ignores
  files specified in .gitignore. If .ebignore is present, the EB CLI
  doesn't read .gitignore.


text:
Q: dpkg: How to remove a package and all other packages which depend on it? I tried to remove KDE from my system.
When I run dpkg -r kdebase-bin, it says kdebase-data depends on it. So how can I remove all the packages related to KDE?

A: Unlike apt-get, aptitude can recursively remove packages which were installed as dependencies, but which are no longer depended on when the requested removal happens.  You have to have installed those packages with aptitude in order for this to work, though.
There are also tools like deborphan which can identify packages which may no longer be necessary on your system, even if you didn't use aptitude to install them.  However, you have to supply it with a list of packages you do want on your system, but it's usually a quick job (there will be fewer packages it has to ask about than you might imagine).

A: Usually one uses a higher-level utility instead of dpkg. You can use apt-get to remove a package and all its dependencies.
apt-get remove <package>

A: dpkg -r --force-depends  $pkg
apt-get install -f

A: To remove package and its dependencies, use purge
Check all dependencies with following command
# sudo dpkg --list | grep <package-name>

Remove packages and its dependencies
# sudo apt purge <package>


text:
Q: SQL where to query in Rails When I type:
User.where(:created_at => "2015-08-06".."2015-08-07").where("updated_at > created_at + 1.day").count

Error Returned:
SELECT COUNT(*) FROM `users` WHERE `users`.`created_at` BETWEEN '2015-08-06' AND '2015-08-07' AND (updated_at > created_at + 1.day)ActiveRecord::StatementInvalid: Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'day)' at line 1: SELECT COUNT(*) FROM `users`  WHERE `users`.`created_at` BETWEEN '2015-08-06' AND '2015-08-07' AND (updated_at > created_at + 1.day)

from /home/guinness/shared/bundle/ruby/2.1.0/gems/activerecord-3.2.13/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:245:in query'

What's wrong with this? As you know I want to know how many users retained after 1 day of their sign up.

A: 1.day is ruby syntax, not sql.  try this:
 User.where(:created_at => "2015-08-06".."2015-08-07").where("updated_at > DATE_ADD(created_at, INTERVAL 1 DAY)").count

see http://www.w3schools.com/sql/func_date_add.asp

A: Try it like this
User.where(:created_at => "2015-08-06".."2015-08-07").where("updated_at > ?", created_at + 1.day).count


text:
Q: Multi-GPU training of AllenNLP coreference resolution I'm trying to replicate (or come close) to the results obtained by the End-to-end Neural Coreference Resolution paper on the CoNLL-2012 shared task. I intend to do some enhancements on top of this, so I decided to use AllenNLP's CoreferenceResolver. This is how I'm initialising & training the model:
import torch
from allennlp.common import Params
from allennlp.data import Vocabulary
from allennlp.data.dataset_readers import ConllCorefReader
from allennlp.data.dataset_readers.dataset_utils import Ontonotes
from allennlp.data.iterators import BasicIterator, MultiprocessIterator
from allennlp.data.token_indexers import SingleIdTokenIndexer, TokenCharactersIndexer
from allennlp.models import CoreferenceResolver
from allennlp.modules import Embedding, FeedForward
from allennlp.modules.seq2seq_encoders import PytorchSeq2SeqWrapper
from allennlp.modules.seq2vec_encoders import CnnEncoder
from allennlp.modules.text_field_embedders import BasicTextFieldEmbedder
from allennlp.modules.token_embedders import TokenCharactersEncoder
from allennlp.training import Trainer
from allennlp.training.learning_rate_schedulers import LearningRateScheduler
from torch.nn import LSTM, ReLU
from torch.optim import Adam

def read_data(directory_path):
    data = []
    for file_path in Ontonotes().dataset_path_iterator(directory_path):
        data += dataset_reader.read(file_path)
    return data

INPUT_FILE_PATH_TEMPLATE = "data/CoNLL-2012/v4/data/%s"
dataset_reader = ConllCorefReader(10, {"tokens": SingleIdTokenIndexer(),
                                       "token_characters": TokenCharactersIndexer()})
training_data = read_data(INPUT_FILE_PATH_TEMPLATE % "train")
validation_data = read_data(INPUT_FILE_PATH_TEMPLATE % "development")

vocabulary = Vocabulary.from_instances(training_data + validation_data)
model = CoreferenceResolver(vocab=vocabulary,
                            text_field_embedder=BasicTextFieldEmbedder({"tokens": Embedding.from_params(vocabulary, Params({"embedding_dim": embeddings_dimension, "pretrained_file": "glove.840B.300d.txt"})),
                                                                        "token_characters": TokenCharactersEncoder(embedding=Embedding(num_embeddings=vocabulary.get_vocab_size("token_characters"), embedding_dim=8, vocab_namespace="token_characters"),
                                                                                encoder=CnnEncoder(embedding_dim=8, num_filters=50, ngram_filter_sizes=(3, 4, 5), output_dim=100))}),
                            context_layer=PytorchSeq2SeqWrapper(LSTM(input_size=400, hidden_size=200, num_layers=1, dropout=0.2, bidirectional=True, batch_first=True)),
                            mention_feedforward=FeedForward(input_dim=1220, num_layers=2, hidden_dims=[150, 150], activations=[ReLU(), ReLU()], dropout=[0.2, 0.2]),
                            antecedent_feedforward=FeedForward(input_dim=3680, num_layers=2, hidden_dims=[150, 150], activations=[ReLU(), ReLU()], dropout=[0.2, 0.2]),
                            feature_size=20,
                            max_span_width=10,
                            spans_per_word=0.4,
                            max_antecedents=250,
                            lexical_dropout=0.5)

if torch.cuda.is_available():
    cuda_device = 0
    model = model.cuda(cuda_device)
else:
    cuda_device = -1

iterator = BasicIterator(batch_size=1)
iterator.index_with(vocabulary)
optimiser = Adam(model.parameters(), weight_decay=0.1)
Trainer(model=model,
        train_dataset=training_data,
        validation_dataset=validation_data,
        optimizer=optimiser,
        learning_rate_scheduler=LearningRateScheduler.from_params(optimiser, Params({"type": "step", "step_size": 100})),
        iterator=iterator,
        num_epochs=150,
        patience=1,
        cuda_device=cuda_device).train()

After reading the data I've trained the model but ran out of GPU memory: RuntimeError: CUDA out of memory. Tried to allocate 4.43 GiB (GPU 0; 11.17 GiB total capacity; 3.96 GiB already allocated; 3.40 GiB free; 3.47 GiB cached). Therefore, I attempted to make use of multiple GPUs to train this model. I'm making use of Tesla K80s (which have 12GiB memory).
I've tried making use of AllenNLP's MultiprocessIterator, by itialising the iterator as MultiprocessIterator(BasicIterator(batch_size=1), num_workers=torch.cuda.device_count()). However, only 1 GPU is being used (by monitoring the memory usage through the nvidia-smi command) & got the error below. I also tried fiddling with its parameters (increasing num_workers or decreasing output_queue_size) & the ulimit (as mentioned by this PyTorch issue) to no avail.
Process Process-3:
Traceback (most recent call last):
  File "/usr/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
Traceback (most recent call last):
  File "/usr/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib/python3.6/multiprocessing/process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "/home/user/.local/lib/python3.6/site-packages/allennlp/data/iterators/multiprocess_iterator.py", line 32, in _create_tensor_dicts
    output_queue.put(tensor_dict)
  File "/usr/lib/python3.6/multiprocessing/process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "/home/user/.local/lib/python3.6/site-packages/allennlp/data/iterators/multiprocess_iterator.py", line 32, in _create_tensor_dicts
    output_queue.put(tensor_dict)
  File "<string>", line 2, in put
  File "<string>", line 2, in put
  File "/usr/lib/python3.6/multiprocessing/managers.py", line 772, in _callmethod
    raise convert_to_error(kind, result)
  File "/usr/lib/python3.6/multiprocessing/managers.py", line 772, in _callmethod
    raise convert_to_error(kind, result)
multiprocessing.managers.RemoteError:
---------------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python3.6/multiprocessing/managers.py", line 228, in serve_client
    request = recv()
  File "/usr/lib/python3.6/multiprocessing/connection.py", line 251, in recv
    return _ForkingPickler.loads(buf.getbuffer())
  File "/home/user/.local/lib/python3.6/site-packages/torch/multiprocessing/reductions.py", line 276, in rebuild_storage_fd
    fd = df.detach()
  File "/usr/lib/python3.6/multiprocessing/resource_sharer.py", line 58, in detach
    return reduction.recv_handle(conn)
  File "/usr/lib/python3.6/multiprocessing/reduction.py", line 182, in recv_handle
    return recvfds(s, 1)[0]
  File "/usr/lib/python3.6/multiprocessing/reduction.py", line 161, in recvfds
    len(ancdata))
RuntimeError: received 0 items of ancdata
---------------------------------------------------------------------------

I also tried achieving this through PyTorch's DataParallel, by wrapping the model's context_layer, mention_feedforward, antecedent_feedforward with a custom DataParallelWrapper (to provide compatibility with the AllenNLP-assumed class functions). Still, only 1 GPU is used & it eventually runs out of memory as before.
class DataParallelWrapper(DataParallel):
    def __init__(self, module):
        super().__init__(module)

    def get_output_dim(self):
        return self.module.get_output_dim()

    def get_input_dim(self):
        return self.module.get_input_dim()

    def forward(self, *inputs):
        return self.module.forward(inputs)

A: After some digging through the code I found out that AllenNLP does this under the hood directly through its Trainer. The cuda_device can either be a single int (in the case of single-processing) or a list of ints (in the case of multi-processing):

cuda_device : Union[int, List[int]], optional (default = -1)
  An integer or list of integers specifying the CUDA device(s) to use. If -1, the CPU is used.

So all GPU devices needed should be passed on instead:
if torch.cuda.is_available():
    cuda_device = list(range(torch.cuda.device_count()))
    model = model.cuda(cuda_device[0])
else:
    cuda_device = -1

Note that the model still has to be manually moved to the GPU (via model.cuda(...)), as it would otherwise try to use multiple CPUs instead.


text:
Q: Python leaks memory if I read a tuple instead of single value I'm querying whether a key exists in a RocksDB database using Python. The API (see bottom) implies it returns a two-element tuple. So I receive both tuple elements:
def contains_key(database: rocksdb, key: int) -> bool:
    found, data = database.key_may_exist(key)
    return found

and I am using it like this:
if not contains_key(database, key):

However, this causes a memory leak.
To prove this, if I change the code to:
def contains_key(database: rocksdb, key: int) -> bool:
    return database.key_may_exist(key)

there is no leak (but it's obviously not correct).
How do I get the first version to work without a memory leak?

A: Your code
def contains_key(database: rocksdb, key: int) -> bool:
    found, data = database.key_may_exist(key)
    return found

does not contain a memory leak.
found and data are two names in the local scope, and both refer to values that exist in a single area of memory. When the function returns, found and data go out of scope. What found referred to can be referred to by the caller (x = contains_key(db, 3)), but data is ignored. Since no other reference to that object exists, Python (as a garbage-collecting language) reclaims whatever resources were devoted to data automatically.
For that matter, the key_may_exist method returns a tuple that you never safe a reference to. It is immediately unpacked, with found and data referring to whatever that tuple referred to. The tuple itself is garbage-collected, but the references to its contents remain.


text:
Q: Wordpress Genesis Theme Wrong MIME Type I built a childtheme based on the Wordpress Genesis Theme. I deployed it on my testing server and it worked. When I uploaded it to the client's site though, it breaks.
The problem is with loading the stylesheet from the childtheme. The error is:

Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://buyinginbergen.com/wordpress/wp-content/themes/CustomBergenTheme/style.css/?ver=1.9.0".

Obviously the site is http://buyinginbergen.com/wordpress/. I haven't been able to figure out how to specify the file type, especially because I don't have FTP access so I had to build elsewhere before deploying.
Thoughts?

A: We had a similiar issue - the mime type of the css files the server sent back were wrong. We solved it by adding:
AddType text/css .css

to the .htaccess file in the wordpress root folder.