问:
ATMEGA128 AVR MEMORY ERRORS
I have code for ATMEGA128. It should be a counter program from 0 to 9.

```<code>#include "iom128v.h"
#include "macros.h"

void delay(int ms)
{
 int c1, c2;
 for(c1=0;c1<ms;c1++)
  for(c2=0;c2<970;c2++) NOP();
}

void main()
{
 char seg[10]={0b01110111, 0b01100000, 0b00111110, 0b01111010, 0b01101001,
  0b01011011, 0b01011111, 0b01110000,0b01111111, 0b01111011};
 char i;
 DDRC=0b10000111;
 DDRA=0xFF;
 DDRG=0x01;
 PORTG=0;
 PORTA=0;
 PORTC=0;
 PORTC=5;
 PORTC=7;
 PORTA=0xFF;
 PORTC=1;
 PORTC=2;
 PORTC=6;
 while(1)
 {
  for(i=0;i<10;i++)
  {
   PORTA=~seg[i];
   delay(300);
  }
 }
}
</code>```

I run this code in proteus and get the following errors cycled

PC=0x00FC. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21E1]=AA. [U1]

PC=0x0132. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21FF]=99. [U1]

PC=0x0132. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21FE]=00. [U1]

PC=0x0168. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D6]=21. [U1]

PC=0x016A. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D5]=D7. [U1]

PC=0x016C. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D4]=02. [U1]

PC=0x016E. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D3]=00. [U1]

PC=0x0174. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21FD]=BA. [U1]

PC=0x0174. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21FC]=00. [U1]

PC=0x01E0. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D2]=0A. [U1]

PC=0x01E2. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D1]=02. [U1]

PC=0x01E4. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D0]=D7. [U1]

PC=0x01E6. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21CF]=21. [U1]

PC=0x01E8. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21CE]=7B. [U1]

PC=0x01EA. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D5]. [U1]

PC=0x01EC. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D6]. [U1]

PC=0x01EE. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D3]. [U1]

PC=0x01F0. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D4]. [U1]

PC=0x0202. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21CE]. [U1]

PC=0x0204. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21CF]. [U1]

PC=0x0206. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D0]. [U1]

PC=0x0208. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D1]. [U1]

PC=0x020A. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D2]. [U1]

PC=0x000E. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21FC]. [U1]

PC=0x0174. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21FD]. [U1]

PC=0x0000. [AVR CPU] RET address = 0x0000 [U1]

答:
Your code doesn't seem to use external memory. This access must stack access. Check for stack address.
Of course, Proteus has a lot of weird behaviors in simulation.

In case of eXternal MEMmory access:
You must set SRE bit on MCUCR register to enable External Memory Interface. Also check configuration for MCUCR.SRW10, XMCRA and XMCRB. XMCRA and XMCRB are not accessible on ATmega103 compatibility mode (M103C fuse programmed).
When SRE bit is set, the A, C and G[2:0] will be dedicated to XMEM interface (instead of normal GPIO port).
(Also see  for better busy-wait delay automated base on F_CPU macro.)

Title: ATMEGA128 AVR MEMORY ERRORS

Body:
I have code for ATMEGA128. It should be a counter program from 0 to 9.

#include "iom128v.h"
#include "macros.h"

void delay(int ms)
{
 int c1, c2;
 for(c1=0;c1<ms;c1++)
  for(c2=0;c2<970;c2++) NOP();
}

void main()
{
 char seg[10]={0b01110111, 0b01100000, 0b00111110, 0b01111010, 0b01101001,
  0b01011011, 0b01011111, 0b01110000,0b01111111, 0b01111011};
 char i;
 DDRC=0b10000111;
 DDRA=0xFF;
 DDRG=0x01;
 PORTG=0;
 PORTA=0;
 PORTC=0;
 PORTC=5;
 PORTC=7;
 PORTA=0xFF;
 PORTC=1;
 PORTC=2;
 PORTC=6;
 while(1)
 {
  for(i=0;i<10;i++)
  {
   PORTA=~seg[i];
   delay(300);
  }
 }
}

I run this code in proteus and get the following errors cycled

PC=0x00FC. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21E1]=AA. [U1]

PC=0x0132. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21FF]=99. [U1]

PC=0x0132. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21FE]=00. [U1]

PC=0x0168. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D6]=21. [U1]

PC=0x016A. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D5]=D7. [U1]

PC=0x016C. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D4]=02. [U1]

PC=0x016E. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D3]=00. [U1]

PC=0x0174. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21FD]=BA. [U1]

PC=0x0174. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21FC]=00. [U1]

PC=0x01E0. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D2]=0A. [U1]

PC=0x01E2. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D1]=02. [U1]

PC=0x01E4. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21D0]=D7. [U1]

PC=0x01E6. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21CF]=21. [U1]

PC=0x01E8. [AVR MEMORY] External Memory Write while interface is not enabled (SRE=0): [0x21CE]=7B. [U1]

PC=0x01EA. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D5]. [U1]

PC=0x01EC. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D6]. [U1]

PC=0x01EE. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D3]. [U1]

PC=0x01F0. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D4]. [U1]

PC=0x0202. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21CE]. [U1]

PC=0x0204. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21CF]. [U1]

PC=0x0206. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D0]. [U1]

PC=0x0208. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D1]. [U1]

PC=0x020A. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21D2]. [U1]

PC=0x000E. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21FC]. [U1]

PC=0x0174. [AVR MEMORY] External Memory Read while interface is not enabled (SRE=0): [0x21FD]. [U1]

PC=0x0000. [AVR CPU] RET address = 0x0000 [U1]


来源: stackexchange

问:
array reduce accumulator as an empty array, push not working
Why is the accumulator.push  not valid? accumulator is an empty array!? If i use the predefined variable flarArray, things work just fine!! I know that if no initial value is included in the reduce callback, then it will use the first item in the array (which in my case will be an object) to be the accumulator, but if I tell it to start off as an array as the accumulator, what is the problem with that?

```<code>const profiles = [
  {
    id: 1,
    userID: '1',
    favoriteMovieID: '1',
  },
  {
    id: 2,
    userID: '2',
    favoriteMovieID: '1',
  }
];

const users = {
  1: {
    id: 1,
    name: 'Jane Cruz',
    userName: 'coder',
  },
  2: {
    id: 2,
    name: 'Matthew Johnson',
    userName: 'mpage',
  }
};

const movies = {
  1: {
    id: 1,
    name: 'Planet Earth 1',
  },
  2: {
    id: 2,
    name: 'Selma',
  }
};
let flatArray = [];
const flattenedProfiles = profiles.reduce(function(accumulator, currentProfile) {
  return accumulator.push({id: currentProfile.id, name: users[currentProfile.id].name, favoriteMovie: movies[currentProfile.favoriteMovieID].name})
},[]);
</code>```

答:
The problem is you return accumulator.push(). This returns the length of the array, so your next accumulator is gonna be a number instead of an array.

I would better return an array and use spread operator on the accumulator.

const profiles = [
  {
    id: 1,
    userID: '1',
    favoriteMovieID: '1',
  },
  {
    id: 2,
    userID: '2',
    favoriteMovieID: '1',
  }
];

const users = {
  1: {
    id: 1,
    name: 'Jane Cruz',
    userName: 'coder',
  },
  2: {
    id: 2,
    name: 'Matthew Johnson',
    userName: 'mpage',
  }
};

const movies = {
  1: {
    id: 1,
    name: 'Planet Earth 1',
  },
  2: {
    id: 2,
    name: 'Selma',
  }
};
let flatArray = [];
const flattenedProfiles = profiles.reduce(function(accumulator, currentProfile) {
  return [...accumulator, {id: currentProfile.id, name: users[currentProfile.id].name, favoriteMovie: movies[currentProfile.favoriteMovieID].name}]
},[]);

console.log(flattenedProfiles);```

ContentLicense: CC BY-SA 4.0

Body:
Why is the accumulator.push  not valid? accumulator is an empty array!? If i use the predefined variable flarArray, things work just fine!! I know that if no initial value is included in the reduce callback, then it will use the first item in the array (which in my case will be an object) to be the accumulator, but if I tell it to start off as an array as the accumulator, what is the problem with that?

const profiles = [
  {
    id: 1,
    userID: '1',
    favoriteMovieID: '1',
  },
  {
    id: 2,
    userID: '2',
    favoriteMovieID: '1',
  }
];

const users = {
  1: {
    id: 1,
    name: 'Jane Cruz',
    userName: 'coder',
  },
  2: {
    id: 2,
    name: 'Matthew Johnson',
    userName: 'mpage',
  }
};

const movies = {
  1: {
    id: 1,
    name: 'Planet Earth 1',
  },
  2: {
    id: 2,
    name: 'Selma',
  }
};
let flatArray = [];
const flattenedProfiles = profiles.reduce(function(accumulator, currentProfile) {
  return accumulator.push({id: currentProfile.id, name: users[currentProfile.id].name, favoriteMovie: movies[currentProfile.favoriteMovieID].name})
},[]);


问:
How Do I Remove The Border Of An Input
enter image description here

I have been trying to create a very simple login page. Around these inputs, as you can see, there are black borders. My question is, how do I remove that border?

答:
is not a border but an accessibility border from chrome.

You could try disabling this flag: chrome://flags/#form-controls-refresh

Apparantly the 83+ version of chrome changed how forms are rendered / handled.

Title: How Do I Remove The Border Of An Input


问:
STL + typedefs vs. OOP, best practices?
I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like: </p>

```<code>typedef std::map<std::string, std::map<std::string, int> > CSVData;
</code>```

<p>Obviously there are limits to this when I need to mix data types, but generally I find myself avoiding OOP when I can in favor of these STL composites for their simplicity. Is this a common progression? Are there best-practice rules-of-thumb for when it's better to define your own class? Are there common pitfalls to this? </p>

答:
Surely a sensible rule of thumb is to find a happy medium between:

Don't reinvent the wheel. (If they serve your purpose, use existing constructs.)

Make sure your code is readable and maintainable. (There comes a point where the reader will find it very difficult to keep track of all the nested templating, etc., even with judicious use of typedefs.)

ContentLicense: CC BY-SA 3.0

Title: STL + typedefs vs. OOP, best practices?

Body:
I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like:

typedef std::map<std::string, std::map<std::string, int> > CSVData;

Obviously there are limits to this when I need to mix data types, but generally I find myself avoiding OOP when I can in favor of these STL composites for their simplicity. Is this a common progression? Are there best-practice rules-of-thumb for when it's better to define your own class? Are there common pitfalls to this?


问:
JS - Show a div only when a number is typed
I have a form with an input type="number", and I need to display a div if the user types a number within a range.

My current code only works when I reload the page, but I want to display the "#alert-one" div when the numeric range is typed (not when the page reloads).

What am I doing wrong...?

Thanks in advance!

CSS:

```<code>#alert-one {
    display:none
}
</code>```

HTML:

```<code><div id="alert-one">Hello</div>

<input type="number" id="enviara" name="enviara" maxlength="5" required>
</code>```

Script:

```<code>$(document).ready(function(){
  function alertaislas() {
    const total = Number($("#enviara").val().replace(".",""));

    if(total > 28999 && total < 29999) {
      $('#alert-one').show();
    }

    else{
      $('#alert-one').hide();
}}

    alertaislas();
});
</code>```

答:
You can execute the function on input event of the element like the following way:

$(document).ready(function(){
  alertaislas();
});

$(document).on('input','#enviara',alertaislas);

function alertaislas() {
  const total = Number($("#enviara").val().replace(".",""));
  if(total > 28999 && total < 29999) {
    $('#alert-one').show();
  }
  else{
    $('#alert-one').hide();
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#alert-one {
   display:none
}</code>```

Hello

<input type="number" id="enviara" name="enviara" maxlength="5" required>```

Body:
I have a form with an input type="number", and I need to display a div if the user types a number within a range.

My current code only works when I reload the page, but I want to display the "#alert-one" div when the numeric range is typed (not when the page reloads).

What am I doing wrong...?

Thanks in advance!

CSS:

#alert-one {
    display:none
}

HTML:

Hello

<input type="number" id="enviara" name="enviara" maxlength="5" required>

Script:

$(document).ready(function(){
  function alertaislas() {
    const total = Number($("#enviara").val().replace(".",""));

    if(total > 28999 && total < 29999) {
      $('#alert-one').show();
    }

    else{
      $('#alert-one').hide();
}}

    alertaislas();
});

Body:
You can execute the function on input event of the element like the following way:

$(document).ready(function(){
  alertaislas();
});

$(document).on('input','#enviara',alertaislas);

function alertaislas() {
  const total = Number($("#enviara").val().replace(".",""));
  if(total > 28999 && total < 29999) {
    $('#alert-one').show();
  }
  else{
    $('#alert-one').hide();
  }
}

#alert-one {
   display:none
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="alert-one">Hello</div>

<input type="number" id="enviara" name="enviara" maxlength="5" required>


问:
Expected spy<method_name> to have been called once.It is called 0 times
I am a newbie to Jasmine.Iam writing a UT to check if a service is being called in ngAfterViewInit function.

Below is my test code

```<code>describe('HomePage', () => {
  let component: HomePage;
  let fixture: ComponentFixture<HomePage>;
  let service:DataloadService;
  let srvSpy:any;
  let compoSpy:any;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ HomePage ],
      imports: [
        HttpClientTestingModule,
        IonicModule.forRoot()]
    }).compileComponents();

    fixture = TestBed.createComponent(HomePage);
    component = fixture.componentInstance;
  }));
   it('getData method should be called on Init',()=>{
      srvSpy=jasmine.createSpy('getData').and.callThrough();
      expect(srvSpy).not.toHaveBeenCalled();
      component.ngAfterViewInit();
      expect(srvSpy).toHaveBeenCalledTimes(1);

  });

});
</code>```

Every time i run the script the test fails giving me the error

Expected spy to have been called once.It is called 0 times

How am i supposed to fix this?

Update:

```<code>import { Component, OnInit, AfterViewInit } from '@angular/core';
import { from } from 'rxjs';
import {DataloadService} from '../services/dataload.service';
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements AfterViewInit {
  value:any;
  constructor(private srv:DataloadService) {}
  ngAfterViewInit(){
    this.srv.getData().subscribe(
      res=>{
        this.value=res;
        console.log(this.value);
      }
    )
  }
}
</code>```

答:
Try doing something like this.

I am surprised Angular testbed is not complaining since you didn't inject DataloadService

```<code>import { of } from 'rxjs';
.....
describe('HomePage', () => {
  let component: HomePage;
  let fixture: ComponentFixture<HomePage>;
  let service:DataloadService;
  let mockDataLoadService = jasmine.createSpyObj('srv', ['getData']); // add this line to mock the dataLoadService with public method of getData
  let srvSpy:any;
  let compoSpy:any;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ HomePage ],
      imports: [
        HttpClientTestingModule,
        IonicModule.forRoot()],
      // stub out the real implementation of DateLoadService with our mock
      providers: [{ provide: DataLoadService, useValue: mockDataLoadService }],
    }).compileComponents();

    // make getData return Observable of 'hello world', it is up to you what you would like to return
    mockDataService.getData.and.returnValue(of('hello world'));
    fixture = TestBed.createComponent(HomePage);
    component = fixture.componentInstance;
  }));
   // change the title of the test
   it('value should be changed on ngAfterViewInit', ()=>{
      component.ngAfterViewInit();
      expect(component.value).toBe('hello world'); // assert that it went inside of the subscribe block and made component.value to 'hello world'

  });

});
</code>```

Body:
I am a newbie to Jasmine.Iam writing a UT to check if a service is being called in ngAfterViewInit function.

Below is my test code

describe('HomePage', () => {
  let component: HomePage;
  let fixture: ComponentFixture<HomePage>;
  let service:DataloadService;
  let srvSpy:any;
  let compoSpy:any;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ HomePage ],
      imports: [
        HttpClientTestingModule,
        IonicModule.forRoot()]
    }).compileComponents();

    fixture = TestBed.createComponent(HomePage);
    component = fixture.componentInstance;
  }));
   it('getData method should be called on Init',()=>{
      srvSpy=jasmine.createSpy('getData').and.callThrough();
      expect(srvSpy).not.toHaveBeenCalled();
      component.ngAfterViewInit();
      expect(srvSpy).toHaveBeenCalledTimes(1);

  });

});

Every time i run the script the test fails giving me the error

Expected spy to have been called once.It is called 0 times

How am i supposed to fix this?

Update:

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { from } from 'rxjs';
import {DataloadService} from '../services/dataload.service';
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements AfterViewInit {
  value:any;
  constructor(private srv:DataloadService) {}
  ngAfterViewInit(){
    this.srv.getData().subscribe(
      res=>{
        this.value=res;
        console.log(this.value);
      }
    )
  }
}

Body:
Try doing something like this.

I am surprised Angular testbed is not complaining since you didn't inject DataloadService

import { of } from 'rxjs';
.....
describe('HomePage', () => {
  let component: HomePage;
  let fixture: ComponentFixture<HomePage>;
  let service:DataloadService;
  let mockDataLoadService = jasmine.createSpyObj('srv', ['getData']); // add this line to mock the dataLoadService with public method of getData
  let srvSpy:any;
  let compoSpy:any;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ HomePage ],
      imports: [
        HttpClientTestingModule,
        IonicModule.forRoot()],
      // stub out the real implementation of DateLoadService with our mock
      providers: [{ provide: DataLoadService, useValue: mockDataLoadService }],
    }).compileComponents();

    // make getData return Observable of 'hello world', it is up to you what you would like to return
    mockDataService.getData.and.returnValue(of('hello world'));
    fixture = TestBed.createComponent(HomePage);
    component = fixture.componentInstance;
  }));
   // change the title of the test
   it('value should be changed on ngAfterViewInit', ()=>{
      component.ngAfterViewInit();
      expect(component.value).toBe('hello world'); // assert that it went inside of the subscribe block and made component.value to 'hello world'

  });

});


问:
WCSession is not reachable for sending messages
I want to trigger few events to my watch extension app from the iOS app but I'm getting the error saying WCSession is not reachable. All my events are time-sensitive, So I can't wait for the user to turn on the watch display to trigger the events.

Is there any way where I can achieve this using local notification?

Is it possible to trigger watchOS launch, so that WCSession becomes reachable without user action?

答:
Is there any way where I can achieve this using local notification?

As far as I know, a notification does not change the reachability. You could debug its behaviour by using this on the iOS side to check if it becomes available.

func sessionReachabilityDidChange(_ session: WCSession) {}

I would recommend you to take a look at Extended Runtime Sessions, although it won't be running 24/7 in the background.


问:
OWASP ZAP - (Authentication) Extract Token from Response and use it for a next Request
I am new to ZAP, Could someone please assist with OWASP ZAP with extracting multiple authentications tokens from a Response and use it for next Request Header

Required:
-Login in
-GET Request A(Response) : {"tokenA":"abcdef","tokenB":"xyz"}
-GET Request B(Header) : Token1:tokenA_Value
-GET Request B(Header) : Token2:tokenB_Value

These Token (A, B) get updated every time user logins, Is there any way where I can store the "tokenA" and "tokenB" values in variables and then use it for a next request header "Token1" and "Token2" ?

答:
Yes, you can use Script Variables for this: https://www.zaproxy.org/docs/desktop/addons/script-console/

I gave a 3 hour workshop on ZAP automation and authentication recently for ADDO - that was recorded and the videos are being added to https://www.alldaydevops.com/zap-in-ten


问:
Running a simulation file in Gatling in Mac
I'm a a novice with Gatling.

I'm running my 1st test on Mac

I've open the recorder in one terminal

I've created a .har file

I've opened user-file in another in another terminal.

I'm trying to run subl RecordedSimulation.scala

I'm getting an error message:

```<code>zsh: command not found: subl
</code>```

I've also done a video for clarity here

答:
This has really nothing to do with Gatling.

subl is the executable for Sublime Text Editor which is simply the text editor the author of the Udemy course you've subscribed uses. You just don't have it (in your path).

Use whatever text editor suites you.

Body:
I'm a a novice with Gatling.

I'm running my 1st test on Mac

I've open the recorder in one terminal

I've created a .har file

I've opened user-file in another in another terminal.

I'm trying to run subl RecordedSimulation.scala

I'm getting an error message:

zsh: command not found: subl

I've also done a video for clarity here


问:
Usage of SASS value variables: best practics
Does it make sense to use sass variables when repeating values?
For example:

```<code>$common-px-value: 20px
$max-value: 100px
$min-value: 200px
.someClass, someAnotherClass
  some styles...
  img
    object-fit: cover
    min-width: $min-value
    max-width: $max-value
    min-height: $min-value
    max-height: $max-value
</code>```

What the best practics with SASS value variables?
Maybe add it to separate folder for separation of logic? And something else:)

Does it use only for readability of code?
What a good practices at real projects?
After all, values can be repeated throughout the all application, but it's hard to find out all values beforehand.

答:
You can use a mixin for this, which would make your code more dry and easy to use. So you could do something like

```<code>@mixin myValues(
$minw: null,
$maxw: null
) {
min-width: $minw;
max-width: $maxw;
}
</code>```

and then you can use that mixin in the styles for .someClass like so:

```<code>.someClass {
 @include myValues($minw: 200px, $maxw: 200px);
}
</code>```

You can change the values of the arguments you pass to that mixin each time you need to, instead of repeating the same chunk of code each time. Hope that helps.

Edit: The sass syntax might be a bit different than scss (which I used in this example)

Body:
Does it make sense to use sass variables when repeating values?
For example:

$common-px-value: 20px
$max-value: 100px
$min-value: 200px
.someClass, someAnotherClass
  some styles...
  img
    object-fit: cover
    min-width: $min-value
    max-width: $max-value
    min-height: $min-value
    max-height: $max-value

What the best practics with SASS value variables?
Maybe add it to separate folder for separation of logic? And something else:)

Does it use only for readability of code?
What a good practices at real projects?
After all, values can be repeated throughout the all application, but it's hard to find out all values beforehand.

Body:
You can use a mixin for this, which would make your code more dry and easy to use. So you could do something like

@mixin myValues(
$minw: null,
$maxw: null
) {
min-width: $minw;
max-width: $maxw;
}

and then you can use that mixin in the styles for .someClass like so:

.someClass {
 @include myValues($minw: 200px, $maxw: 200px);
}

You can change the values of the arguments you pass to that mixin each time you need to, instead of repeating the same chunk of code each time. Hope that helps.

Edit: The sass syntax might be a bit different than scss (which I used in this example)


问:
How Can A .dll File Read a .txt File?
I would like my Browser Helper Object which is simply a .dll, to be able to read a text file. I have tried using a pointer to a FILE, as well as ifstream in("file name goes here"). Before implementing these two methods of reading files into the BHO, I tested them individually, and made sure each example dealt with similar data types and locations. Both of them worked without a problem, yet testing the BHO reveals that the file cant even be opened. I have searched google for an alternative method, and after exhausting all other options, I'm hoping that someone would be able to provide me with some guidance/resource. Anything is appreciated; I will keep trying to find a solution and will post what I can in the event that someone else may have the same problem.</p>

答: Are you providing an absolute path to the file?  If you're just using a relative path you may not be in the same working directory while running IE.</p>

Title: How Can A .dll File Read a .txt File?


问:
React Native Animated. You must specify exactly one property per transform object
I get this error trying to translate a View using translateX and translateY

ExceptionsManager.js:173 JSON value '(
          {
          translateX = 0;
          translateY = 120;
      } )' of type NSMutableArray cannot be converted to a CATransform3D. You must specify exactly one property per transform
  object.

Here is my component:

```<code>  const BounceInUp: FC<IAnimatedView> = ({ children, teddyBear }) => {
  const bounceValue = new Animated.Value(120);
  const shakeValue = new Animated.Value(0);

  const animate = useCallback(() => {
    Animated.sequence([
      Animated.delay(300),
      Animated.spring(bounceValue, {
        useNativeDriver: true,
        toValue: -10,
        velocity: 3,
        friction: 8,
      }),
      Animated.sequence([
        Animated.timing(shakeValue, { toValue: 10, duration: 100, useNativeDriver: true }),
        Animated.timing(shakeValue, { toValue: -10, duration: 100, useNativeDriver: true }),
        Animated.timing(shakeValue, { toValue: 10, duration: 100, useNativeDriver: true }),
        Animated.timing(shakeValue, { toValue: 0, duration: 100, useNativeDriver: true }),
      ]),
    ]).start();
  }, [bounceValue, shakeValue]);

  useEffect(() => {
    animate();
  }, [teddyBear.id]);

  return (
    <Animated.View style={[styles.subView, { transform: [{ translateY: bounceValue, translateX: shakeValue }] }]}>
      {children}
    </Animated.View>
  );
};
</code>```

How can I apply one animation on X and Y without getting this error?

答:
const bounceValue = new Animated.Value(120); I think you might want to try initialising value like this: const valueXY = new Animated.ValueXY({ x: 0, y: 120 }); because you want to animate value x and y.

Then:

```<code>Animated.spring(valueXY, {
        useNativeDriver: true,
        toValue: { x: 0, y: 0 },
        velocity: 3,
        friction: 8,
      }),
</code>```

and in your sequence:

Animated.timing(valueXY, { toValue: { x: 10, y: 0 }, duration: 100, useNativeDriver: true })

Also in style <Animated.View style={[styles.subView, { transform: valueXY.getTranslateTransform() }]}>

You can check here for more info https://animationbook.codedaily.io/animated-value-xy/

Body:
I get this error trying to translate a View using translateX and translateY

ExceptionsManager.js:173 JSON value '(
          {
          translateX = 0;
          translateY = 120;
      } )' of type NSMutableArray cannot be converted to a CATransform3D. You must specify exactly one property per transform
  object.

Here is my component:

  const BounceInUp: FC<IAnimatedView> = ({ children, teddyBear }) => {
  const bounceValue = new Animated.Value(120);
  const shakeValue = new Animated.Value(0);

  const animate = useCallback(() => {
    Animated.sequence([
      Animated.delay(300),
      Animated.spring(bounceValue, {
        useNativeDriver: true,
        toValue: -10,
        velocity: 3,
        friction: 8,
      }),
      Animated.sequence([
        Animated.timing(shakeValue, { toValue: 10, duration: 100, useNativeDriver: true }),
        Animated.timing(shakeValue, { toValue: -10, duration: 100, useNativeDriver: true }),
        Animated.timing(shakeValue, { toValue: 10, duration: 100, useNativeDriver: true }),
        Animated.timing(shakeValue, { toValue: 0, duration: 100, useNativeDriver: true }),
      ]),
    ]).start();
  }, [bounceValue, shakeValue]);

  useEffect(() => {
    animate();
  }, [teddyBear.id]);

  return (
    <Animated.View style={[styles.subView, { transform: [{ translateY: bounceValue, translateX: shakeValue }] }]}>
      {children}
    </Animated.View>
  );
};

How can I apply one animation on X and Y without getting this error?

Body:
const bounceValue = new Animated.Value(120); I think you might want to try initialising value like this: const valueXY = new Animated.ValueXY({ x: 0, y: 120 }); because you want to animate value x and y.

Then:

Animated.spring(valueXY, {
        useNativeDriver: true,
        toValue: { x: 0, y: 0 },
        velocity: 3,
        friction: 8,
      }),

and in your sequence:

Animated.timing(valueXY, { toValue: { x: 10, y: 0 }, duration: 100, useNativeDriver: true })

Also in style <Animated.View style={[styles.subView, { transform: valueXY.getTranslateTransform() }]}>

You can check here for more info https://animationbook.codedaily.io/animated-value-xy/


问:
Showing error on install Firebase/Messaging pod in xcode 11.3?
enter image description here

```<code>pod 'Firebase'
pod 'Firebase/Core'
pod 'Firebase/Messaging'
pod 'Firebase/Analytics'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'Firebase/RemoteConfig'
pod 'Firebase/Storage'
</code>```

I am trying to install firebase/Messaging, with FirebaseAnalytics but it gives error shown in below. please suggest the solution.

!] Unable to find a specification for FirebaseAnalyticsInterop (~> 1.5) depended upon by FirebaseMessaging

You have either:
 * out-of-date source repos which you can update with pod repo update or with pod install --repo-update.
 * mistyped the name or version.
 * not added the source repo that hosts the Podspec to your Podfile.

答:
I have been able to install the dependencies with below pod file without any issues.

```<code>use_frameworks!
platform :ios, '9.0'

install! 'cocoapods'

target 'PodTest' do
use_frameworks!
pod 'Firebase'
pod 'Firebase/Core'
pod 'Firebase/Messaging'
pod 'Firebase/Analytics'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'Firebase/RemoteConfig'
pod 'Firebase/Storage'
end
</code>```

Body:
enter image description here

pod 'Firebase'
pod 'Firebase/Core'
pod 'Firebase/Messaging'
pod 'Firebase/Analytics'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'Firebase/RemoteConfig'
pod 'Firebase/Storage'

I am trying to install firebase/Messaging, with FirebaseAnalytics but it gives error shown in below. please suggest the solution.

!] Unable to find a specification for FirebaseAnalyticsInterop (~> 1.5) depended upon by FirebaseMessaging

You have either:
 * out-of-date source repos which you can update with pod repo update or with pod install --repo-update.
 * mistyped the name or version.
 * not added the source repo that hosts the Podspec to your Podfile.

Body:
I have been able to install the dependencies with below pod file without any issues.

use_frameworks!
platform :ios, '9.0'

install! 'cocoapods'

target 'PodTest' do
use_frameworks!
pod 'Firebase'
pod 'Firebase/Core'
pod 'Firebase/Messaging'
pod 'Firebase/Analytics'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'Firebase/RemoteConfig'
pod 'Firebase/Storage'
end


问:
How can I update the variable in a scheduled event using Python?
I am using twilio and scheduler to send random text messages from a list each day. I am able to send texts at given intervals, but I cannot make it so that it updates the variable and sends a different message. How can I update the variable randomly in schedule? This is the code I have so far:

```<code>import schedule
import time
from twilio.rest import Client
from Positivequotelist import choosequote

def runjob(func, arg1, arg2):
    schedule.every(10).seconds.do(func, number=arg1, message=arg2)
    while True:
        schedule.run_pending()
        time.sleep(1)

def sendtext(number,message):

    account_sid = '(omitted)'
    auth_token = '(omitted)'
    client = Client(account_sid, auth_token)

    message = client.messages \
        .create(
             body=message,
             messaging_service_sid='(omitted)',
             to='+1'+str(number)
         )

if __name__=="__main__":
    quotelist=["Successful people don’t become that way overnight."\
           "What most people see at a glance—happiness, wealth, a great career, purpose—is the result of hard work and hustle over time",
           "Your limitation—it’s only your imagination.",
           "Push yourself, because no one else is going to do it for you.",
           "Sometimes later becomes never. Do it now.",
           " Great things never come from comfort zones.",
           "Dream it. Wish it. Do it",
           "Success doesn’t just find you. You have to go out and get it.",
           "The harder you work for something, the greater you’ll feel when you achieve it.",
           "Dream bigger. Do bigger.",
           "Don’t stop when you’re tired. Stop when you’re done.",
           "You’re off to great places, today is your day. Your mountain is waiting, so get on your way",
           "Wake up with determination. Go to bed with satisfaction.",
           "Do something today that your future self will thank you for.",
           "The Pessimist Sees Difficulty In Every Opportunity. The Optimist Sees Opportunity In Every Difficulty",
           "Don’t Let Yesterday Take Up Too Much Of Today.",
           "All our dreams can come true, if we have the courage to pursue them",
           "The secret of getting ahead is getting started",
           "The best time to plant a tree was 20 years ago. The second best time is now",
           "Only the paranoid survive.",
           "It’s hard to beat a person who never gives up",
           "I wake up every morning and think to myself, ‘how far can I push this company in the next 24 hours",
           "If people are doubting how far you can go, go so far that you can’t hear them anymore.",
           "Write it. Shoot it. Publish it. Crochet it, sauté it, whatever. MAKE",
           "You’ve gotta dance like there’s nobody watching, love like you’ll never be hurt, sing like there’s nobody listening, and live like it’s heaven on earth",
           "Fairy tales are more than true: not because they tell us that dragons exist, but because they tell us that dragons can be beaten",
           "Everything you can imagine is real",
           "Do one thing every day that scares you",
           "It’s no use going back to yesterday, because I was a different person then.",
           "Smart people learn from everything and everyone, average people from their experiences, stupid people already have all the answers",
           "Do what you feel in your heart to be right – for you’ll be criticized anyway.",
           "Happiness is not something ready made. It comes from your own actions.",
           "Whatever you are, be a good one",
           "The same boiling water that softens the potato hardens the egg. It’s what you’re made of. Not the circumstances",
           "If we have the attitude that it’s going to be a great day it usually is",
           "You can either experience the pain of discipline or the pain of regret. The choice is yours.",
           "Impossible is just an opinion.",
           "Your passion is waiting for your courage to catch up",
           "Magic is believing in yourself. If you can make that happen, you can make anything happen.",
           "If something is important enough, even if the odds are stacked against you, you should still do it.",
           "Hold the vision, trust the process.",
           "Don’t be afraid to give up the good to go for the great",
           "People who wonder if the glass is half empty or full miss the point. The glass is refillable",
           "No one is to blame for your future situation but yourself. If you want to be successful, then become Successful",
           "Things may come to those who wait, but only the things left by those who hustle",
           "Everything comes to him who hustles while he waits.",
           "Invest in your dreams. Grind now. Shine later.",
           "Hustlers don’t sleep, they nap.",
           "Greatness only comes before hustle in the dictionary",
           "Without hustle, talent will only carry you so far",
           "Work like there is someone working twenty four hours a day to take it away from you",
           "Hustle in silence and let your success make the noise."]
    chosen = choosequote(quotelist)
    runjob(sendtext, (omitted), chosen)
</code>```

It is working, but it sends the same quote every time. Any help would be appreciated.

Update:
This is the choosequote function:

```<code>def choosequote(listofquotes):
    randomquote=random.randint(0, len(listofquotes)-1)

    chosenquote=listofquotes.pop(randomquote)

    return chosenquote
</code>```

答:
I was able to make it work by editing my runjob function and my sendtext function:

```<code>def sendtext(number):
#now only takes one parameter for the number
    quotelist=["Successful people don’t become that way overnight."\
           "What most people see at a glance—happiness, wealth, a great career, purpose—is the result of hard work and hustle over time",
           "Your limitation—it’s only your imagination.",
           "Push yourself, because no one else is going to do it for you.",
           "Sometimes later becomes never. Do it now.",
           " Great things never come from comfort zones.",
           "Dream it. Wish it. Do it",
           "Success doesn’t just find you. You have to go out and get it.",
           "The harder you work for something, the greater you’ll feel when you achieve it.",
           "Dream bigger. Do bigger.",
           "Don’t stop when you’re tired. Stop when you’re done.",
           "You’re off to great places, today is your day. Your mountain is waiting, so get on your way",
           "Wake up with determination. Go to bed with satisfaction.",
           "Do something today that your future self will thank you for.",
           "The Pessimist Sees Difficulty In Every Opportunity. The Optimist Sees Opportunity In Every Difficulty",
           "Don’t Let Yesterday Take Up Too Much Of Today.",
           "All our dreams can come true, if we have the courage to pursue them",
           "The secret of getting ahead is getting started",
           "The best time to plant a tree was 20 years ago. The second best time is now",
           "Only the paranoid survive.",
           "It’s hard to beat a person who never gives up",
           "I wake up every morning and think to myself, ‘how far can I push this company in the next 24 hours",
           "If people are doubting how far you can go, go so far that you can’t hear them anymore.",
           "Write it. Shoot it. Publish it. Crochet it, sauté it, whatever. MAKE",
           "You’ve gotta dance like there’s nobody watching, love like you’ll never be hurt, sing like there’s nobody listening, and live like it’s heaven on earth",
           "Fairy tales are more than true: not because they tell us that dragons exist, but because they tell us that dragons can be beaten",
           "Everything you can imagine is real",
           "Do one thing every day that scares you",
           "It’s no use going back to yesterday, because I was a different person then.",
           "Smart people learn from everything and everyone, average people from their experiences, stupid people already have all the answers",
           "Do what you feel in your heart to be right – for you’ll be criticized anyway.",
           "Happiness is not something ready made. It comes from your own actions.",
           "Whatever you are, be a good one",
           "The same boiling water that softens the potato hardens the egg. It’s what you’re made of. Not the circumstances",
           "If we have the attitude that it’s going to be a great day it usually is",
           "You can either experience the pain of discipline or the pain of regret. The choice is yours.",
           "Impossible is just an opinion.",
           "Your passion is waiting for your courage to catch up",
           "Magic is believing in yourself. If you can make that happen, you can make anything happen.",
           "If something is important enough, even if the odds are stacked against you, you should still do it.",
           "Hold the vision, trust the process.",
           "Don’t be afraid to give up the good to go for the great",
           "People who wonder if the glass is half empty or full miss the point. The glass is refillable",
           "No one is to blame for your future situation but yourself. If you want to be successful, then become Successful",
           "Things may come to those who wait, but only the things left by those who hustle",
           "Everything comes to him who hustles while he waits.",
           "Invest in your dreams. Grind now. Shine later.",
           "Hustlers don’t sleep, they nap.",
           "Greatness only comes before hustle in the dictionary",
           "Without hustle, talent will only carry you so far",
           "Work like there is someone working twenty four hours a day to take it away from you",
           "Hustle in silence and let your success make the noise."]
    message1 = choosequote(quotelist)
    account_sid = '(omitted)'
    auth_token = '(omitted)'
    client = Client(account_sid, auth_token)

    message = client.messages \
        .create(
             body=message1,
             messaging_service_sid='(omitted)',
             to='+1'+str(number)
         )

def runjob(func, arg1):
    schedule.every().day.at("14:00").do(func, number=arg1)
    while True:
        schedule.run_pending()
        time.sleep(1)
</code>```

Then, I run it using:

```<code>if __name__=="__main__":
    runjob(sendtext, (number omitted))
</code>```

By adding arguments to the runjob function, it allowed me to pass the sendtext function through the runjob function with a parameter for number. The runjob function now automatically chooses a message instead of using the choosequote function, allowing me to choose a new quote each time.

Thanks for all the help!

Body:
I am using twilio and scheduler to send random text messages from a list each day. I am able to send texts at given intervals, but I cannot make it so that it updates the variable and sends a different message. How can I update the variable randomly in schedule? This is the code I have so far:

import schedule
import time
from twilio.rest import Client
from Positivequotelist import choosequote

def runjob(func, arg1, arg2):
    schedule.every(10).seconds.do(func, number=arg1, message=arg2)
    while True:
        schedule.run_pending()
        time.sleep(1)

def sendtext(number,message):

    account_sid = '(omitted)'
    auth_token = '(omitted)'
    client = Client(account_sid, auth_token)

    message = client.messages \
        .create(
             body=message,
             messaging_service_sid='(omitted)',
             to='+1'+str(number)
         )

if __name__=="__main__":
    quotelist=["Successful people don’t become that way overnight."\
           "What most people see at a glance—happiness, wealth, a great career, purpose—is the result of hard work and hustle over time",
           "Your limitation—it’s only your imagination.",
           "Push yourself, because no one else is going to do it for you.",
           "Sometimes later becomes never. Do it now.",
           " Great things never come from comfort zones.",
           "Dream it. Wish it. Do it",
           "Success doesn’t just find you. You have to go out and get it.",
           "The harder you work for something, the greater you’ll feel when you achieve it.",
           "Dream bigger. Do bigger.",
           "Don’t stop when you’re tired. Stop when you’re done.",
           "You’re off to great places, today is your day. Your mountain is waiting, so get on your way",
           "Wake up with determination. Go to bed with satisfaction.",
           "Do something today that your future self will thank you for.",
           "The Pessimist Sees Difficulty In Every Opportunity. The Optimist Sees Opportunity In Every Difficulty",
           "Don’t Let Yesterday Take Up Too Much Of Today.",
           "All our dreams can come true, if we have the courage to pursue them",
           "The secret of getting ahead is getting started",
           "The best time to plant a tree was 20 years ago. The second best time is now",
           "Only the paranoid survive.",
           "It’s hard to beat a person who never gives up",
           "I wake up every morning and think to myself, ‘how far can I push this company in the next 24 hours",
           "If people are doubting how far you can go, go so far that you can’t hear them anymore.",
           "Write it. Shoot it. Publish it. Crochet it, sauté it, whatever. MAKE",
           "You’ve gotta dance like there’s nobody watching, love like you’ll never be hurt, sing like there’s nobody listening, and live like it’s heaven on earth",
           "Fairy tales are more than true: not because they tell us that dragons exist, but because they tell us that dragons can be beaten",
           "Everything you can imagine is real",
           "Do one thing every day that scares you",
           "It’s no use going back to yesterday, because I was a different person then.",
           "Smart people learn from everything and everyone, average people from their experiences, stupid people already have all the answers",
           "Do what you feel in your heart to be right – for you’ll be criticized anyway.",
           "Happiness is not something ready made. It comes from your own actions.",
           "Whatever you are, be a good one",
           "The same boiling water that softens the potato hardens the egg. It’s what you’re made of. Not the circumstances",
           "If we have the attitude that it’s going to be a great day it usually is",
           "You can either experience the pain of discipline or the pain of regret. The choice is yours.",
           "Impossible is just an opinion.",
           "Your passion is waiting for your courage to catch up",
           "Magic is believing in yourself. If you can make that happen, you can make anything happen.",
           "If something is important enough, even if the odds are stacked against you, you should still do it.",
           "Hold the vision, trust the process.",
           "Don’t be afraid to give up the good to go for the great",
           "People who wonder if the glass is half empty or full miss the point. The glass is refillable",
           "No one is to blame for your future situation but yourself. If you want to be successful, then become Successful",
           "Things may come to those who wait, but only the things left by those who hustle",
           "Everything comes to him who hustles while he waits.",
           "Invest in your dreams. Grind now. Shine later.",
           "Hustlers don’t sleep, they nap.",
           "Greatness only comes before hustle in the dictionary",
           "Without hustle, talent will only carry you so far",
           "Work like there is someone working twenty four hours a day to take it away from you",
           "Hustle in silence and let your success make the noise."]
    chosen = choosequote(quotelist)
    runjob(sendtext, (omitted), chosen)

It is working, but it sends the same quote every time. Any help would be appreciated.

Update:
This is the choosequote function:

def choosequote(listofquotes):
    randomquote=random.randint(0, len(listofquotes)-1)

    chosenquote=listofquotes.pop(randomquote)

    return chosenquote

Body:
I was able to make it work by editing my runjob function and my sendtext function:

def sendtext(number):
#now only takes one parameter for the number
    quotelist=["Successful people don’t become that way overnight."\
           "What most people see at a glance—happiness, wealth, a great career, purpose—is the result of hard work and hustle over time",
           "Your limitation—it’s only your imagination.",
           "Push yourself, because no one else is going to do it for you.",
           "Sometimes later becomes never. Do it now.",
           " Great things never come from comfort zones.",
           "Dream it. Wish it. Do it",
           "Success doesn’t just find you. You have to go out and get it.",
           "The harder you work for something, the greater you’ll feel when you achieve it.",
           "Dream bigger. Do bigger.",
           "Don’t stop when you’re tired. Stop when you’re done.",
           "You’re off to great places, today is your day. Your mountain is waiting, so get on your way",
           "Wake up with determination. Go to bed with satisfaction.",
           "Do something today that your future self will thank you for.",
           "The Pessimist Sees Difficulty In Every Opportunity. The Optimist Sees Opportunity In Every Difficulty",
           "Don’t Let Yesterday Take Up Too Much Of Today.",
           "All our dreams can come true, if we have the courage to pursue them",
           "The secret of getting ahead is getting started",
           "The best time to plant a tree was 20 years ago. The second best time is now",
           "Only the paranoid survive.",
           "It’s hard to beat a person who never gives up",
           "I wake up every morning and think to myself, ‘how far can I push this company in the next 24 hours",
           "If people are doubting how far you can go, go so far that you can’t hear them anymore.",
           "Write it. Shoot it. Publish it. Crochet it, sauté it, whatever. MAKE",
           "You’ve gotta dance like there’s nobody watching, love like you’ll never be hurt, sing like there’s nobody listening, and live like it’s heaven on earth",
           "Fairy tales are more than true: not because they tell us that dragons exist, but because they tell us that dragons can be beaten",
           "Everything you can imagine is real",
           "Do one thing every day that scares you",
           "It’s no use going back to yesterday, because I was a different person then.",
           "Smart people learn from everything and everyone, average people from their experiences, stupid people already have all the answers",
           "Do what you feel in your heart to be right – for you’ll be criticized anyway.",
           "Happiness is not something ready made. It comes from your own actions.",
           "Whatever you are, be a good one",
           "The same boiling water that softens the potato hardens the egg. It’s what you’re made of. Not the circumstances",
           "If we have the attitude that it’s going to be a great day it usually is",
           "You can either experience the pain of discipline or the pain of regret. The choice is yours.",
           "Impossible is just an opinion.",
           "Your passion is waiting for your courage to catch up",
           "Magic is believing in yourself. If you can make that happen, you can make anything happen.",
           "If something is important enough, even if the odds are stacked against you, you should still do it.",
           "Hold the vision, trust the process.",
           "Don’t be afraid to give up the good to go for the great",
           "People who wonder if the glass is half empty or full miss the point. The glass is refillable",
           "No one is to blame for your future situation but yourself. If you want to be successful, then become Successful",
           "Things may come to those who wait, but only the things left by those who hustle",
           "Everything comes to him who hustles while he waits.",
           "Invest in your dreams. Grind now. Shine later.",
           "Hustlers don’t sleep, they nap.",
           "Greatness only comes before hustle in the dictionary",
           "Without hustle, talent will only carry you so far",
           "Work like there is someone working twenty four hours a day to take it away from you",
           "Hustle in silence and let your success make the noise."]
    message1 = choosequote(quotelist)
    account_sid = '(omitted)'
    auth_token = '(omitted)'
    client = Client(account_sid, auth_token)

    message = client.messages \
        .create(
             body=message1,
             messaging_service_sid='(omitted)',
             to='+1'+str(number)
         )

def runjob(func, arg1):
    schedule.every().day.at("14:00").do(func, number=arg1)
    while True:
        schedule.run_pending()
        time.sleep(1)

Then, I run it using:

if __name__=="__main__":
    runjob(sendtext, (number omitted))

By adding arguments to the runjob function, it allowed me to pass the sendtext function through the runjob function with a parameter for number. The runjob function now automatically chooses a message instead of using the choosequote function, allowing me to choose a new quote each time.

Thanks for all the help!


问:
StringLengthAttribute doesn't seem to be working
Here is my Test class with data annotations:

```<code>class Test
{
  [Required, StringLength(10)]
  public string MyProperty { get; set; }
}
</code>```

Here is my console test program:

```<code>class Program
{
  static void Main(string[] args)
  {
    var test = new Test {
      MyProperty = "this is way more than 10 characters and should fail."
    };

    var context = new ValidationContext(test, null, null);

    // No exception here! (why not?)
    Validator.ValidateObject(test, context);

    test.MyProperty = null;

    // Exception here, as expected
    Validator.ValidateObject(test, context);
  }
}
</code>```

For some reason, I do not get a validation exception when the string length is too long. I do get a validation exception (as expected) when I set the property to null and re-validate. Any ideas why my string length annotation is not being enforced?

答:
Thanks for posting this. I posted a bug on Microsoft Connect for this issue. I assume that they are incorrectly skipping a System.String property as it is not a value type because they do not do a deep/recursive validation without the "validateAllProperties" parameter.

Here's the bug link if you're interested:
https://connect.microsoft.com/VisualStudio/feedback/details/672247/system-componentmodel-dataannotations-validator-does-not-validate-stringlengthattribute-unless-validateallproperties-specified

ContentLicense: CC BY-SA 2.5

Body:
Here is my Test class with data annotations:

class Test
{
  [Required, StringLength(10)]
  public string MyProperty { get; set; }
}

Here is my console test program:

class Program
{
  static void Main(string[] args)
  {
    var test = new Test {
      MyProperty = "this is way more than 10 characters and should fail."
    };

    var context = new ValidationContext(test, null, null);

    // No exception here! (why not?)
    Validator.ValidateObject(test, context);

    test.MyProperty = null;

    // Exception here, as expected
    Validator.ValidateObject(test, context);
  }
}

For some reason, I do not get a validation exception when the string length is too long. I do get a validation exception (as expected) when I set the property to null and re-validate. Any ideas why my string length annotation is not being enforced?


问:
How to prevent shutil.move from overwriting a file if it already exists?
I'm using this Python code in Windows:

```<code>shutil.move(documents_dir + "\\" + file_name, documents_dir + "\\backup\\"
            + subdir_name + "\\" + file_name)
</code>```

When this code is called more times, it overwrites the destination file. I would like to move the file
and if the destination already exists, to rename it

e.g. file_name = foo.pdf

and in backup folder will be foo.pdf, foo(1).pdf, foo(2).pdf etc. or similarly e.g. with dashes
foo-1.pdf, foo-2.pdf etc.

答:
You could just check with os.path.exists() as you're going.

```<code>import os
import shutil

file_name = 'test.csv'
documents_dir = r'C:\BR\Test'
subdir_name = 'test'

# using os.path.join() makes your code easier to port to another OS
source = os.path.join(documents_dir, file_name)
dest = os.path.join(documents_dir, 'backup', subdir_name, file_name)

num = 0
# loop until we find a file that doesn't exist
while os.path.exists(dest):
    num += 1

    # use rfind to find your file extension if there is one
    period = file_name.rfind('.')
    # this ensures that it will work with files without extensions
    if period == -1:
        period = len(file_name)

    # create our new destination
    # we could extract the number and increment it
    # but this allows us to fill in the gaps if there are any
    # it has the added benefit of avoiding errors
    # in file names like this "test(sometext).pdf"
    new_file = f'{file_name[:period]}({num}){file_name[period:]}'

    dest = os.path.join(documents_dir, 'backup', subdir_name, new_file)

shutil.move(source, dest)
</code>```

Or since this is probably used in a loop you could just drop it into a function.

```<code>import os
import shutil

def get_next_file(file_name, dest_dir):
    dest = os.path.join(dest_dir, file_name)
    num = 0

    while os.path.exists(dest):
        num += 1

        period = file_name.rfind('.')
        if period == -1:
            period = len(file_name)

        new_file = f'{file_name[:period]}({num}){file_name[period:]}'

        dest = os.path.join(dest_dir, new_file)

    return dest

file_name = 'test.csv'
documents_dir = r'C:\BR\Test'
subdir_name = 'test'

source = os.path.join(documents_dir, file_name)

dest = get_next_file(file_name, os.path.join(documents_dir, 'backup', subdir_name))

shutil.move(source, dest)

</code>```

Body:
I'm using this Python code in Windows:

shutil.move(documents_dir + "\\" + file_name, documents_dir + "\\backup\\"
            + subdir_name + "\\" + file_name)

When this code is called more times, it overwrites the destination file. I would like to move the file
and if the destination already exists, to rename it

e.g. file_name = foo.pdf

and in backup folder will be foo.pdf, foo(1).pdf, foo(2).pdf etc. or similarly e.g. with dashes
foo-1.pdf, foo-2.pdf etc.

Body:
You could just check with os.path.exists() as you're going.

import os
import shutil

file_name = 'test.csv'
documents_dir = r'C:\BR\Test'
subdir_name = 'test'

# using os.path.join() makes your code easier to port to another OS
source = os.path.join(documents_dir, file_name)
dest = os.path.join(documents_dir, 'backup', subdir_name, file_name)

num = 0
# loop until we find a file that doesn't exist
while os.path.exists(dest):
    num += 1

    # use rfind to find your file extension if there is one
    period = file_name.rfind('.')
    # this ensures that it will work with files without extensions
    if period == -1:
        period = len(file_name)

    # create our new destination
    # we could extract the number and increment it
    # but this allows us to fill in the gaps if there are any
    # it has the added benefit of avoiding errors
    # in file names like this "test(sometext).pdf"
    new_file = f'{file_name[:period]}({num}){file_name[period:]}'

    dest = os.path.join(documents_dir, 'backup', subdir_name, new_file)

shutil.move(source, dest)

Or since this is probably used in a loop you could just drop it into a function.

import os
import shutil

def get_next_file(file_name, dest_dir):
    dest = os.path.join(dest_dir, file_name)
    num = 0

    while os.path.exists(dest):
        num += 1

        period = file_name.rfind('.')
        if period == -1:
            period = len(file_name)

        new_file = f'{file_name[:period]}({num}){file_name[period:]}'

        dest = os.path.join(dest_dir, new_file)

    return dest

file_name = 'test.csv'
documents_dir = r'C:\BR\Test'
subdir_name = 'test'

source = os.path.join(documents_dir, file_name)

dest = get_next_file(file_name, os.path.join(documents_dir, 'backup', subdir_name))

shutil.move(source, dest)


问:
how to reslove wrong username and password error in h2 database and springboot?
Properties used in application.properties

```<code>server.port=8085
spring.datasource.url=jdbc:h2:~/test spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.path=/h2
</code>```

Error
how to reslove wrong username and password error in h2 database and springboot?

```<code>org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Wrong user name or password [28000-200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:461) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:205) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:181) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:170) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.validateUserAndPassword(Engine.java:357) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.createSessionAndValidate(Engine.java:176) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.createSession(Engine.java:166) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.createSession(Engine.java:29) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:340) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:173) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:152) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.Driver.connect(Driver.java:69) ~[h2-1.4.200.jar:1.4.200]
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-3.4.5.jar:na]
    at org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration.lambda$h2Console$0(H2ConsoleAutoConfiguration.java:73) [spring-boot-autoconfigure-2.3.0.RELEASE.jar:2.3.0.RELEASE]
</code>```

答:
Try to delete DB files (test.mv.db and test.trace.db).
Maybe you have created it before and used for it different credentials.</p>

Body:
Properties used in application.properties

server.port=8085
spring.datasource.url=jdbc:h2:~/test spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.path=/h2

Error
how to reslove wrong username and password error in h2 database and springboot?

org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Wrong user name or password [28000-200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:461) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:205) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:181) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:170) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.validateUserAndPassword(Engine.java:357) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.createSessionAndValidate(Engine.java:176) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.createSession(Engine.java:166) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.createSession(Engine.java:29) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:340) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:173) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:152) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.Driver.connect(Driver.java:69) ~[h2-1.4.200.jar:1.4.200]
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-3.4.5.jar:na]
    at org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration.lambda$h2Console$0(H2ConsoleAutoConfiguration.java:73) [spring-boot-autoconfigure-2.3.0.RELEASE.jar:2.3.0.RELEASE]


答:
You need to return accumulator, instead you are returning the return value of push function which is the size of the array after adding the new item. In next iteration, you are calling push function on an integer

```<code>const flattenedProfiles = profiles.reduce((acc, curr) => {
  acc.push({
     id: curr.id,
     name: users[curr.id].name,
     favoriteMovie: movies[curr.favoriteMovieID].name
  });

  return acc;
},[]);
</code>```

Title: array reduce accumulator as an empty array, push not working

Body:
Why is the accumulator.push  not valid? accumulator is an empty array!? If i use the predefined variable flarArray, things work just fine!! I know that if no initial value is included in the reduce callback, then it will use the first item in the array (which in my case will be an object) to be the accumulator, but if I tell it to start off as an array as the accumulator, what is the problem with that?

const profiles = [
  {
    id: 1,
    userID: '1',
    favoriteMovieID: '1',
  },
  {
    id: 2,
    userID: '2',
    favoriteMovieID: '1',
  }
];

const users = {
  1: {
    id: 1,
    name: 'Jane Cruz',
    userName: 'coder',
  },
  2: {
    id: 2,
    name: 'Matthew Johnson',
    userName: 'mpage',
  }
};

const movies = {
  1: {
    id: 1,
    name: 'Planet Earth 1',
  },
  2: {
    id: 2,
    name: 'Selma',
  }
};
let flatArray = [];
const flattenedProfiles = profiles.reduce(function(accumulator, currentProfile) {
  return accumulator.push({id: currentProfile.id, name: users[currentProfile.id].name, favoriteMovie: movies[currentProfile.favoriteMovieID].name})
},[]);

Body:
You need to return accumulator, instead you are returning the return value of push function which is the size of the array after adding the new item. In next iteration, you are calling push function on an integer

const flattenedProfiles = profiles.reduce((acc, curr) => {
  acc.push({
     id: curr.id,
     name: users[curr.id].name,
     favoriteMovie: movies[curr.favoriteMovieID].name
  });

  return acc;
},[]);


问:
Return related objects in select linq to sql
I have 2 tables Account and Address which has 1:1 relationsip; account has addressid in it. I have created the association in the dbml file. Now I want to write a query to select the account for given accountid and the resulting account should contain the address object in it as well.

```<code> using (var context = new SalesLogixDataClassesDataContext())
        {
            var query = context.ACCOUNTs
                .Where(a => a.ACCOUNTID == id)
                .Select(a => new Account {AccountId = id, AccountName = a.ACCOUNT1, Address=a.ADDRESS});

            return query.FirstOrDefault();
        }
</code>```

But the address is null in the returned object. So what do i have to do in the query so that the address object is also retrieved.

EDIT: Sorry guys for leading you to a wild goose chase. I had the association mapped wrong(Address.AddressId as mapped to Account.AccountId). I fixed that and its working fine now. Thank you all for the help.

答:
Take a closer look at the object relation you have configured, specially the keys involved. Regardless of wanting/needing to use custom objects, the query as you provided will get you the related address, as long as the relations are configured correctly and the data is in the db.

Here is a sample real life config, where StateMaster has a CustomerMasters1 property (naming is being cleaned up :)

OwnerDisplayName: Satish

Body:
I have 2 tables Account and Address which has 1:1 relationsip; account has addressid in it. I have created the association in the dbml file. Now I want to write a query to select the account for given accountid and the resulting account should contain the address object in it as well.

 using (var context = new SalesLogixDataClassesDataContext())
        {
            var query = context.ACCOUNTs
                .Where(a => a.ACCOUNTID == id)
                .Select(a => new Account {AccountId = id, AccountName = a.ACCOUNT1, Address=a.ADDRESS});

            return query.FirstOrDefault();
        }

But the address is null in the returned object. So what do i have to do in the query so that the address object is also retrieved.

EDIT: Sorry guys for leading you to a wild goose chase. I had the association mapped wrong(Address.AddressId as mapped to Account.AccountId). I fixed that and its working fine now. Thank you all for the help.

LastEditorDisplayName: Satish

OwnerDisplayName: Freddy Rios

LastEditorDisplayName: Freddy Rios


问:
Unsafe value used in a resource URL context (iframe)
Trying to pass value as iframe url from local db and and im getting error message:
 Unsafe value used in a resource URL context.
i'm trying to display an array of printers ip so i will be able to check their status via the website there is anyway to do this without iframe ?
i will be more then glad to hear some advises.

I'm new to angular and every help is more then welcome
thanks in advance.

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})

export class ValueComponent implements OnInit {
  values: any;

  constructor(private http: HttpClient, private sanitizer: DomSanitizer) { }

ngOnInit() {
  this.getValues();

}

getValues() {
  this.http.get('http://localhost:5000/api/values/').subscribe(response => {
    this.values = response;
  }, error => {
    console.log(error);
  })
}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><H2>Print Manager</H2>

<div id="outerdiv">
  <iframe src="http://192.168.1.6/general/status.html" id="inneriframe" scrolling="no"  ></iframe>
</div>

<div *ngFor="let value of values">
<p>{{value.id}},{{value.hostName}},{{value.location}},{{value.manufacturer}},{{value.ip}}</p>

<span>Hostname: {{value.hostName}}</span>
<br>
<span>Location: {{value.location}}</span>
<br>
<span>Manufacturer: {{value.manufacturer}}</span>
<br>
<span>IP: {{value.ip}}</span>

</div></code>```

答:
[src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')"
solved it for me</p>

Body:
Trying to pass value as iframe url from local db and and im getting error message:
 Unsafe value used in a resource URL context.
i'm trying to display an array of printers ip so i will be able to check their status via the website there is anyway to do this without iframe ?
i will be more then glad to hear some advises.

I'm new to angular and every help is more then welcome
thanks in advance.

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})

export class ValueComponent implements OnInit {
  values: any;

  constructor(private http: HttpClient, private sanitizer: DomSanitizer) { }

ngOnInit() {
  this.getValues();

}

getValues() {
  this.http.get('http://localhost:5000/api/values/').subscribe(response => {
    this.values = response;
  }, error => {
    console.log(error);
  })
}

}

Print Manager

{{value.id}},{{value.hostName}},{{value.location}},{{value.manufacturer}},{{value.ip}}

Hostname: {{value.hostName}}

Location: {{value.location}}

Manufacturer: {{value.manufacturer}}

IP: {{value.ip}}


问:
Python - Search for multiple files in subfolder present inside a bucket using boto3
So I have a requirement of downloading all the JSON files that are uploaded to the subfolder present inside the bucket.

Is there any way to do so?

I tried the following way:

```<code>for key in bucket_name.objects.filter(Prefix='report'):
        print key
        s3_client.download_file(key, bucket_name, '{}/{}'.format(current_directory, key))
</code>```

And I'm getting the following error on doing so:

AttributeError: 'str' object has no attribute 'objects'

答:
On listing the files present in bucket, i was getting output as -

```<code>s3.ObjectSummary(bucket_name='', key=u'file_Searching_for')
</code>```

After trying multiple options i came upto the following code-

```<code>def main():

    objs = bucket_name.objects.filter(Prefix=Prefix_name)

    for obj in objs:
        filename = obj.key
        if filename.endswith('.json'):
           <download the file if you want to>
</code>```

From the above code, it will give you the file name with the prefix, which you can split and download the file.
It will help you to download any number of files that are present in the bucket which ends with .json

Let me know if the answer helps you. It helped me out.

Thanks

Body:
So I have a requirement of downloading all the JSON files that are uploaded to the subfolder present inside the bucket.

Is there any way to do so?

I tried the following way:

for key in bucket_name.objects.filter(Prefix='report'):
        print key
        s3_client.download_file(key, bucket_name, '{}/{}'.format(current_directory, key))

And I'm getting the following error on doing so:

AttributeError: 'str' object has no attribute 'objects'

Body:
On listing the files present in bucket, i was getting output as -

s3.ObjectSummary(bucket_name='', key=u'file_Searching_for')

After trying multiple options i came upto the following code-

def main():

    objs = bucket_name.objects.filter(Prefix=Prefix_name)

    for obj in objs:
        filename = obj.key
        if filename.endswith('.json'):
           <download the file if you want to>

From the above code, it will give you the file name with the prefix, which you can split and download the file.
It will help you to download any number of files that are present in the bucket which ends with .json

Let me know if the answer helps you. It helped me out.

Thanks


答:
You only have to make two little changes to your js code.

The first is, that you have to call alertaislas on change of the input and you have to change the show and hide method, to css("display","block") and css("display","none")

Here is the corrected code:

```<code>$(document).ready(function(){
  function alertaislas() {
    const total = Number($("#enviara").val().replace(".",""));

    if(total > 28999 && total < 29999) {
      $('#alert-one').css("display", "block");
    }

    else{
      $('#alert-one').css("display", "none");
}}

    $("#enviara").change(alertaislas);
});
</code>```

Title: JS - Show a div only when a number is typed

Body:
I have a form with an input type="number", and I need to display a div if the user types a number within a range.

My current code only works when I reload the page, but I want to display the "#alert-one" div when the numeric range is typed (not when the page reloads).

What am I doing wrong...?

Thanks in advance!

CSS:

#alert-one {
    display:none
}

HTML:

Hello

<input type="number" id="enviara" name="enviara" maxlength="5" required>

Script:

$(document).ready(function(){
  function alertaislas() {
    const total = Number($("#enviara").val().replace(".",""));

    if(total > 28999 && total < 29999) {
      $('#alert-one').show();
    }

    else{
      $('#alert-one').hide();
}}

    alertaislas();
});

Body:
You only have to make two little changes to your js code.

The first is, that you have to call alertaislas on change of the input and you have to change the show and hide method, to css("display","block") and css("display","none")

Here is the corrected code:

$(document).ready(function(){
  function alertaislas() {
    const total = Number($("#enviara").val().replace(".",""));

    if(total > 28999 && total < 29999) {
      $('#alert-one').css("display", "block");
    }

    else{
      $('#alert-one').css("display", "none");
}}

    $("#enviara").change(alertaislas);
});


问:
UILabel word wrapping brings extra word to next line when there is enough space for it
Under certain circumstances, UILabel seems to bring an extra word to new line even when there is enough space for it, for example,

If one more word is appended,

Even if I force the width of the label to become something like below, it still moves the word consists of "c"s to the next line,

I've tried twisting the configuration of the UILabel, but seems it behaves the same unless I set the line breaking mode to character wrap, below is the configuration for the above cases,

And the constraints (in the first two cases, the trailing ),

Is there any reason for this particular behaviour and can I fix this? It looks weird in this way leaving that space emptied.

答:
this is the default behavior since iOS 11, to fix orphaned words. No way to shut it off

to fix it
use the text as attributed text

or
use UItextview and turn of the scroll, edit option

or
use the custom label here
Get each line of text in a UILabel


问:
Javascript doesnt recognize anything from html (spring boot)
This is my first time with spring boot. So, I have a simple index.html page, i go to it just through localhost:8080. I have some console.log() in my js under the html and they dont log a single thing. The api does work though, i tried it in postman and there is no problem. But it seems that the js doesnt recognize anything of the html. This is what the console.log() prints in the console:

As you can see they are empty. See my structure and my code below:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Page</title>
</head>
<body>

<form id="loginform">
    <div class="form-group">
        <label for="Username">Username</label>
        <input name="username" class="form-control" type="text" placeholder="Enter username" required>
    </div>
    <div class="form-group">
        <label for="Password">Password</label>
        <input name="password" class="form-control" type="password" placeholder="Password" required>
    </div>
    <button id="login">Login</button>
</form>

<script>
    function login() {
        var formData = new FormData(document.querySelector("#loginform"));
        var encData = new URLSearchParams(formData.entries());
        console.log(formData);
        console.log(encData);
        console.log(document.querySelector("#loginform"));

        fetch("/authenticate", {method: 'POST', body: encData})
            .then(function (response) {
                if (response.ok) {
                    window.location.href = "/lingogame.html";
                    return response.json();
                } else {
                    alert("Invalid Username or password");
                }
            })
            .then(myJson => window.sessionStorage.setItem("myJWT", myJson.JWT))
            .catch(error => console.log(error));
    }

    var loginButton = document.querySelector("#login")
    if (loginButton) {
        loginButton.addEventListener("click", login);
    }
</script>
</body>
</html>
</code>```

答: The problem may result from CSRF support of Spring Security. Check CSRF support is enabled or disabled, by default it is enabled by Spring Security. If enabled you must be send csrf_token with "X-CSRF-TOKEN" header with csrfToken value, otherwise it is not required.</p>

Body:
This is my first time with spring boot. So, I have a simple index.html page, i go to it just through localhost:8080. I have some console.log() in my js under the html and they dont log a single thing. The api does work though, i tried it in postman and there is no problem. But it seems that the js doesnt recognize anything of the html. This is what the console.log() prints in the console:

As you can see they are empty. See my structure and my code below:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Page</title>

<form id="loginform">

        Username
        <input name="username" class="form-control" type="text" placeholder="Enter username" required>

        Password
        <input name="password" class="form-control" type="password" placeholder="Password" required>

    <button id="login">Login</button>
</form>


问:
C# Nullable: Make nullchecking dependent on another property/variable
I have just enabled null checking in my .net core 3.1 project.

The problem is that I have a response class

```<code>public class DecryptResponse
{
    public DecryptStatus Status { get; set; }

    //This is the attribute in question
    [NotNullWhen(Status==DecryptStatus.Ok)]
    public Stream? Stream { get; set; }

    public string? ErrorMessage { get; set; }
}

public enum DecryptStatus
{
    Ok,
    InvalidData,
    KeyChecksumFailure,
    NoData,
    UnhandledError
}
</code>```

The above is used in this situation where the Verify method does not allow nulls.

But I know that the stream is not null since DecryptStatus==Ok

```<code>if (decryptResponse.Status != DecryptStatus.Ok)
    return (decryptResponse, null);

var verifyResponse = Verify(customerId, decryptResponse.Stream);
return (decryptResponse, verifyResponse);
</code>```

Are there any tags that allows for this logic or does it need a major rewrite of the code?

答:
NotNullWhenAttribute is for usage with parameters only. It tells the compiler that (out) parameter is not null when the method returned specified value (true or false). E.g.

```<code>public bool TryParse(string s, [NotNullWhen(true)] out Person person);
</code>```

It means that person will not be null when method returned true.

But this attribute is not suitable for your what you trying to achieve:

NotNullWhen cannot be applied to class properties - it can be used only with method parameters.

NotNullWhen does not provide dependency on some external value (like class property) - it can only use the return value of the method parameter belongs to. And even more, this return value can be only boolean.

But you can try to use method instead

```<code>public bool TryDecrypt(Foo bar,
    [NotNullWhen(false) out DecryptError error, // wraps error status & message
    [NotNullWhen(true)] out Stream stream)
</code>```

Or use null-forgiving operator

```<code>if (decryptResponse.Status == DecryptStatus.Ok)
{
    // decryptResponse.Stream!
}
</code>```

Body:
I have just enabled null checking in my .net core 3.1 project.

The problem is that I have a response class

public class DecryptResponse
{
    public DecryptStatus Status { get; set; }

    //This is the attribute in question
    [NotNullWhen(Status==DecryptStatus.Ok)]
    public Stream? Stream { get; set; }

    public string? ErrorMessage { get; set; }
}

public enum DecryptStatus
{
    Ok,
    InvalidData,
    KeyChecksumFailure,
    NoData,
    UnhandledError
}

The above is used in this situation where the Verify method does not allow nulls.

But I know that the stream is not null since DecryptStatus==Ok

if (decryptResponse.Status != DecryptStatus.Ok)
    return (decryptResponse, null);

var verifyResponse = Verify(customerId, decryptResponse.Stream);
return (decryptResponse, verifyResponse);

Are there any tags that allows for this logic or does it need a major rewrite of the code?

Body:
NotNullWhenAttribute is for usage with parameters only. It tells the compiler that (out) parameter is not null when the method returned specified value (true or false). E.g.

public bool TryParse(string s, [NotNullWhen(true)] out Person person);

It means that person will not be null when method returned true.

But this attribute is not suitable for your what you trying to achieve:

NotNullWhen cannot be applied to class properties - it can be used only with method parameters.

NotNullWhen does not provide dependency on some external value (like class property) - it can only use the return value of the method parameter belongs to. And even more, this return value can be only boolean.

But you can try to use method instead

public bool TryDecrypt(Foo bar,
    [NotNullWhen(false) out DecryptError error, // wraps error status & message
    [NotNullWhen(true)] out Stream stream)

Or use null-forgiving operator

if (decryptResponse.Status == DecryptStatus.Ok)
{
    // decryptResponse.Stream!
}