text:
Q: Why does my gem take so long to load? I'm developing my first gem called t_time_tracker (woohoo!). All was going great in development; I optomized it as much as I possibly could to cut execution time down to as little as possible:
t_time_tracker[master*]% time ruby -Ilib ./bin/t_time_tracker
You're not working on anything
0.07s user 0.03s system 67% cpu 0.141 total

(this is the "hello world" of my app - calling it with no parameters just prints out "You're not working on anything")
About a tenth of a second and uses 67% of my CPU - cool, I can live with that. It feels fairly instantaneous. Let's build it:
$ gem build t_time_tracker.gemspec
$ gem install ./t_time_tracker-0.0.0.gem

And do the exact same thing with the installed binary:
$ time t_time_tracker
You're not working on anything
t_time_tracker  0.42s user 0.06s system 93% cpu 0.513 total

Half a second?! Where did that come from?! Let's add some debugging output and include the system gem from the development binary to see where the bottleneck is:
t_time_tracker[master*]% time ruby ./bin/t_time_tracker
(starting binary)
(require 'time' and 'optparse')
0.041432
(before `require 't_time_tracker')
0.497135
(after `require 't_time_tracker')
(Gem.loaded_specs.keys = t_time_tracker)
(initializing TTimeTracker class)
You're not working on anything
ruby ./bin/t_time_tracker  0.44s user 0.07s system 91% cpu 0.551 total

Alright, so the `require 't_time_tracker' line seems to be the culprit. Let's try again in irb to narrow it down further:
$ irb
>> t=Time.now; require 't_time_tracker'; puts Time.now-t
0.046792
=> nil

...what? But that was just taking half a second! Let's try building the gem with our debugging output:
$ gem build t_time_tracker.gemspec
$ gem install ./t_time_tracker-0.0.0.gem
$ time t_time_tracker
(starting binary) <---noticeable half second delay before this line shows up
(require 'time' and 'optparse')
0.050458
(before `require 't_time_tracker')
0.073789
(after `require 't_time_tracker')
(Gem.loaded_specs.keys = t_time_tracker)
(initializing TTimeTracker class)
You're not working on anything
t_time_tracker  0.42s user 0.06s system 88% cpu 0.546 total

So yeah, where is this 0.5 second delay coming from? I usually wouldn't care, but this is something that I'm calling about fifty times a day to update what I'm doing. 50 * 0.5 seconds * 365 days * 70 years = 15 days of lost life.
System information:
Mac OS X 10.7.3. 2 GHz Intel Core 2 Duo. 4 GB ram. ruby 1.9.2p290.
% gem -v
1.8.10<---noticeable half second delay before this line shows up
% gem list | wc -l
209

A: Been a while since I looked at this but RubyGems has, in the past (and maybe the present), taken a long time to load for mainly two reasons:

*

*It would load many relatively expensive libraries like 'time' via 'yaml'.  Usually you don't care because it's slow relative to ruby all by itself, not slow compared to the run time of many scripts.

*It would scan over all the installed gems and load the most recent gemspecs into memory.  This took a long time if you have a lot of gems.

These issues may or may not still be in play.  However you'll always have some overhead from RubyGems.  If you really need performance, then just set up your load path yourself!  Ruby without RubyGems is very fast, as you know.
To see where your gem is installed:
gem list -d YOUR_GEM_NAME

You'll see the install directory.  Your gem will be at INSTALL_DIR/gems/GEM_NAME-VERSION so try executing:
time ruby -IINSTALL_DIR/gems/GEM_NAME-VERSION/lib INSTALL_DIR/gems/GEM_NAME-VERSION/bin/t_time_tracker

That's a lot, but you should be able to wrap this in a separate script, something like this (name it t_time_tracker):
#!/usr/bin/env ruby -IINSTALL_DIR/gems/GEM_NAME-VERSION/lib
load 'INSTALL_DIR/gems/GEM_NAME-VERSION/bin/t_time_tracker'

Then:
chmod +x t_time_tracker
time ./t_time_tracker

And put that file anywhere along your PATH. RubyGems does for you automatically, but of course you then accept the overhead of RubyGems.

A: The $LOAD_PATH being used within your gem is likely to be the culprit. Ideally the path for your lib folder is first on that array.

A: It is probably because you have it "from local" gem. So ruby will have to check other paths before he wil pick him up.
eg. if you will have file called json.rb and gem installed globally called json when doing
require 'json'

he will find first gem and load it :). Local path is last to be loaded. If you will bundle the gem and install you will see massive speed improvement just because of different location in gems. I wouldn't worry much about this lack of load time in development.


text:
Q: AngularJS S3 file upload - Policy Condition failed I'm trying to upload a file to S3 using ng-file-upload module. I'm getting an error:

Invalid according to Policy: Policy Condition failed: ["eq",
  "$succes_action_status", "201"]

My code is based on this particular example, slightly changed:
api.js:
exports.signing = function(req, res) {

var request = req.body;
var fileName = request.filename;
var path = fileName;

var readType = "public-read";

var expiration = moment().add(5, 'm').toDate();

var s3Url = process.env.S3_URL;

var s3Policy = {
    'expiration': expiration,
    'conditions': [{
        'bucket' : process.env.S3_BUCKET,
    },
    ['starts-with', '$key', path],
    {
        'acl': readType
    },
    {
        'succes_action_status': '201'
    },
    ['starts-with', '$Content-Type', request.type],
    ['content-length-range', 2048, 10485760],
    ]
};

var stringPolicy = JSON.stringify(s3Policy);
var base64Policy = new Buffer(stringPolicy, 'utf-8').toString('base64');

//sign policy
var signature = crypto.createHmac('sha1', process.env.AWS_SECRET_KEY).update(new Buffer(base64Policy, 'utf-8')).digest('base64');

var credentials = {
    url: s3Url,
    fields: {
        key: fileName,
        AWSAccessKeyId: process.env.AWS_ACCESS_KEY,
        acl: readType,
        policy: base64Policy,
        signature: signature,
        'Content-Type': request.type,
        success_action_status: '201'
    }
};

res.jsonp(credentials);
};

controller.js
$scope.upload = function(files) {
    if (files.length > 0) {
        var filename = files[0].name;
        var type = files[0].type;
        var query = {
            filename: filename,
            type: type
        }
    };

    if (files && files.length) {
        for (var i=0; i < files.length; i++) {
            var file = files[i];
            photoService.signingS3(query).success(function(result) {
                Upload.upload({
                url: "https://***.s3.amazonaws.com",
                method: "POST",
                fields: result.fields,
                transformRequest: function (data, headersGetter) {
                        //Headers change here
                        var headers = headersGetter();
                        delete headers['Authorization'];
                        return data;
                },
                file: file
            }).progress(function(evt) {
                console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total));
            }).success(function (data, status, headers, config) {
                console.log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
                }).error(function(err) {
                    console.log(err);
                });
            }).error(function(data, status, headers, config) {
                console.log(data);
            });
            }

        }
    }

Can you tell me what's wrong with it?

A: here ['starts-with', '$key', path]  the value of path must be: 'somedirectory in s3' + fileName; . Also, check your bucket name is filled accordingly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TF10175: The team project does not exists I use visualstudio online for repository.
I removed [ProjectName] project from collecection of project
After that I got error only on one computer
TF10175: The [ProjectName] team project doesnot exist.
Any idea to solve this issue ?

A: I got rid of the message by deleting my Workspace.
Note: This will remove all your local mappings. Therefore you should checkin all changes before deleting it. After re-connecting to your TFS a new workspace will be created automatically.
To delete the workspace follow these steps:

*

*In "Team Explorer" select "Pending Changes"

*Beside the "Check In" button click on "Actions" and select "Manage Workspaces…"

*Select the Workspace and press "Remove"

A: In Team Explorer, press the "Connect to Team Projects" button, that looks like a plug. You should be able to un-select the deleted Team project.

A: Go to your Source control explorer then click on workspace dropdown in the visual studio, you will find option "Workspaces" click on it. it will list the workspaces you have. click edit on your workspace , and delete the unneeded project from your workspace. it will work after that.

A: I  was adding files/items to a newly created TFS/Agile project when I got this error message.
The TFS Project (source code) was mapped to c:\ABC but for some reason adding files from c:\AAB didn't work. I copied all files from c:\AAB to c:\ABC and then tried adding the items from the mapped folder and it worked.

A: I received this error because of a more basic problem.  I could not attach my solution to the team project because the names were different:
1. Bad Project Name: "Employee Travel" -> space between words
2. Fixed Project Name: "EmployeeTravel" -> matches solution name


text:
Q: Display access query output in a text file - notepad How can I display the outout of a query in a notepad on button click in access?
I have a button "View Query Output" in access. I want to be able to display the ouput in a notepad file. How can I do this?
Thanks in advance

A: You can use DoCmd.TransferText to save the output to a textfile and FollowHyperlink to open the file.


text:
Q: How to detect when an AWS instance is fully functional We are using Bamboo to spin up (through Powershell on the buildserver) an AWS Windows 2008 R2 instance as a target for a web deployment.
What is the best method for determining that the target instance is ready for a deployment (all services up and running, etc).

A: There's no real easy way to do this with Windows instances. Your best bet is to write a infrastructure test that looks to see if a service is running on the target environment and to keep retrying until it either verifies that the service is available or a timeout has occurred. At that point you could start your deployment.
I generally do this with a cucumber script that will check a service's status continually until it gets an answer
You could also set a timeout for an appropriate amount of time, although this option wouldn't be my recommendation


text:
Q: Is there a shorter way to write this code? I want to return a list of the values in the binary tree.
Is there a shorter and more efficient way to write the method for numbers?
Thank you.
class BTNode(object):
    """A node in a binary tree."""

    def __init__(self, item, left=None, right=None):
        """(BTNode, object, BTNode, BTNode) -> NoneType
        Initialize this node to store item and have children left and right,
        as well as depth 0.
        """
        self.item = item
        self.left = left
        self.right = right
        self.depth = 0  # the depth of this node in a tree

    def number(self) -> list:
        lst = []

        if self.right is None and self.left is None:
            lst.append(self.item)
        else:
            lst.append(self.item)
        if self.left:
            left = self.left.number()
            lst.extend(left)
        if self.right:
            right = self.right.number()
            lst.extend(right)
        return lst

A: If you don't mind a generator rather than a list, you can write the code quite neatly.
def number(self):
    yield self.item
    for child in self.left, self.right:
        if child: yield from child.number()

I've never seen the type annotations you have in Python before. Is that a Python 3 thing?

A: I've got a nonrecursive iterator for returning the values in a tree (treap) at
https://pypi.python.org/pypi/treap
To get from an iterator to a list is just a matter of wrapping the iterator like list(it())
Last I heard, 'yield from' was slow.


text:
Q: Understanding proof of Collins' Weingarten calculus formula I am trying to understand Collins' paper on Weingarten calculus. You can find it here: click!
On page 7, between the formulas $(2.6)$ and $(2.7)$, he claims that the action $\pi^{\otimes q} \otimes \Psi$ is on $M_d(\mathbb{C})^{\otimes q}$, but, as far as I understand, since both $\pi^{\otimes q}$ and $\Psi$ are on  $M_d(\mathbb{C})^{\otimes q}$, the tensor product action should be on $M_d(\mathbb{C})^{\otimes q} \otimes M_d(\mathbb{C})^{\otimes q}$, right? However, the minimal invariant projections $I_\lambda$ are multiplicated by a $\tilde{B}$, which is an element of $M_d(\mathbb{C})^{\otimes q}$, confirming that the afore-mentioned action should be on $M_d(\mathbb{C})^{\otimes q}$. Am I missing something?
Moreover, he claims that we know, from representation theory, that an algebra is abelian and that the minimal invariant projections are indexed by partitions of $q$. Could you provide me with a reference on that? I would be very interested by a reference carrying out concrete examples for small $q$.

A: I mean, sure, technically putting a $\otimes$ symbol between $\pi^{\otimes q}$ and $\Psi$ ought to imply an action on the tensor product $M_d(\mathbb{C})^{\otimes q}\otimes M_d(\mathbb{Q})^{\otimes q}$, but that's not what they mean. Since the action of $\Psi$ normalizes the action of $\mathbb{U}_d^q$ (adopting their notation of $\mathbb{U}_d$), so there is an action of the semidirect product $\mathbb{U}_d^q\rtimes S_q$, which is known as the wreath product $\mathbb{U}_d\wr S_d$, on $M_d(\mathbb{C})$. Maybe you want to say $\pi^{\otimes q}\cdot\Psi$ instead of $\pi^{\otimes q}\otimes\Psi$.
The keyword to start searching is "Schur-Weyl duality."


text:
Q: If textbox empty, return true or show confirmation If textbox empty, return true
else, show confirmation
Working Test: http://next.plnkr.co/edit/KfD3oznkl3eBXgPx
What I am trying to do:
When user enter try to click "submit" and the password textfield is blank , then it should return true directly, but if password textfield have data, it should show confirm prompt out.
What I have done:
When password textfield is empty, it directly returns true, but when have value, it show confirmation, but even I click on "no" in the confirmation box, it returns true
Code:

 Edit Profile

<form onSubmit="return validateForm()">
  <input type="text" placeholder="Username" id="uname">

  <input type="password" placeholder="password" id="password">

  <input type="text" placeholder="email" id="email">

  <input type="submit" id="check" value="OK">
</form>

A: Window.confirm()

Returns a boolean value indicating whether OK (true) or Cancel (false) was selected. If a browser is ignoring in-page dialogs, then result is always false.

You should check the value returned by confirm

function validateForm(e) {
  var password=document.getElementById("password").value;
  if (password==""){
    return true;
  }
  else{
    var confirmRes = confirm("Are You Sure you wanted to change password?");
    return confirmRes;
    //OR Simply
    //return confirm("Are You Sure you wanted to change password?");
  }
}

 Edit Profile

<form onSubmit="return validateForm()">
  <input type="text" placeholder="Username" id="uname">

  <input type="password" placeholder="password" id="password">

  <input type="text" placeholder="email" id="email">

  <input type="submit" id="check" value="OK">
</form>

A: confirm returns a boolean value that you are not using in your program.
Try adding return before confirm to actually make use of the value given by the confirm function
if (password==""){
    return true;
}
else{
  return confirm("Are You Sure you wanted to change password?");
}

Hope this helps :)

A: confirm API will return true or false based on user selection. So you can just return the value from confirm as below
function validateForm(e) {
   var password = document.getElementById("password").value;
   return password === "" || confirm("Are You Sure you wanted to change password?");
}

A: I've edited your code See if it works:

function validateForm(e) {
          var password=document.getElementById("password").value;
          if (password==""){
              document.getElementById("myform").submit();
          }
          else{
            if(confirm("Are You Sure you wanted to change password?")){
              document.getElementById("myform").submit();
            }
          }
      }

 Edit Profile

    <form id="myform">
      <input type="text" placeholder="Username" value="Tommy" id="uname">

      <input type="password" placeholder="password" id="password">

      <input type="text" placeholder="email" value="test@gmail.com" id="email">

      <input type="button" id="check" value="OK" onclick="validateForm()">
    </form>

A: You have to return false instead of true when password is empty. That's you don't have to submit the form when the password is not entered. Also require a return statement in for confirm. Make your changes as follows.
function validateForm(e) {
    var password=document.getElementById("password").value;
    if (password==""){
      return false;
    }
    else{
      return confirm("Are You Sure you wanted to change password?");
    }
  }

A: Try this, i checked the confirm value in the else section.

      function validateForm(e) {

          var password=document.getElementById("password").value;
          if (password==""){
              return true;
          }
          else{
            var r = confirm("Are You Sure you wanted to change password?");
            if (r == true){
              return true;
            }
            else {
              return false;
            }
          }
      }

 Edit Profile

    <form onSubmit="return validateForm()">
      <input type="text" placeholder="Username" value="Tommy" id="uname">

      <input type="password" placeholder="password" id="password">

      <input type="text" placeholder="email" value="test@gmail.com" id="email">

      <input type="submit" id="check" value="OK">
    </form>


text:
Q: Non-resolvable parent POM and Could not transfer artifact from/to central repository and transfer failed for spring-boot-starter-parent-2.5.4.pom My Pom File:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <!--<relativePath/>--> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.rakib</groupId>
    <artifactId>kube_demo_child</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>kube_demo_child</name>
    <description>kube_demo_child</description>
    <properties>
        <java.version>16</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

My Dockerfile:
ARG JDK=maven:3.8.2-openjdk-16-slim
ARG JRE=openjdk:16-jre-slim-buster

FROM ${JDK} AS build
WORKDIR /home/app
COPY src /home/app/src
ADD pom.xml .
COPY pom.xml /home/app
RUN mvn -f /home/app/pom.xml clean package

FROM ${JRE}
COPY --from=build /home/app/target/kube_demo_child-0.0.1-SNAPSHOT.jar /usr/local/lib/kube_demo_child-0.0.1-SNAPSHOT.jar
EXPOSE 8081
ENTRYPOINT ["java","-jar","/usr/local/lib/kube_demo_child-0.0.1-SNAPSHOT.jar"]

Giving this error while i trying to build a docker image:
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project com.rakib:kube_demo_child:0.0.1-SNAPSHOT (/home/app/pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for com.rakib:kube_demo_child:0.0.1-SNAPSHOT: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.5.4 from/to central (https://repo.maven.apache.org/maven2): transfer failed for https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.5.4/spring-boot-starter-parent-2.5.4.pom and 'parent.relativePath' points at wrong local POM @ line 5, column 13: Unknown host repo.maven.apache.org: Temporary failure in name resolution -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
The command '/bin/sh -c mvn -f /home/app/pom.xml clean package' returned a non-zero code: 1


text:
Q: I want to make users have full access only on ONE rds instance I tried using this policy:
{
  "Version":"2012-10-17",
  "Statement":[{
    "Effect":"Allow",
    "Action":"rds:*",
    "Resource":"arn:aws:rds:sa-east-1:442617300818:db:databasename"
    }]
}

And the response is:

User: arn:aws:iam::442617300818:user/wa-DB-developers is not
  authorized to perform: rds:DescribeDBInstances (Service: AmazonRDS;
  Status Code: 403; Error Code: AccessDenied; Request ID:
  5f1e86c6-8145-11e4-9598-27c541a5a3a7)

THANKS!

A: Policies can be debugged by using the IAM Policy Simulator.
The simulator allows you to select a User, an Action (eg DescribeDbInstances) and a resource, and then determine whether the User is allowed to call that action on that resource.
In your specific case, since the policy only grants permission on a specific RDS instance, a call to DescribeDBIntances without specifying a specific instance will fail.
For example, from the CLI this will fail:
aws rds describe-db-instances

However, this will work:
aws rds describe-db-instances --db-instance-identifier databasename

This is because you have not granted permission to view all databases. Querying only the specific database to which the policy has granted access will succeed.

A: This worked for me. This way lets the user see all the databases, then deny access to the databases you don't want the user to make adjustments to. The user will be able to see the other instances but will not be able to effect them.  They will not even be able to see the logs, tags, etc.
   {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "rds:*",
                "cloudwatch:DescribeAlarms",
                "cloudwatch:GetMetricStatistics",
                "ec2:DescribeAccountAttributes",
                "ec2:DescribeAvailabilityZones",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeSubnets",
                "ec2:DescribeVpcs",
                "sns:ListSubscriptions",
                "sns:ListTopics",
                "logs:DescribeLogStreams",
                "logs:GetLogEvents"
            ],
            "Effect": "Allow",
            "Resource": "*"
        },
        {
            "Effect": "Deny",
            "Action": [
                "rds:*"
            ],
            "Resource": "arn:aws:rds:eu-west-1:accountIDofIAMUser:db:instancename"
        }
    ]
}

The only issue you might have is if you have many instances that you need to remove access to, other than that and as long as you are ok with the user seeing the overall view of the other databases you should be good to go.


text:
Q: Runtime topic subscription in WSO2 ESB using JMS I have a topic in the WSO2 ESB 4.6.0 that I want to create subscriptions to at runtime using JMS, to allow pub-sub.
It is documented that the event-broker in 4.6.0 is based on Apache Qpid, however, it doesn't appear to be bundled.  By default, an in-memory event broker is configured.
http://docs.wso2.org/wiki/display/ESB460/Eventing
I am using ActiveMQ as my JMS message broker, however, if required, it is possible to change to Qpid.
Has anyone managed to get this working?

A: Yes. You can use apache Qpid as your JMS broker with WSO2 ESB. It has been tested in production enviornments as well. You can follow the same steps as mentioned in the samples which uses ActiveMQ as the JMS broker.


text:
Q: Interleave a list with itself and another list I have a list of 6 numbers and I have a list containing 4 lists.  I want to put the first 3 numbers in the first list and the next 2 numbers in the list after it and  finally the last number in the list of 6 in the last list of lists.
I know this is confusing but here is my code to visualize it :
Start_Comparing_Index = -1
Looping_Counter = 4 # = 4
for counter in range(4):
Looping_Counter -= 1  # =3
Start_Comparing_Index += 1  # = 0
print("counter = " + str(counter))
for i in range(Looping_Counter):
    s[counter].append(x[Start_Comparing_Index])
    print("Comp index= " + str(Start_Comparing_Index))
    if i == range(Looping_Counter)[-1]:
        break
    else:
        Start_Comparing_Index += 1
print(s)

but its printing out :

counter = 0
Comp index= 0
Comp index= 1
Comp index= 2
counter = 1
Comp index= 3
Comp index= 4
counter = 2
Comp index= 5
counter = 3
[[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]

Although I want it to print this list instead:
[[1,2,3],[4,5],[6]]

What is wrong with my code?

A: def get_lists(src, n):
    r, s = [], 0
    for i in range(n, -1, -1):
        r.append(src[s:s+i])
        s += i
    return r

print(get_lists(list(range(1, 7)), 3))
# [[1, 2, 3], [4, 5], [6], []]

A: Strange question.  If you know exactly the length of all lists, and the exact mix of elements you want in the result, why don't you exactly write that, without any loops?
>>> first = range(1,7)
>>> second = [6]
>>> merged = [first[0:3], first[3:-1], second]
>>> merged
[[1, 2, 3], [4, 5], [6]]


text:
Q: How to count a feature x if y condition is true (bigquery) I am new in machine learning and I am running one of my first machine learning problems. I do a lot of research by myself but could not find the solution for this question.
I am creating new variables from my dataset in Bigquery. One of the variables consists in count a variable (x) if a condition in variable (y) is met. I cannot use WHERE or HAVING since the condition is only related to the calculation of this specific variable.
The code is more or less like this:
COUNT(DISTINCT sessionid IF(date > "2018-06-01" && date < "2018-06-30"))
AS sessions_lastmonth

I know that this code is not correct and could not be but is just a way to express more or less what I need.
The goal is to know the number of sessions in a certain period. I cannot use the count for date because in one day you can have more than one session and not every row is a different session (a session can have several lines because the user can go through many pages in the same session).
Thank you!

A: You said you couldn't use WHERE so I am going to assume that the answer that proposes you use WHERE won't fly?
I think you might need to use CASE instead, so your query might look something like:
COUNT(DISTINCT CASE WHEN date > "2018-06-01" AND date < "2018-06-30" THEN sessionid ELSE NULL END) AS sessions_lastmonth

That syntax might not be right, but it might help you onto the right track?

A: Below for BigQuery Standard SQL
COUNT(DISTINCT IF(date >= '2018-06-01' AND date <= '2018-06-30', sessionid, NULL)) AS sessions_lastmonth


text:
Q: Halo effect with WindowsAPICodePack library Does any one have any experience on how to implement the halo(outline) effect for text with Direct 2D using the WindowdsAPICodePack? I searched for its API with google, but could not find any result for this; so I doubt if it supports it.
I appreciate if you have commends or article I can follow with.
Thanks,
Howard

A: I think you're talking about DrawThemeTextEx(), DTTOPTS.iGlowSize value.
No, it doesn't.


text:
Q: Sliding Butoon not moving within a layout enter image description here
In above image I have created a sliding button,which I wish to move towards right side only.And when its to the right side I wish to perform next activity.
The problem is when I move the button the entire relative layout moves.example if I move Button downwards Relative Layout expands downwards.same for left n right..below is layout and Activity.
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/rect"
        android:layout_marginTop="20dp"
        >
        <ImageView
            android:id="@+id/img_slide"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/next"
            android:background="#00000000"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:text="SLIDE TO NEXT ACTIVITY"
            android:layout_centerInParent="true"
            android:textStyle="bold"/>
    </RelativeLayout>

    public class MultiTouchListener implements OnTouchListener
    {

        private float mPrevX;
        private float mPrevY;

        public MainActivity mainActivity;
        public MultiTouchListener(MainActivity mainActivity1)
        {
            mainActivity = mainActivity1;
        }

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            float currX,currY;
            int action = event.getAction();
            switch (action ) {
                case MotionEvent.ACTION_DOWN: {

                    mPrevX = event.getX();
                    mPrevY = event.getY();
                    break;
                }
                case MotionEvent.ACTION_MOVE:
                {
                    currX = event.getRawX();
                    currY = event.getRawY();

                    MarginLayoutParams params = new MarginLayoutParams(view.getLayoutParams());
                    params.setMargins((int)(currX - mPrevX), (int)(currY - mPrevY),0,0);

                    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(params);
                    view.setLayoutParams(layoutParams);

                    break;
                }
                case MotionEvent.ACTION_CANCEL:
                    break;
                case MotionEvent.ACTION_UP:
                    break;
            }
            return true;
        }
}

public class MainActivity extends AppCompatActivity
    {
        ImageView imgSlide;

        MultiTouchListener touchListener=new MultiTouchListener(this);
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.slidingbtn);

            imgSlide=(ImageView)findViewById(R.id.img_slide);
            imgSlide.setOnTouchListener(touchListener);
        }
}

A: activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context="com.example.slidetoopen.MainActivity">

    <RelativeLayout
        android:id="@+id/rlBack"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:background="@drawable/bg_slide">

        <ImageView
            android:id="@+id/img_slide"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:src="@drawable/bg_circle" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="SLIDE TO NEXT ACTIVITY"
            android:textColor="#ffffff"
            android:textStyle="bold" />
    </RelativeLayout>
</RelativeLayout>

bg_circle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="100pt" />
    <solid android:color="#054b9b" />
    <stroke
        android:width="1dp"
        android:color="#a2c1ff" />

    <size
        android:width="50dp"
        android:height="50dp" />
</shape>

bg_slide.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="100pt" />
    <solid android:color="#000000" />
    <stroke
        android:width="2dp"
        android:color="#0000FF" />

</shape>

MainActivity.java
public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private ImageView img_slide;
    private RelativeLayout rlBack;
    private float x = 0, posX = 0, preX = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rlBack = (RelativeLayout) findViewById(R.id.rlBack);
        img_slide = (ImageView) findViewById(R.id.img_slide);
        img_slide.setOnTouchListener(touchListener);
    }

    private View.OnTouchListener touchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    v.bringToFront(); // set current view at front of other view
                    x = event.getX(); // get x pos
                    preX = v.getX(); // get view x pos
                    break;
                case MotionEvent.ACTION_MOVE:
                    float curX = event.getX() - x; // subtract previous x from
                    // current x
                    posX = preX + curX;
                    // check boundary of parent view, so view is move inside
                    // only parent view
                    if (posX > rlBack.getX() + 10 && (posX + v.getWidth()) < rlBack.getWidth() - 10) {
                        v.setX(posX);
                        preX = posX;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    // check circle is left of center of right of center
                    int width = rlBack.getWidth() - 10 - v.getWidth();      // 10 is for margin
                    if (v.getX() > (width / 2)) {
                        v.setX(width);
                        Toast.makeText(MainActivity.this, "Open", Toast.LENGTH_SHORT).show();
                        // code for activity open here
                    } else {
                        v.setX(rlBack.getLeft());
                        Toast.makeText(MainActivity.this, "Not Open", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
            v.invalidate();
            return true;
        }
    };
}

I hope it is helpful to you.


text:
Q: OpenCart 3.x - including a new template file I need to add a new OpenCart template file into another template file.
Essentially I've created a new head file in /theme/customtheme/template/common/ called "header_home.twig".
Then in home.twig, I've changed {{ header }} to say {{ header_home }}, but it's not displaying anything.
Basically, all I did was copy header.twig and rename it to header_home.twig, and put in "xxxxx" to see if it was calling the new file, which it's not. Instead, it's not displaying anything.
Here's what my home.twig now looks like:
{{ header_home }}

{{ column_left }}
    {% if column_left and column_right %}
    {% set class = 'col-sm-6' %}
    {% elseif column_left or column_right %}
    {% set class = 'col-sm-9' %}
    {% else %}
    {% set class = 'col-sm-12' %}
    {% endif %}

{{ content_top }}{{ content_bottom }}

    {{ column_right }}

{{ footer }}

I assume I'm somehow missing a step when it comes to adding a new template file? If someone could help me with adding in a new twig file, that would be fantastic.

A: You can either:

*

*Change the name of Twig rendering template on the OpenCart level in the controller/common/header as @bogalakon pointed out (preferably to do this via ocmod so that your future OpenCart updates will not overwrite your hack).

*or include another template on the Twig level

I.e.:
{{ header }} {# Original rendered to HTML OpenCart header - you can move it to your header_home.twig or just drop it #}
{% include customtheme/template/common/header_home.twig %}

 ...

Twig is very powerful template language. And you can do much more than just a simple include! It's nice that OpenCart officially accepted it. But for now it's just Twig 1.24.2. Please refer to the Twig documentation.

A: I haven't learn OpenCart 3.x, but I guess you need to change
return $this->load->view('common/header', $data);

to
return $this->load->view('common/header_home', $data);

in catalog/controller/common/header.php.

A: In order to connect another template via the {{header_home}} construct, you need to create the header_home.php in the folder /controller/common/directory, create the header_home.twig file in the theme /*theme_name*/template/common/ folder and in the controller , which is responsible for the formation of the page, for example in the directory /controller/common/home.php
add a line:
'$ data [' header_home '] = $ this-> load-> controller (' common / header_home '); '

before:
'$ this-> response-> setOutput ($ this-> load-> view (' common / home ', $ data)); '

A: To add your own custom twig file and include it inside another existing one you need to do three things:

*

*Create the actual custom twig file.
In your case it will be:
catalog/view/theme/customtheme/template/common/header_home.twig

*Create a controller for that twig file. In your case you can just copy:
/catalog/controller/common/header.php and rename that to header_home.php. Edit this controller and change the class name to ControllerCommonHeaderHome usually on line 2.

*Lastly, since you are going to include header_home inside home.twig, edit /catalog/controller/common/home.php and add the line $data['header'] = $this->load->controller('common/header_home'); after $data['header'] = $this->load->controller('common/header');
That's it. After you've done the steps above, you can now include {{ header_home }} inside home.twig. If you are editing the files directly, I find that sometimes I need to login to the admin of the website, go to design>theme editor, open up the files I added or changed, hit reset, and save. Refresh your website and you should see the changes.

A: The answer of @bogalakon is right but if you update your OpenCart core files you will lose your changes so, I suggest you to copy the header.php controller file and rename it to header_home.php and then edit the file and replace the line
return $this->load->view('common/header', $data);

with:
return $this->load->view('common/header_home', $data);

A: There are several ways to give a different value.
For example:
Consider the controller
$data['header'] = $this-> load-> controller ('common / header');

A variable {{header}} is available in the template
You can place a new template in another file (header_home.twig), and then you can immediately download a new template for use:
$data['**header**'] = $this-> load-> controller ('common / ***header_home***');

If you want use {{header}} in the template.
Or,
$data['**header_home**'] = $this-> load-> controller ('common / header_home');

For use {{header_home}} in the template.


text:
Q: How to convert ObservableCollection property result in to ObservableCollection type I have the following read only property,which I need to set it to below mentioned linq expression inside get statement. I have no idea how to do this.
Any advice or guidance will be much appreciated!
public ObservableCollection<Author> Authors { get; } = new ObservableCollection<Author>();

linq query
var result = (from author in Authors where author.Name.StartsWith(this.filterText) select author).ToList<Author>();

A: var result = this.Authors.Where(author => author.Name.StartsWith(this.filterText));
var filteredAuthors = new ObservableCollection<Authors>(result);

A: public ObservableCollection<Author> Authors
{
   get
   {
     var result = (from author in Authors
                   where author.Name.StartsWith(this.filterText)
                   select author).ToList();
     return new ObservableCollection<Author>(result);
   }
}

Blockquote


text:
Q: What is the correct URI to send to handleSamplingAndRotationBitmap? I have the common problem of display a picture in the correct rotation. My images are stored on a server. I call an image and display it in my app. Each image is rotated. So I found a correction with handleSamplingAndRotationBitmap.
public static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage)
        throws IOException {
    int MAX_HEIGHT = 1024;
    int MAX_WIDTH = 1024;

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
    BitmapFactory.decodeStream(imageStream, null, options);
    imageStream.close();

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    imageStream = context.getContentResolver().openInputStream(selectedImage);
    Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);

    img = rotateImageIfRequired(img, selectedImage);
    return img;
}

But it's impossible for me to send the correct Uri selectedImage.
protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon = null;
            final String myUrlStr = urldisplay;
            URL url;

            try {
                url = new URL(myUrlStr);
                uri = Uri.fromFile(new File(urldisplay));
                uri2 = Uri.parse((urldisplay).toString());

                mIcon = handleSamplingAndRotationBitmap(getContext(),uri2);
               } catch (MalformedURLException e1) {
                e1.printStackTrace();
            }

I have the error
} catch (FileNotFoundException e) {
            InputStream in = null;
            try {
                in = new URL(DataConstantes.lien_URLEtb + "Aucune_photo_etablissement.png").openStream();
            } catch (IOException e1) {
                flagError = true;
            }
            mIcon = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            flagError=true;
        }

java.io.FileNotFoundException:
  /http:/$$$$$$$$$$/appli/android_connect/Etablissement/abordage.jpg (No
  such file or directory)

Do you know how I can send the correct URI ?
Thanks


text:
Q: How do I disable the confirmation email sent out from Drupal? I am using Drupal 6.19. I don't want users to receive confirmation email on registration.
For this I unchecked "Require e-mail verification when a visitor creates an account" in Admin > User management > user settings.
But now what happens is that the verification email has been changed to confirmation email. i.e no verification link is there but the still the mail is sent out from the website with the user credentials. I do not need the mail at all. Could anyone suggest a solution for this problem?

A: In Drupal 7, the conf variable you should add the following line in your settings.php
$conf['user_mail_register_no_approval_required_notify'] = FALSE;

The bold could take this value :

*

*register_admin_created: Welcome message for user created by the
admin.

*register_no_approval_required: Welcome message when user
self-registers.

*register_pending_approval: Welcome message, user
pending admin approval.

*password_reset: Password recovery request.

*status_activated: Account activated.

*status_blocked: Account
blocked.

*cancel_confirm: Account cancellation request.

*status_canceled: Account canceled.

Be careful, it's user_mail_YOUR_VARIABLE_notify  .
Docs here and here.
Thanks for previous answers !

A: Depending on the type of message you need to disable, do the following ...
Add something looking like the following line in your settings.php
$conf['user_mail_register_no_approval_required_notify'] = FALSE;
Replace the part in bold with the proper email message code. Some possible values are:

*

*register_admin_created

*register_no_approval_required_notify

*register_pending_approval

*password_reset

*status_activated

*status_blocked

*status_deleted

A: Sounds like you'll need to write a custom module that has hook_form_alter and looks for submission of the registration form. You could hack away at the user module but then any updates will overwrite your changes.
Looks like user_Registration_submit makes a couple of conditional calls to _user_mail_notify which you probably want to catch and stop.
http://api.drupal.org/api/drupal/modules--user--user.module/function/user_register_submit/6
Initially I'd comment out those lines and register to confirm that they are responsible for the mail. If they are then you can try and see what you can do to step in and stop that call...
Hope that helps

A: There is now a module called Mail Control that takes care of this desire.
http://drupal.org/project/mailcontrol
It allows you say you don't want to send the User Welcome mail, and swap it out for Rules if you like, or just leave that part out of the experience.
This could be really useful if you were migrating in tons of users, or for a lightweight ecommerce site (which is why I needed it).
Drupal 7 and Drupal 6 handle this differently behind the scenes, but I think MailControl still puts the checkboxes at the same place in the User Admin UI.


text:
Q: Not accepting regex in IOS /^[a-zA-Z0-9'!@#%$^&*()_+\-=\[\]{};:"\\|,.<>\/? ]*$/

This regex is not working correctly in IOS. It is not accepting ' character.
Please help

let text = "String with a '";

var letters = /^[a-zA-Z0-9'!@#%$^&*()_+\-=[]{};:"\\|,.<>\/? ]*$/;
if (!(text.match(letters))) {
  console.log("No Special Characters Allowed");
}


text:
Q: Powershell export csv foreach loop for inactive AD accounts Hi How do I export the following powershell foreach loop into CSV | export-csv filename.csv sadly doesnt work on foreach loops. Also the Manager paramenter outputs DN only, Is there a way to display the managers email or SamAccountName in the same output instead of DN?
$90Days = (get-date).adddays(-90)
$OUSearch =

"OU=Contractors,OU=User,OU=x,OU=NZ,OU=Office,DC=add,DC=company,DC=coop,DC=us",
"OU=Contractors,OU=User,OU=xxx,OU=NZ,OU=Office,DC=add,DC=company,DC=coop,DC=us",
"OU=Contractors,OU=User,OU=xxxx,OU=NZ,OU=Office,DC=add,DC=company,DC=coop,DC=us",
"OU=Contractors,OU=User,OU=xxxxx,OU=NZ,OU=Office,DC=add,DC=company,DC=coop,DC=us",
"OU=Contractors,OU=User,OU=xxxxxx,OU=NZ,OU=Office,DC=add,DC=company,DC=coop,DC=us"

Foreach ($ou in $OUSearch){
Get-ADUser -SearchBase $ou -filter {(lastlogondate -le $90days -or passwordlastset -le               $90days) -and (enabled -eq $True)} -Properties lastlogondate, passwordlastset, manager |    Select SamaccountName, Name, Email, Manager, lastlogondate, passwordlastset, Enabled

}

A: There are a few ways I know to do that.
Assign the result of the foreach loop to a variable and then export at the end:
$result =
 foreach ($SomeThing in $SomeThings)
  {
    #Create an object
  }

$result | Export-csv c:\somedir\somethings.csv

Or wrap the foreach loop in a sub-expression and then pipe directly to Export-csv:
$(foreach ($SomeThing in $SomeThings)
  {
    #Create an object
  }) | Export-csv c:\somedir\somethings.csv

You can also use a script block instead of the sub-expression:
&{foreach ($SomeThing in $SomeThings)
  {
    #Create an object
  }} | Export-csv c:\somedir\somethings.csv

Not recommended, but too often seen is to create an array and do repetitive additions to the array inside the loop.  Bad idea. Don't do this:
$result = @()

foreach ($SomeThing in $SomeThings)
  {
    #Create an object
    $result += $object
  }

 $result | Export-csv c:\somedir\somethings.csv

A: Having recently had trouble with a similar issue, I might try calling your filter as a string, rather than a codeblock. Something like:
ForEach ($ou in $OUSearch) {
Get-ADUser -SearchBase $ou -filter '( lastlogondate -le $90days -or passwordlastset -le $90days ) -and ( enabled -eq $True )' -Properties lastlogondate, passwordlastset, manager | Select SamaccountName, Name, Email, Manager, lastlogondate, passwordlastset, Enabled
} | export-csv test.csv

This, at least, seemed to work for me in similar straits.


text:
Q: TypeError when fitting surface to 3D scatter data using scipy.optimize.curve_fit() I have a Pandas DataFrame with columns containing x, y, and z-values.
import pandas as pd
df = pd.DataFrame({'Age': x,
                   'Mileage': y,
                   'Price': z})

Using scipy.optimize.curvefit() I'm able to fit a univariate exponential function y = exp(-bx):
import numpy as np
from scipy.optimize import curve_fit

# fit y to x
def exp_function(x, a, b):
    return a * np.exp(-b * x)

popt, pcov = curve_fit(exp_function, df['Age'],    # x-values
                        df['Price'],               # y-values
                        absolute_sigma=False, maxfev=1000)

# popt
# array([2.81641498e+04, 1.29183078e-01])                      # a, b-values

But when I try to extend the same analysis to 3D, I encounter a TypeError:
# fit z to (x, y)
def exp_function_2(x, y, a, b, c):
    return (a/2) * (np.exp(-b * x) + np.exp(-c * y))

popt, pcov = curve_fit(exp_function_2,
                       df['Age'],           # x-values
                       df['Mileage'],       # y-values
                       df['Price'],         # z-values
                       absolute_sigma=False, maxfev=1000)

# TypeError: exp_function_2() takes 5 positional arguments but 1518 were given

Seems like it thinks I'm passing 1518 arguments (the length of my Pandas dataframe) into exp_function_2().
Why does my code work for the 2D (x, y) fit but get hung up on the 3D (x, y, z) fit?

A: You are calling the method with the incorrect arguments.
The docs indicate that the prototype is curve_fit(f, xdata, ydata, p0=None, ...), where p0 is the starting guess for the parameters of your function. So in the case when you have a TypeError, you are passing all 1518 elements of your frame as the default parameters to your function, which of course only accepts 5 arguments. The fact that your code works in the 2D case is a happy coincidence of not using the p0 keyword-argument at all.
You need to pass both the predictors as a single argument in xdata, and then unpack them inside the exponential function. Something like this (though I'm not sure I have the dataframe indexing correct, I rarely use pandas):
def exp_function_2(x, a, b, c):
    return (a/2) * (np.exp(-b * x['Age']) + np.exp(-c * x['Mileage']))


text:
Q: How to remove multiple click event of javafx button I have created a sample fx application with fxml using the scene buidler.
I have mapped an action handler on scene builder and write it on the java controller class. By clicking proceed button the screen will change to another screen. But sometime screen will get stuck at that time user will click proceed button multiple time, so the system will crash.
I have added disable property of button at the beginning of action controller, but it is not happening. How to block multiple event click event or just disable button at once clicked?
@FXML
    public void onBtnProceedClick() {
            btnProceed.setDisable(true);
          // other part of method.
}

FXML
<Button fx:id="btnProceed" maxWidth="1.7976931348623157E308" mnemonicParsing="false"
    onAction="#onBtnProceedClick" prefHeight="40.0" prefWidth="-1.0"
    styleClass="btnProceed" text="" GridPane.columnIndex="1"
    GridPane.rowIndex="0"
/>

A: The event has a getClickCount(). You can add a check to say if getClickCount() > 1 then do nothing and return.


text:
Q: changing Direction in Globalization asp.net MVC View

                        @Resources.VMSResource.VisitorName

                        @Html.EditorFor(model => model.VisitorName, new { htmlAttributes = new { @class = "form-control input-sm " } })
                        @Html.ValidationMessageFor(model => model.VisitorName, "", new { @class = "text-danger" })

                        @Resources.VMSResource.EmployeeID

                        @Html.EditorFor(model => model.EmployeeID, new { htmlAttributes = new { @class = "form-control input-sm" } })
                        @Html.ValidationMessageFor(model => model.EmployeeID, "", new { @class = "text-danger" })

I am implementing globalization in MVC.
For the Arabic language, I want the controls direction to RTL. I tried setting the direction to RTL for the DIV:

But it is only setting the direction within the textbox to RTL. Instead I want the controls (like Label, textbox) to move RTL.

A: To make a CSS that is designed for Left-To-Right languages to work with  Right-To-Left ones is not as easy as it seems. Just changing a parent element's direction to RTL does not mean that all children become RTL correctly. There are more to do. For example, you should change margin-right to margin-right or change the padding's values, etc.
In this way there are several tutorials that are based on different methods; all of them have pros and cons. To start I recommend you 3 Different Ways to RTL your CSS and RTLCSS
If you are using Bootstrap, the best choice, in my opinion, is https://github.com/morteza/bootstrap-rtl.

A:

Code sample taken from aspnet core
In detail, you can reach from the link below.
https://www.w3schools.com/tags/att_global_dir.asp

A: In Html use
<!DOCTYPE html>

<meta charset="utf-8">
...

this change almost everything to right for me except the labels so used this in my site.css file
.form-horizontal .control-label {
    float: right;
}


text:
Q: How to check how many of my friends like particular page on facebook using PHP SDK I'm workin on an app that would award its users points for each of their friends liking my page.
I need a way to check how many of user's friends like my page. I developed this piece of code to check each my friends for liking a particular page:
    $friends = $facebook->api('/me/friends'); //list my friends
    $time_start = microtime(true);
    echo "<pre>";
    $i = 0; //counter of likes
    $b = 0; //counter of request in single batch API request
    $batch_max = 50 // facebook allows max 50 requests in single batch API call
    $page_id = '187941397895831'; //example page ID, i'm checking how many of my    friends like this page
    $batch = array(); //array used for creating batch API request
    $data = array(); //array collecting all API requests results
    foreach ($friends['data'] as $friend) {
        $req = array(
            'method' => 'GET',
            'relative_url' => '/'.$friend['id'].'/likes'
        );
        $batch[] = json_encode($req);
        $b++;
        if ($b == 50) {
            $params = array(
                'batch' => '[' . implode(',',$batch) . ']'
            );
            $data[] = $facebook->api('/', 'POST', $params);
            $b = 0;
            $batch = array();
        }
    }
    $params = array(
        'batch' => '[' . implode(',',$batch) . ']'
    );
    $data[] = $facebook->api('/', 'POST', $params);
    foreach ($data as $data_set) { //iterate through results of each api request
        foreach ($data_set as $friend_likes) { //iterate through data of particular friend
            $likes_array = json_decode($friend_likes['body'], true);
            foreach ($likes_array['data'] as $single_like) { //iterate through all likes of a single friend
                if ($single_like['id'] == $page_id) { //if page id found in user's likes increase counter
                    $i++;
                }
            }
        }
    }
    $time_end = microtime(true);
    $time = $time_end - $time_start;
    echo $time."\n";
    echo $i;
    echo "</pre>";
    exit;

In final version I will not be checking my friends but friends of each of my users. My code executes in 14 seconds, if I had to iterate through, let's say, 100 users it'd be 1400 seconds, which is waaaay to long. Is there better way to do that? I'm newbie to facebook API, so I could miss something obvious :)

A: Ok, so here's the working piece of code. You need to know access token for each of users being checked. It executes in ~0.6 seconds instead of 14 seconds for previous code.
$queryResults = array();
$facebook->setAccessToken($user->getAccessToken());
$fql = "SELECT '' FROM page_fan WHERE page_id = 'xxxxxxxxxxxx' AND uid IN (SELECT uid2 FROM friend WHERE uid1 = '".$user->getFbId()."')";
$fql = urlencode($fql);

try {
    $queryResults = $facebook->api(
        '/fql?q='.$fql
    );
} catch (FacebookApiException $e) {
    $log->setMessage(print_r($e,true));
    $logMapper->save($log);
}

if (!empty($queryResults)) {
    $user->setPoints(count($queryResults['data']));
    $usersMapper->save($user);
}


text:
Q: Как учитывать неразрывный пробел в тексте в push-нотификейшнах от gmail? Всем привет.

*

*Отправляю письмо.
В письме html, например: "...Сумма доставки 1 000 долларов...."

*Письмо приходит получателю.
2.1. У получателя на телефоне отображается push-нотификейшн, где "1" и "000" на разных строках (не верно).
2.2. Но в браузере, в gmail неразрывный пробел отображается нормально ("1 000" не разбивается - все верно).
Может кто сталкивался с таким? Как решить проблему в пушах?


text:
Q: Vista locks up after ~10h. of activity I am experiencing a problem: Windows Vista completely freezes/locks up lately... It happened today twice - the mouse and keyboard stopped responding and I had to re-boot.
I checked the Application Events Log and I see these two errors:
Event filter with query "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA "Win32_Processor" AND TargetInstance.LoadPercentage > 99" could not be reactivated in namespace "//./root/CIMV2" because of error 0x80041003. Events cannot be delivered through this filter until the problem is corrected.
and then
The following boot-start or system-start driver(s) failed to load:
SASDIFSV
SASKUTIL

I checked Help online and it points to http://technet.microsoft.com/en-us/library/cc756390%28WS.10%29.aspx and suggests Updating the drivers.
I'm not sure why would I have problem with drivers and if so, how can I find out which drivers to update?
Can you please help me?

A: I used instructions from http://windowsitpro.com/article/articleid/45480/q-how-can-i-uninstall-the-microsoft-systems-management-server-sms-2003-advanced-client.html - the time will tell if it will help with the problem

A: Check Problem Reports and Solutions
Start -> Problem Reports and Solutions

See if Windows recognizes there is a problem, can tell you what is causing it, and maybe if there is a solution.


text:
Q: Java Excluding 0 from a Random number loop -What issues can come with my solution? Are there any issues with distribution or other problems that I'm oblivious to by doing this?
int exercise = number.nextInt(4);
int repetition = number.nextInt(30);

if(exercise == 0) {
  exercise = exercise + exercise + 1;

A: There is no need for that if clause. If you want to make sure that your "range" of random values doesn't start with 0 ... then simply do:
int exercise = number.nextInt(4) + 1

makes sure that exercise is in [1, 4] for example.


text:
Q: Multiple plots in multiplot window using R I have a data frame which has 12 variables in it, I wish to break the 12 variables into 3 separate plots using a single column of 3 rows.
My data frame is as follows:
> head(wideRawDF)
    Period.Start.Time DO0182U09A3 DO0182U09B3 DO0182U09C3 DO0182U21A1 DO0182U21A2 DO0182U21A3 DO0182U21B1 DO0182U21B2 DO0182U21B3
1 2017-01-20 16:30:00     -101.50     -103.37     -103.86     -104.78     -104.95     -105.33     -102.50      -99.43     -104.05
2 2017-01-20 16:45:00     -101.32     -102.75     -104.22     -104.51     -103.94     -105.29     -102.82     -101.99     -103.94
3 2017-01-20 17:00:00     -101.45     -103.30     -103.93     -104.70     -104.82     -105.13     -103.72     -103.95     -104.25
4 2017-01-20 17:15:00     -100.91      -95.92      -99.22     -103.83     -104.72     -105.19     -103.57     -101.36     -104.09
5 2017-01-20 17:30:00     -100.91     -103.04     -104.09     -102.15     -104.91     -105.18     -103.88     -104.09     -103.96
6 2017-01-20 17:45:00     -100.97     -103.67     -104.12     -105.07     -104.23      -97.48     -103.92     -103.89     -104.01
  DO0182U21C1 DO0182U21C2 DO0182U21C3
1     -104.51     -104.42     -105.17
2     -104.74     -104.65     -105.25
3     -105.02     -105.04     -105.32
4     -103.90     -102.95     -105.16
5     -104.75     -105.07     -105.23
6     -105.08     -105.14     -104.89

I have managed to plot the variables DO0182U09A3, DO0182U09B3 and DO0182U09C3 in three separate plots. I would like to add the "U21A1", "U21A2" and "U21A3" variables to the "U09A3" plot, similarly the "U21B1", "U21B2" and "U21B3" to "U09B3" plots and same again for the "C" plots.
I am a complete novice at R and have hacked a few lines together from here as to how to create multiple plots in a single window but am unsure as how to plot multiple variables in multiple windows, can anyone give a dig out?
If I could also colour all the "U09" lines as a single colour, e.g red, and the U21A1,U21B1 and U21C1 as green and similarly for U21A2,B2 and C2 as blue and again for U21A3,B3 and C3 as purple that would be fantastic.
#3 plots representing each of the sectors and technologies for DO0182
op <- par(no.readonly = TRUE)
par(oma=c(3,3,0,0),mar=c(3,3,2,2),mfrow =c(3,1))

plot(wideRawDF_NA$Period.Start.Time,wideRawDF$DO0182U09A3,ylab="",xlab="",type="l",col = "red", lwd = 1,  ylim = c(-107, -80),title(main = "Test"), sub = "subtitle")
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21A1 , col = 3)
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21A2 , col = 4)
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21A3 , col = "mediumpurple4")

plot(wideRawDF_NA$Period.Start.Time,wideRawDF$DO0182U09B3,ylab="",xlab="",type="l",col = "red", lwd = 1, ylim = c(-107, -70))
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21B1 , col = 3)
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21B2 , col = 4)
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21B3 , col = "mediumpurple4")

plot(wideRawDF_NA$Period.Start.Time,wideRawDF$DO0182U09C3,ylab="",xlab="",type="l",col = "red", lwd = 1, ylim = c(-107, -80))
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21C1 , col = 3)
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21C2 , col = 4)
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21C3 , col = "mediumpurple4")

cols <- rainbow(12)
mtext(text="Time",side=1,line=0,outer=TRUE)
mtext(text="Received Total Wideband Power (dBm)",side=2,line=0,outer=TRUE)

legend(x=1,y=1.7,legend=wideRawDF_NA[,2:13],col=unique(cols),pch=16,bty="n",xpd=NA)

par(old.par)

A: You are almost there. Just need to add the lines to your plot using lines() and select the colors. See ?lines and colors(). Also, you might want to use main() to add a main title to the individual plots. How about:
par(oma=c(3,3,0,0),mar=c(3,3,2,2),mfrow =c(3,1))

plot(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U09A3,ylab="",xlab="",type="l",col = "red", lwd = 1, ylim = c(-105, -95))
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21A1 , col = 3)
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21A2 , col = 4)
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21A3 , col = "mediumpurple4")

plot(wideRawDF_NA$Period.Start.Time,wideRawDF$DO0182U09B3,ylab="",xlab="",type="l",col = "red", lwd = 1, ylim = c(-105, -95))
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21B1 , col = 3)
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21B2 , col = 4)
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21B3 , col = "mediumpurple4")

plot(wideRawDF_NA$Period.Start.Time,wideRawDF$DO0182U09C3,ylab="",xlab="",type="l",col = "red", lwd = 1, ylim = c(-105, -95))
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21C1 , col = 3)
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21C2 , col = 4)
lines(wideRawDF_NA$Period.Start.Time,wideRawDF_NA$DO0182U21C3 , col = "mediumpurple4")


text:
Q: How can I rasterize a SpatialPolygonsDataFrame so that I can fill a shapefile with points? I have a chunk of R code that used to work but does not work anymore and I cannot find the issue. The purpose of the code is to fill a shapefile with regularly spaced points.
My shapefile can be accessed here: https://drive.google.com/drive/folders/1SAbuyIQHevK4fz-0w3TTqpEhz0wKLEII?usp=sharing
If I begin with loading my shapefile:
GUA = raster::shapefile('Guam3BufferPoly.shp')

Then I set a variable for the coordinate reference system for this SpatialPolygonDataFrame:
projGUA = crs(GUA)

Transform to planar crs
putm <- spTransform(GUA, projGUA)

Create a raster (this is where it doesn't work)
ext = extent(putm)
r <- raster(ext, res=500)

Rasterize the polygon and transform to points
r2 <- rasterize(putm, r)
pts <- rasterToPoints(r2, spatial=TRUE)

Transform the points to lon/lat and plot the results
pts_lonlat <- spTransform(pts, "+proj=longlat +datum=WGS84")
plot(pts_lonlat,pch='*')

The raster, r, is empty (breaking all the code downstream).
Please let me know if you can help me. And please be kind (this is my first time posting here and I apologize if I have not formatted my question correctly). Thank you!

A: Welcome!
Basically, it seems like you're working in a coordinate reference system not appropriate for the steps you execute.
library(raster)

GUA <- shapefile("Guam3BufferPoly.shp")

crs(GUA)
#> Coordinate Reference System:
#> Deprecated Proj.4 representation: +proj=longlat +datum=WGS84 +no_defs
#> WKT2 2019 representation:
#> GEOGCRS["GCS_unknown",
#>     DATUM["World Geodetic System 1984",
#>         ELLIPSOID["WGS 84",6378137,298.257223563,
#>             LENGTHUNIT["metre",1]],
#>         ID["EPSG",6326]],
#>     PRIMEM["Greenwich",0,
#>         ANGLEUNIT["Degree",0.0174532925199433]],
#>     CS[ellipsoidal,2],
#>         AXIS["longitude",east,
#>             ORDER[1],
#>             ANGLEUNIT["Degree",0.0174532925199433]],
#>         AXIS["latitude",north,
#>             ORDER[2],
#>             ANGLEUNIT["Degree",0.0174532925199433]]]

Seems like the crs provided Guam3BufferPoly.prj is not quite up to standard, but I'm not 100 % sure here. However, you're working with lat/lon coordinates on WGS 84. Hence, spTransform(GUA, projGUA) has absolutely no effect, since you're reprojecting your feature to the same crs again.
This leads to a follow-up issue: You're working in degrees as units and specify a raster of 500 units (here: degrees, not meters, as probably intended). And this is exactly what raster() does, even if it makes no sense:
ext <- extent(GUA)
ext
#> class      : Extent
#> xmin       : 144.5962
#> xmax       : 145
#> ymin       : 13.19925
#> ymax       : 13.70405

r <- raster(ext, res = 500)
r
#> class      : RasterLayer
#> dimensions : 1, 1, 1  (nrow, ncol, ncell)
#> resolution : 500, 500  (x, y)
#> extent     : 144.5962, 644.5962, -486.2959, 13.70405  (xmin, xmax, ymin, ymax)
#> crs        : NA

To solve this, you should use a projected coordinate reference system suitable for Guam. Not sure how good of a fit this is, you'll probably know better, but let me try WGS 84 / UTM 55 S (EPSG: 32755):
putm <- spTransform(GUA, CRS("+proj=utm +zone=55 +south +datum=WGS84 +units=m +no_defs"))

ext <- extent(putm)
ext
#> class      : Extent
#> xmin       : 239608.8
#> xmax       : 283618.4
#> ymin       : 11460271
#> ymax       : 11516045

r <- raster(ext, res = 500)
r
#> class      : RasterLayer
#> dimensions : 112, 88, 9856  (nrow, ncol, ncell)
#> resolution : 500, 500  (x, y)
#> extent     : 239608.8, 283608.8, 11460045, 11516045  (xmin, xmax, ymin, ymax)
#> crs        : NA

r2 <- rasterize(putm, r)
pts <- rasterToPoints(r2, spatial = TRUE)

pts_lonlat <- spTransform(pts, "+proj=longlat +datum=WGS84")
plot(pts_lonlat, pch='*')

Edit:
You can simplify the process using sf instead of raster and sp IMHO. Individual steps include data import, reprojection to a metric crs, grid creation covering the whole extent of your dataset and "spatial filtering" by intersecting your buffer with the grid centroids.
library(sf)

sf <- st_read("Guam3BufferPoly.shp", crs = "epsg:4326") |> st_transform("epsg:32755")
#> Reading layer `Guam3BufferPoly' from data source
#>   `Guam3BufferPoly.shp' using driver `ESRI Shapefile'
#> Simple feature collection with 1 feature and 1 field
#> Geometry type: POLYGON
#> Dimension:     XY
#> Bounding box:  xmin: 144.5962 ymin: 13.19925 xmax: 145 ymax: 13.70405
#> Geodetic CRS:  WGS 84

grid <- st_make_grid(sf, cellsize = 500, what = "centers") |> st_intersection(x = sf, y = _)

grid
#> Simple feature collection with 3839 features and 1 field
#> Geometry type: POINT
#> Dimension:     XY
#> Bounding box:  xmin: 239858.8 ymin: 11460520 xmax: 283358.8 ymax: 11516020
#> Projected CRS: WGS 84 / UTM zone 55S
#> First 10 features:
#>     ID                  geometry
#> 1    1 POINT (246358.8 11460521)
#> 1.1  1 POINT (246858.8 11460521)
#> 1.2  1 POINT (247358.8 11460521)
#> 1.3  1 POINT (247858.8 11460521)
#> 1.4  1 POINT (248358.8 11460521)
#> 1.5  1 POINT (248858.8 11460521)
#> 1.6  1 POINT (249358.8 11460521)
#> 1.7  1 POINT (249858.8 11460521)
#> 1.8  1 POINT (250358.8 11460521)
#> 1.9  1 POINT (250858.8 11460521)

Created on 2022-08-18 by the reprex package (v2.0.1)


text:
Q: Android vs iPhone color rendering I have used the same color code (#FF0000), but it seems, when compared side by side, Android is showing a slight variance to the red color used.
Is this because of the difference is hardware ?
How can I achieve the same colour standard on both of the devices ?

A: You will never be able to display the exact same colour on all devices.

*

*The screen might display colours in a different way (oled, TFT, IPS).

*The Colourprofile may differ per devices and thus affect the way the colour is shown.

Especially with Android device the colour will look different from device to device. On iOS it might look a bit different between retina and non-retina.


text:
Q: Change function in jQuery is firing twice on postback I am having an issue with the change function in jQuery 1.7.1 and postbacks. Basically I need to toggle the disabled attribute of buttons depending on whether an item is selected in the dropdown. In the code I have:
<input type="button" id="btnRed" value="show Red" disabled="disabled" class="spButton" />
<input type="button" id="btnBlue" value="show Blue"   disabled="disabled" class="spButton"/>
<input type="button" id="btnYellow" value="show Yellow" disabled="disabled"  class="spButton" />

I have my asp dropdown with autopostback set to true
<asp:DropDownList ID="selAccount" runat="server"
    onselectedindexchanged="selAccount_SelectedIndexChanged" AutoPostBack="true">
    <asp:ListItem Value="-1">select me</asp:ListItem>
    <asp:ListItem Value="234">234</asp:ListItem>
</asp:DropDownList>

and the jQuery:
 $(document).ready(function () {
    $("#selAccount").change(function () {
        var selValue = $(this).val();

        if (selValue == '-1') {
            $(".spButton").attr("disabled", "disabled");
        }
        else {
            $(".spButton").removeAttr("disabled");
        }
    });
 });

invariably, when postback occurs, the buttons remain disabled. I tested with an enabled button and it is firing twice. i have tried different approaches (bin, unbind) to no avail. I got around this issue with a hidden variable set on the SelectedIndexChanged in  code-behind and interrogating the hidden variable value in jQuery. is there an issue with the change method? is there a better way to do this? any insight would be appreciated. thanks,

A: If you are doing a postback each time the value is changed, then the page is reloaded and the changes made by jQuery are lost..
Either stop the auto-postback (set it to false), or if required change your code from the change event to the ready event..
$(function(){
    var selValue = $("#selAccount").val();

    if (selValue == '-1') {
        $(".spButton").attr("disabled", "disabled");
    }
    else {
        $(".spButton").removeAttr("disabled");
    }
});


text:
Q: How to concatenate the first 100 files in a directory? I had 4000 text files with unique filenames in a directory.
Is there any Linux command to concatenate only the 1-100 files.
cat 1.txt ... 100.txt > 1.100.txt
cat 101.txt ... 200.txt > 2.200.txt
.......
.......
cat 3901.txt ... 4000.txt > 40.4000.txt

Suggestions please.

A: With zsh:
files=( *(N.n) ) i=0
while (( $#files )) {
  () {cat -- $@ > $((++i)).$@[-1]} $files[1,100]
  files[1,100]=()
}

The n glob qualifier sorts the file names numerically, you can change it to Om to Order by modification time from oldest to newest.

A: You can use head to only pick 100 files.
For example:
cat $(ls -1 --sort=time | head -n 100) > 1.100.txt

(you can change the --sort to something else or remove it to sort by name)
If spaces or newlines might occur in filenames, you can't use ls but find -print0 is safe (uses null as the separator):
find . -type f -print0 | head -z -n 100 | xargs -0 cat > 1.100.txt

A: I'm going to caution you to be careful of using the output of ls in any Bash loop as a matter of habit because it can lull you into a false sense of security that it will always work. (Consider what happens with spaces in the filename...) It does work in this case - but there's a better (if somewhat more complicated) way to do it in general if the unique part of the filename is numeric and sequential.
Bash has built-in integer math functionality, and you can use the seq command with it to construct a loop to do what you want:
i=0
while :; do
    (( i += 1 ))
    (( i >= 4000 )) && break

    files_to_catenate=
    for i in $(seq $i $((i + 99))); do
        files_to_catenate+=( "${i}.txt")
    done
    cat "${files_to_catenate[@]}" > "$((i / 100)).${i}.txt"
done

A: This is a bit creepy but: You could run something along the lines of:
for a in {1..40}
do
  echo cat "{$((a*100-99))..$(($a*100))}.txt > $a.$(($a*100)).txt"
done

echoing
cat {1..100}.txt > 1.100.txt
cat {101..200}.txt > 2.200.txt
...
cat {3901..4000}.txt > 40.4000.txt

And if you like it: for a in.....done | bash


text:
Q: Can an Angular Component also be used as an Authentication Guard I'd like to move the CanActivate method out of my Auth.guard.ts to rather be in each pages component. The reason for this is that my auth guard file is getting cluttered and I think logically it makes sense for the permissions handling of a component to be placed in that components typescript file.
I tried the following but wasn't successful.
Here I added the implements CanActivate and added the canActivate(route,state) method to my component MyPageComponent
@Component({
    selector: 'app-my-page',
    templateUrl: './my-page.component.html',
    styleUrls: ['./my-page.component.scss']
})
export class MyPageComponent implements OnInit, CanActivate {
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        return true; // or return false
    }
    // all other code for the component below here
    constructor()...
    ngOnInit()...

then in the app-routing.module.ts file I added
{
    path: "My-Page",
    component: MyPageComponent,
    canActivate: [MyPageComponent]
},

I end up getting NullInjectorErrors.
So my question is, is this possible to move my canActivate method into my component? any other way to occomplish this?
Thanks for any help that's provided.

A: The answer is basically "no". A route guard is an @Injectable, not a @Component. If you have different authorization patterns for your different routes, I suggest you write multiple guards.
Angular has a set way of doing things. You can do things differently, but you'll be breaking Angular patterns, and that's generally a bad idea. Guards are for route protection, components are for showing stuff to the user.


text:
Q: Does Pub/Sub immediately resend a message in case of a non-success response? I have a Cloud Function subscribed to a Pub/Sub topic.
According to the docs, in case the Cloud Function returns a non-success response, it will resend the message:

The endpoint acknowledges the message by returning an HTTP success status code. A non-success response indicates that the message should be resent.

My question is: In case of a non-success response, the message will be immediately resent or Pub/Sub will respect the confirmation deadline to resend the message?
Update:
I think this question makes no sense, and I'll explain why.
Since you have no access to the Response object in Pub/Sub functions, there's no way to send a response code directly (I'm so not sure about that, so please correct me if I'm wrong).
Because of that, a non-success response can only be caused by:

*

*Timeout, which is based on the confirmation deadline, so in this case the confirmation deadline is obviously going to be respect.

*An error in the Cloud Function, and as Andrei Cusnir said, by default Pub/Sub won't even retry, so caring about the confirmation deadline makes no sense.

A: While investigating the Google Cloud Functions behavior, I found out that if the Cloud Function fails and responds with an error message it will not retry the operation. I have created a Cloud Function that would be triggered by the Pub/Sub event and then respond with an error message. The message was logged in the Stackdriver logging page and then the error was logged as well but the function never resent the message so it was never re-triggered. After that, I also tried responding with error code before actually reading the message of Pub/Sub and it still failed in the logs but never resent the message to actually retry its operation again.
This is expected behavior for the Google Cloud Function to protect themselves from running in an infinitive loop. If the Cloud Function based on the Pub/Sub topic event trigger, failed, it most probably will fail again during retrying. So if it keeps calling itself all the time it resends the message to the topic, it will be stuck in a loop generating billing costs as well.
To use the retry feature of a Google Cloud Function, you will have to enable it when deploying, using a flag. For more information, you can see at Retrying Background Functions documentation. Based on what you will set up in the configuration for the Google Cloud Function retrying strategy, it will trigger a retry.
However, the retry will be immediate and it will not respect the confirmation deadline.
UPDATE
When creating a Google Cloud Function with Pub/Sub event trigger, a subscription is created for the chosen topic, as you can see this in the topic's details page (Google Cloud Platform > Pub/Sub > Topics > [TOPIC_NAME]). The subscription is responsible for reading the message published in the topic and sending the ack back to the topic. A topic can have multiple subscriptions and it is sending each received message at least once to each subscription. As it is stated in Subscriber overview documentation.
In the same link, it is stated that A message is considered outstanding once it has been sent out for delivery and before a subscriber acknowledges it.. It is also stated that The subscriber has a configurable, limited amount of time -- known as the ackDeadline -- to acknowledge the outstanding message.. To elaborate further on how this system works, imagine having a TopicA then SubscriberA and SubscriberB subscribed to that topic. Now, a message is being sent to TopicA, so TopicA forwards the message to Subscriber-A and Subscriber-B and starts waiting for acknowledgments from both subscribers. Each subscriber has a different ack response time which is ackDeadline. If SubscirberA responds with ack, TopicA will keep waiting for Subscriber-B. If Subscriber-B will not send an ack within the time specified, then Topic-A will resend the message only to Subscriber-B.
Now, you have mentioned the The endpoint acknowledges the message by returning an HTTP success status code. A non-success response indicates that the message should be resent. part of the documentation. This part is talking about the subscriber's response and not the Google Cloud Function's response. Since the Google Cloud Function was called due to the message being published in the Topic, from that time the subscriber associated with that Cloud Function will send the ack message back to the topic. After that either the Google Cloud Function fails to process the message or not, it will not affect in any way the Pub/Sub topic as it only cares for the message being already delivered.
To elaborate further on the two points in your update section of the question:

*

*If Google Cloud Function will be executed, this means that the ack message was already been sent back to the topic. Imagine having a subscriber with 10 seconds set as ack response time and a Cloud Function that needs 5 minutes to time out. Obviously, when the 10 seconds of the subscriber has passed already, it will not wait 4 minutes and 50 seconds more for the Cloud Function to timeout. Therefore it means that the ack was already been sent by the subscriber as soon as the Google Cloud Function was called.

*The error that I have mentioned in my first response is the Google Cloud Function's error. So if your Cloud Function failed to process the received message, you will have to implement a retry method that will retry a specific amount of times and then will stop to avoid looping. However, the topic has already been informed that the message was delivered to the subscriber and therefore the acknowledgment was already been sent the time it started the Cloud Function execution.

A: Cloud Functions relies on Cloud Pub/Sub Push deliveries to trigger execution. The rate at which the system delivers concurrent messages continues to double until there is a delivery failure or the system reaches a quota or resource limit. For each delivery failure, the number of concurrent requests to the endpoint halves.
Cloud Pub/Sub, however, will not wait until the ack expiration deadline to resend the message if it was explicitly nacked by the non-ok status. Instead, it will temporarily back-off pushing messages. You can expect this delay to be in the order of a few seconds after a number of delivery failures.
You can read more about quotas and delivery rate here.


text:
Q: Power laws and deterministic systems I am facing the following question. It is well known that power laws arise in many situations in nature. They arise even in thats physical systems that are completely deterministic (e.g. sand piles). But power law is a probability distribution function and can be thought as generated from a stochastic variable. What is the relation between a power law distributed variable and a deterministic dynamical system? In other words why I can see statistical distribution in a deterministic system?

A: Umm. After giving it some thought I came to this conclusions.
As you point out, is clear why you can obtain statistical mechanics from stochastic variables. See Monte Carlo for example. All is deterministic each step but the choice of the random number that gives your ensemble.
Another way to put it is adding noise to your system. Like in a Langevin equation.
Yet another one would be Chaos. Is not really statistical Say you got the solution of the differential equation. Now you put an initial condition and operate + iterate. For diferent initial conditions you will get different realizations. Fractals are made this way.
In all the case above written you can encounter power-laws at critical points, or as an answer from the system telling you "hey, I'm rescalable!"
So my guess will be that stochastic behaviour is madness coming from tiny little details as: initial conditions, using random numbers to generate the distribution you are looking for or adding noise.

A: The answer to your question lies in understanding that probability and information are connected.  A statement about the probability of finding a system in a certain set of states (observing an event) is, in fact, a statement about your knowledge about the system.
Even for perfectly deterministic events, we

*

*may not know the microscopic details that determine their occurance, or

*we do not wish to inspect these details -- it may be tedious, or we may want to generalize.

*And there is also the possibility that cannot make good use of this information, if the system is chaotic -- meaning that even very small errors rapidly become very important.

Naturally it is true that if we do know microscopic details, and the system is deterministic, there is no "probability distribution" -- or rather, it is a single spike or pulse placing 100% probability at the outcome we are certain we will observe.
Now, if we have a system that can have very many starting conditions, we may want to know how it is likely to behave when any starting condition is possible, subject to its own 'prior' probability distribution.  It may not be possible to exhaustively simulate the results for all possible starting conditions.  Besides, if you can get at it analytically, it may be much faster and does give you more insight too.
But why should it work, to apply stats to deterministic things?  Again, it is only a reflection of what we know and what we include in our reasoning.  Probability distributions are usually derived from combinatorial arguments -- by considering the number of ways that an event could occur -- and such combinatorial reasoning is valid for deterministic systems.

A: I don't think that anyone has answered your question yet ( this one "How a probabilistic behavior arise from a deterministic system? Or how happens that we pass from trajectories to frequencies densities?" )
If you can answer this question you have demonstrated that statistical mechanics and so thermodynamics derive from classical mechanics. As far as i know, no one actually have understood why synergetic properties, that is properties that derive from the collective behavior such as entropy, arise. All we can know is that particles "communicate informations" through collision.
The theoretical tool you need to use in order to point out this problem is the "H theorem". One of the consequences of this theorem is that the evolution of a system of many particle provide us a privileged verse of time. Let me explain better.
Also computer simulation based on classical mechanics fail (see Orben and Bellmans Physics Letters 24 page 620 1967). They collected a set of particles in a box and they simulate the evolution of each particle with the classical equation of motion: in this way they could trace position, momentum and the value of the H function. But then, they stopped the system and inverted all the vectors: from a classical point of view, that is following newton's laws, this would result in a "specular" motion. Inverting the system after 50 collisions resulted in a situation very similar to the beginning one. But after 100 collisions the value of the H function was lower.
The presence of probability in this description of a physical system is also a philosophical question. Probability is something that we assign to the system since we are ignorant of his exact behavior or it's a property of the system itself? There are proper books which talk about this and it's still an open question.


text:
Q: How can I determine the generic type argument for an interface used by a derived class Consider a vast set of properties that all implement various interfaces, among them being ICustomProperty<T>.
I need to find all distinct type arguments used for T.
Example:
AgeProp : ICustomProperty<double>
SizeProp : ICustomProperty<string>
NameProp : ICustomProperty<string>
GradeProp : ICustomProperty<int>
DetailProp:  ICustomProperty<IDetailValue>

As I result I would like a list containing the types for double, string, int, IDetailValue.
I've figured out this way, but I'm hoping there is a better way:
    public static IEnumerable<Type> GetDistinctGenericTypeArguments<TBase>(IEnumerable<Type> inputTypes)
    {
        foreach (var t in inputTypes)
        {
            var baseType = t.GetInterfaces()
                .FirstOrDefault(i =>
                    i.IsGenericType
                        &&
                    (i.GetGenericTypeDefinition() == typeof(ICustomProperty<>))
                );

            if (baseType == null) continue;

            yield return baseType.GenericTypeArguments[0];
        }
    }

    //Usage:
    var valueTypes = GetDistinctGenericTypeArguments(inputTypes).Distinct().ToList();

Specifically, I was wondering, if there is a better way than calling GetInterfaces().FirstOrDefault(...).
Is there?
Also, in the code above typeof(ICustomProperty<>) is hard-coded, because I cannot implement GetDistinctGenericTypeArguments<T>(...) and call GetDistinctGenericTypeArguments<ICustomProperty<>>(...), because the compiler then complains: Unexpected use of an unbound generic name.
Is there a way around that as well?


text:
Q: How do I avoid Windows abbreviating the account when setting which user a Service should Log On As? I am trying to set a Windows Service to "Log On" as a specific Windows user, using the Windows GUI. This should allow the service to authenticate as that user when connecting to Microsoft SQL Server.
However, when I provide the account name in this format <DOMAIN NAME>\<username> and click "Apply", the account name gets abbreviated as .\<username>.
As a result, it seems that the service is unable to authenticate with SQL Server, since SQL Server doesn't have a user with the name .\<username>. SQL Server expects the name to be <DOMAIN NAME>\<username>.
Is there a way to prevent the account name from being abbreviated like this?


text:
Q: Lein clean and re-download dependencies I'm working on setting up some password protected dependency repositories. I'd like to clear all dependency packages and re-download to make sure the package restore is working correctly.
How should I clear the lein package cache?

A: If there are no edge cases by additional plugins rm -rf ~/.m2/repository is the brute force version -- this removes all
deps ever downloaded by Leiningen (and also Maven and maybe others).
If you want to be very specific for a certain project, you can get the
list of all actual files by lein cp (Warning: this also contains your
source files!  So you usually want the ones in ~/.m2/repository.  Of
course you use version control and have backups and therefor no problem
here...).  From the list of lein cp you would at least want to remove
the dirname portion to kill the version, or go up two for the whole
artifact.

A: Adding to the previous answer, you can list the individual directories under ~/.m2.  For example:
~/expr/demo > d ~/.m2/repository/cl[jo]*
drwxr-xr-x  3 alan alan 4096 Jan  5  2017 /home/alan/.m2/repository/clj-aws-s3/
drwxr-xr-x  5 alan alan 4096 Nov  4 21:26 /home/alan/.m2/repository/clj-commons/
drwxr-xr-x  3 alan alan 4096 Mar 30  2018 /home/alan/.m2/repository/cljfmt/
drwxr-xr-x  3 alan alan 4096 Nov 15  2017 /home/alan/.m2/repository/clj-http/
drwxr-xr-x  3 alan alan 4096 Nov 15  2017 /home/alan/.m2/repository/clj-http-lite/
drwxr-xr-x  3 alan alan 4096 Sep 17  2018 /home/alan/.m2/repository/clj-jdbcutil/
drwxr-xr-x  3 alan alan 4096 Nov 18  2017 /home/alan/.m2/repository/clj-jgit/
drwxr-xr-x  3 alan alan 4096 Sep 17  2018 /home/alan/.m2/repository/clj-liquibase/
drwxr-xr-x  3 alan alan 4096 Jun 19  2018 /home/alan/.m2/repository/clj-logging-config/
drwxr-xr-x  3 alan alan 4096 Sep 17  2018 /home/alan/.m2/repository/clj-miscutil/
drwxr-xr-x  3 alan alan 4096 Apr 25  2020 /home/alan/.m2/repository/clj-python/
drwxr-xr-x  3 alan alan 4096 Apr  1  2018 /home/alan/.m2/repository/cljs-ajax/
drwxr-xr-x  3 alan alan 4096 Mar 13  2018 /home/alan/.m2/repository/cljsbuild/
drwxr-xr-x  3 alan alan 4096 Apr 20  2019 /home/alan/.m2/repository/cljs-commons/
drwxr-xr-x  3 alan alan 4096 Sep 17  2018 /home/alan/.m2/repository/cljs-http/
drwxr-xr-x 17 alan alan 4096 Jan 28 10:25 /home/alan/.m2/repository/cljsjs/
drwxr-xr-x  3 alan alan 4096 Dec 18  2019 /home/alan/.m2/repository/cljs-log/
drwxr-xr-x  3 alan alan 4096 Jan 25  2017 /home/alan/.m2/repository/clj-stacktrace/
drwxr-xr-x  3 alan alan 4096 Mar 30  2018 /home/alan/.m2/repository/cljs-tooling/
drwxr-xr-x  4 alan alan 4096 Mar 25  2019 /home/alan/.m2/repository/clj-time/
drwxr-xr-x  3 alan alan 4096 Jan  5  2017 /home/alan/.m2/repository/clj-tuple/
drwxr-xr-x  3 alan alan 4096 Nov 18  2017 /home/alan/.m2/repository/clj-yaml/
drwxr-xr-x  4 alan alan 4096 Jul 19  2018 /home/alan/.m2/repository/clojure/
drwxr-xr-x  3 alan alan 4096 Jan  5  2017 /home/alan/.m2/repository/clojure-complete/
drwxr-xr-x  3 alan alan 4096 Jan  5  2017 /home/alan/.m2/repository/clojure-csv/

You can then use rm -rf on a specific subset that you wish to test (i.e. force re-download).


text:
Q: Accessing CSS3 media queries from Javascript Now, finally after 12 years, when all the world is hopping into CSS3 media query and responsive design bandwagon a problem remains.
How one can know from Javascript which media queries are

*

*present in HTML code: this should be simple element traversing, but are there smarter ways?

*effective (query evaluates to true)
... so you can add special code paths to support mobile, tablets, etc. in Javascript code? Eventually one could write function isMobile() and use it as a flag for certain actions specific to small screen estate.

A: It is possible to have a specific object in your page that gets a known style from your CSS for each media query of interest.  You can then read that style off the object with getComputedStyle() and see what was assigned to it and that would tell you which media query had precedence.


text:
Q: Can someone explain how the follwoing code calls football() method and when i run this script it get "football" as the result? <?php
    class container{
        protected $bindings = [];
        public function bind($name, callable $resolver){
            $this->bindings[$name] = $resolver;
        }

        public function make($name){
            //calls football() method , there is no football() method
            return $this->bindings[$name]();
        }
    }

    $container = new container;
    $container->bind('Game', function(){
        return 'football';
    });

    print_r($container->make('Game'));

the code calls football() method, and returns  " football " as a result when i runs it . How does it run the football() method which does not exist ?


text:
Q: pointwise convergence and $L^1$ norm-boundedness implies what...? I have the following questions:
Suppose that $\mu$ is a probability measure on $R^d$, and that $f_n \to f$ a.s., and $\sup_n \int|f_n|d\mu \le C$ for some $C>0$. What can we deduce? For example: (it is ok to take some subsequence if necessary)

*

*$\int |f_n - f |d\mu \searrow 0$?    If not, then

*$\int f_n d\mu \to \int f d\mu$? Still not, then

*$\liminf_n \int f_n d\mu \ge \int f d\mu$? Still not, then

*$\limsup_n \int f_n d\mu \ge \int f d\mu$?

or  is nothing above true?

A: *

*and 2. do not hold when $d=1$ and $\mu$ is the Lebesgue measure restricted to the unit interval. Indeed, let $f_n:=n \mathbf 1_{(0,1/n)}$. Then $ \int \left|f_n\right| \mathrm d\mu=\int f_n \mathrm d\mu=1$ and $f_n \to 0$ almost everywhere. 3. holds by Fatou's lemma if the functions are non-negative. If not,, then take $f_n:= -n \mathbf 1_{(0,1/n)}$ to show that 4. does not hold.


text:
Q: Suggest Box options for relation I have two tables, Application and Client. Application has One Client, Client can have many Applications. I want to use a suggest box to select the client in an application form.
I got it to work with "Suggest Box Query Options" but that only uses startsWith. I want to be able to get suggestions for any word in a string, not just the first one. If I set the "Options" to a string list it does have the desired behavior.
My problem is I don't know how to pick the "Value". I can't pick the foreign key field (Created from adding relation) because it takes a record not a string. And I don't know if I can use a list of relations for the option.