text:
Q: Android honeycomb-like pattern for data from adapter Is it possible in Android to implement strategy of positioning for provided by Adapter elements like this (see image)?

Also in future I would like to make this bubbles interact with each other, react on touches. Could you please recommend some strategies (maybe, physics engines) to do this?


text:
Q: How can I utilise an incremental subset within a for loop in R? I have a dataset that contains ~40,000 data points on chicken weights over a crop cycle in various sheds(called houses). The main variables are: House Number (1:4), Days in the Crop (Continuous from 0.000001 days up to ~39 days, though some houses end before 39) and Weight in grams (though for the first 0.5-0.8 days the weight is NA since no readings are taken, but these still need to be kept to show growth from day 0).
I'm trying to use a for loop to calculate the average weight each day on a per house basis, and then I want to store that data in a new dataframe. I managed to successfully do this initially by subsetting the data into separate houses and then using the below loop:
house_1 <- subset(df,house==1)

daily_averages <- data.frame(Day = 1:39, Average=NA)
for (i in 1:1){
            lower = 0
            upper = 1
            weight = house_1$weight
            days = house_1$days_in_crop
                        for (meanroll in 1:39) {
                          meanroll_val = mean(weight[days > lower & days < upper],na.rm=TRUE)
                          daily_averages$Average[meanroll] <- meanroll_val
                          lower=lower+1
                          upper=upper+1
              }
}

This gives me a dataframe containing the average for each day, but only for House 1. Where Lower is the lower value of the day e.g. Start at 0 and Upper is the upper value of the day e.g. end of day 0 is 1 so any value between 0 and 1 is the first day. The i in 1:1 was so I didn't need to reset the lower and upper everytime I run it but also to allow me to hopefully convert it to using all 4 houses at once.
After this I tried building a second for loop that would store all averages for each day for each house in a single dataframe, what I have so far is below:
house_ID <- unique(df$house)
daily_data <- data.frame(HouseNumber=NA, Day = rep(1:39,length(house_ID), Average= NA)

     for (house_no in 1:length(house_ID)){
       lower= 0
       upper = 1
       weight = df$weight
       days= df$days_in_crop
       house_N <- subset(df,house==house_no)
         with(house_N,
          for(meanroll in 1:39){
            meanroll_val = mean(weight[days > lower & days < upper],na.rm=TRUE)
            daily_data$Average[meanroll] <- meanroll_val
            lower=lower+1
            upper=upper+1
          })
     }

Instead no values are being stored, I've also tried replacing
daily_data$Average[meanroll] <- meanroll_val

with
print(meanroll_val)

To see if the issue was not iterating through the subsets, instead I receive some values, followed by many NaN, some more values then some more NaN (though the combined number of values and NaN does total 156, 4*39)
Is there a better way to achieve this? I could just copy the output of the first for loop for each house, but in the future I'm likely to have many more houses so it will be more practical to have the second for loop
ETA: I also realise houses are not being assigned in that second for loop, but since it's also not working when using Print instead of storing the data, I don't think that's the issue
ETA: output of
dput(head(df, 20))

is:
structure(list(house = c(3L, 1L, 4L, 2L, 3L, 2L, 4L, 1L, 3L,
1L, 4L, 2L, 2L, 3L, 4L, 1L, 3L, 1L, 4L, 2L), days_in_crop = c(0.000856481,
0.001435185, 0.002025463, 0.003252315, 0.003657407, 0.003738426,
0.004479167, 0.005451389, 0.007766204, 0.008333333, 0.008912037,
0.010138889, 0.010497685, 0.010555556, 0.011365741, 0.012361111,
0.01462963, 0.015231481, 0.015798611, 0.017025463), weight = c(NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_)), row.names = c(NA,
20L), class = "data.frame")

A subset containing only days over 9 (note value is 9.1 since chickens tend to be sleeping at the start of the day so are not on sensors):
days_9_39 <- subset(df,days_in_crop > 9.1)
dput(head(days_9_39, 20))

structure(list(house = c(4L, 3L, 3L, 1L, 4L, 1L, 2L, 2L, 3L,
3L, 1L, 4L, 1L, 2L, 2L, 3L, 4L, 1L, 4L, 1L), days_in_crop = c(9.101712963,
9.101944444, 9.102847222, 9.10318287, 9.103229167, 9.106064815,
9.106145833, 9.1065625, 9.10837963, 9.108900463, 9.109849537,
9.110162037, 9.112581019, 9.113032407, 9.113159722, 9.114247685,
9.11462963, 9.116435185, 9.117118056, 9.119236111), weight = c(244L,
255L, 249L, 260L, 259L, 276L, NA, 260L, 254L, 254L, 244L, 265L,
268L, NA, 300L, 250L, 239L, 255L, 251L, 258L)), row.names = 10262:10281, class = "data.frame")

A: Here is a base R solution.
by splits the data by house, then aggregates by the integer part of days_in_crop.
res <- by(days_9_39, days_9_39$house, \(X) {
  X$days_in_crop <- floor(X$days_in_crop)
  agg <- aggregate(weight ~ days_in_crop, X, mean, na.rm = TRUE)
  agg$house <- X$house[1]
  agg[c(3, 1, 2)]
})

res <- do.call(rbind, res)
res
#>   house days_in_crop   weight
#> 1     1            9 260.1667
#> 2     2            9 280.0000
#> 3     3            9 252.4000
#> 4     4            9 251.6000

Created on 2022-10-20 with reprex v2.0.2

Edit
A simpler solution is to aggregate weight by all other variables, with integer days.
The changed days_in_crop is local only.
res2 <- local({
  days_9_39$days_in_crop <- floor(days_9_39$days_in_crop)
  aggregate(weight ~ ., days_9_39, mean, na.rm = TRUE)
})
res2
#>   house days_in_crop   weight
#> 1     1            9 260.1667
#> 2     2            9 280.0000
#> 3     3            9 252.4000
#> 4     4            9 251.6000

all.equal(res, res2, check.attributes = FALSE)
#> [1] TRUE

Created on 2022-10-20 with reprex v2.0.2

Edit 2
To include other aggregate statistics, create a temporary, local function with all wanted statistics but note that the results column is a matrix, the result must be slightly processed before returning.
res3 <- local({
  f <- function(x) {
    c(mean = mean(x, na.rm = TRUE), sd = sd(x, na.rm = TRUE))
  }
  days_9_39$days_in_crop <- floor(days_9_39$days_in_crop)
  agg <- aggregate(weight ~ ., days_9_39, f)
  cbind(agg[-ncol(agg)], agg[[ncol(agg)]])
})
res3
#>   house days_in_crop     mean        sd
#> 1     1            9 260.1667 10.998485
#> 2     2            9 280.0000 28.284271
#> 3     3            9 252.4000  2.701851
#> 4     4            9 251.6000 10.620734

Created on 2022-10-20 with reprex v2.0.2

redpajama_set_name: RedPajamaStackExchange


text:
Q: How many way can you encode a five letter word I have a solution for this problem, but the way iv carried it out seem a bit long and am wondering if and only if my ans is correct if there is a shorter method or maybe and alternate way of looking at the problem.
So here is the question, ignore the first part of the problem, though I do believe it could be used to solve the second part.
Question

Consider a language short speak that has only a 5 letter alphabet A,B,C,D and E and in which all words have either 1,2,3,4 or 5 letter. Repetition of letter in a single word is permitted in short speak.
a) What is the maximum number of possible words in short speak? Do not consider rules of spelling in English.
We consider a general, so-called mono-alphabetic cipher in which each alphabetical letter in a plain text message is uniquely coded to another, different letter in the alphabet and vice versa. One example of suck a cipher is a Caesar 'shift 2' cipher in which A is encoded as C and B is encoded as D and so on.
b) How many ways are there to encipher a 5 letter short speak word in which no letter is repeated?

My solution
My first assumption is that the five word can be of the form : AAAAA, as indicated by ''Repetition of letter in a single word is permitted in short speak''
So I used the following diagram to workout the possible way to encipher.

My digram follow the logic that the first letter I can pick to encode A can be either B C D E which means I have 4 possible choices, so I picked D. For the second letter I cant choose D as this is not allowed therefore I only have 3 possible choices in this case I picked B and so forth now because all letter in the word are the same by the time I encipher the fourth letter all my possible choice to encipher the 5th are gone so that letter remains the same. Therefore in total I have 24 ways to encipher the word.
Now if I change the five letter word as to AAEDB for example and use the same method as shown in diagram below I get 48 ways to encipher.

So depending if the word is all the same letter or one letter different means a different out come, so there are in total 72 ways that a five letter word can be encipherd.
Is this correct? If so is there a shorter more compact way to look at this type of problem that I may have missed.

A: a) Maximum number of words. There are $5^5$ words of length $5$, $5^4$ of $4$, etc.
So in total: $5^5 + 5^4 + 5^3 + 5^2 + 5^1$
b) If no letter is repeated there are 5 choices for the first letter, 4 for the second etc,
giving a total of $5! = 120$ different words.


text:
Q: Filter nested query if no results in Django I have three basic nested serializers that are currently returning a nested data structure (shown below) when I use this query:
queryset = Regulation.objects.all()
serializer_class = RegulationSerializer(queryset, many=True)

My models.py is as follow:
class Regulation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.TextField(null=False)
    documents = models.ManyToManyField(Document, related_name='regulation_documents', through="DocumentRegulation")
    portal = models.BooleanField(default=False)

class RegulationVersion(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    regulation = models.ForeignKey(Regulation, related_name='versions', blank=False, null=False, on_delete=models.DO_NOTHING)
    name = models.CharField(max_length=20, null=False)

class Iteration(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    version = models.ForeignKey(RegulationVersion, related_name='iterations', blank=False, on_delete=models.DO_NOTHING)
    organization = models.ForeignKey(Organization, blank=False, null=False, on_delete=models.DO_NOTHING)
    name = models.CharField(max_length=60, blank=False, null=False)
    date_created = models.DateTimeField(_('created at'), auto_now_add=True)
    created_by_user = models.ForeignKey(User, blank=False, null=False, on_delete=models.DO_NOTHING)

    class Meta:
        unique_together= ('name', 'organization', 'version')

With the serializers.py structured as:
class FilteredIterationSerializer(serializers.ListSerializer):
    def to_representation(self, data):
        organization_id = self.context.get('organization_id')
        data = data.filter(organization=organization_id)
        return super(FilteredIterationSerializer, self).to_representation(data)python

class IterationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Iteration
        list_serializer_class = FilteredIterationSerializer
        fields = ('id', 'organization', 'version', 'name', 'date_created', 'created_by_user')

class VersionSerializer(serializers.ModelSerializer):
    iterations = IterationSerializer(many=True, read_only=True)
    class Meta:
        model = RegulationVersion
        fields = ('name', 'iterations')

class RegulationSerializer(serializers.ModelSerializer):
    versions = VersionSerializer(many=True, read_only=True)
    class Meta:
        model = Regulation
        fields = ('name', 'versions')
        depth = 2

serialized output:
[{ name: "2019-final"
  versions: {
       0: { name: "2019-01",
            iterations: (25) [{…}, {…}, {…}]
          }
       1: { name: "2019-02",
            iterations: []
          }
 }
{ name: "2020-final"
  versions: {
       0: { name: "2020-01",
            iterations: []
          }
       1: { name: "2020-02",
            iterations: []
          }
 }]

How do I exclude all of the versions without any iterations, and also exclude the regulations without any versions or nested iterations.
Using the above serialized output, I would not want to return the object where name is "2020-final", because none of its versions have iterations. I would also not want to return the version object where name is "2019-02", because it has no iterations. The desired output would look like this:
[{ name: "2019-final"
  versions: {
       0: { name: "2019-01",
            iterations: (25) [{…}, {…}, {…}]
          }
 }]

A: Background:
Whenever any nested serializer has many=True argument passed, DRF creates a list serializer instance behind the scene (check BaseSerializer.__new__ and BaseSerializer.many_init methods), with keeping the original serializer as the child class-attribute of the list serializer. Then whenever serialization is needed (when you access serializer.data), as usual, the to_representation of the list serializer is called, the list serializer then, in turn, calls to_representation of the child serializer and returns a list as output.
The default list serializer is serializers.ListSerializer, it be changed via the serializer Meta class option list_serializer_class.
So if we need to change the representation, we need to create our list serializer class and override to_representation to return the modified response.

At first, let's handle the VersionSerializer to only show the versions that have related iteration(s):
class VersionListSerializer(serializers.ListSerializer):

    def to_representation(self, data):
        versions = data.all() if isinstance(data, models.Manager) else data
        return [
            self.child.to_representation(version)
            for version in versions
            if version.iterations.exists()
        ]

class VersionSerializer(serializers.ModelSerializer):
  iterations = IterationSerializer(many=True, read_only=True)

  class Meta:
      model = RegulationVersion
      list_serializer_class = VersionListSerializer
      fields = ('name', 'iterations')

Similar logic for RegulationSerializer, showing only the regulations that have related version(s):
class RegulationListSerializer(serializers.ListSerializer):

    def to_representation(self, data):
        regulations = data.all() if isinstance(data, models.Manager) else data
        return [
            self.child.to_representation(regulation)
            for regulation in regulations
            if regulation.versions.exists()
        ]

class RegulationSerializer(serializers.ModelSerializer):
    versions = VersionSerializer(many=True, read_only=True)

    class Meta:
        model = Regulation
        list_serializer_class = RegulationListSerializer
        fields = ('name', 'versions')


text:
Q: PHP 7.0 on Ubuntu 16 - pdo_mysql.so: undefined symbol: mysqlnd_connect I'm gettind this PDOException could not find driver
here is my /etc/php/7.0/apache2/php.ini file
;extension=php_bz2.dll
extension=php_curl.dll
extension=php_fileinfo.dll
;extension=php_ftp.dll
;extension=php_gd2.dll
;extension=php_gettext.dll
;extension=php_gmp.dll
extension=php_intl.dll
;extension=php_imap.dll
;extension=php_interbase.dll
;extension=php_ldap.dll
extension=php_mbstring.dll
;extension=php_exif.dll      ; Must be after mbstring as it depends on it
;extension=php_mysqli.dll
;extension=php_oci8_12c.dll  ; Use with Oracle Database 12c Instant Client
;extension=php_openssl.dll
;extension=php_pdo_firebird.dll
extension=php_pdo_mysql.dll
;extension=php_pdo_oci.dll
;extension=php_pdo_odbc.dll
;extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll
;extension=php_pgsql.dll
;extension=php_shmop.dll

and when I run php in my server I get this warning PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/20151012/pdo_mysql.so' - /usr/lib/php/20151012/pdo_mysql.so: undefined symbol: mysqlnd_connect in Unknown on line 0

A: I had to make sure that /usr/lib/php/20151012/mysqlnd.so exists and my modules were been enabled by the /etc/php/7.0/mods-available directory, there were multiple .ini files, except for mysqlnd.ini
so I created it
sudo nano mysqlnd.ini

and put this content:
; configuration for php common module
; priority=10
extension=mysqlnd.so

restarted apache
sudo service apache2 restart


text:
Q: How to use Box-Muller transform to generate n-dimensional normal random variables I'm trying to generate random variables. I read about Box-Muller transform which is a way to generate a pair of normal variables, 2-d normal distrubution. But how do I expand that transform to generate 3-d, 4-d, etc. normal variables with this approach? Or is there a different approach to consider?

A: Box-Muller generates pairs of independent normals from pairs of independent uniforms.
To get more than two independent normals, generate more uniforms. If you want 17 normals, generate 18 uniforms, and get 9 pairs of normals. Discard one. If your 18 uniforms are independent, your 17 normals should be.
http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
(Incidentally Marsaglia appears to have invented this kind of approach first, I think perhaps in the polar-method form detailed at  the link. But because it was right after the war, it was treated as a secret and he was not able to publish it.)
You can also get correlated normals by starting from independent ones, for example via use of a Choleski decomposition of the covariance matrix.


text:
Q: Android location manager compilation error I'm trying to retrieve an instance of a LocationManager class (do get some GPS related information). I have used wrote a simple class to do so, but it end up giving me an error
Cannot make a static reference to the non-static method getSystemService(String) from the type Context

here's my class
public class LocationManagerHelper {

    static Location location = null;

    public static Location getLocation () {
        LocationManager manager = (LocationManager) Context.getSystemService(Context.LOCATION_SERVICE);

        if(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        } else {
            System.out.println("Provider is disabled");
        }
        return location;
    }
}

Thanks.

A: The error message means that you're using a class (Context) to make a call that requires a class instance.
You need to pass a Context instance into getLocation, and use that Context instance to invoke getSystemService.
public static Location getLocation (Context context) {
    LocationManager manager =
        (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    //....

If you're using LocationManagerHelper from an Activity, then you could pass the Activity as a Context:
LocationManagerHelper.getLocation(this); // "this" being an Activity instance


text:
Q: Forward price in Black Scholes Model Recall that a forward contract on $S_T$ contracted at time $t$, with time of delivery $T$, and with forward price $f(t; T, S_T)$ can be seen as a contingent T-claim $X$ with payoff:
$$
X = S_T - f(t; T, S_T)
$$
The forward price is determined at time t in such a way that the price of X is zero at time t, i.e. $\pi(t;X) = 0$.
How can I compute the forward price $f(t; T, S_T )$ in the Black-Scholes model?

A: Without loss of generality take $t=0.$ The price of any European claim $g(S_T)$ under black scholes is given by:
$$
P = {\mathbb E}^*[e^{-rT} g(S_T)].
$$
For the forward contact $g(S_T) = S_T -K$ and we would like to choose $K$ sothat $P=0$, then:
$$
0= {\mathbb E}^*[e^{-rT}(S_T -K)]
$$
($K$ is the $ f(t;T,S_T)$ in your question).
The discounted price process $e^{-rt}S_t$ is a martingale under the risk neutral $P^*$ measure, therefore ${\mathbb E}^*[e^{-rT}S_T] =S_0.$ This and the last equation gives
$$
Ke^{-rT}  = S_0
$$
and therefore, $K =S_0 e^{rT}.$
In fact, this price is correct for any risk neutral pricing model (not just BS) and will continue to hold as long as the interest rate is constant.


text:
Q: How to push your local master branch to Heroku when you've already pushed a feature branch? To try out a feature branch, I pushed it to Heroku's master (since that's the only branch it uses for your website), i.e. I did:
git push heroku feature-foo:master

Meanwhile, I made some commits to my local master branch. Now I want to push my local master back out to Heroku, but am getting:
To git@heroku.com:foo-repo.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'git@heroku.com:foo-repo.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Merge the remote changes (e.g. 'git pull')
hint: before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

This makes sense, because indeed Heroku's master is really on my feature-foo branch and thus is ahead of master. But I don't want to pull and merge from Heroku -- because that would be the same as merging my feature-foo branch, which I don't want to do. Right now, I just want to push my local master without the feature-foo commits. (Indeed I have already used heroku rollback so that the feature-foo changes aren't live on the site.)
How do I do that?

A: The answer turns out to be simple. Do a forced push, i.e.
git push -f heroku master

A: You can also go to your sites heroku dashboard and rollback to a previous build from before you pushed off a non master branch.
visit dashboard.heroku.com/apps/your-app-goes-here/activity
Once there you should see:

Click Roll back to here on the build you'd like to go back to. Once you've rolled back to correct build you can push from master without having to use force.


text:
Q: Chrome background tab high CPU usage: how to profile? I have a chrome tab that uses 100% CPU when it's restored from a chrome crash. When I bring it to the foreground it drops back to normal CPU.
How can I start profiling on the tab without switching to it, so I can catch it in the act of misbehaving?


text:
Q: numpy arange and where I am trying to find values in an array created by "arange" by means of "where", but it seems it does not work fine. Here is one example:
from numpy import arange, where

myarr = arange(6.6,10.25,0.05)
for item in [6.6,6.65,6.7,6.8,6.9,6.95,7.95,8.0,8.1,8.15,6.2,6.25,6.35]:
 print where(myarr == item)

(array([0]),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)
(array([], dtype=int32),)

Using Python 2.5.4, Numpy 1.3.0
Thanks in advance!

A: Note:
In [32]: repr(myarr[1])
Out[32]: '6.6499999999999995'

In [33]: repr(6.65)
Out[33]: '6.6500000000000004'

So the float64 value that np.arange assigns to myarr[1] is not exactly the same float that Python uses to represent 6.65.
So, unless you really know what you are doing, never test floats for equality. Use inequalities instead:
def near(a,b,rtol=1e-5,atol=1e-8):
    try:
        return np.abs(a-b)<(atol+rtol*np.abs(b))
    except TypeError:
        return False

myarr = np.arange(6.6,10.25,0.05)
for item in [6.6,6.65,6.7,6.8,6.9,6.95,7.95,8.0,8.1,8.15,6.2,6.25,6.35]:
    print (np.where(near(myarr,item)))

# (array([0]),)
# (array([1]),)
# (array([2]),)
# (array([4]),)
# (array([6]),)
# (array([7]),)
# (array([27]),)
# (array([28]),)
# (array([30]),)
# (array([31]),)
# (array([], dtype=int32),)
# (array([], dtype=int32),)
# (array([], dtype=int32),)


text:
Q: .NET issues Updating (Date / Bit fields) SalesForce Enterprise WSDL We update 3 fields - Status (string), Date and Boolean (SalesForce Enterprise WSDL) using the below code and only the Status is getting updated, but not Date and Boolean. Even tried using "_cSpecified = True" for Boolean, but it didn't work. Please help.
'Update SalesForce Status to 9, Delivery Date and Delivered Bit Flag
Dim updateQuery As Obj = New Obj
updateQuery.Id = ReportID
updateQuery.Deliver_to_Customer_Date__c = DateTime.Now.Date.ToString.Replace("#", "").Substring(0, 10)
updateQuery.Delivered_to_Customer__cSpecified = True
updateQuery.Status__c = "9 - Pdf report delivered to customer"
Dim SaveResults() As SaveResult = _sForceRef.update(New sObject() {updateQuery})

A: You need to set both the value field (to the value you want to send) and the specified field (to tell .NET to send it), e.g.
updateQuery. Delivered_to_Customer__c = true
updateQuery. Delivered_to_Customer__cSpecified = true


text:
Q: https redirection IIS I am currently redirecting http_example and http_www.example to https_www.example on IIS/Server 2016. The redirection works well with 2 rewrite rules. However, I am unable to figure out how to redirect https://example to https://www.example.
Appreciate your help. Thanks

A: You can achieve it even with one rule. In your case rule should be:
<rule name="All in one URL" stopProcessing="true">
   <match url=".*" />
   <conditions logicalGrouping="MatchAny">
       <add input="{HTTPS}" pattern="off" />
       <add input="{HTTP_HOST}" pattern="^www\." negate="true" />
   </conditions>
   <action type="Redirect" url="https://www.example.com{URL}" />
</rule>


text:
Q: Django: Trouble with named URLs instead of ids So I'm making a study app that involves flash cards. A user can make subjects and put decks containing cards in them. So for example, in the Biology subject, there would be a Deck called "unit one" and in that deck would be full of cards. The URL for a deck would ideally look like
localhost:8000/subjects/Biology/unit-one/

Here is my code
views.py
class IndexView(generic.ListView):
  template_name = 'card/index.html'
  context_object_name = 'subjects'

  def get_queryset(self):
      return Subject.objects.all()

class SubjectView(DetailView):
  model = Subject
  slug_field = "subject"
  template_name = 'card/subject.html'

class DeckView(DetailView):
  model = Deck
  template_name = 'card/deck.html'

  def get_object(self, subjects, deck):
      subject_obj = Subject.objects.filter(subject_name=subjects).first()
      obj = Deck.objects.filter(subject=subject_obj, deck_name=deck).first()
      return obj

  def get(self, request, subjects, deck):
      self.object = self.get_object(subjects, deck)
      context = self.get_context_data(object=self.object)
      return self.render_to_response(context)

models.py
class Subject(models.Model):
  subject_name = models.CharField(max_length=100)
  description = models.TextField()

  def __str__(self):
      return self.subject_name

  def get_absolute_url(self):
      return reverse('card:index')

class Deck(models.Model):
  deck_name = models.CharField(max_length=100)
  subject = models.ForeignKey(Subject, on_delete=models.CASCADE)

  def __str__(self):
      return self.deck_name

class Card(models.Model):
  term = models.CharField(max_length=100)
  definition = models.TextField()
  deck = models.ForeignKey(Deck, on_delete=models.CASCADE)

  def __str__(self):
      return self.term

urls.py
url(r'^subjects/(?P<subject>[\w ]+)/$', views.SubjectView.as_view(), name='subject'),
url(r'^subjects/(?P<subject>[\w ]+)/(?P<deck>[\w ]+)/$', views.DeckView.as_view(), name='deck'),

index.html

subject.html

  {% for deck in subject.deck_set.all %}

{{deck.deck_name}}

  {% endfor %}

However, I am getting this error.
Generic detail view SubjectView must be called with either an object pk or a slug.

The index page is showing properly, but when I click on a subject, I get that error. How do I fix this?

A: Just an assumption. Try by change Char to Slug
class Subject(models.Model):
  subject_name = models.SlugField(max_length=100)
  description = models.TextField()

Also
slug_field = "subject_name"

A: Have you tried setting SubjectView.slug_url_kwarg?


text:
Q: Why I am not able to send an email using Amazon SES service? I created a wd site, where a user1 can send email to user2.  My account is removed from the Amazon SES sandbox. You will find, my code bellow.
My  SMTP credentials are configured in US East (Ohio). But my location is in Canada. And the two emails that i am using are Canadian addresses (yahoo.ca)
I don't understand why the User1 is not able to send an email to User2?
Here is my code:
 public void SendEmail(string sender, string recipient, string messageBODY)
    {
        // Replace sender@example.com with your "From" address.
        // This address must be verified with Amazon SES.
        String FROM = sender;
        String FROMNAME = "Sender Name";

        // Replace recipient@example.com with a "To" address. If your account
        // is still in the sandbox, this address must be verified.
        String TO = recipient;

        // Replace smtp_username with your Amazon SES SMTP user name.
        String SMTP_USERNAME = "CAIASJA3JM5CXUEYAIAB";

        // Replace smtp_password with your Amazon SES SMTP password.
        String SMTP_PASSWORD = "RD75K2MbhvOYnBf20WYZ5O9oZlj9lCBH/hqrEIYnClYT";

        // (Optional) the name of a configuration set to use for this message.
        // If you comment out this line, you also need to remove or comment out
        // the "X-SES-CONFIGURATION-SET" header below.
        //String CONFIGSET = "ConfigSet";

        // If you're using Amazon SES in a region other than US West (Oregon),
        // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP
        // endpoint in the appropriate AWS Region.
        String HOST = "email-smtp.us-east-2.amazonaws.com";

        // The port you will connect to on the Amazon SES SMTP endpoint. We
        // are choosing port 587 because we will use STARTTLS to encrypt
        // the connection.
        int PORT = 587;

        // The subject line of the email
        String SUBJECT =
            "Amazon SES test (SMTP interface accessed using C#)";

        // The body of the email
        String BODY = messageBODY;

        // Create and build a new MailMessage object
        MailMessage message = new MailMessage();
        message.IsBodyHtml = true;
        message.From = new MailAddress(FROM, FROMNAME);
        message.To.Add(new MailAddress(TO));
        message.Subject = SUBJECT;
        message.Body = BODY;
        // Comment or delete the next line if you are not using a configuration set
        //message.Headers.Add("X-SES-CONFIGURATION-SET", CONFIGSET);

        using (var client = new System.Net.Mail.SmtpClient(HOST, PORT))
        {
            // Pass SMTP credentials
            client.Credentials =
                new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);

            // Enable SSL encryption
            client.EnableSsl = true;

            // Try to send the message. Show status in console.
            try
            {
                Console.WriteLine("Attempting to send email...");
                client.Send(message);
                Console.WriteLine("Email sent!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("The email was not sent.");
                Console.WriteLine("Error message: " + ex.Message);
            }
        }
    }

Thank you for help


text:
Q: Printer Canon Pixma MX925 on 16.04 I have a "Canon Pixma MX925" printer and run Ubuntu 16.04 on my computer.
How can I install and use this printer?

A: so go here http://support-asia.canon-asia.com/contents/ASIA/EN/0100517002.html and click to download and SAVE what will be cnijfilter-mx920series-3.90-1-deb.tar.gz
You need to open a terminal; and paste the commands below in line by line, hitting the ENTER key after each paste: to find PASTE in the terminal, right-click at the text prompt .....
cd Downloads
tar -zxvf cnijfilter-mx920series-3.90-1-deb.tar.gz
cd cnijfilter-mx920series-3.90-1-deb
./install.sh

and that final command runs the install script; it will ask you for your sudo password but it does 2 things: 1) installs drivers and 2) registers the printer on lpadmin so it should all work


text:
Q: Using mp3wrap with Python via Popen - arguments are not being executed I'm trying to append one mp3 to another--hundreds, actually, but I'm starting with a simplified script here and unable to get Python to work correctly with the command line (Windows). It prints out only the mp3wrap instructions as if I'd only executed 'mp3wrap' at the command line without any arguments. What I need is the full 'mp3wrap newFile.mp3 FLN1.mp3 FLN2.mp3' to be executed. Can anyone advise? Thanks.
from subprocess import Popen, PIPE

process = Popen(['mp3wrap', 'newFile.mp3 FLN1.mp3 FLN2.mp3'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
print stdout


text:
Q: SQL find record that matches in any of three tables I have the following schema:
user -- user_id | first_name
full_time_job -- ft_job_id | user_id
part_time_job -- pt_job_id | user_id
internship -- internship_id | user_id

I'd like to write a query that returns all users that exist in any of the three job tables.  What's the best way to do this? I'd prefer to use LEFT JOINS over WHERE EXISTS if possible, but will be happy with the best working solution.
I do NOT want to return any users that exist in NONE of the three job tables.

A: Using LEFT JOINs, you merely need to verify that user_id is NOT NULL in at least one of the tables:
SELECT
  [user].user_id
FROM
  [user]
  /* LEFT JOIN against each of the 3 tables */
  LEFT JOIN full_time_job ft ON [user].user_id = ft.user_id
  LEFT JOIN part_time_job pt ON [user].user_id = pt.user_id
  LEFT JOIN internship intern ON [user].user_id = intern.user_id
WHERE
  /* And check that *any* of them has a non-null user_id */
  ft.user_id IS NOT NULL
  OR pt.user_id IS NOT NULL
  OR intern.user_id IS NOT NULL

Best to fix the schema if possible...
In the long run though, if possible these should all probably be combined into a single table that has a column indicating the job type, rather than 3 similar tables.
Sample: http://sqlfiddle.com/#!2/2cd2c/1
In the above example, users 5,6 don't exist in any of the 3 tables.

A: You can do this:
SELECT DISTINCT *
FROM "user"
WHERE user_id
IN
(
    SELECT user_id
    FROM
    (
       SELECT user_id FROM full_time_job
       UNION ALL
       SELECT user_id FROM part_time_job
       UNION ALL
       SELECT user_id FROM internship
   ) t
   WHERE user_id IS NOT NULL
)

Or: Using a CTE, you can write it this way:
;WITH AllUsers
AS
(
    SELECT user_id FROM full_time_job
    UNION ALL
    SELECT user_id FROM part_time_job
    UNION ALL
    SELECT user_id FROM internship
)
SELECT *
FROM "user"
WHERE user_id IN ( SELECT user_id
                   FROM AllUsers
                   WHERE user_id IS NOT NULL);

SQL Fiddle Demo


text:
Q: Iterate over vector using loop c++ Let's say I have a vector of long long elements:
std::vector<long long>V {1, 2, 3};

I have seen that in order to iterate over the vector you can do this:
for (auto i = v.begin() ; i != v.end() ; i++)
   cout<<*i;

i++ means i grows by 1, but shouldn't the address go up 8 bytes to print the next element? So "growing" part of the for loop(for any type) should look like this:
i += sizeof(v[0]);

I'm assuming an address can hold 1 byte , so if the starting address of an integer would be 1000 , then its total allocation will be represented by adresses:1000 , 1001 , 1002 , 1003.I would like to understand memory better so I'd be thankful if you could help me.

A: When you increment a pointer it goes up by the "size of" the pointer's type. Remember, for a given pointer i, i[0] is the first element and is equivalent to *(i + 1).
Iterators tend to work in a very similar fashion so their operation is familiar, they feel like pointers due to how operator* and operator-> are implemented.
In other words, the meaning of i++ depends entirely on what i is and what operator++ will do on that type. Seeing ++ does not automatically mean +1. For iterators it has a very specific meaning, and that depends entirely on the type.
For std::vector it moves a pointer up to the next entry. For other structures it might navigate a linked list. You could write your own class where it makes a database call, reads a file from disk, or basically whatever you want.
Now if you do i += sizeof(v[0]) instead then you're moving up an arbitrary number of places in your array. It depends on what the size of that entry is, which depends a lot on your ISA.
std::vector is really simple, it's just a straight up block of memory treated like an array. You can even get a pointer to this via the data() function.
In other words think of i++ as "move up one index" not "move up one byte".

A: One of the nice things about the way you've written this code is that you don't need to worry about bytes.
Your auto type for i is masking the fact that it's a vector iterator, in other words, a special type that is designed for accessing members of a vector of long long. This means that *i evaluates to a long long pulled from whichever member of the vector i is currently indexing, so i++ advances i to index the next member of the vector.
Now, in terms of low level implementation, the values 1, 2, 3 are probably sitting in adjacent 8-byte blocks of memory, and i is probably implemented as a pointer, and incrementing i is probably implemented by adding 8 to its value, but each of those assumptions is going to depend on your architecture and the implementation of your compiler. And as I said, it's something you probably don't need to worry about.


text:
Q: Is this question solvable? $2$ non-linear equations and the proof that the solution is unique As mentioned in the title I want to show the uniqueness of the solution to $2$ non-linear equations. However, it seems that I can not solve this question with my current mathematical knowledge. More than this I am not aware about the difficulty of the problem. Is this question solvable by a very good mathematician at all? This is also what I wonder very much.
Let me introduce my problem:
I have orgininally $4$ equations as given below.
$$\int_{-\infty}^{y_l}\frac{b}{eb^{\mu_1}}f_1(y)\mathrm{d}y+\int_{y_l}^{y_u}K_1 l(y)^{\frac{-\ln(b)}{\ln(a b)}}f_1(y)\mathrm{d}y+\int_{y_u}^{\infty}\frac{1}{eb^{\mu_1}}f_1(y)\mathrm{d}y=1$$
$$\int_{-\infty}^{y_l}\frac{1}{ea^{\mu_0}}f_0(y)\mathrm{d}y+\int_{y_l}^{y_u}K_0 l(y)^{\frac{\ln(a)}{\ln(a b)}}f_0(y)\mathrm{d}y+\int_{y_u}^{\infty}\frac{a}{ea^{\mu_0}}f_0(y)\mathrm{d}y=1$$
$$\small \int_{-\infty}^{y_l}\frac{b}{eb^{\mu_1}}\ln \left(\frac{b}{e b^{\mu_1}}\right)f_1(y)\mathrm{d}y+\int_{y_l}^{y_u}K_1 l(y)^{\frac{-\ln(b)}{\ln(a b)}}f_1(y) \ln \left( K_1 l(y)^{\frac{-\ln(b)}{\ln(a b)}}\right)\mathrm{d}y+\int_{y_u}^{\infty}\frac{1}{eb^{\mu_1}}\ln \left(\frac{1}{eb^{\mu_1}}\right)f_1(y)\mathrm{d}y=\epsilon_1$$
$$\small \int_{-\infty}^{y_l}\frac{1}{ea^{\mu_0}}\ln \left(\frac{1}{e a^{\mu_0}}\right)f_0(y)\mathrm{d}y+\int_{y_l}^{y_u}K_0 l(y)^{\frac{\ln(a)}{\ln(a b)}}f_0(y) \ln \left( K_0 l(y)^{\frac{\ln(a)}{\ln(a b)}}\right)\mathrm{d}y+\int_{y_u}^{\infty}\frac{a}{e a^{\mu_0}}\ln \left(\frac{a}{ea^{\mu_0}}\right)f_0(y)\mathrm{d}y=\epsilon_0$$
Given:
$\rightarrow f_0$ and $f_1$ are some density functions
$\rightarrow l(y)=\frac{f_1(y)}{f_0(y)}$ is an increasing function
$\rightarrow  b=l(y_u),\quad a=\frac{1}{l(y_l)}$
$\rightarrow K_0=\frac{e^{\frac{\ln^2(a)}{\ln (ab)}}}{e a^{\mu_0}},\quad K_1=\frac{e^{\frac{\ln^2(b)}{\ln (ab)}}}{e b^{\mu_1}}$

As you can see the first two equations can be inserted into the third and fourth equation via $e a^{\mu_0}$ and $e b^{\mu_1}$. As a result we can obtain
$$z_0=\int_{-\infty }^{y_l} f_0(y) \, \mathrm{d}y+\int _{y_l}^{y_u}e^{\frac{\text{ln}^2(a)}{\text{ln}(ab)}}l(y)^{\frac{\text{ln}[a]}{\text{ln}(ab)}}f_0(y)\mathrm{d}y+\int _{y_u}^{\infty }a f_0 (y)\mathrm{d}y$$
$$z_1=\int _{-\infty }^{y_l}b f_1(y)\mathrm{d}y+\int _{y_l}^{y_u}e^{\frac{\text{ln}^2(b)}{\text{ln}(ab)}}l(y)^{\frac{-\text{ln}[b]}{\ln (ab)}}f_1(y)\mathrm{d}y+\int_{y_u}^{\infty } f_1(y) \, \mathrm{d}y$$
$$h_0=-\text{ln}(z_0)+\frac{1}{z_0}\left(\int _{y_l}^{y_u}e^{\frac{\text{ln}^2(a)}{\text{ln}(ab)}}l(y)^{\frac{\text{ln}(a)}{\text{ln}(ab)}}\text{ln}\left(e^{\frac{\text{ln}^2(a)}{\text{ln}(ab)}}l(y)^{\frac{\text{ln}(a)}{\text{ln}(ab)}}\right)f_0(y)\mathrm{d}y+\int _{y_u}^{\infty }a\text{ln}(a)f_0 (y)\mathrm{d}y\right)=\epsilon_0$$
$$h_1=-\text{ln}(z_1)+\frac{1}{z_1}\left(\int _{y_l}^{y_u}e^{\frac{\text{ln}^2(b)}{\text{ln}(ab)}}l(y)^{-\frac{\text{ln}(b)}{\text{ln}(ab)}}\text{ln}\left(e^{\frac{\text{ln}^2(b)}{\text{ln}(ab)}}l(y)^{-\frac{\text{ln}(b)}{\text{ln}(ab)}}\right)f_1(y)\mathrm{d}y+\int _{-\infty}^{y_l }b\text{ln}(b)f_1 (y)\mathrm{d}y\right)=\epsilon_1$$
Now I have two functions $h_0(y_l,y_u)=\epsilon_0$ and $h_1(y_l,y_u)=\epsilon_1$.
My conjecture:
There exists a unique solution to $\{h_0(y_l,y_u)=\epsilon_0,\,h_1(y_l,y_u)=\epsilon_1\}$ with some $\{y_l,y_u\}\in\mathbb{R}$ for $\{\epsilon_0\in[0,h_0(y_l\rightarrow -\infty,y_u \rightarrow \infty)],\epsilon_1\in[0,h_1(y_l\rightarrow -\infty,y_u \rightarrow \infty)]\}$
My Question:
Prove or disprove if my conjecture is correct.

Extra Information:
When $y_l\rightarrow -\infty$ and $y_u\rightarrow \infty$, the first $4$ equations above simplifies considerably. Then, for the equation $h_0$ we have a single parameter $0<x=\frac{\ln(a)}{\ln(a b)}<1$. If we take the derivative with respect to $x$, we can show that it is positive. The latter part of this proof (to show that it is positive) can be seen here Prove or disprove that the given expression is "always" positive , thanks to @julien. I havent done by my own but I would guess that the similar story also applies to $h_1$, and this determines the set $\{\epsilon_0\in[0,h_0(y_l\rightarrow -\infty,y_u \rightarrow \infty)],\epsilon_1\in[0,h_1(y_l\rightarrow -\infty,y_u \rightarrow \infty)]\}$ for which a unique solution is sought for.


text:
Q: D3.js tweening forward and backward to a specific point i just started playing around with Tweening in D3 and at start looked easy but now I'm struggling to achive this in my current code:

*

*Tweening to a specific point, example: from 0,0 to lineData[4]

*Tweening back to point 0,0 from lineData[4]

(Probably using buttons to control this)
This is my code at the moment: https://jsfiddle.net/uozko2bw/2/
//The data for our line
var lineData = [
{ "x": 1,   "y": 5},  { "x": 20,  "y": 20},
{ "x": 40,  "y": 10}, { "x": 60,  "y": 40},
{ "x": 80,  "y": 5},  { "x": 100, "y": 60}];

var lineFunction = d3.line()
 .x(function(d) { return d.x; })
 .y(function(d) { return d.y; })
 .curve(d3.curveCardinal);

//The SVG Container
var svgContainer = d3.select("body").append("svg")
    .attr("width", 200)
    .attr("height", 200);

//The line SVG Path we draw
var lineGraph = svgContainer.append("path")
 .attr("d", lineFunction(lineData))
 .attr("stroke", "blue")
 .attr("stroke-width", 2)
 .attr("fill", "none");

 var circle = svgContainer.append("circle")
  .attr("r", 5)
  .attr("transform", "translate(" + lineData[0].x + "," + lineData[0].y +
 ")");

 transition();

 function transition() {
  circle.transition()
  .duration(10000)
  .attrTween("transform", translateAlong(lineGraph.node()))
  .each("end", transition);
 }

 function translateAlong(path) {
 var l = path.getTotalLength();

 return function(d, i, a) {
   return function(t) {
     var p = path.getPointAtLength(t * l);
     return "translate(" + p.x + "," + p.y + ")";
   };
 };
}

A: That t in the interpolator typically goes from 0 to 1:

The returned interpolator will then be invoked for each frame of the transition, in order, being passed the eased time t, typically in the range [0, 1].

Thus, you can simply call another interpolator with t going from 1 to 0:
var p = path.getPointAtLength((1-t) * l);

Here is the demo:

//The data for our line
 var lineData = [
  { "x": 1,   "y": 5},  { "x": 20,  "y": 20},
   { "x": 40,  "y": 10}, { "x": 60,  "y": 40},
   { "x": 80,  "y": 5},  { "x": 100, "y": 60}];

var lineFunction = d3.line()
     .x(function(d) { return d.x; })
     .y(function(d) { return d.y; })
     .curve(d3.curveCardinal);

//The SVG Container
var svgContainer = d3.select("body").append("svg")
  .attr("width", 200)
  .attr("height", 200);

//The line SVG Path we draw
var lineGraph = svgContainer.append("path")
     .attr("d", lineFunction(lineData))
     .attr("stroke", "blue")
     .attr("stroke-width", 2)
     .attr("fill", "none");

var circle = svgContainer.append("circle")
    .attr("r", 5)
    .attr("transform", "translate(" + lineData[0].x + "," + lineData[0].y + ")");

transition();

/*
svgContainer.on("click", function() {
    transition();
});*/

function transition() {
  circle.transition()
      .duration(10000)
      .attrTween("transform", translateAlong(lineGraph.node()))
      .on("end", transition2);
}

function transition2() {
  circle.transition()
      .duration(10000)
      .attrTween("transform", translateAlong2(lineGraph.node()));
}

function translateAlong(path) {
  var l = path.getTotalLength();

  return function(d, i, a) {
    return function(t) {
      var p = path.getPointAtLength(t * l);
      return "translate(" + p.x + "," + p.y + ")";
    };
  };
}

function translateAlong2(path) {
  var l = path.getTotalLength();

  return function(d, i, a) {
    return function(t) {
      var p = path.getPointAtLength((1-t) * l);
      return "translate(" + p.x + "," + p.y + ")";
    };
  };
}
<script src="https://d3js.org/d3.v4.min.js"></script>

PS: In D3 v4, it's .on("end"..., not each("end"....
PPS: There is a lot of repetition in my solution. I'll let the DRY homework for you.


text:
Q: How to change edge of pages in Beamer I'm using long math formulas and need to get smaller edges in Beamer presentation. I mean how I can get all environments such as definition, theorems, proofs starting at the same position as frametitle?

A: Using text margin left=<length> and text margin right=<length> for \setbeamersize you can change the margins; in the example I set them both to 0pt just for illustration purposes:
\documentclass{beamer}

\setbeamersize{text margin left=0pt,text margin right=0pt}

\begin{document}

\begin{frame}
\begin{theorem}
text
\end{theorem}
\end{frame}

\end{document}


text:
Q: How to use useNavigate outside react hook? Gets list of emails from firestore and checks if current user is registered and then redirects them to sign up if they are new user.
The code is functional(it redirects succesfully) but get the following error:
arning: Cannot update a component (BrowserRouter) while rendering a different component You should call navigate() in a React.useEffect(), not when your component is first rendered.
 const navigate = useNavigate();

  let hasEmail = false;
  const [emailList, setEmailList] = useState([]);
  const emailRef = collection(db, "emails");

  useEffect(() => {
    const getEmails = async () => {
      const data = await getDocs(emailRef);
      setEmailList(
        data.docs.map((doc) => ({
          ...doc.data(),
        }))
      );
    };
    getEmails();
  }, []);

  const emailCheck = (emails) => {                     //checks if email exists
    hasEmail = emails.some((e) => e.email === auth.currentUser.email);
  };
  const direct = () => {                         // redirects to required page
    if (hasEmail) {
      navigate("/index");
    } else {
      navigate("/enterdetails");
    }
  };
  emailCheck(emailList);
  direct();

A: Move the email checking logic into a useEffect hook with a dependency on the emailList state.
const navigate = useNavigate();

const [emailList, setEmailList] = useState([]);
const emailRef = collection(db, "emails");

useEffect(() => {
  const getEmails = async () => {
    const data = await getDocs(emailRef);
    setEmailList(
      data.docs.map((doc) => ({
        ...doc.data(),
      }))
    );
  };
  getEmails();
}, []);

useEffect(() => {
  if (emailList.length) {
    const hasEmail = emailList.some((e) => e.email === auth.currentUser.email);
    navigate(hasEmail ? "/index" : "/enterdetails");
  }
}, [auth, emailList, navigate]);

A: This might not run without the proper firebase config but check it out
https://codesandbox.io/s/elated-bell-kopbmp?file=/src/App.js
Things to note:
Use useMemo for hasEmail instead of emailCheck. This will re-run only when emailList changes
const hasEmail = useMemo(() => {
    //checks if email exists
    return emailList.some((e) => e.email === auth.currentUser.email);
 }, [emailList]);

There isn't really a point in having this in a react component if you are just redirecting away. Consider having the content of 'index' at the return (</>) part of this component. Only redirect if they aren't authorized
useEffect(() => {
  if (!hasEmail) {
    navigate("/enterdetails");
  }
  //else {
  //  navigate("/index");
  //}
}, [hasEmail, navigate]);


text:
Q: SOAP request through JMeter with authentication I'm having trouble sending a JMeter SOAP request through HTTP Request element -
Through SOAPUI I'm sending the request with the following properties:
Authentication via SOAP
But I cannot receive a valid response when I try to add these username password. I've tried to place it in HTTP Header Manager/ in HTTP Authorization Manager, but with no luck. I receive either error:

Response code: 404 Response message: Not Found

when placing this in the HTTP Authorization Manager and

HTTP Error 400. The request has an invalid header name

when placing the username and password in the header manager (with wss password type field, while in HTTP Authorization Manager there is not option like this).
What can I do to have a valid response from the server like I get in SOAPUI?

A: If you need to replicate SoapUI request I would suggest just to record the request from the SoapUI via JMeter HTTP(S) Test Script Recorder

*

*In JMeter

*

*File -> Template -> Recording -> Create

*Workbench -> HTTP(S) Test Script Recorder -> Start

*In SoapUI

*

*File -> Preferences -> Proxy Settings

*Host: localhost, Port: 8888

*Enable proxy in SoapUI

*Execute your request

*Expand Thread Group -> Recording Controller in JMeter and observe the recorded request.

You may also need to correlate timestamps using __time() function check out Take the Pain out of Load Testing Secure Web Services for details on bypassing different web services security in JMeter tests.


text:
Q: Bad Request (404) using Spring MVC 3 I keep getting an HTTP Bad Request however i'm not sure why. Below is my code that is producing the error:
$http(
            {
                method : 'POST',
                url : 'http://localhost:8081/spring/employee-module/searchvalue',
                data : $scope.idNumber,
                headers : {
                    'Content-Type' : 'application/x-www-form-urlencoded'
                }
            }).then(function(response) {
        return response.data;
    });

A: Your javascript is mal-formed.  Try this:
$http.post('http://localhost:8081/spring/employee-module/searchvalue', {
    data: $scope.idNumber,
    headers: {
        //did you mean x-www-form-urlencoded??
        'ContentType': 'application/json; charset=utf-8'
    }
}).then(function(response) {
    return response.data;
}, function(error) {
    //error
});


text:
Q: PHP retrieving data from 30 million records I am using the below given custom query in my moodle site and its working fine but now the total records in mdl_user_enrollments table is 30 million which take time to return the result to my frond end screen. Please let me know how to make it fast.
Query given below
select t1.userid,t2.courseid AS course_id, t1.timestart AS subscription_start, t1.timeend AS subscription_end,t1.timecreated AS timecreated,t1.timemodified AS timemodified, t3.id AS quiz_id,

t3.name AS quiz_name from mdl_user_enrolments t1

join  mdl_enrol t2 on t1.userid=$user_id and  t1.enrolid = t2.id

join mdl_quiz t3 on t3.course = t2.courseid

Explain output
Explain mdl_user_enrolments result

Field          Type       Null    Key    Default      Extra
id           bigint(10)    NO     PRI     NULL         auto_increment
status       bigint(10)    NO      0
enrolid      bigint(10)    NO     MUL     NULL
userid       bigint(10)    NO     MUL     NULL
timestart    bigint(10)    NO      0
timeend      bigint(10)    NO   2147483647
modifierid   bigint(10)    NO      MUL      0
timecreated  bigint(10)    NO       0
timemodified bigint(10)    NO       0

Analyze table mdl_user_enrolments result
Table                                Op      Msg_type   Msg_text
eLearningDev_v1.mdl_user_enrolments analyze    status     OK
Size of table mdl_user_enrolments 910 MB

A: Select t1.userid,t2.courseid AS course_id, t1.timestart AS subscription_start, t1.timeend AS subscription_end,t1.timecreated AS timecreated,t1.timemodified AS timemodified, t3.id AS quiz_id,
t3.name AS quiz_name from mdl_user_enrolments t1
LEFT join  mdl_enrol AS  t2 on t1.userid=$user_id and  t1.enrolid = t2.id
LEFT join mdl_quiz AS  t3 on t3.course = t2.courseid

Hopefully this will works for you.


text:
Q: Can you help me understand why the two equations are equivalent? I have this equation:
$$-\frac{n-1}{n-2}\left\{ \frac{b\sum_{i=1}^{n}x_i^2\left[ x_i^2-\left( \frac{\sum_{j=1}^{n}x_j^2}{n}\right)\right]}{\left( \sum_{i=1}^{n}x_i^2  \right)^2} \right\} [1]$$
and he transforms it into:
$$-\frac{n-1}{n-2}\left\{\frac{b\sum_{i=1}^{n}\left[x_i^2-\frac{\sum_{j=1}^{2}x_j^2}{n}\right]\left[x_i^2-\frac{\sum_{j=1}^{2}x_j^2}{n}\right]}{\left(\sum_{i=1}^{n}x_i^2\right)^2}            \right\}
+\frac{n-1}{n-2}\left\{\frac{\frac{b*\sum_{j=1}^{n}x_j^2}{n}\sum_{i=1}^{n}\left(x_i^2-\frac{\sum_{j=1}^{n}x_j^2}{n}\right)}{\left(\sum_{i=1}^{n}x_i^2\right)^2}\right\} [2]$$
I do not understand why equation [1] is equal to equation [2]. Also, how can someone come up with this. I would have never thought of doing this in an exam if that equation would have been given to me for the first time? Should I just memorize the process of doing this? I mean in an exam I don't have a few hours to just try and see what works. (this equation is part of demonstrating that that that the expected value of a term understimate the variance of another term)

A: Because $$\sum_{i=1}^n (z_i - \bar z)^2 = \sum_{i=1}^n z_i^2 - 2\bar z\sum_{i=1}^n z_i + \sum_{i=1}^n\bar z^2\\ = \sum_{i=1}^nz_i^2 - 2\bar z\frac{n}{n}\sum_{i=1}^nz_i + n\bar z^2\\ = \sum_{i=1}^nz_i^2 - 2n\bar z^2 + n\bar z^2\\ = \sum_{i=1}^nz_i^2 - n\bar z^2\\ = \overline{z^2} - \bar z^2\\$$ with $\overline{ z^k} = \frac{1}{n}\sum_{i=1}^n z_i^k$
Actually, only the first term in the second equation is relevant (you get it from equation 1 by the above described).
Let $z_i = x_i^2$. Then note that in the second term in equation 2 that $\sum_{i=1}^n(z_i - \bar z) = \frac{n}{n}\sum_{i=1}^n z_i - n\bar z = n\bar z - n\bar z = 0$ so the second term vanishes.
And to answer your questions: actually this is very simple. The only thing is that it is written down very complicated... First, replace all $x_i^2$ by $z_i$. Then it already looks easier. Second step: replace all $\frac{1}{n}\sum_{i=1}^nz_i$ with $\bar z$. Then you are almost done -- provided you know this formula (well, you don't even have to memorize it since you can easily derive it, as shown above).


text:
Q: Understand ejb-link markup I read this great article about best-practice for EJB-JNDI mapping :
http://www.ibm.com/developerworks/websphere/library/bestpractices/increase_app_portability.html
The notion of ejb-link isn't clear for me.
For example, let's say we have an ejb-jar.xml containing this :
<ejb-ref>
   <ejb-ref-name>ejb/Bean2Home</ejb-ref-name>
   <ejb-ref-type>Entity</ejb-ref-type>
   <home>com.ibm.wsc.Bean2Home</home>
   <remote>com.ibm.wsc.Bean2</remote>
   <ejb-link>Bean2</ejb-link>
</ejb-ref>

Thus, it is precised that the targeted EJB component is Bean2 and this simple notation means that Bean2 must be find on this J2EE application package or .ear file.
So, if ejb-link markup is enough determinant to indicate the right way to link to the good EJB component, what is the need for assembler to create a JNDI name for this ejb-ref ?
Is it really useful?

A: Here are some scenarios that hopefully clarify why <ejb-link/> (or @EJB(beanName="...")) and EJB ref bindings are both useful and complementary:

*

*An application can itself be logically broken up into components, and the developer chooses to use EJBs to implement those components.  In this case, the application developer knows the target EJB component that the client wants to use.  If there are multiple components implementing the same interface, then some disambiguation is required, and <ejb-link/> can be used.

*An application has a dependency on an external service.  In this case, the application knows it has a dependency on an external service, so <ejb-link/> cannot be used since the service implementation does not exist in the same application.

*An application has a dependency on an external service, but a minimal implementation is provided in the same application.  In this case, the developer might use an <ejb-link/> as in #1, but the deployer has the flexibility to override that choice as in #2.

A: This could be maybe useful:
http://www.theserverside.com/discussions/thread.tss?thread_id=2012


text:
Q: Can I release a new App for iPad 1, as of 2017? I have downloaded old versions of Xcode and macOS so I could develop and test an app on my old 1st-gen iPad device.
I wonder if I can submit a new app which runs on iPad 1 (iOS 5)
to Apple App Store as of 2017?

A: 32-bit apps will be rejected, but that's not the whole story. Providing the app supports 64-bit, you can provide a 32-bit version alongside in the same app bundle. This way there is a 64-bit version for newer devices/iOS (iOS 11 removes 32-bit app support), but also a 32-bit version for older devices.
To add 32-bit and 64-bit support to your app bundle in Xcode, you need:

*

*to target iOS 5.1.1. Targeting earlier versions of iOS doesn't support the combined app bundles. Later versions of iOS aren't supported on the iPad 1.

*a version of Xcode which is able to target this iOS and also provide the combined bundle functionality, such as Xcode 5.0.2 or 5.0.3.

*to change your project to build both 32-bit and 64-bit. In your project build settings, change Architectures to 'Standard Architectures (including 64-bit)'.

You can then build your app to support 32-bit and 64-bit which will successfully submit to iTunes Connect.


text:
Q: Html Radio button selection Following is my code,
$(document).ready(function () {
    $("#es").hide();
    $("#n").hide();
    $('input[type="radio"]').click(function () {
        if (this.value === "Yes")
            $("#es").show();
        else if (this.value === "No")
            $("#n").show();
    });
});

There are 2 radio buttons for yes and no.After selecting yes if select no only no option should be selected but here both buttons are getting selecte.How can i rectify this?

A: Just provide both of them the same name. You don't need javascript to do that.
<input type="radio" name="group" id="es" value="Yes"/>Yes
<input type="radio" name="group" id="n" value="No"/>No

Fiddle

A: try this :
give same name both of radio button like this
<input type="radio" name="radio" value="Yes">Yes
<input type="radio" name="radio" value="no">No

A: You need to group the radio buttons.  Give same names to the radio buttons to do so.


text:
Q: Building a life-critical System using Agile Looking at the general trend of comments in my question about Building an Aircraft using Agile, the biggest problem other than cost appears to be safety.
Do people feel that it is not possible to build a safe system (or prove it is safe) using agile? Doesn't all the iterative testing mitigate this? Is it likely that a piece of software developed using agile will never be as reliable as counterparts such as waterfall?

A: Agile is a method of managing a project, not a method of testing or verifying the safety of a finished project.
A safety critical system would still need extensive testing after it is complete (functionality wise) to be absolutly sure it is actually up-to-task. I would expect that this sort of work would be given over to a separate team of testers who are specifically focussed on such testing.
Agile is good with soft requirements, where the traditional product lifecycle is long enough for the business goals to have changed, though in a safety-critical environment, I think that rapidly changing requirements or under-specified requirements would be A Very Bad Thing.
I don't buy the idea that using waterfall would in some way give the code some intrinsic order or stability - if the individual sprints are well managed, the code tested and reviewed, then the shorter cycle would produce code of equal quality, just in chunks.
Using Scrum gives you a heads-up earlier in the project timeline when things are getting problematic - it's not going to do anything but remove hiding places for poor performing managers / devs / whoever.
In short, it is possible to build any sort of system using Agile methods, just so long as you don't expect it to test what you have built. Thats for the testers.

A: There are a number of high-profile software failures that illuminate this issue.  In particular, Ariane 5 Flight 501 and the Therac-25 are both examples of software failures that bring this problem into sharp relief. The Ariane 5 rocket veered off its flight path 37 seconds after launch due to an integer overflow in the guidance software.  The accident cost $370 million in lost equipment, but there was no loss of life.  The same cannot be said of the Therac-25, a medical machine that killed several people with lethal doses of radiation.
Could these problems have been prevented with a better software methodology?  I'm not so sure.  The management decisions that contributed to the failure of the Ariane 5 had little to do with the manner in which the software was constructed, and the Therac-25 investigation was hampered by the belief that it was not possible for the machine to fail.
Better testing methodologies could have helped.  It's hard to believe that a good statically typed compiler would have failed to find the integer overflow.  New testing methodologies like Pex, with its built-in theorem prover, have the capability to search for corner cases, and could have identified the sensor anomalies that existed in the Therac-25.
But no technique is reliable unless you have an uncompromising commitment to safety, from the very highest levels of management all the way down to the people who box the product for shipment.

A: The WHOLE point about safety critical systems that everyone seems to be missing here is that because of their potential to cause loss of life (sometimes on a large scale), they have to be proven to be correct. Often they require an operating certificate unless a licensing authority that is satisfied that the system's requirements have been accurately specified, (often using formal methods like Z and VDM), that the design is a reflection of those requirements (and can be proven to be such) and that the code is an accurate reflection of the design (again proven to be so).
More often than not, the option to test the product to provide such proof doesn't exist (OK guys let's go life with the nuclear reactor, Boeing 777, Therac 25 - whatever and see where the bugs are). Safety critical systems (especially those categorised at S.I.L 3 and above) need thorough and comprehensive documentation which is totally at odds with the Agile manifesto in all respects as far as I can see. Programmers of safety critical systems are not even allowed to make changes to the relesed software without requesting a new revaluation of the software from the licensing authority and rightly so, given the rigour that goes into proving the correctness of the first version and the catestrophic implications for a screw up.

A: Agile is a dynamic development model - You use it when requirements of your application are to be changed fast and unforeseen. Also if the number of your developers are still countable.
You do NOT use it just because it is modern/in/hip/cool.
Sure you can find errors with unit tests, but they never prove their absence. Changing/Adding requirements of the application during development greatly involves adding hidden errors.
For exactly planned applications which is typical for safety critical applications you want to use more static development models like waterfall or v-model.

A: Most safety critical or mission critical systems can benefit from a more standard development structure such as the waterfall model and formal code reviews. Such methods help maintain a more structured code base. Great Book about software construction - especially if the project has already begun using an Agile process - Code Complete 2 ed.


text:
Q: Git alias para o nome do branch anterior Onde trabalho é bem rotineiro ficar alterando entre a branch release e features branches várias vezes durante o dia. Com isso, muitas vezes tenho que escrever linhas longas, usar o tab ou alguma outra solução. Eu queria algo que tivesse como comportamento semelhante a uma variável onde guardasse o a referência anterio do branch em que estava, para assim, então, construir um alias de alteração de branch
problema:
// suponhamos que main é minha branch principal e feature-1, a secundária
$ git branch
   * main
   * feature-1

// troca para fazer algo na branch feature-1 e depois volta par a main
$ git checkout feature-1
$ git checkout main

// troca para fazer algo na branch feature-1 e depois volta par a main
$ git checkout feature-1
$ git checkout main

etc


text:
Q: Getting a still image from the video output on the iphone? I am writing an application to show stats on the light conditions as seen by the iphone camera. I take an image every second, and the performing calculations on it.
To capture an image, I am using the following method:
-(void) captureNow
{
    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in captureManager.stillImageOutput.connections)
    {
        for (AVCaptureInputPort *port in [connection inputPorts])
        {
            if ([[port mediaType] isEqual:AVMediaTypeVideo] )
            {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection) { break; }
    }

    [captureManager.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
     {
         NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
         latestImage = [[UIImage alloc] initWithData:imageData];
     }];
}

However, the captureStillImageAsynhronously.... method causes the 'shutter' sound to be played by the phone, which is no good for my application, as it will be capturing images constantly.
I have read that it is not possible to disable this sound effect. Instead, I want to capture frames from the video input for the phone:
AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self backFacingCamera] error:nil];

and hopefully turn these into UIImage objects.
How would I achieve this? I don't know that much about how the AVFoundation stuff is working - I downloaded some example code and modified it for my purposes.

A: Don't use a still camera for this. Instead, grab from the video camera of the device and process the data contained within the pixel buffer you get in response to being an AVCaptureVideoDataOutputSampleBufferDelegate.
You can set up a video connection using code like the following:
// Grab the back-facing camera
AVCaptureDevice *backFacingCamera = nil;
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices)
{
    if ([device position] == AVCaptureDevicePositionBack)
    {
        backFacingCamera = device;
    }
}

// Create the capture session
captureSession = [[AVCaptureSession alloc] init];

// Add the video input
NSError *error = nil;
videoInput = [[[AVCaptureDeviceInput alloc] initWithDevice:backFacingCamera error:&error] autorelease];
if ([captureSession canAddInput:videoInput])
{
    [captureSession addInput:videoInput];
}

// Add the video frame output
videoOutput = [[AVCaptureVideoDataOutput alloc] init];
[videoOutput setAlwaysDiscardsLateVideoFrames:YES];
[videoOutput setVideoSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]];

[videoOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()];

if ([captureSession canAddOutput:videoOutput])
{
    [captureSession addOutput:videoOutput];
}
else
{
    NSLog(@"Couldn't add video output");
}

// Start capturing
[captureSession setSessionPreset:AVCaptureSessionPreset640x480];
if (![captureSession isRunning])
{
    [captureSession startRunning];
};

You'll then need to process these frames in a delegate method that looks like the following:
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
    CVImageBufferRef cameraFrame = CMSampleBufferGetImageBuffer(sampleBuffer);
    CVPixelBufferLockBaseAddress(cameraFrame, 0);
    int bufferHeight = CVPixelBufferGetHeight(cameraFrame);
    int bufferWidth = CVPixelBufferGetWidth(cameraFrame);

        // Process pixel buffer bytes here

    CVPixelBufferUnlockBaseAddress(cameraFrame, 0);
}

The raw pixel bytes for your BGRA image will be contained within the array starting at CVPixelBufferGetBaseAddress(cameraFrame). You can iterate over those to obtain your desired values.
However, you'll find that any operation performed over the entire image on the CPU will be a little slow. You can use Accelerate to help with an average color operation, like you want here. I've used vDSP_meanv() in the past to average luminance values, once you have those in an array. For something like that, you might be best served to grab YUV planar data from the camera instead of the BGRA values I pull down here.
I've also written an open source framework to process video using OpenGL ES, although I don't yet have whole-image reduction operations in there like you'd need for the kind of image analysis here. My histogram generator is probably the closest I have to what you're trying to do.


text:
Q: Is it possible to use Kendo UI FX with MVVM binding? I'm currently using two-way binding to control the visibility of a DIV based on a boolean in my view model. Instead of merely setting it as visible or hidden, I would like it to expand or contract via the the "expand" effect.
http://docs.telerik.com/kendo-ui/api/javascript/effects/expand
I don't see any way to bind this via MVVM. Has anyone managed to do this?
Thanks

A: Following is the given link from where I got help for my issue.
http://demos.telerik.com/kendo-ui/mvvm/custom


text:
Q: setHasOptionsMenu(Boolean): Unit está deprecatado Android Kotlin Tras una update de depedencias me sale el aviso de que setHasOptionsMenu está deprecatado
Dentro de los fragmentos que cargo menús adicionales
  override fun onCreateView(...): View {
        setHasOptionsMenu(true)
    }

A: Buscando por la red, ahora para cargar los menús se debe hacer con MenuProvider dejo ejemplos de uso para activity fragment y PreferenceFragmentCompat
Activity
class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

   addMenuProvider(object : MenuProvider {
      override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
        menuInflater.inflate(R.menu.main_menu, menu)
      }

      override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        // Handle the menu selection
        return true
      }
    })
  }
}

Fragment
  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

    // The usage of an interface lets you inject your own implementation
    val menuHost: MenuHost = requireActivity()

    //Same Activtiy declaration
    menuHost.addMenuProvider...

PreferenceFragmentCompat
val menuHost: MenuHost = requireHost() as MenuHost
//Same declaration with Fragment

Usando la interface MenuProvider
class FirstFragment : Fragment(), MenuProvider {

      override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
              val menuHost: MenuHost = requireActivity()
              menuHost.addMenuProvider(this, viewLifecycleOwner, Lifecycle.State.RESUMED)
      }

      override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
        // Add menu items here
        menuInflater.inflate(R.menu.second_menu, menu)
      }

      override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        // Handle the menu selection
            return when (menuItem.itemId) {
                R.id.menu_clear -> {
                    // Do stuff...
                    true
                }
                R.id.menu_refresh -> {
                    // Do stuff...
                    true
                }
                else -> false
            }
      }
}


text:
Q: Could anybody tell me what this problem talks about? I found it in the section on sequence spaces. I don't know Russian.

Две последовательности $\{a_n\}$ и $\{b_n\}$ называем существенно
  различными, если $a_n\ne b_n$ для бесконечного множества натуральных
  чисел. Каждая конечная система существенно различных
  подпоследовательностей последовательности простых чисел образует
  линейно независимую систему.

A: Here is the translation to the best of my understanding:

Two sequences $\{a_n\}$ and $\{b_n\}$ are called essentially different if $a_n \not= b_n$ for infinitely many natural numbers. Each finite system of essentially different subsequences of the sequence of prime numbers forms linearly independent system.


text:
Q: Creating a Database using DBExpress in Delphi? I need to create a Firebird Database programmatically using DBExpress. I have done this for SQL server, by first connecting to Master, then passing in the script for Create to a query, but with Firebird I have a little chicken and egg problem.

A: I got a good tip from a collegue that created some code for the Freepascal project. It doesn't use DB express, but according to him it is the only way to create a database with code. This code is based on the InterBase manual, and uses a call from the gdslib / fbclient dll:
procedure TIBConnection.CreateDB;

var ASQLDatabaseHandle,
    ASQLTransactionHandle : pointer;
    CreateSQL : String;
    pagesize : String;
begin
  CheckDisConnected;
  {$IfDef LinkDynamically}
    InitialiseIBase60;
  {$EndIf}
  ASQLDatabaseHandle := nil;
  ASQLTransactionHandle := nil;
  CreateSQL := 'CREATE DATABASE ';
  if HostName <> '' then
    CreateSQL := CreateSQL + ''''+ HostName+':'+DatabaseName + ''''
  else
    CreateSQL := CreateSQL + '''' + DatabaseName + '''';

  if UserName <> '' then
    CreateSQL := CreateSQL + ' USER ''' + Username + '''';
  if Password <> '' then
    CreateSQL := CreateSQL + ' PASSWORD ''' + Password + '''';
  pagesize := params.Values['PAGE_SIZE'];
  if pagesize <> '' then
    CreateSQL := CreateSQL + ' PAGE_SIZE '+pagesize;

  if isc_dsql_execute_immediate(@FStatus[0],@ASQLDatabaseHandle,@ASQLTransactionHandle,length(CreateSQL),@CreateSQL[1],Dialect,nil) <> 0 then
    CheckError('CreateDB', FStatus);

  if isc_detach_database(@FStatus[0], @ASQLDatabaseHandle) <> 0 then
    CheckError('CreateDB', FStatus);

  {$IfDef LinkDynamically}
    ReleaseIBase60;
  {$EndIf}
end;

The trick is the isc_dsql_execute_immediate function. I hope this code helps you. Here are the links to the Freepascal source files where this code comes from:
Unit containing CreateDB function
Unit containing API call isc_dsql_execute_immediate

A: Run a script isql
isql-i createDB.sql
CreateDB.sql the file includes the command to create the database as shown below.
SET SQL DIALECT 3;
CREATE DATABASE 'C:\DATABASE\DB.FDB'
USER 'SYSDBA' PASSWORD 'masterkey'
PAGE_SIZE 4096
DEFAULT CHARACTER SET WIN1252;
QUIT;


text:
Q: Can we have event handling for jsp controls at server side in Spring MVC? In Swing we have action listeners for every control we add, and we handle all the events fired with those controls. Is there any similar method or way in Spring Model View Controller architecture to handle events of "Java Server Pages" controls like buttons, text boxes etc. in the controller at server side?

A: In Spring MVC you can handle and verify those controls in JavaScript or at server side in controller. When any method(e.g. GET, POST etc.) calls the controller then your data goes to controller and you can handle those data.


text:
Q: Insert data into a table when the data is inserted into another table in SQL Server I have two identical tables, each in a different database on a different server. The two servers are on the same network. Data is inserted more often into one of the tables, I want the same data to be inserted into the other table when it's inserted into the first table.
Is there way to do it instead of merging tables and SSIS?

A: If the two servers are linked servers, you can create a trigger on the first table for inserting the same data in the second table.
the code would be something like below
CREATE TRIGGER <trigger name>
ON <Table1>
AFTER INSERT AS
BEGIN
INSERT INTO <server name>.<database name>.<schema>.<table2>
SELECT * FROM INSERTED
END


text:
Q: Can $\mathbb{P}^n$ be regarded as an algebraic vector bundle over some algebraic variety? Is it possible that $\mathbb{P}^n$ is an algebraic vector bundle over some algebraic variety? This is an interesting question that my friend asked in a student seminar. I believe that the answer is NOT. Because the only global sections of $\mathcal{O}_{\mathbb{P}^n}$ are constants. However as a total space of vector bundles $E$ over $X$, the global sections are all in $\Gamma(X, \oplus Sym^n E)=\oplus \Gamma(X,Sym^n E)$ which may not be $\mathbb{C}$ in general. The trouble case is when $\Gamma(X, E)=0$? Am I correct? Is there any other explanation?
Edit: Thanks to everyone for your comments and answer. It seems that compactness is the correct way to follow.
However, I still wondering that why the argument on sections doesn't work. In other words, is there an example of a non-proper algebraic variety whose structure sheaf only has constant global sections.

A: Stephen Griffeth's argument works over any field. The total space of a vector bundle is never proper (follows by, e.g., valuative criterion for properness). On the other hand, $P^n$ is always proper.
Here is an argument that the total space of a vector bundle is not proper: A fiber of a vector bundle is isomorphic to $A^n$ . Moreover, the fiber considered as a subscheme is a closed subscheme. You can map $(A^1 \setminus 0)$ into the fiber by a map like $f(x)=1/x$. This map can't extend over zero, because if it did, then zero would be sent to something in the closure of the fiber. But the fiber is already closed, so zero would be sent to the fiber, contradiction.

Edit: Of course, amaanush's answer is a much better answer than mine!

A: That's right. I think the one sentence rephrasing of Kevin's argument would be proper morphisms are stable under pullback (this is obvious by the very definition of properness which is stated through the pullbacks).
Of course a variety is proper if and only if the structure map to the point scheme (spec k) is proper. Thus a closed fibre of a locally trivial fibre-bundle, with total-space proper, is proper (complete)-- which cannot be the case for a vector bundle.
On the other hand that does not apply to $\mathbb{A}^n \hookrightarrow \mathbb{P}^n$, as the pullback will just give $\mathbb{A}^n \stackrel{id}{\longrightarrow} \mathbb{A}^n$ is proper, which is fine :).

A: Heh, actually it is a rank zero vector bundle over itself.  Don't forget this possibility, folks!

A: In answer to your last question, on why the "sections" argument does not work: Let $X = \mathbb{P}^n_k$, and let $E$ be the line bundle over $X$ with sheaf of sections given by $\mathcal{O}(-1)$.  Then the global sections of $E$ are given by
$$\Gamma(E, \mathcal{O}_E) \cong \Gamma(X, Sym(\mathcal{O}(-1)))
\cong \bigoplus_{n=0}^{\infty} \Gamma(X, \mathcal{O}(-n))
\cong k.$$
Thus, the global sections of $E$ are all constant.  However, as the arguments given in the other answers show, $E \to \text{Spec} k$ is not proper.


text:
Q: custom_require.rb:36:in `require': no such file to load -- myapp(LoadError) i get the above error, all i did was install rvm and update to ruby 1.9.2 from the default ruby that you get with mac.
all my gems appear in the gem list but do i need to specify a path somewhere?
cheers,
glenno.

A: Check that you have the gems installed gem list If not, install as usual gem install whatever or if you want a specific version gem install whatever -v 1.2.3 Or if you have bundler in your project (ie Rails), it's just bundle install
If you have all the gems, then this is probably a local file, and you're probably coming from Ruby version < 1.9, you need to either fix your $LOAD_PATH (which will depend on too many factors for me to explain here), or specify the full path to the file you want File.dirname(__FILE__) + '/myapp'
Otherwise, you need to give more info, like what version you used to be running, what myapp is, and where it is in relation to your file.

A: In my case it was rvm issue, I was using rvm 1.9 when i changed it to 1.8, migration worked.
rvm use 1.8

A: In my case I was converting to Cygwin64.  The Cygwin directory name changed and Ruby upgraded to 1.9.  After I fixed the Cygwin directory name, the second solution worked.  Or at least got past this problem:
require File.dirname(FILE) + '/myapp.rb'


text:
Q: Is this a bug in Kotlin or I missing something? I don't have to much experience in multi-threading. So not sure if I got right the following Java code decompiled from Kotlin.
Here is the Kotlin code:
companion object {
    @Volatile private var INSTANCE: SomeDatabase? = null

    fun getInstance(context: Context): SomeDatabase =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
            }
}

Here is the decompiled code in Java:
     SomeDatabase var10000 = ((SomeDatabase.Companion)this).getINSTANCE();
     if (var10000 == null) {
        synchronized(this){}

        SomeDatabase var4;
        try {
           var10000 = SomeDatabase.Companion.getINSTANCE();
           if (var10000 == null) {

               ...

        var10000 = var4;
     }

     return var10000;

Doesn't this mean that code is actually not synchronized because of empty block in synchronized(this){}?

A: If you look at the bytecode itself without decompiling it, you'll see that the synchronization happens as it should - this here is a version stripped of lots of load and store operations, line numbers, etc., but what matters is where the MONITORENTER and MONITOREXIT instructions are:
public final getInstance(Landroid/content/Context;)Lcom/example/SomeDatabase;
    LDC "context"
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
    INVOKESTATIC com/example/Foo.access$getINSTANCE$cp ()Lcom/example/SomeDatabase;
    MONITORENTER
    INVOKESTATIC com/example/Foo.access$getINSTANCE$cp ()Lcom/example/SomeDatabase;
    INVOKESTATIC com/example/FooKt.buildDatabase (Landroid/content/Context;)Lcom/example/SomeDatabase;
    INVOKESTATIC com/example/Foo.access$setINSTANCE$cp (Lcom/example/SomeDatabase;)V
    MONITOREXIT
    MONITOREXIT
    ARETURN

The issue you're seeing is not a bug in the compiler, but rather an issue with the decompiler, which isn't particularly rare. It's quite the challenge to decompile arbitrary generated bytecode back to Java.


text:
Q: Stability of optimal transference mappings (Exercise 2.17 in Villani's Topics in Optimal Transportaiton) I'm really stuck on the first part of this exercise. I've tried to type it up in a fashion that is as self-contained as possible, but some background in optimal transport is likely required to read this.
Let $P_{ac,2}(\mathbb{R}^n)$ denote the space of absolutely continuous probability measures with finite second moments. Suppose $\sigma \in P_{ac,2}(\mathbb{R}^n)$ is given, as well as a family $\rho_k \in P_{ac,2}(\mathbb{R}^n)$ that weakly converges to some $\rho \in P_{ac,2}(\mathbb{R}^n)$.
Let $\nabla \varphi_k$ be the optimal mapping of the Monge problem with quadratic cost between $\sigma$ and $\rho_k$, i.e. $$\int_{\mathbb{R}^n} |x-\nabla \varphi_k(x)|^2 d\sigma(x) = \inf_{T \# \sigma = \rho_k} \int_{\mathbb{R}^n} |x - T(x)|^2 d\sigma(x)$$
Here, the infimum is taken over functions $T : x \mapsto T(x)$ satisfying the pushforward constraint. Similarly, we can define $\nabla \varphi$ between $\sigma$ and $\rho$.
Let $d\pi_k(x,y) = d\sigma(x) \delta(y = \nabla \varphi_k(x))$, and similarly define $\pi$ between $\sigma$ and $\rho$.
How can I show that $\pi_k$ weakly converges to $\pi$? (The hint given is to note that the optimal transference plan is unique.)


text:
Q: Bootstrap calendar show two calendar in IE 11 Bootstrap calendar show two calendars in IE 11 when I click on << or >> icons to get previous or last month. Below is the code written to show calendar. Pls help. Thanks in advance.
$(".datepicker, .date").datepicker({
        format: 'dd M yyyy',
        weekStart: 1,
        todayBtn: "linked",
        showTodayButton: true,
        forceParse: false,
        //clearBtn: true,
        beforeShowDay: function (date) {
            var d = date.getDate();
            var m = date.getMonth() + 1;
            var y = date.getFullYear();

            if (holidayJson[y] && holidayJson[y][m] && holidayJson[y][m][d]) {
                var s = holidayJson[y][m][d];
                return {
                    tooltip: s.tooltip,
                    classes: s.className
                };
            } else {
                return { tooltip: ' ', classes: '' };
            }
        }
    });

I think problem is with beforeShowDay function if I remove it its working fine. Below is html code from html file and aspx file.

    <input type="text" id="FromDate" class="form-control input-sm" onfocus="blur();" data-ng-model="ttsViewModel.FromDate" style="display: inline-block;" />

    <asp:TextBox ID="txtFdate" Width="80px" runat="server" ToolTip="mm/dd/yyyy" ClientIDMode="Static" CssClass="form-control input-sm"
            style="width: 80px; display: inline-block;" ></asp:TextBox>

A: The issue is caused by the way you are applying the datepicker functionality to your element/textbox. The class .datepicker is already used by the library itself for the datepicker window, using the same class name to indicate whigh elements to apply datepickers, cause your code to try to add a new datepicker on the datepicker popup itself (because it try to add a datepicker to every element having the class .datepicker, and the datepicker popup is using that class).
As far as I know, this seems to cause a bug only in the month switch and when using IE11, for whatever reasons. Maybe because other click in the datepicker popup cause a change of datepicker mode and a redraw of the datepicker.
Try simply using a different class than '.datepicker' to implement datepickers to your control (i.e.  .attachadatepickertothiscontrol)


text:
Q: Confusion between HttpServlet class and using it with Jersey I am building servlets which implement a RESTful API. I understand the Jersey is a framework for deciphering and using given URL's. How do I use it in conjunction with the HttpServlet class.
I don't understand how the two work with each other. I guess this is a very broadstrokes question but I have done a fair share of reading but am still stuck on this seemingly trivial concept. I have attempted to deploy apps with classes that extend the HttpServletclass AND use Jersey annotations.
@Path("/api")
public class API extends HttpServlet{

@GET
@Path("/{name}")
@Produces("text/hmtl")
public String doGetSayHello(@PathParam("name") String name){
    return "Hello" + name;
}
@GET
@Path("/articles")
@Produces("text/json")
public String doGetArticles(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{

    JSONObject obj = new JSONObject();
    obj.put("interns", interns);
    obj.put("company", "Stack Overflow");

    return obj.toString();

}

}
Any help or informative materials would be greatly appreciated!

A: Jersey uses a servlet to route URLs to the appropriate service. Your service itself does not need to extend a servlet.
At a high level, Jersey's ServletContainer class accepts the requests, and then based on your Jersey configuration, your web service will be invoked. You configure what url patterns are processed by Jersey. Check out section 5.3 http://www.vogella.com/articles/REST/.

A: Actually you are confused because you don't understand how jersey works. Jersey framework basically uses com.sun.jersey.spi.container.servlet.ServletContainer servlet to intercept all the incoming requests. As we configure in our projects web.xml, that all the incoming rest request should be handled by that servlet. There is an init-param that is configured with the jersey servlet to find your REST service classes. REST service classes are not Servlet and they need NOT to extend the HttpServlet as you did in your code. These REST service classes are simple POJOs annotated to tell the jersey framework about different properties such as path, consumes, produces etc. When you return from your service method, jersey takes care of marshalling those objects in the defined 'PRODUCES' responseType and write it on the client stream. Here is a sample of jersey config in web.xml
<servlet>
        <servlet-name>REST</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>
                com.rest.services;
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>REST</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>


text:
Q: How to compare tonnes? I need to describe the following data highlighting the difference in terms of tonnes between the amount of gas and oil sold in 2014.

In 2014 were sold

*

*10 tonnes of oil

*20 tonnes of gas

Are the following sentences correct?

*

*In 2014 10 more tonnes of gas were sold compared to oil

*In 2014 the amount of gas sold was 10 tonnes more than that of oil

*In 2014 the amount of gas sold was twice the amount of oil

A: With the edits you've made, all of the sentences are factually correct and convey the meaning you were looking for. I would suggest adding a comma after 'In 2014' in all cases, so you would have:

*

*In 2014, 10 more tonnes of gas were sold compared to oil.

*In 2014, the amount of gas sold was 10 tonnes more than that of oil.

*In 2014, the amount of gas sold was twice the amount of oil.

As to which to choose, it really depends on what information you want to focus on. The final sentence emphasizes the dramatic difference in sales between the two products. The first two sentences emphasize the 10 tonne difference,which could be a major difference or a minor one, depending on how much oil was sold.

Two of the sentences are correct, but one changes the meaning of the data.
In 2014 20 more tonnes of gas were sold compared to oil.
This sentence would mean that the following equation would be true:
gas sales - oil sales = 20 tonnes
That isn't the case. According to your data, the answer to that problem would be 10 tonnes. You could say something like this, though:
In 2014, 20 tonnes of gas were sold. This compares to 10 tonnes of oil sold.

A: The answer is obvious, #3, because it provides the most information.  We don't know what difference "10 tonnes more" represents. Is it 10% more? 50% more.  #3 gives us that info, even though it does not provide the raw numbers.  But that's not really an English-language question. :-)


text:
Q: save an active records array I have an array like this
a = []

a << B.new(:name => "c")
a << B.new(:name => "s")
a << B.new(:name => "e")
a << B.new(:name => "t")

How i can save it at once?

A: B.transaction do
  a.each(&:save!)
end

This will create a transaction that loops through each element of the array and calls element.save on it.
You can read about ActiveRecord Transactions and the each method in the Rails and Ruby APIs.

A: a.each(&:save)

This will call B#save on each item in the array.

A: Wrapping save in transaction will not be enough: if a validation is not passed, there will be no exception raised and no rollback triggered.
I can suggest this:
B.transaction do
  a.each do |o|
    raise ActiveRecord::Rollback unless o.save
  end
end

Just doing B.transaction do a.each(&:save!) end is not an option either, because the transaction block will not rescue any exception other than ActiveRecord::Rollback, and the application would crash on failed validation.
I do not know how to check afterwards if the records have been saved.

Update.  As someone has downrated my answer, i assume that the person was looking for a cut-and-paste solution :), so here is some (ugly :)) way to process fail/success value:
save_failed = nil
B.transaction do
  a.each do |o|
    unless o.save
      save_failed = true
      raise ActiveRecord::Rollback
    end
  end
end
if save_failed
  # ...
else
  # ...
end

A: I know this is an old question but I'm suprised no one thought of this:
B.transaction do
  broken = a.reject { |o| o.save }
  raise ActiveRecord::Rollback if broken.present?
end

if broken.present?
  # error message
end

A: So I think we need a middle ground to Alexey's raising exceptions and aborting the transaction and Jordan's one-liner solution. May I propose:
B.transaction do
  success = a.map(&:save)
  unless success.all?
    errored = a.select{|b| !b.errors.blank?}
    # do something with the errored values
    raise ActiveRecord::Rollback
  end
end

This will give you a bit of both worlds: a transaction with rollback, knowledge of which records failed and even gives you access to the validation errors therein.

A: In case you're looking for more efficient solution than save each row in the loop please look my answer here Ruby on Rails - Import Data from a CSV file
I'm suggesting to use gem activerecord-import there.


text:
Q: Dealing with noisy movement positions I have positions of an object moving around an image. I think I'm detecting it the best I can where most of the time I'm detecting the center of the object. However, I'm still getting the odd detection of around the center caused by the frame rate not being fast enough, and the frame containing two positions of the object.
As I can't control the frame rate, how can I minimise the effects of the noise in the jittery positions.
As this is a common issue in computer vision, are there any filters in opencv to deal with noisy position data?

A: I asked for the comment by Berak to be made into an answer, but my request was "declined". So, yes, the answer that I found most useful was to use the Kalman filter which is implemented in opencv.


text:
Q: python setattr not checking if variable exists test file:
my_name = ''
my_home_address = ''
my_home_phone = ''

my_office_address = ''
my_office_phone = ''

This another file, lets call it test2
import test

line1 = ['address', 'home', 'tom', 'downtown', '12345']
line1 = ['address', 'office', 'tom', 'uptown', '4567']

my_map = { 'home': ['my_name', 'my_home_address', 'my_home_phone'],
           'office1': ['my_name', 'my_office_address', 'my_office_phone'],
           'office2': ['my_name', 'my_office_address', 'my_office_phone'],
           }

if line1[1] in my_map.keys():
    for position, c_name in enumerate(line1):
        setattr(test, my_map[line1[1]][pos], my_map[line1[1]][pos])

Question: I have test file which has all the fields that save the data e.g.: my_name = ''
my_home_address = '' my_home_phone = '' my_office_address = '' my_office_phone = '' etc...
My input is line1 which can have information in different formats but line1[0] and line1[1] is there for sure.
line1[1] tells me what address it is. Now depending on line1[1] i will have to populate variables.
Problem I am facing: Since there are hundreds of Fields , sometimes I miss the spelling, Ex: instead of 'my_home_phone'
i give it as 'my_hoe_phne' , stil it loads the information in test.my_hoe_phne = 4567
Instead I want it to through error saying that this variable does not exist in test file. How do I achieve that?
"""

A: Before running setattr, you can do a quick check to see if the attribute exists on the module or not:
for pos, c_name in enumerate(line1):
    if not hasattr(test, my_map[line1[1]][pos]):
        raise AttributeError(
            'module `test` has no attribute %s' % my_map[line1[1]][pos])
    setattr(test, my_map[line1[1]][pos], my_map[line1[1]][pos])


text:
Q: CNAME and MX records on naked domain I have a domain (registered with Daily.co.uk) that for quite a while was set up with a CNAME pointed to my friend's webserver which uses dynamic DNS to resolve to his IP, in addition to MX records pointed to my Google Apps setup. I've recently realised that this is an invalid configuration and that it was causing issues where certain email servers couldn't send to my address. If I could I'd use the IP of the webserver as the A record, but it's dynamic. I could use something like WWWizer to force a redirect to the www host, but I'd prefer not to do that especially considering I have a nice three letter domain :)
Is there a way I could forward everything to the webserver with the CNAME record and then somehow redirect the MX records from there? Or would I have to set up a mail server to redirect it?
For what it's worth, the domain is http://malachy.org.uk which I eventually am going to alias with http://mal.so in the same way.