text:
Q: I want to console.log() only my data present in my MongoDB database I am entering data in my database in mongodb and want to console.log() the data entered but whenever I try to do it, my data do come to console but with various other properties, which I do not need.
I just want to bring the data entered on my console !
const mongoose = require("mongoose");

mongoose
  .connect("mongodb://localhost/playground")
  .then(() => {
    console.log("database connected");
  })
  .catch(err => {
    console.log("Could not connect", err);
  });

const courseSchema = new mongoose.Schema({
  name: String,
  author: String,
  tags: [String],
  date: { type: Date, default: Date.now },
  isPublished: Boolean
});

// To Create a class of Course, we need to use the model method
const Course = mongoose.model("Course", courseSchema);

async function createCourse() {
  //Lets create a object to the Course class
  // Async Routine
  const course = new Course({
    name: "React Course",
    author: "Mosh",
    tags: ["FrontEnd", "React"],
    isPublished: true
  });

  // Log Tree : Schema -> Model -> Class -> Object !....

  const result = await course.save();
  console.log(result);
}

async function getCourse() {
  const course = await Course.find();

//Bringing the data from the data base.

  console.log(course);
}

getCourse();

What I want to be displayed on my console is (Actual Data in my mongo data base)
[ {"_id":{"$oid":"5e847c6e6ed0fa2c785647e4"},
"tags":["Backend","Node"],
"date":{"$date":{"$numberLong":"1585740910542"}},
"name":"Node Course",
"author":"Mosh","isPublished":true,
"__v":{"$numberInt":"0"}
} ,

{"_id":{"$oid":"5e84868970369f3a30e25270"},
"tags":["FrontEnd","React"],
"date":{"$date":{"$numberLong":"1585743497438"}},
"name":"React Course",
"author":"Mosh",
"isPublished":true,"__v":{"$numberInt":"0"} } ]

BUT What I get is my data BUT with this extra information :-
[
  model {
    '$__': InternalCache {
      strictMode: true,
      selected: {},
      shardval: undefined,
      saveError: undefined,
      validationError: undefined,
      adhocPaths: undefined,
      removing: undefined,
      inserting: undefined,
      version: undefined,
      getters: {},
      _id: 5e847c6e6ed0fa2c785647e4,
      populate: undefined,
      populated: undefined,
      wasPopulated: false,
      scope: undefined,
      activePaths: [StateMachine],
      pathsToScopes: {},
      ownerDocument: undefined,
      fullPath: undefined,
      emitter: [EventEmitter],
      '$options': true
    },
    isNew: false,
    errors: undefined,
    _doc: {
      tags: [Array],
      date: 2020-04-01T11:35:10.542Z,
      _id: 5e847c6e6ed0fa2c785647e4,
      name: 'Node Course',
      author: 'Mosh',
      isPublished: true,
      __v: 0
    },
    '$init': true
  },
  model {
    '$__': InternalCache {
      strictMode: true,
      selected: {},
      shardval: undefined,
      saveError: undefined,
      validationError: undefined,
      adhocPaths: undefined,
      removing: undefined,
      inserting: undefined,
      version: undefined,
      getters: {},
      _id: 5e84868970369f3a30e25270,
      populate: undefined,
      populated: undefined,
      wasPopulated: false,
      scope: undefined,
      activePaths: [StateMachine],
      pathsToScopes: {},
      ownerDocument: undefined,
      fullPath: undefined,
      emitter: [EventEmitter],
      '$options': true
    },
    isNew: false,
    errors: undefined,
    _doc: {
      tags: [Array],
      _id: 5e84868970369f3a30e25270,
      name: 'React Course',
      isPublished: true,
      __v: 0
    },
    '$init': true
  }
]

I dont want this extra information along with my data, when I console.log my Class !

A: I see the problem. I was running mongoose 5.0.1, just updated the mongoose package and It stopped displaying other properties  !


text:
Q: Supplying non-AWS credentials to EC2 instance on launch We have an EC2 instance is coming up as part of autoscaling configuration. This instance can retrieve AWS credentials using the IAM role assigned to it. However, the instance needs additional configuration to get started, some of which is sensitive (passwords to non-EC2 resources) and some of which is not (configuration parameters).
It seems that the best practice from AWS is to store instance configuration in IAM and retrieve it at run-time. The problem I have with this approach is that configuration is sitting unprotected in S3 bucket - incorrect policy may expose it to parties who were never meant to see it.
What is a best practice for accomplishing my objective so that configuration data stored in S3 is also encrypted?
PS: I have read this question but it does not address my needs.

A:
[…] incorrect policy may expose it to parties who were never meant to see it.

Well, then it's important to ensure that the policy is set correctly. :) Your best bet is to automate your deployments to S3 so that there's no room for human error.
Secondly, you can always find a way to encrypt the data before pushing it to S3, then decrypt it on-instance when the machine spins-up.

A: AWS does not provide clear guidance on this situation, which is a shame. This is how I am going to architect the solution:

*

*Developer box encrypts per-instance configuration blob using the
private portion of  asymmetric keypair and places it in an S3 bucket.

*Restrict access to S3 bucket using IAM policy.

*Bake public portion of asymmetric keypair into AMI.

*Apply IAM role to EC2 instance and launch it from AMI

*EC2 instance is able to download configuration from S3 (thanks to IAM role) and decrypt it (thanks to having the public key available).

The private key is never shared sent to an instance so it should not be compromised. If the public key is compromised (e.g. if the EC2 instance is rooted), then the attacker can decrypt the contents of the S3 bucket (but at that point they already have root access to the instance and can read configuration directly from the running service).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Meeting walks on directed graphs Consider a directed graph $G = (V,A)$. For every vertex $v \in V$ we have $d$ directed edges out of $v$, which we'll denote $v(1), v(2), \dots, v(d)$.
Given a sequence $i_1, i_2, \dots, i_\ell \in \{1, 2, \dots, d\}$ and a starting vertex $v$, there is a length-$\ell$ walk $v_0, v_1, \dots, v_\ell$ defined recursively:

*

*$v_0 = v$.

*for $1 \le k \le \ell$, from $v_{k-1}$, we take edge $v_{k-1}(i_k)$, and call its target $v_k$.

The question is: when can we guarantee that for any two vertices $x,y \in V$ there is a sequence $i_1, i_2, \dots, i_\ell \in \{1, 2, \dots, d\}$ such that the walks $x_0, x_1, \dots, x_\ell$ and $y_0, y_1, \dots, y_\ell$ meet (that is, such that $x_\ell = y_\ell$)?


text:
Q: Rounding products prices in magento? I create a new product and type price= $1.2222. But when I click Save and Continue edit the price = $1.22. I don't want to round the price, i want the price=$1.2222. How can I do that? Thank you!

A: It's because of Mage_Core_Model_Store->roundPrice($price)
/**
 * Round price
 *
 * @param mixed $price
 * @return double
 */
public function roundPrice($price)
{
    return round($price, 2);
}

I've created a module which rewrite core/store and overrides the roundPrice() and has the round($price, 4) inside.

A: This is a "feature".
Everything happens because of the input renderer for the price attributes. The Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Price class is used to render the price inputs.
At the end of the class there is this method:
public function getEscapedValue($index=null)
{
    $value = $this->getValue();

    if (!is_numeric($value)) {
        return null;
    }

    return number_format($value, 2, null, '');
}

This makes the prices show with only 2 decimals even if in the db there are 4 of them.
I guess you have to override this method and replace
return number_format($value, 2, null, '');
with
return number_format($value, 4, null, '');


text:
Q: Uploaded audio file to salesforce ContentVersion getting corrupted I need to upload a Zoom recording as ContentVersion to salesforce using the recording file donwload_url.
What I've done so far is this:
// Get download_url field from Zoom file returned by api
const downloadFileUrl = audioFile.download_url;

const token = await generateToken();

// Call Zoom file download
const recordingResponse = await axios.get(`${downloadFileUrl}?access_token=${token.access_token}`);

// Generate form data
const formData = new FormData();

const metadata = {
    Title: file.id,
    ContentLocation: 's',
    PathOnClient: 'audio.m4a',
    OwnerId: ownerId ?? process.env.DEFAULT_FILE_OWNER_ID,
    ReasonForChange: 'Testing',
};

formData.append('entity_content', JSON.stringify(metadata), {
    contentType: 'application/json'
});

const file = recordingResponse.data;

formData.append('VersionData', file, {
    filename: metadata.PathOnClient,
    contentType: 'application/octet-stream'
});

const conn = await salesforceClient.getClient();

const axiosConfig = {
    headers: {
        'Authorization': `Bearer ${conn.accessToken}`,
        'Content-type': 'multipart/form-data',
    }
};

// Post to Salesforce
await axios.post(`${process.env.SALESFORCE_LOGIN_URL}/services/data/v55.0/sobjects/ContentVersion`, formData, axiosConfig).catch((error) => console.log(error));

The file is uploaded successfully, and I see it in the list of files in Salesforce, but the file is corrupted and cannot be played.
The data that comes from the zoom api when posting to 'download_url' is some kind of utf-16 string.
My guess would be that the encoding format is failing because of that when submitting to salesforce.
Does anybody know how this can be solved?

A: I found the solution to the problem by grabbing the file as a 'arraybuffer':
const recordingResponse = await axios.get(`${downloadFileUrl}?access_token=${token.access_token}`,
{
    responseType: 'arraybuffer'
});

And then passing the file as buffer:
formData.append('VersionData', Buffer.from(downloadedResponse.data), {
    filename: metadata.PathOnClient,
    contentType: 'application/octet-stream'
});


text:
Q: Foreign key based on another column I have one database having following tables: Comments, Articles, Videos, Songs, Games, Books with one-to-many relationships between Comments and the others (an Article, Video, Song... may have many comments). I have a associative table CommentBelongsTo having three columns comment_id, page_type, page_id), for example if page_type = 'article' and page_id = 1, means the comment belongs to the article with id = 1. The question is how can i set page_id to be foreign key depending on the page_type? Or is there any better table design?

A: Following table structure can solve the issue
DROP TABLE IF EXISTS `test`.`article`;
CREATE TABLE  `test`.`article` (
  `idArticle` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Name` varchar(45) NOT NULL DEFAULT '',
  PRIMARY KEY (`idArticle`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS `test`.`games`;
CREATE TABLE  `test`.`games` (
  `idGames` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL DEFAULT '',
  PRIMARY KEY (`idGames`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS `test`.`comments`;
CREATE TABLE  `test`.`comments` (
  `idComments` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `a_id` int(10) unsigned DEFAULT NULL,
  `g_id` int(10) unsigned DEFAULT NULL,
  `Comment` varchar(45) NOT NULL DEFAULT '',
  PRIMARY KEY (`idComments`),
  KEY `FK_Comments_1` (`a_id`),
  KEY `FK_Comments_2` (`g_id`),
  CONSTRAINT `FK_Comments_1` FOREIGN KEY (`a_id`) REFERENCES `article` (`idArticle`),
  CONSTRAINT `FK_Comments_2` FOREIGN KEY (`g_id`) REFERENCES `games` (`idGames`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

insert into article values (1,'A1');
insert into comments values (1,1,null,'A1 comment')
insert into games values (1,'G1');
insert into comments values (1,null,1,'G1 comment')

select * from comments where a_id<>'NULL';

To get the comments for particular type


text:
Q: Using Drush permissions issue Using my own non-root account I installed Drush on my Ubuntu 14.04 server using the following:
sudo apt-get install drush

My problem is whether I use sudo or not with the same user account, I get Could not download project status information from http://updates.drupal.org/release-history/drupal/7.x as the following shows:
axel@ITS-DEV-SVR:/var/www$ drush dl drupal-7.34
Could not download project status information from                   [error]
http://updates.drupal.org/release-history/drupal/7.x
axel@ITS-DEV-SVR:/var/www$ sudo drush dl drupal-7.34
Could not download project status information from                   [error]
http://updates.drupal.org/release-history/drupal/7.x
axel@ITS-DEV-SVR:/var/www$

Are there settings, permissions
Can anyone please offer some insight into how to resolve this?
UPDATE:
The server is Ubuntu 14.04.1 LTS.
Below is the output of executing a drush download in verbose mode.
drush -v dl drupal-7.34
Loading version_control engine.                                         [notice]
Loading package_handler engine.                                         [notice]
Executing: wget --version
Loading release_info engine.                                            [notice]
Downloading release history from                                        [notice]
http://updates.drupal.org/release-history/drupal/7.x
Executing: wget --version
Executing: wget -q --timeout=30 -O /tmp/download_filectSEpS http://updates.drupal.org/release-history/drupal/7.x
Undefined variable: xml updatexml.inc:404                               [notice]
Could not download project status information from                   [error]
http://updates.drupal.org/release-history/drupal/7.x
Command dispatch complete                                               [notice]

UPDATE#2
It's worth adding that the website is configured as a multisite even though it's running a single website

A: If it is a multi-site installation, then Drush needs to know to which "site" (one of the multi-sites supported by the Drupal instance) the Drush command is to be applied.
Therefor make sure to FIRST navigate to the subfolder "sites". Try to run the same Drush command(s). I believe it will then assume you want the sites/all subfolder to be updated. If you still have the same issue, then try to navigate to the sites subfolder "default" (or any other subfolder corresponding to any of the other sites related to this multi-sites setup, and try again.


text:
Q: Probability measure and conditional probability intuition and notation problem I have the following definition in probability theory from a paper in game theory.
$\textit{Definition:}$ Suppose that $(X^i)_{i=1}^n$, where $i=\{1,2,\dots,n\}$ and $n<+\infty$, is a collection of finite sets. Define the set $\mathcal{A}=(X,\mu)$, where $X=\Pi_{i=1}^nX_i$ and $\mu$ is the probabolity measure over $X$. When $x\in X$ is drawn according to $\mu$, then every palyer $i$ is informed about the coordinate $x^i$. Even further for every $x^i$ such that $\mu(x^i)>0$, then $p(x^i)\in\Delta(X^{-i})$ denotes the conditional probability of $\mu$ given $x^i$ over $X^{-i}$:
$$p(x^i)(x^{-i})=\mu(x^{-i}|x^i)=\frac{\mu(x^i,x^{-i})}{\mu(x^i)}$$
Also, note that $\mu(x^i)$ stands for $\mu(x^i\times X^{-i})$.
I face difficulty in understanding the notation and I have the following questions:

*

*Is the probability measure $\mu$ defined as follows:

$$\mu:X\to \Delta(X)\subset [0,1]^ n$$

*I strugle to understand the last proposition ''Even further...stands for $\mu(x^i\times X^{-i})$''. What is the intuition and how this transition occurs from $\mu$ to $p$?

If it would be simple to provide an example according to the definition I would appreciate this. For instance lets suppose that n=3, so $X=X^1\times X^2\times X^3= \{a,b\}\times\{z,y\}\times\{u,v\}$, and then $x=(\underbrace{a}_{x^1},\underbrace{z}_{x^1},\underbrace{u}_{x^1})$, what does it mean that $\mu(x^2)>0$ according to the definition above? Can anybody build an example?

A: Consider $X_1=\{a_1,b_1\}$, $X_2=\{a_2,b_2\}$ and $X_3=\{a_3,b_3\}$. Then $X=\{a_1,b_1\}\times\{a_2,b_2\}\times \{a_3,b_3\}$. Consider following probability on $X$:

*

*$\mu(\{(a_1,a_2,a_3)\})=\mu(\{(b_1,b_2,b_3)\})=\frac{1}{5}.$

*$\mu(\{(x_1,x_2,x_3)\})=\frac{1}{10}$ for all other $(x_1,x_2,x_3)\in X$.

Now $X^{-i}=\prod_{j=1, j\neq i}^nX_i$, in our case $X^{-1}=X_2\times X_3$, $X^{-2}=X_1\times X_3$ and $X^{-3}=X_1\times X_2$. This yields the first abuse of notation. For example, by $(a_2,X^{-2})$ we usually denote the set $\{(x_1,a_2,x_3)\in X:\ (x_1,x_3)\in X^{-2}\}$. I hope this meets your understanding so far.
If we now want to consider conditional probabilities, we could think of the probability of $x_1=a_1$ and $x_3=a_3$ if we know $x_2=a_2$. This is indeed $\mu(\{(a_1,x_2,a_3):\ x_2\in X_2\} |\{(x_1,a_2,x_3):\ (x_1,x_3)\in X^{-2}\} )$. Using the definition of conditioned probability yields, that this equals $\mu(\{(a_1,a_2,a_3)\})/\mu((a_2,X^{-2}))=\frac{\frac{1}{5}}{\frac{1}{5}+3\cdot\frac{1}{10}}=\frac{2}{5}$.
If $a=(a_1,a_2,a_3)$, the same notational abuse as above lets us write $a=(a_2,a^{-2})$ with $a^{-2}=(a_1,a_3)$ and by $p(a_2)(a^{-2})$ we obtain a far nicer way of writing the conditional probability we just derived.
I hope those conventions I used make sense for your applications.


text:
Q: select where condition if exists else other condition limit X I'm trying to get a SQL query in Postgres where I could get 5 results based on a standard query :
SELECT ... FROM ... WHERE ... LIMIT 5;

But if I get less than 5 results I'd like to change the WHERE condition, but keeping a total of 5 results (1st condition + 2nd condition).
Would you have any clue how to do so?

A: You can use UNION ALL (or UNION if it suits your requirement) and order by a dummy number column created specifically to set the priority of the rows:
select 1 nr, col1, col2, ... from tablename where condition1
union all
select 2 nr, col1, col2, ... from tablename where condition2
union all
select 3 nr, col1, col2, ... from tablename where condition3
union all
  ............................
order by nr
limit 5


text:
Q: MS Access Hide Button on Startup I'm trying to write code to only show a button during certain months of the year. I think I have the code down, but I don't know where to put it to make it work. When I put the code in "on paint", I get a 32521 error code: "You can't change the value of this property in the OnPaint event."
Here's the code:
Button.Visible = False

If ( (Month(Now) = 6) Or (Month(Now) = 7) Or (Month(Now) = 8) ) Then
Button.Visible = True
End If

Where should I put this code to make it run right when the home screen form is opened?

A: In your Load Event
Private Sub Form_Load()

Button.Visible = False

If ( (Month(Now) = 6) Or (Month(Now) = 7) Or (Month(Now) = 8) ) Then
    Button.Visible = True
End If

End Sub


text:
Q: multiple values for argument on_delete When I run this code I get an error which looks like the text below and I actually have no clue on how to fix it because I'm a newbie, someone on here must know how to fix this, was following a tutorial on YouTube and started making some of my own changes.

File "C:\Users\kristian\webdevelopment\websida\ecommerce\store\models.py", line 131, in OrderItem
product = models.ForeignKey(Product_main, Product_Diverse, Product_Teknikprylar, Product_Verktyg, Product_Maskiner, Product_Guldfynd, on_delete=models.SET_NULL, blank=True, null=True)
TypeError: init() got multiple values for argument 'on_delete'

class Product_Diverse(models.Model):
    name = models.CharField(max_length=100, null=True)
    price = models.FloatField()
    digital = models.BooleanField(default=False, null=True, blank=False)
    image = models.ImageField(null=True, blank=True)

    def __str__(self):
        return self.name

    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ''
        return url

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
    date_order = models.DateTimeField(auto_now_add=True)
    complete = models.BooleanField(default=False, null=True, blank=False)
    transaction_id = models.CharField(max_length=200, null=True)

    def __str__(self):
        return str(self.id)

class OrderItem(models.Model):
    product = models.ForeignKey(Product_main, Product_Diverse, Product_Teknikprylar, Product_Verktyg, Product_Maskiner, Product_Guldfynd, on_delete=models.SET_NULL, blank=True, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
    quantity = models.IntegerField(default=0, null=True, blank=True)
    date_added = models.DateTimeField(auto_now_add=True)

A: The constructor of a ForeignKey object [GitHub], is defined as:
    def __init__(self, to, on_delete, related_name=None, related_query_name=None,
                 limit_choices_to=None, parent_link=False, to_field=None,
                 db_constraint=True, **kwargs):
so the second position parameter is on_delete, the third position parameter is related_name, etc.
If you write:
    product = models.ForeignKey(
        Product_main,          # to
        Product_Diverse,       # on_delete
        Product_Teknikprylar,  # related_name
        Product_Verktyg,       # related_query_name
        Product_Maskiner,      # limit_choices_to
        Product_Guldfynd,      # parent_link
        on_delete=models.SET_NULL,
        blank=True,
        null=True
    )
you thus pass values for parameters like on_delete, etc. Not to other things a ForeignKey can refer to.
A ForeignKey can not refer to multiple models. A ForeignKey can only refer to one model. You might want to make a parent model Product and use model inheritance [Django-doc]. You can also make use of generic relations [Django-doc] if you need this, but there are several disadvantages (like referential integrity).


text:
Q: SimpleHttpWorkerRequest with post I'm currently using SimlpeHttpWorkerRequest object to make request to a .net Mvc application for testing purposes.
Based on this blog post http://lostechies.com/chadmyers/2008/06/25/hosting-an-entire-asp-net-mvc-request-for-testing-purposes/
From what I can decipher SimpleHttpWorkerRequest only uses GET requests. How can I use this approach and extend it to other http verbs ?


text:
Q: Models give different scores when predictions are made in a loop VS when predictions are made from a list of models The variable grid.best_estimator_ contains a Decision Tree model found from GridSearchCV
for subset in range(len(smol_X_train)):
    temp_tree = grid.best_estimator_.fit(smol_X_train[subset], smol_y_train[subset])
    pred = temp_tree.predict(X_test)
    accuracy = accuracy_score(y_test, pred)
    print(accuracy)

Output-
0.827
0.7025
0.782
0.7205
..
..
0.8365
0.8395

With a list-
tree_list = []

for subset in range(len(smol_X_train)):
    temp_tree = grid.best_estimator_.fit(smol_X_train[subset], smol_y_train[subset])
    tree_list.append(temp_tree)

for one_tree in tree_list:
    pred = one_tree.predict(X_test)
    accuracy = accuracy_score(y_test, pred)
    print(accuracy)

Output-
0.8395
0.8395
0.8395
0.8395
..
..
0.8395
0.8395

The models in the list are returning the same score (the score of the last model).

*

*Why do the outputs differ here? Aren't the models stored in the list all fitted on different subsets and hence, should give different predictions too?

*Is the fitness of the models (except the last one) lost when they're put in the list?

A: Cloning, fitting the model and then appending it to a list did the trick. Rather than directly appending the model to the list.
from sklearn.base import clone

tree_list = []

for subset in range(len(smol_X_train)):
    temp_tree = grid.best_estimator_.fit(smol_X_train[subset], smol_y_train[subset])
    tree_list.append(clone(temp_tree))
    pred = temp_tree.predict(X_test)
    accuracy = accuracy_score(y_test, pred)
    print(accuracy)


text:
Q: RenderTransform vs PushTransform I have a shape (the red path below) and i have to apply to this path a TranslateTransform and a ScaleTransform transformation. But if i use the Shape RenderTransform property in this way:
Path MyPath = new Path { Fill = new SolidColorBrush(Colors.Red) };
MyPath.Data = MyPathGeometry;
TransformGroup transf = new TransformGroup();
transf.Children.Add(new TranslateTransform(50, 50));
transf.Children.Add(new ScaleTransform(2, 2));
MyPath.RenderTransform = transf;

I get a drawing of this type:

Instead, if I use DrawingContext PushTransform method in this way:
DrawingVisual MyPath = new DrawingVisual();

using (DrawingContext context = MyPath.RenderOpen()) {
   context.PushTransform(new TranslateTransform(50, 50));
   context.PushTransform(new ScaleTransform(2, 2));
   context.DrawGeometry(Brushes.Red, null, MyPathGeometry);
}

I get a drawing of this type:

Why the two paths are placed in a different way? What is the difference between using PushTransform and RenderTransform? How could i get the same result in both cases?
Thanks.

A: The difference is simply the order in which the transformations are applied.
In the first case (TransformGroup) you first translate by (50, 50), then scale by (2, 2). In the second case (PushTransform) you first scale, then translate.
The transformations in a TransformGroup are executed in a sequential, first-in-first-out order, wheras the pushed transforms are executed in a stack-like or last-in-first-out order.


text:
Q: GitLab SSL certificate error: No account exists I am trying to setup a self-hosted GitLab instance, everything works except when I try to create a https connection using Let's encrypt. I get the following error when trying to reconfigure the GitLab instance:
There was an error running gitlab-ctl reconfigure:

letsencrypt_certificate[gitlab.***.org] (letsencrypt::http_authorization line 6) had an error: Acme::Client::Error::AccountDoesNotExist: acme_certificate[staging] (/opt/gitlab/embedded/cookbooks/cache/cookbooks/letsencrypt/resources/certificate.rb line 41) had an error: Acme::Client::Error::AccountDoesNotExist: No account exists with the provided key

My external_url=https://gitlab.***.org, and on my network I have set port forwarding for both port :80 and :443. I also set the DNS to my IP, this works as the site is reachable when not secured.
Hope someone recognizes the error, I looked all over and didn't see it pop up anywhere.
Best Regards

A: I had the same problem while I tried to change the url of my GitLab.
I solved this issue thanks to : https://gbe0.com/posts/linux/server/gitlab-acme-account-does-not-exist/, by desactiving the old Acme private key then reloading GitLab config
sudo mv /etc/acme/account_private_key.pem /etc/acme/account_private_key.pem.backup
sudo gitlab-ctl reconfigure


text:
Q: Finding the exact position of the bar of the scrollbar I want to make a margin next to the scrollbar that highlights chapters and other items on a html page. Similar to what eclipse has to show errors, todos etc. (right arrow in this pic)
I can easily calculate the scrollbars relative position within my element using scrollTop, windowHeight and height of the scrollable content. The problem is that this does not take into account that the scrollbar has two small arrows at the top/bottom which makes my algorithm think the scrollbar is slightly taller than it is making the highlight both too large and tending to drift a bit from the center. And i can't find any way of finding the height of these small arrows-buttons.
So the way i see it i need to know either

*

*The size of the arrows above/under the scrollbar. I guess this is pretty constant but if possible it would be better to read it in case different browsers use different scrollbars. Especially considering mobile devices which might not have them at all.

*A direct method of matching scrollposition to a position inside the viewport

*A way of hiding the arrows completely. (Without reimplementing a scrollbar from scratch using javascript.)


text:
Q: How to POST json to the Wufoo Entries API? The current documentation is a little lacking on how exactly to submit forms via Ajax. There is The Entries POST API but it talks only about xml, and doesn't even show an example payload.
I see that Wufoo has a half-built, abandoned jQuery plugin wufoo/Wufoo-jQuery-API-Wrapper which seems to do little more than wrap $.get and format errors a bit. POST is listed as a "todo".
I've tried hitting the API with things like:
{
  "Field1": "first",
  "Field2": "last",
  "Field3": "email@example.com",
  "Field4": "test messsage",
}

And based on the line "This call would contain POST parameters in name/value pairs" and the example postAuthenticated(array('Field1' => 'Frank')); I tried just sending an array of arrays.
[
  ['Field1', 'first'],
  ['Field2', 'last'],
  ['Field3', 'email@example.com'],
  ['Field4', 'test messsage']
]

But since those are obviously the wrong format, I always get the following in response.
{
    "Success": 0,
    "ErrorText": "Errors have been <b>highlighted</b> below.",
    "FieldErrors": [
        {
            "ID": "Field3",
            "ErrorText": "This field is required. Please enter a value."
        },
        {
            "ID": "Field4",
            "ErrorText": "This field is required. Please enter a value."
        }
    ]
}

Does anyone have any idea how to format these requests? Maybe someone with more experience with CurlService could interpret it from their example, but I can't make heads or tails of that documentation, nor find any examples online.

A: I should have known. The service doesn't accept json, it only replies in json. Submitting a regular urlencoded form body works.


text:
Q: ChromeDriver 79 under Selenium needs HTTPS certificate manually accepted every time I've just updated my ChromeDriver from version 78 to version 79. Now Chrome gives me a warning on all my tests and fails if I don't add the certificate as an exception in time (a have a few seconds before the test fails). I didn't have to do anything special to ChromeDriver 78, it just worked.

How can I get ChromeDriver 79 to work without manual intervention?

A: DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("acceptInsecureCerts", true);
driver = new ChromeDriver(capabilities);


text:
Q: Python Unittest for a PyTorch Model I have got the following function where I struggle with:
def load_trained_bert(
    num_classes: int, path_to_model: Union[Path, str]
) -> Tuple[BertForSequenceClassification, device]:
    """Returns a bert model and device from four required model files of a folder

    Parameters
    ----------
    num_classes: int
        Number of output layers in the bert model
    path_to_model: Union[Path, str]
        Folder where the four required models files are

    Returns
    -------
      Tuple[BertForSequenceClassification, device]
        BERT model in evaluation mode and device

    """

    # Set device
    device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")

    # Initialize BERT
    model = BertForSequenceClassification.from_pretrained(
        path_to_model,
        num_classes=num_classes,
        output_attentions=False,
        output_hidden_states=False,
    )

    # Load fine tuned model weights
    weight_file = get_weight_file(path_to_model)
    path_to_weights = os.path.join(path_to_model, weight_file)

    model.load_state_dict(torch.load(path_to_weights, map_location=torch.device("cpu")))

    # Send model to device
    model.to(device)
    # Set model to inference mode
    model.eval()

    return model, device

I am in general not sure how to fest this function, but I thought it would be a good idea just to check the parameters I call the function with:
class LoadModelTest(TestCase):
    @patch("abox.util.model_conversion.get_weight_file", return_value="test.model")
    def test_load_trained_bert(self, get_weight_file):
        BertForSequenceClassification.from_pretrained = Mock()
        load_trained_bert(num_classes=16, path_to_model="./model")
        BertForSequenceClassification.from_pretrained.assert_called_with(
            "./model",
            num_classes=16,
            output_attentions=False,
            output_hidden_states=False,
        )

This results in the following error:
FileNotFoundError: [Errno 2] No such file or directory: './model\\test.model'

Now it´s getting difficult... I have no idea what to do with the following snippet:
model.load_state_dict(torch.load(path_to_weights, map_location=torch.device("cpu")))
Can anyone help me here?


text:
Q: Creating map based on json given JSON
{
 "type": {
   "type1": {
     "sub1": [
        "sub1A": {
        }
     ]
   }
 }
"type2": {
   "type1": {
     "sub1": [
        "sub1A": {
        }
     ]
   }
 }

}
I have Json like this , I am not getting how to create map for this, like
Map<String, Object> requestMap = new HashMap<>();
requestMap.get("type");

Inside type again create map containing sub data.

A: I didn't understand your question completely. But, from your statement, if you are trying to fetch json data into your class and that JSON data has recursive mapping, i.e., one object contains itself under its body. Then, I don't think you need HashMap to map this json into your class. You can use single Entity with a field of type of itself like employee-manager relationship. e.g.,
class Type {
  private Type type;
  private String otherField;
  // constructors, setters, getters
}

Now, you can read values from type using the recursive functions.

A: According to what you have shared you can use:
Map <String, Map<String, Map<String, Set<Map<String, String>>>>>

Or to get more details concerning working with json objects you can look at: Query a JSONObject in java


text:
Q: Can't understand basic algebra behind transfer function. Im having trouble understanding the algebra behind what is in the red box. I just can't grasp how -Vo(s) was brought to the left side and how the result written in blue was obtained.
Can someone help me understand?

A: We have
$$\dfrac{V_i (s)}{R_1} = - V_o (s) \left(\dfrac{R_2 C s + 1}{R_2}\right)$$
Dividing both sides by $V_i (s)$,
$$\dfrac{1}{R_1} = - \dfrac{V_o (s)}{V_i (s)} \left(\dfrac{R_2 C s + 1}{R_2}\right)$$
Multiplying both sides by $-R_1$,
$$-1 = \dfrac{V_o (s)}{V_i (s)} \dfrac{R_1}{R_2} (R_2 C s + 1)$$
Thus,
$$\dfrac{V_o (s)}{V_i (s)} =  -\dfrac{R_2}{R_1} \left(\dfrac{1}{R_2 C s + 1}\right)$$

A: You have:
$$
V_1=-R_1V_0\left(\frac{1}{R_2}+sC \right)
$$
so:
$$
\frac{V_0}{V_1}=\frac{-1}{R_1\frac{1+R_2sC}{R_2}}=-\frac{R_2}{R_1}\frac{1}{1+R_2sC}
$$


text:
Q: Minimum value of $a+b$ If the graph of $f(x)=2x^3+ax^2+bx$ intersects the $x$-axis at three distinct points, then what is minimum value of $a+b$? Here $a$ and $b$ are natural numbers.
My attempt:
As the graph intersects the $x$-axis at three distinct points, it has $2$ local maxima/minima. Let these $2$ local maxima/minima be $x_1, x_2$.
I found $f'(x)=6x^2+2ax+b$
So $x_1, x_2$ are the roots of $6x^2+2ax+b=0$
I could not solve this further. I think the minimum value of $a+b$ is $\sqrt {ab}$.
Is my approach correct or is there any other method?

A: For intersection of the curve $f(x)=2x^3+ax^2+bx$ with the x-axis, we have $$f(x)=0 \implies 2x^3+ax^2+bx=0$$ $$\implies x(2x^2+ax+b)=0 \implies x=0\ \text{&}\ 2x^2+ax+b=0 $$  Now, for intersection of curve $f(x)$ with the x-axis at three distinct points, the quadratic equation: $2x^2+ax+b=0$ must have two distinct roots.
Hence, we have determinant $B^2-4AC>0$ $$\implies (a)^2-4(2)(b)>0$$  $$\implies a^2-8b>0$$   $$\implies \color{red}{a^2>8b}$$ Since, $a$ & $b$ are natural numbers hence, to get minimum value of $\color{red}{(a+b)}$ the numbers $a$ & $b$ both must be least natural numbers satisfying the above relation.
Hence, substituting the least possible value of $b$ as $b=1$, we get $$a^2>8\times 1\implies a^2>8$$ Now, the least possible value of $a$ satisfying the above inequality is $8$
Thus, $a=3$ & $b=1$ are fully satisfying the inequality, hence the minimum value of $(a+b)$ is given as follows $$\color{blue}{a+b=3+1=4}$$

A: It must cut at $x=0$, so we need to ensure just that $2x^2+ax+b$ has two distinct non-zero roots. Clearly $b \neq 0$.
So the discriminant $\Delta = a^2-8b > 0 \implies a^2 > 8b$.  Among natural numbers, it should be obvious we must choose $b=1, a = 3$ to get the minimum $a+b$.


text:
Q: Changing NavigationView.MenuItemsSource crashes I need to change the NavigationView menu depending on the page I navigate to.
<ux:NavigationView x:Name="NavView" MenuItemsSource="{x:Bind MainMenu, Mode=OneWay}">

MainMenu is a dependency property of type List<ux.NavigationViewItemBase>. Everything is still fine when I fill it in my constructor:
MainMenu = GetMenuItems().ToList();

But when I try to change it later:
ContentFrame.Navigate(item.PageType, null, transitionInfo);
MainMenu = GetMenuItems().ToList();

my app crashes with 0xC0000005: Access violation reading location 0x00000000. in NavigationView.cpp at line 924.
Is it completely forbidden to change the menu items later or did I hit another problem somehow?


text:
Q: In Azure WebRole always GetExternalLoginInfoAsync is null when Multiple instances I am using a external authentication (Google y Microsoft) in mvc Project (vb.NET). It is work good when i use only one instance in Azure. But when i use multi instances always fail (return null) but I see than the urls are correct. I use a MachineKey in web.config pero it is not solve nothing. I am using a classic web role.
In development or with a single instance it works. If I put more than one instance it always fails (except if I was authenticated with an instance, in that case the authentication still works)
I only use external cookie, since I only need to determine that they have been authenticated, but not save their identity in a local authentication cookie
    Public Sub ConfigureAuth(app As IAppBuilder)

    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie)

    Dim options = New MicrosoftAccountAuthenticationOptions With {
            .ClientId = "CLIENID",
            .ClientSecret = "SECRET",
            .CallbackPath = New PathString("/signinMS")
        }
    app.UseMicrosoftAccountAuthentication(
            options
            )

    app.UseGoogleAuthentication(New GoogleOAuth2AuthenticationOptions() With {
            .ClientId = "CLIENTID",
            .ClientSecret = "SECRET"
        })

End Sub

Example function callback (where is the error)
        <AllowAnonymous>
    Public Async Function ExternalLoginCallback() As Task(Of ActionResult)
        Dim loginInfo = Await AuthenticationManager.GetExternalLoginInfoAsync()

        If loginInfo Is Nothing Then
            Return Redirect("/")
        End If

        Request.GetOwinContext().Authentication.SignOut(HttpContext.GetOwinContext().Authentication.GetAuthenticationTypes().Select(Function(o)
                                                                                Return o.AuthenticationType
                                                                                End Function).ToArray())

        Return Redirect("/Areatrabajo")

    End Function

Image Redirects
PROBLEM FOUND
Found the problem. Increasing Web Role instances in azure changes the machineKey. For this reason, I cannot use the authentication cookies of the other instances.


text:
Q: How can I find the initial state vector from state space model? Assume that we have input $u(k)\in \Re $ and output $y(k) \in \Re$ and we estimate the black box model by using subspace identification method.
$$x (k+1) = Ax (k)  + Bu(k) $$
$$y (k) = Cx (k) $$
If we know $A \in \Re^{2x2} ,B \in \Re^{2x1},C  \in \Re^{1x2}$ and the input and output.
How can we find $x (k) \in \Re^{2}$ at $y (k) $ when $k > 0$ ?

A: I assume you do not know the initial condition and/or have uncertainty and noise. Otherwise you can use the state equations to propagate the state vector. If the system is observable
https://en.wikipedia.org/wiki/Observability,
then you can use an observer:
https://en.wikipedia.org/wiki/State_observer.
If you have noise in the output and uncertainty in the model, you can use the Kalman filter:
https://en.wikipedia.org/wiki/Kalman_filter
Better resource on KF:
http://www.cs.unc.edu/~tracker/media/pdf/SIGGRAPH2001_CoursePack_08.pdf
If your system is not observable, then the state cannot be estimated from the information you have.


text:
Q: Is it possible to insert a form within an html table? Multiple forms in one table, these forms last for varying lengths of rows, however this does not seem to work:

    <form>

    </form>
    <form>

    </form>

I believe a table has a definite structure, and this cannot be interlaced with other structures, but is there a tidy work around this?
Thanks.

A: No. According to this document: http://www.w3.org/TR/html401/struct/tables.html#h-11.2.1
table may contain only these:
TABLE --
     (CAPTION?, (COL*|COLGROUP*), THEAD?, TFOOT?, TBODY+)>

But you can use something like this

  <form>

...

...

  </form>

with styles:
div.table { display:table; }
div.table > form { display:table-row; }
div.table > form > div.cell { display:table-cell; }

A: No, you can't do that. I guess you want it that way to have both forms aligned in a table, right?
If you are allowed javascript on the page, you could add the different text boxes etc. inside the  elements, and attach onchange event handlers to these boxes to populate the corresponding (hidden) fields in your actual forms.

A: It would be a problem in all HTML ... including both XHTML and HTML5.
XHTML table dtd ..
<!ELEMENT table (caption?, (col*|colgroup*), thead?, tfoot?, (tbody+|tr+))>

A: Not between
 tags.  They should work outside of
 or inside of  though.

A: There's no real need to have two forms in a single table if you're looking to put them on multiple rows. The bigger the table, the longer it takes for the browser to load and display it. Instead, give each form its own table and place the table tags within the form tags, like so:
<form method="GET" action="foo.sh">

</form>

A: Yes! No problem to HTML5.
Now table tags are just a shorthand for table styling rules.


text:
Q: Failure to turn on list auditing programatically I have a SPListEventReceiver with a ListAdded() override that responds to the creation of Document Libraries. What I am trying to do is turn on auditing for the newly created Document Library like so:
SPList list = web.Lists[properties.List.ID];
list.Audit.AuditFlags = SPAuditMaskType.View;
list.Audit.Update();

When I go to the list in the UI and look in its Information management policy settings, the Enable Auditing box isn't ticked. Stepping through the code in debug mode doesn't throw an error either. How do I properly activate auditing on a list?

A: If you are adding the auditing for every list, why don't you turn it on for the whole site collection?:
public static void ActivateAuditing(SPWeb web)
{
    if (web.IsRootWeb == true)
    {
        var site = web.Site;

        AuditLogTrimmingReportCallout.SetAuditReportStorageLocation(site,
            SPUtility.ConcatUrls(site.ServerRelativeUrl, "/AuditReports"));

        site.TrimAuditLog = true;

        site.Audit.AuditFlags = SPAuditMaskType.View

        site.Audit.Update();
    }
}

In your particular case, you might be missing a one time configuration setting of where to store the audit logs:
AuditLogTrimmingReportCallout.SetAuditReportStorageLocation(site,
                SPUtility.ConcatUrls(site.ServerRelativeUrl, "/AuditReports"));

Hope this helps.


text:
Q: In SharePoint 2013 does read only permissions allow a user to open a link I have a list where for most users they will have read access to the list.  The list has URL links to pages outside of SharePoint on our Company intranet.  These pages on the intranet are available to everyone.  My assumption is if a user has read only to a list that contains hyperlinks then they should be able to click on the hyperlink ?  Am I correct ?

A: If a user has Read access to the List (and subsequent List items, if the items do not have inheritance broken), yes they would be able to click on the links to the sites within the List. It would be up to the target system to enforce any sort of authentication/authorization.

A: User has a read or view permission in SharePoint list or library . User can click on item and download the document as well as user can click on hyperlink .
Read

Can view pages and items in existing lists and document libraries. Can download documents.

Refereed Link :
User Permissions in SharePoint

A: Yes, with 'Read' or 'View', your User can click on the Hyperlink. The page won't render it to be disabled based on the user's read/view permissions.

A: users can see the URLs in the list, but if the URLs formatting is just text and not a hyperlink they will not be able to click on it.
Regards

A: To be more precise, in this case it is nothing to do with permission level.
If item from the list is visible to user then he can click it.


text:
Q: unexpected EOF while looking for matching `}' I have below command which is working fine if I hard code the values -
find . -name '*txt' -exec bash -c ' mv $0 ${0/\7777/4444}' {} \;

it replace 4444 with 7777
But when I trying by passing value using variable with double quotes, it is not working -
SourceString1=7777 and TargetString1=4444
find . -name '*txt' -exec bash -c ' mv "{$0}" "${0/\"${SourceString1}"/"${TargetString1}"}"' {} \;


text:
Q: Binding issue WPF I am new at WPF and of course I faced some issues with Bindings.
I have initialized RadCartesianChart and I want display data from different type of category lists. For each of those lists I want different color, but I fail to Bind Fill property to my Color property in code behind.
This is how my XAML looks like:
    <telerik:RadCartesianChart Name="RevChart">
        <telerik:RadCartesianChart.Grid>
            <telerik:CartesianChartGrid MajorYLineDashArray="5, 5" MajorLinesVisibility="Y">
                <telerik:CartesianChartGrid.MajorYLineStyle>
                    <Style TargetType="{x:Type Line}">
                        <Setter Property="Stroke" Value="Gray"/>
                    </Style>
                </telerik:CartesianChartGrid.MajorYLineStyle>
            </telerik:CartesianChartGrid>
        </telerik:RadCartesianChart.Grid>
        <telerik:RadCartesianChart.HorizontalAxis>
            <telerik:CategoricalAxis />
        </telerik:RadCartesianChart.HorizontalAxis>
        <telerik:RadCartesianChart.VerticalAxis>
            <telerik:LinearAxis/>
        </telerik:RadCartesianChart.VerticalAxis>

        <telerik:AreaSeries CategoryBinding="Date" ValueBinding="Rev" Fill="{Binding Color}">

        </telerik:AreaSeries>

    </telerik:RadCartesianChart>

This is my C# code:
public class Revenue
{
    public double Rev { get; set; }
    public DateTime Date { get; set; }
    public Color Color { get; set; }
}

List<Revenue> list = new List<Revenue>();
...
...
this.RevChart.Series[0].ItemsSource = list;

As a results I am getting correct picture, but color is default. So my binding of Color doesn't work. Is it problem in this line Fill={Binding Color} ? Why?

A: Its because Fill is a Brush and you are trying to assign a Color, this wont work.
You will have to assign your Color to the Color property of a SolidColorBrush in the Fill property.
Example
<telerik:AreaSeries CategoryBinding="Date" ValueBinding="Rev">
    <telerik:AreaSeries.Fill>
        <SolidColorBrush Color="{Binding Color}" />
    </telerik:AreaSeries.Fill>
</telerik:AreaSeries>


text:
Q: Хочу скачать файл в aiogram и сохранить в формате text Отправляет пользователь файл
@dp.message_handler(content_types=types.ContentTypes.DOCUMENT)
async def oo(doc: types.document.Document):
    file_id = doc['document']['file_id']
    file = await bot.get_file(file_id)
    file_path = file.file_path
    result = await bot.download_file(file_path, '/Users/nnnnn/Documents/python__programs/еее/tt.txt')

в итоге получается вот это
{\rtf1\ansi\ansicpg1251\cocoartf1671\cocoasubrtf600
{\fonttbl\f0\fswiss\fcharset0 Helvetica-BoldOblique;}
{\colortbl;\red255\green255\blue255;}
{\*\expandedcolortbl;;}
\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0

\f0\i\b\fs24 \cf0 PYTHON\
AIOGRAM\
\uc0\u1055 \u1040 \u1049 \u1058 \u1054 \u1053  \
\uc0\u1060 \u1049 \u1054 \u1043 \u1056 \u1040 \u1052 }

А хотелось бы чтобы файл сохранялся в таком же виде в котором отправляют.
Ну или что надо сделать чтобы вернуть файл в прежнее состояние


text:
Q: Click and Slide object in Air for Android Wondering which gesture to use to be able to allow the user to touch the object with their finger, slide and release the object and allow the object to continue to move across the screen once they release the object.  This would all be in Air for Android as well.  I don't want to move the stage itself, just an object on the screen.  Thanks for any help!

A: I am not quite sure if this is what you are looking for, but you should consider reading here.  It starts like this:

With the Android drag/drop framework, you can allow your users to move
  data from one View to another View in the current layout using a
  graphical drag and drop gesture. The framework includes a drag event
  class, drag listeners, and helper methods and classes.
Although the framework is primarily designed for data movement, you
  can use it for other UI actions. For example, you could create an app
  that mixes colors when the user drags a color icon over another icon.
  The rest of this topic, however, describes the framework in terms of
  data movement.

Your question leads me to believe that you need something like this to happen. Hope this helps and sorry if you are asking something different. Cheers


text:
Q: Creating a temp table and using aggregate select query I am trying to create a temp table from a sub select query and am receiving an error message

Msg 102, Level 15, State 1, Line 5
  Incorrect syntax near ';'

Here is my query:
select *
into #temp
from
    (select dollars,  PostingDate, EntryDescription
     from MillsEntOps.dbo.OE_InvoiceGLSumm
     where Postingdate between '2018/03/01' and '2018/04/11')

The error message is :

Msg 102, Level 15, State 1, Line 5
  Incorrect syntax near ')'.

Any ideas what I am doing wrong?

A: Alternatively you can write:
select dollars,  PostingDate, EntryDescription
into #TEMP
from MillsEntOps.dbo.OE_InvoiceGLSumm
where Postingdate between '2018/03/01' and '2018/04/11'

A: I think you missed alias name
select * into #temp from ( select dollars, PostingDate, EntryDescription from MillsEntOps.dbo.OE_InvoiceGLSumm where Postingdate between '2018/03/01' and '2018/04/11')temp_table /* alias name temp_table */


text:
Q: Sum of Legendre symbols for divisors of a quadratic non-residue modulo an odd prime. Let $\big(\frac{n}{p}\big)=-1$ (Legendre's symbol) for an odd prime p. Then show that
$$\sum_{d,\ \ d\mid n}\Big(\frac{d}{p}\Big)=0.$$
I know that if $d$ is a divisor of $n$, then $-d$ is also its divisor. Therefore, by properties of Legendre's symbol, we have
$$\Big(\frac{-d}{p}\Big)=\Big(\frac{-1}{p}\Big)\times \Big(\frac{d}{p}\Big).$$Since $p$ is an odd prime, we have that $$ \Big(\frac{-1}{p}\Big)=(-1)^{\frac{p-1}{2}}=\pm 1.$$  If $\frac{p-1}{2}$ is odd, then we can prove. How to deduce the result when $\frac{p-1}{2}$ is even.
Is my way of solving correct? Please give hint or solution.

A: Legendre symbol is a completely multiplicative function whose values are in $\{-1,1,0\}$. Therefore
$$\Big(\frac{d}{p}\Big)\Big(\frac{n/d}{p}\Big)=\Big(\frac{n}{p}\Big)=-1\implies\Big(\frac{d}{p}\Big)=-\Big(\frac{n/d}{p}\Big).$$
It follows that
$$\sum_{d,\ \ d\mid n}\Big(\frac{d}{p}\Big)=\frac{1}{2}\left(\sum_{d,\ \ d\mid n}\Big(\frac{d}{p}\Big)+\sum_{d,\ \ d\mid n}\Big(\frac{n/d}{p}\Big)\right)
=\frac{1}{2}\sum_{d,\ \ d\mid n}\left(\Big(\frac{d}{p}\Big)+\Big(\frac{n/d}{p}\Big)\right)=0$$


text:
Q: Populating a listview with checkboxes from a XAML file I've got a listview that looks like this (except a Load button has been added since this screen shot was taken):
Listview image
Here's the XAML code:
<Window.Resources>
    <DataTemplate x:Key="YoungPicCell">
        <StackPanel Orientation="Horizontal">
            <Image Height="200" Width="200" Stretch="None" Source="{Binding YoungPic}" />
        </StackPanel>
    </DataTemplate>
    <DataTemplate x:Key="MediumPicCell">
        <StackPanel Orientation="Horizontal">
            <Image Height="200" Width="200" Stretch="None" Source="{Binding MediumPic}" />
        </StackPanel>
    </DataTemplate>
    <DataTemplate x:Key="AdultPicCell">
        <StackPanel Orientation="Horizontal">
            <Image Height="200" Width="200" Stretch="None" Source="{Binding AdultPic}" />
        </StackPanel>
    </DataTemplate>

    <DataTemplate x:Key="TerrainCell">
        <StackPanel Orientation="Vertical">
            <CheckBox Content="Salt Water"  Name="SaltWaterCheckbox" IsThreeState="False" IsChecked="{Binding Saltwater}" />
            <CheckBox Content="Fresh Water"  Name="FreshWaterCheckbox" IsThreeState="False" IsChecked="{Binding Freshwater}" />
            <CheckBox Content="Grassland / Plains"  Name="GrasslandsCheckbox" IsThreeState="False"  IsChecked="{Binding Grassland}" />
            <CheckBox Content="Swamp"  Name="SwampCheckbox" IsThreeState="False" IsChecked="{Binding Swamp}" />
            <CheckBox Content="Tropical Forest"  Name="TropicalForestCheckbox" IsThreeState="False"  IsChecked="{Binding TropicalForest}" />
            <CheckBox Content="Forest"  Name="ForestCheckbox" IsThreeState="False" IsChecked="{Binding Forest}" />
            <CheckBox Content="Forest Edge"  Name="ForestEdgeCheckbox" IsThreeState="False"  IsChecked="{Binding ForestEdge}" />
            <CheckBox Content="Sand"  Name="SandCheckbox" IsThreeState="False" IsChecked="{Binding Sand}" />
            <CheckBox Content="Coastal"  Name="CoastalCheckbox" IsThreeState="False" IsChecked="{Binding Coastal}" />
            <CheckBox Content="River Border"  Name="RiverBorderCheckbox" IsThreeState="False" IsChecked="{Binding RiverBorder}" />
            <CheckBox Content="LakeBorder"  Name="LakeBorderCheckbox" IsThreeState="False"  IsChecked="{Binding LakeBorder}" />
            <CheckBox Content="Floodplain"  Name="FloodplainCheckbox" IsThreeState="False"  IsChecked="{Binding Floodplain}" />
        </StackPanel>
    </DataTemplate>

    <DataTemplate x:Key="PlacePlantsCell">
        <StackPanel Orientation="Vertical">
            <Label Margin="10"  Content="Random" HorizontalAlignment="Center" ></Label>
            <Slider Margin="10"  Width="190" Value="50" Orientation="Horizontal" HorizontalAlignment="Center" IsSnapToTickEnabled="True" Maximum="100" TickPlacement="BottomRight"  TickFrequency="5"> </Slider>
            <Button Margin="10"  Content="Randomly Seed Plants" HorizontalAlignment="Center"  Height="23" Name="SeedButton" ></Button>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

<DockPanel>
    <Grid>
        <ListView ItemsSource="{Binding Path=lsvData, Mode=TwoWay}" Name="listView1">
            <ListView.View>
                <GridView>
                    <GridViewColumn Width="152" Header="Name" DisplayMemberBinding="{Binding Path=Name}"  />
                    <GridViewColumn Width="202" Header="Picture of Young Plant" DisplayMemberBinding="{Binding Path=YoungPic}" CellTemplate="{StaticResource YoungPicCell}" />
                    <GridViewColumn Width="202" Header="Picture of Medium Plant"  DisplayMemberBinding="{Binding Path=MediumPic}" CellTemplate="{StaticResource MediumPicCell}" />
                    <GridViewColumn Width="202" Header="Picture of Adult Plant"  DisplayMemberBinding="{Binding Path=AdultPic}" CellTemplate="{StaticResource AdultPicCell}" />
                    <GridViewColumn Width="202" Header="Terrain / Environments" CellTemplate="{StaticResource TerrainCell}" />

                    <GridViewColumn Width="202" Header="Place Plants" CellTemplate="{StaticResource PlacePlantsCell}" />
                </GridView>
            </ListView.View>
        </ListView>
        <Button Content="New Plant"  DockPanel.Dock="Bottom"  Height="23" HorizontalAlignment="Left" Margin="160,240,0,0" Name="NewPlant" VerticalAlignment="Top" Width="75" Click="NewPlant_Click" />
        <Button Content="Save" DockPanel.Dock="Bottom"   Height="23" HorizontalAlignment="Center" Margin="1099,240,15,0" Name="SavePlant" VerticalAlignment="Top" Width="75" Click="SavePlant_Click"/>
        <Button Content="Load" DockPanel.Dock="Bottom" Height="23" HorizontalAlignment="Left" Margin="26,240,0,0" Name="LoadPlants" VerticalAlignment="Top"  Click="LoadPlants_Click" Width="75" />
    </Grid>
</DockPanel>

Here is the XML file that is being loaded when you click on the Load button:
<?xml version="1.0" encoding="UTF-8"?>
<Plants>
<Species>
    <Name>Alethopteris</Name>
    <YoungPic>AlethopterisYoung.bmp</YoungPic>
    <MediumPic>AlethopterisMedium.bmp</MediumPic>
    <AdultPic>AlethopterisAdult.bmp</AdultPic>
    <Saltwater>true</Saltwater>
    <FreshWater>False</FreshWater>
    <Grasslands>False</Grasslands>
    <Swamp>False</Swamp>
    <TropicalForrest>False</TropicalForrest>
    <Forest>False</Forest>
    <ForestEdge>False</ForestEdge>
    <Sand>False</Sand>
    <Coastal>False</Coastal>
    <RiverBorder>False</RiverBorder>
    <LakeBorder>False</LakeBorder>
    <Floodplain>False</Floodplain>
</Species>
</Plants>

And, lastly, here's the relevant code behind:
      public PlantDisplay()
    {
        InitializeComponent();
        _wvm = new WindowViewModel();
        this.DataContext = _wvm;
    }

    public class LVData
    {
        public string Name { get; set; }
        public string YoungPic { get; set; }
        public string MediumPic { get; set; }
        public string AdultPic { get; set; }
        public bool SaltWater { get; set; }
        public bool FreshWater { get; set; }
        public bool Grasslands { get; set; }
        public bool Swamp { get; set; }
        public bool TropicalForrest { get; set; }
        public bool Forest { get; set; }
        public bool ForestEdge { get; set; }
        public bool Sand { get; set; }
        public bool Coastal { get; set; }
        public bool RiverBorder { get; set; }
        public bool LakeBorder { get; set; }
        public bool Floodplain { get; set; }
    }

    public class WindowViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        //called when a property is changed
        protected void RaisePropertyChanged(string PropertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
            }
        }

        private ObservableCollection<LVData> _plantList = new ObservableCollection<LVData>();
        public ObservableCollection<LVData> lsvData
        {
            get { return _plantList; }
            set { _plantList = value; RaisePropertyChanged("lsvData"); }
        }

        public void PopulateDataFromXML()
        {
            XDocument loaded = XDocument.Load(@"DinoIslandPlants.xml");

            var Plants = from x in loaded.Descendants("Plants")
                          select new
                          {
                              Name = x.Descendants("Name").First().Value,
                              YoungPic = x.Descendants("YoungPic").First().Value,
                              MediumPic = x.Descendants("MediumPic").First().Value,
                              AdultPic = x.Descendants("AdultPic").First().Value,
                              SaltWater = x.Descendants("SaltWater").First().Value
                          };
            foreach (var _plant in Plants)
            {
                _plantList.Add(new LVData {
                    Name = _plant.Name,
                    YoungPic = _plant.YoungPic,
                    MediumPic = _plant.MediumPic,
                    AdultPic = _plant.AdultPic,
                    SaltWater = Convert.ToBoolean(_plant.SaltWater) });
            }

            RaisePropertyChanged("lsvData");
        }

    }

I'm having two problems:

*

*It's crashing on this line: SaltWater = Convert.ToBoolean(_plant.SaltWater) });

*It's not loading the image of the plant, but rather is displaying the path string.

Any ideas, suggestions? Is the way I'm saving a boolean in the XAML file correct?

A: The problem regarding question 1 is that in your XML you have the item Saltwater.
In your code you have this line.
SaltWater = x.Descendants("SaltWater").First().Value

Notice the difference between SaltWater and Saltwater? If you fix your case I believe you will sort that problem.
I am not sure why .First().Value does not throw an exception. Maybe another person could answer that for you.


text:
Q: SCP to multiple servers using key pair authentication I'm using a key pair for authentication for SSH on all my servers. We disable password login over SSH for security reasons on all our Linux servers.
On each server I have a folder at the root level and in that folder I have a set of scripts that I tend to run for routine maintenance on all the servers.
I have a single linux management workstation, which I use to SSH into each of my servers, and on that management station I have a copy of that script folder.
What I want to do is maintain only one copy of that folder on my management station and then use a script to SCP into each of my servers to then copy that folder over. I have the list of all my servers in a text file which sits alongside my replicate script.
So far I've written the replicate script to handle parsing the "servers" file and loop through each entry and SCP into each server to copy the folder over.
My problem is i'm being asked for the keyphrase for my private key each time, and I was wondering if there was a way to open the key once and then use it for all the connections. Thus asking me for the keyphrase only once, instead of for every server it wants to connect to.
I realise I could use something like Syncthing or another replication system to do this replication automatically, maybe even rsync but I want to avoid running software like that on all my servers, just for replicating this one folder, and I have very little knowledge on what's involved setting up rsync, and again I want to avoid putting specific config on all my servers to just allow rsync to work.
The basic/crude script I have is as follows, and it works but I just have to keep typing the passphrase.
replicate.sh
hosts=$(<servers_file)
for host in $hosts; do
    echo "Connecting to host $host";
    scp -r /data/scripts root@$host:/data
done

servers_file
10.1.1.10
10.1.1.11
etc

I thought I had run into a nice solution using SSH sockets, but that only allows me to run multiple commands on the same remote host, when I need to connect to multiple hosts.
Also a solution at https://serverfault.com/questions/389404/use-scp-to-copy-a-file-to-different-servers will work, but only if we're using passwords for SSH, which we are not.
If someone can point me in the right direction, it would be very much appreciated.

A: I have a similar use case where I want to fully automate commands over ssh where there is an interaction that can be automated .  I've automated using python and use pexpect to answer questions (which could be passphrase)
def localexpect(alog, config, host):
    TMPLOG = "/tmp/pexpect.log"
    mcs = config["mcs"]
    cmd = f'''
ssh-keygen -R {host}.local ;\
ssh-copy-id -i rsa/id_rsa.pub {mcs["user"]}@{host}.local ;\
echo "publickeyinstalled" ;\
echo "alldone"
        '''

    alog.info(cmd)

    with open(TMPLOG, "w") as log:
        ch = pexpect.spawn(f"/bin/bash -c \"{cmd}\"", encoding='utf-8', logfile=log)
        while True:
            i = ch.expect(["Are you sure", "password:", "publickeyinstalled"])
            if i == 0:
                alog.info("ECDSA check")
                ch.send("yes\r")
            elif i == 1:
                alog.info("Password required")
                ch.send(f"{mcs['pwd']}\r")
            elif i == 2:
                alog.info("public key installed")
                break
        ch.expect("alldone")
        i = ch.expect([pexpect.EOF], timeout=5)
        ch.close()
        alog.info("expect done - EOF")


text:
Q: Finding Memory leaks in C with Visual Studio 2013 I am using Visual Studio 2013, and taking a course in C programming and we started talking about memory bugs detaction, in particular memory leaks, and how to detect them using Valgrind on Linux.
I want to know if there is a way to detect such memory leaks using VS 2013. I tried searching online but it just leads to lots of articles and blogs and msdn posts and blogs with lots of words like dump files, and analizing them, etc which weird because:
1) It sounds so complex, convoluted and unintuitive it is actually hard to comprehend it.
2) The main reason this is weird is due to the fact that VS is the most advanced IDE around and Microsoft spends so much money on in, yet from what I have read it seems that there is no simple way to use VS to detect memory leaks - certainly no way that's as simple as Valgrind where I only have to compile the program and run the command
valgrind -leaks-check=yes ProgramName
and it simply prints to me all location it thinks there is a memory leak and describes the error (like not freeing memory after allocating it with malloc hence having "dead" memory after the program finishes, or accessing memory that's out of the array bounds)
So my question is how to use VS 2013 in order to achieve the same results and to find out First in high level if there are memory leaks in the program, and second - to detect in a simple manner where those leaks are- preferably without involving dump files (not that I know how to use them anyway in VS).

A: The answer I offer cannot be perfect as exhaustively explaining ALL features VS2013 etc. offer to find C/C++ heap hickups could be a book well sold. And not a very thin one for that matter.
First, things I will NOT cover:

*

*sal.h - Semantic annotations (which are also used by MS tools, if provided).

*Not EVERY _Crt* function available. Only a few to give the idea.

*Additional steps an application designer might to add to their design for a "production quality" code base.

Having said that, here a piece of annotated code containing various bugs. Each bug is annotated with how it was possible to detect it by means of what VS2013 has to offer. Either at run time or at compile time or with static code analysis.
The compile time error sections are placed in comments, btw.
#include "stdafx.h"
#include <crtdbg.h>
#include <malloc.h>
#include <cstdint>
#include <cstdlib>

// This small helper class shows the _Crt functions (some of them)
// and keeps the other code less cluttered.
// Note: This is NOT what you should do in production code,
// as all those _Crt functions disappear in a release build,
// but this class does not disappear...
class HeapNeutralSection
{
    _CrtMemState m_start;

public:
    HeapNeutralSection()
    {
        _CrtMemCheckpoint(&m_start);
    }

    ~HeapNeutralSection()
    {
        _CrtMemState now;
        _CrtMemState delta;
        _CrtMemCheckpoint(&now);
        if (_CrtMemDifference(&delta, &m_start, &now))
        {
            // This code section is not heap neutral!
            _CrtMemDumpStatistics(&delta);
            _CrtDumpMemoryLeaks();
            _ASSERTE(false);

        }
    }
};

static void DoubleAllocationBug()
{
    {
        HeapNeutralSection hns;

        uint32_t *rogue = (uint32_t*)malloc(sizeof(uint32_t));
        if (NULL != rogue)
        {
            *rogue = 42; // Static Analysis without the NULL check: Dereferencing null pointer.
        }
        rogue = (uint32_t*)malloc(sizeof(uint32_t));
        free(rogue);
        // detected in destructor of HeapNeutralSection.
    }
}

static void UninitializedPointerAccessBug()
{
//  uint32_t *rogue;
//  *rogue = 42; // C4700: uninitialized local variable 'rogue' used.
}

static void LeakBug()
{
    {
        HeapNeutralSection hns;

        uint32_t *rogue = (uint32_t*)malloc(sizeof(uint32_t));
        if (NULL != rogue)
        {
            *rogue = 42; // Static Analysis without the NULL check: Dereferencing null pointer.
        }
    }
}

static void InvalidPointerBug()
{
    // Not sure if the C-compiler also finds this... one more reason to program C with C++ compiler ;)
    // uint32_t *rogue = 234; // C2440: 'initalizing': cannot convert from 'int' to 'uint32_t *'

}

static void WriteOutOfRangeBug()
{
    {
        HeapNeutralSection hns;
        uint32_t * rogue = (uint32_t*)malloc(sizeof(uint32_t));
        if (NULL != rogue)
        {
            rogue[1] = 42; // Static analysis: warning C6200: Index '1' is out of valid index range '0' to '0' for non-stack buffer 'rogue'.
            rogue[2] = 43; // Static analysis: warning C6200: Index '2' is out of valid index range '0' to '0' for non-stack buffer 'rogue'.
            // warning C6386: Buffer overrun while writing to 'rogue':  the writable size is '4' bytes, but '8' bytes might be written.
        }
        free(rogue); // We corrupted heap before. Next malloc/free should trigger a report.
        /*
        HEAP[ListAppend.exe]: Heap block at 0076CF20 modified at 0076CF50 past requested size of 28
        ListAppend.exe has triggered a breakpoint.
        */
    }
}

static void AccessAlreadyFreedMemoryBug()
{
    {
        HeapNeutralSection hns;
        uint32_t * rogue = (uint32_t*)malloc(sizeof(uint32_t));
        free(rogue);

        *rogue = 42; // Static analysis: warning C6001: Using uninitialized memory 'rogue'.
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    // checks heap integrity each time a heap allocation is caused. Slow but useful.
    _CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF);

    AccessAlreadyFreedMemoryBug();
    WriteOutOfRangeBug();
    UninitializedPointerAccessBug();
    DoubleAllocationBug();

    // _CrtDumpMemoryLeaks();
    return 0;
}

Last not least, on Windows CE and in the DDKs (maybe also in the platform SDKs), there used to be the 2 static code checkers "prefast" and "prefix". But maybe they are now outdated.
Additionally, there are MS research projects, going a step beyond sal.h, such as:
VCC, which help finding concurrency bugs etc.


text:
Q: Is it possible to allow Azure elastic jobs access to Azure SQL Databases without the need to allow all Azure resources to the server? We are trying to use Azure elastic jobs to run database jobs on a set of Azure SQL databases. The access to these Azure SQL databases is restricted to only certain ip-addresses which we have configured in the firewall rules. When testing the execution of the elastic jobs the elastic job agent cannot access our databases. We do not want to enable access for all Azure Services.
I found a post that it is possible to limit the access by manually adding the ip addresses of the Azure resources of the location we use. (https://github.com/MicrosoftDocs/azure-docs/issues/35138) But this means it is still possible for all Azure resources in that location to try and access our servers.
Is there a way to only provide access to our SQL databases for our Elastic Job SQL Agent resource?

A: Yes, it is no need to allow all Azure resources to the server, but after that we need to list ip whitelist. (https://github.com/MicrosoftDocs/azure-docs/issues/35138) as the post also said: Please go ahead to white list the IP Ranges for the specific data center you are deployed to instead of allowing all IPs from all Azure services.
I also created a test to prove it.
I turned off this setting of my Azure SQL database.

Then I executed EXEC jobs.sp_start_job 'CreateTableTest' to start a job, I only got an error as follows:

So I need to add the client ip to the firewall rules of my Azure SQL database. After that, it works well.

When we allow Azure services and resources to access this server, it will automatically and implicitly add all the ip range of azure services and resources.
Update:
I've removed other IP list and the elastic jobs can still run successfully.

That's amazing!

A: The only way I have come up with doing this without either whitelisting huge amounts of ip addresses or allowing all azure services, is to have an automation job that makes a query via the external source, and then if the link fails extract the ip address from the error message and add that to the sql firewall.
This is far from ideal, but at least is more maintainable, and probably more secure.


text:
Q: ConcurrentModificationException with synchronized and unsynchronized methods so we've got a neat class which looks similar to this:
class ConnectionObserver {
    private List<DbConnection> connections;

    // singleton logic

    public synchronized void closeConnection(int id) {
        for(Iterator<DbConnection> it = connections.iterator(): it.hasNext()) {
            DbConnection conn = it.next();
            if(conn.getId() == id) {
                conn.close();
                it.remove();
            }
        }
    }

    public int countOpenConnections() {
        int open = 0;
        for(DbConnection conn : connections) {
            if(conn.isOpen()) {
                ++open;
            }
        }
        return open;
    }

    // more synchronized methods which alter the list via iterators
}

The problem is, when multiple threads access the singleton some call synchronized the methods which alter the list and some try to count the open connections which fails sometimes because the list is altered in the meantime by one of the synchronized methods.
I'm convinced that just making the method countOpenConnections synchronized too won't solve the problem. Making the list a Collections.synchronizedList won't do too much too, I think.
Do some of you have an approach which could help me?

A: If you can make your List final you can synchronise on the list itself - this way only one thread will have a monitor on the list at any one time. This kind of blunt synchronization solves the immediate problem at the cost of increasing lock contention; only one thread can access the List at any one time. But why should multiple reading threads not be able to access the list simultaneously - they aren't modifying it after all...
Enter the ReentrantReadWriteLock, this would allow multiple threads to read but if a thread is writing everything would have to wait. It had two modes, "read" and "write" (hence the name). This allows you to separate methods that modify the List from those that do not - reducing lock contention.
class ConnectionObserver {

    private List<DbConnection> connections;
    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void closeConnection(int id) {
        final Lock writeLock = readWriteLock.writeLock();
        writeLock.lock();
        try {
            for (Iterator<DbConnection> it = connections.iterator(); it.hasNext();) {
                DbConnection conn = it.next();
                if (conn.getId() == id) {
                    conn.close();
                    it.remove();
                }
            }
        } finally {
            writeLock.unlock();
        }
    }

    public int countOpenConnections() {
        int open = 0;
        final Lock readLock = readWriteLock.readLock();
        readLock.lock();
        try {
            for (DbConnection conn : connections) {
                if (conn.isOpen()) {
                    ++open;
                }
            }
        } finally {
            readLock.unlock();
        }
        return open;
    }
    // more synchronized methods which alter the list via iterators
}

Obviously alter any other methods that access the List to get the appropriate lock beforhand and remove any synchronized keywords.
On another note, I do not understand the use of a List - it seems to you have to search the List for a DbConnection with a specific id. Wouldn't a Map be a better choice (constant rather than linear time search...)
    private Map<Integer, DbConnection> connections;

    public void closeConnection(int id) {
        final Lock writeLock = readWriteLock.writeLock();
        writeLock.lock();
        try {
            final DbConnection dbConnection = connections.remove(id);
            if (dbConnection == null) {
                //handle invalid remove attempt
            } else {
                dbConnection.close();
            }
        } finally {
            writeLock.unlock();
        }
    }

    public int countOpenConnections() {
        int open = 0;
        final Lock readLock = readWriteLock.readLock();
        readLock.lock();
        try {
            for (final DbConnection conn : connections.values()) {
                if (conn.isOpen()) {
                    ++open;
                }
            }
        } finally {
            readLock.unlock();
        }
        return open;
    }

A: Every time you close the connection you are removing it from the list. So just return the size of the connections. Also, as its a connection observer, you may listen to connection close events and keep the list updated with only the open connections.

A:
I'm convinced that just making the method countOpenConnections synchronized too won't solve the problem.

Actually that is exactly what you need to make your program correctly synchronized.

Making the list a Collections.synchronizedList won't do too much too, I think.

There you are right: synchronizedList will give you a too fine granularity of critical sections.
The only other approaches you have at your disposal are those that copy the current list, modify the copy, and then assign the copy to a volatile shared variable. I don't think you'll benefi from such an approach.

A: First of all, making countOpenConnections synchronized will solve the problem.
Another thing you can do to increase concurrency, is to replace your current list implementation for the connections field with a CopyOnWriteArrayList. That allows you to drop the synchronized on countOpenConnections, and therefore removes contention points. However, this really only makes sense if countConnections() is called much more often than closeConnection, due to the overhead of CopyOnWriteArrayList.


text:
Q: how to add "Empty Module" in Android Studio? I am trying to add AndEngine to my Android Project using the tutorial here: https://docs.google.com/document/d/1fcSowvlKMqfTjM9r1mMP48KEhWbkJZGBDR5duFg4QYc/edit
I am stuck at Step #6 in the tutorial, unable to see the "Empty Module" option in my Android Studio Envt. (Version 0.4.0)

A: You can simply copy the AndEngine module inside your project directory and then configure your build.gradle and settings.gradle to include it in to dependencies  like
 ----YOUR_PROJECT
   ---AndEngine
     --res
     --src
     -- .....
     -- build.gradle
   ---YOUR_MODULE
     --res
     --src
     --build.gradle (no : A)
 ----settings.gradle

build.gradle (No. A) file
  dependencies {
       compile project(':AndEngine')
   }

settings.gradle :
   include ':YOUR_MODULE'
   include ':AndEngine'

As Observed AndEngine is not moved to gradle yet, In that case download create jar using ant or eclipse.
The create a libs folder inside your Project
  ----YOUR_PROJECT

   ---YOUR_MODULE
     --libs
       -AndEngine.jar
     --res
     --src
     --build.gradle (no : A)
 ----settings.gradle

Now go to File > Project Structure > Modules > Dependencies > + green button > File Dependency > select AndEngine.jar and press OK
You will see these lines will be automatically added in your build.gradle file inside dependencies, you can add this manually as well no difference.
      compile files('libs/AndEngine.jar')

A: Their instructions were written for Android Studio 0.2; this dialog has changed since then. They have some hasty steps for 0.3 which should work; I've amended them:

*

*Download andengine.jar (Google it, there is no official download)

*Create your own libs folder in your project

*Copy andengine.jar into this folder

*File > Project Structure > Modules > Dependencies > + button > File Dependency > select andengine.jar

If you need more help, there are many other answers on SO on how to add a jar library to Android Studio; they vary a little bit based on what version of Android Studio they're written for, but they should help you out. Many of them have you modify your build.gradle file directly; the UI steps above accomplish much the same thing and make the edits on your behalf.


text:
Q: Update Immutable.Map I would like to change the active for item 1 to true, while also setting others (some hundred) active to false.
import {Map, Record} from 'immutable';

const initialState = new Map({
  0: new Record({
    id: 0,
    name: 'foo',
    active: true,
  }),
  1: new Record({
    id: 1,
    name: 'bar',
    active: false,
  }),
  2: new Record({
    id: 2,
    name: 'baz',
    active: false,
  }),
});

const TARGET = 1;

const newState = initialState.merge(
  initialState.map((value) => {
    if (value.id === TARGET) {
      return value.set('active', true);
    } else if (value.active) {
      return value.set('active', false);
    }
    return value;
  })
);

Is it possible to do it easiest or better? Thanks!


text:
Q: Build multiple docker images in Gitlab CI I would like to create 2 different Docker images from 2 different folders.
My repo has the following structure:
.gitlab-ci.yml
node_app/
   src/
   package.json
   Dockerfile
php_app/
   src/
   composer.json
   Dockerfile

I have the following code in .gitlab-ci.yml
image: docker:stable
services:
  - docker:dind

stages:
  - build
  - test

variables:
  DOCKER_HOST: tcp://docker:2375
  DOCKER_DRIVER: overlay2

before_script:
  - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY

.build:
  stage: build
  script:
    - |

      IMAGE_TAGGED=$CI_REGISTRY_IMAGE/$CONTAINER_NAME:$CI_COMMIT_REF_SLUG
      IMAGE_LATEST=$CI_REGISTRY_IMAGE/$CONTAINER_NAME:latest

      docker build \
        --pull \
        --tag $IMAGE_TAGGED \
        --tag $IMAGE_LATEST \
        --file $CONTAINER_NAME/Dockerfile \
        $CONTAINER_NAME

      docker push $IMAGE_TAGGED
      docker push $IMAGE_LATEST

build node app:
  extends: .build
  variables:
    CONTAINER_NAME: "node_app"

build php app:
  extends: .build
  variables:
    CONTAINER_NAME: "php_app"

.test:
  before_script:
    - echo 'testing app'
  image: $CI_REGISTRY_IMAGE/$CONTAINER_NAME:$CI_COMMIT_REF_SLUG
  stage: test

test node app:
  extends: .test
  variables:
    CONTAINER_NAME: "node_app"
  script:
    - ls -la
#    - run test scripts

test php app:
  extends: .test
  variables:
    CONTAINER_NAME: "php_app"
  script:
    - ls -la
#    - run test scripts

The problem is that the docker build context is not the application folder, but the root of the entire repository, thus container the code of all apps.
The result of the test jobs ls -la command are:
total 40
drwxrwxrwx    7 root     root          4096 Aug  6 08:46 .
drwxrwxrwx    4 root     root          4096 Aug  6 08:46 ..
drwxrwxrwx    6 root     root          4096 Aug  6 08:46 .git
-rw-rw-rw-    1 root     root             6 Aug  6 08:46 .gitignore
drwxrwxrwx    2 root     root          4096 Aug  6 08:46 .gitlab
-rw-rw-rw-    1 root     root          5705 Aug  6 08:46 .gitlab-ci.yml
drwxrwxrwx    3 root     root          4096 Aug  6 08:46 .idea
drwxrwxrwx    7 root     root          4096 Aug  6 08:46 node_app
drwxrwxrwx    3 root     root          4096 Aug  6 08:46 php_app

If I run the exact same docker commands locally, the images build just fine, with the correct build context. However, inside Gitlab Runner the build context doesn't seem to do anything.
I've checked the official Docker build reference if there is anything related to this, but I can't find anything.
The only mention of an exception when using build context is:

You cannot specify the build-context directory (myfolder in the examples above) when using BuildKit as builder (DOCKER_BUILDKIT=1). Support for this feature is tracked in buildkit#1684.

but I'm not using that variable, and Gitlab also doesn't set it.
Also, the official Docker reference gives this example :
$ cd /home/me/myapp/some/dir/really/deep
$ docker build -f /home/me/myapp/dockerfiles/debug /home/me/myapp
$ docker build -f ../../../../dockerfiles/debug /home/me/myapp

These two docker build commands do the exact same thing. They both use the contents of the debug file instead of looking for a Dockerfile and will use /home/me/myapp as the root of the build context. Note that debug is in the directory structure of the build context, regardless of how you refer to it on the command line.
Any suggestions are welcome!

A: I think the solution for this is not related to Docker build at all. Look at your test node app job. You are running ls command in the folder which is used for cloning your whole repo. So in the fact you are running ls inside your image, inside the folder with the content of your repo.
This is the default behaviour of the GitLab CI job. It will clone your repo to the newly created folder and that's why you are seeing this output. Try to disable it with GIT_STRATEGY: none variable for both of your tests jobs or try to run ls /somewhereelse.
If you want to run your tests command for the content of your node/php image, it would be better to remove image: from the job and run it on the default pipeline image as docker run $CI_REGISTRY_IMAGE/$CONTAINER_NAME:latest run test scripts


text:
Q: Rate of convergence of an exponential function If I have a function $$f = \exp(\sqrt{n} \cdot \frac{\sqrt{\log{n}}}{\sqrt{n}-\sqrt{\log n}}),$$ I can notice, that $$\lim_{n \to \infty} f = \infty,$$ but also I can notice that it goes very slowly to infinity, for example for $$n = 1000, f(n) \approx exp(2.87),$$ $$n = 10000, f(n) \approx exp(3.13).$$
How can I write that the rate of convergence is very slow? I mean I don't want to just write that $f \to \infty$, but I want use more accurate asymptotic notation which will help me to express that?

A: I guess one way of seeing it rewriting the function $\frac{\sqrt{n} \log n }{\sqrt{n}-\log n} = \frac{\log n }{1 -\frac{\log n}{\sqrt{n}}}$. Hence your function becomes $n^\frac{1}{1-\frac{\log n }{\sqrt{n}}} \sim n^{1 +\frac{\log n}{\sqrt{n}} + O\big(\frac{1}{n^2}\big)}$, where each term $n^{a_n} \to_n 1$. Hence your expression grows $\sim n$ for large enough $n$.


text:
Q: From Xml point of view, what is action, category and data(of intent filter of Android) called as? We have terms like attributes, name , elements etc.

In XML point of view, What is "action", "category", "data" and "intent-filter" called? What the name given for those?

A: THat means whenever an application sends an Intent with action=VIEW and a url that starts with geo://, that the Activity with this filter can be started to handle it.  Usually you would put a URL as well so it would only handle geo://url, but they decided not to here.  The usual usecase for this is deep linking.


text:
Q: Can't change value of cell with code in a protected sheet I have a password protected sheet, with some unlocked cells that user can chage.
Once the user changes any value, it automatically should make changes to other unlocked cells by vba code. This works fine if the sheet is unlocked, but not if it's protected.
example of code:
In Workbook_Open() I set UserInterfaceOnly attribute to TRUE:
Sheets("Sheet Name").Protect Password:="123456", UserInterFaceOnly:=True, Contents:=True

Sheet code: Set date.01 value into date.02 cell if date.01 changes
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  If Not Intersect(Target, Range("date.01")) Is Nothing Then
    Worksheets("Sheet Name").Range("date.02") = Target
  End If
End Sub

cells "date.01" and "date.02" are unlocked.
Why can't I update them?
EDIT:
Is SelectionChange event the best option to change cell values? And is it ok to do the assignment like this:
Worksheets("Sheet Name").Range("date.02") = Target

I can see that the changes are applieD when the original cell get the focus back.
What I really want to do is to give a group of cells in different sheets the same value anytime any of them are changed by the user.
SOLVED.
My bad, I was using
Worksheet_SelectionChange

instead of
Worksheet_Change

I also had to use this to prevent any errors.
Application.EnableEvents = False
<CODE>
Application.EnableEvents = True

There was no need of using UserInterfaceOnly as all cells/ranges are unlocked.

A: you can simply check it's something to do with protection.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Range("date.01")) Is Nothing Then
Sheets("Sheet Name").unProtect Password:="123456"
`Worksheets("Sheet Name").Range("date.02") = Target`
`Sheets("Sheet Name").Protect Password:="123456", UserInterFaceOnly:=True`

End if

End Sub
Do you apply validation through VBA

A: The event method to use is Worksheet.Change Event
https://msdn.microsoft.com/en-us/library/office/ff839775.aspx
And the code was like:
Private Sub Worksheet_Change(ByVal Target As Range)
  If Not Intersect(Target, Range("date.01")) Is Nothing Then
    Application.EnableEvents = False
    Worksheets("Sheet1").Range("date.01") = Target
    Worksheets("Sheet2").Range("date.02") = Target
    Worksheets("Sheet3").Range("date.03") = Target
    Worksheets("Sheet4").Range("date.04") = Target
    Worksheets("Sheet5").Range("date.05") = Target
    Application.EnableEvents = True
  End If
End Sub


text:
Q: Python 3 - How to remove line/paragraph breaks from docx import Document

alphaDic = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','!','?','.','~',',','(',')','$','-',':',';',"'",'/']

while docIndex < len(doc.paragraphs):
    firstSen = doc.paragraphs[docIndex].text
    rep_dic = {ord(k):None for k in alphaDic + [x.upper() for x in alphaDic]}
    translation = (firstSen.translate(rep_dic))
    removeSpaces = " ".join(translation.split())
    removeLineBreaks = removeSpaces.replace('\n','')
    doc.paragraphs[docIndex].text = removeLineBreaks

    docIndex +=1

I am attempting to remove line breaks from the document, but it doesn't work.
I am still getting
Hello

There

Rather than
Hello
There

A: I think what you want to do is get rid of an empty paragraph. The following function could help, it deletes a certain paragraph that you don't want:

def delete_paragraph(paragraph):
    p = paragraph._element
    p.getparent().remove(p)
    p._p = p._element = None

Code by: Scanny*

In your code, you could check if translation is equal to '' or not, and if it is then call the delete_paragraph function, so your code would be like:
while docIndex < len(doc.paragraphs):
    firstSen = doc.paragraphs[docIndex].text
    rep_dic = {ord(k):None for k in alphaDic + [x.upper() for x in alphaDic]}
    translation = (firstSen.translate(rep_dic))
    if translation != '':
        doc.paragraphs[docIndex].text = translation
    else:
        delete_paragraph(doc.paragraphs[docIndex])
        docIndex -=1 # go one step back in the loop because of the deleted index

    docIndex +=1

*Reference- feature: Paragraph.delete()

A: The package comes with an example program that extracts the text.
That said, I think your problem springs from the fact that you are trying to operate on paragraphs. But the separation between paragraphs is where the newlines are happening. So even if you replace a program with the empty string (''), there will still be a newline added to the end of it.
You should either take the approach of the example program, and do your own formatting, or you should make sure that you delete any spurious "empty" paragraphs that might be between the "full" ones you have ("Hello", "", "There") -> ("Hello", "There").

A: Since readlines could read any type of text files, you can open the file rewrite the lines you want and ignore the lines you dont want to use.
"""example"""

file = open("file name", "w")
for line in file.readlines():
    if (line != ''):
        file.write(line)


text:
Q: Make Ant's Java task print empty lines When running Java applications through the java Ant task empty lines are not printed. This makes it harder scan long output files, since all separation is removed.
Do anybody know how to make ant print empty lines?
Thanks
Example:
Running the following java code through ant:
System.out.println("Hello");
System.out.println("");
System.out.println("World");

I expect ant to produce:
[java] Hello
[java]
[java] World

But the outputs is
[java] Hello
[java] World

A: I tested the following code using Ant 1.8.2 on Ubuntu Linux 12.04 as well as on Windows 7. On both operating systems the empty line was printed as shown in the output below.
JavaTest.java
/**
 * Java test.
 */
public class JavaTest {

  public static void main(String[] args) {
    System.out.println("Hello");
    System.out.println("");
    System.out.println("World");
  }
}

Inside build.xml
<target name="java-test" depends="compile">
  <java classpath="${classes.dir}" classname="JavaTest"
      fork="true" failonerror="true" />
</target>

Output
$ ant java-test
Buildfile: /home/my/project/build.xml

java-test:
     [java] Hello
     [java]
     [java] World

BUILD SUCCESSFUL
Total time: 2 seconds

A: Another way without compiling special classes - use script e.g.

<script language="groovy">
       println("Hello\n\nWorld!")
</script>


text:
Q: Minimum $\chi^2$ fit of experimental data in absence of fluctuations of one variable I know how to make a minimum-chi square fit when I have two variables both affected by statistical error. But how do I perform the fit when one of them has no statistical error, just the uncertainty of the instrument (for example say I am using a ruler which carries a constant uncertainty of 1mm) and according to my model this uncertainty cannot be neglected?
I use Root by Cern to make fits. I assume it follows this procedure to minimize $\chi^2$ of the fit when both the $x$ and $y$ variables are affected by statistical error (picture taken from L. Lyons, Statistics for nuclear and particle physicists, page 139)

This hinges on the condition that both values of $x$ and $y$ are gaussian distributed, so that you can evaluate the $\chi^2$ value corresponding to a given choice of the fit parameters. But what happens when you have no info on the statistics of $x$ and you just know that each measurement is sistematically affected by some fixed uncertainty of the measuring instrument?

A:
how do I perform the fit when one of them has no statistical error, just the uncertainty of the instrument

The best resource for learning about how to handle analyzing and reporting uncertainty in science is the NIST technical note 1297 on uncertainty: https://www.nist.gov/pml/nist-technical-note-1297
In there they classify uncertainty in two broad category. One is uncertainty which is evaluated based on statistical methods and the other is uncertainty which is evaluated based on non-statistical methods. In your case, for the specific measurement of interest the uncertainty would be the second type.
The best place to obtain the non-statistical uncertainty is in the manufacturer's documentation for the measuring device. If there is no documentation available or if the documentation doesn't specifically list the uncertainty, then it might be reasonable to assume that the uncertainty is based on the smallest digit of a digital display or the smallest tick mark of a non-digital display. If so, then you would model a reading of 1.02 V as coming from a uniform distribution from 1.015 V to 1.025 V. The standard uncertainty would then be equal to the standard deviation of a uniform distribution with a width of 0.01 V.
When you have both types of uncertainty, statistical and non-statistical uncertainties, then the combined standard uncertainty is the square root of the sum of squares of the individual uncertainties. This is basically the propagation of errors formula.

A: This is not a trivial problem: indeed, $\chi^2$ goodness-of-fit tests assume Gaussian distribution of the residual errors, and would be affected by the rounding error (since it renders these distribution non-Gaussian). A brief google search for "Goodness of fit rounding" shows that there is no generally accepted procedure for dealing with such situations, e.g., see
About the effect of rounding on the properties of tests for testing statistical hypotheses
Sensitivity of goodness-of-fit statistics to rainfall data rounding off
Parametric approach
One could design a statistical model for the rounding error (e.g., the values are uniformly distributed between two scale marks and rounded with probability $p$ to upper value and with probability $q=1-p$ to the lower one), which would give the general distribution of residuals for which one can construct a statistical test (likely more complicated than the $\chi^2$, but doable with modern computers.)
Non-parametric approach
One could look for non-parametric tests for goodness-of-fit, that is the tests that do not assume a specific underlying distribution. I would not be surprised, if some people would still argue that the Gaussian assumption is not necessary for using the least squares test. E.g., see What are some of the most common misconceptions about linear regression?
Practical approach
Posting a question on Cross Validated (the Stack Exchange forum for statisticians) is likely to generate more qualified answers than in PSE.