text:
Q: How to run C++ application in Android SHELL I want to run hello world written on C++ and compiled with Android toolchain 9, but I faced with issue: by default I have no permissions to launch it and I can't change permissions using chmod`.
I used Android 2.3.3 - Api Level 10
Application was compiled by cross compiler for API level 9
Procedure:
Compile application:

~/toolchain_andr9/bin/  arm-linux-androideabi-g++ helloworld.cpp

Then send application to SDCARD on the emulator:
>adb push a.out /mnt/sdcard

then go to SHELL and try to run a.out:
>adb shell
>
>/mnt/sdcard/a.out

And result is:
>`/mnt/sdcard/a.out: permission denied`

command ls -l shows rights for a.out:
>`----rwxr-x system   sdcard_rw   863656 2012-04-12 22:42 a.out`

I tried to change permissions:
>chmod 777 /mnt/sdcard/a.out

But rights don't change:
>`----rwxr-x system   sdcard_rw   863656 2012-04-12 22:42 a.out`

I think I have left some important thing using android.
Could anybody help me and give me a way how to run application in `Android SHELL?
Thanks a lot.
P.S. sorry for my English =)

A: If you have rooted your phone you can do a mount -o remount,rw /mnt/sdcard and it should run.
I've tried it on my Android.

A: By default, the SD card is mounted with option noexec, that disallows the execution of any file on the card, no matter what it's permissions(even -rwxrwxrwx), so you need to move the file to another location and then execute it.
The easiest is to move the file to /data/local/tmp/ and execute it using the full path (usual POSIX PATH semantics).
> adb push a.out /data/local/tmp/a.out
> adb shell
> chmod 755 /data/local/tmp/a.out
> /data/local/tmp/a.out

This does not require root access and survives reboot.


text:
Q: What is the most efficient way to store images feature vector? I'm working on project that needs to deal with images, I extract their feature vector instantly when any image uploaded then I store the feature vectors in MySQL database as text per each image.
Also I'm using django framework.
def search_images_by_features(query_image: ImageFieldFile, images):
    featured_images = [
        (calculate_similarity(load_features_from_str(image.features), get_image_feature(query_image)), image.item) for image in
        images if image.features is not None]
    ...

But looping on each image isn't a big deal as it takes more time as images increase.
Also my feature vector in database stored like that:
0.0010601664,0.0003533888,0.8969008,0.0014135552,...

Also is there a way to make MySQL database engine calculate similarity from feature vectors?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Yii - How to use a class inside config/main? 'urlManager'=>array(
        'urlFormat'=>'path',
        'rules'=>array(
                'gii'=>'gii',
                'gii/<controller:\w+>'=>'gii/<controller>',
                'gii/<controller:\w+>/<action:\w+>'=>'gii/<controller>/<action>',
                '(' . implode('|', EventType::$TYPES_TO_URL) . ')' => 'home/index',

In the code above, I try to use a static variable of EventType class, to create a regex for urlManager's rules. But I get the errors:
Warning: include(EventType.php): failed to open stream: No such file or directory in /Users/trmop/Sites/test.dev/Yii-1-1-14/YiiBase.php on line 427

Warning: include(): Failed opening 'EventType.php' for inclusion (include_path='.:/Applications/MAMP/bin/php/php5.4.19/lib/php') in /Users/trmop/Sites/test.dev/Yii-1-1-14/YiiBase.php on line 427

Fatal error: Class 'EventType' not found in /Users/trmop/Sites/test.dev/app/config/main.php on line 72

It seems that Yii has not loaded the classes yet.
I could do include(dirname(__FILE__) . '../../models/EventType.php');, but it does not seem a clean solution.
Is there a better way to do it using Yii's features?

A: May be this can help you out.
Register Autoloader
Also you can import your class
import'=>array(
    'application.models.*',
    'application.components.*',
),


text:
Q: Method chaining and returning value from method this is a general question about Python class method chaining. I have a class that performs some data wrangling operations and returns a dataframe for the methods. I'm trying to method chain using the methods after creating the dataframe object, much like Pandas does. However, I seem to be running into some issues. Here's a simple example of a couple of methods in the class:
class Data:

    def __init__(self, df):
        self.df = df

    def remove_rows(self, col):
        df = (perform_some_operations)
        return df

    def collapse(self, cols):
        df = (perform_some_operations)
        return df

So I can use this like so:
df = Data(df)
df = df.remove_rows(col_1)
df = df.collapse(col_1)

However, if I want to use it like:
df = df.remove_rows(col_1).collapse(col_1)

I will get errors. Now if I returned self from these methods, I am able to chain them together, but the output is the Data object instead of a dataframe.
In Pandas, you are able to, for example do the following:
df = pd.read_csv('data.csv')
df = df.rename(columns={'col_1':'COL_1'}).drop(columns=['COL_1'])

and also
df = df.rename(columns={'col_1':'COL_1'})
df = df.drop(columns=['COL_1'])

I would like to understand how I can create methods that allow me to both chain operations but also use them separately to get values if I need to. I did some research and it seems like you can do one or the other, but if you take Pandas for example, you are able to do both.

A: You need to use self.df in methods
Like this:
class Data:

    def __init__(self, df):
        self.df = df

    def remove_rows(self, col):
        self.df = (perform_some_operations)
        return self.df

    def collapse(self, cols):
        self.df = (perform_some_operations)
        return self.df


text:
Q: Is there a non-boostrap way to estimate confidence intervals for Kernel regression predictions? Simple problem of estimating:
$$ y = f(x) + \epsilon $$
Where I use your standard Nadaraya-Watson Regression to guess $f(x)$. This is relatively fast and works well even in an online setting.
Now I use the regression to predict $y'$ at $x'$. However in my use case I'd really like to get a confidence interval around my predicted $\hat y'$.
Usually I'd solve this by bootstrap, but for my application it is just too computationally expensive (it is an online problem where a stream of data keeps coming in and I just can't stop to do bootstrap at each step).
Is there an approximative way to get a prediction error interval? It seems like I should be able to say "this prediction is far away from where I have the data so my confidence is low".
 Any help?

A: Under non-fixed-design $x$'s, [Härdle][1] (p136) gives an asymptotic distributional approximation relating to the Nadaraya-Watson estimator $\hat{m}(x_j)$:
$(nh)^\frac12 \frac{\hat{m}_h(x_j)-m(x_j)}{V(x_j)^\frac12} \stackrel{.}{\sim} N(B(x_j),1)$
where $V(x_j) = \sigma^2(x_j)||K||_2^2/f(x_j)$ and $B(x_j) = \mu_2(K)[m''(x_j)+2m'(x_j)f'(x_j)/f(x_j)]$,
with $\sigma^2(x_j)$ being the conditional noise variance, $f(x_j)$ being the density of $X$ at $x_j$, $||K||_2^2 = \int K^2(u) du$, $\mu_2(K) = \int u^2 K(u) du$.
(Actually he gives the multivariate distribution over $k$ different locations but since you seem to only need it pointwise, I believe the univariate case suffices)
Note that $V$ is the variance of the estimate of $m$. The approximate predictive variance would then add the observation noise variance $\sigma^2(x_j)$ to give $V^p(x_j)=\sigma^2(x_j)+V(x_j)$. The MSPE at $x_j$ is the sum of the variance and the square of the bias, so an asymptotic approximation for that is $V^p(x_j)+B(x_j)^2$.
The bias term, $B$ involves derivatives of both $m$ and $f$ and so is somewhat complicated to evaluate/estimate (but should be doable, nonetheless).
Some people make the assumption that $B$ is small relative to the variance and ignore it; this would give a lower bound on the prediction error variance.
Härdle gives estimators for $\sigma^2(x)$ and $f(x)$ based on NW-kernel regression from the squared error and kernel density estimation respectively (all using the same bandwidth) and he gives tables for $\mu_2(K)$ and $||K||_2^2$ on p220 (the kernels themselves are defined on p45).
For the Gaussian case
$\mu_2(K)=1$ and $||K||_2^2=\frac{1}{2\sqrt{\pi}}$.
[1]: Härdle, W. (1991),
Smoothing Techniques - With Implementation in S,
Springer Series in Statistics,
Springer-Verlag New York


text:
Q: MySQL Slow Query Magento 2 Can you please help me to resolve the below slow query from MySQL?
SELECT `queue_message`.`topic_name`, `queue_message`.`body`, `queue_message_status`.`id` AS `relation_id`,
`queue_message_status`.`queue_id`,
`queue_message_status`.`message_id`, `queue_message_status`.`status`,
`queue_message_status`.`updated_at`, `queue_message_status.message_id`
INNER JOIN `queue` ON queue.id = queue_message_status.queue_id
WHERE (queue_message_status.status IN (2, 5))
  AND (queue.name = 'codegenerator')
ORDER BY `queue_message_status`.`updated_at` ASC,
  `queue_message_status`.`id` ASC
LIMIT 1;

Thank you in advance!


text:
Q: Calculating $\int_{- \infty}^{\infty} \frac{\sin x \,dx}{x+i} $ I'm having trouble calculating the integral
$$\int_{- \infty}^\infty \frac{\sin x}{x+i}\,dx $$
using residue calculus. I've previously encountered expressions of the form
$$\int_{- \infty}^\infty f(x) \sin x \,dx $$
where you would consider $f(z)e^{iz}$ on an appropriate contour (half circle), do away with the part of the contour that wasn't on the real axis by letting the radius go to infinity, then recover the imaginary part of the answer to get back the sine. However here, I can't replace the sine with $e^{iz}$ in my complex function because $$\operatorname{Im} \frac{e^{ix}}{x+i} \neq \frac{\sin x}{x+i}\cdots$$
How to remedy this? I'm not sure if substituting $\sin x = \frac{1}{2i}(e^{ix}-e^{-ix})$ and solving two integrals is how this problem is meant to be solved, although I'm 99% sure it would work

A: You're on the right track.  Rewrite $\sin{x}=(e^{i x}-e^{-i x})/(2 i)$, but evaluate separately.  For $e^{i x}$, consider
$$\frac{1}{2 i}\oint_{C_+} dz \frac{e^{i z}}{z+i}$$
where $C_{+}$ is the semicircle of radius $R$ in the upper half plane.  The integral is then zero because the pole at $z=-i$ is outside the contour.  Thus, by Jordan's lemma, we have
$$\int_{-\infty}^{\infty} dx \frac{e^{i x}}{x+i}=0$$
For the other piece, consider
$$\frac{1}{2 i}\oint_{C_-} dz \frac{e^{-i z}}{z+i}$$
where $C_{-}$ is the semicircle of radius $R$ in the lower half plane.  By Jordan's lemma and the residue theorem,
$$-\int_{-\infty}^{\infty} dx \frac{e^{-i x}}{x+i}= i 2 \pi e^{-i (-i)} = \frac{i 2 \pi}{e}$$
Note the minus sign before the integral because we require the contour to be traversed in a positive sense (counterclockwise).  Therefore
$$\int_{-\infty}^{\infty} dx \frac{\sin{x}}{x+i} = \frac{1}{2 i} \frac{i 2 \pi}{e} = \frac{\pi}{e}$$

A: Using the identity $\sin(x)=\frac{1}{2i}(e^{ix}-e^{-ix})$ and separating into two integrals is a very reasonable way to solve this problem, and I would imagine it's the easiest way. For comparison, I want to describe another possibility, which involves separating $\frac{1}{x+i}$ into its real and imaginary parts.
We have
$$
\frac{1}{x+i}=\frac{x-i}{x^2+1}=\frac{x}{x^2+1}-i\frac{1}{x^2+1},
$$
so we can break up our integral as a sum in the following way:
\begin{eqnarray*}
\int_{-\infty}^{\infty}\frac{\sin(x)}{x+i}\,dx&=&\int_{-\infty}^\infty\frac{x\sin(x)}{x^2+1}\,dx-i\int_{-\infty}^\infty\frac{\sin(x)}{x^2+1}\,dx\\
&=&\mathrm{Im}\int_{-\infty}^\infty\frac{xe^{ix}}{x^2+1}\,dx-i\cdot\mathrm{Im}\int_{-\infty}^\infty \frac{e^{ix}}{x^2+1}\,dx.
\end{eqnarray*}
Both of these integrals can be evaluated using the method of contours.
I don't necessarily think this is easier than writing $\sin(x)=\frac{1}{2i}(e^{ix}-e^{-ix})$.


text:
Q: If a dependency is not in the maven repository should I add it to source control? One of the jar files that I use in my code is not in the maven repository(and yes I tried to avoid using it). I have installed it locally so when I build the project it gets picked up by maven. I also put instructions in my README so anyone who wants to build my code can see how to add the jar to their local repository.
The question is, should I check this jar into my git source control?
I know normally you don't check jars into source when using maven and git but in this case it seems like it might be a better idea than saying, find this jar on the internet.
I am the only developer in my group so setting up a company hosted repository for just this single jar is overkill.

A: If it is just a single JAR file, then I don't think version controlling it will be apocalyptic.
If however, you start adding more and more external JAR files to your app, then you should consider using a repo manager like artifactory to deal with this whether you opt to use Gradle/Maven/ANT.
If you have a build script, you can further simplify the task of building the app by automating the process of checking out the JAR from GIT and making it available.  This might be a little easier as it puts the onus on you, the author, to manage the dependency opposed to the library user. You can also upgrade the library behind the scenes without the user being aware of it (unless there is no network connection..).


text:
Q: Django join unmanaged tables I have a four models which each contains their own data. The models are:

*

*Category (contains department_id foreign key)

*Department (contains data, no foreign key)

*ProductCategory (join table containing only product_id and category_id)

*Product (contains data with no foreign key)

# models.py (excluded the rest for brevity)

from django.db import models

class Department(models.Model):
    department_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=1000, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'department'

class Category(models.Model):
    category_id = models.AutoField(primary_key=True)
    #department_id = models.IntegerField()
    department = models.ForeignKey(Department, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=1000, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'category'

class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=1000)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    discounted_price = models.DecimalField(max_digits=10, decimal_places=2)
    image = models.CharField(max_length=150, blank=True, null=True)
    image_2 = models.CharField(max_length=150, blank=True, null=True)
    thumbnail = models.CharField(max_length=150, blank=True, null=True)
    display = models.SmallIntegerField()

    class Meta:
        managed = False
        db_table = 'product'

class ProductCategory(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

    class Meta:
        managed = False
        db_table = 'product_category'
        unique_together = (('product', 'category'),)

From my endpoint, I need to get all products in a department and return the response in the following format:
"rows": [
    {
      "product_id": integer,
      "name": string,
      "description": string,
      "price": string,
      "discounted_price": string,
      "thumbnail": string
    }
]

This is the endpoint:
path('products/inDepartment/<int:department_id>/', ProductViewSet.as_view({"get": "get_products_by_department"}))
How can I go about doing this? I'm stuck with the code below:
# products.py

def get_products_by_department(self, request, department_id):
        """
        Get a list of Products of Departments
        """
        categories = Category.objects.filter(department_id=department_id).values('category_id')

        for item in categories:
          category_id = item['category_id']
          products = ProductCategory.objects.filter(category_id=category_id).values(
            'product_id', name=F('product__name'), description=F('product__description'),
          price=F('product__price'), discounted_price=F('product__discounted_price'), thumbnail=F('product__thumbnail'))

        # Return response
        if products.exists():
          return Response(products, 200)
        else:
          return Response(products, 204)

The code above works and gives me the correct response but I'm not sure if I'm doing the query correctly? Should I be using a loop or is there a Django way to do it better without a loop?

A: Django's ORM allows for reverse relationship lookup.
https://docs.djangoproject.com/en/2.2/topics/db/queries/#lookups-that-span-relationships
categories = Category.objects.filter(department_id=department_id)
products = Product.objects.filter(productcategory__category__in=categories)


text:
Q: Question about $f(x+y)=f(x)f(y)$ Let $f(x)$ be a function increasing on $[0,+\infty)$ such that $f(0)\neq0$ and $f(x+y)=f(x)f(y)$, for any $x,y>=0$.
it is known that the following statements are true:

*

*$f(0)=1$

*$f(kx)=f(x)^k$ for any non-negative integer $k$.

*$f(n)=f(1)^n$ for any non-negative integer $n$.

*$1/a\le f(x)/(a^x)\le a$ where $a=f(1)$

I want to prove that it is impossible that $f(X)/(a^X)>1$ and $f(Y)/(a^Y)<1$ for some non-negative real numbers $X$ and $Y$ in order to show that $f(x)/a^x=1$ for any non-negative real number $x$ but have no clue. Can anyone help?

A: You know that $f(1)^n = f(n)$ for any non-negative integer $n$. Now, suppose that $f(1) = a>0$. Then, $f(\frac{n}{m}) = f(\frac{1}{m})^n$. Now, because $m * \frac{1}{m} = 1$, it follows that $f(1)=f(m*\frac{1}{m})=f(\frac{1}{m})^m$.
Hence, for all rational  numbers $\frac{n}{m}$, $f(\frac{n}{m}) = a^{\frac{n}{m}}$, which is well defined because $a$ is positive.
Assume continuity. Consider any real number $x$. Then, there exists a sequence of rational numbers converging to $x$, say $x_n \to x$. Now, since $f$ is densely defined, there is  a unique continuous extension to the reals, by saying $f(x) = \lim_{n \to \infty} f(x_n)$. This limit is $\lim_{n\to\infty } a^{x_n} = a^x$. Hence, $f(x) = a^x$, for any $a$ positive (if a were negative, then we would have problems in square rooting, for example)
It turns out that all solutions of the functional equation(including discontinuous ones) are differing from this only at the irrationals.However, adding even Lebesgue measurability gives a unique solution $a^x$.

A: I think i have figured out the proof.
Note that for any n$\in$$\Bbb R^+$, $[f(x)/(a^x)]^n=f(nx)/(a^nx)$.
Suppose there exits some $X$$\in$$\Bbb R^+$ such that $f(X)/(a^X)$$\gt$1.
Then $f(nX)/a^{nX}$$\gt$1.
$\Rightarrow$ $\lim_{n\to \infty}$[$f(X)/(a^X)]^n$=$+\infty$.
Then for the positive number $a$, there exists N$\in$$\Bbb N$ such that n>N $\Rightarrow$$[f(x)/(a^x)]^n$$\gt$$a$.
Hence $f((N+1)X)/(a^{(N+1)X})$$\gt$$a$, which contradicts to
$1/a\le f(x)/(a^x)\le a$
Proving another part is of similar idea.

A: From 4) you get
$$
a^{x-1}\le f(x)\le a^{x+1}
$$
Now apply that $f(x)=f(nx)^{1/n}$ to transform that initial inequality to
$$
a^{x-1/n}\le f(x)\le a^{x+1/n}
$$
which has to be true for all $1<n\in\Bbb N$. This is only possible for
$$
f(x)=a^x.
$$


text:
Q: Could not find package magento/upgrade-compatibility-tool with stability stable I am trying to install the Magento Upgrade Compatibility Tool on a Magento Enterprise 2.4.2  version. I am facing below error message while executing the command
composer create-project magento/upgrade-compatibility-tool uct --repository https://repo.magento.com

Error:
[InvalidArgumentException]
Could not find package magento/upgrade-compatibility-tool with stability stable.

I am following this docs Upgrade compatibility Tool
My auth keys are already present in the auth.json and it is a enterprise cloud project. Please help.

A: I had to check in the below composer path and update the auth keys.
cd /home/<user>/.config/composer

If you do not find auth.json file than create a file and add the keys.


text:
Q: How to use php and java apis on the same proxy server to interact with a remote application server through webservices I am having one proxy webserver and I was only using php APIs that interact with a remote application server. Now I want to use also java APIs and all I know is to install tomacat but I don't know how to configure my server to listen for php and java requests.
I will appreciate your tips. Thanks

A: Check out this great series about configuring and setting up a modern LEMP for PHP.
https://serversforhackers.com/s/lemp-stack-php-71
It will guide you on how to setup and configure your server in a secure manner which will also co-incide with Tomcat. Just remember to listen on different ports for Tomcat and PHP/nginx.

A: I finally realized that it's easy. Either I call files using the same same domain http://thesamedomain:8080 since my tomcat is listenning on port 8080. Or I use another domain and create vhost like this:

 ServerName predevjava.mcash.rw
ProxyPreserveHost On
 ProxyRequests off
ProxyPass / http://anotherdomain:8080/
ProxyPassReverse / http://anotherdomain:8080/

Remember tomcat files are by default located in /opt/tomcat/webapps
So any time you call http://samedomain it fetches php files (port 80 by default) and any time you http://samedomain:8080 it fetches java files in tomcat.
Or simply you call http://anotherdomain and it calls java files. As simple as that.


text:
Q: How to integrate a complex function which doesn't have any singularities? I am trying to solve this question.
$$\int_{0}^{2\pi}(\cos(z))^{6}dz$$
Usually when I try doing complex integration questions the function has a singularity and you are given a simple closed curve. So I am able to use Cauchy's Residue theorem or Cauchy's integral formula to evaluate the integral. The problem I'm having which this one is that they haven't given a function that has singularities and it isn't a simple closed curve either. I haven't run into this type of problem before and I'm not even sure where to begin. I was wondering whether someone can help on how to go about doing these types of questions. Sorry about not being able to show work I'm not sure where to start.

A: Firstly we can put: $\cos(z)=(e^{iz}+e^{-iz})/2$ ,
$$
\int_{0}^{2\pi}(\frac{e^{iz}+e^{-iz}}{2})^{6}dz
$$
$$
\frac{1}{2^6}\int_{0}^{2\pi}(e^{iz}+e^{-iz})^{6}dz
$$
$$
\frac{1}{2^6}\int_{0}^{2\pi}((e^{iz})^6+6(e^{iz})^5e^{-iz}+15(e^{iz})^4(e^{-iz})^2+20(e^{iz})^3(e^{-iz})^3+15(e^{iz})^2(e^{-iz})^4+6(e^{iz})(e^{-iz})^5+(e^{-iz})^6)dz
$$
$$
\frac{1}{2^6}\int_{0}^{2\pi}((e^{iz})^6+6(e^{iz})^4+15(e^{iz})^2+20+15(e^{-iz})^2+6(e^{-iz})^4+(e^{-iz})^6)dz
$$
"Now for first term $\frac{1}{2^6}\int_{0}^{2\pi}(e^{iz})^6dz$ , put $t=e^{iz}$ so $dt=i.e^{iz}dz$.
Hence, first term evaluates to (with changed limits)  $\frac{1}{i.2^6}\int_{0}^{1}t^5dt$ , which is equal to $\frac{1}{i.6.2^6}$ ."
Finally using this similar technique,
$$
\frac{1}{i.6.2^6}+\frac{6}{i.4.2^6}+\frac{15}{i.2.2^6}+\frac{40\pi}{2^6}+\frac{-15}{i.2.2^6}+\frac{-6}{i.4.2^6}+\frac{-1}{i.6.2^6}
$$
$$
\frac{5\pi}{8}
$$
Hence, the final answer is $\frac{5\pi}{8}$ .

A: Without any specification of an integration path, there is no reason to interpret the integral as anything more than it's face value. In other words, just ignore the fact that $z$ is complex. Just as @SahilKumar has shown elsewhere on this page, the integral is simply $5\pi/8$, just as if you integrated $\cos^6(\theta)$.
This is a good time to remind ourselves of the well-known solution for
$$
\int_0^{2\pi}\cos^n\theta\ d\theta=\frac{\pi}{2^{n-1}}
\left(
\begin{matrix}
n\\
n/2
\end{matrix}
\right)=\frac{\pi}{2^{n-1}}\frac{n!}{(n/2)!^2}
\ \ \ \text{for } n \text{ even}, \text{ and 0 (zero) otherwise}
$$


text:
Q: As I'm just a student, I don't have enough money to take a class that (takes / imposes) me high cost. -Can you help me find proper word to use here?
As I'm just a student, I don't have enough money to take a class that (takes / imposes) me high cost.

I don't know what word I have to use in this context. But I vaguely remember someone using takes in this situation. Can you help me find proper word to use here?

A: A typical idiomatic way to express this (in AmE) is:

*

*That class is too expensive—I can't afford it.

A: As other answers show, there are many ways of expressing the intended sense. But sticking as close as possible to OP's original suggestion...

I don't have enough money to take a class that imposes a high cost on me.

Here are a few hundred written instances where [something expensive] imposes a high cost on [those who pay for it], but note that there are even more instances of the plural form imposes high costs on (which would be equally acceptable in OP's example, and means the same thing).

A: There's no word you can put there that results in a grammatical sentence.  You could say:

As I'm just a student, I don't have enough money to take a class
  that costs me a lot.
As I'm just a student, I don't have enough money to take an
  expensive class.
As I'm just a student, I don't have enough money to take a class that
  has a high cost.

A: You can also use the word "demand".
As I'm just a student, I don't have enough money to take a class, which demands me high cost.


text:
Q: How to return a File in a WebService for Android in Java I've made a web service in java which should returns the content of a folder that is in my pc. I want to fill a list with the files name and when the user tap one, it will be donwload thane opened by my application. For the test, I just want to get at least the files name. I used the folowing code:
SimpleWebService:
@WebService
@SOAPBinding(style=Style.RPC)
public interface SimpleService {
   @WebMethod
   File getFiles();
}

SimpleWebServiceImpl:
@WebService(endpointInterface="com.medex.webServiceMegXsoft.SimpleService")
public class SimpleServiceImpl implements SimpleService{
    public File getFiles() {
        File directory = new
            File("C:\\Users\\student\\Desktop\\MegXsoftMobile\\");
        return directory;
    }
}

SimpleServicePublisher :
public class SimpleServicePublisher {
    public static void main(String[] args) {
        Endpoint.publish("http://192.168.0.58:9000/simple",
                new SimpleServiceImpl());
    }
}

And my receiver :
public class Receiver {

private final String NAME_SPACE = "http://192.168.0.71:9000/";
private final String URL = "http://192.168.0.71:9000/simple?wsdl";
private final String SOAP_ACTION = "\"getFiles\"";
private final String METHOD_NAME = "getFiles";
private Object resultsRequestSOAP;

public File getFilesFromXML() {
    SoapObject request = new SoapObject(NAME_SPACE, METHOD_NAME);
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER11);

    envelope.setOutputSoapObject(request);
    AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
    try
    {
        androidHttpTransport.call(SOAP_ACTION, envelope);
        resultsRequestSOAP =  envelope.getResponse();
    } catch (SoapFault e) {
        e.printStackTrace();
    }catch (XmlPullParserException e){
        e.printStackTrace();
    }catch (IOException e) {
        e.printStackTrace();
    }catch (Exception e){
        e.printStackTrace();
    }

    return (File)resultsRequestSOAP;
}

}
And finaly the Activity :
ArrayList<String> stringTable;
File files = null;
ProgressDialog dialog;
Thread thread;
Context context;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
    dialog = ProgressDialog.show(this, null, "loading", true, false);

    thread = new Thread(new Runnable() {
        public void run() {
            Receiver receiver = new Receiver();
            files = receiver.getFilesFromXML();
            dialog.dismiss();
        }
    });
    thread.start();

    final Handler h = new Handler();
    h.postDelayed(new Runnable() {

        public void run() {
            if (thread.getState() == Thread.State.TERMINATED) {
                int i = 0;

                stringTable = new ArrayList<String>();

                for (File file : files.listFiles()) {
                    stringTable.add(i, file.getName());
                    i++;
                }
                final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                        context, R.layout.item, stringTable);
                ListView listView = getListView();
                listView.setAdapter(adapter);

                listView.setOnItemClickListener(new OnItemClickListener() {

                    public void onItemClick(AdapterView<?> parent,
                            View view, int position, long id) {
                        System.out.println(stringTable.get(position));
                    }
                });

            }
            h.postDelayed(this, 1000);
        }
    }, 1000);
}

It seems to publish something as when I go to http://192.168.0.58:9000/simple?wsdl I have some lines in XML. But I feel like I can't receive the File in my android. I got this error:

06-20 13:55:55.759: W/System.err(13370): org.xmlpull.v1.XmlPullParserException: expected: END_TAG {http://schemas.xmlsoap.org/soap/envelope/}Body (position:END_TAG @1:290 in java.io.InputStreamReader@4053a7f0)

If someone have any idea how I could get the list of the files easier, your welcome :)
Where am I wrong?

A: Hmmm, don't know for sure, but I don't believe there is a real way to support a "file" construct in SOAP, but you might be able to construct a message with  mime encoded attachment(s). This link for a similar question on PHP servers lead to This description on how to do it in Java and Jax/RPC
Good luck!


text:
Q: Inject date picker on FullCalendar's Month/Year element Is there a way to inject/have a date-picker on FullCalendar's header where the Month/Year are displayed?
Snippet of full-calendar header with highlighted portion I am talking about
Thanks


text:
Q: How can I specify a condition on a PermissionEx in wix? I would like to conditionally add an ACE to a directory. The WiX documentation and XSD states that  is a valid child of util:PermissionEx, but I can't get it to work. Is it really supported?
I have this installer definition:
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
  xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">
  <Product Id="*" Name="test" Language="1033" Version="0.0.1" Manufacturer="Microsoft Corporation" UpgradeCode="89028746-7cf3-42e7-8121-d0bf0140e2dd">
    <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" Platform="x64" />

    <MediaTemplate EmbedCab="yes" />

    <Feature Id="ProductFeature" Title="test" Level="1">
      <ComponentRef Id="Component_TokenFolder_HybridAgent" />
    </Feature>

    <Property Id="ISDOMAINCONTROLLER" Value="0"/>
    <Property Id="SERVICEUSERGROUP" Value="foo"/>
    <InstallExecuteSequence>

    </InstallExecuteSequence>
  </Product>

  <Fragment>
    <Directory Id="TARGETDIR" Name="SourceDir">
      <Directory Id="CommonAppDataFolder">
        <Directory Id="AppDataFolder_HybridAgent" Name="FOO">
          <Directory Id="TokenFolder_HybridAgent" Name="Tokens">
            <Component Id="Component_TokenFolder_HybridAgent" Guid="b733054f-b0df-40fe-942a-a492fa8109a3">
              <CreateFolder>
                <util:PermissionEx GenericAll="yes" User="NT AUTHORITY\SYSTEM"/>
                <util:PermissionEx GenericAll="yes" User="Administrators"/>
                <util:PermissionEx Read="yes" ReadAttributes="yes" ReadExtendedAttributes="yes" ReadPermission="yes" GenericRead="yes" User="[SERVICEUSERGROUP]">
                  <Condition>ISDOMAINCONTROLLER=0</Condition>
                </util:PermissionEx>
              </CreateFolder>
            </Component>
          </Directory>
        </Directory>
      </Directory>
    </Directory>
  </Fragment>

  </Wix>

When I try to compile it with candle.exe in WiX 3.11, I get:
C:\onebranch\HybridAgent\src\deploy\Deployment\Deployment\test.wxs(30) : error CNDL0203 : The util:PermissionEx element contains an unsupported extension element 'Condition'.  The util:PermissionEx element does not currently support extension elements. Is the Condition element using the correct XML namespace?

A: PermissionEx is a little bit of a tricky element. There is one that comes from the WixUtilExtension (the one you get from the util: namespace) and one that is built into the Windows Installer (the one you get from the default wix namespace).
Why are there two? Well, we added util:PermissionEx that could do permission things the normal Permission element could not. Then in Windows Installer 5.0 they added PermissionEx creating the collision.
So you want to make sure you are on the correct link:

*

*util:PermissionEx

*PermissionEx
To answer your question, you can condition the util:PermissionEx by conditioning the Component. If you can adopt Windows Installer 5.0 (available in Win7+) then you could use the PermissionEx with its more fine-grained condition support.


text:
Q: How to apply top_k_categorical_accuracy over batch dimension in Keras I am making a custom metric in keras, based on top_k_categorical_accuracy. In my custom metric function I receive y_true and pred (two tensors) with 3 dimensions, having a shape of (batch_size, d2, d3), but apparently top_k_categorical_accuracy expects a 2-d tensor.
tf.keras.metrics.top_k_categorical_accuracy(y_true, y_pred, k=2)

My question is how can I apply this top_k function across different batches?
In the example below I would expect the output of the metric to be 1/2 (with k=2).
This would be done by taking the K.mean of top_k_categorical_accuracy(y_true[0], y_pred[0]) (1st batch gives 2/3) and top_k_categorical_accuracy(y_true[1], y_pred[1]) (2nd batch gives 1/3). So the mean would be 1/2
y_true = [
    [[0, 0, 1], [0, 1, 0], [1, 0, 0]],
    [[0, 0, 1], [0, 1, 0], [1, 0, 0]]
]
y_pred = [
    [[0.1, 0.7, 0.2], [0.05, 0.95, 0], [0.2,0.3,0.5]],
    [[0.7, 0.2, 0.1], [0.95, 0, 0.05], [0.3,0.2,0.5]]
]

A: Since only the last dimension is actual class predictions, you can reshape the first two dimensions into one using K.reshape:
y_true = K.reshape(y_true, shape=(-1,3))
y_pred = K.reshape(y_pred, shape=(-1,3))

Then the tensors will meet the API's shape requirements and produce an average score across batch*d1, which is also average across batch as you requested since each batch has the same number of d1.


text:
Q: Error while make for pyotherside I want to install pyotherside for my ubuntu 14.10, so I did:
git clone https://github.com/thp/pyotherside.git
cd pyotherside
sudo qmake

which succeeds, but when I do:
sudo make

it says:
cd src/ && ( test -e Makefile || /usr/lib/x86_64-linux-gnu/qt5/bin/qmake /usr/src/pyotherside/src/src.pro -o Makefile ) && make -f Makefile
Project MESSAGE: PYTHON_CONFIG = python3-config
Project ERROR: Unknown module(s) in QT: quick qml
Makefile:39: recipe for target 'sub-src-make_first' failed
make: *** [sub-src-make_first] Error 3

How can I solve this?

A: I figured it out afterwards.
Ubuntu 14.10 has a QT5 already installed, but it is QT5.0 and you should manually change to QT5.4 you installed.
sudo home/X/Qt/5.4/gcc_64/bin/qmake

This works perfectly.


text:
Q: NoMethodError at / undefined method `name' for nil:NilClass I have tried many solution and came up with good one but still getting error. I am editing my whole question.
I am trying to create Friendly URL with friendly_id gem.
In my project First user need to signup with devise.
Devise will pass some information to profile model with

model/user.rb
delegate :age, :city, :region, :country, to: :profile

I want to make user.name to be Friendly_id candidate. I have tried following code in my Profile model:-
 class Profile < ActiveRecord::Base

       extend FriendlyId
      friendly_id :user_name , use: :slugged

       def user_name
       user.name
       end

But it is giving error

NoMethodError at /
  undefined method `name' for nil:NilClass

now After submitting user form.
Please suggest possible solution with explanation.
My User.rb looks like
require 'open-uri'

class User < ActiveRecord::Base
  paginates_per 10

  validates :name , presence: true, length: { maximum: 200 }

  scope :by_name, ->(name) do
    joins(:profile).where('lower(name) LIKE ?', "%#{name.downcase}%")
  end

  delegate :age, :city, :region, :country, to: :profile

  has_one :profile, dependent: :destroy
  accepts_nested_attributes_for :profile

      def self.new_with_session(params, session)
        session_params = { 'profile_attributes' => {} }

        provider = session['devise.provider']
        if provider && data = session["devise.#{provider}"]
          session_params['name'] = data[:name] if data[:name]
          session_params['email'] = data[:email] if data[:email]
          session_params['profile_attributes'] =
            { avatar: data[:image] } if data[:image]
        end

        params.deep_merge!(session_params)
        super.tap do |user|
          if auth = Authorization.find_from_session(session, provider)
            user.authorizations << auth
          end
        end
      end

      def password_required?
        super && registered_manually?
      end

      def registered_manually?
        encrypted_password.present?
      end

    end

And my profile.rb looks like
class Profile < ActiveRecord::Base

   extend FriendlyId
    friendly_id user.name, use: :slugged

  belongs_to :user
  accepts_nested_attributes_for :user

  validates :website, allow_blank: true, uri: true

  def website=(url_str)
    if url_str.present?
      url_str = "http://#{url_str}" unless url_str[/^https?/]
      write_attribute :website, url_str
    end
  end

end

I think Problem is here:
Request parameters
{"action"=>"new", "controller"=>"users/registrations"}
Please suggest possible solution and explanation.

And users/registration:
class Users::RegistrationsController < Devise::RegistrationsController
  layout 'land'

  def create
    params[:user][:profile_attributes].delete(:place)

  end
  protected

    def after_sign_up_path_for(resource)
      welcome_path
    end
end

I am creating user in profile controller
    def load_profile
      @profile = Profile.friendly.find(params[:id])
      if !@profile || @profile.user.blocked_users.include?(current_user)
        redirect_to home_path
      else
        @user = @profile.user
      end
    end

@Rodrigo helped me find out error that error is due to Friendly_id can't create link with user instance.

A: There is an error on this line:
friendly_id user.name, use: :slugged

The variable user doesn't exists at Profile class scope. You should use something like this:
friendly_id :user_name, use: :slugged

def user_name
  user.name
end

A: extend FriendlyId
     friendly_id u_name, use: :slugged
     def u_name
      user.name
     end
    belongs_to :user

Have you defined user? what is user.name?


text:
Q: How do I limit voltage from two power sources? I am designing a system to mist my outdoor air conditioning units during the summer.  I will be powering a low voltage irrigation value using the low voltage from the AC controls - 24 VAC.  I have 2 air conditioning units that work independently of each other. However, there will be times that both units come on at the same time.
How do ensure when both units come on at the same time that electricity is sent to the power power supply without shorting out the solenoid or shorting out the air conditioner power supplies?

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. AC source switching.
How it works:

*

*If AC1 (supply 1) is off the relay is de-energised. If AC2 (supply 2) turns on it is passed through the normally closed contacts of the relay to the irrigation valve.

*AC AC1 turns on the relay energises and AC1 supplies the irrigation valve.

You need a relay with 24 V AC coil and contacts rated at 24 V AC/DC minimum and rated at the switching current or greater.


text:
Q: How to delete some of scale? x <- seq(0.5, 0.9, length = 400)
y <- dnorm(x,0.7,0.0458)
plot(x, y, type="l",  yaxt="n",ann=FALSE,bty="n")
axis(1, at=c(0.7, 0.8),tick=FALSE)
mtext("Proportions", 1, at=0.9, line=2)

I got photo1.jpg with the code,how can i delete some scales(0.5,0.6) in x-axis ,that is to say, to change photo1.jpg into photo2.jpg?
this is a photo1.jpg

this is a photo2.jpg


text:
Q: Pulumi Azure: get keyvault key version I want to use customer managed key for the sql server. For that I need to load the key from the keyvault but I cannot get the version of the key, which is required according to the pulumi documentation:

:param pulumi.Input[str] key_name: The name of the server key to be
operated on (updated or created). The key name is required to be in
the format of 'vault_key_version'. For example, if the keyId is
https://YourVaultName.vault.azure.net/keys/YourKeyName/YourKeyVersion,
then the server key name should be formatted as:
YourVaultName_YourKeyName_YourKeyVersion

Relevant code:
def create_tde_key(self, key: keyvault.Key, vault_name: str):
    key_name            = "{}_{}_{}".format(vault_name, key.name, key.version ) // here I need the version but there is only key.key_uri_with_version

    tde_key = sql.ServerKey('tde-key-' + self.location_flag,
        key_name            = key_name,
        resource_group_name = self.resource_group_name,
        server_name         = self.sql_server,
        server_key_type     = sql.ServerKeyType.AZURE_KEY_VAULT,
        uri                 = key.key_uri_with_version
    )

tried to disassemble key.key_uri_with_version this way:
key_version = key.key_uri_with_version[key.key_uri_with_version.rfind('/') + 1:]
but then I got TypeError: 'Output' object is not callable
I tried to use lambdas to get the string Output from key.key_uri_with_version but got the same TypeError as before.
I tried hardcoding the version and it is working so somehow I need to get the keyversion.
Any idea what should I do?


text:
Q: I have to solve this sum but I cannot do it I have this sum
$$\sum_{k=0}^{\infty} (-1)^k\frac{2^{(k+3)}(k+1)}{(k+3)!}$$
and I have to get the result.
I have continued like this
$$\sum_{k=0}^{\infty}(-1)^k\frac{2^{k}2^3}{k!(k+2)(k+3)} = e^2 \sum_{k=0}^{\infty}(-1)^k\frac{2^3}{(k+2)(k+3)}$$
I don't know if this is a good approach to the problem, but I don not know how to continue, could you help me please?
Thank you.

A: Looking for $e$-type sums is the right idea. I'd do this:
$$
\begin{align}
\sum_{k=0}^\infty (-1)^k \frac{2^{k+3}(k+1)}{(k+3)!} &= \sum_{k=0}^\infty (-1)^k \frac{2^{k+3}(k+3)}{(k+3)!} + \sum_{k=0}^\infty (-1)^k \frac{2^{k+3}(-2)}{(k+3)!} \\ &= 2\sum_{k=0}^\infty \frac{(-2)^{k+2}}{(k+2)!} + 2\sum_{k=0}^\infty \frac{(-2)^{k+3}}{(k+3)!} \\ &= 2(e^{-2} - 1 - (-2)) + 2(e^{-2} - 1 - (-2) - 2) \\ &= 4e^{-2}
\end{align}
$$

A: $$f(z) = -\left(1 + z + \frac{z^2}{2}\right) + e^z = \sum_{k=0}^\infty \frac{z^{k+3}}{(k+3)!} = z^2 \sum_{k=0}^\infty \frac{z^{k+1}}{(k+3)!},
$$ consequently $$z^3 \frac{d}{dz}\left[\frac{f(z)}{z^2} \right] = \sum_{k=0}^\infty \frac{(k+1) z^{k+3}}{(k+3)!}.$$  Evaluating the LHS via a straightforward application of the quotient rule gives $$(z-2) e^z + z+2 = \sum_{k=0}^\infty \frac{(k+1) z^{k+3}}{(k+3)!}.$$  Now letting $z = -2$ gives $$\sum_{k=0}^\infty (-1)^k \frac{(k+1) 2^{k+3}}{(k+3)!} = -\sum_{k=0}^\infty \frac{(k+1)(-1)^{k+3} 2^{k+3}}{(k+3)!} = 4e^{-2}.$$


text:
Q: Swift: AnyClass variable that conforms to protocol I have a static function I want to call on a class conforming to a protocol.
protocol P {
    static func f();
}

class C: P {
    static func f() {}
}

Is there a way to store C.self as a variable with a type that conforms to the protocol? Below does not compile, but it's what I'm ideally trying to do:
let a: AnyClass<P> = C.self;
a.f();

A: The type of the object you are trying to store with C.self is C.Type.
The Type C conforms to the protocol P
If you want to store your object by ensuring it conforms to P, use P.Type as the type.
Example:
let myObject: P.Type = C.self;
myObject.f();


text:
Q: Filter in collection My json:
  {
    "doc_id": "58107c7913065ff99318b268",
    "first_name": "test",
    "last_name": "test123",
    "email": "mail@account.com",
    "company": {
      "company_id": "580ab2b8ded0b2dfa56b9879",
      "name": "Test company",
      "contact_info": null,
      "location": {
        "location_id": "58094b8eded0b2dfa56b9864",
        "name": "NY",
        "formatted_address": "277 Canal St, New York, NY 10013, Stany Zjednoczone",
        "additional_options": "",
        "latitude": 50.894028,
        "longitude": 4.473816
      }
    },
    "role": "USER"
  },

I want to search all users where user.company.name = 'Test company', or user.company.location.name = 'NY'
Is there any option to find it ?
This doesn't work:
db.getCollection('User').find({"company.name": "NY"})
also I want to do this in doctrine mongodb but didnt work. What do I wrong ?

A:
Also one important thing. Relations is made by reference, not embed documents.

If that's the case, you're basically out of luck using simple queries. Simple queries cannot do joins. You can only query complete documents.
What you can do however is to do a multi step aggregation using the $lookup operator. It was introduced in version 3.2 so chances are you're running a compatible version.
Check out the introductory post or the relevant documentation.
Be warned though that if you have not used aggregations before, there is a bit of a learning curve to it - at least that was the case for me.


text:
Q: How to check if table exists, if not create in SQLite/PDO? At the moment I'm having to do it manually by documenting out one of my includes, I've tried a few things but it never seems to work properly and messes up my page?
include("dbconnection.php");
include("dbresults.php");
/*$sqltable = "CREATE TABLE Devices (id, dname, dmodel, ddesc, dcountry,dprivacy)";
if ($db->query($sqltable) == TRUE) {
 echo "table created succesfully";
} else {
    echo "error creating table: . $e->getMessage()";
}
*/

If I delete my table, I get nothing but a blank after include("dbconnection.php"); runs, when I comment out dbresults .php and uncomment the table code it works fine until the table is created, on refresh another white page until I reverse the commented out lines again (back to how they are above)
dbconnection.php

try {

$db = new PDO("sqlite:".__DIR__."/database.db");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch  (exception $e) {
echo "unable to connect";
echo $e->getMessage();

 exit;
}

dbresults.php
$sth = $db->prepare("SELECT * FROM Devices");
$sth->execute();
while ($result = $sth->fetch(PDO::FETCH_ASSOC)) {
$dbarray[] = $result;
}

I've tried putting the create table inbetween Dbconnection.php and Dbresults.php, or even putting it in the files themselves. I've tried multiple things but seems like whatever I do, it just breaks the page after dbconnection.php. I can get it to recognise the table doesn't exist, but once I go to create the table my page breaks. I'm sure I'm missing something really silly here, hopefully someone can push me in the right direction what I'm doing wrong
Edit: I realise my above code isn't checking for if table exists or anything, I tried a few things but nothing really worked so I just reverted it back to what's above.

A: You have probably found the answer by now, but for anyone else looking for a solution, you can simply change
CREATE TABLE

to
CREATE TABLE IF NOT EXISTS

and not actually check if the table exists in the first place.


text:
Q: Java Paint() issues first post here ever so forgive me if I am totally ignorant of all the rules.
I have some issues, I am relatively new to Java and have read and got some help from this community before.
I am having issues at the moment paint multiple balls on a JFrame, I have some solutions from other students but to no success. One student has got it working now but by painting everything within the Frame class which I don't feel is correct and putting repaint() within paint() which also feels wrong. if anyone could point me in the right direction I would be extremely appreciative.
Daniel
Code:
Gamejava
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package myanimie;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author Dan
 */
public class Game extends JFrame implements Runnable {

    private Ball myBall = new Ball();
    private Paddle myPad = new Paddle();
    final JPanel jp = new JPanel();
    final JPanel jp1 = new JPanel();
    final JPanel jp2 = new JPanel();

    public Game()
    {
        setVisible(true);
        setResizable(false);
        setTitle("First Test Animation");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setAlwaysOnTop(true);
        setSize(640,480);

    }

public void run()
    {
    move();
    }

    public void paint(Graphics g)
    {
        super.paint(g);
        myBall.paint(g);
    }

    public void move()
    {

      myBall.start();
      repaint();

        try
        {
            Thread.sleep(50);
        }
        catch (InterruptedException e)
        {
            System.exit(0);
        }
    }
    }

Ball.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package myanimie;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.geom.Ellipse2D;

/**
 *
 * @author Dan
 */
public class Ball  extends Thread  {

    Point pos;
    Color ballColor = Color.red;
    Color[] ts = {Color.CYAN,Color.green,Color.black};
    private int yChange = 2;
    private int xChange = 1;

    public Ball()
    {
    pos = new Point();
    pos.x = (int)(Math.random() * (500 - 100)) + 10 ;
    pos.y = (int)(Math.random() * (500/2 - 100)) + 10;

    }

    @Override
    public void run()
    {
     while(true)
    {
       move();

    }
    }

    public void paint(Graphics g)
    {
       g.setColor(ballColor);
       g.fillOval(pos.x - 10, pos.y - 10, 60,60);

    }

    public void move()
    {
//        System.out.println("y " + pos.y);
//        System.out.println("x " + pos.x);

        if(pos.y < 20)
        {
            yChange = -yChange;
            System.out.println("T");
            ballColor = Color.BLUE;
        }
        if(pos.x < 20)
        {
            xChange = -xChange;
            System.out.println("L");
            ballColor = Color.MAGENTA;
        }
        if(pos.x > 620 - 20)
        {
        xChange = -xChange;
        System.out.println("R");
        ballColor = Color.GREEN;
        }
        if(pos.y > 430 - 20)
        {
            yChange = -yChange;
            System.out.println("B");
            ballColor = Color.PINK;
        }
        if(pos.y < 640 - 20)
        {
            pos.translate(xChange, yChange);
        }
        if(pos.x < 480 - 20 || pos.x > 460)
        {
            pos.translate(xChange, yChange);
        }
        }

    public Point getPosition()
    {
        return pos;
    }

    public Ellipse2D area()
    {
        return new Ellipse2D.Double(pos.x, pos.y,60,60);
    }

    }

This is my terrible code, I have gotten around the errors but no animation atm.
Thanks guys!! your insight is invaluable

A: "and putting repaint() within paint()" sounds dangerous!
repaint()  method causes a call to this component's paint method as soon as possible.
You may elaborate how you are trying to draw "multiple" balls on the frame. If nothing special, your answer may be here

A: Yes it is indeed very bad practice. Calling repaint() in paint() will cause a StackOverflow Error.
Take a look at the game engine Bonsai from Ivo Wetzel. I like it a lot.
And indeed: You should create a JComponent which overrides the paintComponent(Graphics g) method. Add that JComponent to the JFrame. But you don't have to care about this. This will do the Bonsai game engine automatically.

A: OK some general observations based on the code you posted.

*

*You need to throttle your move() method so that it's not updating millions of times per second.  I see you have a Thread.sleep() in your Game.move method.  I think what you were trying to do was something like this:
public void run() {
    while(true) {
        //change the game state
        move();

        //draw the changes to the state that I just made
        repaint();

        //wait before moving to the next "frame"
        try {
           Thread.sleep(50);
        } catch ( InterruptedException ie ) {
        }
    }
}

private void move() {
    myBall.move();
}

*Since Ball.move() won't loop anymore, don't have Ball extend Thread at all.  Get rid of the run() method.  Your main game loop will be managed centrally by Game.

*From your main method or whoever starts the game running, call Game.run() either in that thread or in a new thread like this:
  public void main(String[] args) {
      Game game /* = new Game(...)*/;
      Thread gameThread = new Thread(game);
      gameThread.start();
  }

*Is there a good reason for getPosition() to exist?  This is probably better off as encapsulated state.


text:
Q: Create BMP Screenshot and save as 8pp Grayscale I'm having a lot of problems trying to accomplish this task. I know how to create a screenshot and save it as a bitmap....
    Dim printscreen As New Bitmap(thewidth, theheight, PixelFormat.Format24bppRgb)
    Dim xscreenshot As Graphics = Graphics.FromImage(printscreen)
    Dim theTest As New Size(thewidth, theheight)

    Dim theXLoc As String = "200"
    Dim theYLoc As String = "200"

    xscreenshot.CopyFromScreen(theXLoc, theYLoc, 0, 0, theTest)

    printscreen.Save("C:\Temp\printscreen.bmp", ImageFormat.MemoryBmp)

However when you pull up the options for Pixelformat. there is no option to save in 8pp. I really am trying to do this because I have been using AFORGE.Imaging library for image comparisons and in order to compare grayscale images they have to be in 8pp format.


text:
Q: Display properties in Better Javascript Sublime package? The Better Javascript package looks quite promising, as it correctly and nicely lists functions in my files... except for properties which display as a bunch of get() and set() functions without any context.

Is there a way to add properties in the Symbol List Preferences so that lines with Object.defineProperty(myObject, "property name") show up?
Bonus points for also hiding get & set functions nested within those properties.


text:
Q: IMAP search for non-ascii characters What is the COMMAND used to search for non ascii or Japanese characters in IMAP GMAIL server?

A: The correct way is to use a CHARSET UTF-8 SEARCH with a literal.  For example (each line ends with a \r\n):
> tag UID SEARCH CHARSET UTF-8 TEXT {4}
< + go ahead
> term
< * SEARCH 700 701 702
< tag OK SEARCH done

term should be UTF-8 encoded, and the 4 should be the length of the search therm, in bytes after encoding.
For example, to search for the term 日本 which is \xE6\x97\xA5\xE6\x9C\xAC in UTF-8 encoding (6 bytes)
> tag UID SEARCH CHARSET UTF-8 TEXT {6}
< + go ahead
> <6 bytes of binary data>
< * SEARCH 700 701 702
< tag OK SEARCH done

You can use different search keys besides TEXT, such as BODY or TO.  Searching in utf-8 should work on any reasonable IMAP server.  Other character sets are less likely to be supported.


text:
Q: Python3.6 No module named '_curses' I'm running Ubuntu 14.04 and just installed Python3.6 manually (downloading the tar file). I already have Python2.7 and Python3.4 with Python2.7 the default one. With Python3.6, everything seems to be OK except when I run
import curses
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/curses/__init__.py", line 13, in <module>
    from _curses import *
ModuleNotFoundError: No module named '_curses'

Running
sudo apt-get install libncurses-dev
sudo apt-get install libncursesw5-dev

did not work and neither did
pip3.6 install libncurses-dev

How do I install the curses module in python3.6?


text:
Q: Non-linear coupled ODE: How to pulse a dynamical system? I have a set of coupled non-linear differential equations:
$$y'=-a y+i (b+c x+d |y|^2 )\, y+e$$
$$x''+x \omega^2 + \Gamma x'=f  |y|^2$$
where $i=\sqrt{-1}$,
$y=y(t)$ is a complex number,
$x=x(t)$ is real,
$a,c,e,c, \omega ,\Gamma,f$ are real and positive, $b$ and $d$ can be negative.
I would like to find a set $( a,b,c,d,e,f,\omega ,Γ )$ of parameters so that the time trace of $x(t)$ is a pulsed oscillation.
What do I mean by pulsed oscillation? $x(t)$ should be a sine wave of angular frequency ω with an modulation envelope that looks like pulses with repetition rate $< \omega$ The fft of $x(t)$ should be a comb centered on ω.
In Matlab, I've try to play with the parameters and look at the FFT but it seems like a endless quest... I often find chaos.
I have no idea how to approach this problem and even if it's solvable.
How would you approach it?
PS: I have constraints on my parameters but I think it is irrelevant to speak of it at this stage.


text:
Q: String Formatting: what is the width for the e format? My IronPython console gives the following:
 >>> "%9.2e" % 1.236
 '1.24e+00'
 >>> "%10.2e" % 1.236
 ' 1.24e+00'
 >>>

The total characters in the output do not seem to correspond to 9 or 10 respectively.

A: This is a know bug with IronPython; the width is not handled correctly when using the %<width>e format.
CPython handles the width as expected; e.g. '%9.2e' % 1.236 produces a string of length 9. You could try using the format() function instead, if you are lucky it doesn't reuse the same code:
format(1.236, '9.2e')


text:
Q: Mapkit annotation image resolution I've changed the annotation pin to a custome image, and it works great. However the image looks a little rough around the edges when it drops in the mapview. Does anyone know how to sharpen the image up?
Thanks.

A: I had the same problem and solved it by using UIGraphicsImageRenderer to create the images. Now they are sharp.
let whiteImage = UIImage(named: "white")

let size = CGSize(width: 60, height: 60)

  let myImage = UIGraphicsImageRenderer(size: size).image { imageContext in
      let context = imageContext.cgContext
      whiteImage?.draw(in: CGRect(origin: .zero, size: CGSize(width: 70, height: 90)))
  }

annotationView!.image = myImage


text:
Q: passing std::array variable as argument I need help in resolving an issue which i am facing .
I would want to have a function prototype which accepts two different types of argument at two instances.
For example shown below:
I have a structure as shown below:
         typedef struct BufferStruct
         {
            unsigned long    BufferType;
            unsigned long    TheAddress;
          } Buffer;

I have a function named Test and this function should accept two different types of argument
  1) std::array<Buffer, 2> axBuffer;
  2) Buffer axBuffer;

   void Test(??)/* function argument ?*/

 These are C functions and not C++.

 Can someone please help me in getting the appropriate function prototype for the function named "Test"?

 Advanced thanks.

A: C doesn't have function overloading.  The simplest way to approach this with a single function is to take a pointer-to-Buffer and a length:
void Test(Buffer *buffer, size_t length);

When invoking this function with a single Buffer:
Buffer buf = ...;
Test(&buf, 1);

When invoking it with an std::array:
std::array<Buffer, 2> buffers = ...;
Test(buffers.data(), buffers.size());

If you want the length argument to be optional, you have two use two differently-named functions, unfortunately:
void TestOne(Buffer *);
void TestMany(Buffer *, size_t);


text:
Q: R: Join two tables (tibbles) by *list* columns Seems like there should be a simple answer for this but I haven't been able to find one:
tib1 <- tibble(x = list(1, 2, 3), y = list(4, 5, 6))
tib1
# A tibble: 3 × 2
      x         y
 <list>    <list>
1 <dbl [1]> <dbl [1]>
2 <dbl [1]> <dbl [1]>
3 <dbl [1]> <dbl [1]>

tib2 <- tibble(x = list(1, 2, 4, 5), y = list(4, c(5, 10), 6, 7))
tib2
# A tibble: 4 × 2
      x         y
 <list>    <list>
1 <dbl [1]> <dbl [1]>
2 <dbl [1]> <dbl [2]>
3 <dbl [1]> <dbl [1]>
4 <dbl [1]> <dbl [1]>

dplyr::inner_join(tib1, tib2)

Joining, by = c("x", "y")
Error in inner_join_impl(x, y, by$x, by$y, suffix$x, suffix$y) :
        Can't join on 'x' x 'x' because of incompatible types (list / list)

So is there a way to perform a join based on list columns (before I start writing my own)?
Basically if the list of both key variables is identical, I want the row to be included in the final table, and if not - not. In the above example there are two key variables x and y and the result should be only the first row in the two tibbles since it's the only identical one in both key variables:
tibble(x = list(1), y = list(4))
# A tibble: 1 × 2
      x         y
 <list>    <list>
1 <dbl [1]> <dbl [1]>

A: We could use hashes from digest:
tib1 <- tibble(x = list(1, 2, 3), y = list(4, 5, 6))
tib2 <- tibble(x = list(1, 2, 4, 5), y = list(4, c(5, 10), 6, 7))

tib1 <- mutate_all(tib1, funs(hash = map_chr(., digest::digest)))
tib2 <- mutate_all(tib2, funs(hash = map_chr(., digest::digest)))

inner_join(tib1, tib2, c('x_hash', 'y_hash')) %>%
  select(x.x, x.y)

# A tibble: 1 × 2
        x.x       x.y
     <list>    <list>
1 <dbl [1]> <dbl [1]>


text:
Q: How do I do Firebase analytics from ionic 3? I have tried different work around, but I am unable to do Firebase analytics in ionic 3. Please anyone help me from scratch on Firebase analytics from ionic 3.

A: first add the firebase analytics to your project:
ionic cordova plugin add cordova-plugin-firebase-analytics
npm install @ionic-native/firebase-analytics

then create the event you want to log:
import { FirebaseAnalytics } from '@ionic-native/firebase-analytics';

constructor(private firebaseAnalytics: FirebaseAnalytics){
  this.firebaseAnalytics.logEvent('custom_event',{param: 'my_param'
}

and finally add the custom_event and the param to your analytics dashboard to see it (it takes few hours for it to appear)

A: For Ionic3: the correct commands are
ionic cordova plugin add cordova-plugin-firebase-analytics
npm install --save @ionic-native/firebase-analytics@4

See also this helpful blog post : here


text:
Q: linear regression in python error I try to implement the code below but it return an error : 'LinearRegression' object is not.  What gets wrong? Thanks
repair_agg.groupby('block_id').apply(clf.fit(repair_agg['t'].reshape(repair_agg['t'].shape[0],1),repair_agg['lognum']))
repair_agg is the dataframe.

A: The Pandas apply() method takes a callable function. You're passing it a scikit-learn LinearRegression object, which is not callable.


text:
Q: RSQLite Warning: "Too many SQL variables" I was having an issue getting the following error with RSQLite and was having trouble diagnosing the problem:
Error in result_create(conn@ptr, statement) : too many SQL variables
The database showed the correct, fixed number (24) of columns and should have had ~190 rows. Because the many rows at once won't fit in RAM, each entry (row) is iteratively appended.
Unfortunately it kept failing on entry 99. However, when I tried to only enter rows 95 to 105 into a database, it works.
    # Doesn't work

    samplesToAdd <- samplesToAdd[1:100, ]

    newDatabase2 <- DBI::dbConnect(RSQLite::SQLite(),
                           "C:/Users/chase/Documents/GitHub/IDBac_App/inst/app/SpectraLibrary/z1.sqlite")
    IDBacApp::addNewLibrary(samplesToAdd = samplesToAdd,
                    newDatabase = newDatabase2,
                    selectedIDBacDataFolder = selectedIDBacDataFolder)

    Warning: Error in result_create: too many SQL variables

    # Works

    samplesToAdd <- samplesToAdd[95:105, ]

    newDatabase2 <- DBI::dbConnect(RSQLite::SQLite(),
                           "C:/Users/chase/Documents/GitHub/IDBac_App/inst/app/SpectraLibrary/z1.sqlite")
    IDBacApp::addNewLibrary(samplesToAdd = samplesToAdd,
                    newDatabase = newDatabase2,
                    selectedIDBacDataFolder = selectedIDBacDataFolder)

So, why was this failing for "too many variables" when there were only 24?

A: Stupidly, there was a for loop that was assigning globally. This was having the effect of re-adding multiple columns each iteration. The SQLite just doesn't append the extra columns, so doesn't fail until the insert is too large.
However, the puzzling nature of the problem can be seen in the simplified example below.
library(RSQLite)
library(magrittr)
library(dplyr)

a <- mtcars[1, ]
b <- cbind(mtcars[1, ], mtcars[2, ])

> as_tibble(a)
    # A tibble: 1 x 11
       mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
    * <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
    1    21     6   160   110   3.9  2.62  16.5     0     1     4     4
> as_tibble(b)

Error: Columns `mpg`, `cyl`, `disp`, `hp`, `drat`, `wt`, `qsec`, `vs`, `am`, `gear`, `carb` must have unique names

# But "tibbble" wasn't used:
> b
          mpg cyl disp  hp drat   wt  qsec vs am gear carb mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4  21   6  160 110  3.9 2.62 16.46  0  1    4    4  21   6  160 110  3.9 2.875 17.02  0  1    4    4

con <- DBI::dbConnect(RSQLite::SQLite(),
file.path(getwd(),"StackoverflowExample", "exw.sqlite"))

DBI::dbWriteTable(conn = con,
              name = "IDBacDatabase", # SQLite table to insert into
              a, # Insert single row into DB
              append = TRUE, # Append to existing table
              overwrite = FALSE) # Do not overwrite

DBI::dbWriteTable(conn = con,
              name = "IDBacDatabase", # SQLite table to insert into
              b, # Insert single row into DB
              append = TRUE, # Append to existing table
              overwrite = FALSE) # Do not overwrite

 db <- dplyr::tbl(con, "IDBacDatabase")

 db

 # Source:   table<IDBacDatabase> [?? x 11]
 # Database: sqlite 3.22.0           [C:\Users\chase\Documents\StackoverflowExample\ex.sqlite]
     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1    21     6   160   110   3.9  2.62  16.5     0     1     4     4
 2    21     6   160   110   3.9  2.62  16.5     0     1     4     4

Edit
To make failing insert:
    b <- mtcars[1, ]
    for(i in 1:1000){
        b <- cbind(b, mtcars[2, ])
    }


text:
Q: Encountering issues with std::mutex and std::thread I am encountering issues with both std::thread and std::mutex, unable to get both to play nicely with each other. I've been pulling my hair out over this for the past few hours and just cannot make any progress whatsoever. I believe it is out of my skill area. The code is just below:
void GekkoFyre::TuiHangouts::gui_userRosterListNav(std::shared_ptr<WINDOW> display,
                                                   std::vector<const char *> userList,
                                                   const short &menuItem)
{
    while (rosterEnabled) {
        for (short i = 0; i < totalMenuItems; ++i) {
            short diff = (menuItem - i);
            if (i < numMenuItems) {
                if (i == menuItem) {
                    size_t msgLen = strlen(userList.at(i));
                    size_t l = 0;
                    if (msgLen > subMaxX) {
                        for (l = subMaxX; l < msgLen; ++l) {
                            // Scroll the message from left to right, then vice versa, so that it fits within
                            // the designated window.
                            std::this_thread::sleep_for(std::chrono::milliseconds(500));
                            rosterListMutex.lock();
                            wattron(usrSubWin.get(), A_REVERSE); // Highlight selection
                            const char *msg = userList.at(i);
                            mvwaddstr(usrSubWin.get(), i, 0, &msg[(msgLen - l)]);
                            wrefresh(usrSubWin.get());
                            touchwin(usrSubWin.get());
                            rosterListMutex.unlock();
                        }
                    } else {
                        rosterListMutex.lock();
                        wattron(usrSubWin.get(), A_REVERSE); // Highlight selection
                        mvwaddstr(usrSubWin.get(), i, 0, userList.at(i));
                        wrefresh(usrSubWin.get());
                        touchwin(usrSubWin.get());
                        rosterListMutex.unlock();
                    }
                }

                wattroff(usrSubWin.get(), A_REVERSE); // Remove highlight

                if ((i + 1) < numMenuItems) {
                    mvwaddstr(usrSubWin.get(), (i + 1), 0, userList.at((i + 1)));
                }
            } else if (diff < (totalMenuItems - numMenuItems) && diff > 0) {
                // Allow the scrolling of a username list, from downwards and then back upwards, so that
                // the user may see the list in its entirety.
                wclear(usrSubWin.get());
                int pos = 0;
                for (short c = diff; c < (numMenuItems + diff); ++c) {
                    ++pos;
                    mvwaddstr(usrSubWin.get(), pos, 0, userList.at(c));
                }
                pos = 0;
                break;
            }
        }

        rosterListMutex.lock();
        wattroff(usrSubWin.get(), A_REVERSE); // Remove highlight
        touchwin(usrSubWin.get());
        wrefresh(usrSubWin.get());
        wrefresh(display.get());
        rosterListMutex.unlock();
    }
}

I am trying to display a list of users to the left of a chat window in NCurses, as can be seen in [ 1 ] below, albeit without any users present in said screenshot. I want to keep my privacy :) What happens is that as you scroll down the list, flickering begins to occur back and forth between two usernames after scrolling past just a few. They keep repeatedly selecting each other, just over and over. I believe this is reason of the threads not syncing up properly. The function is implemented as so:
[ 1 ] - http://imgur.com/ZZlFHg2
        #define WIDGET_USERS_LIST 1
        short menuItem = 0;
        int ch = 0;
        int curr_widget = 0;
        std::thread rosterListNav1(&GekkoFyre::TuiHangouts::gui_userRosterListNav, this, userListWin, rosterFormatted, menuItem);
        rosterListNav1.detach();

        while ((ch = wgetch(display.get())) != KEY_F(12)) {
            switch (ch) {
            case KEY_DOWN:
                if (curr_widget == WIDGET_USERS_LIST && rosterEnabled) {
                    ++menuItem;
                    if (menuItem > totalMenuItems - 1) {
                        menuItem = 0;
                    }
                }
                break;
            case KEY_UP:
                if (curr_widget == WIDGET_USERS_LIST && rosterEnabled) {
                    --menuItem;
                    if (menuItem < 0) {
                        menuItem = totalMenuItems - 1;
                    }
                }
            }

            std::thread rosterListNav2(&GekkoFyre::TuiHangouts::gui_userRosterListNav, this, userListWin, rosterFormatted, menuItem);
            rosterListNav2.detach();
        }

Any help on this issue would be dearly appreciated, and I believe I have placed the std::mutex's in the right areas. I am really stumped with this problem. Also beware that while I know a few tricks of the trade, I am entirely self-taught. Some of the nomenclature that is normal to programmers who have gone through university is completely unintelligible to me.


text:
Q: How to add lstlisting to Algorithms List I have written a document where I use pseudo code to describe some general algorithms (with \usepackage{algpseudocode} ) which can be viewed at the begining after toc as "List of Algorithms".
I also use some java code written using \usepackage{listings} to describe more code. I would like to also add these algorithms written in java to the List Of Algorithms among those written in pseudo code.
Is it possible?
Listings configuration:
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{listings}
\usepackage{courier}
\usepackage{subcaption}
\lstset{
  language=Java,
  basicstyle=\footnotesize\ttfamily, % Standardschrift
  %numbers=left,               % Ort der Zeilennummern
  numberstyle=\tiny,          % Stil der Zeilennummern
  %stepnumber=2,               % Abstand zwischen den Zeilennummern
  numbersep=6pt,              % Abstand der Nummern zum Text
  tabsize=4,                  % Groesse von Tabs
  extendedchars=true,         %
  breaklines=true,            % Zeilen werden Umgebrochen
  keywordstyle=\color{blue},
  commentstyle=\itshape\color{gray},
  stringstyle=\ttfamily, % Farbe der String
  showspaces=false,           % Leerzeichen anzeigen ?
  showtabs=false,             % Tabs anzeigen ?
  xleftmargin=17pt,
  framexleftmargin=17pt,
  framexrightmargin=5pt,
  framexbottommargin=4pt,
  %backgroundcolor=\color{lightgray},
  showstringspaces=false,
  morekeywords={get,set,interface, null, var, in}
}
\DeclareCaptionFont{white}{\color{black}}
\DeclareCaptionFormat{listing}{\colorbox[cmyk]{0.13,0.14,0.10,0.1}{\parbox{\textwidth}{\hspace{15pt}#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white, singlelinecheck=false, margin=0pt, font={bf,footnotesize}}

A: Here's one possibility; etoolbox was used to patch the internal \lst@MakeCaption (from listings) so the caption is written in the .loa file (used for \listofalgorithms):
\documentclass{report}
\usepackage{listings}
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{etoolbox}

\makeatletter
\patchcmd{\lst@MakeCaption}{\addcontentsline{lol}}{\addcontentsline{loa}}{}{}
\patchcmd{\lst@MakeCaption}{\addcontentsline{lol}}{\addcontentsline{loa}}{}{}
\AtBeginDocument{%
  \let\c@lstlisting\c@algorithm
  \let\thelstlisting\thealgorithm
  \renewcommand\listalgorithmname{List of algorithms}
}
\makeatother

\begin{document}

\listofalgorithms

\begin{algorithm}
This is an algorithm
\caption{An algorithm}
\end{algorithm}

\begin{lstlisting}[caption=A listing]
This is a listing
\end{lstlisting}

\begin{algorithm}
This is another algorithm
\caption{Another algorithm}
\end{algorithm}

\begin{lstlisting}[caption=Another listing]
This is another listing
\end{lstlisting}

\end{document}

Now that the original question has been edited, the code from my previous example has to be placed before loading subcaption:
\documentclass{report}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{listings}
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{etoolbox}
\usepackage{courier}

% Before loading subcaption %%%%%%%%%%%%%%%%%%%%%%%
\makeatletter
\patchcmd{\lst@MakeCaption}{\addcontentsline{lol}}{\addcontentsline{loa}}{}{}
\patchcmd{\lst@MakeCaption}{\addcontentsline{lol}}{\addcontentsline{loa}}{}{}
\AtBeginDocument{%
  \let\c@lstlisting\c@algorithm
  \let\thelstlisting\thealgorithm
  \renewcommand\listalgorithmname{List of algorithms}
}
\makeatother
% Before loading subcaption %%%%%%%%%%%%%%%%%%%%%%%

\usepackage{subcaption}
\lstset{
  language=Java,
  basicstyle=\footnotesize\ttfamily, % Standardschrift
  %numbers=left,               % Ort der Zeilennummern
  numberstyle=\tiny,          % Stil der Zeilennummern
  %stepnumber=2,               % Abstand zwischen den Zeilennummern
  numbersep=6pt,              % Abstand der Nummern zum Text
  tabsize=4,                  % Groesse von Tabs
  extendedchars=true,         %
  breaklines=true,            % Zeilen werden Umgebrochen
  keywordstyle=\color{blue},
  commentstyle=\itshape\color{gray},
  stringstyle=\ttfamily, % Farbe der String
  showspaces=false,           % Leerzeichen anzeigen ?
  showtabs=false,             % Tabs anzeigen ?
  xleftmargin=17pt,
  framexleftmargin=17pt,
  framexrightmargin=5pt,
  framexbottommargin=4pt,
  %backgroundcolor=\color{lightgray},
  showstringspaces=false,
  morekeywords={get,set,interface, null, var, in}
}
\DeclareCaptionFont{white}{\color{black}}
\DeclareCaptionFormat{listing}{\colorbox[cmyk]{0.13,0.14,0.10,0.1}{\parbox{\textwidth}{\hspace{15pt}#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white, singlelinecheck=false, margin=0pt, font={bf,footnotesize}}

\begin{document}

\listofalgorithms

\begin{algorithm}
This is an algorithm
\caption{An algorithm}
\end{algorithm}

\begin{lstlisting}[caption=A listing]
This is a listing
\end{lstlisting}

\begin{algorithm}
This is another algorithm
\caption{Another algorithm}
\end{algorithm}

\begin{lstlisting}[caption=Another listing]
This is another listing
\end{lstlisting}

\end{document}


text:
Q: Use of Grid Tkinter GUI and is there any other correct practice to achieve this I am doing an UI in GUI Tk . I the one which is marked in the
"Blue" : I am using columnspan but also it is not extending till the end of UI frame .
"Red" : Here I don't know why this here UI is middle Aligned .
I might be doing some simple mistake , I tried much to find solution .
And
Is there any other way than giving row and column number like in the below code , if there any other way to achieve it
Code =tk.Label(self.page2,text="Code ").grid(row=1,rowspan=2,pady=(10,10),sticky="NW")
CodeTextbox= Entry(self.page2).grid(row=1,column= 2,rowspan=2,columnspan=100,pady=(10,10),sticky="NW" )
SerialNumber=tk.Label(self.page2,text=" Serial Number").grid(row=3,rowspan=2,pady=(10,10),sticky="NW" )
SerialNumberTextBox=Entry(self.page2).grid(row=3,column=2,rowspan=2,columnspan=100,pady=(10,10),sticky="NW" )
Model=tk.Label(self.page2,text="Model ").grid(row=5,rowspan=2,pady=(10,10),sticky="NW" )
ModelTextbox=Entry(self.page2).grid(row=5,column=2,rowspan=2,columnspan=100,pady=(10,10),sticky="NW" )
KCheckBox=Checkbutton(self.page2,text="").grid(row=7,column=1,rowspan=2,columnspan=2,pady=(10,10),sticky="W")
FCheckBox = Checkbutton(self.page2, text="F").grid(row=7, column=3,rowspan=2,columnspan=2, pady=(10, 10), sticky="W")
OW=tk.Label(self.page2,text="OW").grid(row=9,column=1,rowspan=2,columnspan=2,pady=(10,10),sticky="NW" )
OWSupported=Checkbutton(self.page2,text="Supported").grid(row=9,column=3,rowspan=2,columnspan=2,pady=(10,10),sticky="W")
OWNOTSupported=Checkbutton(self.page2,text="NOT Supported").grid(row=9,column=5,rowspan=2,columnspan=2,pady=(10,10),sticky="W")

A: None of your columns have any weight associated with them, so they will all be as small as possible. Even though you do columnspan=100, columns 6-100 all have a width of zero. As a rule of thumb you should always give at least one row and one column a non-zero width so that the full amount of the space in the GUI is used.
Also, you aren't requesting that the entry widgets "stick" to the right side. So even if the column they are in expands the full width of the GUI, the entry widgets will not expand because you haven't told them too.
Finally, I strongly encourage you to separate widget creation from widget layout, and to group all of your layout code together so that it's possible to see all of your layout options as a group. The way you're doing it now, the variables are useless because they are all being set to None, since that's what .grid(...) returns.


text:
Q: Laravel - only a zero is saved to the database I have a simple car model with one attribute:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Filesystem\Filesystem;

/*
*   TODO:
*   Property Fotos ausfüllen
*/

class Car extends Model
{
    //Tablenname
    protected $table = 'cars';

    protected $fillable = ['title'];

    public $timestamps = false;

    /**
    *   @var string
    */
    protected $title = NULL;

    /**
    *   @var integer
    */
    protected $imagesId = NULL;

    /**
    *
    *   @return string
    */
    public function getTitle()
    {
        return $this->attributes['title'];
    }

    /**
    *
    *   @param string $title
    *
    *   @return void
    */
    public function setTitle($title)
    {
        $this->attributes['title'] = $title;
    }

}

This is my store function from the controller:
<?php

namespace App\Http\Controllers;

use App\Car;

class CarController extends Controller
{

 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
  public function store(Request $request)
  {
      $car = new Car();

      // $car->setTitle($request->title);
      $car->setTitle('stackoverflow');
      $car->save();

      ...
   }
}

However, this is how the entry in the database looks like:

Title is always zero! I also tried it with other models, same.

A: Check field datatype.if you want to store string you have to change your 'title' field datatype to varchar.
hope it works.


text:
Q: How to check if a property from an object in a List exists in another List? Friendly Notice:
I am aware of the nested foreach method, but I'm trying to avoid it if there is a more efficient way.
Setup of Class 1:
public class Product{

      public int ID {get; set;}
      //Other irrelevant properties
}

Setup of Class 2:
public class JoinedDiscounts{

      public int ID {get; set;}
      public List<Product> Products = new List<Product>();
      //Other irrelevant properties

}

Suppose I now have a list of products (I've filtered specific products out into this list):
List<Product> products;

I also have this list.
List<JoinedDiscount> joinedDiscounts;

My goal is to check if any of the Joined Discounts from the joinedDiscounts list have a list of Products wherein any Product from the products list exists.
I think I've spent too much time thinking about it and now I'm having difficulty figuring out something that's probably very simple.
Any help is much appreciated

A: Let's start from the top down...

if any of the Joined Discounts

Ok, so the outer structure is:
joinedDiscounts.Any()

But we need a boolean clause in there...

have a list of Products wherein any

Ok, we want to examine the .Products property and know if anything in that list matches a condition:
joinedDiscounts.Any(jd => jd.Products.Any())

Now we need a boolean clause in there...

any Product from the products list exists

So, if the products contains any given product of this collection?
joinedDiscounts.Any(jd => jd.Products.Any(p => products.Contains(p)))

That ought to do it, at least semantically.
However, if the comparator for Product isn't defined on that class then the code might just do a reference comparison, which might not be what you want.  (Two instances may have the same values and may conceptually represent the same product, but they wouldn't be the same instance of the Product class.)  If you need to drill further into the ID to manually compare, you'd have to do something like this:
joinedDiscounts.Any(jd => jd.Products.Any(prod => products.Select(p => p.ID).Contains(prod.ID)))

As the code grows, I'd recommend encapsulating comparison logic into your models appropriately.  Implementing .Equals() and .GetHashCode() should do the trick in this case.  That way consuming code stays simple and the logic is encapsulated on the objects where it belongs.  That would allow you to perform semantically intuitive comparisons of your objects instead of drilling in to ID values manually.

A: This should give you an enumeration of the JoinedDiscounts in joinedDiscounts that contain a Product in products.
joinedDiscounts.Where(disc => disc.Products.Any(prod => products.Contains(prod)))

I think that covers what you're looking for.

A: joinedDiscounts.Where(joinedDiscountse => joinedDiscountse.Products.Any()).ToList()

A: Using linq you can do this
List<JoinedDiscount> joinedDiscounts; //the joined products
List<Product> products; //desired products

joinedDiscounts.Where(d => d.Products.Any(
                     p => products.Select(prod => prod.ID).Contains(p.ID)
                     ).ToList()


text:
Q: jQuery Replacewith ( replace 2 elements ) why dont this code replace both object and embed?
$(".watch-on-mobile").click(function () {
$('object' && 'embed').replaceWith($('.video-js'));
$('.video-js').css("display", "block")
});

Thanks in advance!

A: You can't invent a syntax and hope for the library to guess.
Use the multiple selector :
$('object,embed').replaceWith($('.video-js'));


text:
Q: How to enable & handle "tap" event on fabricjs on mobile device?
I want to handle event tap with fabricjs on mobile device. What is correct way to implement that ?

Currently, I see implement "tap" event in the fabricjs source code. And if I want handle that event, I need change fabricjs source code:
if (typeof eventjs !== 'undefined' && eventjsFunctor in eventjs) {
    eventjs[eventjsFunctor](canvasElement, 'gesture', this._onGesture);
    eventjs[eventjsFunctor](canvasElement, 'drag', this._onDrag);
    eventjs[eventjsFunctor](canvasElement, 'orientation', this._onOrientationChange);
    eventjs[eventjsFunctor](canvasElement, 'shake', this._onShake);
    eventjs[eventjsFunctor](canvasElement, 'longpress', this._onLongPress);
    eventjs[eventjsFunctor](canvasElement, 'tap', this._onLongPress);
  }

Add last line:
eventjs[eventjsFunctor](canvasElement, 'tap', this._onLongPress);

And now I can catch tap event through "longpress" event.
this.canvas.on({'touch:longpress': function(e) {
        console.log("touch:longpress + tap");
    });

My question is there another nice way to handle 'tap' event on fabricjs without modified fabricjs source code & can handle 'tap' event by listen "touch:tap" event name ?

Thank you,

A: You can add events to uppercanvas using
eventjs.add( canvas.upperCanvasEl, 'tap', onTap);
eventjs.remove( canvas.upperCanvasEl, 'tap', onTap);

function onTap(e) {
  console.log("tap");
})


text:
Q: Scaling gltf model, what is wrong? I want to scale the mesh in a gltf model. i.e. the actual vertex data, while keeping the animations.
Before me editing the gltf file, we have the following math model, let A be the animation matrix, i/e/ the blended matrix obtained after multiplying and adding the animation and ibm matrices. Let S be the scaling matrix.
Trivially, at rendering time doing SAx for every x in the shader will yield the scaled model.
Now, if you scale x before applying the transformation, your input is now Sx. We thus want a matrix B such that
SAx = BSx => B = SAS^-1.
Which is trivially ttrue since BSx = SAS^-1Sx = SAx.
For any animation matrix A this is what SAS^-1 looks like:
⎡A₀₀  A₀₁  A₀₂  s⋅A₀₃⎤
⎢                    ⎥
⎢A₁₀  A₁₁  A₁₂  s⋅A₁₃⎥
⎢                    ⎥
⎢A₂₀  A₂₁  A₂₂  s⋅A₂₃⎥
⎢                    ⎥
⎢A₃₀  A₃₁  A₃₂       ⎥
⎢───  ───  ───   A₃₃ ⎥
⎣ s    s    s        ⎦

But the bottom row is (0, 0, 0, 1), so basically we can ignore all but the last column of the matrix.
This mathematical model is telling me that if I scale down the translation component of my animation data AND my mesh data, I should be fine.
To that effect I wrote this functions in rust (the implementation is irrelevant)
    for animation in &gltf.animations
    {
        scale_animation(0.02, &animation, &gltf);
    }

    for skin in &gltf.skins
    {
        scale_skin(0.02, &skin, &gltf);
    }

    scale_nodes(0.02, &mut gltf);

    for mesh in &gltf.meshes
    {
        scale_mesh(0.02, &mesh, &gltf);
    }

All these do is scale down the translation component of the respective data, for example:
fn scale_skin(scale : f32, skin : &Skin, gltf : &Gltf)
{
    let mat_data =
        gltf.data_from_accessor::<Mat4>(
            skin.inverse_bind_matrices);

    for mat in mat_data
    {
        let mut slice =
            mat.slice_mut((0, 0), (3,4));

        slice *= scale;
    }
}

These all work and do what they should I tested. The thing is, doing all these 4 operations yields this result:

But If I don't scale the mesh data and only scale the animation data, I get this:

Which is correct. But of course if I delete the animation data from the gltf json, the model is back up to humongous size.
I don't understand where my math is failing. It's not an implementation bug, I am thinking about something wrong.
TL;DR, if I scale down the mesh data, what transformation must I apply to my animation data to keep the animations?

A: If anyone ever runs into this issue.
Turns out my math was fine. I was making the mistake of multiplying the whole IBM matrix instead of just the scaling components. I.e. I was applying the same transformation twice.


text:
Q: PHP unset parts of a nested array Trying to process an array and remove a specific associative array in a larger array set. The code I have now works in removing the specific sections locally, within the for loop, but doesn't effect the original $cursor array.
foreach($cursor as $key) {

    foreach($key as $value => $k){

        if ($value == 'user'){

            unset($k['confinfo']);
        }
    }
}

Is it a GLOBAL variable problem? How to unset the original variable?

A: Iterate over the original array by reference:
foreach($cursor as &$key) // added &

It's important to note than whenever you do this, it's a very good idea to follow the loop with an unset to destroy the reference:
foreach($cursor as &$key) {
    // ...
}
unset($key);

Personally I find this a little ugly (par for the course in PHP), but this way you eliminate the risk of reusing the name $key later on and causing all sorts of "interesting" effects.

A: The problem is that the $k you get in the loop is not the original array that $cursor contains, it's just a copy that gets destroyed once the loop goes into the next round. To really remove the confinfo index from $cursor you need to start with $cursor and reference work your way down.
Replace
unset($k['confinfo']);

with
unset($cursor[$key][$value]['confinfo']);

It's not as short as the other answer, but it shows better what's going on and is thus easier to debug and extend later.


text:
Q: Reactjs. I have an arrow key navigation problem I'm trying to do xmb (psp/ps3) menu in react and i have a problem. The problem is that items scroll through the next item. For example: Item 1 scrolls to Item 3 (Item 2 is skipped although item 2 should come after 1 item) and in back From Item 3 to 1. How Can i fix it?
The demo: https://codesandbox.io/embed/relaxed-cohen-05tvt6?fontsize=14&hidenavigation=1&theme=dark
I tried some ways
      $(".container").on("keydown", function (e) {
        if (e.which === arrowKeys.left) {
          _position = --_position / _length;
        }

        if (e.which === arrowKeys.right) {
          _position = ++_position / _length;
        }

        move();
      });

      $(".container").on("keydown", function (e) {
        if (e.which === arrowKeys.left) {
          _position = (1-_position) % _length;
        }

        if (e.which === arrowKeys.right) {
          _position = (1-_position) % _length;
        }

        move();
      });

      $(".container").on("keydown", function (e) {
        if (e.which === arrowKeys.left) {
          _position = --_position % (_length-1);
        }

        if (e.which === arrowKeys.right) {
          _position = ++_position % (_length-1);
        }

        move();
      });

And i edited in HTML

            item 1

            item 2

            item 3

            item 4

            item 5

            item 6

            item 7

            item 8

            item 9

            item 10

But none of this ways worked. How can i fix it?

A: That is because you are using <StrictMode> in the index.js file.

To help surface these issues, React 18 introduces a new development-only check to Strict Mode. This new check will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount.

This will re-run some lifecycle methods (like componentDidMount) and so it will add your key handler twice.

You could ofcource make your code more defensive and remove all the global event handlers once the component is unmounted.

A: I think using React instead of Jquery to listen to events is the best way.

These codes only demo how to refactor the keydown event.

https://codesandbox.io/s/awesome-framework-jsbrx2?file=/src/App.js
import React from "react";
import $ from "jquery";
import "./style.css";

class App extends React.Component {
  _position = 1;
  _length = 0;
  arrowKeys = { left: 37, up: 38, right: 39, down: 40 };

  componentDidMount() {
    const componentRef = this;
    (function () {
      var _items = $(".container").find(".item");
      componentRef._length = _items.length;

      $(".container").on("focus", ".item", function () {
        componentRef._position = $(this).index();
      });

      $(".container").on("click", ".item", function () {
        componentRef.move();
      });
    })();
  }

  move() {
    $(".container").find(".item").get(this._position).focus();
    $(".wrapper").css("transform", function (a, b) {
      var left = a - 3 * this._position + "%";
      return "translate3d(" + left + ",0,0)";
    });
  }

  customKeydown = (e) => {
    if (e.which === this.arrowKeys.left) {
      this._position = --this._position % this._length;
    }

    if (e.which === this.arrowKeys.right) {
      this._position = ++this._position % this._length;
    }

    this.move();
  };

  render() {
    return (

            item 1

            item 2

            item 3

            item 4

            item 5

            item 6

            item 7

            item 8

            item 9

            item 10

    );
  }
}
export default App;


text:
Q: Ember: How to access element when action happens? I am new to Ember and I am not sure how to do things the Ember way so I turn to you.
My problem:
I have a sidebar, I created a View for it. I have two buttons on the sidebar for the moment. I added an action for each button on it. I am not sure if I should handle it on controller or on view. I want on clicking one of these button, a new view to be inserted that would open a pop up menu and also the button that called the action to remain in a selected state.
I am not very sure how to do this. I tried to target the view with the action but I can't have access to the target element or at least I don't know how to access it (tried this.$()).
What way do you suggest to follow?

A: User 'actions' are handled with methods on a Controller or a Route.  You should put them in an actions hash:
App.MyController = Ember.ObjectController.extend({
    actions: {
        doSomething: function() {
            // do it here
        }
    }
});

Ember manipulates the DOM and inserts views automatically based on resources and routes.  If you don't want to use the router, you can manually control the view hierarchy, but I'd suggest getting more familiar with Ember routing before you try manual views.
If I were you, I'd create a Component that handled the button.  You will have a reference to the DOM element in the didInsertElement callback: http://emberjs.com/api/classes/Ember.Component.html#event_didInsertElement


text:
Q: dropdown was working on localhost, but not on server? possibly .htaccess? I've uploaded a static website to server, and after realising the filepath was in the URL (eg, .co.uk/index.html) I've followed instructions on how to use .htaccess to remove. But now my dropdown options in my navbar don't work. No error message.
In localhost, the dropdown appears, but file doesn't exist (I think thats because I removed the file ext),
But on server, the dropdown doesn't even appear, in order to make a selection.
dropdown list:

              Services

              Physiotherapy
              Massage
              Pilates

              Acupuncture

.htaccess
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [NC,L]


text:
Q: System.IO.WriteAllBytes - Access to path denied error Currently developing a C# WinForms application in Visual Studio 2010 .NET 4 on Windows 7.
Firstly I am reading a stream of bytes from a file using the File.ReadAllBytes() method.  Then when attempting to write the file back, I am getting a access to path denied error when using the WriteAllBytes method.
I have tried passing in literal paths, Environment.SpecialFolder.ApplicationData, Path.GetTempPath(), but all are providing me with the same error.
I have checked permissions on these folders and also attempted to start the program in administrator mode with no luck.

A: In windows7 there are security issues on c:. If you modified the path to D: then no access denied issue will be there.
Try following sample code with Path.GetTempPath(), it will execute successfully.
    static void Main(string[] args)
    {
        string path = Path.GetTempPath();
        byte[] binaryData;
        string text = "romil123456";
        using (MemoryStream memStream = new MemoryStream(Encoding.ASCII.GetBytes(text)))
            {
                binaryData = memStream.ToArray();
            }
            System.IO.File.WriteAllBytes(@path + "\\words123.txt"    , binaryData);
        }
    }

Environment.SpecialFolder.ApplicationData provides the folder name, not provides the full path to that folder. so when you use this in path defined to write file, this folder is searched under in local application path.

A: Are you sure the file isn't still locked? If you are planning to read + write bytes from a file, you might want to consider using a Stream class (for example the FileStream), the advantage is that you will lock the file and that no other application can access the file in the meantime.
Code example from this topic:
FileStream fileStream = new FileStream(
  @"c:\words.txt", FileMode.OpenOrCreate,
  FileAccess.ReadWrite, FileShare.None);

A: Make sure that you specify the entire path when using File.WriteAllBytes() including file name.
File.WriteAllBytes() cannot write to a general directory, it has to write to a specific file.
Hope this helps.


text:
Q: Visual studio completion python I'm new to python in visual studio..I'm trying to have the same environment of sublime text.
I configured everything auto-formatting , auto-completion etc...
But when I write essential keyword like "self", the tool doesn't suggest me the keyword
So if I write "s" in sublime I obtain a suggest for "self".
But this don't happen in visual studio.
Is it normal? what can i do?

A: PTVS will only use autocomplete functionality in certain scenarios.  In order for 'self' to display after typing 's' you will need to press CTR+SPACE or CTR+J.  These are the default commands for autocomplete.  You can learn more at the completion page of the wiki.
Here's an excerpt:

Completions can be shown at any time by pressing Ctrl+J or Ctrl+Space, or may be triggered automatically by certain commands (such as import), operators (such as a period/full stop), or by typing at any place where completions are likely to be helpful.