text:
Q: Hi. I am working on a django project. I have a regisration page and I want to include email address verification to it My registration page accepts username, email and password. I want to include email address verification to it. A link that will be send to the user's email id and then after they verify,the registration process completes.
            signup.html

        {% extends 'fir/base_visitor.html' %}
        {% block title %}Sign Up{% endblock %}
        {% block signup_active %}active{% endblock %}

        {% block body %}

Sign up for an Account

                            {% if error_message %}

{{ error_message }}

                            {% endif %}
                            <form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
                                {% csrf_token %}
                                {% include 'fir/form_template.html' %}

                                        <button type="submit" class="btn btn-success">Submit</button>

                            </form>

                            Already have an account? Click here to sign in.

        {% endblock %}

            views.py

def signup(request):
            form = UserForm(request.POST or None)
            if form.is_valid():
                user = form.save(commit=False)
                username = form.cleaned_data['username']
                password = form.cleaned_data['password']
                user.set_password(password)
                user.save()
                user = authenticate(username=username, password=password)
                if user is not None:
                    if user.is_active:
                        login(request, user)
                        evidences = Evidence.objects.filter(user=request.user)
                        return render(request, 'fir/index.html', {'evidences': evidences})
            context = {
                "form": form,
            }
            return render(request, 'fir/signup.html', context)

        This is for activation and I also have used tokens.

def activate(request, uidb64, token):
            try:
                uid = force_text(urlsafe_base64_decode(uidb64))
                user = User.objects.get(pk=uid)
            except(TypeError, ValueError, OverflowError, User.DoesNotExist):
                user = None
            if user is not None and account_activation_token.check_token(user, token):
                user.is_active = True
                user.save()
                login(request, user)
                return HttpResponse('Thank you for your email confirmation. Now you can login to your account.')
            else:
                return HttpResponse('Activation link is invalid!')

I have also included acc_active_email.html and acc_active_sent.html to my templates. Now,in my registration part in views.py, how do I edit my code to add these lines of code?
  current_site = get_current_site(request)
                    message = render_to_string('acc_active_email.html', {
                        'user':user, 'domain':current_site.domain,
                        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                        'token': account_activation_token.make_token(user),
                    })
                    # Sending activation link in terminal
                    # user.email_user(subject, message)
                    mail_subject = 'Activate your blog account.'
                    to_email = form.cleaned_data.get('email')
                    email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
                    return HttpResponse('Please confirm your email address to complete the registration.')

And,I have also included the email tls thing in settings.py.Please do help me with it. Thank you.And, everything is properly added to urls.py as well.

A: class SomeModel(models.Model):
    myvariable = model.IntegerField(validators=[MinValueValidator(18)])

I would assume you are making validation checks in the form also, before the data is ever submitted.


text:
Q: How to set permissions when uploading to Amazon S3? I'd like to set permissions for the files I'm uploading to S3 to be "Read" for All users, but can't find the way to use AWSS3PutObjectRequest grantRead neither AWSS3Permission AWSS3PermissionRead.
Any suggestion how to solve the problem?
Here's my code:
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest.body = NSURL(fileURLWithPath: filePath)
uploadRequest.key = fileName
uploadRequest.bucket = S3BucketName
uploadRequest.grantFullControl = "All users" // I think here's an error
self.upload(uploadRequest)

When I comment out the line uploadRequest.grantFullControl = "All users" the file gets uploaded, but the privilege for All users is set to None. I think the problem is in the penultimate line in the above code. When the line is not commented out I get this error:
upload() failed: [Error Domain=com.amazonaws.AWSS3ErrorDomain Code=0 "The operation couldn't be completed. (com.amazonaws.AWSS3ErrorDomain error 0.)" UserInfo=0x191a5bc0 {HostId=xxx+xxxxxxx/14=, ArgumentValue=All users, Message=Argument format not recognized, ArgumentName=x-amz-grant-full-control, Code=InvalidArgument, RequestId=xxxx}]
EDIT: The code above actually tries to grant full control permissions but the core problem is the same. Also I've added an image showing privileges for uploaded file:

A: I've found a solution:
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest.body = NSURL(fileURLWithPath: filePath)
uploadRequest.key = fileName
uploadRequest.bucket = S3BucketName
uploadRequest.ACL = AWSS3ObjectCannedACL.PublicRead  // there was the error
self.upload(uploadRequest)

More details at: https://forums.aws.amazon.com/thread.jspa?threadID=109840

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display each element of an array with different timeout delay and each delay time being a value inside each element in react Every element of the array should be displayed for some time and the time for which each element is displayed should be determined by a value in each element.
let array=[{display:"a",time:10},{display:"b",time:15},{display:"c",time:22}]
class App extends React.Component{
  state={stateDisplay:"",
        stateTime:""
        }
         componentWillMount(){
            var i=0;
              let handle=setInterval(()=>{
              var element=  array[i]
              this.setState({
                stateDisplay:element.display,
                stateTime:element.time,
              })
               i=i+1;

               if(i===array.length){
                 clearInterval(handle)
               }

            },10000)

            }
render(){
return(
<div> {this.state.stateDisplay} </div>
)}}

i have done something like this but using setinterval the delay can only be set for a constant time,here 10s.
I want the first element to display for 10s and then the next element for 15s, third for 22s which is the time value for each element of the array.
I know i cant do that using setinterval is there a way to do this using Settimeout?

A: This was almost like a little challenge, heres what i managed to come up with, its in typescript, if you need js, just remove interfaces and type annotations
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable prettier/prettier */
/* eslint-disable no-shadow */
/* eslint-disable no-console */
import React, { FC, useState, useEffect, useCallback } from 'react';
import { View, Button, Text } from 'react-native';

interface Data {
  duration: number;
  bgColor: string;
}

const dataArr: Data[] = [
  { duration: 3, bgColor: 'tomato' },
  { duration: 6, bgColor: 'skyblue' },
  { duration: 9, bgColor: 'gray' },
];

const Parent = () => {
  const [currentIdx, setCurrentIdx] = useState<number>(0);
  const [elementData, setElementData] = useState<Data>(dataArr[currentIdx]);

  useEffect(() => {
    console.log('idx', currentIdx);
    if (currentIdx > dataArr.length) return;
    setElementData({ ...dataArr[currentIdx] });
  }, [currentIdx]);

  const pushNext = () => {
    setCurrentIdx(currentIdx + 1);
  };

  const handleRestart = () => {
    setCurrentIdx(0);
    setElementData({ ...dataArr[0] });
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Timer
        data={elementData}
        onCountDownComplete={pushNext}
        restart={handleRestart}
      />
    </View>
  );
};

interface Props {
  data: Data;
  onCountDownComplete: () => void;
  restart: () => void;
}

const Timer: FC<Props> = ({ data, onCountDownComplete, restart }) => {
  const [seconds, setSeconds] = useState<number>(data.duration);

  // update on data change
  useEffect(() => {
    setSeconds(data.duration);
  }, [data]);

  const callback = useCallback(() => {
    onCountDownComplete();
  }, [onCountDownComplete]);

  useEffect(() => {
    let interval: any = null;
    if (seconds > -1) {
      interval = setInterval(() => {
        if (seconds - 1 === -1) {
          callback();
        } else {
          setSeconds(seconds - 1);
        }
      }, 1000);
    } else {
      return;
    }
    return () => {
      clearInterval(interval);
    };
  }, [seconds, callback]);

  return (
    <View
      style={{ backgroundColor: data.bgColor, padding: 16, borderRadius: 10 }}
    >
      <Text style={{ marginBottom: 24 }}>{seconds}</Text>
      <Button title="restart" onPress={restart} />
    </View>
  );
};


text:
Q: How do i fix error at f letter and so on at rot13 c program i'm new at programming. i'm currently making a rot13 program in c, i tried using "for","if" and it works untill letter f it shows question mark. if i were to write letters from a-z the encrypted results is like : nopqrstuvwxyzabcde???????? . i tried to change the addition/substraction values, the variable, the int. it didn't came out well.
#include<stdio.h>

int main()
{
    char message[100], ch;
    int i;
    printf("Enter a message to encrypt: ");
    gets(message);
    for(i = 0; message[i] != '\0'; ++i){
        ch = message[i];
        if(ch >= 'a' && ch <= 'z'){
            ch = ch + 13;
            if(ch > 'z'){
                ch = ch - 26;
            }
            message[i] = ch;
        }
        else if(ch >= 'A' && ch <= 'Z'){
            ch = ch + 13;
            if(ch > 'Z'){
                ch = ch - 26;
            }
            message[i] = ch;
        }
    }
    printf("Encrypted message: %s", message);
    return 0;
}

A: Your code is almost okay. But there is a catch in ASCII. As we know Ascii contains both ASCII (0-127) characters and extended ASCII (128-255) characters. Ascii uses 7 bit for representation whereas extended ASCII uses 8 bit. So, when the value of ch + 13 exceeds 127 and you are subtracting 26 from it, it's basically producing a negative decimal number.
You can check by print like this printf("%d", ch);.
And there is no ascii character associated with negative decimal numbers. That's why it's producing garbage values. You should check before assigning ch = ch + 13.
Check the below code for reference.
#include<stdio.h>

int main()
{
    char message[100], ch;
    int i;
    printf("Enter a message to encrypt: ");
    scanf("%s", message);
    for(i = 0; message[i] != '\0'; ++i){
        ch = message[i];
        if(ch >= 'a' && ch <= 'z'){
            if (ch + 13 > 'z') {
                ch = ch - 13;
            }
            else ch = ch + 13;

            message[i] = ch;
        }
        else if(ch >= 'A' && ch <= 'Z'){
            if (ch + 13 > 'Z') {
                ch = ch - 13;
            }
            else ch = ch + 13;
            message[i] = ch;
        }
    }
    printf("Encrypted message: %s", message);
    return 0;
}

A: Most likely char is signed on your machine. So ch = ch + 13 end up being negative in some cases (e.g. when ch is z). Consequently if(ch > 'z'){ doesn't work as you expect.
Try
int main(void) {
    char ch = 'z';
    ch = ch + 13;
    if (ch > 'z')
    {
        puts("Larger");
    }
    else
    {
        puts("Less or equal");
    }
    printf("ch value is %d\n", ch);
    return 0;
}

This may print:
Less or equal
ch value is -121

Use an usigned type or an int for the calculation.


text:
Q: How to disable secure_file_priv in MySQL 8.0 in windows 10 machine? I tried to load csv file into table using
load  data infile 'C:\\a.csv' into table errorClick columns terminated by ',' lines terminated by ',\r\n' ignore 1 lines;

I am using sql version 8.0 It gave error:
Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement    0.000 sec

I ran this statement:
SHOW VARIABLES LIKE "secure_file_priv";

The result is
secure_file_priv    C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\

Then i tried
 Set secure_file_priv="";

It gave result
Error Code: 1238. Variable 'secure_file_priv' is a read only variable   0.047 sec

Then I tried to find my.ini in my windows 10 machine at location
C:\ProgramData\MySQL\MySQL Server 8.0\

I did not find any my.ini file; Please help me resolve this error;

A: you can only change it in my.inio file and then restart he server
You find my.ini in a hidden folder

C:\ProgramData\MySQL\MySQL Server 8.0

There you find under the section

[mysqld]

secure-file-priv = ""

After the edit, you need to restart the server, so that the changes will take effect.


text:
Q: Commutative subspace lattice I have seen an article in which there is an algebra which was named CSL-algebra (Commutative Subspace Lattice). This algebra is about projection on Banach algebra? I couldn't find any good source to study about it? Do somebody know about it?

A: This article has useful information about CSL-algebras
IVAN G. TODOROV; Subspace Lattices, Reflexivity and Tensor Products, Irish Math. Soc. Bulletin 53 (2004), 57–67


text:
Q: How to avoid "ls: write error: Broken pipe" with php exec In PHP I am running this command:
exec ("ls -U ".$folder." |head -1000", $ls_u);

This command is inside a PHP file, run directly by PHP on the console and throws this error:
ls: write error: Broken pipe

What causes this error?  Or is using pipes in PHP exec not a good idea?

A: In Linux with PHP on the terminal, you can reproduce this error with this code:
main.php:
<?php
  $process = popen("ls", "r");
  pclose($process);
?>

Then running it like this on the terminal:
eric@dev ~ $ php main.php
ls: write error: Broken pipe

The error happens because you are running a command which returns data and you are not catching it, so it complains about a broken pipe.
I was able to fix it like this:
<?php
  $handle = popen('ls', 'r');
  $read = fread($handle, 2096);
  pclose($handle);
  echo $read;
?>

Then it works, printing:
eric@dev ~ $ php main.php
main.php
anotherfile.txt

Note, you'll have to stick the fread(...) in a loop if you want to get all the output from ls.

A: I believe there's a syntax error in the console command, and suggest escaping the arguments with escapeshellarg().
exec('ls -U '.escapeshellarg($folder).' | head -1000', $ls_u);


text:
Q: What number representation is the adjoint representation of the Monster? Given this list of representations of the Monster. How far along the list until we get to the adjoint representation that is the same size as the Monster group itself?
(This might be interesting because the modular J-functions coefficients is made up of the size of representations the Monster.)


text:
Q: How do I set a float without using an OGNL converter? I have a class that looks like this:
public class Foobar {
   private float value;
   public void setValue(float value) {
      this.value = value;
   }
}

I then have a webpage (Struts2) that passed in a variable foobar.value.
<input type="text" name="foobar.value" value="123.456">

I then get this error:
ognl.MethodFailedException: Method "setValue" failed for object Foobar@19d373d [java.lang.NoSuchMethodException: setValue([Ljava.lang.String;)]
    at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:823)

I found this website that talks about creating converters http://www.opensymphony.com/ognl/html/DeveloperGuide/typeConversion.html
Doesn't OGNL and Struts2 have support for setting a primitive float by default?

A: If you change value to Float (the Object), does that work?

A: OK, I figured it out. The above code DOES work. But this does NOT work.
 <input type="text" name="foobar.value" value="-123.456">

Apparently OGNL interprets the negative number as a String. I'm not sure how to deal with this without a converter. It's nice to know that it will handle positive float and Float natively.
I did some further research on this about found this bug. http://issues.apache.org/struts/browse/WW-2971
It's closed but the version 2.1.8 isn't in Maven and the latest version of Struts2 doesn't rely on it yet. :(
I think I'll be writing a converter for now.


text:
Q: What part of speech is "unless" in the following sentence?
Unless disciplined, a dog becomes a household pest.

Is the use of unless in this sentence correct? It sounds to my naive ear to be fine, but I always think of unless as a conjunction, which does not seem to be the case here. I looked up unless in an online dictionary and discovered that it can additionally be used as a preposition in the sense of "except for", but again that would not seem to apply to this sentence as disciplined is an adjective.  Since the sentence is taken from Strunk and White and sounds right to my ear, I am sure it is correct, so my main interest is to discover what the underlying construction is here.

A: In the sentence,

Unless disciplined, a dog becomes a household pest

unless is a conjunction*. This sentence is really a reduction of

Unless it is disciplined, a dog becomes a household pest.

The conjunctional function becomes clearer upon a rearrangement of the clauses:

A dog becomes a household pest, unless [it is] disciplined.

The most likely constructions a native speaker would use are the following:

*

*A dog becomes a household pest, unless it is disciplined.

*Unless it is disciplined, a dog becomes a household pest.

*Unless a dog is disciplined, it becomes a household pest.

*Unless disciplined, a dog becomes a household pest.

*I see how unless could be said to be used as a preposition:

A dog becomes a household pest unless disciplined.

(No comma before unless and disciplined becomes an adjective.) I doubt this is formal usage, though. Before the independent clause, however, I would always take unless as a conjunction.

A: Unless means "if not"; hence, the word "not" should not be introduced in the clause beginning with "unless." For example:

Unless you work hard, you will fail.


text:
Q: Global variable not defined in Javascript In my case why arr is not defined? I saw the error in jsfiddle's console log. Supposed it's a gobal variable so it can be access in any function scope?
http://jsfiddle.net/xgpqe4rv/3/
$(function() {

    autoSlide = setInterval(cycle(), 3000);

    arr = [{
            'logo': 'http://placehold.it/50&text=1'
        },

        {
            'logo': 'http://placehold.it/50&text=2'
        },

        {
            'logo': 'http://placehold.it/50&text=3'
        },

        {
            'logo': 'http://placehold.it/50&text=4'
        }

    ];

    $('img').attr('src', arr[0]['logo']);

    function cycle() {

        var i = 1;

        $('img').attr('src', arr[i]['logo']);

        if (i == 3) {

            i = 0;
        } else {
            i++;

        }
    };

    $('#right').click(function() {
        cycle();
    });
});

A: *

*You're not declaring your variables with var

*autoSlide = setInterval(cycle(), 3000); you are passing the return value of the function to the interval, whereas you want a function reference.
autoSlide = setInterval(cycle, 3000);
or
autoSlide = setInterval(function() { cycle() }, 3000);


text:
Q: Why does Service.providers(java.sql.Driver.class) can always get mysql's driver? p I'm testing Proxool connection pool now (the DB is mysql), and I find a very curious case, which is that the mysql's Driver can always be registered to DriverManager even though I don't explicitly invoke
Class.forName("com.mysql.jdbc.Driver")

while the Proxool's Driver cann't. And I look into the JDK code and find a clue, which is that
Service.providers(java.sql.Driver.class)

can get mysql's Driver while cann't get Proxools. This maybe the reason. And my question is why this method can automatically find mysql's driver?
The following is my testing code:
public static void main(String[] args) throws Exception{
   Iterator drivers = Service.providers(java.sql.Driver.class);
   while(it.hasNext()){
      System.out.println(it.next());
   }
}

and the result is:
sun.jdbc.odbc.JdbcOdbcDriver@31d520c4
com.mysql.jdbc.Driver@1f5a3d6b


text:
Q: Highlighting the elastic search giving the results only matched Working on Php and Elastic Search 6.5.2. For test scenario I used postman, When I apply Highlighting, Only the trimmed piece of content which has matched keyword sentence is displaying  when I added two or more fragments under the highlight. I Don't wan to trim the content at the elastic search level. For this I changed the number of fragments to zero and I got the expected output in the elastic search that its giving the whole content, butwhen I check the output in the php application the whole content is getting bold whenever the matched keyword existing in the url field.
Index:
PUT test/_doc/1
{
  "title":"Apply For the admissions graduate and undergraduate"
  "url":"https://someurl.com/admissions",
  "content": "Engineers play an important role in almost every aspect of modern life. As an engineer in the 21st century, you'll work in teams to develop ingenious ways to transform the world in which we live. Industrial engineers are in high demand in nearly every industry. Astounding innovations in semiconductor microelectronic engineering will continue to drive productivity and the economy by playing a key role in a wide range of technologies – information, communication, nanotechnology, defense, medicine, and energy.Admission into the microelectronic engineering program is competitive, but our admission process is a personal one. Each application is reviewed holistically for strength of academic preparation, performance on standardized tests, counselor recommendations, and your personal career interests. We seek applicants from a variety of geographical, social, cultural, economic, and ethnic backgrounds."
}

Query:
{
   "query":{
      "query_string":{
         "fields":[
            "content"
         ],
         "query":"admissions"
      }
   },
   "highlight":{
      "fields":{
         "title":{
            "pre_tags":[
               ""
            ],
            "post_tags":[
               ""
            ],
            "number_of_fragments":3            //changed to 0 earlier
         },
         "content":{
            "pre_tags":[
               ""
            ],
            "post_tags":[
               ""
            ],
            "fragment_size":150,
            "number_of_fragments":3           //changed to 0 earlier
         }
      }
   }
}

Result:
"highlight": {
          "content": [
            "information, communication, nanotechnology, defense, medicine, and energy.Admission into the microelectronic engineering program is competitive, but our admission"
          ]
        }

A: After looking at the code you shared via comments. This issue is not in elasticsearch response.
This following line is causing the issue:
<?php echo  substr($r['highlight']['content'][0],0,300); ?>
Due to this one of the result is missing closing  tag as you are taking only first 300 characters.
If you notice you can see, one of the highlighting content in your html has the following:
Tourism Management Curriculum Capstone/Exam/Thesis Options Admissi

As you can see closing  tag is missing for Admissi and hence everything after this is in bold.
Solution to this could be not using substring.


text:
Q: django: Call to remote service kills python I'm writing a django app that communicates with remote service (on my VPN but not hosted locally). I can successfully communicate with the service via the django shell but when I try to call the exact same function, posting the information from a webform, the development server dies.
I would have thought the shell and the development server would behave exactly the same way. The only thing I could think of was that the shell might be more 'patient', waiting for a response?
The communication happens via protocol buffers.
Help!

A: The developpement server is single-threaded so if you open another connection it hangs the server.
You could try for dev purposes : http://github.com/jaylett/django_concurrent_test_server
works very well for me
Or use a real configuration, apache+wsgi for example


text:
Q: How can I go back a directory in an "ftp_put" file path? I have a page where users of my website can change the info they have entered in for their account (e.g. real name, email, and avatar). What I want to do is let them change their avatar. It's all been goin' good except for the last part of it all: uploading the file. First I found the file, then resized it, and now I'm tryin' to upload it to my server via the "ftp_put" method in PHP.
The script I'm using is in (from my site's root directory) the folder "/scripts/newavatar.php". The folder I'm trying to upload into is "/avatars/". My problem is that FTP won't recognize that I've entered in "public_html/avatars" or "../avatars/", or it shouldn't or something. I don't know how to explain it any better. Can someone please help me?

A: You should use full FTP path to "avatars" folder.
If it is located in FTP root directory, try:
ftp_put($conn_id, "/avatars/" . $file_name, $local_file_name, FTP_BINARY);

A: The image file is already on your server so you don't need to use FTP methods.
Here's how you do it

*

*Upload file via form

*Load file into imagecreatefrompng() or similar via the $_FILES['field_name']['tmp_name'] path

*Make changes / resize

*Save the file to its final destination using imagepng($imageResource, '/path/to/avatars/image-file-name.png')
Update
I'm guessing you're having a bit of trouble understanding server-side paths. It's probably easiest for you to use a path relative to your scripts/newavatar.php file when saving the final image. To do so, use the special __FILE__ constant, eg
// save final image
imagepng($imageResource, dirname(dirname(__FILE__)) . '/avatars/' . $imageFilename);

A: You should pay attention to difference between remote_file and local_file.
local_file can be any relative path and directory but remote_file is a file name in remote server and it's better to not use relative path and only use the file name.
For example:
remote_file = "1532574888.exe";
local_file = "../../files/cleaned/1532574888.exe";
ftp_put($ftp_conn, $remote_file, $local_file, FTP_ASCII);

It works for me.


text:
Q: Is there a reason that `Functor` is not a superclass of `Category`? It seems you can simply declare:
import qualified Control.Category as Cat
instance Cat.Category q => Functor (q r) where
     fmap = (Cat..)

Is there anything speaking against this?

A: That instance would overlap with many other useful instances, e.g. one could no longer add
instance Functor (State s) where ...

for the State s monad.


text:
Q: how to return a factory object after all ajax calls are done I have a factory which returns an object with several properties. But each property value is computed by ajax call and in some cases I do promise chaining in order to set a property value. Before I return the object how do i make sure all ajax calls are done such that property values are assigned
My factory looks something like this
app.factory('Resource', ['$http', '$q', function ($http, $q) {
    var Resource = {
    masterDB: null,
    replicaDB: null,
    replicaCluster: null,
    masterForests: null,
    forestHosts:{}
};

    Resource.setMasterDB = function (dbname) {
        console.log('inside setMasterDB', dbname);
        this.masterDB = dbname;
    };

    Resource.getResources = function (dbname) {
        var  url = '/manage/v2/databases/'+ dbname + '?format=json';
        $http.get(url).then(function (response) {
            Resource.masterForests = getAttachedForests(response.data);
            console.warn('Master Forests = ', Resource.masterForests);
            return response;
        }).then(function (response) {
            Resource.replicaCluster = getReplicaClusters(response.data);
            console.warn('Replica Cluster = ',Resource.replicaCluster);
        }).then(function () {
            console.log('final then',  Resource.masterForests);
            var reqs = function () {
                var arr = [];
                angular.forEach(Resource.masterForests, function(forestName){
                    arr.push($http.get('/manage/v2/forests/'+ forestName + '?format=json'));
                });
                return arr;
            }.call();

                console.log('reqs = ', reqs);

            $q.all(reqs).then(function (results) {
                console.warn(results);
                angular.forEach(results, function(result){
                    console.log('HOST', getForestHost(result.data));
                });
                return results;
            });
        });

    };
    console.warn('RESOURCES: ', JSON.stringify(Resource));
    return Resource;

}]);

A: We had scenario where the datas have to be updated from two different ajax responses, we have followed the below approach.
For Example:
function functionname()
{

var First_Response = $http.$get("/test1/test2/...");
var Second_Response = $http.$get("test3/test4/...");
return $q.all([First_Response,Second_Response]); // This function will return only when all the ajax responses are obtained.
}

In the below url:
https://docs.angularjs.org/api/ng/service/$q
It is mentioned that $q.all will return result only when all the requests mentioned in the array gets the ajax response.
We tried this approach and it worked for us. Hopefully it will give some pointers

A: Here's the working code
 getResources: function (dbname) {
            var  url = '/manage/v2/databases/'+ dbname + '?format=json';
            return $http.get(url).then(function (response) {
                Resource.masterForests = getAttachedForests(response.data);
                Resource.appservers = getAttachedAppServers(response.data);
                Resource.replicaClusters = getReplicaClusters(response.data);
                console.warn('Master Forests = ', Resource.masterForests);
                return Resource.replicaClusters;
            }).then(function(replicaClusters) {
                var clusterArr = [];
                angular.forEach(replicaClusters, function(cluster) {
                    clusterArr.push($http.get('/manage/v2/clusters/'+ cluster + '?format=json'));
                });
                return $q.all(clusterArr).then(function(results) {
                    angular.forEach(results, function(result) {
                        var cluster = result.data['foreign-cluster-default'].name;
                        var dbs = getReplicaDBs(result.data);
                        Resource.replicaDBs[cluster] = dbs;
                    });
                });
            }).then(function() {
                var forestarr = [];
                    angular.forEach(Resource.masterForests, function(forestName){
                        forestarr.push($http.get('/manage/v2/forests/'+ forestName + '?format=json'));
                    });
                return $q.all(forestarr).then(function (results) {
                    angular.forEach(results, function(result){
                        var host = getForestHost(result.data);
                        var forest = result.data['forest-default'].name;
                        Resource.forestHosts.push(host);
                        // group forest by hosts
                        groupForestsByHost(Resource, host, forest);
                    });
                });
            });
        }

In controller
Resource.getResources($scope.db).then(function() {
     $scope.masterForests = Resource.masterForests;
     $scope.replicaClusters = Resource.replicaClusters;
     $scope.forestHosts = Resource.forestHosts;
     $scope.forestsOnHosts = Resource.forestsOnHosts;
     $scope.replicaDBs = Resource.replicaDBs;
     $scope.appservers = Resource.appservers;
 }


text:
Q: ROI labeller for training images for R-CNN image analysis I have a set of ground truth data images with multiple ROIs which I will use to train an R-CNN for image analysis.  To create the training set I need to manually identify and label the ROIs (yeah, won't that be fun).  What good applications can I use for this other than Matlab's Training Image Labeller?  Is there any app out there which would allow me to identify ROIs and then label them and output a file with the ROI coords and labels?  Output format doesn't matter but JSON would be ideal.
OR, if no such application exists outside Matlab, is there an application which could quickly / easily extract the ROIs into a separate image file which I could label?  When they created training datasets like CIFAR-10, what did they use?


text:
Q: How to use java.lang.reflect.Method in udf? I want to get a method externally by reflection and then call this method in udf
I get the method through reflection and register it as udf and store the udf in the hashMap
def initNodeClass(node: NodeDto, initParam:util.HashMap[String, String]): Unit = {
    val filePath = node.getArithmetic.getFilePath
    try {
      val classLoader = new URLClassLoader(Array[URL](new URL("file:" + filePath)),
        Thread.currentThread.getContextClassLoader)
      node.setCls(classLoader.loadClass("Arithmetic"))
      if (initParam == null || initParam.isEmpty) {
        node.setObject(node.getCls.newInstance)
      }
      else {
        val constructor = node.getCls.getDeclaredConstructor(classOf[util.Map[_, _]])
        node.setObject(constructor.newInstance(initParam))
      }
    } catch {
      case e: Exception =>
        e.printStackTrace()
    }
    val inputConfig = node.getInputConfig
    var method:Method = null
    if (inputConfig == null || inputConfig.isEmpty){
      method = node.getCls.getDeclaredMethod("result")
    } else {
      method = node.getCls.getDeclaredMethod("result", classOf[util.Map[_,_]])
    }

    val invokeNodeMethodUdf = udf((input:scala.collection.immutable.Map[String, Array[String]]) => {
      var res = new util.HashMap[String, Array[Double]];
      if (input == null || input.isEmpty) {
        res =  method.invoke(node.getObject).asInstanceOf;
      }
      else {
        res = method.invoke(node.getObject, input).asInstanceOf;
      }
      res;
    })

    udfMap.put(node.getName, invokeNodeMethodUdf)
  }

When I want to call the method obtained by reflection in udf and show result, it is ok.
But if I want to call the method obtained by reflection in udf, and then do some Transformation operations, and then shoe result, got:
org.apache.spark.SparkException: Task not serializable
        at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:416)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:406)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:163)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2326)
    at org.apache.spark.rdd.RDD.$anonfun$mapPartitionsWithIndex$1(RDD.scala:872)
........

Caused by: java.io.NotSerializableException: java.lang.reflect.Method
Serialization stack:
    - object not serializable (class: java.lang.reflect.Method, value: public java.util.Map Arithmetic.result(java.util.Map))
    - field (class: scala.runtime.ObjectRef, name: elem, type: class java.lang.Object)
    - object (class scala.runtime.ObjectRef, public java.util.Map Arithmetic.result(java.util.Map))
    - element of array (index: 0)
    - array (class [Ljava.lang.Object;, size 2)
    - field (class: java.lang.invoke.SerializedLambda, name: capturedArgs, type: class [Ljava.lang.Object;)
    - object (class java.lang.invoke.SerializedLambda, SerializedLambda[capturingClass=class com.sia.spark.Engine.TaskEngine, functionalInterfaceMethod=scala/Function1.apply:(Ljava/lang/Object;)Ljava/lang/Object;, implementation=invokeStatic com/sia/spark/Engine/TaskEngine.$anonfun$initNodeClass$1:(Lscala/runtime/ObjectRef;Lcom/sia/spark/dto/NodeDto;Lscala/collection/immutable/Map;)Lscala/collection/immutable/Map;, instantiatedMethodType=(Lscala/collection/immutable/Map;)Lscala/collection/immutable/Map;, numCaptured=2])
    - writeReplace data (class: java.lang.invoke.SerializedLambda)
    - object (class com.sia.spark.Engine.TaskEngine$$Lambda$1691/206707321, com.sia.spark.Engine.TaskEngine$$Lambda$1691/206707321@3ee910d0)
    - element of array (index: 0)


text:
Q: Exploratory factor analysis of turtle data I'm learning a bit about exploratory factor analysis working with some datasets, but some doubts came in mind.
I'm using this data to practice turtle data. I have two groups of turtles: male and female and measures of 3 variables length, width and height.
The output of factor model using R is
  Uniquenesses:
        length     width     height
    0.017 0.026 0.053

    Loadings:
      Factor1
    length 0.991
    width 0.987
    height 0.973

               Factor1
SS loadings      2.904
Proportion Var   0.968

The degrees of freedom for the model is 0 and the fit was 0

The above result, shows that a single factor is good enough to describe the covariance structure of the data. Then I calculated the factor scores using the regression option and did a plot of it

(1) Clearly there are differences between males and females, but what conclusions could I draw from the scores?
(2) In this case I have a single factor and can't do a biplot, how I could check what variable is the one that most differentiates males and females?
(3) I used some rotation (varimax and promax) and results were the same that I get without rotation. Is it because I have a single factor?
(4) Is there any difference between use Regression Scores and Barlett scores?

A: That's four questions.  I will take them one at a time:

(1) Clearly there are differences between males and females, but what
  conclusions could I draw from the scores?

First, if you are interested in differences between males and females, I'd look at a parallel boxplot and a t-test. However, one conclusion is clear: While both males and females can have negative or small positive scores, only males have scores over about 1.  Since the variables all have positive loadings, this means that large turtles are all male.

(2) In this case I have a single factor and can't do a biplot, how I
  could check what variable is the one that most differentiates males
  and females?

With length, width and height, this is unlikely to be fruitful because the 3 variables are likely to be highly correlated. I haven't checked the correlations, but you could easily do so.  If you really wanted to do this, you could run 3 t-tests comparing males and females on the 3 variables and seeing which had the largest t.

(3) I used some rotation (varimax and promax) and results were the
  same that I get without rotation. Is it because I have a single
  factor?

Yes.  With only one factor, there is nothing to rotate.

(4) Is there any difference between use Regression Scores and Barlett
  scores?

I don't know.


text:
Q: Proper way to populate dropdown from foreign key in Laravel 5.3 can anyone help me in solving this problem? I've been stuck for days with the error htmlspecialchars() expects parameter 1 to be string, array given in Laravel 5.3.
Here is my controller
public function create()
    {
      $categories = DB::table('categories')->pluck('name', 'id');
      foreach($categories as $category)
      {
          echo $category;
      }
      return view('admin.processor.create', compact('categories', $categories));
    }

And here's my view (the form)
{!! Form::open(['url' => '/processor']) !!}
    {!! csrf_field() !!}

        {!! Form::label('make', 'Manufacturer') !!}
        {!! Form::select('make', ['Intel', 'AMD', 'Apple', 'Qualcomm', 'class' => 'form-control']) !!}

        {!! Form::label('chipset', 'Chipset') !!}
        {!! Form::text('chipset', ['class' => 'form-control']) !!}

        {!! Form::label('type', 'Type') !!}
        {!! Form::text('type', ['class' => 'form-control']) !!}

        {!! Form::label('category', 'Category') !!}
        {!! Form::select('categories', $categories, null, ['class' => 'form-control']) !!}

        {!! Form::submit('Add Processor', ['class' => 'btn btn-primary form-control']) !!}

{!! Form::close() !!}

I just want to achieve something equivalent to this
<select class="form-control" name="category">
    <?php
    $stmt = $connect->prepare("SELECT * FROM categories");
    $stmt->execute();
    while($row = $stmt->fetch())
    {
      print "<option value='".$row['id']."'>".$row['name']."</option>";
    }
    ?>
</select>

My Category Model
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['name'];

    public function processor()
    {
      return $this->hasMany('App\Processor', 'category_id');
    }
}

My Processor Model
use Illuminate\Database\Eloquent\Model;

class Processor extends Model
{
    protected $fillable = ['make', 'chipset', 'type', 'category_id'];

    public function category()
    {
      return $this->belongsTo('App\Category', 'category_id');
    }
}

A: Try this:
Controller
$categories = DB::table('categories')->pluck('name', 'id');
return view('admin.processor.create', compact('categories'));

View
{!! Form::select('categories', $categories, null, ['class' => 'form-control']) !!}

A: So for those who are facing the same problem and still getting the htmlspecialchars() expects parameter 1 to be string, array given in Laravel 5.3, I'd suggest that you use the normal html form instead of the Form helper from Laravel Collective.
Here's what I did
My Controller
public function create()
    {
      $categories = Category::pluck('name', 'id');
      return view('admin.processor.create', ['categories' => $categories]);
    }

And the view

has('category') ? ' has-error' : '' }}">
        Category
        <select name="category" id="category" class="form-control" required autofocus>
            @foreach($categories as $category)
            <option value="{{ $category }}">{{ $category }}</option>
            @endforeach
        </select>

You should be able to display the create page now. Hopefully it helps.


text:
Q: Bringing Variables from one form to another I want to bring variables (Amount and Interest rates) made in Form 1 into Form 3.
I need to put the variables made in form 1 into labels in form 3 or get the variables from form 1 into form 3. Is there any way to pass variables from one form to another and how?
namespace InvestmentCalc
{
public partial class Form1 : Form
{
    decimal Amount;
    decimal WeekInterest;
    decimal TwoWeekInterest;
    decimal MonthInterest;
    decimal ThreeMonthInterest;

    public Form1()
    {
        InitializeComponent();
    }

    private void nextButton_Click(object sender, EventArgs e)
    {
        ParseItems();
        Formchange();
    }
        private void ExitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ClearButton_Click(object sender, EventArgs e)
        {

        }

    //Methods

        public void ParseItems()
        {
            WeekInterest = decimal.Parse(WeekIntTextBox.Text);
            TwoWeekInterest = decimal.Parse(tWeekIntTextBox.Text);
            MonthInterest = decimal.Parse(monthIntTextBox.Text);
            ThreeMonthInterest = decimal.Parse(threeMonthIntTextBox.Text);
            Amount = decimal.Parse(DepositTextBox1.Text);
        }

        public void Formchange()
        {
            Form3 Check = new Form3();
            Check.Show();
            Hide();
        }
    }

A: Yes, certainly, but you would have to look for a solution at a higher level. First, instantiate the first form, then e.g. show it modal, when the call returns, read the properties from that form and pass them to the next one.
int amount, interest;
using (Form1 form = new Form1())
{
    form.ShowDialog();
    amount = form.Amount;     // these, of course, have to be public
    interest = form.Interest; // make the fields private and expose them via properties
    [...]
}

using (Form2 form = new Form2(amount, interest))
{
    form.ShowDialog();
}

ShowDialog() returns when the form closes, so it's probably the easiest thing to do here.
Depending on how many values you need to pass, creating a struct or class to hand them over might be a good strategy.
[Edit:] In contrast to the other answer, this will spawn a series of forms. Passing the current form into the constructor of a new one, although not necessarily, is more of a modal-dialog approach. If that was indeed what you were asking for, all you need to know is that you can write a form with a constructor that requires arguments.

A:
Is there any way to pass variables from one form to another and how? Thanks

Sure, simplest way is define your variables as public.Then when you opening your second form pass your current Form instance to Show method:
Form3 f3 = new Form3();
f3.Show(this);

Then inside of Form3 cast Owner to your Form1 and access your variable like this
((Form1)Owner).VariableName;

A: if you want to move many value to another form, create constructor first in form3(in here for example sent two string from form1 to form3)
Public Form3(object[] data) :this()
{
string s1 = data[0].Tostring();
string s2 = data[1].Tostring();
label1.Text = s1;
label2.Text = s2;
}

in form1, now we can create form3 that can receive our data, stringA will be sent to form3 as s1, stringB will be sent to form3 as s2.
private void button_Click(object sender, Eventargs e)
{
stringA = "my value";
stringB = "my another value";
object[] data = {stringA, stringB};
Form3 frm = new Form3(data);
frm.Showdialog();
}


text:
Q: SQLC Override Bool Type PostgreSQL I am using SQLC and my YAML config file contains the following type overrides for postgresql:
gen:
  go:
    emit_json_tags: true
    package: "hmdb"
    out: "hmdb"
    overrides:
    - db_type: "hstore"
      nullable: true
      go_type: "github.com/jackc/pgtype.Hstore"
    - db_type: "text"
      nullable: true
      go_type:
        import: "gopkg.in/guregu/null.v4"
        package: "null"
        type: "String"
    - db_type: "timestamptz"
      nullable: true
      go_type:
        import: "gopkg.in/guregu/null.v4"
        package: "null"
        type: "Time"

Everything here works, but if I add:
    - db_type: "bool"
      nullable: true
      go_type:
        import: "gopkg.in/guregu/null.v4"
        package: "null"
        type: "Bool"

I do not get the expected result. I have also tried boolean and bit to no avail, both with and without nullable.
I have an update query defined here:
-- name: SetUser :one
UPDATE users SET
    username = coalesce(sqlc.narg(username), username),
    email = coalesce(sqlc.narg('email'), email),
    phone = coalesce(sqlc.narg('phone'), phone),
    password = coalesce(sqlc.narg('password'), password),
    mfatoken = coalesce(sqlc.narg('mfatoken'), mfatoken),
    active = coalesce(sqlc.narg('active'), active)
    WHERE id = $1 RETURNING *;

But the generated struct looks like:
type SetUserParams struct {
    ID       uuid.UUID    `json:"id"`
    Username null.String  `json:"username"`
    Email    null.String  `json:"email"`
    Phone    null.String  `json:"phone"`
    Password null.String  `json:"password"`
    MFAToken null.String  `json:"mfatoken"`
    Active   sql.NullBool `json:"active"`
}

I want to use null.Bool instead of sql.NullBool, is this possible?

A: Create your schema.yaml like this:
CREATE TABLE users (
    ...
    active pg_catalog.bool
)

In sqlc.yaml the entry should look something like this:
   - db_type: "pg_catalog.bool"
     nullable: true
     go_type:
       import: "gopkg.in/guregu/null.v4"
       package: "null"
       type: "Bool"

Then after sqlc generate it would look like this:
type SetUserParams struct {
    ...
    Active   null.Bool   `json:"active"`
}

So it uses null.Bool instead of sql.NullBool.


text:
Q: Download file from virtual directory (SharePoint 2010) I need to download a file from a virtual directory when clicking on a button in sharepoint.
I've tried this:
page.Response.ContentType = "text/vcard";
page.Response.AppendHeader("Content-Disposition", "attachment; filename=" + path);
page.Response.TransmitFile(page.Server.MapPath("~/vcf/" + path));
page.Response.Flush();
page.Response.End();

The problem with this is that I can download the file, but after downloading, I can't do anything on the page. I guess that's the Response.End(), but deleting that line doesn't work because he'll add text to my downloaded file...
Is there an easy solution to this? Or another (working) solution is always welcome...

A: Change the web part (or whatever) that's rendering the button to include the following javascript into the page:
_spOriginalFormAction = document.forms[0].action;
_spSuppressFormOnSubmitWrapper=true;


text:
Q: I want to extract specific char by using sed command I want to extract /battle/result from following the txt file
$ cat sample
user_id=1234 /battle/start

I run following the sed command
$ cat sample | sed 's|.*\(/.*\)|\1|g'
/start

But, result is deleting /battle, so I can't extract it as I want.
What is wrong with it?

A: You can remove all characters up to last space:
$ sed 's/.* //' <<< "user_id=1234 /battle/start"
/battle/start

or use cut:
$ cut -d' ' -f2 <<< "user_id=1234 /battle/start"
/battle/start

A: Sed tries to do a greedy (maximal) match, therefore .* matches your whole line up to but not including the second /.
Try:
< sample sed 's|.* \(/.*\)|\1|g'

or
< sample sed 's|[^/]*\(/.*\)|\1|g'

A: In your RE the .* is greedy and swallows the /battle part, you could try to invert the logic and delete everything in front of /:
cat sample | sed 's/[^/]*//'

Here [^/]* matches everthing that is not a / and replaces it with nothing.

A: echo  user_id=1234 /battle/start |grep -oP '\s\K.*'
/battle/start

echo  user_id=1234 /battle/start |sed -r 's/(^.*\s)(.*)/\2/g'
/battle/start


text:
Q: Use commands under directory only for interactive use? I have a bin/ under $HOME. This contains some augmented versions of common commands. Hence, I don't want these commands to be used by scripts, but only to be used in interactive use.
Is the best I can do to add
for f in ~/bin/*
do
    alias "$(basename $f)"="$f"
done

to my ~/.bash_profile? Or is there another solution?

A: You also can add the lines as follows to your .bashrc, which only sets the PATH if you are in a interactive shell.
if [ "$PS1" ]
then
    export PATH=~/bin:$PATH
fi

A: You could use environment modules to manually enable (load) a module setting the desired path
module load homebin

Where homebin module would look like
#%Module1.0
prepend-path PATH ~/bin

http://modules.sourceforge.net

A: It depends on which shell and (unfortunately) which system you are using. Bash, for example, uses different startup files depending on whether it is used as an interactive or non-interactive shell, as explained in the bash manual.
In principle you should be able to add export PATH=$HOME/bin:$PATH to your ~/.bashrc file, which then will be executed only for interactive non-login shells. In practice some systems are configured such that they read ~/.bashrc also for non-interactive shells.
Related questions:

*

*What's the difference between .bashrc, .bash_profile, and .environment?

*About .bash_profile, .bashrc, and where should alias be written in?


text:
Q: Problem overriding MagePlaza OSC 3rd party .html file I want to override this file but everything I have tried does not work.
/app/code/Mageplaza/Osc/view/frontend/web/template/container/payment.html
Any help would be appreciated.

A: copy "payment.html" file from

/app/code/Mageplaza/Osc/view/frontend/web/template/container/payment.html

and override it in your theme on below path

/app/code/Design/Frontend/Your/Theme/Mageplaza_Osc/template/container/payment.html

A: Add below code in requirejs-config.js
var config = {
    map: {
        '*': {
          'Mageplaza_Osc/template/container/payment.html':
              'Namespace_Module/template/container/payment.html'
        }
  }
};

After run the magento commands.

A: it's simple put file below path
app/design/frontend/<vendor>/<theme>/Mageplaza_Osc/web/template/container/payment.html


text:
Q: Using boost with Bazel under Windows 10 and Visual Studio Community 2019 I have set up a simple C++ program that makes use of the boost filesystem module. To build the program I use Bazel 0.25.0. I am working under Windows 10 x64.
I installed Visual Studio 2019 Community Edtion and set BAZEL_VC to E:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC. I have installed the MSYS2 shell.
Here are my files (can be found also on GitHub):
WORKSPACE
workspace(name = "BoostFilesystemDemo")

load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")

# Boost
git_repository(
    name = "com_github_nelhage_rules_boost",
    commit = "6681419da0163d097d4e09c0756c0d8b785d2aa8",
    remote = "https://github.com/nelhage/rules_boost",
    shallow_since = "1556401984 -0700"
)

load("@com_github_nelhage_rules_boost//:boost/boost.bzl", "boost_deps")
boost_deps()

main.cpp
#include <iostream>
#include <boost/filesystem.hpp>

using namespace boost::filesystem;

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        std::cout << "Usage: tut1 path\n";
        return 1;
    }
    std::cout << argv[1] << " " << file_size(argv[1]) << '\n';
    return 0;
}

BUILD
cc_binary(
    name = "FilesystemTest",
    srcs = ["main.cpp"],
    deps = [
            "@boost//:filesystem",
    ],
)

When I try to build I receive the following error message (unfortunately mixed with some German language - Datei kann nicht gefunden werden means file not found)
PS E:\dev\BazelDemos\BoostFilesystemDemo> bazel build //...
INFO: Analyzed target //:FilesystemTest (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
ERROR: E:/dev/bazeldemos/boostfilesystemdemo/BUILD:1:1: Linking of rule '//:FilesystemTest' failed (Exit 1104)
LINK : fatal error LNK1104: Datei "libboost_filesystem-vc141-mt-x64-1_68.lib" kann nicht ge÷ffnet werden.
Target //:FilesystemTest failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 1.175s, Critical Path: 0.12s
INFO: 0 processes.
FAILED: Build did NOT complete successfully

Does anyone have some idea to fix this problem (compiling the source using Bazel 0.25.0 or up, Visual Studio 2019 Community Edition, Windows 10 x64, Target should be x64)? Using Ubuntu 18.04 everything went fine.
Switching to another git repository that provides boost is also fine for me.
I want to also to use other parts of the boost library such as boost signals2, boost log, boost algorithm and boost compute.

A: Modify the BUILD.boost this way:
diff --git a/BUILD.boost b/BUILD.boost
index a3a2195..2cffdda 100644
--- a/BUILD.boost
+++ b/BUILD.boost
@@ -623,6 +623,14 @@ boost_library(
         ":system",
         ":type_traits",
     ],
+    defines = select({
+        ":linux_arm": [],
+        ":linux_x86_64": [],
+        ":osx_x86_64": [],
+        ":windows_x86_64": [
+            "BOOST_ALL_NO_LIB",
+        ],
+    }),
 )

 boost_library(
@@ -1491,6 +1499,14 @@ boost_library(
         ":predef",
         ":utility",
     ],
+    defines = select({
+        ":linux_arm": [],
+        ":linux_x86_64": [],
+        ":osx_x86_64": [],
+        ":windows_x86_64": [q
+            "BOOST_ALL_NO_LIB",

I cloned the rules_boost repo and applied the above changes - the cloned repository can be used direclty in the WORKSPACE file:
workspace(name = "BoostFilesystemDemo")

load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")

# Boost
git_repository(
    name = "com_github_nelhage_rules_boost",
    commit = "f0d2a15d6dd5f0667cdaa6da9565ccf87b84c468",
    remote = "https://github.com/Vertexwahn/rules_boost",
    shallow_since = "1557766870 +0200"
)

load("@com_github_nelhage_rules_boost//:boost/boost.bzl", "boost_deps")
boost_deps()

Currently, a pull request is running to merge these changes into the original repository: https://github.com/nelhage/rules_boost/pull/123


text:
Q: How to make a domain point to my site hosted on AWS Sorry if this is a silly question. I used to know how to do this, but now GoDaddy has changed their UI so much that I'm not sure.
In IIS I added a binding for mysite.com for my website. Then in GoDaddy I bought the mysite.com domain. Suppose my public DNS for my site is
ec2-32-258-223-00.us-west-2.compute.amazonaws.com

and the public IP is 32.258.229.30. How do I connect the dots?
In GoDaddy under manage/mysite.com/dns there is "Forwarding" and "Nameservers", but I'm not sure if either of those are what I want. So confusing. Can someone help me figure this out?

A: To point your domain to a specific EC2 instance:

*

*Create an Elastic IP Address. This is a static IP address that will remain associated with your EC2 instance. If you use an auto-assigned IP address, it might change when your instance is stopped/started.

*In GoDaddy, create an A record for your domain that points to the Elastic IP address of your instance

Alternatively, you could configure GoDaddy to send all DNS requests to Amazon Route 53 and you could do the above configuration within Route 53 itself. See: Old article showing how to redirect a subdomain from GoDaddy to Route 53


text:
Q: How to replace a line in a csv file without sed I have a csv file and I want to replace a line (remove it and add new information in its place) but I can't use sed. I don't know, my bash terminal doesn't support it. Let's say the csv file is like this:
a,b,c
d,e,f

I want to remove the line d,e,f and add g,h,i, for example.

A: With Awk:
awk '/^d,e,f$/ { $0 = "g,h,i" }1' file.csv

GNU Awk has an inplace option, or just write to a temporary file and then mv it on top of the original.
If you have sed but it doesn't support the -i option, the same approach will work there.
perl -pi 's/^d,e,f$/g,h,i/' file.csv

will replace in-place just like sed -i.
tr is not suitable for this task. A Bash while read -r loop will work, but is clumsy and very inefficient.


text:
Q: How to add/install pygame to Yocto project on Raspberry Pi 4? How can you install pygame to your yocto project? Can only seem to find old solutions that doesn't seem to work. I mange to install python3 without any issues, but the meta-python layer doesn't contain pygame as standard. How can you create your own layer/recipe to get pygame?
Tried to create my own recipe from the script here
but when I use bitbake add-layer <PATH>
I get an error saying that:
Specified layer directory <PATH> doesn't contain a conf/layer.conf file
SUMMARY = "Python Game Development"
HOMEPAGE = "https://www.pygame.org"
AUTHOR = "A community project. <pygame@pygame.org>"
LICENSE = "LGPL-2.0"
LIC_FILES_CHKSUM = "file://setup.py;md5=59f9a291287e87473bbb98f2c9291c5c"

SRC_URI = "https://files.pythonhosted.org/packages/9a/50/67767e5586a45e7e7b02e6f0e07853f8fcb81b54c66db6278f1a1344491f/pygame-2.1.2.tar.gz"
SRC_URI[md5sum] = "8467a125e9075fa701f082806d228366"
SRC_URI[sha256sum] = "d6d0eca28f886f0477cd0721ac688189155a587f2bb8eae740e52ca56c3ad23c"

S = "${WORKDIR}/pygame-2.1.2"

RDEPENDS_${PN} = ""

inherit setuptools3

How my other files look.
local.conf:
MACHINE ??= "raspberrypi4-64"
RASPBERRYPI_DISPLAY = " 1"
IMAGE_INSTALL:append = " python3"
IMAGE_FSTYPES = "wic wic.bmap"

bblayers.conf:
  <PATH>/poky/meta \
  <PATH>/poky/meta-poky \
  <PATH>/poky/meta-yocto-bsp \
  <PATH>/meta-openembedded/meta-oe \
  <PATH>/meta-openembedded/meta-python \
  <PATH>/meta-raspberrypi \

A: Have you managed to add pygame to Yocto? I'm trying to achieve the same thing.
I've also tried generating a recipe with pipoe. (Without creating a custom layer. I've added the recipe to ../sources/poky/meta/recipes-devtools/python.) The recipe is parsed successfully, however the compilation fails.
This is my python3-pygame_2.1.3.dev8.bb:
SUMMARY = "Python Game Development"
HOMEPAGE = "https://www.pygame.org"
AUTHOR = "A community project. <pygame@pygame.org>"
LICENSE = "LGPL-2.0"
LIC_FILES_CHKSUM = "file://setup.py;md5=f28719c8b1d7e19071bd25e2f3a54c06"

SRC_URI = "https://files.pythonhosted.org/packages/f0/34/fc13b596b637cc59961ed606447a27a96d31bfda3ca965b73ebd16a02750/pygame-2.1.3.dev8.tar.gz"
SRC_URI[md5sum] = "6cf32b59a453b9824f421065a0205b52"
SRC_URI[sha256sum] = "94d98328e73d56be35cc3ae8e31f9d95fbce4f3dca6a74f05c58f4c5ef18c33d"

S = "${WORKDIR}/pygame-2.1.3.dev8"

RDEPENDS_${PN} = "libsdl2"

inherit setuptools3

A: The solution that worked for me:
Add meta-python and meta-netoworking via meta-openembedded.
In local.conf add IMAGE_INSTALL:append = " python3-pip".
While up and running use the command pip3 install pygame


text:
Q: Group Actions: Orbit Space Given a group action $G\curvearrowright X$.
Consider the orbit space: $\pi:X\to X/G$

Do continuous group actions correspond to open projections, i.e.:
  $$l_g\in\mathcal{C}(X)\quad(g\in G)\iff\pi(U)\in\mathcal{T}_{X/G}\quad(U\in\mathcal{T}_X)$$
  (Note that this is a slightly different more appropriate version of continuous group actions.)

Certainly, continuous group actions give rise to open projections since:
$$\pi^{-1}(\pi(U))=\bigcup_{u\in U}Gu=GU=\bigcup_{g\in G}gU=\bigcup_{g\in G}l_g(U)\in\mathcal{T}$$
Surely, the converse may hold as the following example suggests:
$$l_{k\in\mathbb{Z}}:=\mathrm{id}+k\chi_\mathbb{Z}:\quad \pi^{-1}(\pi(-\varepsilon,\varepsilon))=(-\varepsilon,\varepsilon)\cup\mathbb{Z}\notin\mathcal{T}_\mathbb{R}$$
Besides, the analog assertion about closed projections is wrong:
$$l_{q\in\mathbb{Q}}(x):=x+q:\quad\pi^{-1}(\pi(\{0\}^\complement))=\mathbb{Q}^\complement\notin\mathcal{T}_\mathbb{R}$$
(That is arbitrary unions of closed sets are not closed in general.)
Still how to prove that the converse holds true, too?
Reference: This is a follow-up to: Group Actions: Discontinuity

A: This is false in general, take for instance, $G\cong {\mathbb Z}$ acting on the circle via irrational rotations. Then the projection of each point to $Q=S^1/G$ is not only not closed, it is actually a dense point in $Q$.
Edit: I misread the original question as I thought you were asking about the quotient map being closed. The answer to you question is that open projection $\pi$ does not imply that the action is continuous. As an example, consider the  transitive action of the group $G$ of real numbers on itself via left translation, $G\times X\to X$, $X=G$. Now, change the topology on $X$ to make this action discontinuous (say, pick a bijection of $f: X\to [0,1]$ and equip $X$ with the preimage of the standard topology on $[0,1]$). The resulting action is no longer continuous, but the map $\pi: X\to X/G=\{p\}$ is open.


text:
Q: How to display a pdf file in browser by passing a search string and need to display that page 1st with contains highlighted search string using java I already done with displaying a pdf file in browser and i am passing a search string, but it parsing the string into words and then searching in the pdf file .I want whole string search in pdf file directly when i pass the search string
In java ,i done  a project tool for pdf search engine where i used the lucene 3.x and pdfbox0.7 works similar google search engine ...
1) Enter the search string in the text box
2) When click on search it will search in the pdf files and display the matched result as a fragment of some text from file ,displays in the result with highlighted words in the result
3) Now when user clicks on the results found it should open the pdf file and the search string must be highlighted in the pdf file...
< object data=".<%=filename%>#search=<%=key1%>&view=FitBH,top&toolbar=0" type="application/pdf" width="1350" height="650"> alt : < a href=".<%=filename%>">test.pdf< /a>  < /object>
it is displaying the pdf file in browser with highlighted words of a search string but i need the whole string need to be highlighted...
PLease help me

A: About the part of displaying a pdf directly in the browser: How do you do it? Not everybody has a pdf-plugin in his browser, so the browser would offer to download the pdf as a file. When this happens you can't highlight text in the pdf. Or do you use a library for that?
For displaying PDFs in the browser, you might have a look at pdf.js. Maybe it even supports highlighting a given search string (i.e. triggering the search inside pdf.js).


text:
Q: How to get data from API (JSON) in android? I tried to get some data from song API. What I want to get is the tags from the song.
Here the JSON :
{"track":
    {"name":"Let It Happen",
    "url":"http://www.last.fm/music/Tame+Impala/_/Let+It+Happen",
    "duration":"469000",
    "streamable":{"#text":"0","fulltrack":"0"},
    "listeners":"150111",
    "playcount":"758518",
    "artist":{"name":"Tame Impala","mbid":"63aa26c3-d59b-4da4-84ac-716b54f1ef4d","url":"http://www.last.fm/music/Tame+Impala"},
    "toptags":
        {"tag":[
            {"name":"indie","url":"http://www.last.fm/tag/indie"},
            {"name":"psychedelic","url":"http://www.last.fm/tag/psychedelic"},
            {"name":"Psychedelic Rock","url":"http://www.last.fm/tag/Psychedelic+Rock"},
            {"name":"2015","url":"http://www.last.fm/tag/2015"},
            {"name":"electronic","url":"http://www.last.fm/tag/electronic"}
            ]
        },
    "wiki":
        {"published":"11 Mar 2015, 08:59","summary":"Let It Happen is the opening track and first song revealed from Tame Impala's upcoming third album, Currents. Read more on Last.fm.","content":"Let It Happen is the opening track and first song revealed from Tame Impala's upcoming third album, Currents. Read more on Last.fm. User-contributed text is available under the Creative Commons By-SA License; additional terms may apply."}
    }
}

From what I've learned, I use this code to parse it
private static ArrayList<String> parseTagsAPI(final String response)
{
    ArrayList<String> tagTemp = new ArrayList<String>();
    try
    {
        String tag="", logtag="test, test2";

        JSONObject jsonObject = new JSONObject(response);
        if (jsonObject.has("track"))
        {
            JSONObject jsonTrack = jsonObject.getJSONObject("track");
            Log.d("API (tag)", "track");

            if (jsonObject.has("toptags"))
            {
                JSONArray jsonArray = jsonTrack.getJSONObject("toptags").getJSONArray("tag");
                Log.d("API (tag)", "track > album > toptags > tag(array)");

                for (int i = 0; i < jsonArray.length(); i++)
                {
                    if (jsonArray.getJSONObject(i).has("name"))
                    {
                        JSONObject tagArray = jsonArray.getJSONObject(i).getJSONObject("name");
                        tag = tagArray.optString("name");

                        logtag += (tag + ", ");
                        Log.d("API (tag)", "tags : " + tag);
                    }
                    tagTemp.add(tag);
                }
            }
        }
        Log.d("API (tag)", "Logtag : "+logtag);
    } catch (Exception e) {
        e.printStackTrace();
        return new ArrayList<String>();
    }
    return tagTemp;
}

I put some logs to mark the progress, but it only show 2 logs:

*

*Log.d("API (tag)", "track");

*Log.d("API (tag)", "Logtag :"+logtag); -> this var is empty

which means my second if doesnt work. Anyone know why this is happen?

A: You're looking for the wrong tag - it's just a typo.

    private static ArrayList<String> parseTagsAPI(final String response)
{   ArrayList<String> tagTemp = new ArrayList<String>();
    try
    {   String tag="", logtag="test, test2";

        JSONObject jsonObject = new JSONObject(response);
        if (jsonObject.has("track"))
        {   JSONObject jsonTrack = jsonObject.getJSONObject("track");
            Log.d("API (tag)", "track");

            if (jsonObject.has("toptags"))
            {   JSONArray jsonArray = jsonTrack.getJSONObject("toptags").getJSONArray("tag");
                Log.d("API (tag)", "track > album > toptags > tag(array)");

Notice that you're looking for jsonObject.has("toptags") rather than jsonTrack.has("toptags");

A: It is wrong here:
JSONObject tagArray = jsonArray.getJSONObject(i).getJSONObject("name");
tag = tagArray.optString("name");

you should do instead:
tag = jsonArray.getJSONObject(i).getString("name");

or
tag = jsonArray.getJSONObject(i).optString("name");

Also change this:
if (jsonObject.has("toptags"))

to
if (jsonTrack.has("toptags"))


text:
Q: Remove selected option from another select box I am trying implement multiple select boxes in a single page. All these select boxes will have the same option values. When I select first option from select box 1, then that option should be removed from remaining select boxes.
<select name="selectBox1" id="selectBox1">
   <option value="option1">option1</option>
   <option value="option2">option2</option>
   <option value="option3">option3</option>
   <option value="option4">option4</option>
</select>

<select name="selectBox2" id="selectBox2">
    <option value="option1">option1</option>
    <option value="option2">option2</option>
    <option value="option3">option3</option>
    <option value="option4">option4</option>
</select>

<select name="selectBox3" id="selectBox3">
    <option value="option1">option1</option>
    <option value="option2">option2</option>
    <option value="option3">option3</option>
    <option value="option4">option4</option>
</select>

How do I do it? I know how to remove or add option if there is only one select box, but for multi select box, I am stuck.

A: I recommend using jquery, code would look like this:
$("select").change(function(e){
    var $s = $(e.target);
    $("select").not($s).find("option[value="+$s.val()+"]").remove();
});

JSFiddle
UPDATE (inspired by Bhushan Kawadkar's answer)
Here is how you can improve it:
$("select").change(function(e){
    $("select option").removeAttr('disabled');
    $("select").each(function(i,s){
       $("select").not(s).find("option[value="+$(s).val()+"]").attr('disabled','disabled');
    });
});

JSFiddle

A: Try this : Instead of removing options from the list you can show / hide it, so that if user change selected option then same option should get restored in rest of the select boxes.
$(document).ready(function(){
   $('select').on('change', function(event ) {
       //restore previously selected value
       var prevValue = $(this).data('previous');
       $('select').not(this).find('option[value="'+prevValue+'"]').show();
       //hide option selected
       var value = $(this).val();
       //update previously selected data
       $(this).data('previous',value);
       $('select').not(this).find('option[value="'+value+'"]').hide();
   });
});

DEMO

A: here you go: DEMO
$('select').on('change',function(){
    var value=$(this).val();
    $('select').not(this).each(function(){
        $(this).find('option[value='+value+']').remove();
    });
});

but keep in mind that this is not how you ask questions in SO, you need to try some code then show what you've tried and ask for help fixing the problem!

A: Instead of trying to hack your own multiple select box, how about just using a real multi-select box?

<select name="selectBox1" id="selectBox1" multiple="multiple">
  <option value="option1">option1</option>
  <option value="option2">option2</option>
  <option value="option3">option3</option>
  <option value="option4">option4</option>
</select>

A: Try if the following code example could work for you:
$(document).ready(function(){
  $('select').on('change', function(event ) {
    var value = $(this).val();
    $(this).prop('disabled', false);

    $('select').find('option[value="'+ value +'"]')
     .attr('disabled', 'disabled')
     .hide();
  });
});


text:
Q: Windows task scheduler to execute tasks in seconds I'm looking for an open source/free task scheduler for Windows 7 (development machine) that will allow me to schedule tasks (HTTP requests to a web service) to run every x seconds.
I've tried a couple of Cron clones and windows own Task Scheduler but neither seem to allow tasks to run at intervals less than 60 seconds. Am I missing something? I don't want to have to go and write any custom scripts either if possible.

A: It is possible to create multiple triggers for one scheduled task. If you create 59 identical triggers with an offset of 1 second to each other, and schedule the task itself to run every minute, you end up the scheduled task to run every second.
You could create those 59 triggers manually using the GUI. However, a much quicker way to create so many triggers is to create a task with one or two triggers, export it to a text file, duplicate the according lines, change the start offsets accordingly, and then re-import the file.

A: I've googled this to death, so as far as I can see the answer is, there are none. There are plenty of commercial solutions, but no open source/free programs.
I ended up writing a very simple periodic HTTP GET scheduler in java using quartz scheduler. It may be useful to other so posting a link to the source on guthub https://github.com/bjordan/simple_java_periodic_HTTP_scheduler

A: I was actually able to achieve this.
Update: Seems I over complicated it.
In the trigger, where it says "Repeat task every:" you can actually TYPE into the drop-down "1 minute" (It wont let you type the time in seconds)
I did this on a Windows 7 machine.
Also, I clearly did not read the question well enough, as the asker seems to already have been able to get the time down to 1 minute. However, I'll leave this answer here, as it will explain for future readers exactly how to get the time down to one minute.
It does seem as though you cannot get it to run at an interval of less than one minute.

I set up a task with a trigger set to Daily to recur every 1 day.
I check the "Repeat task every:" box. Setting it to 5 Minutes for a duration of 1 day
This makes the task go forever, every 5 minutes.
I then exported the task. It exports to a .xml file.
Under Task > Triggers > CalendarTrigger > Repeition there is the following tag: <Interval>PT5M</Interval> I changed it from PT5M to PT1M. I re-imported the task.
The task now runs every 1 minute.
I have not fully tested this, and I have not tried with less than one minute, but it might be possible by putting PT30S or something for 30 seconds. I'll try it out and report back. Update: You cannot do this, you get an error when importing the task. It's not possible to set this time to less than 1 minute.
The whole trigger looks like this for me:
  <Triggers>
    <CalendarTrigger>
      <Repetition>
        <Interval>PT1M</Interval>
        <Duration>P1D</Duration>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
      <StartBoundary>2013-11-07T17:04:51.6062297</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>

A: Short explanation:
Main program starts a service process that will stay active in memory and will periodically activate a job – do something.

*

*Create a class that extends System.ServiceProcess.ServiceBase class

*Implement at least methods OnStart and OnStop

*Start and use Quartz.NET scheduler in OnStart to run tasks periodically

Here is my template C# solution for a Windows service and a Linux demon in .NET/Mono https://github.com/mchudinov/ServiceDemon
And a short blogpost about it

    class Program
    {
        public static void Main(string[] args)
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] { new ServiceDemon.Service() };
            ServiceBase.Run(ServicesToRun);
        }
    }

    public class Service : ServiceBase
    {
        static IScheduler Scheduler { get; set; }

        protected override void OnStart(string[] args)
        {
            StartScheduler();
            StartMyJob();
        }

        protected override void OnStop()
        {
            Scheduler.Shutdown();
        }

        void StartScheduler()
        {
            ISchedulerFactory schedFact = new StdSchedulerFactory();
            Scheduler = schedFact.GetScheduler();
            Scheduler.Start();
        }

        void StartMyJob()
        {
            var seconds = Int16.Parse(ConfigurationManager.AppSettings["MyJobSeconds"]);
            IJobDetail job = JobBuilder.Create<Jobs.MyJob>()
                .WithIdentity("MyJob", "group1")
                .UsingJobData("Param1", "Hello MyJob!")
                .Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("MyJobTrigger", "group1")
                .StartNow()
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(seconds).RepeatForever())
                .Build();

            Scheduler.ScheduleJob(job, trigger);
        }
    }

    public class MyJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            log.Info(dataMap["Param1"]);
        }
    }


text:
Q: How to properly sum over conditional probabilities? I'm trying to write the explicit sum of $D_{KL} \big(p(X | A, B) ~||~ p(X|A)\big)$, where $D_{KL}$ is the Kullback-Leibler divergence (also known as relative entropy).
I know I should be summing over $X$, $A$ and $B$ and I'm not sure I'm doing it correctly:
$$
D_{KL} \big(~p(X | A, B) ~||~ p(X|A)~\big) = \sum_b p(b) ~ \sum_a p(a|b) \sum_x p(x|a,b)\log\frac{p(x|a,b)}{p(x|b)}
$$
Is this correct? I tried using the chain rule of relative entropy to simplify the sum, but I only confused myself more, because the left distribution is conditioned by both $A$ and $B$, while the right distribution is only conditioned by $B$.


text:
Q: How to change the height (or width) of tkinter widget with mouse drag, after initialization? The closest approach I found was by packing the widgets separated with ttk.Separator changing the cursor and triggering a function that resizes the top and bottom widgets when the mouse starts clicked motion on the separator. The problem is, it is not working because of the glitch I am getting, and I could not find out the cause. Please check the code below:
import tkinter as tk

from tkinter import ttk

from ttkwidgets.autocomplete import AutocompleteEntryListbox

def resize(event):
    searchbox.config(height=searchbox.winfo_height()+event.y)
    template.config(height=template.winfo_height()-event.y)

window = tk.Tk()

frame_navigator = tk.Frame(window)

frame_navigator.configure(background="white",width=300,height=300)
frame_navigator.pack_propagate(0)

searchbox = AutocompleteEntryListbox(frame_navigator,completevalues=[],allow_other_values=False)
searchbox.pack(side=tk.TOP,expand=1,fill=tk.BOTH)

separator = ttk.Separator(frame_navigator,orient='horizontal',cursor="size_ns")
separator.bind("<B1-Motion>",resize)
separator.pack(side=tk.TOP,fill=tk.X)

template = tk.Listbox(frame_navigator,exportselection=False)
template.pack(side=tk.TOP,expand=1,fill=tk.BOTH)

frame_navigator.pack(side=tk.TOP,expand=1,fill=tk.BOTH)

Your help will be appreciated!

A: I don't have ttkwidgets installed but I replaced AutocompleteEntryListbox with tk.Listbox for testing and found a solution that worked using tk.PanedWindow, a widget specifically designed for doing this. There is no reason it shouldn't work with a different widget. Set the orient of the PanedWindow to tkinter.constants.VERTICAL to change the height, and use frame_navigator.add() instead of widget.pack() for it to work. Completed code:
import tkinter as tk
from tkinter.constants import *

window = tk.Tk()

frame_navigator = tk.PanedWindow(window, orient=VERTICAL)

frame_navigator.configure(background="white", width=300, height=300)
frame_navigator.pack_propagate(0)

searchbox = tk.Listbox(frame_navigator)
frame_navigator.add(searchbox)

template = tk.Listbox(frame_navigator, exportselection=False)
frame_navigator.add(template)

frame_navigator.pack(side=tk.TOP, expand=1, fill=tk.BOTH)

window.mainloop()


text:
Q: Displacment field for linear dielectric Consider the following statement:

In the case of a linear dielectric of arbitrary shape, when no free charges are present, in an external applied electric field $\vec E_0$, then  $\vec D=0$.

Is this statement always true (considering that $\nabla \times \vec D= \nabla \times \vec P$) and can it be proved? If it is false can you please provide a counter example.
Can a similar statement be made for the auxiliary field $H$ in terms of the magnetization $M$?

A: No, this is essentially never true. In a linear dielectric, $D=\varepsilon E$, so $D=0$ can only be true if $E=0$. In other words, the statement is saying that any linear dielectric always perfectly screens a uniform external electric field. That's not true. Conductors perfectly screen electric fields in their interior, but dielectrics don't (unless the permittivity goes to infinity).
A particularly simple example is the limit $\varepsilon \rightarrow \varepsilon_0$, in which case the dielectric acts like a vacuum and has no effect on the external field. So obviously D inside is nonzero.
Another simple example is a parallel-plate capacitor in which a dielectric slab fills most of the space (but doesn't touch the plates). That's equivalent to being in a uniform electric field. As you'll find in textbooks, the (E or D) field inside the dielectric is not zero in this situation.

A: *

*Adding a counter example for a finite volume dielectric solved in detail in these notes on BOUNDARY VALUE PROBLEMS WITH "CLASS-A"/LINEAR DIELECTRICS  (starting on pg.4 bottom through pg.10): a spherical (linear) dielectric in uniform external field.

*Also adding an interesting bit on why dielectrics cannot perfectly screen electric fields.
In the absence of any free charges, bound charges in the dielectric's volume $\Omega$ are also null, $\rho_\text{free} = \rho_\text{bound} = 0$. Then from ${\vec \nabla} \cdot \vec{D} =0$, ${\vec \nabla} \times \vec{D} =0$ it follows that the potential within the dielectric must be harmonic, $\Delta V = 0$. Since free charges are absent on the boundary too, the potential must be continuous there, $V_{in} = V_\text{out}\Big|_{\partial\Omega}$, along with its normal derivatives, $\left(\frac{\partial V_\text{in}}{\partial n} - \frac{\partial V_\text{out}}{\partial n}\right)\Big|_{\partial\Omega} = \sigma_\text{free}\Big|_{\partial\Omega} = 0$. But if the displacement $\vec{D}$ were null in $\Omega$, so would the field $\vec{E}$, and the potential's normal derivative would have to vanish on the interior of the boundary. This would leave $\left(-\frac{\partial V_\text{out}}{\partial n}\right)\Big|_{\partial\Omega} = 0$ for a non-vanishing  field outside the boundary, which cannot be.
The result is that there must be a non-vanishing bound/polarization charge density on the dielectric's boundary, $\sigma_\text{bound} = \vec{P}\cdot\vec{n}\neq 0$, and a non-vanishing displacement in the volume, $\vec{D} \neq 0$.


text:
Q: How to pass variables from javascript to form? In my application I get json with place details from google maps API using autocomplete
var place = autocomplete.getPlace();

I can get a name of the place with place.name
On the same page I have a form where I get another details from user. The question is how do I pass the place.name to my rails controller when the form gets submitted? In js I tried to change HTML of the form
<form...>

</form>

using
$("#hidden_fields").append("<input name='name' type='hidden' value='"+place.name+"' />");

But apparently it doesn't works.
Should I learn AJAX to do such things or there another ways?
Thanks in advance for any hint.

A: Please ensure you are creating the hidden fields after the autocomplete finished. check the viewsource if the hidden variables has appended before submitting. As long as the control available with in the form tag before submit, your controller able to get it.

A: Thank you all! The problem has been solved. The important things I learned were

*

*View/Source doesn't show dynamically added content, but Firebug does.

*Rails modify forms field names: It turns

<%=form_for @place do |f| ...
<%= f.password_field :password , :class =>"form-field", :id =>"passwordField"
into
<input class="form-field" id="passwordField" name="place[password]" type="password" />
which means that I have to pass values from js in the same manner:
$text.append('<input name="place[name]" type="hidden" value="'+place.name+'"/>');
Hope it will help to someone else.


text:
Q: R: Change RasterBrick dimensions from TXY to XYT I am having difficulties in R getting climate data from a netCDF file into the right format for further analysis. I am working with gridded global data on Standardized Precipitation Index (downloaded from here and want to aggregate the monthly values for each grid-cells to an annual average.
Now the issue is that in the file the data is organised as TXY, where T are the number of months since January 1960 and X and Y are longitude and latitude respectively. As a result, when I load the file into R with,
library(raster)
spi<-brick("data.nc")

I get the following dimensions:
class       : RasterBrick
dimensions  : 144, 441, 63504, 58  (nrow, ncol, ncell, nlayers)
resolution  : 1, 2.5  (x, y)
extent      : 228, 669, 0, 360  (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : data.nc
names       : X.66.25, X.63.75, X.61.25, X.58.75, X.56.25, X.53.75,...
degree_north: -66.25, 76.25 (min, max)
varname     : aprod

So annoyingly, the monthly observations are on the columns whereas the latitude coordinates are on the layers. Which I don't find very useful and makes processing the data rather difficult.
Therefore I wondered, if there is a way in which I can change the dimensions to a more conventional format? With the data of interest on the layers.

A: That particular data source (IRI data library) allows reordering in its language, e.g. append
[ X Y ] REORDER
data link


text:
Q: converting lines to columns in perl or python I have a data like this:
Re: Building A

Month
kWh
1
100
2
110
3
105

Re: Building B

Month
kWh
1
200
2
210
3
205

I would like to convert it to multiple text files one for each building. My plan is to:

*

*extract the values between the building delimiter line

*convert the lines into a table

For task (1) I tried to use the flip-flop operator like this:
while( <DATA> ) {
  next unless /^Re: Building A/ .. /^Re: Building B/;
  my $line = $_;
  print $line;
}

But it does not work because the above will show only the data for building A. The data is for multiple buildings (about 50 of them) so that I need to do this somewhat recursively. I have not started to do task (2).
Any help will be appreciated.

A: I would do something like this:
#!/usr/bin/perl
use strict;
use warnings;

my %buildings;

while (<DATA>) {
    chomp;
    $buildings{$1} = [] if /^Re: Building ([AB])/;
    push @{$buildings{$1}}, $_ if $_;
}

while (my ($building, $data) = each %buildings) {
    open(my $out, '>', "$building.txt") or die "Unable to open file for writing: $!\n";

    for my $i (1 .. $#$data / 2) {
        print $out sprintf "%s\t%s\n", $data->[$i*2-1], $data->[$i*2];
    }
    close $out;
}

A.txt:
Month   kWh
1       100
2       110
3       105

B.txt:
Month   kWh
1       200
2       210
3       205

A: I think you might do well with a table so I'll show you how to do both what you ask and what I think would be good.
$name = "";
$data = {};
open(IN, "build.txt");
foreach my $line (<IN>){
    if($line =~ /Re: (.*)\n/) { # get building name
        $name = $1;
        $name =~ s/ /_/;
        $data->{$name} = []; # link to empty array
    } else {
        # make a new list and return to a list
        @{$data->{$name}} = (@{$data->{$name}}, $line); # add line to current building data
    }
}
close IN;
#
# write on file for each
#
foreach my $name (keys %{$data}){
    open(OUT, ">$name.txt");
    foreach my $line (@{$data->{$name}}){
        print OUT $line;
    }
    close OUT;
}
#
# or write into one file as a table
#
open(OUT, ">tabledata.txt");
foreach my $name (keys %{$data}){
    # because the data was not filtered on import we filter it now
    my $flag = 0;
    my @data;
    foreach my $line (@{$data->{$name}}){
        if($line =~ /kWh/) {
            $flag = 1;
        } elsif($line =~ /^\n$/){ # skip blanks
        } elsif($flag == 1) {     # skip the counters
            $flag++;
        } elsif($flag > 1) {
            chomp($line);
            @data = (@data, $line);
            $flag = 1;
        }
    }
    # print pretty rows
    my $format = "%20s" . ("%10d" x @data);
    print OUT sprintf($format, $name, @data) . "\n";

}
close OUT;

This makes a file for each building with the building name.  An example of the Building_A.txt is:
Month
kWh
1
100
2
110
3
105

And the table file is called tabledata.txt and looks like:
          Building_A       100       110       105
          Building_B       200       210       205

A: In python, I would parse the text file into a data structure and then output it using asciitables.  Ideally you wouldn't really be manipulating strings directly but rather parsing, and then displaying as separate actions.
How exactly you do the parsing depends on factors such as how regular the format of the file is, and whether or not you need to be tolerant of mistakes or typos in the file.


text:
Q: Can we run wpf application with other credentials other than logged in person? Can we run a wpf application .exe file with some other credentials other than the one whose has logged into that system, with out prompting for new user credentials.

A: You can create a batch file containing the RUNAS command in the following manner:
Example: Run notepad.exe as the user Jdoe on domain SS64dom with no profile:
C:\> Runas /noprofile /user:SS64Dom\jDoe "notepad.exe"

You will have to enter the password when prompted.
In addition you can install the free CPAU tool from joeware.net:
joeware.net - CPAU (Create Process As User) like RunAs but with an options to encrypt the password and no need to set password when prompted.
Direct link to the tool download and guide: http://www.joeware.net/freetools/tools/cpau/index.htm
Source: http://ss64.com/nt/runas.html


text:
Q: Applying skeleton to procedural skinned mesh In this fiddle I'm trying to create a procedural worm (or snake or caterpillar) character, based on the basic bones example at threejs.org/docs/scenes/bones-browser, but with an extra four bones and two spheres for eyes added on; the added/altered code shown here...
function eyeBall() {
function eyeBall(  ) {

    var faceIndices = [ 'a', 'b', 'c' ];
    var color, f, i, j, p, vertexIndex, radius = 1;
    var geometry  = new THREE.SphereGeometry( radius, 18, 5 );

    for ( i = 0; i < geometry.faces.length; i ++ ) {
        f  = geometry.faces[ i ];
        for( j = 0; j < 3; j++ ) {
            vertexIndex = f[ faceIndices[ j ] ];
            p = geometry.vertices[ vertexIndex ];
            f.color = new THREE.Color( 0xffffff );
            if( p.y < -0.9 ) {
                f.color = new THREE.Color( 0x000000 );
            }
        }
    }
    return geometry;
}

function createBones ( sizing ) {
function createBones ( sizing ) {

    bones = [];

    var prevBone = new THREE.Bone();
    bones.push( prevBone );
    prevBone.position.z = - sizing.halfLength;

    for ( var i = 0; i < sizing.segmentCount; i ++ ) {

        var bone = new THREE.Bone();
        bone.position.z = sizing.segmentLength;
        bones.push( bone );
        prevBone.add( bone );
        prevBone = bone;
    }

    //add more bones
    var lHdBone = new THREE.Bone();
        lHdBone.position.set( 1.4, 0, 2.8 );
        lHdBone.name = 'lHdBone';
        bones.push( lHdBone );
        prevBone.add( lHdBone );

    var rHdBone = new THREE.Bone();
        rHdBone.position.set( -1.4, 0, 2.8 );
        rHdBone.name = 'rHdBone';
        bones.push( rHdBone );
        prevBone.add( rHdBone );

    var lEyeBone = new THREE.Bone();
        lEyeBone.position.set( 0, 0, 1 );
        lEyeBone.name = 'lEyeBone';
        bones.push( lEyeBone );
        lHdBone.add( lEyeBone );

    var rEyeBone = new THREE.Bone();
        rEyeBone.position.set( 0, 0, 1 );
        rEyeBone.name = 'rEyeBone';
        bones.push( rEyeBone );
        rHdBone.add( rEyeBone );

    return bones;
}

function initBones () {
function initBones () {

    var segmentLength = 8;
    var segmentCount = 4;
    var length = segmentLength * segmentCount;
    var halfLength = length * 0.5;

    var sizing = {
        segmentLength : segmentLength,
        segmentCount : segmentCount,
        length : length,
        halfLength : halfLength
    };

    var geometry = createGeometry( sizing );
    var bones = createBones( sizing );
    mesh = createMesh( geometry, bones );

    var lEye = eyeBall();
    var rEye = eyeBall();
    lEye.rotateX(  -Math.PI * 0.5);
    rEye.rotateX( -Math.PI * 0.5);
    lEye.translate( 1.4, 0, sizing.halfLength + 2.8 );
    rEye.translate( -1.4, 0, sizing.halfLength + 2.8 );

    var lEyeMesh = new THREE.Mesh( lEye, material );
    var rEyeMesh = new THREE.Mesh( rEye, material );

    mesh.add( lEyeMesh );
    mesh.add( rEyeMesh );

    mesh.scale.multiplyScalar( 1 );
    scene.add( mesh );
}

The animation in the fiddle moves the spheres in the same general direction but the spheres are clearly not tied to the skeleton as desired. The eyes should be looking forward throughout. I haven't found any comparable questions for this since most modelling is done in Blender, but I am sure this should be possible in three.js alone.
I feel I'm missing something simple!
This is another fiddle with merged geometries. Now one eye seems to act correctly, but the other eye is evidently a child bone; i.e. bones[6] is a child of bones[5], while they should both be children of bones[4].


text:
Q: Cast json in to Map> Format I need to convert the json string to nested Map and access the same.
Following Json String is in form of Map given below
Map<String,Map<String,String>>

{"0":{"1551874690005":"2","1551874722124":"2","1551874810817":"2","1551874681110":"2","1551874739821":"2","1551874763604":"2","1551874692381":"2","1551874816028":"2","1551874708292":"2","1551874804308":"2","1551874694205":"2","1551874696644":"2","1551874729332":"2","1551874749950":"2","1551874767786":"2"},"1":{"1551948649643":"0","1551948733576":"0","1551948601167":"0","1551948592816":"0","1551948699297":"0","1551874822043":"2","1551948681513":"0","1551948531568":"0","1551948577374":"0","1551948719758":"0","1552370125650":"0","1551948549863":"0","1551948564519":"0","1551948631000":"0","1551953956716":"0"},"2":{"1551875011432":"0","1551875020618":"0","1551874991952":"0","1551875091300":"0","1551875073622":"0","1551875032851":"0","1551874827691":"0","1551948658122":"0","1551874846523":"0","null":"0","1552545417127":"0","1551875083856":"0","1551874929076":"0","1552545972738":"0"},"3":{"1552651031695":"0"},"4":{"1551875144268":"0","1551875157028":"0","1551875115211":"0","1551875124660":"0"}}

Getting following error while trying using my code:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>' in type cast

Map offlineExeStatus = jsonDecode(prefs.getString("offlineExeStatus"));

Map<String,Map<String,String>> exeStatusFinalJson = new Map();

exeStatusFinalJson = offlineExeStatus.cast<String,Map<String,String>();

Need to cast the given json in "exeStatusFinalJson" Map and access like:
exeStatusFinalJson["0"] should give the output like:
{"1551874690005":"2","1551874722124":"2","1551874810817":"2","1551874681110":"2","1551874739821":"2","1551874763604":"2","1551874692381":"2","1551874816028":"2","1551874708292":"2","1551874804308":"2","1551874694205":"2","1551874696644":"2","1551874729332":"2","1551874749950":"2","1551874767786":"2"}

A: Try to declare your map as Map<String, dynamic> rather than Map<String, Map<String, String>>.

A: Finally figured out the way to do it!
Map offlineExeStatus = jsonDecode(prefs.getString("onlineExeStatus"));

Map<String, dynamic> exeStatusJson = new Map();

Map<String, Map<String, String>> exeStatusFinalJson = new Map();

List<String> mapKeyExe = new List();

mapKeyExe = offlineExeStatus.keys.cast<String>().toList();

exeStatusJson = offlineExeStatus.cast<String, dynamic>();

for (int i = 0; i < mapKeyExe.length; i++) {
    Map<String, String> exeStatusInsideJson = new Map();

    exeStatusInsideJson = offlineExeStatus[mapKeyExe[i].toString()]
       .cast<String, String>();

    exeStatusFinalJson[i.toString()] = exeStatusInsideJson;

    print(exeStatusFinalJson);
}