问:
How do you call a C function that takes (or returns) a struct by value from JS via Emscripen/Wasm?
Passing structs, arrays, and strings by reference from Javascript to C is pretty well documented in the Emscripten docs (https://kripken.github.io/emscripten-site/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#interacting-with-code-direct-function-calls).

But what about passing structures by value?  If I have a C function like this:

```<code>typedef struct {double a, b, c;} MyStruct;

MyStruct Foo(const MyStruct x, double y);
</code>```

How would I call Foo and decode the result? (Either using Module.cwrap or calling Module._Foo directly).  Would I need to get access to the Emscripten stack to do that? Where is that documented?

答:
It is possible and here how it works:

When C structure is passed by value, it is proceeded as if it is passed by pointer.

Structure:

typedef struct {
    size_t a;
    double b;
} my_struct_t;
```

<p>Pass by value (C):</p>

<pre class="lang-c prettyprint-override"><code>size_t my_struct_get_a(my_struct_t my) {
    return my.a;
}
</code>```

Pass by value (Wasm):

```<code>  (func $func3 (param $var0 i32) (result i32)
    get_local $var0
    i32.load
  )
</code>```

Pass by pointer (C):

size_t my_struct_ptr_get_a(const my_struct_t* my) {
    return my->a;
}
```

<p>Pass by pointer (Wasm):</p>

```  (func $func5 (param $var0 i32) (result i32)
    get_local $var0
    i32.load
  )
```

<p><strong>WebAssembly code is the same!</strong></p>

<ol start="2">
<li>When C structure is <strong>returned by value</strong>, then it is expected to be passed as a first function parameter!</li>
</ol>

<p>Return by value (C):</p>

<pre class="lang-c prettyprint-override"><code>my_struct_t my_struct_create(size_t a, double b) {
    return (my_struct_t){a, b};
}
</code>```

Return by value (Wasm):

```<code>  (func $func1 (param $var0 i32) (param $var1 i32) (param $var2 f64)
    get_local $var0
    get_local $var2
    f64.store offset=8
    get_local $var0
    get_local $var1
    i32.store
  )
</code>```

Pay attention that Wasm does not contain result and has 3 params.

For comparison lets check alternative function:

void my_struct_fill(my_struct_t* my, size_t a, double b) {
    my->a = a;
    my->b = b;
}
```

<p>Wasm is equal to the previous function:</p>

```  (func $func2 (param $var0 i32) (param $var1 i32) (param $var2 f64)
    get_local $var0
    get_local $var2
    f64.store offset=8
    get_local $var0
    get_local $var1
    i32.store
  )
```

Full C code sample and its Wasm

Note, this approach works well for WebAssembly, asm.js was not checked.

Body:
Passing structs, arrays, and strings by reference from Javascript to C is pretty well documented in the Emscripten docs (https://kripken.github.io/emscripten-site/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#interacting-with-code-direct-function-calls).

But what about passing structures by value?  If I have a C function like this:

typedef struct {double a, b, c;} MyStruct;

MyStruct Foo(const MyStruct x, double y);

How would I call Foo and decode the result? (Either using Module.cwrap or calling Module._Foo directly).  Would I need to get access to the Emscripten stack to do that? Where is that documented?

Body:
It is possible and here how it works:

When C structure is passed by value, it is proceeded as if it is passed by pointer.

Structure:

typedef struct {
    size_t a;
    double b;
} my_struct_t;

Pass by value (C):

size_t my_struct_get_a(my_struct_t my) {
    return my.a;
}

Pass by value (Wasm):

  (func $func3 (param $var0 i32) (result i32)
    get_local $var0
    i32.load
  )

Pass by pointer (C):

size_t my_struct_ptr_get_a(const my_struct_t* my) {
    return my->a;
}

Pass by pointer (Wasm):

  (func $func5 (param $var0 i32) (result i32)
    get_local $var0
    i32.load
  )

WebAssembly code is the same!

When C structure is returned by value, then it is expected to be passed as a first function parameter!

Return by value (C):

my_struct_t my_struct_create(size_t a, double b) {
    return (my_struct_t){a, b};
}

Return by value (Wasm):

  (func $func1 (param $var0 i32) (param $var1 i32) (param $var2 f64)
    get_local $var0
    get_local $var2
    f64.store offset=8
    get_local $var0
    get_local $var1
    i32.store
  )

Pay attention that Wasm does not contain result and has 3 params.

For comparison lets check alternative function:

void my_struct_fill(my_struct_t* my, size_t a, double b) {
    my->a = a;
    my->b = b;
}

Wasm is equal to the previous function:

  (func $func2 (param $var0 i32) (param $var1 i32) (param $var2 f64)
    get_local $var0
    get_local $var2
    f64.store offset=8
    get_local $var0
    get_local $var1
    i32.store
  )

<a href="https://mbebenita.github.io/WasmExplorer/?state=%7B%22options%22%3A%7B%22showGutter%22%3Atrue%2C%22showConsole%22%3Atrue%2C%22showOptions%22%3Atrue%2C%22autoCompile%22%3Atrue%2C%22showLLVM%22%3Afalse%2C%22darkMode%22%3Atrue%2C%22fastMath%22%3Afalse%2C%22noInline%22%3Afalse%2C%22noRTTI%22%3Afalse%2C%22noExceptions%22%3Afalse%2C%22cleanWast%22%3Atrue%2C%22wasmBaseline%22%3Afalse%2C%22dialect%22%3A%22C99%22%2C%22optimizationLevel%22%3A%22s%22%7D%2C%22source%22%3A%22%23include%20%3Cstddef.h%3E%5Cn%5Cntypedef%20struct%20%7B%5Cn%20%20%20%20size_t%20a%3B%5Cn%20%20%20%20double%20b%3B%5Cn%7D%20my_struct_t%3B%5Cn%5Cnsize_t%20my_struct_size(void)%20%7B%5Cn%20%20%20%20return%20sizeof(my_struct_t)%3B%5Cn%7D%5Cn%5Cnmy_struct_t%20my_struct_create(size_t%20a%2C%20double%20b)%20%7B%5Cn%20%20%20%20return%20(my_struct_t)%7Ba%2C%20b%7D%3B%5Cn%7D%5Cn%5Cnvoid%20my_struct_fill(my_struct_t*%20my%2C%20size_t%20a%2C%20double%20b)%20%7B%5Cn%20%20%20%20my-%3Ea%20%3D%20a%3B%5Cn%20%20%20%20my-%3Eb%20%3D%20b%3B%5Cn%7D%5Cn%5Cnsize_t%20my_struct_get_a(my_struct_t%20my)%20%7B%5Cn%20%20%20%20return%20my.a%3B%5Cn%7D%5Cn%5Cndouble%20my_struct_get_b(my_struct_t%20my)%20%7B%5Cn%20%20%20%20return%20my.b%3B%5Cn%7D%5Cn%5Cnsize_t%20my_struct_ptr_get_a(const%20my_struct_t%20*my)%20%7B%5Cn%20%20%20%20return%20my-%3Ea%3B%5Cn%7D%5Cn%5Cndouble%20my_struct_ptr_get_b(const%20my_struct_t%20*my)%20%7B%5Cn%20%20%20%20return%20my-%3Eb%3B%5Cn%7D%5Cn%22%7D" rel="noreferrer">Full C code sample and its Wasm

Note, this approach works well for WebAssembly, asm.js was not checked.


来源: stackexchange

问:
What is the difference between 'WCHAR' and 'wchar_t'?
Is there any practical difference between WCHAR and wchar_t?

答:
Does anybody know how old WCHAR is? I would imagine it dates to at least Windows NT 3.1. I'd speculate that when Microsoft started using WCHAR in the Windows headers, wchar_t was not defined in either the C or C++ standard. Please correct me if I'm wrong.

Microsoft is in the unenviable position of having to support declarations and headers that a) must work in either C and C++ ; b) compile under very different architectures (i86, MIPS, PowerPC, Alpha, ...) and c) must be backwards-compatible with source code written for 15+ year old compilers. Plus, any breaking changes and thousands of books, reference manuals, online documentation, etc published over the last two decades would suddenly become WRONG.

WCHAR is an interface—once it became published it was written in stone, even if it's not needed for new code.

OwnerDisplayName: stimms

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Euro Micelli


问:
How can I secure an ASP .NET website that already uses Forms authentication?
I've got an ASP .NET website which uses Forms authentication to secure certain parts of the site. We have a test version of the site on a server and are making it available to partners over the web, e.g. at test.mydomain.com.

I need to secure all parts of the site so that only our partners can use it. Ideally it would be nice to have basic authentication pop up when they first hit the site, then have it work as normal thereafter, i.e. forms auth for certain areas.

However it seems ASP .NET and IIS don't support this. I'm aware of MADAM but that achieves something slightly different to what I need.

I'm considering restricting access by IP but that has two drawbacks, one it requires parters to "sign up" with their IP, and two, their IP could change.

Does anyone else have any suggestions?

答:
Ummm....

Well, the above solutions will work, but overall there is a better way. But does require some planning ahead.

your development and staging servers shouldn't be open to the general public, search bots, ect.. ect..

your dev and stg boxes can be locked down buy firewall or even ip access controls via IIS

No code solution


问:
How to approve multi-authentication in laravel
hi m working on Laravel multi-auth which is working fine, the admin redirects to admin page and user redirects to home page but I wants that if the user isn't approved then it shouldn't login and see the error "you can login after 24hr after your account will be approved"

I add this code in admin middleware but itsn't working:

if (auth()->check() && $request->user()->status == 0) {
    return redirect()->guest('login');
}else{
    return redirect('login')->with('flash_message_error','You can  login after approval');
}
```

<p>admin middleware:</p>

<pre class="lang-php prettyprint-override"><code>public function handle($request, Closure $next)
{
    if (auth()->check() && $request->user()->admin == 0) {
        return redirect()->guest('home');
    }
    return $next($request);
}
</code>```

Routes:

Route::group(['middleware' => ['web','auth']], function(){
    Route::get('/home', function(){
        if (Auth::user()->admin == 0) {
            return view('home');
         }else {
             $users['users'] = \App\User::all();
             return view('adminhome', $users);
         }
    });
});
```

<p>user model:</p>

<pre class="lang-php prettyprint-override"><code>protected $fillable = [
    'name', 'email', 'password', 'admin',
];
</code>```

this id db migration:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->boolean('admin')->default(0);
    $table->boolean('approved')->default(0);
    $table->rememberToken();
    $table->timestamps();
});
```

I just wants that when a user register then it should wait until the approved column in database becomes 1 manually

答:
inside your Auth/LoginController add below methods

```<code>namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use AuthenticatesUsers;

use Illuminate\Support\Facades\Hash;
use App\User;
class LoginController extends Controller
{

 protected function credentials(Request $request)
{
    $credentials = $request->only($this->username(), 'password');
    $credentials['status'] = 1;
    return $credentials;
}

 protected function sendFailedLoginResponse(Request $request)
{
    $errors = [$this->username() => trans('auth.failed')];
    // Load user from database

    $user = \App\User::where($this->username(), $request->{$this->username()})->first();

    // Check if user was successfully loaded, that the password matches
    // and status is not 1. If so, override the default error message.

    if ($user && \Hash::check($request->password, $user->password) && $user->status != 1) {

        $errors = [$this->username() => 'you can login after 24hr after your account will be approved'];
    }
    if ($request->expectsJson()) {
        return response()->json($errors, 422);
    }
    return redirect()->back()
        ->withInput($request->only($this->username(), 'remember'))
        ->withErrors($errors);
}

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
hi m working on Laravel multi-auth which is working fine, the admin redirects to admin page and user redirects to home page but I wants that if the user isn't approved then it shouldn't login and see the error "you can login after 24hr after your account will be approved"

I add this code in admin middleware but itsn't working:

if (auth()->check() && $request->user()->status == 0) {
    return redirect()->guest('login');
}else{
    return redirect('login')->with('flash_message_error','You can  login after approval');
}

admin middleware:

public function handle($request, Closure $next)
{
    if (auth()->check() && $request->user()->admin == 0) {
        return redirect()->guest('home');
    }
    return $next($request);
}

Routes:

Route::group(['middleware' => ['web','auth']], function(){
    Route::get('/home', function(){
        if (Auth::user()->admin == 0) {
            return view('home');
         }else {
             $users['users'] = \App\User::all();
             return view('adminhome', $users);
         }
    });
});

user model:

protected $fillable = [
    'name', 'email', 'password', 'admin',
];

this id db migration:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->boolean('admin')->default(0);
    $table->boolean('approved')->default(0);
    $table->rememberToken();
    $table->timestamps();
});

I just wants that when a user register then it should wait until the approved column in database becomes 1 manually

Body:
inside your Auth/LoginController add below methods

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use AuthenticatesUsers;

use Illuminate\Support\Facades\Hash;
use App\User;
class LoginController extends Controller
{

 protected function credentials(Request $request)
{
    $credentials = $request->only($this->username(), 'password');
    $credentials['status'] = 1;
    return $credentials;
}

 protected function sendFailedLoginResponse(Request $request)
{
    $errors = [$this->username() => trans('auth.failed')];
    // Load user from database

    $user = \App\User::where($this->username(), $request->{$this->username()})->first();

    // Check if user was successfully loaded, that the password matches
    // and status is not 1. If so, override the default error message.

    if ($user && \Hash::check($request->password, $user->password) && $user->status != 1) {

        $errors = [$this->username() => 'you can login after 24hr after your account will be approved'];
    }
    if ($request->expectsJson()) {
        return response()->json($errors, 422);
    }
    return redirect()->back()
        ->withInput($request->only($this->username(), 'remember'))
        ->withErrors($errors);
}

}


问:
EventEmitter Subscribing not working as expected, how to update value in component using subscribe
I like to subscribe to EventEmitter in a component. I wrote this code in Service

```<code>import { Injectable, OnChanges, EventEmitter } from '@angular/core';
import { area } from "../model-classes/area"
import { city } from "../model-classes/city"

@Injectable({
  providedIn: 'root'
})
export class servicetalk implements OnChanges
{
    ngOnChanges(changes: import("@angular/core").SimpleChanges): void {

    }
  area: string;
  areachange: EventEmitter<string> = new EventEmitter();
  constructor() { }
  setArea(lang) {
    this.area = lang;
    this.areachange.emit(this.area);
  }

  getArea() {
    return this.area;
  }

  MainToCity(i: string): void {
    this.area = i;
    this.areachange.emit(this.area);

  }

}
</code>```

And in my Component I am using this component code that also includes subscribing to EventEmitter

```<code>  import { Component, OnInit, OnChanges } from '@angular/core';
import { servicetalk } from "../../services/lh-component-talking"

@Component({
  selector: 'app-city',
  templateUrl: './city.component.html',
  styleUrls: ['./city.component.css']
})
export class CityComponent implements OnInit, OnChanges {
  ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
    alert(this.areaTxt)
    }
  areaTxt: string;
  constructor(ser: servicetalk) {
    ser.areachange.subscribe((area1) => { this.areaTxt = ser.area });

  }

  ngOnInit() {

  }

}
</code>```

I am using this line get get the value in city component

```<code>  ser.areachange.subscribe((area1) => { this.areaTxt = ser.getArea() });
</code>```

That subscribe is undefined

Basically I have one set of component,template. Clicking this template item my city template shows with cities

Master template is "area" clicking on any area cities get displayed. So on clicking on area I call getArea to set the area.

This is my area component

```<code>import { Component, OnInit, OnChanges, ChangeDetectorRef} from '@angular/core';
import { LhClientServiceService } from "../../services/lh-client-service.service"
import { area } from "../../model-classes/area"
import { servicetalk } from "../../services/lh-component-talking"

@Component({
  selector: 'app-area',
  templateUrl: './area.component.html',
  styleUrls: ['./area.component.css']
})
export class AreaComponent implements OnInit, OnChanges {
  areas: area[];
  selectedArea: string;
  constructor(private ser: LhClientServiceService, private cdr: ChangeDetectorRef, public talk: servicetalk)
  {

  }

  ngOnInit() {
    this.getAreas();
  }
  ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
    this.cdr.detectChanges()
  }
  getAreas(): void {
    this.ser.getArea();;
    this.cdr.detectChanges()

    console.log(this.areas);
  }
  onSelectArea(sa: string): void {
    this.selectedArea = sa;
    this.talk.setArea(sa);

  }

}
</code>```

But now the problem is when I click on area, it's not updating variable in city component. So my question now is how can I handle eventEmitter changes and display update when click on area (txtArea in city component should get update and display the respective data in city template). How can I refresh city component based on value change in EventEmitter?

答:
made this example and it would work for you.

https://stackblitz.com/edit/angular-vhazlx

change

```<code>ser.areachange.subscribe((area1) => { this.areaTxt = ser.area });
</code>```

}

for this

```<code>ser.areachange.subscribe((area1) => { this.areaTxt = area1});
</code>```

and create a event call

setArea

Body:
I like to subscribe to EventEmitter in a component. I wrote this code in Service

import { Injectable, OnChanges, EventEmitter } from '@angular/core';
import { area } from "../model-classes/area"
import { city } from "../model-classes/city"

@Injectable({
  providedIn: 'root'
})
export class servicetalk implements OnChanges
{
    ngOnChanges(changes: import("@angular/core").SimpleChanges): void {

    }
  area: string;
  areachange: EventEmitter<string> = new EventEmitter();
  constructor() { }
  setArea(lang) {
    this.area = lang;
    this.areachange.emit(this.area);
  }

  getArea() {
    return this.area;
  }

  MainToCity(i: string): void {
    this.area = i;
    this.areachange.emit(this.area);

  }

}

And in my Component I am using this component code that also includes subscribing to EventEmitter

  import { Component, OnInit, OnChanges } from '@angular/core';
import { servicetalk } from "../../services/lh-component-talking"

@Component({
  selector: 'app-city',
  templateUrl: './city.component.html',
  styleUrls: ['./city.component.css']
})
export class CityComponent implements OnInit, OnChanges {
  ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
    alert(this.areaTxt)
    }
  areaTxt: string;
  constructor(ser: servicetalk) {
    ser.areachange.subscribe((area1) => { this.areaTxt = ser.area });

  }

  ngOnInit() {

  }

}

I am using this line get get the value in city component

  ser.areachange.subscribe((area1) => { this.areaTxt = ser.getArea() });

That subscribe is undefined

Basically I have one set of component,template. Clicking this template item my city template shows with cities

Master template is "area" clicking on any area cities get displayed. So on clicking on area I call getArea to set the area.

This is my area component

import { Component, OnInit, OnChanges, ChangeDetectorRef} from '@angular/core';
import { LhClientServiceService } from "../../services/lh-client-service.service"
import { area } from "../../model-classes/area"
import { servicetalk } from "../../services/lh-component-talking"

@Component({
  selector: 'app-area',
  templateUrl: './area.component.html',
  styleUrls: ['./area.component.css']
})
export class AreaComponent implements OnInit, OnChanges {
  areas: area[];
  selectedArea: string;
  constructor(private ser: LhClientServiceService, private cdr: ChangeDetectorRef, public talk: servicetalk)
  {

  }

  ngOnInit() {
    this.getAreas();
  }
  ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
    this.cdr.detectChanges()
  }
  getAreas(): void {
    this.ser.getArea();;
    this.cdr.detectChanges()

    console.log(this.areas);
  }
  onSelectArea(sa: string): void {
    this.selectedArea = sa;
    this.talk.setArea(sa);

  }

}

But now the problem is when I click on area, it's not updating variable in city component. So my question now is how can I handle eventEmitter changes and display update when click on area (txtArea in city component should get update and display the respective data in city template). How can I refresh city component based on value change in EventEmitter?

Body:
made this example and it would work for you.

https://stackblitz.com/edit/angular-vhazlx

change

ser.areachange.subscribe((area1) => { this.areaTxt = ser.area });

}

for this

ser.areachange.subscribe((area1) => { this.areaTxt = area1});

and create a event call

setArea


问:
I can't get infinite nested loop within onCreate() method
I'm new to Android Studio programming and I'd like to know what is the substitute for code below..
I'm trying to iterate an infinite loop that has a nested one and it seem to not work. The application still crushes when it comes to that loop.

I also tried to use non-infinite loop without nesting another inside of it.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main3);

    while (state) {
        int i = 0;

        while (i < person[i].length) {
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    someTextView.setText(person[i].getName());
                }
            });
        }
        i++;
    }
}
</code>```

This Logcat below just represents the nested while loop without
the onClickListener unlike shown in code.

```<code>2019-06-01 11:59:10.695 19529-19529/com.example.app2 I/Timeline: Timeline: Activity_launch_request id:com.example.app2 time:120814793
2019-06-01 11:59:10.771 19529-19543/com.example.app2 I/art: Enter while loop.
2019-06-01 11:59:10.789 19529-19543/com.example.app2 I/art: Enter while loop.
</code>```

After entering while loop all I'm getting is a black screen on my device.

How do I  use these loops within onCreate() method?

答:
I have a few questions. If you want a infinite loop why not just:

```<code>while(true)
{
    //Execute some code
}
</code>```

My next question is why are you trying to do this? The reason why you are getting a black screen is cause you are stuck in an infinite loop. The code for the nested loop gets executed but because you are incrementing i outside the nested loop you will always return true, i will always be less than the length of person[]. There is nothing to render because a result is never reached. If you are looking to add onClickListeners to multiple objects the far better approach is to use a Recycler view with cards, and to assign the OnclickListeners in the Recycler adapter.

Body:
I'm new to Android Studio programming and I'd like to know what is the substitute for code below..
I'm trying to iterate an infinite loop that has a nested one and it seem to not work. The application still crushes when it comes to that loop.

I also tried to use non-infinite loop without nesting another inside of it.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main3);

    while (state) {
        int i = 0;

        while (i < person[i].length) {
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    someTextView.setText(person[i].getName());
                }
            });
        }
        i++;
    }
}

This Logcat below just represents the nested while loop without
the onClickListener unlike shown in code.

2019-06-01 11:59:10.695 19529-19529/com.example.app2 I/Timeline: Timeline: Activity_launch_request id:com.example.app2 time:120814793
2019-06-01 11:59:10.771 19529-19543/com.example.app2 I/art: Enter while loop.
2019-06-01 11:59:10.789 19529-19543/com.example.app2 I/art: Enter while loop.

After entering while loop all I'm getting is a black screen on my device.

How do I  use these loops within onCreate() method?

Body:
I have a few questions. If you want a infinite loop why not just:

while(true)
{
    //Execute some code
}

My next question is why are you trying to do this? The reason why you are getting a black screen is cause you are stuck in an infinite loop. The code for the nested loop gets executed but because you are incrementing i outside the nested loop you will always return true, i will always be less than the length of person[]. There is nothing to render because a result is never reached. If you are looking to add onClickListeners to multiple objects the far better approach is to use a Recycler view with cards, and to assign the OnclickListeners in the Recycler adapter.


问:
Simplebar scrollbar plugin - Scroll to top / reset position in function
I need to be able to scroll back to the top of a page within my ui-routed angular one-page site when a function is triggered, but I've used the simplebar scrollbar plugin as a custom scroller, so can't use the window scrolltop method to take the user back to the top of the page.

I can't use any window/document scrolling method as the container that utilises simplebar is a fixed 100vh container, therefore the window is always scrolled to the top.

I've tried using the jquery method below to reset the position of the scrollbar back to the top, but can't get it working, and there are no error messages in the console.

```<code>angular.element('#mainContent').simplebar('getScrollElement').scrollTop(0);
</code>```

I've also tried this in plain js, which returns 'is not a function' in the console:

```<code>var mainContent = new SimpleBar(document.getElementById('mainContent'));
</code>```

mainContent.SimpleBar.getScrollElement().scrollTop = 0;

答:
```<code>var el = new SimpleBar(document.getElementById('myElement'));
el.getScrollElement().scrollTop = 0;
</code>```

Body:
I need to be able to scroll back to the top of a page within my ui-routed angular one-page site when a function is triggered, but I've used the simplebar scrollbar plugin as a custom scroller, so can't use the window scrolltop method to take the user back to the top of the page.

I can't use any window/document scrolling method as the container that utilises simplebar is a fixed 100vh container, therefore the window is always scrolled to the top.

I've tried using the jquery method below to reset the position of the scrollbar back to the top, but can't get it working, and there are no error messages in the console.

angular.element('#mainContent').simplebar('getScrollElement').scrollTop(0);

I've also tried this in plain js, which returns 'is not a function' in the console:

var mainContent = new SimpleBar(document.getElementById('mainContent'));

mainContent.SimpleBar.getScrollElement().scrollTop = 0;


问:
Exporting Access Query to Excel
I've got an Access 2007 database on which I have created around 15 SQL queries to process specific data, I have created a main frame navigation menu using menus in Access, I now need to extract all th queries to Excel using VBA code, I have managed to do this with the code below by creating a button and specifying this code to it.

```<code>Private Sub query1_Click()
DoCmd.TransferSpreadsheet acExport, _
acSpreadsheetTypeExcel9, "Total Users and Sessions", _
"C:\UsersandSessions.xls", , "Total Users & Sessions"
End Sub
</code>```

Now my problem at the moment is that fine the query is exported to Excel, but it is done so without any formatting applied at all, I would like to add some formatting at least to the headers and maybe a title inside the spreadsheet, and one thing I dont really like is that all records are being started from the first cell. Also I would prefer that if I hit that button again in Access and the Excel spreadsheet has already exists with that query output then when clicked again it will write again to a the next available sheet.

Any suggestions or ideas a very welcome.

答:
if you use DoCmd.TransferSpreadsheet and create an original and then edit it so that the formatting is correct, you can then run DoCmd.TransferSpreadsheet again and it will update the file with the values but keep the formatting.

However, if a human then changes the file by adding new tabs, or adding calculations, etc, then the DoCmd.TransferSpreadsheet will no longer work and will fail with an ugly error message. So what we do in our enviroment is DoCmd.TransferSpreadsheet to an original file with formatting, and follow that up in the VBA by copying the file to the users desktop, and then opening that copy so the user doesn't mess up the original source excel file.

This approach is a minimum code, clean, and easy to maintain solution. But it does require a extra "source" or original file to be hanging around. Works in Access 2007.

You also would like the results to end up on a new tab. Unfortunately, I think it will take some excel automation to do that.  The VBA inside Acccess can call a function inside the VBA in Excel.  That VBA could then copy the tabs as needed.

ContentLicense: CC BY-SA 2.5

Title: Exporting Access Query to Excel

Body:
I've got an Access 2007 database on which I have created around 15 SQL queries to process specific data, I have created a main frame navigation menu using menus in Access, I now need to extract all th queries to Excel using VBA code, I have managed to do this with the code below by creating a button and specifying this code to it.

Private Sub query1_Click()
DoCmd.TransferSpreadsheet acExport, _
acSpreadsheetTypeExcel9, "Total Users and Sessions", _
"C:\UsersandSessions.xls", , "Total Users & Sessions"
End Sub

Now my problem at the moment is that fine the query is exported to Excel, but it is done so without any formatting applied at all, I would like to add some formatting at least to the headers and maybe a title inside the spreadsheet, and one thing I dont really like is that all records are being started from the first cell. Also I would prefer that if I hit that button again in Access and the Excel spreadsheet has already exists with that query output then when clicked again it will write again to a the next available sheet.

Any suggestions or ideas a very welcome.


问:
All post message is not showing with sql GROUP_CONCAT
I have this comments table to store all comments of each Post

```<code>comment_id    comment_message    posts_id   u_id   created
=============================================================
46            comments....       2          6      1559376498
47            comments....       2          6      1559376502
48            comments....       2          6      1559376598
</code>```

and comments_like table for each comment reaction (r_id)

```<code>cl_id    comment_id   posts_id    u_id   r_id   created
=============================================================
42       46           2           6      6     1559376598
43       47           2           6      2     1559376598
44       48           2           6      8     1559376598
45       46           2           1      2     1559376598
</code>```

Note: posts_id means posts table id, u_id means users table id, r_id means reaction id, comment_id means comment table id.

Now, I want to get all comments for a specific ID with a list of reaction id's and that reaction id which is given by the logged user.

For that, I am using the following SQL query but it's not showing my expected result :(

```<code>$query = $this->_db->_pdo->prepare("
            SELECT c.*, u.u_id, u.full_name, cl.r_id, GROUP_CONCAT(cl.r_id ORDER BY cl.u_id) AS r_id
            FROM comments AS c
            LEFT JOIN users AS u ON c.u_id = u.u_id
            LEFT JOIN comments_like AS cl ON cl.comment_id = c.comment_id
            WHERE c.posts_id = '$post_id'
            ORDER BY c.comment_id  ");
</code>```

Output of this query should be

1) all comments of specific post id ($post_id);

2) a list of reaction id's

3) reaction id of logged user.

答:
You seem to want the reaction id for a particular user as well.  If so:

```<code>SELECT c.*, u.u_id, u.full_name,
       MAX(ASE WHEN cl.u_id = ? THEN cl.r_id END) as specific_user_reaction,
       GROUP_CONCAT(cl.r_id ORDER BY cl.u_id) AS r_id
FROM comments c LEFT JOIN
     users u
     ON c.u_id = u.u_id LEFT JOIN
     comments_like cl
     ON cl.comment_id = c.comment_id
WHERE c.posts_id = ?
GROUP BY c.comment_id, u.u_id, u.full_name
ORDER BY c.comment_id;
</code>```

The ? are for parameters.  This is how you should be passing values into prepared statement (rather than munging query strings).

The first ? is for the user whose reaction you want.  The second is for the post that you want ($post_id in your original code).  You can review the documentation on prepared statements if you need to learn more about passing in parameters.

Body:
I have this comments table to store all comments of each Post

comment_id    comment_message    posts_id   u_id   created
=============================================================
46            comments....       2          6      1559376498
47            comments....       2          6      1559376502
48            comments....       2          6      1559376598

and comments_like table for each comment reaction (r_id)

cl_id    comment_id   posts_id    u_id   r_id   created
=============================================================
42       46           2           6      6     1559376598
43       47           2           6      2     1559376598
44       48           2           6      8     1559376598
45       46           2           1      2     1559376598

Note: posts_id means posts table id, u_id means users table id, r_id means reaction id, comment_id means comment table id.

Now, I want to get all comments for a specific ID with a list of reaction id's and that reaction id which is given by the logged user.

For that, I am using the following SQL query but it's not showing my expected result :(

$query = $this->_db->_pdo->prepare("
            SELECT c.*, u.u_id, u.full_name, cl.r_id, GROUP_CONCAT(cl.r_id ORDER BY cl.u_id) AS r_id
            FROM comments AS c
            LEFT JOIN users AS u ON c.u_id = u.u_id
            LEFT JOIN comments_like AS cl ON cl.comment_id = c.comment_id
            WHERE c.posts_id = '$post_id'
            ORDER BY c.comment_id  ");

Output of this query should be

1) all comments of specific post id ($post_id);

2) a list of reaction id's

3) reaction id of logged user.

Body:
You seem to want the reaction id for a particular user as well.  If so:

SELECT c.*, u.u_id, u.full_name,
       MAX(ASE WHEN cl.u_id = ? THEN cl.r_id END) as specific_user_reaction,
       GROUP_CONCAT(cl.r_id ORDER BY cl.u_id) AS r_id
FROM comments c LEFT JOIN
     users u
     ON c.u_id = u.u_id LEFT JOIN
     comments_like cl
     ON cl.comment_id = c.comment_id
WHERE c.posts_id = ?
GROUP BY c.comment_id, u.u_id, u.full_name
ORDER BY c.comment_id;

The ? are for parameters.  This is how you should be passing values into prepared statement (rather than munging query strings).

The first ? is for the user whose reaction you want.  The second is for the post that you want ($post_id in your original code).  You can review the documentation on prepared statements if you need to learn more about passing in parameters.


问:
How can I email a specific range of cells while KEEPING the displayed formatting?
I am trying to export a specific range of cells in the form of an email.  The cells are formatted a certain way, and also have conditional formatting associated for color-coding.

Here is my demo sheet: https://docs.google.com/spreadsheets/d/1ibB87Vhz7wTjKrIrasYSRLoAiadQHtNqqmyl-xywtOI/edit?usp=sharing

Ive gotten the email to send successfully, however I cant figure out how to take the associated formatting, conditional formatting, fonts, borders...etc.

Currently, it's taking the displayValues, and listing them with comas.  I'm also looking to get rid of the comas, and if possible, limit the range to only cells with data within the range.

Here is what I've got:

```<code>    function sendReport(){
      var incidents = SpreadsheetApp.getActiveSheet().getRange(2,1,4,1).getDisplayValues();
      var subjectRange = SpreadsheetApp.getActiveSheet().getRange("A1");
      var subjectCell = subjectRange.getValues();
      for (i in subjectCell) {
        var rowData = subjectCell[i];
        var subject = rowData [0];
      }
      MailApp.sendEmail("emailaddress@domain.com",
                subject,
                incidents);
    }
</code>```

答:
That's because you are literally sending an Array in your email (since getValues() returns a 2-dimensional Array). If you want to keep formatting, you should construct an html table from this array by iterating over it and append the result to email body via htmlBody property in options.

Take a look at the documentation for detailed info on how to get styles from Range. You will have to map each styling into style="" attribute for HtmlElements you want to be formatted, like so (to save resources, get styling in bulk and include into Array loop):

getFontColors() - color:{method result} (if one, apply to HtmlTableElement);

getFontFamilies() - font-family:{method result};

...etc...

or simply get all styles in bulk with getTextStyles() and access individual style property with appropriate methods (note that you will still need to access background colors with getBackgrounds() method, height with getHeight(), etc).

Body:
I am trying to export a specific range of cells in the form of an email.  The cells are formatted a certain way, and also have conditional formatting associated for color-coding.

Here is my demo sheet: https://docs.google.com/spreadsheets/d/1ibB87Vhz7wTjKrIrasYSRLoAiadQHtNqqmyl-xywtOI/edit?usp=sharing

Ive gotten the email to send successfully, however I cant figure out how to take the associated formatting, conditional formatting, fonts, borders...etc.

Currently, it's taking the displayValues, and listing them with comas.  I'm also looking to get rid of the comas, and if possible, limit the range to only cells with data within the range.

Here is what I've got:

    function sendReport(){
      var incidents = SpreadsheetApp.getActiveSheet().getRange(2,1,4,1).getDisplayValues();
      var subjectRange = SpreadsheetApp.getActiveSheet().getRange("A1");
      var subjectCell = subjectRange.getValues();
      for (i in subjectCell) {
        var rowData = subjectCell[i];
        var subject = rowData [0];
      }
      MailApp.sendEmail("emailaddress@domain.com",
                subject,
                incidents);
    }


问:
Python: Getting all pairs and frequency of pairs in multi-dimensional list
my multi-dimensional list looks as follows:

```<code>    mylist = [[13, 41, 3, 23, 12, 16], [12, 32, 30, 49, 3, 18],
              [34, 12, 14, 24, 35, 20], [29, 28, 12, 44, 13, 4],
              [31, 44, 6, 49, 5, 39]]
</code>```

There are pairs (numbers with difference 1) in some of the lists. not in every list: (12,13) in the first list, (34,35) in the third list, (28,29) and (12,13) in the fourth.

What I want to have is to get all the found pairs which should be saved in a (sorted) list based on the frequency (ascending). In my case above, it would look like follows:

```<code>    fr_list = [[12,13],[12,13],[28,29],[34,35]]
</code>```

I wrote the following code to find the pairs

```<code>    def find_pairs(lst, key):
            return [(a,b) for a,b in permutations(lst, 2) if a-b==key]
</code>```

Then, I tried this:

```<code>    fr_list = [find_pairs(mylist,1) for x in mylist]
</code>```

However, I get the following error message:

```<code>    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in <listcomp>
      File "<stdin>", line 2, in find_pairs
      File "<stdin>", line 2, in <listcomp>
    TypeError: unsupported operand type(s) for -: 'list' and 'list'
</code>```

Can anybody help me out? Thanks.

答:
this is how i would go about this:

```<code>from collections import Counter
from itertools import repeat, chain

def find_diff(lst):
    srt = sorted(lst)
    return Counter((a, b) for a, b in zip(srt, srt[1:]) if b - a == 1)

pairs = sum((find_diff(item) for item in mylist), Counter())
# Counter({(12, 13): 2, (34, 35): 1, (28, 29): 1, (5, 6): 1})
res = tuple(
    chain.from_iterable(repeat(item, count) for item, count in pairs.most_common())
)
# ((12, 13), (12, 13), (34, 35), (28, 29), (5, 6))
</code>```

it is more efficient to iterate over the sorted list if you are looking for a difference of 1. then i store everything in Counter objects in order to efficiently find the most common.

the last part is a bit of itertools magic that extracts the items and their multiplicity by frequency.

Body:
my multi-dimensional list looks as follows:

    mylist = [[13, 41, 3, 23, 12, 16], [12, 32, 30, 49, 3, 18],
              [34, 12, 14, 24, 35, 20], [29, 28, 12, 44, 13, 4],
              [31, 44, 6, 49, 5, 39]]

There are pairs (numbers with difference 1) in some of the lists. not in every list: (12,13) in the first list, (34,35) in the third list, (28,29) and (12,13) in the fourth.

What I want to have is to get all the found pairs which should be saved in a (sorted) list based on the frequency (ascending). In my case above, it would look like follows:

    fr_list = [[12,13],[12,13],[28,29],[34,35]]

I wrote the following code to find the pairs

    def find_pairs(lst, key):
            return [(a,b) for a,b in permutations(lst, 2) if a-b==key]

Then, I tried this:

    fr_list = [find_pairs(mylist,1) for x in mylist]

However, I get the following error message:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in <listcomp>
      File "<stdin>", line 2, in find_pairs
      File "<stdin>", line 2, in <listcomp>
    TypeError: unsupported operand type(s) for -: 'list' and 'list'

Can anybody help me out? Thanks.

Body:
this is how i would go about this:

from collections import Counter
from itertools import repeat, chain

def find_diff(lst):
    srt = sorted(lst)
    return Counter((a, b) for a, b in zip(srt, srt[1:]) if b - a == 1)

pairs = sum((find_diff(item) for item in mylist), Counter())
# Counter({(12, 13): 2, (34, 35): 1, (28, 29): 1, (5, 6): 1})
res = tuple(
    chain.from_iterable(repeat(item, count) for item, count in pairs.most_common())
)
# ((12, 13), (12, 13), (34, 35), (28, 29), (5, 6))

it is more efficient to iterate over the sorted list if you are looking for a difference of 1. then i store everything in Counter objects in order to efficiently find the most common.

the last part is a bit of itertools magic that extracts the items and their multiplicity by frequency.


问:
When I use my php post function, It deletes my session cookie without my control
I set a user cookie when my user logs in to the page and it works correctly. Also, I put a script to all my pages to check cookies. But when I use a php post script, my cookie is being deleted and system automatically send me back to login page. Have you got any idea about that situation?

I have tried to set cookie again in my post.php scripts but it doesn't work.

'

```<code><?php
    include 'config.php';

$blok_header = filter_input(INPUT_POST,'blok_header');
$blok_text = filter_input(INPUT_POST,'blok_text');
$Sayfa_Linkleri = filter_input(INPUT_POST,'Sayfa_Linkleri');

$sl = $_GET["Sayfa_Linkleri"];
    // Veritabanına Ekleyelim.

$guncelle = mysqli_query($conn,"UPDATE example_table
  SET blok_header = '$blok_header' , blok_text = '$blok_text', Sayfa_Linkleri = '$Sayfa_Linkleri' ,guncelle = '$now'
  WHERE Sayfa_Linkleri='$sl'") ;

if($guncelle){
      header("location: http://example.com/example-admin/admin/example_edit.php?Sayfa_Linkleri=".$sl);
}
else{
    echo "Bir Sorun Oluştu";
}
?>
</code>```

'

```<code><?php
</code>```

if(htmlspecialchars($_COOKIE["kullanici"]) == null)
{

```<code>header("refresh:1;url=http://www.example.com/example-admin");
</code>```

}
?>

答:
I found my problem and solve it. If anyone who see the same issue, my problem was about

```<code>header("location:  http://examplesite/example-admin/admin/some.php");
</code>```

I turned it to

```<code>header("location: ../../some.php");
</code>```

It worked !

Body:
I set a user cookie when my user logs in to the page and it works correctly. Also, I put a script to all my pages to check cookies. But when I use a php post script, my cookie is being deleted and system automatically send me back to login page. Have you got any idea about that situation?

I have tried to set cookie again in my post.php scripts but it doesn't work.

'

<?php
    include 'config.php';

$blok_header = filter_input(INPUT_POST,'blok_header');
$blok_text = filter_input(INPUT_POST,'blok_text');
$Sayfa_Linkleri = filter_input(INPUT_POST,'Sayfa_Linkleri');

$sl = $_GET["Sayfa_Linkleri"];
    // Veritabanına Ekleyelim.

$guncelle = mysqli_query($conn,"UPDATE example_table
  SET blok_header = '$blok_header' , blok_text = '$blok_text', Sayfa_Linkleri = '$Sayfa_Linkleri' ,guncelle = '$now'
  WHERE Sayfa_Linkleri='$sl'") ;

if($guncelle){
      header("location: http://example.com/example-admin/admin/example_edit.php?Sayfa_Linkleri=".$sl);
}
else{
    echo "Bir Sorun Oluştu";
}
?>

'

<?php

if(htmlspecialchars($_COOKIE["kullanici"]) == null)
{

header("refresh:1;url=http://www.example.com/example-admin");

}
?>

Body:
I found my problem and solve it. If anyone who see the same issue, my problem was about

header("location:  http://examplesite/example-admin/admin/some.php");

I turned it to

header("location: ../../some.php");

It worked !


问:
How to use Future<AudioCache>?
Question by a Flutter Newbie ;D :

I want to play an audiofile and be able to set its volume or pause it.

The function "loop" returns a variable of the type Future but the documentation (https://github.com/luanpotter/audioplayers/blob/master/doc/audio_cache.md) says it returns type AudioPlayer.

```<code>Future<AudioPlayer> audioPlayer = audioCache.loop('background_music.mp3');
</code>```

should be

```<code>AudioPlayer audioPlayer = audioCache.loop('background_music.mp3');
</code>```

But how can I work with this variable or convert it to AudioPlayer?

```<code>AudioPlayer.pause();
</code>```

works but not
    Future.pause();

My Solution:

```<code>    Future<AudioPlayer> audioPlayer = audioCache.loop('background_music.mp3');
  audioPlayer.then((player) {
    player.setVolume(0.2);
  });
</code>```

答:
Concept

Futures in Dart is something similar to Promise in JS world. Futures indicate that something is going to happen at some point in the future. The best part about it is that it allows Dart not to block program execution until a computation is done. It allows Dart to keep running other parts of your application that do not depend on that usually slow computation. Such as starting to loop an audio file.

To loop an audio file you have to do a bunch of things:

load the file from FS into memory

instantiate an AudioPlayer

set some properties on it

Out of all that, reading the file-system is a relatively slow operation, therefore wrapped in a Future. Read more about futures here

But how can I work with this variable or convert it to AudioPlayer?

await the future: AudioPlayer loopingPlayer = await audioCache.loop('somefile');

then the future: audioCache.loop('somefile').then((pl) { /* do work here */ });

works but not Future.pause();

That is because Future (a class), doesn't have a method pause(). AudioPlayer does. So to call that method, you have to wait for the computation wrapped in a Future to complete (in this case, the things I mentioned above).

Title: How to use Future<AudioCache>?

Body:
Question by a Flutter Newbie ;D :

I want to play an audiofile and be able to set its volume or pause it.

The function "loop" returns a variable of the type Future but the documentation (https://github.com/luanpotter/audioplayers/blob/master/doc/audio_cache.md) says it returns type AudioPlayer.

Future<AudioPlayer> audioPlayer = audioCache.loop('background_music.mp3');

should be

AudioPlayer audioPlayer = audioCache.loop('background_music.mp3');

But how can I work with this variable or convert it to AudioPlayer?

AudioPlayer.pause();

works but not
    Future.pause();

My Solution:

    Future<AudioPlayer> audioPlayer = audioCache.loop('background_music.mp3');
  audioPlayer.then((player) {
    player.setVolume(0.2);
  });


问:
update an array inside an EntityAdapter
I have the following EntityAdapter

```<code>export interface IDroneRoute {
  assignedDroneId?: number;
  routeId: string;
  rerouting?: boolean;
  waypoints: Waypoint[];
}

export const featureAdapter: EntityAdapter<IDroneRoute> = createEntityAdapter<IDroneRoute>({
  selectId: model => model.routeId,
});
</code>```

I would like to have an action that add, remove and delete a waypoint in the array

```<code>const ADD_ROUTE_POINT = (state: State, action: any) => {
  return featureAdapter.updateOne({
    id: action.payload.routeId,
    changes: {// add waypoint},
  }, state);
};
</code>```

how do I access the current array of the item inside the changes so that I can update it ?

答:
changes corresponds to the entity you want to update (IDroneRoute), so before you return featureAdapter.updateOne({ you can build your updated object.

```<code>const REMOVE_ROUTE_POINT = (state: State, action: any) => {
  const droneRoute = {...state.entities[action.payload.routeId]}
  droneRoute.waypoints = droneRoute.waypoints.filter(
    wp => wp.id !== action.payload.waypoint.id);

  return featureAdapter.updateOne({
    id: action.payload.routeId,
    changes: droneRoute,
  }, state);
};

const ADD_ROUTE_POINT = (state: State, action: any) => {
  const droneRoute = {...state.entities[action.payload.routeId]};
  droneRoute.waypoints = [...droneRoute.waypoints, ...action.payload.waypoint];

  return featureAdapter.updateOne({
    id: action.payload.routeId,
    changes: droneRoute,
  }, state);
};
</code>```

Title: update an array inside an EntityAdapter

Body:
I have the following EntityAdapter

export interface IDroneRoute {
  assignedDroneId?: number;
  routeId: string;
  rerouting?: boolean;
  waypoints: Waypoint[];
}

export const featureAdapter: EntityAdapter<IDroneRoute> = createEntityAdapter<IDroneRoute>({
  selectId: model => model.routeId,
});

I would like to have an action that add, remove and delete a waypoint in the array

const ADD_ROUTE_POINT = (state: State, action: any) => {
  return featureAdapter.updateOne({
    id: action.payload.routeId,
    changes: {// add waypoint},
  }, state);
};

how do I access the current array of the item inside the changes so that I can update it ?

Body:
changes corresponds to the entity you want to update (IDroneRoute), so before you return featureAdapter.updateOne({ you can build your updated object.

const REMOVE_ROUTE_POINT = (state: State, action: any) => {
  const droneRoute = {...state.entities[action.payload.routeId]}
  droneRoute.waypoints = droneRoute.waypoints.filter(
    wp => wp.id !== action.payload.waypoint.id);

  return featureAdapter.updateOne({
    id: action.payload.routeId,
    changes: droneRoute,
  }, state);
};

const ADD_ROUTE_POINT = (state: State, action: any) => {
  const droneRoute = {...state.entities[action.payload.routeId]};
  droneRoute.waypoints = [...droneRoute.waypoints, ...action.payload.waypoint];

  return featureAdapter.updateOne({
    id: action.payload.routeId,
    changes: droneRoute,
  }, state);
};


问:
How to change the objects of an array based on objects of another array
I encountered the following problem. I want to do the following, there is an array of 5 elements, I want to add a property and isExist to the elements of the array that are contained in the second, otherwise leave the object unchanged.

I tried to use the map method, but it returns an array of arrays to me, and I need to return the same array, only with the additional property of the first 2 objects.

```<code>const arr1 = [{id: 1, title:'test1'}, {id: 2, title:'test2'}, {id: 3, title:'test3'},{id: 4, title:'test4'} ,{id: 5, title:'test5'}];
const arr2 = [{id: 1, title:'test1'}, {id: 2, title:'test2'}];

const filteredArr = arr1.filter(item => {
    return arr2.filter(item2 => {
        if (item2.id === item.id) {
            return {...item, isExist: true}
        } else {
            return {...item}
        }
    })
})
</code>```

Expected result: in the first array the objects with ID 1 and 2 should contain additionally the isExist property, the rest should remain in the array, but without the isExist property.

答:
You can use map and some

map through arr1 check for id of each element on arr2

If it is found add isExist else return original value

const arr1 = [{id: 1, title:'test1'}, {id: 2, title:'test2'}, {id: 3, title:'test3'},{id: 4, title:'test4'} ,{id: 5, title:'test5'}];
const arr2 = [{id: 1, title:'test1'}, {id: 2, title:'test2'}];

let op = arr1.map(value => {
  let isExist = arr2.some(e => e.id === value.id)
  return isExist ? {...value,isExist} : value
})

console.log(op)```

Body:
I encountered the following problem. I want to do the following, there is an array of 5 elements, I want to add a property and isExist to the elements of the array that are contained in the second, otherwise leave the object unchanged.

I tried to use the map method, but it returns an array of arrays to me, and I need to return the same array, only with the additional property of the first 2 objects.

const arr1 = [{id: 1, title:'test1'}, {id: 2, title:'test2'}, {id: 3, title:'test3'},{id: 4, title:'test4'} ,{id: 5, title:'test5'}];
const arr2 = [{id: 1, title:'test1'}, {id: 2, title:'test2'}];

const filteredArr = arr1.filter(item => {
    return arr2.filter(item2 => {
        if (item2.id === item.id) {
            return {...item, isExist: true}
        } else {
            return {...item}
        }
    })
})

Expected result: in the first array the objects with ID 1 and 2 should contain additionally the isExist property, the rest should remain in the array, but without the isExist property.


问:
Ruby on Rails segfault in excon/connection.rb connect function
I am using Carrierwave with Rails 3.0.4.  Everything works fine on my big project when I am storing the files locally on the server, but when I switch over to use Amazon s3 things fall apart.  Namely I get this error (just the end of a very large trace):

```<code>/Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/excon-0.6.1/lib/excon/connection.rb:252: [BUG] Segmentation fault
ruby 1.9.2p136 (2010-12-25 revision 30365) [x86_64-darwin10.6.0]

-- control frame ----------
c:0099 p:---- s:0529 b:0529 l:000528 d:000528 CFUNC  :connect
c:0098 p:0192 s:0526 b:0526 l:000525 d:000525 METHOD /Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/excon-0.6.1/lib/excon/connection.rb:252
c:0097 p:0333 s:0519 b:0519 l:000518 d:000518 METHOD /Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/excon-0.6.1/lib/excon/connection.rb:231
c:0096 p:0030 s:0513 b:0510 l:000509 d:000509 METHOD /Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/excon-0.6.1/lib/excon/connection.rb:268
c:0095 p:0618 s:0507 b:0507 l:000506 d:000506 METHOD /Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/excon-0.6.1/lib/excon/connection.rb:148
c:0094 p:0100 s:0491 b:0491 l:000490 d:000490 METHOD /Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/fog-0.7.1/lib/fog/core/connection.rb:20
c:0093 p:0106 s:0483 b:0483 l:000482 d:000482 METHOD /Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/fog-0.7.1/lib/fog/storage/aws.rb:323
</code>```

What makes it even weirder is that I have successfully made two other projects that use the same code and the same gems and the same version of Ruby (1.9.2-p136) that work just fine with Amazon s3.  The only difference between the projects is SQLite vs MySQL along with different internal, seemingly unrelated code.

Here is a post I made to the Carrierwave google group.

Thanks for any help.

答: Solved.  The problem was the mysql gem.  Use ruby-mysql or mysql2 instead.  This causes a broken pipe on Linux systems and can easily be misdiagnosed as an openssl, carrierwave, or fog problem.</p>

Body:
I am using Carrierwave with Rails 3.0.4.  Everything works fine on my big project when I am storing the files locally on the server, but when I switch over to use Amazon s3 things fall apart.  Namely I get this error (just the end of a very large trace):

/Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/excon-0.6.1/lib/excon/connection.rb:252: [BUG] Segmentation fault
ruby 1.9.2p136 (2010-12-25 revision 30365) [x86_64-darwin10.6.0]

-- control frame ----------
c:0099 p:---- s:0529 b:0529 l:000528 d:000528 CFUNC  :connect
c:0098 p:0192 s:0526 b:0526 l:000525 d:000525 METHOD /Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/excon-0.6.1/lib/excon/connection.rb:252
c:0097 p:0333 s:0519 b:0519 l:000518 d:000518 METHOD /Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/excon-0.6.1/lib/excon/connection.rb:231
c:0096 p:0030 s:0513 b:0510 l:000509 d:000509 METHOD /Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/excon-0.6.1/lib/excon/connection.rb:268
c:0095 p:0618 s:0507 b:0507 l:000506 d:000506 METHOD /Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/excon-0.6.1/lib/excon/connection.rb:148
c:0094 p:0100 s:0491 b:0491 l:000490 d:000490 METHOD /Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/fog-0.7.1/lib/fog/core/connection.rb:20
c:0093 p:0106 s:0483 b:0483 l:000482 d:000482 METHOD /Users/nic/.rvm/gems/ruby-1.9.2-p136@hci/gems/fog-0.7.1/lib/fog/storage/aws.rb:323

What makes it even weirder is that I have successfully made two other projects that use the same code and the same gems and the same version of Ruby (1.9.2-p136) that work just fine with Amazon s3.  The only difference between the projects is SQLite vs MySQL along with different internal, seemingly unrelated code.

Here is a post I made to the Carrierwave google group.

Thanks for any help.


问:
Why do we pass nn.Module as an argument to class definition for neural nets?
I want to understand why we pass torch.nn.Module as a argument when we define the class for a neural network like GAN's

import torch
import torch.nn as nn

class Generator(nn.Module):
    def __init__(self, input_size, hidden_size, output_size, f):
        super(Generator, self).__init__()
        self.map1 = nn.Linear(input_size, hidden_size)
        self.map2 = nn.Linear(hidden_size, hidden_size)
        self.map3 = nn.Linear(hidden_size, output_size)
        self.f = f
```

答:
We are essentially defining the class 'Generator' with the nn.Module (with its functionalities). In programming we refer to this as inheritence (with the super(Generator, self).__init__()).

You can read more here: https://www.w3schools.com/python/python_inheritance.asp


问:
How to effectively combine multiple Maybe monads in JavaScript?
I have an object of css rules which can have any or none of the following properties:

```<code>{ 'font-style': '…',
  'font-variant': '…',
  'font-weight': '…',
  'text-decoration': '…',
  'vertical-align': '…' }
</code>```

The next step is to build up a css string that is applied to an input, e.g.:

```<code>style({'text-decoration': 'underline'}, 'foo');
//=> '<span style="text-decoration:underline">foo</span>'
</code>```

However if the rules object does not contain any of the above five css rule, the input is returned as is:

```<code>style({}, 'foo'); //=> 'foo'
</code>```

As you can see this is not rocket science but care must be taken so as to not apply an empty css string or include extra stuff that we don't need.

I did come up with a solution using ramda.js which I was quite happy with until I decided to dive deeper into Monads.

I was impressed with the amount of code I have been able to remove by using a few Monadic principles.

```<code>const {curry} = require('ramda');
const {Maybe} = require('monet');

const css = (attrs, key) =>
  attrs[key] ?
    Maybe.of(`${key}:${attrs[key]};`) :
    Maybe.of('');

const style = curry((va, td, fw, fv, fs, input) =>
  va || td || fw || fv || fs ?
    `<span style="${va}${td}${fw}${fv}${fs}">${input}</span>` : input);

module.exports = curry((attrs, input) =>
  Maybe.of(input)
    .ap(css('font-style', attrs)
    .ap(css('font-variant', attrs)
    .ap(css('font-weight', attrs)
    .ap(css('text-decoration', attrs)
    .ap(css('vertical-align', attrs)
    .map(style))))))
    .some());
</code>```

I'm happy with this but I can't help thinking that all these nested ap are some sort of callbacks hell in disguise. Perhaps there's a better way which I am not aware of?

Question: is there a better way to combine multiple Maybe monads?

答:
You are really overcomplicating things:</p>

```<code>  const keys = ['font-style', 'font-variant', 'font-weight', 'text-decoration', 'vertical-align'];

  const css = attrs => keys
     .map(it => attrs[it] && `${it}: ${attrs[it]}`)
     .filter(it => it)
     .join(", ");

 const style = (attrs, input) =>
   css(attrs) ? `<span style="${css(attrs)}">${input}</span>` : input;
</code>```

Body:
I have an object of css rules which can have any or none of the following properties:

{ 'font-style': '…',
  'font-variant': '…',
  'font-weight': '…',
  'text-decoration': '…',
  'vertical-align': '…' }

The next step is to build up a css string that is applied to an input, e.g.:

style({'text-decoration': 'underline'}, 'foo');
//=> 'foo'

However if the rules object does not contain any of the above five css rule, the input is returned as is:

style({}, 'foo'); //=> 'foo'

As you can see this is not rocket science but care must be taken so as to not apply an empty css string or include extra stuff that we don't need.

I did come up with a solution using ramda.js which I was quite happy with until I decided to dive deeper into Monads.

I was impressed with the amount of code I have been able to remove by using a few Monadic principles.

const {curry} = require('ramda');
const {Maybe} = require('monet');

const css = (attrs, key) =>
  attrs[key] ?
    Maybe.of(`${key}:${attrs[key]};`) :
    Maybe.of('');

const style = curry((va, td, fw, fv, fs, input) =>
  va || td || fw || fv || fs ?
    `<span style="${va}${td}${fw}${fv}${fs}">${input}</span>` : input);

module.exports = curry((attrs, input) =>
  Maybe.of(input)
    .ap(css('font-style', attrs)
    .ap(css('font-variant', attrs)
    .ap(css('font-weight', attrs)
    .ap(css('text-decoration', attrs)
    .ap(css('vertical-align', attrs)
    .map(style))))))
    .some());

I'm happy with this but I can't help thinking that all these nested ap are some sort of callbacks hell in disguise. Perhaps there's a better way which I am not aware of?

Question: is there a better way to combine multiple Maybe monads?

Body:
You are really overcomplicating things:

  const keys = ['font-style', 'font-variant', 'font-weight', 'text-decoration', 'vertical-align'];

  const css = attrs => keys
     .map(it => attrs[it] && `${it}: ${attrs[it]}`)
     .filter(it => it)
     .join(", ");

 const style = (attrs, input) =>
   css(attrs) ? `<span style="${css(attrs)}">${input}</span>` : input;


问:
conditional formatting for a full column based on the average value in that row?
I'm going through a sheet with multiple different data points across different rows (for different versions of the same action each on their own row).

In order to easily compare from one row to the next, I would like to use conditional formatting to on a simple level as follows: - highlight cell green if a value in that cell is equal to or greater than average for that column - highlight cell red if a value is less than average for that column

So for example, I need all cells in column F to be green if the value in each cell is equal to or greater than the average of all values in that column or red if it's less than the average of all values in that column.

But I'm struggling to get that working.

Does anyone have any ideas?

I tried in 2 ways, trying to get a custom formula that calculates this average and merely doing greater than or less than in reference to a specific cell in another column (I have a separate column where I only have the average of each column calculated as follows: =Average(E3:E18) but neither is working consistently, it's highlighting some cells green that should be red and vice versa.

答:
Maybe what you want is this CF formula rule:

```<code>=D2<average(D:D)
</code>```

applied to the whole of D2:Rx (where x is last row) for red, and a corresponding rule with < replaced by >= for green (or simply format all range with 'standard' fill of green).

Body:
Maybe what you want is this CF formula rule:

=D2<average(D:D)

applied to the whole of D2:Rx (where x is last row) for red, and a corresponding rule with < replaced by >= for green (or simply format all range with 'standard' fill of green).


问:
problems to get correct reuseIdentifier
I've created an extension for UITableView and want to get the correct reuseIdentifier at runtime, but I can't:

```<code>extension UITableView {

func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {

    let s = T.reuseIdentifier
</code>```

The variable "s" always contains "UITableViewCell" and not the name which I did specify within the storyboard.

答:
Never mind, the whole method

```<code>extension UITableView {

    func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {
        return self.dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as! T
    }
}
</code>```

is supposed to work correctly.

An alternative is a protocol extension and static methods, just adopt the protocol in the UITableViewCell subclasses.

```<code>protocol Reusable {
    associatedtype CellType : UITableViewCell = Self

    static var cellIdentifier : String { get }
    static func dequeueReusableCell(in tableView : UITableView, for indexPath: IndexPath) -> CellType
}

extension Reusable where Self : UITableViewCell {

    static var cellIdentifier : String {
        return String(describing: Self.self)
    }

    static func dequeueReusableCell(in tableView : UITableView, for indexPath: IndexPath) -> CellType {
        return tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CellType
    }
}
</code>```

And call it

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = MyTableViewCell.dequeueReusableCell(in: tableView, for: indexPath)
...
</code>```

Title: problems to get correct reuseIdentifier

Body:
I've created an extension for UITableView and want to get the correct reuseIdentifier at runtime, but I can't:

extension UITableView {

func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {

    let s = T.reuseIdentifier

The variable "s" always contains "UITableViewCell" and not the name which I did specify within the storyboard.

Body:
Never mind, the whole method

extension UITableView {

    func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {
        return self.dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as! T
    }
}

is supposed to work correctly.

An alternative is a protocol extension and static methods, just adopt the protocol in the UITableViewCell subclasses.

protocol Reusable {
    associatedtype CellType : UITableViewCell = Self

    static var cellIdentifier : String { get }
    static func dequeueReusableCell(in tableView : UITableView, for indexPath: IndexPath) -> CellType
}

extension Reusable where Self : UITableViewCell {

    static var cellIdentifier : String {
        return String(describing: Self.self)
    }

    static func dequeueReusableCell(in tableView : UITableView, for indexPath: IndexPath) -> CellType {
        return tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CellType
    }
}

And call it

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = MyTableViewCell.dequeueReusableCell(in: tableView, for: indexPath)
...


问:
Reducing number of Line Breaks/chr(10) in a Cell
I have an excel sheet that has cells with variable amounts of line breaks and I want to reduce it so that there is only one line break between each new line.

For example

```<code>HELLO

WORLD

GOODBYE
</code>```

will be modified to:

```<code>HELLO

WORLD

GOODBYE
</code>```

I've been banging my head over this for hours and have come up with a few ways but none are very efficient or produce the best results.

This is made especially difficult because I'm working with a dataset that has spaces preceeding the Line Breaks.

And so a regular parse doesn't work as well.

I've tried to replace all the instances of chr(10) in the cell with ~ to make it easier to work with, however i'm still not getting it to an exact amount. I'm wondering if there are better ways.

here is what I have so far:

```<code> myString = Replace(myString, Chr(10), "~")

    Do While InStr(myString, "~~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "~~", "~")
        Next k
    Loop

    Do While InStr(myString, "   ~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "  ~", "")
        Next k
    Loop

myString = Replace(myString, "   ~", " ~")
myString = Replace(myString, " ~", "~")
myString = Replace(myString, "~", Chr(10))

Cells(2, 2).Value = myString
</code>```

So i'm using a few do while loops to catch instances of different types of line breaks (or in this case, tildes) but I don't think this is the best way to tackle this.

I was thinking of ways to loop through the characters in the cell, and if there is an instance where there is more than one chr(10), replace it with "".

So the psuedocode would look like:

```<code>for i to len(mystring)
    if mystring(i) = chr(10) AND myString(i+1) = chr(10) Then
       myString(i + 1) = ""
</code>```

but unfortunately I don't think this is possible through vba.

If anyone is kind enough to help me adjust my current code or assist me with the aforementioned psuedocode, it would be greatly appreciated!

答:
This has already been answered fairly well, but not meeting one of the requirements yet (have 1 line between each new line), so here is my take on answering this. Please see the comments through the code for more details:

Option Explicit

Sub reduceNewLines()

Dim ws As Worksheet: Set ws = ActiveWorkbook.Sheets("Sheet1")
Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Dim lCol As Long: lCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
Dim arrData As Variant: arrData = ws.Range(ws.Cells(1, 1), ws.Cells(lRow, lCol))
Dim arrVal() As String
Dim R As Long, C As Long, X As Long

For R = LBound(arrData) To UBound(arrData) 'Iterate through each row of data
    For C = LBound(arrData, 2) To UBound(arrData, 2) 'iterate through each column of data (though might be just 1)

        arrVal = Split(arrData(R, C), Chr(10)) 'allocate each row to an array, split at new line

        arrData(R, C) = "" 'reset the data inside this field

        For X = LBound(arrVal) To UBound(arrVal)
            arrVal(X) = Trim(arrVal(X)) 'clear leading/trailing spaces
            If Left(arrVal(X), 1) <> " " And arrVal(X) <> "" Then
                arrData(R, C) = arrData(R, C) & arrVal(X) & Chr(10) & Chr(10) 'allocate new data + 2 lines
            End If
        Next X

        arrData(R, C) = Left(arrData(R, C), Len(arrData(R, C)) - 2) 'remove the last 2 extra new lines
    Next C
Next R

ws.Range(ws.Cells(1, 1), ws.Cells(lRow, lCol)) = arrData 'allocate the data back to the sheet

End Sub
```

Happy to assist further if needed.

Body:
I have an excel sheet that has cells with variable amounts of line breaks and I want to reduce it so that there is only one line break between each new line.

For example

HELLO

WORLD

GOODBYE

will be modified to:

HELLO

WORLD

GOODBYE

I've been banging my head over this for hours and have come up with a few ways but none are very efficient or produce the best results.

This is made especially difficult because I'm working with a dataset that has spaces preceeding the Line Breaks.

And so a regular parse doesn't work as well.

I've tried to replace all the instances of chr(10) in the cell with ~ to make it easier to work with, however i'm still not getting it to an exact amount. I'm wondering if there are better ways.

here is what I have so far:

 myString = Replace(myString, Chr(10), "~")

    Do While InStr(myString, "~~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "~~", "~")
        Next k
    Loop

    Do While InStr(myString, "   ~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "  ~", "")
        Next k
    Loop

myString = Replace(myString, "   ~", " ~")
myString = Replace(myString, " ~", "~")
myString = Replace(myString, "~", Chr(10))

Cells(2, 2).Value = myString

So i'm using a few do while loops to catch instances of different types of line breaks (or in this case, tildes) but I don't think this is the best way to tackle this.

I was thinking of ways to loop through the characters in the cell, and if there is an instance where there is more than one chr(10), replace it with "".

So the psuedocode would look like:

for i to len(mystring)
    if mystring(i) = chr(10) AND myString(i+1) = chr(10) Then
       myString(i + 1) = ""

but unfortunately I don't think this is possible through vba.

If anyone is kind enough to help me adjust my current code or assist me with the aforementioned psuedocode, it would be greatly appreciated!

Body:
This has already been answered fairly well, but not meeting one of the requirements yet (have 1 line between each new line), so here is my take on answering this. Please see the comments through the code for more details:

Option Explicit

Sub reduceNewLines()

Dim ws As Worksheet: Set ws = ActiveWorkbook.Sheets("Sheet1")
Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Dim lCol As Long: lCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
Dim arrData As Variant: arrData = ws.Range(ws.Cells(1, 1), ws.Cells(lRow, lCol))
Dim arrVal() As String
Dim R As Long, C As Long, X As Long

For R = LBound(arrData) To UBound(arrData) 'Iterate through each row of data
    For C = LBound(arrData, 2) To UBound(arrData, 2) 'iterate through each column of data (though might be just 1)

        arrVal = Split(arrData(R, C), Chr(10)) 'allocate each row to an array, split at new line

        arrData(R, C) = "" 'reset the data inside this field

        For X = LBound(arrVal) To UBound(arrVal)
            arrVal(X) = Trim(arrVal(X)) 'clear leading/trailing spaces
            If Left(arrVal(X), 1) <> " " And arrVal(X) <> "" Then
                arrData(R, C) = arrData(R, C) & arrVal(X) & Chr(10) & Chr(10) 'allocate new data + 2 lines
            End If
        Next X

        arrData(R, C) = Left(arrData(R, C), Len(arrData(R, C)) - 2) 'remove the last 2 extra new lines
    Next C
Next R

ws.Range(ws.Cells(1, 1), ws.Cells(lRow, lCol)) = arrData 'allocate the data back to the sheet

End Sub

Happy to assist further if needed.


问:
Printing message in specific place on screen with DOS int 21h in graphic mode
I want to print out strings in assembly, I've managed to print out a string but I can't figure out how to print it in a specific place on the screen

This is the code I'm using:

```<code>IDEAL
MODEL small
STACK 100h
DATASEG

message db 'Hello World',10,13,'$'

CODESEG
start:
    mov ax, @data
    mov ds, ax

       ;graphic mode:;
    mov ax, 13h
    int 10h

    pop ds
    mov dx, offset message
    mov ah, 9h
    int 21h

exit:
    mov ax, 4c00h
    int 21h
END start
</code>```

The graphic mode is because this is part of a bigger project I'm working on but to my understanding it shouldn't be a problem.

This program does print out the message it just prints it out on the upper right corner of my screen.
I would very much like to know how to print the message in a specific place and also determine its size if possible.

答:
You just have to position the cursor where you need the string to appear.

The screen 13h has 40 columns and 25 rows.

Use BIOS function 02h:

```<code>mov dl, 20    ;Center column
mov dh, 12    ;Center row
mov bh, 0     ;Display page 0
mov ah, 02h   ;SetCursor
int 10h
mov dx, offset message
mov ah, 09h   ;DispayString
int 21h
</code>```

```<code>pop ds
</code>```

What's this doing in your code?

...also determine its size if possible.

Write the following:

```<code>message db 'Hello World',10,13,'$'
size    equ ($-1)-message
</code>```

$ is the position where the current line (code) starts.

Here size will get 13 bytes.

Then use it like:

```<code>mov cx, size
</code>```

Body:
I want to print out strings in assembly, I've managed to print out a string but I can't figure out how to print it in a specific place on the screen

This is the code I'm using:

IDEAL
MODEL small
STACK 100h
DATASEG

message db 'Hello World',10,13,'$'

CODESEG
start:
    mov ax, @data
    mov ds, ax

       ;graphic mode:;
    mov ax, 13h
    int 10h

    pop ds
    mov dx, offset message
    mov ah, 9h
    int 21h

exit:
    mov ax, 4c00h
    int 21h
END start

The graphic mode is because this is part of a bigger project I'm working on but to my understanding it shouldn't be a problem.

This program does print out the message it just prints it out on the upper right corner of my screen.
I would very much like to know how to print the message in a specific place and also determine its size if possible.

Body:
You just have to position the cursor where you need the string to appear.

The screen 13h has 40 columns and 25 rows.

Use BIOS function 02h:

mov dl, 20    ;Center column
mov dh, 12    ;Center row
mov bh, 0     ;Display page 0
mov ah, 02h   ;SetCursor
int 10h
mov dx, offset message
mov ah, 09h   ;DispayString
int 21h

pop ds

What's this doing in your code?

...also determine its size if possible.

Write the following:

message db 'Hello World',10,13,'$'
size    equ ($-1)-message

$ is the position where the current line (code) starts.

Here size will get 13 bytes.

Then use it like:

mov cx, size


问:
Flutter apk/ipa size vs React Native apk/ipa size
React Native APK size for a hello world example is around 20M (in recent versions) because of support different hardware architectures (ARMv7, ARMv8, X86, etc) while Flutter APK size for same application is around 7M.

What's the reason for the difference in size? Do Flutter support all hardware architecture?

答: RN use open source JavaScriptCore, which is the default engine for Safari. RN iOS and Android apps don't have the same size. For iOS RN uses the JavaScriptCore provided by the iOS platform, and for Android RN bundles JavaScriptCore with the app, which increases the size of the app. The reason why Flutter and RN Hello World differ in size is because of JavaScriptCore.


问:
State stays the same when using event listeners
https://codesandbox.io/s/state-shenanigans-mifyg

This code example is a bit un-orthodox, but it still puzzles me so I decided to form it into a question.

Please open the link above and play with the example. Keep the console open as well.

When the form changes I'm calling console.log, passing it the state. As you can see when changing the question it logs the right value (the new question with the existing answer).

But if you then change the answer you find that the old question is logged out with the new answer.

I guess it has something to do with closures, but I couldn't figure it out.

```<code>import * as React from "react";
import { render } from "react-dom";

import "./styles.css";

function Faq({ onChange, data }) {
  const questionRef = React.createRef<HTMLInputElement>();
  const answerRef = React.createRef<HTMLInputElement>();

  React.useEffect(() => {
    if (questionRef.current) {
      questionRef.current.addEventListener("keydown", (e: any) => {
        onChange({ ...data, question: e.target.value });
      });
    }

    if (answerRef.current) {
      answerRef.current.addEventListener("keydown", (e: any) => {
        onChange({ ...data, answer: e.target.value });
      });
    }
  }, []);

  return (
    <div>
      <input ref={questionRef} type="text" defaultValue={data.question} />
      <input ref={answerRef} type="text" defaultValue={data.answer} />
    </div>
  );
}

const App = () => {
  const [faq, setFaq] = React.useState({
    id: "1",
    question: "I am a question?",
    answer: "I am the answer!"
  });
  React.useEffect(() => {
    console.log(faq);
  }, [faq]);
  return <Faq data={faq} onChange={setFaq} />;
};

const rootElement = document.getElementById("root");
render(<App />, rootElement);
</code>```

答:
You will need to refresh the data:

```<code>import * as React from "react";
import { render } from "react-dom";

import "./styles.css";

function Faq({ onChange, data }) {
  const questionRef = React.createRef<HTMLInputElement>();
  const answerRef = React.createRef<HTMLInputElement>();

  React.useEffect(() => {
    if (questionRef.current) {
      questionRef.current.addEventListener("keydown", (e: any) => {
        onChange({ ...data, question: e.target.value });
        data.question = e.target.value;
      });
    }

    if (answerRef.current) {
      answerRef.current.addEventListener("keydown", (e: any) => {
        onChange({ ...data, answer: e.target.value });
        data.answer = e.target.value;
      });
    }
  }, []);

  return (
    <div>
      <input ref={questionRef} type="text" defaultValue={data.question} />
      <input ref={answerRef} type="text" defaultValue={data.answer} />
    </div>
  );
}

const App = () => {
  const [faq, setFaq] = React.useState({
    id: "1",
    question: "I am a question?",
    answer: "I am the answer!"
  });
  React.useEffect(() => {
    console.log(faq);
  }, [faq]);
  return <Faq data={faq} onChange={setFaq} />;
};

const rootElement = document.getElementById("root");
render(<App />, rootElement);
</code>```

https://codesandbox.io/s/state-shenanigans-kupjj

Body:
https://codesandbox.io/s/state-shenanigans-mifyg

This code example is a bit un-orthodox, but it still puzzles me so I decided to form it into a question.

Please open the link above and play with the example. Keep the console open as well.

When the form changes I'm calling console.log, passing it the state. As you can see when changing the question it logs the right value (the new question with the existing answer).

But if you then change the answer you find that the old question is logged out with the new answer.

I guess it has something to do with closures, but I couldn't figure it out.

import * as React from "react";
import { render } from "react-dom";

import "./styles.css";

function Faq({ onChange, data }) {
  const questionRef = React.createRef<HTMLInputElement>();
  const answerRef = React.createRef<HTMLInputElement>();

  React.useEffect(() => {
    if (questionRef.current) {
      questionRef.current.addEventListener("keydown", (e: any) => {
        onChange({ ...data, question: e.target.value });
      });
    }

    if (answerRef.current) {
      answerRef.current.addEventListener("keydown", (e: any) => {
        onChange({ ...data, answer: e.target.value });
      });
    }
  }, []);

  return (

      <input ref={questionRef} type="text" defaultValue={data.question} />
      <input ref={answerRef} type="text" defaultValue={data.answer} />

  );
}

const App = () => {
  const [faq, setFaq] = React.useState({
    id: "1",
    question: "I am a question?",
    answer: "I am the answer!"
  });
  React.useEffect(() => {
    console.log(faq);
  }, [faq]);
  return <Faq data={faq} onChange={setFaq} />;
};

const rootElement = document.getElementById("root");
render(<App />, rootElement);

Body:
You will need to refresh the data:

import * as React from "react";
import { render } from "react-dom";

import "./styles.css";

function Faq({ onChange, data }) {
  const questionRef = React.createRef<HTMLInputElement>();
  const answerRef = React.createRef<HTMLInputElement>();

  React.useEffect(() => {
    if (questionRef.current) {
      questionRef.current.addEventListener("keydown", (e: any) => {
        onChange({ ...data, question: e.target.value });
        data.question = e.target.value;
      });
    }

    if (answerRef.current) {
      answerRef.current.addEventListener("keydown", (e: any) => {
        onChange({ ...data, answer: e.target.value });
        data.answer = e.target.value;
      });
    }
  }, []);

  return (
    <div>
      <input ref={questionRef} type="text" defaultValue={data.question} />
      <input ref={answerRef} type="text" defaultValue={data.answer} />
    </div>
  );
}

const App = () => {
  const [faq, setFaq] = React.useState({
    id: "1",
    question: "I am a question?",
    answer: "I am the answer!"
  });
  React.useEffect(() => {
    console.log(faq);
  }, [faq]);
  return <Faq data={faq} onChange={setFaq} />;
};

const rootElement = document.getElementById("root");
render(<App />, rootElement);

https://codesandbox.io/s/state-shenanigans-kupjj


问:
API call working with `curl` does not work in Swift
I am getting a json file back from a http request:

```<code>[
  {
    "_ref": "Ref0",
    "name": "someName0"
  },
  {
    "_ref": "Ref1",
    "name": "someName1"
  },
  {
    "_ref": "Ref2",
    "name": "someName2"
  }
]
</code>```

Here's my swift code so far:

guard let natRules = try? JSONSerialization.jsonObject(
  with: data, options: []) as? [Any]
  else { return }
```

<p>How can I get the array's item's content as a <code>[String:String]</code> dictionary? When I print <code>natRules</code>, the result looks like this:</p>

```[
  {
    "_ref" = "Ref0";
    "name" = "someName0"
  },
  {
    "_ref" = "Ref1";
    "name" = "someName1"
  },
  {
    "_ref" = "Ref2";
    "name" = "someName2"
  }
]
```

I would expect the entries to look like "_ref": "Ref0" ... though...
What am I missing here?

Edit (and message to future me):

Seems as though with the above sample I gave, I didn't account for non-string values (which are present in the code I am trying to handle) -- so basically, if there are non-string values present, a cast to [[String:Any]] is necessary.
So that's my TIL I guess...

答:
You need to cast from [Any] to [[String: String]]

```<code>var result = [[String: String]]()
do {
   if let natRules = try JSONSerialization.jsonObject(
    with: data, options: []) as? [[String: String]] {
    result = natRules
    }
} catch {
    print(error)
}
</code>```

Body:
I am getting a json file back from a http request:

[
  {
    "_ref": "Ref0",
    "name": "someName0"
  },
  {
    "_ref": "Ref1",
    "name": "someName1"
  },
  {
    "_ref": "Ref2",
    "name": "someName2"
  }
]

Here's my swift code so far:

guard let natRules = try? JSONSerialization.jsonObject(
  with: data, options: []) as? [Any]
  else { return }

How can I get the array's item's content as a [String:String] dictionary? When I print natRules, the result looks like this:

[
  {
    "_ref" = "Ref0";
    "name" = "someName0"
  },
  {
    "_ref" = "Ref1";
    "name" = "someName1"
  },
  {
    "_ref" = "Ref2";
    "name" = "someName2"
  }
]

I would expect the entries to look like "_ref": "Ref0" ... though...
What am I missing here?

Edit (and message to future me):

Seems as though with the above sample I gave, I didn't account for non-string values (which are present in the code I am trying to handle) -- so basically, if there are non-string values present, a cast to [[String:Any]] is necessary.
So that's my TIL I guess...

Body:
You need to cast from [Any] to [[String: String]]

var result = [[String: String]]()
do {
   if let natRules = try JSONSerialization.jsonObject(
    with: data, options: []) as? [[String: String]] {
    result = natRules
    }
} catch {
    print(error)
}


问:
How to destructure defaults from a string
I'm wondering how I can destructure default values from a string. For instance, take the following code:

function f({length, valueOf}) {
  console.log("The length is:", length);
  console.log("The string is:", valueOf()); // Expected: "The string is: foo"
}

f("foo");```
</div>
</div>
</p>

<p>Above, I am trying to get the <code>length</code> of the passed in string, as well as the string itself (ie: by calling <code>valueOf</code>), however, I get an error:</p>

<blockquote>
  <p>Uncaught TypeError: String.prototype.valueOf requires that 'this' be a
  String</p>
</blockquote>

<p>I was thinking that this was because I can't destructure methods from objects but my testing tells me otherwise:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const obj = {
  id: 1,
  foo: function() {
    return "bar";
  }
}

const {id, foo} = obj;
console.log(id, foo());</code>```

So, I would like to know two things:

How can I get the original string passed into my function f while destructuing its arguments (is it even possible?)

Why do I get an error with my first bit of code, but not the other?

答:
It's not possible. Once you've destructured a method from an object, you're left with only a reference to the base function, but not the original object (or, in this case, the original string) - without a this to extract a value from, the valueOf method will not be callable.

For similar reasons, if your foo tried to extract a value from the obj, it wouldn't work:

const obj = {
  id: 1,
  foo: function() {
    return this.id;
  }
}

const { foo } = obj;
// at this point, without referencing `foo` again, it's impossible to get the `id` of 1
console.log(foo());```
</div>
</div>
</p>

<p>Your original <code>foo</code> works because it does not depend on any calling context - it may as well be just a standalone function.</p>

<p>Note that if you passed an <em>object</em> with the string as a property, it would be possible, though you'd have to put the string into a standalone variable, so you may consider it to be cheating:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function f({str: { length, valueOf}, str}) {
  console.log("The length is:", length);
  console.log("The string is:", valueOf.call(str)); // Expected: "The string is: foo"
}

f({ str: "foo" });</code>```

Body:
I'm wondering how I can destructure default values from a string. For instance, take the following code:

function f({length, valueOf}) {
  console.log("The length is:", length);
  console.log("The string is:", valueOf()); // Expected: "The string is: foo"
}

f("foo");

Above, I am trying to get the length of the passed in string, as well as the string itself (ie: by calling valueOf), however, I get an error:

Uncaught TypeError: String.prototype.valueOf requires that 'this' be a
  String

I was thinking that this was because I can't destructure methods from objects but my testing tells me otherwise:

const obj = {
  id: 1,
  foo: function() {
    return "bar";
  }
}

const {id, foo} = obj;
console.log(id, foo());

So, I would like to know two things:

How can I get the original string passed into my function f while destructuing its arguments (is it even possible?)

Why do I get an error with my first bit of code, but not the other?

Body:
It's not possible. Once you've destructured a method from an object, you're left with only a reference to the base function, but not the original object (or, in this case, the original string) - without a this to extract a value from, the valueOf method will not be callable.

For similar reasons, if your foo tried to extract a value from the obj, it wouldn't work:

const obj = {
  id: 1,
  foo: function() {
    return this.id;
  }
}

const { foo } = obj;
// at this point, without referencing `foo` again, it's impossible to get the `id` of 1
console.log(foo());

Your original foo works because it does not depend on any calling context - it may as well be just a standalone function.

Note that if you passed an object with the string as a property, it would be possible, though you'd have to put the string into a standalone variable, so you may consider it to be cheating:

function f({str: { length, valueOf}, str}) {
  console.log("The length is:", length);
  console.log("The string is:", valueOf.call(str)); // Expected: "The string is: foo"
}

f({ str: "foo" });