text:
Q: Google Directory API return outdated values I have a strange problem for about 2 weeks. My python script repeatedly (every 5 min) asking google directory api for  gsuite users. A would like find users who has enable 2 factor auth (isEnrolledIn2Sv)
Unfortunately when user turns on 2FA my script returns  isEnrolledIn2Sv=True only several hours later.
When I asking it by gam ( https://github.com/jay0lee/GAM ) gets properly answer immediately.
What going on? Some kind of cache? Why google return to me not actual data for several hours? It is possible that my python library versions have bugs?
My python code:
from google.oauth2 import service_account
import googleapiclient.discovery
...
...
...

#inside class:

    def run(self):
        log("Start no2faMonitor ")
        while (True):
            log("checking no2fa list")
            self.get_google_token()
            self.ask_google_user()
            log("Users in no2fa with 2-step verification: {}".format(len(self.users)))
            for u in self.users:
                self.send_notify(u)
            time.sleep(274)

    #---------------------------------------------------------------------------------
    def get_google_token(self):

        credentials = service_account.Credentials.from_service_account_file(config.ServiceAccountFile, scopes=config.GoogleScopes).with_subject(config.SubjectAccount)
        self.directory = googleapiclient.discovery.build('admin', 'directory_v1', credentials=credentials)

    #---------------------------------------------------------------------------------
    def ask_google_user(self):

        results = self.directory.users().list(customer="my_customer", query="orgUnitPath=/no2fa", maxResults=500).execute()
        self.userdata = json.loads(json.dumps(results))
        for element in self.userdata['users']:
            log("user: {}, 2fa: {}".format(element['primaryEmail'], element['isEnrolledIn2Sv']))

...
...
...

element['isEnrolledIn2Sv'] contain "False" for users with turned on 2FA.
**pip3 list | grep google**
google                   2.0.1
google-api-python-client 1.7.4
google-auth              1.5.1
google-auth-httplib2     0.0.3

Before about 2 weeks everythink worked OK, Good answers I recived after 5 min

A: I found cache parameter in python library. (default is True)
build(serviceName, version, http=None, discoveryServiceUrl=DISCOVERY_URI, developerKey=None, model=None, requestBuilder=HttpRequest, credentials=None, cache_discovery=True, cache=None)
Construct a Resource for interacting with an API.

verified patch:
- self.directory = googleapiclient.discovery.build('admin', 'directory_v1', credentials=credentials)
+ self.directory = googleapiclient.discovery.build('admin', 'directory_v1', credentials=credentials, cache_discovery=False)

A: Unfortunley my last answer is not true.
I found right way to solve this issue.
After change metod form list() to get() all returned data is up to date.
list() should be used only to get user list, not it's parameters
results = self.directory.users().list(customer="my_customer", query="orgUnitPath=/no2fa", maxResults=500).execute()

unfortunley get() needs one requset per user.
getuser = self.directory.users().get(userKey=element['primaryEmail'], projection="full").execute()


text:
Q: Chain memoizer in python I already have a memoizer that works quite well. It uses the pickle dumps to serializes the inputs and creates MD5 hash as a key. The function results are quite large and are stored as pickle files with file name being MD5 hash.  When I call two memoized function one after another, the memoizer will load the output of the first function and pass it to the second function.  The second function will serialize it, create MD5 and then load the output.  Here is a very simple code:
@memoize
def f(x):
    ...
    return y

@memoize
def g(x):
    ...
    return y

y1 = f(x1)
y2 = g(y1)

y1 is loaded from the disk when f is evaluated and then it's serialized when g is evaluated. Is it possible to somehow bypass this step and pass the key of y1 (i.e. MD5 hash) to g? If g already has this key, it loads the y2 from the disk.  If it doesn't, it "requests" the full y1 for the evaluation of g.
EDIT:
import cPickle as pickle
import inspect
import hashlib

class memoize(object):
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        arg = inspect.getargspec(self.func).args
        file_name = self._get_key(*args, **kwargs)
        try:
            f = open(file_name, "r")
            out = pickle.load(f)
            f.close()
        except:
            out = self.func(*args, **kwargs)
            f = open(file_name, "wb")
            pickle.dump(out, f, 2)
            f.close()

        return out

    def _arg_hash(self, *args, **kwargs):
        _str = pickle.dumps(args, 2) + pickle.dumps(kwargs, 2)
        return hashlib.md5(_str).hexdigest()

    def _src_hash(self):
        _src = inspect.getsource(self.func)
        return hashlib.md5(_src).hexdigest()

    def _get_key(self, *args, **kwargs):
        arg = self._arg_hash(*args, **kwargs)
        src = self._src_hash()
        return src + '_' + arg + '.pkl'

A: I think you could do it in an automatic fashion but I generally think it's better to be explicit about "lazy" evaluation. So I'll present a way that adds an additional argument to your memoized functions: lazy. But instead of files, pickle and md5 I'll simplify the helpers a bit:
# I use a dictionary as storage instead of files
storage = {}

# No md5, just hash
def calculate_md5(obj):
    print('calculating md5 of', obj)
    return hash(obj)

# create dictionary entry instead of pickling the data to a file
def create_file(md5, data):
    print('creating file for md5', md5)
    storage[md5] = data

# Load dictionary entry instead of unpickling a file
def load_file(md5):
    print('loading file with md5 of', md5)
    return storage[md5]

I use a custom class as intermediate object:
class MemoizedObject(object):
    def __init__(self, md5):
        self.md5 = result_md5

    def get_real_data(self):
        print('load...')
        return load_file(self.md5)

    def __repr__(self):
        return '{self.__class__.__name__}(md5={self.md5})'.format(self=self)

And finally I show the changed Memoize assuming your functions take only one argument:
class Memoize(object):
    def __init__(self, func):
        self.func = func
        # The md5 to md5 storage is needed to find the result file
        # or result md5 for lazy evaluation.
        self.md5_to_md5_storage = {}

    def __call__(self, x, lazy=False):
        # If the argument is a memoized object no need to
        # calculcate the hash, we can just look it up.
        if isinstance(x, MemoizedObject):
            key = x.md5
        else:
            key = calculate_md5(x)

        if lazy and key in self.md5_to_md5_storage:
            # Check if the key is present in the md5 to md5 storage, otherwise
            # we can't be lazy
            return MemoizedObject(self.md5_to_md5_storage[key])
        elif not lazy and key in self.md5_to_md5_storage:
            # Not lazy but we know the result
            result = load_file(self.md5_to_md5_storage[key])
        else:
            # Unknown argument
            result = self.func(x)
            result_md5 = calculate_md5(result)
            create_file(result_md5, result)
            self.md5_to_md5_storage[key] = result_md5
        return result

Now if you call your functions and specify lazy at the correct positions you can avoid loading (unpickling) your file:
@Memoize
def f(x):
    return x+1

@Memoize
def g(x):
    return x+2

Normal (first) run:
>>> x1 = 10
>>> y1 = f(x1)
calculating md5 of 10
calculating md5 of 11
creating file for md5 11
>>> y2 = g(y1)
calculating md5 of 11
calculating md5 of 13
creating file for md5 13

Without lazy:
>>> x1 = 10
>>> y1 = f(x1)
calculating md5 of 10
loading file with md5 of 11
>>> y2 = g(y1)
calculating md5 of 11
loading file with md5 of 13

With lazy=True
>>> x1 = 10
>>> y1 = f(x1, lazy=True)
calculating md5 of 10
>>> y2 = g(y1)
loading file with md5 of 13

The last option only calculates the "md5" of the first argument and loads the file of the end-result. That should be exactly what you wanted.

redpajama_set_name: RedPajamaStackExchange


text:
Q: angular material stepper: disable header navigation I want to navigate the stepper only through the next and back buttons.
I can't get this to work since users can also click each step label to navigate to any step. I can't use linear, since it requires each step to have a formArray or FormGroup.
I have tried <mat-step (click)="$event.stopPropagation()">.

A: Don't use ::ng-deep as it is deprecated.
https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep
Instead, if you are using Angular Material, use the theme guide from the documentation.
https://material.angular.io/guide/theming
Example of a implementation of the style:
my-custom-elements.scss
@import '~@angular/material/theming';

@mixin custom-stepper-theme() {
  .mat-horizontal-stepper-header {
    pointer-events: none;
  }
}

global-material-theme.scss
@import '~@angular/material/theming';
// Plus imports for other components in your app.

// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();

@import './material/my-custom-elements.scss';

@include custom-stepper-theme();

angular.json
...
"styles": ["src/styles.scss", "src/app/global-material-theme.scss"]
...

A: Use a linear stepper with completed=false steps. When the user presses your button, programattically complete the step and move to the next one.
This way you don't need to mess with CSS pointer events. In our app, that resulted in accessibility problems with NVDA.
    <mat-horizontal-stepper linear #stepper>
      <mat-step completed="false">
        <ng-template matStepLabel>Step 1</ng-template>
        <app-some-child (nextClicked)="nextClicked($event)" ></app-some-child>
      </mat-step>
      <mat-step>
        <ng-template matStepLabel>Step 2</ng-template>
        <app-some-other-child></app-some-other-child>
      </mat-step>
    </mat-horizontal-stepper>

    export class AppComponent implements OnInit {

      @ViewChild('stepper') stepper: MatStepper;

      nextClicked(event) {
        // complete the current step
        this.stepper.selected.completed = true;
        // move to next step
        this.stepper.next();
      }
    }

A: Does not work without ::ng-deep
    ::ng-deep .mat-horizontal-stepper-header{
      pointer-events: none !important;
    }

A: For anyone that's still looking for an alternate solution if ::ng-deep does not work.
Furthermore, ::ng-deep is deprecated and setting ViewEncapsulation to none is the preferred way to go if you want to do it using CSS.
Import ViewEncapsulation and set to None in your
compnent.ts:
import { Component, OnInit, ViewEncapsulation } from "@angular/core";

@Component({
  selector: "stepper-overview-example",
  templateUrl: "stepper-overview-example.html",
  styleUrls: ["stepper-overview-example.css"],
  encapsulation: ViewEncapsulation.None
})
export class StepperOverviewExample implements OnInit {
  isLinear = false;

  constructor() {}

  ngOnInit() {}
}

set pointer-events to none in your
component.css:
.mat-horizontal-stepper-header {
  pointer-events: none !important;
}

Here's a DEMO.

A: Just to improve on the accepted answer, as it will not work if you have a vertical stepper.
To stop the user being able to click the header and navigate add the following code to you style.css file in the root:-
.mat-step-header {
  pointer-events: none !important;
}

This will ensure it works for mat-horizontal-stepper-header and mat-vertical-stepper-header

A: I found a somewhat hacky solution for this. The problem is that you cannot fully disable the header navigation, but you can prevent it from being active until a certain moment.
And that moment is form.invalid.
My situation was the following: User needs to fill the form inside the step, press 'save' and only then be able to use NEXT button and navigate the stepper further (also back).
What I did was introduce another hidden input which would be using angular's [required] dynamic attribute. It will only be required if the previous save condition wasn't successful. Once it succeeds this field won't be required and user can navigate further.
Together with mat-stepper (or md-stepper) attribute editable you should be able to achieve what you want.
Let me know if you fully understood the idea.

A: Following works for me with click on previous step enabled:
::ng-deep .mat-vertical-stepper-header:not([ng-reflect-active="true"]){
    pointer-events: none !important;
}

For horizontal stepper do this:
::ng-deep .mat-horizontal-stepper-header:not([ng-reflect-active="true"]){
        pointer-events: none !important;
}

A: Add this to your style sheet. I was trying to disable the header navigation. Tried many things but this hack worked. You can try this till Angular Material Team support this feature.
::ng-deep .mat-horizontal-stepper-header{
    pointer-events: none !important;
}

A: This also did the trick for me
Requirement:

*

*Allow navigation either from Navigation or Next Button only WHEN form is valid

*Disabled Header navigation and keep button disabled till form is not valid.

 <mat-horizontal-stepper #stepper [linear]="true">

    <!----------------------------->
    <!---- STEP: 1:---->
    <!----------------------------->

    <mat-step #generalStep [completed]="formGroup1.valid">
      <ng-template matStepLabel>Step-1</ng-template>

      <form [formGroup]="formGroup1">

      // STEP-1 Content
      // matInput - with form control bindings

       <div class="container">
          <button mat-raised-button matStepperNext color="primary"[disabled]="!formGroup1.valid">Next Step</button>
        </div>

      </form>

    </mat-step>

    <!------------------------------->
    <!-- STEP: 2:-->
    <!------------------------------->

    <mat-step #generalStep [completed]="formGroup2.valid">
      <ng-template matStepLabel>Step-2</ng-template>

      <form [formGroup]="formGroup2">

      // STEP-2 Content
      // matInput - with form control bindings

      <button mat-raised-button matStepperNext color="primary"[disabled]="!formGroup.valid">Next Step</button>

      </form>
    </mat-step>

  </mat-horizontal-stepper>

*

*FormGroup/FormControl initialization

*Adding Validators

  formGroup1: FormGroup;
  formGroup2: FormGroup;

   this.formGroup1 = this.formBuilder.group({
      control1: new FormControl('', [Validators.required]),
      control2: new FormControl('', [Validators.required]),
    });

  this.formGroup1 = this.formBuilder.group({
    control3: new FormControl('', [Validators.required]),
    control4: new FormControl('', [Validators.required]),
  });

A: Here ::ng-deep .mat-horizontal-stepper-header-container {
        display: none ;
      }
Use this on your style sheet to remove stepper header...Like Step-1,Step-2

A: First you need add ViewEncapsulation.None in your component config
@Component({
 selector: 'app-example',
 encapsulation: `ViewEncapsulation.None`
 })

Then add this in your component CSS.
.mat-horizontal-stepper-header-container  {
  display: none !important;
 }

A: You need to add an "linear" attribute (This will disable navigation)
<mat-vertical-stepper linear>

A: In the  tag add [linear]="true"
<mat-horizontal-stepper labelPostion="botton" [linear]="true">
...
</mat-horizontal-stepper>


text:
Q: How to get Pages to automatically save documents as .docx files Is there a way to get Pages to automatically save documents as .docx (Word) files? How do you do it? I'm wondering because I do not have access to Microsoft Word and this is the preferred format for what I'm doing

A: Pages does not support saving as a Word .doc or .docx file.  Your only option is to Export your document to that format, which obviously isn't nearly as easy as simply hitting the Save button.
It's important to note that Pages support of .doc/.docx isn't perfect.  If the document has a lot of formatting or review comments, there's a pretty good chance of lost formatting or comments when you export your document.
A free alternative to purchasing Office:Mac is to use Office Online, which will happily run in Safari or Chrome on your Mac.  If this is a short-term need, you can download a free trial of Office:Mac.  If you have an iPad, there's a free version of Word for it too.  I realize that none of these are what you've asked about; I provide them in case an alternative to using Pages will work for you.

A: My answer may be not very helpful but I think there may be some script that after one click may convert the .pages file into doc or docx file, outside of the pages. Apple is trying to stick to it's own invented format, due to compatibility between Mac OS and iOS, so it is very unlikely that you would ever be able to do that.
Check this one out. I hope it helps:
https://discussions.apple.com/thread/5539968?tstart=0


text:
Q: Is it possible to update the data of a child when the Key is generated automatically by the Firebase? I'm trying to update a specific data when the key is automatically generated by Firebase.
I tried the code bellow. It still does not work :(
I've tried this :
  function updateHomeworkStatus(agent) {

    var chosenHw = request.body.queryResult.outputContexts[0].parameters.chosenHw;
    var status = request.body.queryResult.outputContexts[0].parameters.status;

    var query = admin.database().ref('Homework').orderByChild('Name').equalTo(chosenHw);
    query.once('value')
      .then(snapshot => {
        // Once we have a result, we can use the reference to it
        var snapshotRef = snapshot.ref;

        // We want to change the value of Completed field,
        // so we get a reference to that
        var completedRef = snapshotRef.child('CompletionStatus');

        // We can then set it, since we have a direct reference to the
        // field and there is nothing else that will be changed.
        completedRef.update(status);
      });

    agent.add("Status has been changed to " + status);

  }

For example (I've attach the picture of my firebase):
Dialogflow: What is the name of the homework that you want to change the
            CompletionStaus of? (I've done this)
and when the user says "Coding Worksheet 7" and the desired status "Yes",
the specific data will be changed. (I need hep for this coding part).
So the expected result will be that CompletionStatus of "Coding Worksheet 7" will be changed to "No".

A: The key problem with your current solution is that the Firebase RT Database calls are asynchronous and you are not waiting for these calls to return results before responding to your user.
Additionally, Firebase RT Database Queries will return a list/collection of results. So to look at the results of your query, you must use snapshot.forEach() to iterate over the returned data.
If you are going to use the update operation, update(), the parameter you pass into the function must be an object containing the 'path/to/value': value pairs. See this Firebase Blog post for further information. So for your code, you could update 'CompletionStatus' using `update({ CompletionStatus: status }) and not have to worry about using child() at all.
You also need to consider your error cases, such as non-existent files, duplicated names and Firebase RTDB errors. I have added the error-handling scaffold for these out below.
// somewhere near the top of your request handler
const RESULT_NOT_FOUND = -1;
const RESULT_DUPLICATED = -2;

function updateHomeworkStatus(agent) {
  var outputContext = request.body.queryResult.outputContexts[0];
  var chosenHw = outputContext.parameters.chosenHw;
  var status = outputContext.parameters.status;

  var query = admin.database().ref('Homework').orderByChild('Name').equalTo(chosenHw);

  // Remember to return the promise
  return query.once('value')
    .then(snapshot => {
      // "snapshot" is the query result, it's children contain the queried data

      if (!snapshot.hasChildren()) {
          throw RESULT_NOT_FOUND;
      } else if (snapshot.numChildren() != 1) {
          throw RESULT_DUPLICATED;
      }

      // init variable to store DatabaseReference
      var firstResultRef;

      // only one child at this point, so only called once
      snapshot.forEach(childSnapshot => {
        firstResultRef = childSnapshot.ref;
        return true; // stop looping
      });

      // Update 'CompletionStatus' with new value (using update() to protect existing data)
      // Remember to return the promise
      return firstResultRef.update({ CompletionStatus: status });
    })
    .then(() => { // Promise.then(successHandlerFunc, errorHandlerFunc)
      // success
      agent.add("Status has been changed to " + status);
    }, (err) => {
      // failure
      if (err === RESULT_NOT_FOUND) {
        agent.add("Sorry, I couldn't find '" + chosenHw + "'.");
      } else if (err === RESULT_DUPLICATED) {
        agent.add("Sorry, I found multiple files that match '" + chosenHw + "'.");
      } else {
        // if here, a database error has occurred.
        agent.add("Sorry, I could not process that request at this time.");
        // TODO: Log error "err".
      }
    });
}


text:
Q: Bash Script unwanted compute the key of an associative array ASS_ARR["20221005-130001"]="CIAO"
ASS_ARR["20221004-130001"]="TEST"

echo "${!ASS_ARR[@]}"

for KEY in "${!ASS_ARR[@]}"; do
  echo $KEY
done

Output of the Keys
# sh ./test.sh
20091003 20091004
20091003
20091004

Basicaly will subtract 130001 to 20221005
How can I avoid this behavior?

A: You need to declare the array as associative, otherwise it's a default indexed array where the index is evaluated in an arithmetic context.
declare -A ASS_ARR
ASS_ARR["20221005-130001"]="CIAO"
ASS_ARR["20221004-130001"]="TEST"

echo "${!ASS_ARR[@]}"

for KEY in "${!ASS_ARR[@]}"; do
  echo $KEY
done


text:
Q: Error for SKScene alloc In the SKScene gamescene I alloc the scene but it has an error message with No visible @interface with 'SKScene' declares the selector alloc.
I have think this means im not declaring it in my interface?? Corrections plz.
     -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];

// if play button touched, start transition to next scene
if ([node.name isEqualToString:@"play"]) {
    NSLog(@"play pressed");
    SKScene *GameScene = [[GameScene alloc] initWithSize:self.size];
    SKTransition *flip = [SKTransition flipVerticalWithDuration:1.0];
    [self.view presentScene:GameScene transition:flip];
   }
}

A: It looks like you are trying to create a variable that is the same name as the class!
SKScene *GameScene = [[GameScene alloc] initWithSize:self.size];

This is probably confusing the compiler. Change the variable name of *GameScene to something else and see if that works.


text:
Q: How to send Summer note content directly via email I need to send a mail with the summer note content,I'm using Code Igniter loadview method to render body of my mail but text content displaying images are not
Once i got the issue "transfer closed, bytes remaining to read" I jhave fixed this issue using this link
https://justrocketscience.com/post/php_guzzle_bug/
newsletterMail.php
<html>
<head>Mailer</head>
<?php echo $body; ?>
</html>

$view= $this->CI->load>view('admin_user/newsletterMail',$pageData,TRUE);

$headers=array(
            'Authorization: Bearer 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',
            'Content-Type: application/json'
        );

        $data=[
            "personalizations"=>[
                [
                    "to"=>$mailData['to']
                ]
            ],
            "from"=>[
                "email"=>"test@gmail.com"
            ],
            "subject"=>$subject,
            "content"=>[
                [
                    "type"=>"text/html",
                    "value"=>$body
                ]
            ]
        ];

$ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,"https://api.sendgrid.com/v3/mail/send");
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($data));
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_TCP_KEEPALIVE, 10);
        curl_setopt($ch,CURLOPT_TCP_KEEPIDLE, 10);
        $response= curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);

I need to show the content which I created in summer note in mail
Any solution?

A: Instead of using curl you can use default email functionality of codeigniter to send mail, also use SMTP protocol to send mail. Check below code to send mail.
function setProtocol(){
   $CI = &get_instance();

   $CI->load->library('email');

   $config = Array(
      'protocol' => 'smtp',
      'smtp_host' => 'smtp.googlemail.com',
      'smtp_port' => 465, //(Port: 465 (SSL required) or 587 (TLS required))
      'smtp_user' => '**************', //(your Gmail account (e.g. admin@gmail.com))
      'smtp_pass' => '**************', //(your Gmail password)
      'mailtype' => "html",
      'charset' => 'iso-8859-1',
      'wordwrap' => TRUE,
      'newline' => '\r\n',
    );

    $CI->email->initialize($config);

    return $CI;
 }

function newsletter(){
  $CI = setProtocol();

  $CI->email->from('admin@gmail.com');
  $CI->email->subject("Enter your subject");
  $CI->email->message($CI->load->view('admin_user/newsletterMail', $pageData, TRUE));
  $CI->email->to('user@gmail.com');
  $status = $CI->email->send();

  return $status;
}

You can use setProtocol() globally to send other emails also.


text:
Q: How can I display more than one row in a table in JSP? This is my Servlet code:
while(rs.next()){
    int questionId = rs.getInt("question_id");
    String questions = rs.getString("questions_name");
    String option1 = rs.getString("option1");
    String option2 = rs.getString("option2");
    String option3 = rs.getString("option3");
    String option4 = rs.getString("option4");
    String correctAns = rs.getString("correct_ans");

    request.setAttribute("questionId", questionId);
    request.setAttribute("questions", questions);
    request.setAttribute("option1", option1);
    request.setAttribute("option2", option2);
    request.setAttribute("option3", option3);
    request.setAttribute("option4", option4);
    request.setAttribute("correctAns", correctAns);
}

This is my DAO code:
 public ResultSet StartTest(Test passData) throws SQLException{
        Statement myStatement = getConnection();
        String query;
        query = "SELECT question_id, questions_name, option1, option2, option3, option4, correct_ans "
                + "FROM question WHERE courses_codes = '"+passData.getCourseCode()+"'"
                + "ORDER BY RAND()"
                + "LIMIT 5";
        rs = myStatement.executeQuery(query);
        return rs;
    }

JSP code:

        ${questions}${b}

        <input name="${questionId}" type="radio" value="${option1}" />${option1}${b}

        <input name="${questionId}" type="radio" value="${option2}" />${option2}${b}

        <input name="${questionId}" type="radio" value="${option3}" />${option3}${b}

        <input name="${questionId}" type="radio" value="${option4}" />${option4}${b}

        <input name="${questionId}" type="radio" value="${correctAns}" />${correctAns}${b}

A: Use this code in your servlet
HttpSession session=request.getSession();
Arraylist<Person>listPerson=daoPerson.getLisPersons();
        session.setAttribute("lsperson",listPerson);

Import jstl tag library in jsp page
 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

and put this code
   <c:forEach items="${lsperson}" var="person">

            ${person.name}
            ${person.lastName}
            ${person.age}

    </c:forEach>


text:
Q: Create ingress firewall rule for GKE API For testing purposes I want to make the GKE API endpoint publicly available.
However, I can't seem to be able to create a firewall rule to allow this.
I receive the error "source_ranges": conflicts with destination_ranges with the following terraform code to create it.
Any idea why I can't allow internet traffic but filter on destination IP?
Thanks.
resource "google_compute_firewall" "gke_api_allow" {
  name        = "gke-${var.cluster_name}-allow-firewall"
  project     = var.project_id
  network     = google_compute_network.gke_cluster_vpc.name
  description = "Main firewall that allows traffic to GKE cluster API public endpoint."

  priority  = 9
  direction = "INGRESS"

  allow {
    ports = [443]
    protocol = "tcp"
  }

  destination_ranges = ["${google_container_cluster.gke_cluster.endpoint}/32"]
  source_ranges = ["0.0.0.0/0"]

  log_config {
    metadata = "INCLUDE_ALL_METADATA"
  }
}

A: Google Kubernetes Engine (GKE) automatically creates firewall rules in Google Cloud.

Warning: Do not modify or delete firewall rules created by GKE, or you might encounter unexpected behavior in your clusters.

The priority for all automatically created firewall rules is 1000, which is the default value for firewall rules. If you would like more control over firewall behavior, you can create firewall rules with a higher priority. Firewall rules with a higher priority are applied before automatically created firewall rules.
GKE creates the following ingress firewall rule when creating a Service.
Name: k8s-fw-[loadbalancer-hash]

Purpose: Permits ingress traffic to reach a Service.

Source: Specified in the Service manifest. Defaults to 0.0.0.0/0 (any source)

Destination: Node tag

Protocol and ports: TCP and UDP on the ports specified in the Service manifest.

There is a similar issue with a provided workaround.


text:
Q: How do I return the values of searched items in powershell instead of the object? How do I fix this issue?
I am working on a code that will copy all of a single filetype (ie. txt, jpg, etc) to a single location so that I can suss out duplicates and manipulate them in one place. I was finally able to list all the physical drives but the systemroot, search each drive recursively for the files, and list them.
Example below:
 #TFT  - This File Type
    #This bit find all hard drives and jump drives, lists files of the extension given
    #and returns that list of files.

    function tft($ext){
        $thisvalue = ($ext)
        $just_drives = @(get-psdrive |where root -Like '*`:`\'|where  Used* -gt ''|where name -NE 'c')

    if($ext -notlike '`*.*'){$ext='*.'+$ext}

    $a=foreach($jd in $just_drives){set-location -path $jd.Root;gci $ext -Recurse -Force -ErrorAction SilentlyContinue|where fullname -NotLike '*RECYCLE.BIN*'|ft fullname -autosize -HideTableHeaders

    }}
PS:>tft ttf

and the result of it is
PS:>$a [enter]
    [truncated for space]
    E:\$WINDOWS.~BT\Windows\Boot\Fonts\chs_boot.ttf
    E:\$WINDOWS.~BT\Windows\Boot\Fonts\cht_boot.ttf
    E:\$WINDOWS.~BT\Windows\Boot\Fonts\jpn_boot.ttf
    E:\$WINDOWS.~BT\Windows\Boot\Fonts\kor_boot.ttf
    E:\$WINDOWS.~BT\Windows\Boot\Fonts\malgunn_boot.ttf
    ...
    H:\WINX21H2\efi\microsoft\boot\fonts\segoe_slboot.ttf
    H:\WINX21H2\efi\microsoft\boot\fonts\wgl4_boot.ttf
    H:\WINX21H2\sources\segoeui.ttf

Awesome! Code worked perfectly.
Well... Until I try to manipulate that listing.
    PS:> write-host $a -join(',')
        Microsoft.PowerShell.Commands.Internal.Format.FormatStartData,Microsoft.PowerShell.Commands.Internal.Format.GroupStartData,Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData,Microsoft.PowerShell.Commands.Internal.Format...
PS:> $a|copy-item d:\
copy : The input object cannot be bound to any parameters for the command either because the command does not take
pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At line:1 char:4
+ $a|copy d:\
+    ~~~~~~~~
    + CategoryInfo          : InvalidArgument: (Microsoft.Power...FormatStartData:PSObject) [Copy-Item], ParameterBin
   dingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.CopyItemCommand....
... for 337K+ lines!!!

Long winded, I know and it may have been answered elswhere but for all my searches I could not find the key. Everything I try returns the object and not the text.

A: Looks to me like the final pipeline item you have is an ft, so the output object is a formatted table, not the objects you want.
I'd remove this and give it another go:
|ft fullname -autosize -HideTableHeaders


text:
Q: How London dispersion forces come into existence out of nowhere? I was revisiting the chapter on states of matter and one thing that bothered me was a section on London dispersion forces. This is what the textbook says:

Atoms and nonpolar molecules are electrically symmetrical and have no dipole moment because their electronic charge cloud is symmetrically distributed. But a dipole may develop momentarily even in such atoms and molecules. This can be understood as follows.
  Suppose we have two atoms A and B in the close vicinity of each other. It may so happen that momentarily electronic charge distribution in one of the atoms, say A, becomes unsymmetrical i.e., the charge cloud is more on one side than the other. This results in the development of instantaneous dipole on the atom A for a very short time. This instantaneous or transient dipole distorts the electron density of the other atom B, which is close to it and as a consequence a dipole is induced in the atom B.

Now since I don't have any further knowledge of quantum mechanics (than what was taught in the introductory chapter on it) therefore it bothers me a lot as to

*

*why does a symmetrical atom may turn unsymmetrical out of nowhere?

If so it happens that an unsymmetry appears instantaneously and goes soon then there must be a cause for it. So

*

*what causes this unsymmetry?

A: Nothing. The atomic cloud ( electron distribution) is probabilistic in nature.  Untertainty in charge distribution causes polarization

A: The explanation of the force as due to oscillating dipoles is only an approximate description and should be regard only as a guide for students. The actual explanation is that the wavefunctions of the two atoms overlap and the system now needs to be described by a larger wavefunction that includes the electrons in both atoms.
In principle this new wavefunction could be calculated directly by numerical methods, but as computers were not available to London in 1930 he did the calculation using perturbation theory. In any case, the energy of the new wavefunction is slightly lower than the energies of the two atoms when separated to infinity, so we find there is a small attractive force between the atoms. For more on this see the Wikipedia article on the subject.
I will stick my neck out and suggest that we can justify the oscillating dipole explanation as follows:
When the two atoms are separated to infinity the electrons in them are in eigenstates of the Hamiltonian and these eigenstates are time independent i.e. there are no oscillations in their charge densities.
However when we bring the atoms together the interaction between them changes the eigenstates so the electrons in the atoms are no longer in eigenstates but would be in a superposition of the eigenstates. In general a superposition of energy eigenstates is not time independent and such superpositions will have oscillations in the charge density. These oscillations will generate the fluctuating electric dipoles used in the heuristic description of the force.
So if you look at the situation this way it is the interaction between the two atoms, i.e. the electrostatic forces between the electrons and nucleus in atom A with the electrons and nucleus in atom B, that causes the oscillating dipoles to appear.


text:
Q: Workflow Get value from web service response I have called a web service in SP designer and the response is something like

{"odata.metadata":"https://cloud.sharepoint.com/sites//_api/$metadata#SP.ListData.ParametersList","value":[{"odata.type":"SP.Data.ParametersList","odata.id":"XXXX-XXXX-XX-XXXX-XXXXXXXX","odata.etag":"\"2\"","odata.editLink":"Web/Lists(guid'XXXXX-XXXX-XXX-XXXX-XXXXXXXX')/Items(30)","FileSystemObjectType":0,"Id":30,"ContentTypeId":"XXXXXXXXXXXXXXXXX","Title":"targetTitle","Value":"targetgetvalue_123","ID":24,"Modified":"2015-12-29T07:45:26Z","Created":"2015-12-30T07:45:13Z","AuthorId":20,"EditorId":20,"OData__UIVersionString":"1.0","Attachm>ents":false,"GUID":"XXXXXX-XXXXX-XXXX-XXXX-XXXXXX"}]}

I tried to use Get value from dictionary in Sharepoint designer to obtain Value
, but the result is not as expected. How to get the Value. i.e  (targetgetvalue_123).

A: It`s bit tricky. Here is sample from designer:
Get d/results([%Variable: index%])/ID from Variable: JsonResult (Output to Variable: OutID )

index is just number from 0 to Item count


text:
Q: как передать значение $scope из функции в другой $scope вне этой функции   .controller("PostsCtrl",
    function($scope, $http) {
      $http
        .jsonp('https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://www.nbrb.by/RSS/?p=RatesDaily&callback=JSON_CALLBACK')
        .then(function(data, status, headers, config) {
          var str, usd;
          str = data.data.responseData.feed.entries[0].contentSnippet;
          usd = str.match(/.+Доллар США (.+) Российский рубль.*/)[1].replace(/[\s,]/g, '') / 100;
          $scope.ByBankUSD = usd;
        });

      $scope.newscope = ???;
    }
  );

подскажите как мне $scope.ByBankUSD передать в $scope.newscope

A: Нашел решение для данной проблемы удобное лично для меня.
Нужно создать до запроса $scope, собственно как у вас и есть.
В .then необходимый для вас результат можно передать за ее пределы .push
То есть:
.controller("PostsCtrl",
    function($scope, $http) {

      /* переменные используемые в асинхронных запросах
         нужно всегда объявлять в контроллере, до их использования */
      $scope.ByBankUSD = '';
      $http
        .jsonp('https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://www.nbrb.by/RSS/?p=RatesDaily&callback=JSON_CALLBACK')
        .then(function(data, status, headers, config) {
          var str, usd;
          str = data.data.responseData.feed.entries[0].contentSnippet;
          usd = str.match(/.+Доллар США (.+) Российский рубль.*/)[1].replace(/[\s,]/g, '') / 100;

          $scope.ByBankUSD.push(usd);

        });

      console.log($scope.ByBankUSD)
    }
  );

Я пользуюсь таким способом. Работает отлично!

A: .controller("PostsCtrl",
    function($scope, $http) {

      /* переменные используемые в асинхронных запросах
         нужно всегда объявлять в контроллере, до их использования */
      $scope.ByBankUSD = '';
      $http
        .jsonp('https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://www.nbrb.by/RSS/?p=RatesDaily&callback=JSON_CALLBACK')
        .then(function(data, status, headers, config) {
          var str, usd;
          str = data.data.responseData.feed.entries[0].contentSnippet;
          usd = str.match(/.+Доллар США (.+) Российский рубль.*/)[1].replace(/[\s,]/g, '') / 100;
          $scope.ByBankUSD = usd;
        });

      $scope.$watch('ByBankUSD', function (newValue, oldValue){
          $scope.newscope = newValue;
      });
    }
  );

PS. Не проверял, но должно быт так (когда то писал такое уже). И почему ты не хочешь сразу присваивать ByBankUsd нужной переменной в $scope. Если нужно передать в корень своего модуля, то передавать нужно в $rootScope. Там он будет доступен во всех контроллерах подключенных к модулю.


text:
Q: I want to read android play store app rating in my android app I want to read app rating from android play store of my app. To do this, is there any api provided by google or not?
Is there any other way to read rating of particular app?

A: You can try out Android Market API, as this is the unofficial API, i am not sure it will work fully.
To fetch Rating of a particular app, try HowToSearchApps from the same API.


text:
Q: Acceptance test Redirecting to specific URL I created an Acceptance test on ember-cli, in order to check when a user is on a URL and then clicks on the "Cancel" button on that page, the page should be redirected to other URL.
When running the test I'm getting this error:

"Promise rejected during Redirects to previous URL if cancel button is
  clicked: Element .close-button not found".

But I have that element on my template. Could someone suggest me what I'm missing here or suggest me a documentation I can read in order to solved this error?.
This is my acceptance test:
import { test } from 'qunit';
import moduleForAcceptance from '/tests/helpers/module-for-acceptance';

moduleForAcceptance('Acceptance | test/company');
test('Redirects to previous URL if cancel button is clicked', function() {
    return visit('test/company/add').then(function(){
      return click('.close-button');
    }).then(function(assert){
      assert.equal(currentURL(), 'test/company');
    });
});

I tried this test too, but I keep getting similar error:
test('Redirects to previous URL if cancel button is clicked', function(assert) {
  visit('/test/company/add');
  click ('.close-button');
  andThen(function() {
    assert.equal(currentURL(), '/test/company');
  });
});

This is the error:

Error: Element .close-button not found.

This is part of the template where I have the cancel button( add.hbs)

    Close

This is the controller, where the action 'cancel' is defined:
actions: {
    cancel() {
       if (this.get('isSaved')) {
           return;
       }
         this.transitionToRoute('test/company');
    }
}

A: Visit and click are the test helpers which will return a promise.Usually you will execute the further testing once your promises are resolved.
Try doing this:
test('Redirects to previous URL if cancel button is clicked', function(assert) {
  visit('/test/company/add');
  andThen(()=>{
    click ('.close-button');
    andThen(()=>{
        assert.equal(currentURL(), '/test/company');
    })
  });
});


text:
Q: How to make an element disappear after scrolling? I have a custom icon element that is only displayed when its specific row in the table is hovered over, but when I scroll down without moving my mouse it doesn't update the hover and maintains the button on the screen and over my table's header. How can I make sure this doesn't happen?

export const StyleTr = styled.tr`
  z-index: ${({ theme }) => theme.zIndex.userMenu};
  &:hover {
    background-color: ${({ theme, isData }) =>
      isData ? theme.colors.primary.lighter : theme.colors.white};
    div {
      visibility: visible;
    }
    svg[icon] {
      display: initial;
    }
  }
`;

A: I was just working on something similar to this for a web scraper recently.
Something like this should work:

function checkIfIconInViewport() {
// define current viewport (maximum browser compatability use both calls)
const viewportHeight =
window.innerHeight || document.documentElement.clientHeight;

//Get our Icon
let icon = document.getElementById('icon');
let iPos = icon.getBoundingClientRect();

//Show if any part of icon is visible:
if (viewportHeight - iPos.top > 0 && iPos.bottom > 0) {
  icon.style.visibility = visibile;
}
else { icon.style.visibility = hidden; }

//Show only if all of icon is visible:
if (iPos.bottom > 0 && iPos.top >= 0) {
{
  icon.style.visibility = visibile;
}
else { icon.style.visibility = hidden; }

//Add && iPos.bottom <= viewportHeight to the if check above for very large elements.
{

//Run function everytime that the window is scrolled.
document.addEventListener('scroll', checkIfIconInViewport);

Basically, every time a scroll event happens, we just check to see if the top & bottom of our element (the icon in your case) are within the bounds of the viewport.
Negative values, or values greater than the viewport's height mean that the respective portion of the element is outside the viewport's boundary.
Hopefully this helps! If you are dealing with a large quantity of objects, it may make sense to bundle the objects you are tracking together into an array and check each of them in a single function call to avoid saving function definitions for each individual object.
Edit: I just realized that I misunderstood your issue a bit. I think you can get by with just the bottom part of the code, and when a scroll event happens, set the icon's visibility to hidden. Assuming you want to hide it whenever the user scrolls?

A: Have you tried getting the scroll position of the DOM, then disabling (removing) the element once a certain scroll position is reached?


text:
Q: What is the average rotation angle needed to change the color of a sphere? A sphere is painted in black and white. We are looking in the direction of the center of the sphere and see, in the direction of our vision, a point with a given color. When the sphere is rotated, at the end of the rotation we might see the same or a different color.
The coloring of the sphere is given; we know how the white and black color is distributed. The coloring is also "nice" (no fractals); the black patches have borders that are smooth and infinitely differentiable curves. How can I calculate the average angle required to change from black to white?
The question is very general. So a simple sub-case would be: if one hemisphere of the sphere is black, the other is white, and if one starts in a situation where the random starting point is black, what would the average angle be?
Starting from this subcase, what would be the way to calculate the average angle for a general black-and-white coloring?

A: If one hemisphere is black and the other white, choose spherical coordinates such that the border between the colours is at the equator. Then the rotation angle required to change colours is $|\theta|$, where $\theta$ is the latitude. So the average angle is
$$\frac{\int_{-\pi/2}^{\pi/2}|\theta|\cos \theta\mathrm d\theta}{\int_{-\pi/2}^{\pi/2}\cos \theta\mathrm d\theta}= \int_0^{\pi/2}\theta\cos\theta\mathrm d\theta=\left[\theta\sin\theta+\cos\theta\right]_0^{\pi/2}=\frac{\pi}{2}-1\;.$$
I don't see how anything useful could be said about the general case.

A: For the general case you can define a function that assigns to each point on the sphere the distance (angle) to the nearest boundary.
The desired number is then the integral of this function over the whole sphere (see example by Joriki).
For the sphere, we can consider, for example, circular regions (a hemisphere is a special case).
Inside a small circular region (cap) the distance function looks like a little cone, centered at the center of the circle.
If the black (and therefore also the white) regions are made up of unions, intersection or differences of caps the distance function can be constructed from the distance functions for each of the caps.
Note that the colors are irrelevant.
The only thing that matters is the distance to the nearest boundary.
All you need is the list of circles.
Performing the integration exactly would not be easy.
The case of two non-overlapping caps is doable (non-intersecting circles).
For a set of circles that is not too large, you could use Monte Carlo integration (for a random set of points, average the distance to the nearest circle).
Easy to implement, but not very efficient.
Monte Carlo would also work for more general cases.
You could consider intersections of hemispheres as the equivalent of polygons on a sphere.
So the ideas described above apply to the case of "polygonal" regions on the sphere.
If you approximate your boundary by a discrete set of points you can probably use a Voronoi diagram.
Note that this kind of question is much easier to think about on a unit square (with periodic boundary conditions) or easier still on a unit interval (with periodic boundary conditions).
In the latter case, the distance function for an arbitrary partition is made up of "hats" with slopes of 1 and -1.
The integration is easy to perform in this case.
http://en.wikipedia.org/wiki/Signed_distance_function
http://en.wikipedia.org/wiki/Medial_axis


text:
Q: Why does SELECT ... WHERE id = a returns a result if value is 0 Table preview
Note: 'id' is an integer column (offcourse)

+-------------+
| id | value  |
+----+--------+
| 0  | abc    |
| 1  | def    |
+-------------+

Queries:
1. Returns abc: SELECT value FROM table WHERE id = 0
2. Returns def: SELECT value FROM table WHERE id = 1
3. Returns nothing: SELECT value FROM table WHERE id = 2
4. Returns abc: SELECT value FROM table WHERE id = 'a'
The question: Why does query 4 returns abc? It should give no results right?

A: MySQL silently converts strings to numbers in a numeric context.
It does so by converting the leading numeric characters (such as digits, minus sign, and decimal point).
If there are no digits, it stops.  So:
where id = 'a'

is interpreted as:
where id = 0

Moral:  Never use single quotes around numeric constants -- or constants that should be numbers.


text:
Q: Print images in body field content to node template file In my node-page.tpl.php I print:
<?php print $node->content['body']['#value']; ?>
However, it doesn't display all body content, it does display all text entered, I use TinyMCE WYSIWYG editor to insert inline images.
Visually, editing the node, the images appear in the editor, so I wrote text before and after the image disabling the rich-text editor, and the text before and after the image appears.
Viewing the source there's no <img> tags at all.
The images are uploaded to /sites/default/files/
How can I print the images?

A: Try
<?php print $content; ?>


text:
Q: How to get the `html` element in Javascript? I want to get the html element in Javascript.  I can now use document.body.parentNode or document.getElementsByTagName("html").  But I think there should be a simple, "right" way to do it.
So, what's the right way to get the html element in Javascript?
I tried to use search engines, but I don't know how to tell them the html tag is different from any other HTML tag, so it yielded no result I wanted.

A: You can use:
document.documentElement

which points to the document's root html node.
https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement

A: Chek this answer

https://stackoverflow.com/a/22873490/3134112

reference:

https://developer.mozilla.org/en-US/docs/Web/API/Document.documentElement.

A: I'd say document.getElementsByTagName, querySelector etc. are all "right ways" to get reference to html tag, it doesn't get simpler than that.


text:
Q: Gradle build succeeds in local, but builds fail in Docker Gradle build succeeds in local, but builds fail in Docker.
The following error occurs during gradle build in docker:
java.rmi.UnmarshalException: Error unmarshaling return header; nested exception is:
    java.io.EOFException
    at java.rmi/sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:254)
    at java.rmi/sun.rmi.server.UnicastRef.invoke(UnicastRef.java:164)
    at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:217)
    at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:162)
    at com.sun.proxy.$Proxy110.compile(Unknown Source)
    at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.incrementalCompilationWithDaemon(GradleKotlinCompilerWork.kt:290)
    at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.compileWithDaemon(GradleKotlinCompilerWork.kt:213)
    at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.compileWithDaemonOrFallbackImpl(GradleKotlinCompilerWork.kt:151)
    at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.run(GradleKotlinCompilerWork.kt:130)
    at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:173)
    at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:168)
    at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runJvmCompilerAsync(GradleKotlinCompilerRunner.kt:87)
    at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompilerAsync$kotlin_gradle_plugin(Tasks.kt:541)
    at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompilerAsync$kotlin_gradle_plugin(Tasks.kt:465)
    at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.executeImpl(Tasks.kt:387)
    at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:351)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:104)

It seems to be caused by the lack of memory in gradle daemon.
My gradle.properties is as follows.
org.gradle.jvmargs=-XX:MaxMetaspaceSize=1024m -XX:+HeapDumpOnOutOfMemoryError -Xmx2g

My Dockerfile is as follows.
...
RUN gradlew build -Dspring.profiles.active=${PHASE}
...

It's the same gradle memory setting,
but why does it succeed in local and fail in docker?


text:
Q: Android TextView styles I'm trying to set styles for TextView control. I am able to add either user defined style or system style. But I can't set both for my TextView. I want to display TextView like button style and I have to add width and height.
My Layout code is:
<TextView
    android:id="@+id/trans_payable"
    <-- style="@android:style/Widget.Button" -->
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="left"
    android:clickable="true"
    android:paddingLeft="10sp"
    android:paddingTop="20sp"
    android:paddingRight="50sp"
    style="@style/transactionbtn"
    android:text="@string/trans_payable" >
</TextView>

And my style.xml code is:
<style name="transactionbtn">
    <item name="android:width">140dp</item>
    <item name="android:height">45dp</item>
    <-- How to add button style here -->
</style>

A: Your style can inherit another style, e.g. a style from the Android resources.
    <style name="Button" parent="@android:style/Widget.Button">
        .
        .
        .
    </style>

Change the parent to @android:style/Widget.Holo.Button for Holo style.


text:
Q: Free idempotent monad associated to a monad Let $C$ be a category. There is a full subcategory $\text{IdemMnd}(C) \hookrightarrow \text{Mnd}(C)$ of the category of monads on $C$ spanned by the idempotent monads. Given a monad $T$ on $C$, suppose we wish to construct an idempotent monad $\hat T$ on $C$ associated to $T$. There are two ways by which we might consider doing so.

*

*Considering the value at $T$ of a left adjoint to the inclusion $\text{IdemMnd}(C) \hookrightarrow \text{Mnd}(C)$ (the free idempotent monad).

*Considering the value at $T$ of a right adjoint to the inclusion $\text{IdemMnd}(C) \hookrightarrow \text{Mnd}(C)$ (the cofree idempotent monad).

The second case is well-studied: for instance, it is studied by Fakir in Monade idempotente associée à une monade.
Has the first case been studied in the literature? (Alternatively: is there a good reason it has not?) I spell out the universal property we expect of $\hat T$ below, to make it easier to compare with reformulations that may appear.

Let $T$ be a monad on $C$. The free idempotent monad on $T$, denoted $\hat T$ when it exists, is an idempotent monad on $C$ equipped with a monad morphism $\tau : T \to \hat T$ such that for every idempotent monad $T'$ on $C$ and monad morphism $\phi : T \to T'$, there exists a unique monad morphism $\hat\phi : \hat T \to T'$ such that $\hat\phi \circ \tau = \phi$.
We may rewrite this in terms of the categories of algebras as follows: for every functor $F : T'\text{-Alg} \to T\text{-Alg}$ commuting with the forgetful functors, there exists a unique functor $\hat F : T'\text{-Alg} \to \hat T\text{-Alg}$ commuting with the forgetful functors such that $\tau\text{-Alg} \circ \hat F = F$.

A: What follows is a long comment, and because the question is asking for a reference, it is also an irrelevant comment.

Anyhow, the whole idea behind the Fakir construction is to build on a characterisation of idempotent monads.
Prop.
A monad $T$ is idempotent iff $T\eta, \eta T: T \to T^2$ are the same arrow.
Following this characterisation, Fakir thought that an intelligent way to make a monad idempotent was to take the equalizer $T_1$ of $T\eta$ and $\eta T$,$$ T_1 \hookrightarrow T \rightrightarrows T^2. $$ Now $T_1$ is a monad, but it might not be idempotent (yet), so we have to transfinitely iterate this procedure and hope that it converges at some point.
So, if I would have to guess a dual construction, I would take the coequalizer,
$$T \rightrightarrows T^2 \twoheadrightarrow T_1.$$
The key thing to check is that $T_1$ still produces a monad. It is clear that we have a unit $1 \to T \to T_1$. Concerning the multiplication, that is a bit more delicate and one should dualize the argument discussed here. I could believe it works, but a gut feeling prevents me from true optimism.


text:
Q: JavaFX Canvas not resizing correctly inside StackPane Below is the Main.class and the Controller.class , i tried to make it as simpler as possible.
The program outputs the below window:

The black is a StackPane named visualizerStackPane and inside it is a Canvas named visualizerCanvas . What i want to do is the Canvas inside the StackPane to be resized accordingly to the StackPane size substract 4 . But everything fails when you resize the window.
What you have to try...
1)Maximize the window and then normalize it back.
2)Increase the size of the window and slowly decrease it back.
Why this is happening?I have this problem 3 months now and i can't find a solution...
I have also looked JavaFX - Resize Canvas when screen is resized but the problem here seems to be different...

Main.java:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {

            //Scene
            Scene scene = new Scene(new Controller(), 400, 400);
            primaryStage.setScene(scene);

            //Show
            primaryStage.show();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Controller.java:
I have modified the Controller class to paint the Canvas and removed the bindings from Initialize method , it doesn't work it produces the below:

If i don't set the width and height of the Canvas manually it doesn't even get painted...I don't know why .
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;

public class Controller extends StackPane {

    @FXML
    private GridPane container;

    @FXML
    private GridPane topGridPane;

    @FXML
    private StackPane visualizerStackPane;

    @FXML
    private Canvas visualizerCanvas;

    @FXML
    private VBox topRightVBox;

    @FXML
    private StackPane mediaFileStackPane;

    @FXML
    private GridPane bottomGridPane;

    // ------------------------------

    GraphicsContext gc;
    int             canvasWidth     = 0;
    int             canvasHeight    = 0;

    /**
     * Constructor
     */
    public Controller() {

        // ------------------------FXMLLoader ---------------------------------
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Controller.fxml"));
        loader.setController(this);
        loader.setRoot(this);

        try {
            loader.load();
        } catch (IOException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Controller FXML can't be loaded!", ex);
        }
    }

    /**
     * Called as soon as FXML FILE has been loaded
     */
    @FXML
    private void initialize() {

        gc = visualizerCanvas.getGraphicsContext2D();

        // // VisualizerStackPane inside which visualizerCanvas is
        // visualizerCanvas.widthProperty().bind(visualizerStackPane.widthProperty().subtract(4));
        // visualizerCanvas.heightProperty().bind(visualizerStackPane.heightProperty().subtract(4));
        //

        // Add width and height change listeners
        visualizerStackPane.widthProperty().addListener((observable, oldValue,
                newValue) -> resizeVisualizerCanvas(newValue.doubleValue(), visualizerStackPane.getHeight()));

        visualizerStackPane.heightProperty().addListener((observable, oldValue,
                newValue) -> resizeVisualizerCanvas(visualizerStackPane.getWidth(), newValue.doubleValue())

        );

        repaintCanvas();
    }

    /**
     * Repaints the Canvas
     */
    public void repaintCanvas() {

        //Clear the previous rectangle
        gc.clearRect(0, 0, canvasWidth, canvasHeight);

        // Draw the
        gc.setFill(Color.RED);
        gc.fillRect(0, 0, canvasWidth, canvasHeight);

        // Draw the Line
        gc.setLineWidth(3);
        gc.setStroke(Color.WHITE);
        gc.strokeLine(0, canvasHeight, canvasWidth, 0);

    }

    /**
     * Resizes the visualizerCanvas to the given values.
     *
     * @param width
     *            the width
     * @param height
     *            the height
     */
    public void resizeVisualizerCanvas(double width, double height) {
        if (width > 0 && height > 0) {

            this.canvasWidth = (int) width;
            this.canvasHeight = (int) height;

            // Print something
            System.out.println("Canvas Width is:" + width+" , Canvas Height is:"+height +" Canvas is Resizable: "+visualizerCanvas.isResizable());

            // Repaint the Canvas
            repaintCanvas();

            // ---------------------------Below i have tried several things to
            // solve the problem....

            // Set the width and height of Canvas
            visualizerCanvas.setWidth(width);
            visualizerCanvas.setHeight(height);

            // Careful with contentBias here
            prefWidth(-1);
            prefHeight(-1);

            // autosize()

            // System.out.println("Content Bias is:"+this.getContentBias())

        }
    }
}

Controller.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.canvas.Canvas?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.Region?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.layout.VBox?>

<fx:root prefHeight="212.0" prefWidth="456.0" type="StackPane" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <padding>
      <Insets bottom="2.0" left="2.0" right="2.0" top="2.0" />
   </padding>
   <children>
      <GridPane fx:id="container">
        <columnConstraints>
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" percentWidth="50.0" prefWidth="100.0" />
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" percentWidth="50.0" prefWidth="100.0" />
        </columnConstraints>
        <rowConstraints>
          <RowConstraints minHeight="10.0" percentHeight="40.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" percentHeight="60.0" vgrow="SOMETIMES" />
        </rowConstraints>
         <children>
            <GridPane fx:id="topGridPane" gridLinesVisible="true" GridPane.columnSpan="2">
              <columnConstraints>
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" percentWidth="50.0" prefWidth="100.0" />
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" percentWidth="50.0" prefWidth="100.0" />
              </columnConstraints>
              <rowConstraints>
                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
              </rowConstraints>
               <children>
                  <StackPane fx:id="visualizerStackPane" style="-fx-border-color: white; -fx-border-width: 1.5; -fx-background-color: rgb(0,0,0,0.95);">
                     <children>
                        <Canvas fx:id="visualizerCanvas" />
                     </children>
                  </StackPane>
                  <VBox fx:id="topRightVBox" GridPane.columnIndex="1">
                     <children>
                        <StackPane prefHeight="150.0" prefWidth="200.0">
                           <children>
                              <Region style="-fx-background-color: rgb(255,255,255,0.7);" />
                              <Label alignment="CENTER" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" style="-fx-font-weight: bold;" text="text here" />
                           </children>
                        </StackPane>
                        <StackPane fx:id="mediaFileStackPane" maxWidth="1.7976931348623157E308" />
                     </children>
                  </VBox>
               </children>
            </GridPane>
            <GridPane fx:id="bottomGridPane" gridLinesVisible="true" GridPane.columnSpan="2" GridPane.rowIndex="1">
              <columnConstraints>
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" percentWidth="20.0" prefWidth="35.0" />
                <ColumnConstraints halignment="CENTER" hgrow="SOMETIMES" minWidth="10.0" percentWidth="60.0" prefWidth="343.0" />
                  <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" percentWidth="20.0" prefWidth="52.0" />
              </columnConstraints>
              <rowConstraints>
                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
              </rowConstraints>
               <children>
                  <StackPane prefHeight="150.0" prefWidth="200.0" GridPane.columnIndex="2">
                     <children>
                        <Region style="-fx-background-color: rgb(255,255,255,0.7);" />
                        <Label alignment="CENTER" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" style="-fx-font-weight: bold;" text="text here" textAlignment="CENTER" wrapText="true" StackPane.alignment="CENTER" />
                     </children>
                  </StackPane>
                  <VBox prefHeight="200.0" prefWidth="100.0" spacing="5.0" />
               </children>
            </GridPane>
         </children>
      </GridPane>
   </children>
</fx:root>

Finally:

A big thanks to the person who will manage to solve this problem :).

A: Remove the binding from your initialize() method. You are attempting to take control of layout operations yourself, which stop StackPane doing what it is supposed to do. This will resize the Canvas appropriately.
You state that when you print the width and height of the Canvas, it returns -1. Instead of doing this, print the width and height of the container StackPane. Since Canvas is, after all, contained fully within the StackPane, then the width and height will be almost identical, if not identical.

A: After research i have found the solution . Creating a custom Canvas class and @Overriding methods from Canvas:

Very glad from the final answer on this question: How to make canvas Resizable in javaFX?
A link that gave me the idea: http://dlsc.com/2014/04/10/javafx-tip-1-resizable-canvas/

ResizableCavas.java :
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;

class ResizableCanvas extends Canvas {

    GraphicsContext gc                  = getGraphicsContext2D();
    int             canvasWidth         = 0;
    int             canvasHeight        = 0;
    int             halfCanvasHeight    = 0;

    /**
     * Constructor
     */
    public ResizableCanvas() {

        // if i didn't add the draw to the @Override resize(double width, double
        // height) then it must be into the below listeners

        // Redraw canvas when size changes.
        widthProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("Entered WIDTH property");
            canvasWidth = (int) widthProperty().get();
        });
        heightProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("Entered HEIGHT property");

            canvasHeight = (int) heightProperty().get();
            halfCanvasHeight = canvasHeight >> 1;
        });

    }

    /**
     * Redraw the Canvas
     */
    private void draw() {

        System.out.println(" Real Canvas Width is:" + getWidth() + " , Real Canvas Height is:" + getHeight() + "\n");

        gc.clearRect(0, 0, canvasWidth, canvasHeight);

        gc.setStroke(Color.RED);
        gc.strokeLine(0, 0, canvasWidth, canvasHeight);
        gc.strokeLine(0, canvasHeight, canvasWidth, 0);
    }

    @Override
    public double minHeight(double width) {
        return 1;
    }

    @Override
    public double maxHeight(double width) {
        return Double.MAX_VALUE;
    }

    @Override
    public double prefHeight(double width) {
        return minHeight(width);
    }

    @Override
    public double minWidth(double height) {
        return 1;
    }

    @Override
    public double maxWidth(double height) {
        return Double.MAX_VALUE;
    }

    @Override
    public boolean isResizable() {
        return true;
    }

    @Override
    public void resize(double width, double height) {
        super.setWidth(width);
        super.setHeight(height);
        draw();
    }
}

Controller.java:
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javafx.beans.property.SimpleIntegerProperty;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;

public class Controller extends StackPane {

    @FXML
    private GridPane container;

    @FXML
    private GridPane topGridPane;

    @FXML
    private StackPane visualizerStackPane;

    @FXML
    private VBox topRightVBox;

    @FXML
    private StackPane mediaFileStackPane;

    @FXML
    private GridPane bottomGridPane;

    // ------------------------------

    ResizableCanvas visualizerCanvas = new ResizableCanvas();

    /**
     * Constructor
     */
    public Controller() {

        // ------------------------FXMLLoader ---------------------------------
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Controller.fxml"));
        loader.setController(this);
        loader.setRoot(this);

        try {
            loader.load();
        } catch (IOException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Controller FXML can't be loaded!", ex);
        }
    }

    /**
     * Called as soon as FXML FILE has been loaded
     */
    @FXML
    private void initialize() {

        visualizerStackPane.getChildren().add(visualizerCanvas);

    }
}


text:
Q: Get Ip from Steam Game Server? Is there a way to determine the Ip of a specific game server via Steam's WEB API? I have already asked Steam, they just said that the support will not help me. The reason for my question is that I am writing a Discord Bot for friends to check the server status of the server, but it has a dynamic Ip, now we give the bot always the current Ip, but if possible he should do it himself.

A: You can't get the Steam game server IP adress.
This video answers why Steam will not give you their server IP adresses:

*

*a classic IP address will be subject to DDOS attacks

*all their servers a are behind server gateway which assign dynamic IPs

*No public service exists to get the dynamic IP because that would give DDos attackers an automated way to attack the gateway


text:
Q: Pandas vectorization: Compute the fraction of each group that meets a condition Suppose we have a table of customers and their spending.
import pandas as pd
df = pd.DataFrame({
    "Name":  ["Alice", "Bob", "Bob", "Charles"],
    "Spend": [3, 5, 7, 9]
})
LIMIT = 6

For each customer, we may compute the fraction of his spending that is larger than 6, using the apply method:
df.groupby("Name").apply(
    lambda grp: len(grp[grp["Spend"] > LIMIT]) / len(grp)
)

Name
Alice      0.0
Bob        0.5
Charles    1.0

However, the apply method is just a loop, which is slow if there are many customers.
Question: Is there a faster way, which presumably uses vectorization?
As of version 0.23.4, SeriesGroupBy does not support comparison operators:
(df.groupby("Name") ["Spend"] > LIMIT).mean()

TypeError: '>' not supported between instances of 'SeriesGroupBy' and 'int'

The code below results in a null value for Alice:
df[df["Spend"] > LIMIT].groupby("Name").size() / df.groupby("Name").size()

Name
Alice      NaN
Bob        0.5
Charles    1.0

The code below gives the correct result, but it requires us to either modify the table, or make a copy to avoid modifying the original.
df["Dummy"] = 1 * (df["Spend"] > LIMIT)
df.groupby("Name") ["Dummy"] .sum() / df.groupby("Name").size()

A: Groupby does not use vectorization, but it has aggregate functions that are optimized with Cython.
You can take the mean:
(df["Spend"] > LIMIT).groupby(df["Name"]).mean()

df["Spend"].gt(LIMIT).groupby(df["Name"]).mean()

Or use div to replace NaN with 0:
df[df["Spend"] > LIMIT].groupby("Name").size() \
.div(df.groupby("Name").size(), fill_value = 0)

df["Spend"].gt(LIMIT).groupby(df["Name"]).sum() \
.div(df.groupby("Name").size(), fill_value = 0)

Each of the above will yield
Name
Alice      0.0
Bob        0.5
Charles    1.0
dtype: float64

Performance
Depends on the number of rows and number of rows filtered per condition, so it's best to test on real data.
np.random.seed(123)

N = 100000
df = pd.DataFrame({
    "Name":  np.random.randint(1000, size = N),
    "Spend": np.random.randint(10, size = N)
})
LIMIT = 6

In [10]: %timeit df["Spend"].gt(LIMIT).groupby(df["Name"]).mean()
6.16 ms ± 332 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [11]: %timeit df[df["Spend"] > LIMIT].groupby("Name").size().div(df.groupby("Name").size(), fill_value = 0)
6.35 ms ± 95.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [12]: %timeit df["Spend"].gt(LIMIT).groupby(df["Name"]).sum().div(df.groupby("Name").size(), fill_value = 0)
9.66 ms ± 365 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

# RafaelC comment solution
In [13]: %timeit df.groupby("Name")["Spend"].apply(lambda s: (s > LIMIT).sum() / s.size)
400 ms ± 27.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [14]: %timeit df.groupby("Name")["Spend"].apply(lambda s: (s > LIMIT).mean())
328 ms ± 6.12 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

This NumPy solution is vectorized, but a bit complicated:
In [15]: %%timeit
    ...: i, r = pd.factorize(df["Name"])
    ...: a = pd.Series(np.bincount(i), index = r)
    ...:
    ...: i1, r1 = pd.factorize(df["Name"].values[df["Spend"].values > LIMIT])
    ...: b = pd.Series(np.bincount(i1), index = r1)
    ...:
    ...: df1 = b.div(a, fill_value = 0)
    ...:
5.05 ms ± 82.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


text:
Q: How can I easily access Views in a Fragment that is inflated on Button Click? I have an activity with a FrameLayout as my container for the Fragments and I want to replace the inflated Fragment on screen when I press a button there. I am doing this dynamically via FragmentManager and FragmentTransaction. I know that I have to wait a little bit to access the Views in the first Fragment, so I do it in the activities onStart. When I press the button I replace the old Fragment with a new one but now the question is when can I access the new Fragments views? E. g. I have an EditText in the first Fragment and I want to give the text in this EditText to the new Fragment and put it in an EditText there. I am adding the new Fragment via FragmentTransaction and then I want to define a new EditText and refer the EditText from the new Fragment to it. How and when can I do this since the new Fragment is inflated on button click?

A: you can Dynamically add fragment , use this Link
you can access to fragment with id or name :
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.myFragment);
if (fragment instanceof MyFragment)
    fragment.setMyEdittext();

so declare method that set Text your edittext in fragment and access this method with above code .

A: You should init and update views of a Fragment on its own. Back to your case, do the following steps.

*

*Define an interface to pass data (text in EditText) from first fragment to activity.

*When pressing on the button on the first fragment, call the callback method with data along to the activity.

*In the callback method of the activity, create a new instance of the new/second fragment which receives the text as a param.

*In the new/second fragment, write code to get value which passed from the activity, then set it as EditText content.


text:
Q: Angular: Couldn't resolve original symbol for ..."@angular/core/core.d.ts" I've been beating my head around this for days. My work place has a project on TFS.  I download the project and run the following cli commands to modify the application to my environment.
cd to .\ClientApp
npm install
npm install --save jquery popper.js moment bootstrap@4.0.0 @angular/material @angular/cdk ajv @fortawesome/fontawesome @fortawesome/fontawesome-free-regular @fortawesome/fontawesome-free-solid @angular/material-moment-adapter @angular/cdk@5.2.4 @angular/material@5.2.4 @angular/material-moment-adapter@5.2.4

I get the error

Error in error: Couldn't resolve original symbol for ./src/debug/debug_node from D:/src/Expenser/ClientApp/node_modules/@angular/core/core.d.ts aaaaat D:\src\Expenser\ClientApp\node_modules\@angular\compiler\bundles\compiler.umd.js:29542.....

enter image description here
If I have a co worker zip the folder and give it to me it works fine.  But this is not a real solution.  I have tons of projects here and I need to be able to download these deals from TFS and go.  I should not have to hunt through file systems and cli commands to figure out what to do or why it doesn't.
enter image description here

A: This should work fine.
Try installing the core in your local machine. Below is the command. Run it in your terminal.
----- npm install @angular/core

Let me know if it helps

A: I just had the same issue, the reason the zip file works and the source control doesn't work is because your source control is ignoring the files in the folders that contain the word "debug".
This explains the message:

Error in error: Couldn't resolve original symbol for ./src/debug/debug_node

As the code for "debug_node" can't be found.
The fact that angular uses the word "debug" in folders all over the place is very annoying.  There may be other keywords that your source control is ignoring too.
I recommend using a file comparison tool such as "Beyond Compare" to see all the differences between what is in your source control and what you have from the zip file.


text:
Q: Will the image of the points inside a circle be inside the image of the circle after this transformation in the complex plane? In the image below (part (b)), Since $z < |3|$ before the transformation, does that simply imply that the region to be shaded after the transformation is definitely the inside of the circle and not its outside? It seems so to me but I don't want to jump to the conclusion.
Also is the convention to use dotted lines for the locus of the circle, since $z < |3|$ as opposed to $z \leq |3|$ ?

A: If $|z - (-i)|$ is very small, then $|w|$ will be very large. In fact, within a certain neighborhood of $-i$, the closer $z$ is to $-i$, the larger $|w|$ is. This implies that wherever the circle $C$ is, there will be points in a neighborhood of $-i$ that are mapped to points outside the circle $C$.  But $|z| < 3$ for at least some of those points.
So it seems not to be a good assumption that the image of the points inside a circle will be inside the image of the circle.  In this case, in fact, they are not.

A: I'm not sure if you still want information on this question but I was recently stuck on a similar problem. I presume you were fine with part a), and if my working is correct I get the following equation for the circle in the $w$-plane:
$$
(u-\frac{9}{8})^2 + v^2 = (\frac{3}{8})^2
$$
This describes a circle with centre ($\frac{9}{8}$, 0) and radius $\frac{3}{8}$.
To get to this answer part of my working involved rearranging the given equation to make $z$ the subject and then taking the modulus of either side:
$$
|z| = \frac{|w|}{|1-w|}
$$
From this step it is simple to replace the $|z|$ with $3$ as we are told this is what the modulus of $z$ is. But in part b) we are told that $|z|<3$. So the equation becomes:
$$
3 > \frac{|w|}{|1-w|}
$$
Following my working for a), I arrived at the conclusion that:
$$
(u-\frac{9}{8})^2 + v^2 > (\frac{3}{8})^2
$$
Hence it would seem that the new region to shade is outside the cirlce $C$ because the coordinates of any point in this region must lie a distance greater than $\frac{3}{8}$ from the circle centre.
Hope this is useful!
(With regards to dotted lines, I agree with your thinking!).


text:
Q: Should I protect my cookies from injections? I have this script in my header:
if (isset($_COOKIE['username'])) {$_SESSION['username'] = $_COOKIE['username'];}
if (isset($_COOKIE['is_logged_in'])) {$_SESSION['is_logged_in'] = $_COOKIE['is_logged_in'];}

Should I protect my cookies from injections?
like stripslashes etc.

A: First and foremost you should rethink your authentication system. Because currently, anyone who knows how to alter cookies can impersonate any user without proper authentication. That's a way more actual security flaw.
Injection vulnerabilities depend on the actual context the values are inserted into and without providing information about that, we won't be able to help you.

A: You should esacpe input when appropriate. If you're going to output the username to an HTML page, use htmlentities($_COOKIE['username']). If you're going to check the username in the database, use mysql_real_escape_string($_COOKIE['username']) or prepared statements.
And you know users can alter cookies? What happens if I set my username cookie to 'Admin' and my is_logged_in cookie to 'true'?


text:
Q: Starting out with CSS media queries Please see my website here www.andrewtanner.me/dev
Basically, I'm just starting out with media queries. There are no specific devices I'm wanting to target other than mobile ones (tablets, smartphones). The website renders fine on mobile as it is so it's really just a case of optimising for mobile (eventually I want to look at big chunky touch buttons and generally a more friendly touch experience). The website is only for my own personal benefit and is really just a playground for myself.
My code is very basic so far and the pixel value is arbitrary.
@media (max-width: 480px) {
#container {display: none}

The 'container' ID contains a mixture of CSS and JavaScript/jQuery for rendering an interactive background.
When I resize the browser window on desktop (using Chrome) it works as expected, the background disappears. However, when viewed on a mobile device (Galaxy S4 using both Chrome and the stock browser) the background remains visible. I'm pretty certain this is because of the PPI of modern smartphones being just as good, if not better than laptop/desktop screens. Of course, a pixel is a relative value but I am are of the pixel-ratio element that can be used for media queries but I have tried this but to no avail (as well as including the browser engine).
I'm wanting to know how to fix this and also learn a bit more about how best to render specific CSS on mobile devices. I'm clearly missing something and while I could perhaps just take code from elsewhere and modify it - this doesn't really satisfy my curiosity).
Thanks
Andrew

A: You may need to add meta tags to define the width for the viewport. Try adding the following to the head of your document and let me know if the media query is respected on your mobile device:
<meta name="viewport" content="width=device-width,maximum-scale=1.0,minimum-scale=1.0">

A: Try adding this to the head section:
<!-- Mobile Specific Metas -->
    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">


text:
Q: Is there a way to configure clang-format to keep nested namespace declarations on the same line? In the codebase I'm working in, we always declare nested namespaces thusly:
namespace foo { namespace detail {

// stuff

} }  // foo::detail namespace

I haven't yet been able to find a way to configure clang-format not to break this out into multiple lines:
namespace foo {
namespace detail {

// stuff

}
}  // foo::detail namespace

I've played around with the BreakBeforeBraces configuration, and I've looked into the new BraceWrapping configuration in clang 3.8, both without success.
Is it possible to do this without annotating the code with // clang-format [on/off]?

A: It turns out that this is a feature that has been considered by the clang-format team, but has been rejected. For additional details, see https://llvm.org/bugs/show_bug.cgi?id=17928.

A: clang-format 6.0 has the "CompactNamespaces: true" option that does exactly what you're asking for. See http://clang.llvm.org/docs/ClangFormatStyleOptions.html


text:
Q: RDBMS normalization vs performance We are writing a MMORPG and suppose we have the following tables. The location_dynamic_objects is the table going to be queried and updated HEAVILY. As you can see position_x, position_y, location_id columns are duplicated as well as the object type. But if we normalize and use joins we are to apply additional filters for the selected data. We plan to send all the location_static_objects ONCE to client, so there is no real point in keeping them together with location_dynamic_objects.
Static objects represent unmovable data to be rendered and is send once to client on location load. Dynamic objects represent data being updated frequently like players, rockets, asteroids, etc and is constantly sent to the client, selecting depends on client position and location.
Our question is should we give up normalization to achieve performance?
create table location_static_object_types (
  location_static_object_type_id integer auto_increment primary key,
  object_type_name                varchar(16) not null
);
create table location_static_objects (
  location_static_object_id      integer auto_increment primary key,
  location_static_object_type_id integer not null,
  location_id                    integer not null,
  position_x                     integer not null,
  position_y                     integer not null
);
create table location_dynamic_object_types (
  location_dynamic_object_type_id integer auto_increment primary key,
  object_type_name                varchar(16) not null
);
create table location_dynamic_objects (
  location_dynamic_object_id      integer auto_increment primary key,
  location_dynamic_object_type_id integer not null,
  object_native_id                integer not null,
  location_id                     integer not null,
  position_x                      integer not null,
  position_y                      integer not null
);

A: Because denormalization increases the redundancy of your data, it increases your total data volume. For this reason it is most rare for a denormalization to improve performance of write accesses (creates and updates) to your data; the reverse is typically true. Further, even for read queries, denormalization trades off increased performance of a small set of queries, often just one, for decreased performance of all others acccessing the denormalized data. If you have properly employed artificial primary keys for your foreign key constraints, supplementd by corresponding uniqueness constraints on your natural (primary) keys, I would be amazed if you saw an iota of performance gain through denormalization.


text:
Q: How to change value of a variable in thymeleaf? I am new to thymeleaf. I am bit confused now. Please check out the codes below

             //Here I need to change the value of someVarible to true

    Its true

I need to edit the value of someVarible . How can I do it. Thanks in advance.

A: As Lukas said, it's not possible to change the value of a variable in Thymeleaf, because that only applies to the content within that element. However it is possibe to achieve something very similar using Thymeleaf only.
You can use Collection Selection and the ^[...] syntax to select the first element in your list that matches the criteria status==0. This expression would look like:
${demo.^[status==0]}

If the demo list contains an element with status==0, then that will be returned. Otherwise, it will result in null. This can be used directly in your th:if:
Its true

Or, if you need to use someVariable for other things too, you can assign it to a variable using th:with (Docs):

    Its true

A: You can't achieve your desired functionality as you described with Thymeleaf.
th:with does just local variable definition which is only available for evaluation inside that fragment.

And you can't change that variable in template. Thymeleaf is just presentation layer, you're trying to achieve something which has to be done on application layer (Java code).
On application layer (Java code) you could do:
Map<Integer, Boolean> fooMap = new HashMap<Integer, Boolean>();

for(Demo demo : demos) {
    if(demo.getStatus() == 0) {
        fooMap.put(demo.getId(), true);
    } else {
        fooMap.put(demo.getId(), false);
    }
}

And then on presentation layer (Thymeleaf):

    It's true

If you don't want to use HashMap you could use inheritance and extend object Demo.
(Please note that code which I wrote is not tested, so it may need some small fixed, but I hope that I helped you.)

A: Do you have a form? How do you send data to server?
If your variable of type boolean you can add, e.g., a checkbox for editing :

         Edit someVariable
         <input id="someVariableCheck" type="checkbox" th:value="${someVariable}"/>

Its true


text:
Q: How to make a div not propagate it's own width I want a setup like this:
.---------------.
| .-----------. |
| |  title    | |
| '-----------' |
| .----. .----. |
| | A  | | B  | |
| '----' '----' |
'---------------'

where title doesn't push its own width but adapts to the width dictated by A and B.
I currently have

this text needs to break, too long

 I am AAAA

 I am BBBB

But title does not break here.

A: Flex 0 the inner div to stop it from growing.

.outer {
  display: flex;
  justify-content: center;
}

.size-constrain {
  flex: 0;
}

.r { background-color: red }
.b { background-color: blue }
.y { background-color: yellow }

            Part A

Part B

Part C


text:
Q: cygwin startxwin, then ssh into a different machine i have a batch file on windows with the following line in it:
c:\cygwin64\bin\run.exe --quote /usr/bin/bash.exe -l -c "cd; /usr/bin/startxwin;"

When i execute this from windows, it launches an xterm window (with xwin enabled) and from there i can ssh into our remote linux server.
What i would like to do is add the ssh command in the batch file so that from my windows desktop, i can simply click it, and end up ssh'ing into our remote Linux server. I have tried doing something like this:
c:\cygwin64\bin\run.exe --quote /usr/bin/bash.exe -l -c "cd; /usr/bin/startxwin; ssh -Y my-remote-server xterm"

But doesn't seem to work. Any advice would be appreciated.

A: It should work with the following modifications:
c:\cygwin64\bin\run.exe --quote /usr/bin/bash.exe -l -c "cd; /usr/bin/startxwin & sleep 5; DISPLAY=:0 ssh -Y my-remote-server xterm"

First, startxwin doesn't daemonize itself, so you need to start it with & to ensure it runs in the background.
Then you need to export the correct DISPLAY enviornment, so that ssh will know which X11 server to connect to (my solution doesn't export the variable, but provides it to ssh only).
Then you need to wait for some seconds to be sure the X server started (sleep 5 is a guess, works on my machine).
Then you actually start the ssh process that connects and executes to the remote server.
I don't know about the run.exe part, I don't have it in my cygwin installation, maybe in your environment it would also work with the following:
c:\cygwin64\bin\bash.exe -l -c "cd; /usr/bin/startxwin & sleep 5; DISPLAY=:0 ssh -Y my-remote-server xterm"


text:
Q: That is house of my brother's classmate Which one is correct to say?

That is my brother's classmate house.
That is my brother's classmate's house.

What's the grammar rule behind this? What's the correct use of apostrophe?

A: The second sentence is correct. You need to add the apostrophe 's  after the word "classmate". However, you could also say:

That house belongs to a classmate of my brother's.


text:
Q: Does a $\mathbb{C}[G]$-module V imply a G-module? While I study representation theory, I have a question.
Let G be a group. Then,

Does a $\mathbb{C}[G]$-module V imply a G-module?

To see this, I tried to find a group homomorphism $\varphi : G \longrightarrow GL(V)$. For each $g\in G$, $\varphi(g)$ must be an invertible linear map. But, I'm failed to find the homomorphism. Please give me a hint!

A: Here's a hint: If $M$ is a (say, left) module over a ring $R$, then, for each $r \in R$, multiplication by $r$ induces an endomorphism of $M$, say $\mu_r$, with $\mu_r(m) = rm$. In your case $R=\mathbb C[G]$ and so this works in particular for all $g \in G$.
Remark:

*

*In fact, in this way, you can equivalently characterize an $R$-module structure on $M$ as a ring homomorphism $R \to \operatorname{End}(M)$, $r \mapsto \mu_r$. Can you see how this is analogous to the description of a $G$-module structure by a group homomorphism $G \to \operatorname{GL}(M)?$

*Your suspicion is correct, every $\mathbb C[G]$-module is a $G$-module. In fact, $G$-modules are the same thing as $\mathbb Z[G]$-modules.


text:
Q: How do I nest conditionals to identify sub-site & other criteria? In a site's header.php which is in a child theme shared by the root and 4 other sites on a network (using MU configured in directories) I need to identify which site/sub-site is being shown and subsequently look for other conditionals.
I've seen mention of get_blog_id_from_url, get_current_site and blog_id as potential methods, some more reliable than others. Which is the better approach?
I basically need the following (oversimplified):
If site 2, then
- if is_single() {echo some code}
- elsif is_template() {echo some code}
elsif site 3, then
- same as above but with different output

I'm essentially coming up with a rudimentary way to implement conditional menus. Plugins I have tried haven't worked as they were supposed to and I don't want to rely on a plugin for such a vital function.
If someone could lend a hand to figuring this out, it would be much appreciated.

A: You should use get_current_blog_id() if you need just the id and get_blog_details() if you need more fields.
Be aware that get_current_site in fact gives you information about the network of sites in a WP_Network object. Yeah, the name is kind of confusing, as  noted in the Codex but not yet on developer docs:

Note: get_current_site() was inherited from MU, and is named based on the old terminology which spoke of multiple "blogs" on a "site". We now speak of multiple "sites" on a "network" instead, but some of the old terminology still lives on in some function names. This function returns information about the current network. To get information about the current site on the network, see get_current_blog_id() and get_blog_details().

It would be something like this.
// get current blog id
$blog_id = get_current_blog_id();
if ( 2 === $blog_id){
    // if site id is 2
    //middle part for this case
} else {
    //if is not
    //middle part for this case
}


text:
Q: Passing Value Including Spaces on Ajax Call Trying to pass spaces along with ajax call.
'word' is been passed the same as 'word ' i believe so.
On the other hand two words need to be send completely with call.
'word second' but not the same as
'word second '
Should I trim before call or do this on server side script?
How can I send spaces as well?

A: To allow a parameter to include spaces, etc. you will want to use the javascript escape() [W3Schools] function.
escape( 'hello world ' ) = 'hello%20world%20';

The handling on the PHP side will automatically decode/unescape the parameter, restoring the spaces (along with any other characters which cannot be part of a parameter's value when sent through AJAX, such as "=" or "&".
Within PHP, if you are wanting to strip off any leading or trailing spaces, you can use the PHP trim() [PHP.net] function.
trim( 'hello world ' ) = 'hello world';

A: I know this is an old question, but I'd like to point out that the accepted answer is suggesting a function that is deprecated as of JavaScript version 1.5.
Instead, you should use either encodeURI() or encodeURIComponent() for sending spaces and other special characters.
var param = encodeURIComponent("word second ");
console.log(param); // outputs 'word%20second%20'

PHP on the other end will handle the decoding automatically. You should trim server side, as client side code can be edited by users to circumvent trimming, potentially causing bugs or vulnerabilities.

A: The simplest way, I think, is to encodeURIComponent string in javascript before sending xmlhttprequest, and then urldecode it in PHP