问:
How to make my cursor behave like a pen in my sketch webpage project?
I set up a grid 16x16 which a white background now i want the divs (grid items) to change color every time i press and hold my mouse and move over them, and to stop changing color when i stop the mousedown event, like in paint. in my script:

```<code>let gridContainer = document.getElementById('grid-container');
let gridArray = [];
for(let i = 0; i < 256; i++){
    let div = document.createElement('div');
    div.setAttribute('class', 'grid-item');
    gridContainer.append(div);
    gridArray[i] = div;
}

gridContainer.addEventListener("mousedown", draw)
gridContainer.addEventListener("mouseup",stopDraw)

function draw(){
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        (item.classList.add('hover'))
    }));
}

function stopDraw(){
    gridArray.forEach(item => item.removeEventListener("mouseover", () => {
        (item.classList.add('hover'))
    }));
}
</code>```

The hover class is used to change the background color to blue.

I tried multiple other approaches but i always end up at the same place, the draw function not working unless i click which runs the function then it doesnt stop, it keeps running even after i leave the mouse.

Im using vanilla JS, I am still learning the basics.

Here is my code for better understanding my problem: https://codepen.io/ahmedmk11/pen/VwrmyGW

EDIT: I just realized that i didnt explain my problem in a clear way, so the draw function works properly, but my problem is that it doesnt stop working, i need in to only work when im pressing and holding only, like a pen.

答:
Looks like you say that the div's should be paint when the mouse button is pressed, but you never really say that the divs should not be painted when the mouse button is not pressed, this happen in this specifc part:

```<code>function draw(){
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        (item.classList.add('hover'))
    }));
}

function stopDraw(){
    // right here!
    gridArray.forEach(item => item.removeEventListener("mouseover", () => {
        (item.classList.add('hover'))
    }));
}
</code>```

You could change your code to make something like "hey, when my mouse is up and over the divs, I don't want to insert the class that paint them", like this:

```<code>function draw(){
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        item.classList.add('hover');
    }));
}

function stopDraw(){
    // now we have a event that removes the class
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        item.classList.remove('hover');
    }));
}
</code>```

I also did some refactor (changed let by const when necessary, corrected the layout and moved the use of the functions draw and stopDraw after his declarations), I tried make less changes as I could, the final solution is:

```<code>const gridContainer = document.getElementById('grid-container');
let gridArray = [];
for(let i = 0; i < 256; i += 1){
    const div = document.createElement('div');
    div.setAttribute('class', 'grid-item');
    gridContainer.append(div);
    gridArray.push(div);
}

function draw(){
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        item.classList.add('hover');
    }));
}

function stopDraw(){
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        item.classList.remove('hover');
    }));
}

gridContainer.addEventListener("mousedown", draw);
gridContainer.addEventListener("mouseup", stopDraw);
</code>```

Body:
I set up a grid 16x16 which a white background now i want the divs (grid items) to change color every time i press and hold my mouse and move over them, and to stop changing color when i stop the mousedown event, like in paint. in my script:

let gridContainer = document.getElementById('grid-container');
let gridArray = [];
for(let i = 0; i < 256; i++){
    let div = document.createElement('div');
    div.setAttribute('class', 'grid-item');
    gridContainer.append(div);
    gridArray[i] = div;
}

gridContainer.addEventListener("mousedown", draw)
gridContainer.addEventListener("mouseup",stopDraw)

function draw(){
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        (item.classList.add('hover'))
    }));
}

function stopDraw(){
    gridArray.forEach(item => item.removeEventListener("mouseover", () => {
        (item.classList.add('hover'))
    }));
}

The hover class is used to change the background color to blue.

I tried multiple other approaches but i always end up at the same place, the draw function not working unless i click which runs the function then it doesnt stop, it keeps running even after i leave the mouse.

Im using vanilla JS, I am still learning the basics.

Here is my code for better understanding my problem: https://codepen.io/ahmedmk11/pen/VwrmyGW

EDIT: I just realized that i didnt explain my problem in a clear way, so the draw function works properly, but my problem is that it doesnt stop working, i need in to only work when im pressing and holding only, like a pen.

Body:
Looks like you say that the div's should be paint when the mouse button is pressed, but you never really say that the divs should not be painted when the mouse button is not pressed, this happen in this specifc part:

function draw(){
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        (item.classList.add('hover'))
    }));
}

function stopDraw(){
    // right here!
    gridArray.forEach(item => item.removeEventListener("mouseover", () => {
        (item.classList.add('hover'))
    }));
}

You could change your code to make something like "hey, when my mouse is up and over the divs, I don't want to insert the class that paint them", like this:

function draw(){
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        item.classList.add('hover');
    }));
}

function stopDraw(){
    // now we have a event that removes the class
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        item.classList.remove('hover');
    }));
}

I also did some refactor (changed let by const when necessary, corrected the layout and moved the use of the functions draw and stopDraw after his declarations), I tried make less changes as I could, the final solution is:

const gridContainer = document.getElementById('grid-container');
let gridArray = [];
for(let i = 0; i < 256; i += 1){
    const div = document.createElement('div');
    div.setAttribute('class', 'grid-item');
    gridContainer.append(div);
    gridArray.push(div);
}

function draw(){
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        item.classList.add('hover');
    }));
}

function stopDraw(){
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        item.classList.remove('hover');
    }));
}

gridContainer.addEventListener("mousedown", draw);
gridContainer.addEventListener("mouseup", stopDraw);


来源: stackexchange

问:
Adding a number with a plus button
I want to make a button that will ad a number to existing field. My code:

HTML:

```<code><div class="str">
    <div class="str-img"><div>10</div></div>
    <div class="stat-plus"><img src="images/plus.png" alt="Plus"></div>
    <div class="stat-minus"><img src="images/minus.png" alt="Minus"></div>
    <input type="hidden" name="register-str" value="10">
</div>
</code>```

JAVASCRIPT:

```<code>$(document).ready(function() {
    $('.str .stat-plus img').click(function() {
        var val = $('.str-img div').val();
        var new_val = parseInt($('.str-img div').val(),10) + 1 ;
        $('.str-img div').val(new_val);
    });
});
</code>```

答:
The val method is primarily used to get the values of form elements such as input, select and textarea.

Instead of val method, you can use text or html method on $('.str-img div') element, like this:

$(document).ready(
    function() {
        $('.str .stat-plus img').click(function() {
            var val = $('.str-img div').html();
            var new_val = parseInt(val,10) + 1 ;
            $('.str-img div').html(new_val);
        });
    }
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="str">
  <div class="str-img">
    <div>10</div>
  </div>
  <div class="stat-plus"><img src="images/plus.png" alt="Plus"></div>
  <div class="stat-minus"><img src="images/minus.png" alt="Minus"></div>
  <input type="hidden" name="register-str" value="10">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

ContentLicense: CC BY-SA 4.0

Title: Adding a number with a plus button

Body:
I want to make a button that will ad a number to existing field. My code:

HTML:

10

    <input type="hidden" name="register-str" value="10">

JAVASCRIPT:

$(document).ready(function() {
    $('.str .stat-plus img').click(function() {
        var val = $('.str-img div').val();
        var new_val = parseInt($('.str-img div').val(),10) + 1 ;
        $('.str-img div').val(new_val);
    });
});

Body:
The val method is primarily used to get the values of form elements such as input, select and textarea.

Instead of val method, you can use text or html method on $('.str-img div') element, like this:

$(document).ready(
    function() {
        $('.str .stat-plus img').click(function() {
            var val = $('.str-img div').html();
            var new_val = parseInt(val,10) + 1 ;
            $('.str-img div').html(new_val);
        });
    }
);

<div class="str">
  <div class="str-img">
    <div>10</div>
  </div>
  <div class="stat-plus"><img src="images/plus.png" alt="Plus"></div>
  <div class="stat-minus"><img src="images/minus.png" alt="Minus"></div>
  <input type="hidden" name="register-str" value="10">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
Angular: DI in inherited component from abstract base
So in my Angular project, I was trying to have an abstract base class for editing forms. Let's call it Editor.

There will be many components that do operations on a form so they inherit from the base class. For example, there is a component which edits a user. So the component would look like this

```<code>export abstract class Editor {
  public form!: FormGroup;
  private _hasChanges = false;

  constructor() {
    this.createForm();
    this.subscribe();
  }

  protected abstract createForm(): void;

  private subscribe(): void {
    this.form.valueChanges.subscribe((_) => {
      this._hasChanges = true;
    });
  }

  public get hasChanges(): boolean {
    return this._hasChanges;
  }
}

@Component({
  selector: 'user-editor',
  templateUrl: './user-editor.component.html',
  styleUrls: ['./user-editor.component.scss'],
})
export class UserEditorComponent extends Editor {
  public dummy = 'dummyText';

  constructor(private fb: FormBuilder) {
    super();
  }

  protected createForm(): void {
    this.form = this.fb.group(
      name: ['', Validators.required]
    );
  }
}
</code>```

But this sample won't work! in the implementatoin of createForm, this.fb will be undefined. Even more, when putting a breakpoint and inspecting this. It seems like we are not in the chlid component but in the parent component.

Since the 'dummy' variable is not there.

I made a minimal reproducible sample here

答:
Since you have never passed the FormBuilder dependency to your parent class, it's undefined in it's scope.

In your UserEditorComponent's constructor you have to call the parent class by the super() method, which instantiates your parent class then applies everything provided by your child class.

If you modify your baseClass to accept parameters:

```<code>// Editor
constructor(private fb: FormBuilder) {
  this.createForm();
  this.subscribe();
}
</code>```

And your child's constructor:

```<code>// UserEditorComponent
constructor(private fb: FormBuilder) {
  super(fb);
}
</code>```

Then you can pass your dependency.

Alternatively (this is not tested), but if you would call the init methods in your child instead of the base class, it also should work:

```<code>// UserEditorComponent
constructor(private fb: FormBuilder) {
  super();
  this.createForm();
  this.subscribe();
}
</code>```

Because you have already initialzed your base class and the dependencies are available in your child class. Although, this is highly impractical.

A more sophisticated solution would be the use of Angular's injector.
If you have multiple dependencies, maybe it would be worth it to pass only the injector into your base class and cherry-pick what you need there.

There's an explanation about the injector here: https://stackoverflow.com/a/41433007/5627312

Body:
So in my Angular project, I was trying to have an abstract base class for editing forms. Let's call it Editor.

There will be many components that do operations on a form so they inherit from the base class. For example, there is a component which edits a user. So the component would look like this

export abstract class Editor {
  public form!: FormGroup;
  private _hasChanges = false;

  constructor() {
    this.createForm();
    this.subscribe();
  }

  protected abstract createForm(): void;

  private subscribe(): void {
    this.form.valueChanges.subscribe((_) => {
      this._hasChanges = true;
    });
  }

  public get hasChanges(): boolean {
    return this._hasChanges;
  }
}

@Component({
  selector: 'user-editor',
  templateUrl: './user-editor.component.html',
  styleUrls: ['./user-editor.component.scss'],
})
export class UserEditorComponent extends Editor {
  public dummy = 'dummyText';

  constructor(private fb: FormBuilder) {
    super();
  }

  protected createForm(): void {
    this.form = this.fb.group(
      name: ['', Validators.required]
    );
  }
}

But this sample won't work! in the implementatoin of createForm, this.fb will be undefined. Even more, when putting a breakpoint and inspecting this. It seems like we are not in the chlid component but in the parent component.

Since the 'dummy' variable is not there.

I made a minimal reproducible sample here

Body:
Since you have never passed the FormBuilder dependency to your parent class, it's undefined in it's scope.

In your UserEditorComponent's constructor you have to call the parent class by the super() method, which instantiates your parent class then applies everything provided by your child class.

If you modify your baseClass to accept parameters:

// Editor
constructor(private fb: FormBuilder) {
  this.createForm();
  this.subscribe();
}

And your child's constructor:

// UserEditorComponent
constructor(private fb: FormBuilder) {
  super(fb);
}

Then you can pass your dependency.

Alternatively (this is not tested), but if you would call the init methods in your child instead of the base class, it also should work:

// UserEditorComponent
constructor(private fb: FormBuilder) {
  super();
  this.createForm();
  this.subscribe();
}

Because you have already initialzed your base class and the dependencies are available in your child class. Although, this is highly impractical.

A more sophisticated solution would be the use of Angular's injector.
If you have multiple dependencies, maybe it would be worth it to pass only the injector into your base class and cherry-pick what you need there.

There's an explanation about the injector here: https://stackoverflow.com/a/41433007/5627312


问:
How can I use the LIKE operator on a map type in hiveql?
I want to select two columns out of students:

```<code>id_test         int
number  map<string,string>
</code>```

I tried followed command with the LIKE Operator:

```<code>SELECT id_test ,number FROM students WHERE id_test = 123456 AND number LIKE %MOBILE%;
</code>```

And get this error:

```<code>FAILED: SemanticException [Error 10014]: Line 1:82 Wrong arguments ''%MOBILE%'': No
matching method for class org.apache.hadoop.hive.ql.udf.UDFLike with
(map<string,string>, string). Possible choices: _FUNC_(string, string)
</code>```

Code for reproduction:

```<code>CREATE TABLE students(id_test INT, number MAP<STRING, STRING>) ROW FORMAT DELIMITED FIELDS TERMINATED by
'|' COLLECTION ITEMS TERMINATED BY ',' MAP KEYS TERMINATED BY ':';

INSERT INTO TABLE students SELECT 123434, map('MOBILE','918-555-1162') FROM existingtable LIMIT 1;
INSERT INTO TABLE students SELECT 245678, map('WORK','806-555-4722') FROM existingtable LIMIT 1;
</code>```

答:
```<code>select *
from   students
where  concat_ws(' ',map_keys(number)) like '%MOBILE%'
</code>```

The following is posted here just that you could see how the expression used with LIKE looks like:

```<code>select concat_ws(' ',map_keys(number))
from   students

+-----------------------+
|          _c0          |
+-----------------------+
| MOBILE MOBILE2 OFFICE |
| WORK                  |
+-----------------------+
</code>```

Body:
I want to select two columns out of students:

id_test         int
number  map<string,string>

I tried followed command with the LIKE Operator:

SELECT id_test ,number FROM students WHERE id_test = 123456 AND number LIKE %MOBILE%;

And get this error:

FAILED: SemanticException [Error 10014]: Line 1:82 Wrong arguments ''%MOBILE%'': No
matching method for class org.apache.hadoop.hive.ql.udf.UDFLike with
(map<string,string>, string). Possible choices: _FUNC_(string, string)

Code for reproduction:

CREATE TABLE students(id_test INT, number MAP<STRING, STRING>) ROW FORMAT DELIMITED FIELDS TERMINATED by
'|' COLLECTION ITEMS TERMINATED BY ',' MAP KEYS TERMINATED BY ':';

INSERT INTO TABLE students SELECT 123434, map('MOBILE','918-555-1162') FROM existingtable LIMIT 1;
INSERT INTO TABLE students SELECT 245678, map('WORK','806-555-4722') FROM existingtable LIMIT 1;

Body:
select *
from   students
where  concat_ws(' ',map_keys(number)) like '%MOBILE%'

The following is posted here just that you could see how the expression used with LIKE looks like:

select concat_ws(' ',map_keys(number))
from   students

+-----------------------+
|          _c0          |
+-----------------------+
| MOBILE MOBILE2 OFFICE |
| WORK                  |
+-----------------------+


问:
How to parse an array of data in PHP separated by a semicolon and display each section as a new line on an HTML page?
What I got is an array coming as in the format below.
What I would need to do is to print each block of string, separated by an ";" to a new line on an html page.

For example, the two lines below would be printed after processing the array below them.

```<code>Tesla motors : 60%
Mercedes Benz : 40%
</code>```

How to split this data to an array, which could then be looped thru and display each one on page? The separator here is ";" semicolon.

Thank you so much already in advance!
Yours,

```<code>array (
  0 => 'T',
  1 => 'e',
  2 => 's',
  3 => 'l',
  4 => 'a',
  5 => ' ',
  6 => 'm',
  7 => 'o',
  8 => 't',
  9 => 'o',
  10 => 'r',
  11 => 's',
  45 => ' ',
  46 => ':',
  47 => ' ',
  48 => '60',
  49 => '%',
  50 => ';'
  53 => 'M',
  53 => 'e',
  53 => 'r',
  54 => 'c',
  55 => 'e',
  56 => 'd',
  57 => 'e',
  58 => 's',
  59 => ' ',
  60 => 'B',
  61 => 'e',
  62 => 'n',
  63 => 'z',
  94 => ' ',
  95 => ':',
  96 => ' ',
  97 => '4',
  98 => '0',
  99 => '%',
  100 => ';'
)
</code>```

答:
First you should use implode() to with empty string as glue parameter.

This will transform your array into an string:

```<code>Tesla motors : 60%;Mercedes Benz : 40%
</code>```

Now you can either use explode() to get an array with one row for each line:

```<code>$output = explode(";", implode('', $input));
</code>```

Or you can replace the ; by a new line character:

```<code>$output = str_replace(";", "\n", implode('', $input));
</code>```

Body:
What I got is an array coming as in the format below.
What I would need to do is to print each block of string, separated by an ";" to a new line on an html page.

For example, the two lines below would be printed after processing the array below them.

Tesla motors : 60%
Mercedes Benz : 40%

How to split this data to an array, which could then be looped thru and display each one on page? The separator here is ";" semicolon.

Thank you so much already in advance!
Yours,

array (
  0 => 'T',
  1 => 'e',
  2 => 's',
  3 => 'l',
  4 => 'a',
  5 => ' ',
  6 => 'm',
  7 => 'o',
  8 => 't',
  9 => 'o',
  10 => 'r',
  11 => 's',
  45 => ' ',
  46 => ':',
  47 => ' ',
  48 => '60',
  49 => '%',
  50 => ';'
  53 => 'M',
  53 => 'e',
  53 => 'r',
  54 => 'c',
  55 => 'e',
  56 => 'd',
  57 => 'e',
  58 => 's',
  59 => ' ',
  60 => 'B',
  61 => 'e',
  62 => 'n',
  63 => 'z',
  94 => ' ',
  95 => ':',
  96 => ' ',
  97 => '4',
  98 => '0',
  99 => '%',
  100 => ';'
)

Body:
First you should use implode() to with empty string as glue parameter.

This will transform your array into an string:

Tesla motors : 60%;Mercedes Benz : 40%

Now you can either use explode() to get an array with one row for each line:

$output = explode(";", implode('', $input));

Or you can replace the ; by a new line character:

$output = str_replace(";", "\n", implode('', $input));


问:
MariaDB max connections
We have a big application that uses 40 microservices (Spring boot) that each have about 5 database connections to a mariadb server. That causes too many connection errors on our mariadb server. Default is 151 however I was thinking of just setting the max connections to 1000 to be on the safe side. I cant find anywhere on the Internet if this is possible or even wise. Our MariaDB is running standalone on a VPS with 8GB memory. It is not running in a docker container or something like that. It is run directly on the VPS.

What is the maximum connections advisable taking into consideration that we might scale up with our microservices?

答:
You can scale up your max_connections just fine. Put a line like

```<code>max_connections=250
</code>```

in your MariaDB my.cnf file. But don't just set it to a very high number; each potential connection consumes RAM, and with only 8GiB you need to be a bit careful about that.

If you give this command you'll get a bunch of data about your connections.

```<code>SHOW STATUS LIKE '%connect%';
</code>```

The important ones to watch:

Connection_errors_max_connections  The number of connection attempts that failed because you ran out of connection slots.

Connections  The total number of connections ever handled

Max_used_connections  The largest number of simultaneous connections used.

Max_used_connections_time   The date and time when the server had its largest number of connections.

The numbers shown are cumulative since the last server boot or the most recent FLUSH STATUS; statement.

Keep an eye on these. If you run short you can always add more. If you have to add many more connections as you scale up, you probably will need to provision your VPS with more RAM.  The last two are cool because you can figure out whether you're getting hammered at a particular time of day.

And, in your various microservices be very careful to use connection pools of reasonable maximum size. Don't let your microservices grab more than ten connections unless you run into throughput trouble. You didn't say what client tech you use (nodejs? dotnet? php? Java?) so it's hard to give you specific advice how to do that.

Title: MariaDB max connections

Body:
You can scale up your max_connections just fine. Put a line like

max_connections=250

in your MariaDB my.cnf file. But don't just set it to a very high number; each potential connection consumes RAM, and with only 8GiB you need to be a bit careful about that.

If you give this command you'll get a bunch of data about your connections.

SHOW STATUS LIKE '%connect%';

The important ones to watch:

Connection_errors_max_connections  The number of connection attempts that failed because you ran out of connection slots.

Connections  The total number of connections ever handled

Max_used_connections  The largest number of simultaneous connections used.

Max_used_connections_time   The date and time when the server had its largest number of connections.

The numbers shown are cumulative since the last server boot or the most recent FLUSH STATUS; statement.

Keep an eye on these. If you run short you can always add more. If you have to add many more connections as you scale up, you probably will need to provision your VPS with more RAM.  The last two are cool because you can figure out whether you're getting hammered at a particular time of day.

And, in your various microservices be very careful to use connection pools of reasonable maximum size. Don't let your microservices grab more than ten connections unless you run into throughput trouble. You didn't say what client tech you use (nodejs? dotnet? php? Java?) so it's hard to give you specific advice how to do that.


问:
Vue js cookies is undefined
I have installed the vue-cookies in my project.

I have included the following in the main.js file:

createApp(App)
    .use(store)
    .use(router, axios, VueCookies)
```
<p>Then the script part in the <em>App.vue</em> file contains the following:</p>
<pre class="lang-js prettyprint-override"><code><script>
import Navbar from '@/components/layout/Navbar'
import axios from 'axios'

export default {
  name: 'App',
  components: {
    Navbar
  },
  beforeCreate() {

    console.log(this.$cookies)

</code>```

This says cookies is undefined, so I can't set or get any cookies.

If I add a import VueCookies from 'vue-cookies' the result is the same.

Before, I used localStorage, and I used this beforeCreate to read the login information from it. I want to start using cookies to store the token between sessions, as I have read it's more secure.

I have searched arout a little bit I have not read anything regarding cookie initialization or anything else I have to do so that this.$cookies is not undefined.

答:
I have never used this library. But looking at npm: https://www.npmjs.com/package/vue-cookies

You have to import the library and use the plugin.

```<code>import VueCookies from 'vue-cookies';

Vue.use(VueCookies)
</code>```

***I assume that you have installed the library previously.

Title: Vue js cookies is undefined

Body:
I have installed the vue-cookies in my project.

I have included the following in the main.js file:

createApp(App)
    .use(store)
    .use(router, axios, VueCookies)

Then the script part in the App.vue file contains the following:

Body:
I have never used this library. But looking at npm: https://www.npmjs.com/package/vue-cookies

You have to import the library and use the plugin.

import VueCookies from 'vue-cookies';

Vue.use(VueCookies)

***I assume that you have installed the library previously.


问:
Setting Devise Login to be root page
I am using the following code for my routes:

```<code>devise_for :user,
  :as => '',
  :path_names => {
    :sign_in => "",
    :sign_out => "logout",
    :sign_up => "register"
  }
</code>```

But when I'm logged out and I goto /logout I get the following error:

No route matches {:action=>"new",
  :controller=>"devise/sessions"}

How do I setup the root path to be to :sign_in action?

答:
I'm new on rails and I didn't know your 'device_scope' name have to be different to your 'device_for' name. Notice my example.

I tried this a hundred times a this is why it didn't work jajaja

```<code>  devise_for :user_devises, path: 'user_devises'

  devise_scope :user_devise do
    authenticated :user_devise do
      root 'home#index', as: :authenticated_root
    end

    unauthenticated do
      root 'devise/sessions#new', as: :unauthenticated_root
    end
  end
</code>```

ContentLicense: CC BY-SA 3.0

Title: Setting Devise Login to be root page

Body:
I am using the following code for my routes:

devise_for :user,
  :as => '',
  :path_names => {
    :sign_in => "",
    :sign_out => "logout",
    :sign_up => "register"
  }

But when I'm logged out and I goto /logout I get the following error:

No route matches {:action=>"new",
  :controller=>"devise/sessions"}

How do I setup the root path to be to :sign_in action?

Body:
I'm new on rails and I didn't know your 'device_scope' name have to be different to your 'device_for' name. Notice my example.

I tried this a hundred times a this is why it didn't work jajaja

  devise_for :user_devises, path: 'user_devises'

  devise_scope :user_devise do
    authenticated :user_devise do
      root 'home#index', as: :authenticated_root
    end

    unauthenticated do
      root 'devise/sessions#new', as: :unauthenticated_root
    end
  end


问:
Understanding of Android Log files
I have Log.d to log some info inside the the source files.

1)Where do you see the output of that Log.d statement?  Logcat has way too many process and kernel operations listed just junked up the whole place. I don't need to know all those internal system operations. I only need to list the Log.d statement.

答:
You can specify a filter as described in the 'adb logcat' help output. But you need to also silence the things you are not interested in. For instance, if you specified the Tag as 'MyApp' you can just have logcat dump the MyApp lines using:
 adb logcat 'MyApp:v,*:s' which silences everything (*:s) and displays anything tagged with 'MyApp' that is verbose and above. For debug and above use 'MyApp:d' instead.</p>

Title: Understanding of Android Log files


问:
How can I increase my BFS speed when solving the 8-puzzle problem?
I am implementing BFS for a project. I am trying to solve the 8 puzzle game. I tested my BFS implementation on simpler inputs such as the following and it works:

Input State: [1, 2, 5, 3, 4, 8, 6, 7, 0]
Goal State: [0, 1, 2, 3, 4, 5, 6, 7, 8]

This leads me to think that more complex solutions are not solving fast because my code is slow.

Here are a few things to note about my code.

Each board state is contained in a board object from the board class.

My BFS saves the parent board state so I can map the path once I find the solution.

My thoughts about why it is slow:

I am using pop() in my frontier queue.

I was searching through all of the visited nodes to compare to the newly created child node to see if it was in the visitedStates list so I could not add it to the frontier. I assume this was an O(n) search and my visitedStates list gets very large. I changed that list to a set because as far as I know sets in Python are on average O(1) for lookup. I then contemplated on the time difference between doing those extra searches and removing them with the comparison.

Maybe looking up the values from all the Board objects is slowing it down?

Any ideas on how I can speed up my BFS code?

BFS function:

```<code>def breadthFirstSearch(startState, endState):
#Set of states that have being visited from the graph.
visitedStates = set()
#Queue of states to be visted. This is our frontier.
frontier = [startState]

while frontier:
    #Pop the current state from the head of the queue.
    currentState = frontier.pop(0)
    #Add the current child to the visited states list.
    visitedStates.add(currentState)

    #Compare the currentState's state to the goalState.
    if currentState.state == endState:
        #Solution found.
        #print(str(currentState.state))
        #print("Depth: " + str(visitedStates[-1].depth))
        print("Depth: " + str(currentState.depth))
        return currentState.state

    #Generate the childs children so the search can continue.
    #This creates a part of the next layer of the tree.
    currentState.generateChildList()
    #print("\nCurrent State: " + str(currentState.state))
    #if currentState.parent is not None:
    #   print("Parent State: " + str(currentState.parent.state))

    #This loop peeks at each of the current states neighbors and decides if they have
    #being visited yet. If they have not being visited then they are added to the queue.
    for child in currentState.childrenList:
        if child not in visitedStates:
            frontier.append(child)

    setNodeParents(currentState, currentState.childrenList)

#Print the depth.
print("Depth: " + str(currentState.depth))
steps = len(visitedStates)
return currentState.state, steps
</code>```

EDIT: I noticed that I use pop() a lot. I am thinking that implementing a deque from collections.deque will speed up the popping operation a lot. Only issue is I cant figure out how to add a deque of class objects. Maybe a dictionary?

答: The solution to my issue was to turn my boards from lists into tuples and change my visitedStates list to a set that contains tuples. This made my program tremendously fast.</p>

Body:
I am implementing BFS for a project. I am trying to solve the 8 puzzle game. I tested my BFS implementation on simpler inputs such as the following and it works:

Input State: [1, 2, 5, 3, 4, 8, 6, 7, 0]
Goal State: [0, 1, 2, 3, 4, 5, 6, 7, 8]

This leads me to think that more complex solutions are not solving fast because my code is slow.

Here are a few things to note about my code.

Each board state is contained in a board object from the board class.

My BFS saves the parent board state so I can map the path once I find the solution.

My thoughts about why it is slow:

I am using pop() in my frontier queue.

I was searching through all of the visited nodes to compare to the newly created child node to see if it was in the visitedStates list so I could not add it to the frontier. I assume this was an O(n) search and my visitedStates list gets very large. I changed that list to a set because as far as I know sets in Python are on average O(1) for lookup. I then contemplated on the time difference between doing those extra searches and removing them with the comparison.

Maybe looking up the values from all the Board objects is slowing it down?

Any ideas on how I can speed up my BFS code?

BFS function:

def breadthFirstSearch(startState, endState):
#Set of states that have being visited from the graph.
visitedStates = set()
#Queue of states to be visted. This is our frontier.
frontier = [startState]

while frontier:
    #Pop the current state from the head of the queue.
    currentState = frontier.pop(0)
    #Add the current child to the visited states list.
    visitedStates.add(currentState)

    #Compare the currentState's state to the goalState.
    if currentState.state == endState:
        #Solution found.
        #print(str(currentState.state))
        #print("Depth: " + str(visitedStates[-1].depth))
        print("Depth: " + str(currentState.depth))
        return currentState.state

    #Generate the childs children so the search can continue.
    #This creates a part of the next layer of the tree.
    currentState.generateChildList()
    #print("\nCurrent State: " + str(currentState.state))
    #if currentState.parent is not None:
    #   print("Parent State: " + str(currentState.parent.state))

    #This loop peeks at each of the current states neighbors and decides if they have
    #being visited yet. If they have not being visited then they are added to the queue.
    for child in currentState.childrenList:
        if child not in visitedStates:
            frontier.append(child)

    setNodeParents(currentState, currentState.childrenList)

#Print the depth.
print("Depth: " + str(currentState.depth))
steps = len(visitedStates)
return currentState.state, steps

EDIT: I noticed that I use pop() a lot. I am thinking that implementing a deque from collections.deque will speed up the popping operation a lot. Only issue is I cant figure out how to add a deque of class objects. Maybe a dictionary?


问:
What is the standard or best practice with regards to quotes on JavaScript keys?
I have been going through several questions such as this to see if there is a standard practice/ best practice for whether to put quotes on keys in JavaScript or JSX or TSX. I, however, haven't found anything and would like to know (before building a huge project on bad practices) which is best between:

```<code>obj = {'foo': 'bar'}
</code>```

and

```<code>obj = {foo: 'bar'}
</code>```

Or better yet, is there some document I can refer to for this?

答:
checkout the Airbnb JavaScript Style Guide. It has a standard set of guidelines and best practices.

3.6 Only quote properties that are invalid identifiers. eslint: quote-props

Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.

// bad
const bad = {
  'foo': 3,
  'bar': 4,
  'data-blah': 5,
};

// good
const good = {
  foo: 3,
  bar: 4,
  'data-blah': 5,
};
```

Body:
I have been going through several questions such as this to see if there is a standard practice/ best practice for whether to put quotes on keys in JavaScript or JSX or TSX. I, however, haven't found anything and would like to know (before building a huge project on bad practices) which is best between:

obj = {'foo': 'bar'}

and

obj = {foo: 'bar'}

Or better yet, is there some document I can refer to for this?


问:
That route does not exist! Getting a 404 error when making a sign up form
im trying to create a signup form by allowing users to enter in their email, password and name. I set up a 404 error code route when a route does not exist and for some reason its going off but i dont know for what reason. Can anyone detect the issue going on. I also have mongodb connected but im not sure if thats affecting it. Heres my code.

```<code>const { validationResult } = require('express-validator')
const User = require('../modelSchema/User')

const signUp = (req, res) => {

        const errors = validationResult(req)
        if(!errors.isEmpty()) return res.status(400).json({ errors: errors.array()})

        //new instance of user
       const user = new User({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password })

        //save the user
      user.save()
      .then(data => {
          response.json(data)
          console.log(data)
      })
      .catch(err => {
          response.json(err)
      })

}

module.exports = { signUp }
</code>```

heres my backend code where im importing mongodb and where my 404 error code is that detects a bad route

```<code>const express = require('express')
const cors = require('cors')
const app = express()
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const routes = require('./routes/index')

//middleware
app.use(cors())

dotenv.config()

mongoose.connect(process.env.DATABASE_ACCESS, () => console.log('Database Connected'))

//bodyParser
app.use(express.json({ extended: false }))

app.get('/', (req, res) => {
    res.send('Hello World!');
})

app.all('*', (req, res) => res.send('That route does not exist!'))

app.use('/app', routes)
app.listen(4000, () => console.log('Server is listening on port 4000'))
</code>```

heres where my routes are. for now i just have my signup route but later i will implement a login route

```<code>const express = require('express');
const { check } = require('express-validator')
const { signUp } = require('../controllers/users');

const router = express.Router();

router.post('/signup', [
    check('name', 'Please Enter your Name').not().isEmpty(),
    check('email', 'Please Enter your Email').isEmail(),
    check('password', 'Please Enter your Password').isLength({ minLength: 6})
], signUp)

module.exports = router;
</code>```

答:
```<code>const signUp = (req, res) => {

        const errors = validationResult(req)
        if(!errors.isEmpty()) return res.status(400).json({ errors: errors.array()})

        //new instance of user
       const user = new User({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password })

        //save the user
      user.save()
      .then(data => {
          res.json(data)
          console.log(data)
      })
      .catch(err => {
          res.status(400).json(err)
      })

}
</code>```

Body:
im trying to create a signup form by allowing users to enter in their email, password and name. I set up a 404 error code route when a route does not exist and for some reason its going off but i dont know for what reason. Can anyone detect the issue going on. I also have mongodb connected but im not sure if thats affecting it. Heres my code.

const { validationResult } = require('express-validator')
const User = require('../modelSchema/User')

const signUp = (req, res) => {

        const errors = validationResult(req)
        if(!errors.isEmpty()) return res.status(400).json({ errors: errors.array()})

        //new instance of user
       const user = new User({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password })

        //save the user
      user.save()
      .then(data => {
          response.json(data)
          console.log(data)
      })
      .catch(err => {
          response.json(err)
      })

}

module.exports = { signUp }

heres my backend code where im importing mongodb and where my 404 error code is that detects a bad route

const express = require('express')
const cors = require('cors')
const app = express()
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const routes = require('./routes/index')

//middleware
app.use(cors())

dotenv.config()

mongoose.connect(process.env.DATABASE_ACCESS, () => console.log('Database Connected'))

//bodyParser
app.use(express.json({ extended: false }))

app.get('/', (req, res) => {
    res.send('Hello World!');
})

app.all('*', (req, res) => res.send('That route does not exist!'))

app.use('/app', routes)
app.listen(4000, () => console.log('Server is listening on port 4000'))

heres where my routes are. for now i just have my signup route but later i will implement a login route

const express = require('express');
const { check } = require('express-validator')
const { signUp } = require('../controllers/users');

const router = express.Router();

router.post('/signup', [
    check('name', 'Please Enter your Name').not().isEmpty(),
    check('email', 'Please Enter your Email').isEmail(),
    check('password', 'Please Enter your Password').isLength({ minLength: 6})
], signUp)

module.exports = router;


问:
How to wait for thread complete before continuing?
I have some code for starting a thread on the .NET CF 2.0:

```<code>ThreadStart tStart = new ThreadStart(MyMethod);
Thread t = new Thread(tStart);
t.Start();
</code>```

If I call this inside a loop the items completely out of order. How do introduce a wait after t.Start(), so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads?

答:
How much order do you need to impose on the threads? If you just need all of the work started in the loop to finish before the code continues, but you don't care about the order the work within the loop finishes, then calling Join is the answer. To add more detail to Kevin Kenny's answer, you should call Join outside the loop. This means you will need a collection to hold references to the threads you started:

```<code>// Start all of the threads.
List<Thread> startedThreads = new List<Thread>();
foreach (...) {
  Thread thread = new Thread(new ThreadStart(MyMethod));
  thread.Start();
  startedThreads.Add(thread);
}

// Wait for all of the threads to finish.
foreach (Thread thread in startedThreads) {
  thread.Join();
}
</code>```

In contrast, if you called Join inside the loop, the result would basically be the same as not using threads at all. Each iteration of the loop body would create and start a thread but then immediately Join it and wait for it to finish.

If the individual threads produce some result (write a message in a log, for example) then the messages may still appear out of order because there's no coordination between the threads. It is possible to get the threads to output their results in order by coordinating them with a Monitor.

Body:
I have some code for starting a thread on the .NET CF 2.0:

ThreadStart tStart = new ThreadStart(MyMethod);
Thread t = new Thread(tStart);
t.Start();

If I call this inside a loop the items completely out of order. How do introduce a wait after t.Start(), so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads?

LastEditorDisplayName: Oli

Body:
How much order do you need to impose on the threads? If you just need all of the work started in the loop to finish before the code continues, but you don't care about the order the work within the loop finishes, then calling Join is the answer. To add more detail to Kevin Kenny's answer, you should call Join outside the loop. This means you will need a collection to hold references to the threads you started:

// Start all of the threads.
List<Thread> startedThreads = new List<Thread>();
foreach (...) {
  Thread thread = new Thread(new ThreadStart(MyMethod));
  thread.Start();
  startedThreads.Add(thread);
}

// Wait for all of the threads to finish.
foreach (Thread thread in startedThreads) {
  thread.Join();
}

In contrast, if you called Join inside the loop, the result would basically be the same as not using threads at all. Each iteration of the loop body would create and start a thread but then immediately Join it and wait for it to finish.

If the individual threads produce some result (write a message in a log, for example) then the messages may still appear out of order because there's no coordination between the threads. It is possible to get the threads to output their results in order by coordinating them with a Monitor.

ContentLicense: CC BY-SA 2.5


问:
What is a good tool to aid in browsing/following C code?
I sometimes need to modify OSS code or other peoples' code (usually C-based, but sometimes C++/Java) and find myself "grep"ing headers for types, function declarations etc. as I follow code flow and try to understand the system.  Is there a good tool that exists to aid in code browsing.  I'd love to be able to click on a type and be taken to the declaration or click on a function name and be taken to it's implementation.  I'm on a linux box, so replies like "just use Visual Studio" won't necessarily work for me.  Thanks!</p>

答:
Even if you are not a developer go for Source Insight

And if you are, its a MUST HAVE :)

OwnerDisplayName: Chris

OwnerDisplayName: Prakash


答:
ESLint docs have some input on this:

In many cases, it doesn't matter if you choose to use an identifier instead of a string or vice-versa. Even so, you might decide to enforce a consistent style in your code.

There are, however, some occasions when you must use quotes:

If you are using an ECMAScript 3 JavaScript engine (such as IE8) and you want to use a keyword (such as if) as a property name. This restriction was removed in ECMAScript 5.

You want to use a non-identifier character in your property name, such as having a property with a space like "one two".

Another example where quotes do matter is when using numeric literals as property keys:

var object = { 1e2: 1, 100: 2 };

IMO it's good to use quotes when needed.

Title: What is the standard or best practice with regards to quotes on JavaScript keys?


问:
Iterate over rows in pandas DataFrame and create a dict
I am trying to create a dictionary using pandas DataFrame.

```<code>import pandas as pd

df = pd.DataFrame({'name': ["p1","p1","p2","p2","p2"],
                   'val': [0, 1, np.nan, 1, 0] })
</code>```

I'd like to create a dictionary with name column as key and val column as values. Values will be a list. I am using a for loop as the DataFrame is only 100 rows.

```<code>mydict = dict()
valList = []

for index, row in df.iterrows():

    # create list of values
    ......

    mydict[row['name']] = valList
</code>```

Expected output:

```<code>{
 'p1': [0, 1],
 'p2': [nan, 1, 0]
}
</code>```

Open to other approaches, but I have a slight preference for using for loop and iterrows().

答:
You could use groupby and a dictionary comprehension:

```<code>d = {k:list(v) for k,v in df.groupby('name')['val']}
</code>```

output:

```<code>{'p1': [0.0, 1.0], 'p2': [nan, 1.0, 0.0]}
</code>```

using iterrows (not my favorite option)

NB. this will be quite slower on large dataframes

```<code>from collections import defaultdict

d = defaultdict(list)

for _, row in df.iterrows():
    d[row['name']].append(row['val'])

dict(d)
</code>```

Body:
I am trying to create a dictionary using pandas DataFrame.

import pandas as pd

df = pd.DataFrame({'name': ["p1","p1","p2","p2","p2"],
                   'val': [0, 1, np.nan, 1, 0] })

I'd like to create a dictionary with name column as key and val column as values. Values will be a list. I am using a for loop as the DataFrame is only 100 rows.

mydict = dict()
valList = []

for index, row in df.iterrows():

    # create list of values
    ......

    mydict[row['name']] = valList

Expected output:

{
 'p1': [0, 1],
 'p2': [nan, 1, 0]
}

Open to other approaches, but I have a slight preference for using for loop and iterrows().

Body:
You could use groupby and a dictionary comprehension:

d = {k:list(v) for k,v in df.groupby('name')['val']}

output:

{'p1': [0.0, 1.0], 'p2': [nan, 1.0, 0.0]}

using iterrows (not my favorite option)

NB. this will be quite slower on large dataframes

from collections import defaultdict

d = defaultdict(list)

for _, row in df.iterrows():
    d[row['name']].append(row['val'])

dict(d)


问:
Python(3) - store one specific link of output from soup.find_all in variable
I am working on a web scrapping function.
I want to find the latest download link ending with ".img.html" from:

"https://dl.twrp.me/gauguin/"

and store this link in a variable, not just print it.

My code so far:

```<code>from bs4 import BeautifulSoup
from urllib.request import urlopen

url = "https://dl.twrp.me/gauguin/"

html_doc = urlopen(url)
# defining html link (twrp...)

soup = BeautifulSoup(html_doc, "html.parser")

for link in soup.find_all('a'):
    links = (link.get('href'))
print(links)
</code>```

My Output:

```<code>https://twrp.me
#
https://twrp.me/about/
https://twrp.me/contactus/
https://twrp.me/Devices/
https://twrp.me/FAQ/
/public.asc
/gauguin/twrp-3.5.2_10-0-gauguin.img.html
/gauguin/twrp-3.5.1_10-0-gauguin.img.html
/gauguin/twrp-3.5.0_10-0-gauguin.img.html
https://twrp.me/terms/termsofservice.html
https://twrp.me/terms/cookiepolicy.html
https://github.com/TeamWin
</code>```

So my goal is to filter this output so I just have those one link (the latest):

```<code>/gauguin/twrp-3.5.2_10-0-gauguin.img.html
</code>```

stored in a variable, so I can call this variable later on or even directly download it with wget for example.

答:
As you iterate over all the  elements, you can use the str.endswith() function to check if the URL ends with .img.html. Do this to extract all your URLs to a single list:

```<code>urls = []
for link in soup.find_all('a'):
    url = link.get('href')
    if url.endswith('.img.html')
        urls.append(url)
</code>```

Which gives a list like so:

```<code>urls = ['/gauguin/twrp-3.5.2_10-0-gauguin.img.html',
'/gauguin/twrp-3.5.1_10-0-gauguin.img.html',
'/gauguin/twrp-3.5.0_10-0-gauguin.img.html']
</code>```

Next, it depends on whether the version-specifiers in your URLs are guaranteed to follow lexicographic order, i.e. will doing a simple string compare get you the latest one? This is usually true if they're all of the same format where the number of digits in each part of the version number remains the same for different strings. The ones you have shown in your example meet this requirement.

If this is the case, simple do

```<code>max(urls)
</code>```

which gives

```<code>'/gauguin/twrp-3.5.2_10-0-gauguin.img.html'
</code>```

If this is not the case, (for example if you had '/gauguin/twrp-3.15.2_10-0-gauguin.img.html', which is numerically > 3.5.2 but not lexicographically) you're going to have to parse out the version number from your string, possibly using a regex, and compare those version numbers. You can do this using the key argument to the max() function (stay tuned, I'm editing my answer for this).

Let's say your version numbers have the format <numbers>.<numbers>.<numbers>_<numbers>-<numbers>. You'd use the following regex (try it online):

\d+\.\d+\.\d+_\d+-\d+

Explanation
\d+    : One or more digits
\.     : The . character
```
<p>To use it with <code>max()</code>, you could write a function that extracts the version number from the file name:</p>
```import re

def extract_version(filename):
    # e.g. filename = '/gauguin/twrp-3.5.2_10-0-gauguin.img.html'

    match = re.search(r"(\d+)\.(\d+)\.(\d+)_(\d+)-(\d+)", filename)
    # e.g. match = <re.Match object; span=(14, 24), match='3.5.2_10-0'>
    # e.g. match.groups() = ('3', '5', '2', '10', '0')

    if match is not None:
        return tuple(int(m) for m in match.groups()) # Convert match to tuple of integer for correct comparison

    return tuple() # if match is none, return an empty tuple
```
<p>The one modification I made to the regex was to surround the <code>\d+</code> in parentheses. The parentheses make it a capturing group, so all the numeric parts are captured as separate groups. Then, <code>re.search()</code> returns a match object, and its <code>.groups()</code> method gives a tuple containing the numbers, but as strings. So we need to convert these strings to integers before returning it.</p>
<p>Then, use the function as the <code>key</code> argument to <code>max()</code>:</p>
```max(urls, key=extract_version)
```

Body:
I am working on a web scrapping function.
I want to find the latest download link ending with ".img.html" from:

"https://dl.twrp.me/gauguin/"

and store this link in a variable, not just print it.

My code so far:

from bs4 import BeautifulSoup
from urllib.request import urlopen

url = "https://dl.twrp.me/gauguin/"

html_doc = urlopen(url)
# defining html link (twrp...)

soup = BeautifulSoup(html_doc, "html.parser")

for link in soup.find_all('a'):
    links = (link.get('href'))
print(links)

My Output:

https://twrp.me
#
https://twrp.me/about/
https://twrp.me/contactus/
https://twrp.me/Devices/
https://twrp.me/FAQ/
/public.asc
/gauguin/twrp-3.5.2_10-0-gauguin.img.html
/gauguin/twrp-3.5.1_10-0-gauguin.img.html
/gauguin/twrp-3.5.0_10-0-gauguin.img.html
https://twrp.me/terms/termsofservice.html
https://twrp.me/terms/cookiepolicy.html
https://github.com/TeamWin

So my goal is to filter this output so I just have those one link (the latest):

/gauguin/twrp-3.5.2_10-0-gauguin.img.html

stored in a variable, so I can call this variable later on or even directly download it with wget for example.

Body:
As you iterate over all the <a> elements, you can use the str.endswith() function to check if the URL ends with .img.html. Do this to extract all your URLs to a single list:

urls = []
for link in soup.find_all('a'):
    url = link.get('href')
    if url.endswith('.img.html')
        urls.append(url)

Which gives a list like so:

urls = ['/gauguin/twrp-3.5.2_10-0-gauguin.img.html',
'/gauguin/twrp-3.5.1_10-0-gauguin.img.html',
'/gauguin/twrp-3.5.0_10-0-gauguin.img.html']

Next, it depends on whether the version-specifiers in your URLs are guaranteed to follow lexicographic order, i.e. will doing a simple string compare get you the latest one? This is usually true if they're all of the same format where the number of digits in each part of the version number remains the same for different strings. The ones you have shown in your example meet this requirement.

If this is the case, simple do

max(urls)

which gives

'/gauguin/twrp-3.5.2_10-0-gauguin.img.html'

If this is not the case, (for example if you had '/gauguin/twrp-3.15.2_10-0-gauguin.img.html', which is numerically > 3.5.2 but not lexicographically) you're going to have to parse out the version number from your string, possibly using a regex, and compare those version numbers. You can do this using the key argument to the max() function (stay tuned, I'm editing my answer for this).

Let's say your version numbers have the format <numbers>.<numbers>.<numbers>_<numbers>-<numbers>. You'd use the following regex (try it online):

\d+\.\d+\.\d+_\d+-\d+

Explanation
\d+    : One or more digits
\.     : The . character

To use it with max(), you could write a function that extracts the version number from the file name:

import re

def extract_version(filename):
    # e.g. filename = '/gauguin/twrp-3.5.2_10-0-gauguin.img.html'

    match = re.search(r"(\d+)\.(\d+)\.(\d+)_(\d+)-(\d+)", filename)
    # e.g. match = <re.Match object; span=(14, 24), match='3.5.2_10-0'>
    # e.g. match.groups() = ('3', '5', '2', '10', '0')

    if match is not None:
        return tuple(int(m) for m in match.groups()) # Convert match to tuple of integer for correct comparison

    return tuple() # if match is none, return an empty tuple

The one modification I made to the regex was to surround the \d+ in parentheses. The parentheses make it a capturing group, so all the numeric parts are captured as separate groups. Then, re.search() returns a match object, and its .groups() method gives a tuple containing the numbers, but as strings. So we need to convert these strings to integers before returning it.

Then, use the function as the key argument to max():

max(urls, key=extract_version)


问:
Unable to refresh AD access_token through Easy Auth (403)
I cannot seem to figure out where I went wrong in setting up an Azure Easy Auth for an app service:

I have a single app service that uses Azure Easy Auth (with Azure AD as the provider) & a token store turned on. When I visit my application, I am prompted to login. Once logged in, I can visit /.auth/me and I can see both an access_token and a refresh_token. After 60mins or so, the access_token expires. The Microsoft docs explain all I have to do is call /.auth/refresh to generate a new access_token. This does not work for me - I am getting a 403 Access Denied back.

My scope does include offline_access and I am retrieving a refresh_token in /.auth/me but the refresh will just not work. It has also not been revoked since logging in. Annoyingly, I cant find any application logs to tell me why this is failing (I have turned everything on but I am running a Node js app which uses PM2 in the background and doesnt seem to log anything from the Easy Auth module?).

To make things stranger, I can manually retrieve a new token by using the OAuth endpoint (POSTing to https://login.microsoftonline.com/) so I don't believe there is any issue with any of the tokens in the token store.

What could be causing this? How can I debug it?

Edit: From doing some testing, it looks like this is caused by an extra scope in my login params. My application requires this scope, but removing it seems to fix the issue. I assume it is failing to refresh the token because the other scope does not support it? What updates do I need to do to allow token refreshing on this custom scope?

```<code>"loginParameters": ["scope=openid profile email offline_access api://xxx-xxx-xxx/user_impersonation"]
</code>```

答: To fix this issue, I had to add the API scope of the app registration to the "Authorized client applications" for the app registration:

Body:
I cannot seem to figure out where I went wrong in setting up an Azure Easy Auth for an app service:

I have a single app service that uses Azure Easy Auth (with Azure AD as the provider) & a token store turned on. When I visit my application, I am prompted to login. Once logged in, I can visit /.auth/me and I can see both an access_token and a refresh_token. After 60mins or so, the access_token expires. The Microsoft docs explain all I have to do is call /.auth/refresh to generate a new access_token. This does not work for me - I am getting a 403 Access Denied back.

My scope does include offline_access and I am retrieving a refresh_token in /.auth/me but the refresh will just not work. It has also not been revoked since logging in. Annoyingly, I cant find any application logs to tell me why this is failing (I have turned everything on but I am running a Node js app which uses PM2 in the background and doesnt seem to log anything from the Easy Auth module?).

To make things stranger, I can manually retrieve a new token by using the OAuth endpoint (POSTing to https://login.microsoftonline.com/) so I don't believe there is any issue with any of the tokens in the token store.

What could be causing this? How can I debug it?

Edit: From doing some testing, it looks like this is caused by an extra scope in my login params. My application requires this scope, but removing it seems to fix the issue. I assume it is failing to refresh the token because the other scope does not support it? What updates do I need to do to allow token refreshing on this custom scope?

"loginParameters": ["scope=openid profile email offline_access api://xxx-xxx-xxx/user_impersonation"]


问:
Hadoop Distributed Cache (Cloudera CH3)
I am trying to run a simple example using a binary executable and the
cached archive and it does not seem to be working:

The example I am trying to run has a mapper which generates three
random doubles and a key and the reducer will average those three
numbers together and log the average. Very simple stuff. I wrote a
simple EXE in c do generate the random numbers:

```<code>#include <cstdio>
#include <stdlib.h>
#include <time.h>

int main(int argc, char*argv[]) {
    srand ( time(NULL) );
    int rand1 = rand() % 10 + 1;
    int rand2 = rand() % 10 + 1;
    int rand3 = rand() % 10 + 1;
    printf("%s, %f, %f, %f", argv[1], (float)rand1/5, (float)rand2/5, (float)rand3/5);
    return 0;
}
</code>```

so if i call ./a.out [key]

i will see

key, random1, random2, random3

im using python streaming, and here is my mapper written in python:

```<code>#!/usr/bin/python

import os
import sys
import random
import shlex, subprocess
from subprocess import PIPE

from misc import *

for line in sys.stdin:
    line = line.strip()
    sline = line.split(',')

    # parse out the au and cost from the line ....
    key = int( sline[0] )
    au = int( sline[1])
    cost = float( sline[2] )

    command = "./a.out %d" % ( key )
    cli_parts = shlex.split(command)
    mp = subprocess.Popen(cli_parts, stdin=PIPE, stderr=PIPE,
stdout=PIPE)
    print mp.communicate()[0].strip('\r\n')
</code>```

here is the reducer that will just do the averaging:

```<code>#!/usr/bin/python

import os
import sys
import math
import re

from misc import *

for line in sys.stdin:
    line = line.strip()
    m = re.match("(\w+),\s+(.*),\s+(.*),\s+(.*)", line)
    if m:
        average = (float(m.groups(0)[1]) + float(m.groups(0)[2]) +
float(m.groups(0)[3])) / 3
        print "key: %d average: %f" % ( int(m.groups(0)[0]), average )
    else:
        print "not found"

#f.close()
</code>```

so after reading the documentation, it seems like i need to compile
the binary and the tar.gz-it

1) tar cvaf a.out.tar.gz a.out

now I should be able to pass this to the datanodes via the -
cacheArchive parameter and everything should work fine. Here is my
Hadoop command:

hadoop jar /usr/lib/hadoop-0.20/contrib/streaming/hadoop-
streaming-0.20.2+737.jar \
           -numReduceTasks 1 \
           -mapper mapper1.py \
           -file mapper1.py \
           -reducer reducer1.py \
           -file reducer1.py \
           -file misc.py \
           -cacheArchive a.out.tar.gz \
           -input input/* \
           -output testsvmoutput \
           -verbose

Needless to say, this does not work, and it seems its because the
mapper is not generating data.

I confirmed my code works by testing it on the command line:

cat input/svminput1.txt | python mapper1.py | sort | python
reducer1.py

I would love for someone to explain why this is not working, how
passing an exe via the cacheArchive command works on the datanodes,
and/or how to debug this because the error messages coming out of the
Cloudera html panel are not that helpful.

Thanks

Here is the error I am seeing:

```<code>java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1
    at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:362)
    at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:572)
    at org.apache.hadoop.streaming.PipeMapper.close(PipeMapper.java:136)
    at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:57)
    at org.apache.hadoop.streaming.PipeMapRunner.run(PipeMapRunner.java:36)
    at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:383)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:317)
    at org.apache.hadoop.mapred.Child$4.run(Child.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:396)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1063)
    at org.apache.hadoop.mapred.Child.main(Child.java:211)
</code>```

答:
Are you sure python is available at /usr/bin/python on the cluster machines?  A good practice is to always use #!/usr/bin/env python at the top of your scripts... that way it's not hardcoded.

Also be sure to check the python installation on your cluster machines... make sure the imports work.

You aren't using any try/excepts in your code so it will be very difficult to debug what the problem is... I suggest try/excepting your code and printing log messages to a well-known location such as /tmp....

For more you can check out davidvhill.com/articles.... my actual production code is captured here....

Title: Hadoop Distributed Cache (Cloudera CH3)

Body:
I am trying to run a simple example using a binary executable and the
cached archive and it does not seem to be working:

The example I am trying to run has a mapper which generates three
random doubles and a key and the reducer will average those three
numbers together and log the average. Very simple stuff. I wrote a
simple EXE in c do generate the random numbers:

#include <cstdio>
#include <stdlib.h>
#include <time.h>

int main(int argc, char*argv[]) {
    srand ( time(NULL) );
    int rand1 = rand() % 10 + 1;
    int rand2 = rand() % 10 + 1;
    int rand3 = rand() % 10 + 1;
    printf("%s, %f, %f, %f", argv[1], (float)rand1/5, (float)rand2/5, (float)rand3/5);
    return 0;
}

so if i call ./a.out [key]

i will see

key, random1, random2, random3

im using python streaming, and here is my mapper written in python:

#!/usr/bin/python

import os
import sys
import random
import shlex, subprocess
from subprocess import PIPE

from misc import *

for line in sys.stdin:
    line = line.strip()
    sline = line.split(',')

    # parse out the au and cost from the line ....
    key = int( sline[0] )
    au = int( sline[1])
    cost = float( sline[2] )

    command = "./a.out %d" % ( key )
    cli_parts = shlex.split(command)
    mp = subprocess.Popen(cli_parts, stdin=PIPE, stderr=PIPE,
stdout=PIPE)
    print mp.communicate()[0].strip('\r\n')

here is the reducer that will just do the averaging:

#!/usr/bin/python

import os
import sys
import math
import re

from misc import *

for line in sys.stdin:
    line = line.strip()
    m = re.match("(\w+),\s+(.*),\s+(.*),\s+(.*)", line)
    if m:
        average = (float(m.groups(0)[1]) + float(m.groups(0)[2]) +
float(m.groups(0)[3])) / 3
        print "key: %d average: %f" % ( int(m.groups(0)[0]), average )
    else:
        print "not found"

#f.close()

so after reading the documentation, it seems like i need to compile
the binary and the tar.gz-it

1) tar cvaf a.out.tar.gz a.out

now I should be able to pass this to the datanodes via the -
cacheArchive parameter and everything should work fine. Here is my
Hadoop command:

hadoop jar /usr/lib/hadoop-0.20/contrib/streaming/hadoop-
streaming-0.20.2+737.jar \
           -numReduceTasks 1 \
           -mapper mapper1.py \
           -file mapper1.py \
           -reducer reducer1.py \
           -file reducer1.py \
           -file misc.py \
           -cacheArchive a.out.tar.gz \
           -input input/* \
           -output testsvmoutput \
           -verbose

Needless to say, this does not work, and it seems its because the
mapper is not generating data.

I confirmed my code works by testing it on the command line:

cat input/svminput1.txt | python mapper1.py | sort | python
reducer1.py

I would love for someone to explain why this is not working, how
passing an exe via the cacheArchive command works on the datanodes,
and/or how to debug this because the error messages coming out of the
Cloudera html panel are not that helpful.

Thanks

Here is the error I am seeing:

java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1
    at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:362)
    at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:572)
    at org.apache.hadoop.streaming.PipeMapper.close(PipeMapper.java:136)
    at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:57)
    at org.apache.hadoop.streaming.PipeMapRunner.run(PipeMapRunner.java:36)
    at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:383)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:317)
    at org.apache.hadoop.mapred.Child$4.run(Child.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:396)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1063)
    at org.apache.hadoop.mapred.Child.main(Child.java:211)


问:
Loading EXASOL data in R. Unknown ODBC error
R is unable to read the EXASOL Database due to some unknown ODBC error. Has anyone come across a similar instance. The problem occurs with Mac OS.

I have installed the ODBC driver for Mac OS.

```<code>library(exasol)
library(RODBC)

con <- dbConnect("exasol", **)
# removed the connection credentials

df1 <- dbGetQuery(con,paste("query", sep=""))
# removed the query

Error in try(.Call(C_asyncRODBCQueryFinish, slot, 1)) :
  Unknown ODBC error
Error in exa.readData(conn, statement, ...) :
  Could not allocate SQLAllocHandle (-2)
Error in exa.readData(conn, statement, ...) : Unknown ODBC error
</code>```

The issue is at the moment unanswered here https://github.com/exasol/r-exasol/issues/32.

答: I had a similar issue, what helped me was to reinstall install.packages("RODBC", type="source")

Body:
R is unable to read the EXASOL Database due to some unknown ODBC error. Has anyone come across a similar instance. The problem occurs with Mac OS.

I have installed the ODBC driver for Mac OS.

library(exasol)
library(RODBC)

con <- dbConnect("exasol", **)
# removed the connection credentials

df1 <- dbGetQuery(con,paste("query", sep=""))
# removed the query

Error in try(.Call(C_asyncRODBCQueryFinish, slot, 1)) :
  Unknown ODBC error
Error in exa.readData(conn, statement, ...) :
  Could not allocate SQLAllocHandle (-2)
Error in exa.readData(conn, statement, ...) : Unknown ODBC error

The issue is at the moment unanswered here https://github.com/exasol/r-exasol/issues/32.


问:
How Can I mapping DTOs using mapstruct?
I am tring to mapping entity datas to DTOs using mapstruct.
And with these sources, I could map id,title datas.
But the problem is.... I can not map userName using these sources.

How can I resolve this problem??

```<code>@Entity // DB와의 연결을 위하여
@Data   // getter setter
public class Board {
    @Id // id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Size(min=2, max=30)
    private String title;

    @Length(min=20)
    @Lob
    @Column(columnDefinition="TEXT", nullable = false)
    private String content;

    @ManyToOne
    @JoinColumn(name="userId", referencedColumnName = "id")
    private User user;
}
</code>```
```<code>@Builder
@AllArgsConstructor
@Data
public class BoardListDto {
    private Long id;
    private String title;
    private String userName;
}
</code>```
```<code>@Mapper(componentModel = "spring")
public interface BoardListMapper extends EntityMapper<BoardListDto, Board> {
    @Override
    @Mapping(target = "userName", source = "user.name.value")
    List<BoardListDto> toDtos(List<Board> board);

}
</code>```
```<code>public interface EntityMapper <D, E> {
    E toEntity(D dto);
    D toDto(E entity);

    // Entity업데이트 시 null이 아닌 값만 업데이트 하도록 함.
    @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
    void updateFromDto(D dto, @MappingTarget E entity);

    List<D> toDtos(List<E> entity);
}
</code>```

答:
no need to implement toDtos method for this. This code should be enough and Mapstruct will handle the rest alone.</p>
```<code>@Mapper(componentModel = "spring")
public interface BoardListMapper extends EntityMapper<BoardListDto, Board> {
    @Override
    @Mapping(target = "userName", source = "user.name")
    BoardListDto toDto(Board board);

}
</code>```

Title: How Can I mapping DTOs using mapstruct?

Body:
I am tring to mapping entity datas to DTOs using mapstruct.
And with these sources, I could map id,title datas.
But the problem is.... I can not map userName using these sources.

How can I resolve this problem??

@Entity // DB와의 연결을 위하여
@Data   // getter setter
public class Board {
    @Id // id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Size(min=2, max=30)
    private String title;

    @Length(min=20)
    @Lob
    @Column(columnDefinition="TEXT", nullable = false)
    private String content;

    @ManyToOne
    @JoinColumn(name="userId", referencedColumnName = "id")
    private User user;
}

@Builder
@AllArgsConstructor
@Data
public class BoardListDto {
    private Long id;
    private String title;
    private String userName;
}

@Mapper(componentModel = "spring")
public interface BoardListMapper extends EntityMapper<BoardListDto, Board> {
    @Override
    @Mapping(target = "userName", source = "user.name.value")
    List<BoardListDto> toDtos(List<Board> board);

}

public interface EntityMapper <D, E> {
    E toEntity(D dto);
    D toDto(E entity);

    // Entity업데이트 시 null이 아닌 값만 업데이트 하도록 함.
    @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
    void updateFromDto(D dto, @MappingTarget E entity);

    List<D> toDtos(List<E> entity);
}

Body:
no need to implement toDtos method for this. This code should be enough and Mapstruct will handle the rest alone.

@Mapper(componentModel = "spring")
public interface BoardListMapper extends EntityMapper<BoardListDto, Board> {
    @Override
    @Mapping(target = "userName", source = "user.name")
    BoardListDto toDto(Board board);

}


问:
JSON object return of an array of objects which contains the keys and its values
Boris has a list of all the beers available in his pub, but it's a huge mess. He would like to see the beers grouped by brands. Boris also told you that the Function should return an array of objects which contains the Brand name and an array of beer IDs of that Brand.

JSON file with data:
https://challenge.codingsans.com/beers.json

Output Example:

```<code>[
  {
    "brand": "brandName2",
    "beers": [
      "beerID3",
      "beerID4"
    ]
  },
  {
    "brand": "brandName1",
    "beers": [
      "beerID2",
      "beerID1"
    ]
  }
]
</code>```

//

I have done this:
(So basically nothing. I just would like to get some idea how to solve it.)

```<code>request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        // Date Parse
        data = JSON.parse(request.responseText);
        // Success!

        // Arrays
        var beerIDs = [];
        var beerBrand = [];
        // Iteration

        for (var key in data) {
            beerIDs.push(data[key].id);
            beerBrand.push(data[key].brand);
            // console.log(beerIDs);
            // console.log(beerBrand);
        }
        console.log(beerIDs);
        console.log(beerBrand);

        //final list

        var finalList = [];

    } else {
        // We reached our target server, but it returned an error
    }
};

request.onerror = function() {
    // There was a connection error of some sort
};

request.send();
</code>```

答:
Try this:</p>
```<code>request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Date Parse
    data = JSON.parse(request.responseText);
    // Success!

    const organizedBeers = data.reduce((acc, beers) => {

      const findIndex = acc.findIndex(beer => beer.brand === beers.brand)

      if(findIndex > -1) {

        acc[findIndex].beersId.push(beers.id)

      } else {

        acc.push({
          brand: beers.brand,
          beersId: [beers.id],
        })

      }

      return acc;
    }, [])

   console.log(organizedBeers)

  } else  {
    // We reached our target server, but it returned an error
  }
};

request.onerror = function() {
    // There was a connection error of some sort
};

request.send();
</code>```

Body:
Boris has a list of all the beers available in his pub, but it's a huge mess. He would like to see the beers grouped by brands. Boris also told you that the Function should return an array of objects which contains the Brand name and an array of beer IDs of that Brand.

JSON file with data:
https://challenge.codingsans.com/beers.json

Output Example:

[
  {
    "brand": "brandName2",
    "beers": [
      "beerID3",
      "beerID4"
    ]
  },
  {
    "brand": "brandName1",
    "beers": [
      "beerID2",
      "beerID1"
    ]
  }
]

//

I have done this:
(So basically nothing. I just would like to get some idea how to solve it.)

request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        // Date Parse
        data = JSON.parse(request.responseText);
        // Success!

        // Arrays
        var beerIDs = [];
        var beerBrand = [];
        // Iteration

        for (var key in data) {
            beerIDs.push(data[key].id);
            beerBrand.push(data[key].brand);
            // console.log(beerIDs);
            // console.log(beerBrand);
        }
        console.log(beerIDs);
        console.log(beerBrand);

        //final list

        var finalList = [];

    } else {
        // We reached our target server, but it returned an error
    }
};

request.onerror = function() {
    // There was a connection error of some sort
};

request.send();

Body:
Try this:

request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Date Parse
    data = JSON.parse(request.responseText);
    // Success!

    const organizedBeers = data.reduce((acc, beers) => {

      const findIndex = acc.findIndex(beer => beer.brand === beers.brand)

      if(findIndex > -1) {

        acc[findIndex].beersId.push(beers.id)

      } else {

        acc.push({
          brand: beers.brand,
          beersId: [beers.id],
        })

      }

      return acc;
    }, [])

   console.log(organizedBeers)

  } else  {
    // We reached our target server, but it returned an error
  }
};

request.onerror = function() {
    // There was a connection error of some sort
};

request.send();


问:
Java slow 2D performance - Resizing
I am using Windows 7 with Aero, and have a very fast graphics card (Radeon 6870) that I use for gaming.

I have some issues when resizing very simple programs I make with java. For instance, this program does absolutely nothing. It has no action listeners, no loops. It's simply a GUI interface with buttons.

Resizing with OpenGL acceleration off:

[View fullscreen]

It takes about a second to resize the components. For me that's very noticeable.

Resizing with OpenGL acceleration on:

I have tried to enable OpenGl acceleration to solve this problem. I compiled the JAR and
run it with java -Dsun.java2d.opengl=true -jar C:\Test.jar. The result is slightly less black areas around the window, but much more flickering. In fact the flickering shows up as grey in the screenshot above.

Is the issue present in any other software?

No. Eclipse, Netbeans, Chrome and other applications have been tested. None have this issue. Therfore I must conclude that there must be some problem with the code. Various people have run this code and said they have "No issues". If you are going to test it, please make sure you resize the window from the smallest size to the largest size of the screen, whilst moving the mouse in circular motion.

Code:

```<code>import java.awt.*;
import javax.swing.*;

public class JFrameWithButtonsTest {
    private int iScreen = 25;
    private int iLocation = 10;
    JFrame frame = new JFrame();
    Container contentPane = frame.getContentPane();

    public JFrameWithButtonsTest() {
        JPanel northButtonPanel = new JPanel();
        northButtonPanel.setLayout(new GridLayout(2,2));
        northButtonPanel.add(new JButton(" I do nothing"));
        northButtonPanel.add(new JButton(" I do nothing"));
        northButtonPanel.add(new JButton(" I do nothing"));
        northButtonPanel.add(new JButton(" I do nothing"));
        contentPane.add(northButtonPanel, BorderLayout.NORTH);

        JPanel southButtonPanel = new JPanel();
        southButtonPanel.setLayout(new GridLayout(2,2));
        southButtonPanel.add(new JButton(" I do nothing"));
        southButtonPanel.add(new JButton(" I do nothing"));
        southButtonPanel.add(new JButton(" I do nothing"));
        southButtonPanel.add(new JButton(" I do nothing"));
        contentPane.add(southButtonPanel, BorderLayout.SOUTH);

        JPanel eastButtonPanel = new JPanel();
        eastButtonPanel.setLayout(new GridLayout(2,2));
        eastButtonPanel.add(new JButton(" I do nothing"));
        eastButtonPanel.add(new JButton(" I do nothing"));
        eastButtonPanel.add(new JButton(" I do nothing"));
        eastButtonPanel.add(new JButton(" I do nothing"));
        contentPane.add(eastButtonPanel, BorderLayout.EAST);

        boolean packFrame = false;
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = frame.getSize();
        frameSize.height = (int) (iScreen * screenSize.height / 100);
        frameSize.width = (int) (iScreen * screenSize.width / 100);
        frame.setSize(frameSize);
        frame.setLocation((screenSize.width - frameSize.width) / iLocation,
                (screenSize.height - frameSize.height) / iLocation);
        if (packFrame) {
            frame.pack();
            packFrame = true;
        } else {
            frame.validate();
        }
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JFrameWithButtonsTest();
            }
        });
    }
}
</code>```

Note that the issue is still present without this line:  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

答:
Usually Flickering can be improved if not solved using double buffering, you can enable it by setting true to each of the panels .setDoubleBuffer(true);

To read more about it : http://download.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html

Title: Java slow 2D performance - Resizing

Body:
I am using Windows 7 with Aero, and have a very fast graphics card (Radeon 6870) that I use for gaming.

I have some issues when resizing very simple programs I make with java. For instance, this program does absolutely nothing. It has no action listeners, no loops. It's simply a GUI interface with buttons.

Resizing with OpenGL acceleration off:

[View fullscreen]

It takes about a second to resize the components. For me that's very noticeable.

Resizing with OpenGL acceleration on:

I have tried to enable OpenGl acceleration to solve this problem. I compiled the JAR and
run it with java -Dsun.java2d.opengl=true -jar C:\Test.jar. The result is slightly less black areas around the window, but much more flickering. In fact the flickering shows up as grey in the screenshot above.

Is the issue present in any other software?

No. Eclipse, Netbeans, Chrome and other applications have been tested. None have this issue. Therfore I must conclude that there must be some problem with the code. Various people have run this code and said they have "No issues". If you are going to test it, please make sure you resize the window from the smallest size to the largest size of the screen, whilst moving the mouse in circular motion.

Code:

import java.awt.*;
import javax.swing.*;

public class JFrameWithButtonsTest {
    private int iScreen = 25;
    private int iLocation = 10;
    JFrame frame = new JFrame();
    Container contentPane = frame.getContentPane();

    public JFrameWithButtonsTest() {
        JPanel northButtonPanel = new JPanel();
        northButtonPanel.setLayout(new GridLayout(2,2));
        northButtonPanel.add(new JButton(" I do nothing"));
        northButtonPanel.add(new JButton(" I do nothing"));
        northButtonPanel.add(new JButton(" I do nothing"));
        northButtonPanel.add(new JButton(" I do nothing"));
        contentPane.add(northButtonPanel, BorderLayout.NORTH);

        JPanel southButtonPanel = new JPanel();
        southButtonPanel.setLayout(new GridLayout(2,2));
        southButtonPanel.add(new JButton(" I do nothing"));
        southButtonPanel.add(new JButton(" I do nothing"));
        southButtonPanel.add(new JButton(" I do nothing"));
        southButtonPanel.add(new JButton(" I do nothing"));
        contentPane.add(southButtonPanel, BorderLayout.SOUTH);

        JPanel eastButtonPanel = new JPanel();
        eastButtonPanel.setLayout(new GridLayout(2,2));
        eastButtonPanel.add(new JButton(" I do nothing"));
        eastButtonPanel.add(new JButton(" I do nothing"));
        eastButtonPanel.add(new JButton(" I do nothing"));
        eastButtonPanel.add(new JButton(" I do nothing"));
        contentPane.add(eastButtonPanel, BorderLayout.EAST);

        boolean packFrame = false;
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = frame.getSize();
        frameSize.height = (int) (iScreen * screenSize.height / 100);
        frameSize.width = (int) (iScreen * screenSize.width / 100);
        frame.setSize(frameSize);
        frame.setLocation((screenSize.width - frameSize.width) / iLocation,
                (screenSize.height - frameSize.height) / iLocation);
        if (packFrame) {
            frame.pack();
            packFrame = true;
        } else {
            frame.validate();
        }
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JFrameWithButtonsTest();
            }
        });
    }
}

Note that the issue is still present without this line:  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());


问:
How to STR Replace and echo in laravel
Files that are uploaded to my site have their names changed and extention change to bin. So for example a uploaded file will be dfd84848.bin, using the bin file worked fine with modelviewer but im trying to test babylon.js and it doesnt work with .bin only if i change .bin to .glb.

This code {{uploaded_asset($detailedProduct->cad_file)}} provides link like uploads/all/p1YZX9TBc7EmimFx4rXnSFKvVor8EttpOUUpylLL.bin

I want to change .bin to .glb and echo it.

i tried this

```<code>@php
    $previewfile = uploaded_asset($detailedProduct->cad_file);
    $replaced = Str::replace('.bin', '.glb', $previewfile );
@endphp
</code>```

to show i used this <model url="{$replaced}"> but it never echoed url

Edit

So now that it echos as name.glb it doesnt work because the file doesnt exist on server. When 3d models such as .glb, .gltf are uploaded they are renamed to .bin i dont know why. The uploader is AizUploadController.php

答:
To echo a value you should use double curly braces:

<model url="{{ $replaced }}">

Docs: https://laravel.com/docs/8.x/blade#displaying-data

Title: How to STR Replace and echo in laravel

Body:
Files that are uploaded to my site have their names changed and extention change to bin. So for example a uploaded file will be dfd84848.bin, using the bin file worked fine with modelviewer but im trying to test babylon.js and it doesnt work with .bin only if i change .bin to .glb.

This code {{uploaded_asset($detailedProduct->cad_file)}} provides link like uploads/all/p1YZX9TBc7EmimFx4rXnSFKvVor8EttpOUUpylLL.bin

I want to change .bin to .glb and echo it.

i tried this

@php
    $previewfile = uploaded_asset($detailedProduct->cad_file);
    $replaced = Str::replace('.bin', '.glb', $previewfile );
@endphp

to show i used this <model url="{$replaced}"> but it never echoed url

Edit

So now that it echos as name.glb it doesnt work because the file doesnt exist on server. When 3d models such as .glb, .gltf are uploaded they are renamed to .bin i dont know why. The uploader is AizUploadController.php


问:
keep/copy XMP with libexif
I try to add a thumbnail to a JPEG picture using libexif.
For now I'm borrowing the code from exif (the command line tool that is shipped by the libexif team).
However I noticed the XMP tags get deleted from the metadata. There is an old bugreport here.

I tried to see how to achieve this anyway with libexif but I don't really understand how to get the XMP from input file and put it in the output file. I just want to copy all XMP data, I don't need to extract anything of it.

I saw there is a TAG EXIF_TAG_XML_PACKET in exif_tag.h but couldn't figure out how to read/write this tag.

A related solution is in this SO answer but it looks complicated. I'm not familiar coding in C.

Is it actually possible to keep all XMP when using only libexif API? Have things changed in recent years on that? How would you write this in code?

Thanks

答:
I believe it should be somewhat straightforward. XMP fields are described in the ISO/Adobe standard. Regular Kotlin/Java/Android file I/O and some string manipulation should be all that is required.

I would start out by becoming intimately familiar with ISO 16684-1:2019. Then, write a method for your jpeg file class that grabs all the XMP fields. Store those fields in a temp file (to prevent difficult to recover data loss in the event of your code or libexif crashing). Hand the file off to libexif. Generate the thumbnail. Finally, when that's done you can restore the XMP fields. If the thumbnail is stored in an XMP field as well (and it sounds like it is), it may be easier to concatenate that field with the other ones which were already grabbed, updating the temp file so that it contains EVERY XMP field, before adding all of the XMP fields back to the jpeg.

Unfortunately, I do not currently have the time to read a 50 page ISO standard, synthesize the information, and then write the code to implement the solution. Here's a link to the standard at least, to get you started.

https://www.iso.org/obp/ui/#iso:std:iso:16684:-1:ed-2:v1:en

Title: keep/copy XMP with libexif


问:
Can't pickle local object 'ArgumentParser.__init__.<locals>.identity
```<code>import argparse
import pickle

parser = argparse.ArgumentParser(description='Process some integers.')
_ = pickle.dumps(parser)
</code>```

In my code, the ArgumentParser object is serialized. But in runtime I get the error Can't pickle local object 'ArgumentParser.__init__.<locals>.identity.
In Lib/argparse.py the identity is function defined locally inside __init__ method and this prevents serialization. If convert this function to a method, then serialization is successful. But I think that this way is not the best solution, since the python library file is being changed. How serialize parser object best way?

答:
I had a program that used sub-parsers and initializing the ArgumentParser noticeably delayed startup, even for —help. I experimented with several things encountered this. I found this to work.</p>
```<code>from argparse import ArgumentParser
from pickle import dumps

def identity(string):
    return string

p = ArgumentParser()
p.register('type', None, identity)
x = dumps(p)
</code>```

Body:
import argparse
import pickle

parser = argparse.ArgumentParser(description='Process some integers.')
_ = pickle.dumps(parser)

In my code, the ArgumentParser object is serialized. But in runtime I get the error Can't pickle local object 'ArgumentParser.__init__.<locals>.identity.
In Lib/argparse.py the identity is function defined locally inside __init__ method and this prevents serialization. If convert this function to a method, then serialization is successful. But I think that this way is not the best solution, since the python library file is being changed. How serialize parser object best way?

Body:
I had a program that used sub-parsers and initializing the ArgumentParser noticeably delayed startup, even for —help. I experimented with several things encountered this. I found this to work.

from argparse import ArgumentParser
from pickle import dumps

def identity(string):
    return string

p = ArgumentParser()
p.register('type', None, identity)
x = dumps(p)


问:
iPhone app Facebook login with different account than FB app, when Single Sign on is enabled
I'd like to use Facebook single sign on (SSO) in my iPhone app, but I would also like to get the option to users to login with a different account from the one they are logged in the official Facebook app. Ideally, the user will be first sent to the Facebook app, but when she refuses to accept the sign on, the control will be sent back to my app. At this point, it would be perfect to show the old in app login view, so that she can use a different userid/password combination. Is that last step possible?
Thanks!</p>

答: When the call the iOS SDK authorize method a dialog will be popped up to ask for permissions if a logged-in user of the Facebook app was found. In that dialog there should be a "Not You?" link that would give the user the option to log in as a different user.</p>


问:
Accessing information - Array of pointers
```<code>int* a[2];
int x = 5;
int y = 7;
int *b = x;
int *c = y;
a[0] = b;
a[1] = c;
printf("%d", *a[1]);
</code>```

Why isn't this working?
This is an Array of pointers and I'm trying to get the value of y - a[1] is the address of y so I added a * to get the value of it..
Thanks everyone!

答:
A slight change to your code to pass the address of the integer x and y to pointers b and c will make your code work.</p>
```<code>int *b = &x;
int *c = &y;
</code>```

Body:
int* a[2];
int x = 5;
int y = 7;
int *b = x;
int *c = y;
a[0] = b;
a[1] = c;
printf("%d", *a[1]);

Why isn't this working?
This is an Array of pointers and I'm trying to get the value of y - a[1] is the address of y so I added a * to get the value of it..
Thanks everyone!

Body:
A slight change to your code to pass the address of the integer x and y to pointers b and c will make your code work.

int *b = &x;
int *c = &y;


问:
Deprecated: Directive 'allow_url_include' is deprecated in Unknown on line 0
I upload my Laravel project on shared hosting. When I upload my project on the server it throws an exception then switched my PHP version 5.4 to 7.4. Now am facing this issue.

```<code>Deprecated: Directive 'allow_url_include' is deprecated in Unknown on line 0
</code>```

I also disable the allow_url_include in my PHP ini file which exists in project root directory but it still says allow_url_include depreciated error.

Also, I go into the PHP Multi INI Editor and change the allow_url_include but it still throw the above error.

答: If your web host uses  Cpanel, log in and under the Software section click Select PHP Version, then on the next screen click Options.  Under Options, unclick allow_url_include:

Body:
I upload my Laravel project on shared hosting. When I upload my project on the server it throws an exception then switched my PHP version 5.4 to 7.4. Now am facing this issue.

Deprecated: Directive 'allow_url_include' is deprecated in Unknown on line 0

I also disable the allow_url_include in my PHP ini file which exists in project root directory but it still says allow_url_include depreciated error.

Also, I go into the PHP Multi INI Editor and change the allow_url_include but it still throw the above error.