问:
SwiftUI Firestore fetch user data after log in
After a successful log in from Firestore I want to call my /users table to fetch additional data for this user. Like rating, savedItems and other stuff like that.

What I have done is that I have created an UserEnvironmentObject which as the name says it's an EnvironmentObject. I'm storing here the User which I get back from Firestore and also a ClientViewModel

ClientViewModel is used also for ex: when a user request the profile of another user, thats why I went with this approach, to reuse my existing ClientViewModel. However the issue is that I do not feel it's ok to have an ObservableObject inside an EnvironmentObject. Is there A better way to achieve this ?

```<code>class UserEnvironmentObject: ObservableObject {
    @Published var user: User?
    @Published var clientViewModel: ClientViewModel?
    var handle: AuthStateDidChangeListenerHandle?

    func listen() {
        handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
            self.user = user

            self.firestoreService.fetchDocument(documentReference: documentReference) { (result: Result<Client, Error>) in
                switch result {
                case .success(let client):
                    let clientViewModel = ClientViewModel(client: client)
                    self.savedItems = client.savedItems
                    self.rating = clientViewModel.rating
                case .failure(let error):
                    print(error.localizedDescription)
                }
            }
        })
    }
}

class ClientViewModel: ObservableObject {
    @Published var client: Client?
    var firestoreService: FirestoreService = FirestoreService()

    init(client: Client?) {
        self.client = client
    }

    var rating: String {
        guard let ratings = client?.ratings else { return "5.0" }
        return Double(ratings.reduce(0, +) / ratings.count).roundToDecimal(1).description
    }

    func loadClient(documentReference: DocumentReference?) {
        if let documentReference = documentReference {
            firestoreService.fetchDocument(documentReference: documentReference) { (result: Result<Client, Error>) in
                switch result {
                case .success(let client):
                    self.client = client
                case .failure(let error):
                    print(error.localizedDescription)
                }
            }
        }
    }
}
</code>```

答:
What are your concerns about having an ObservableObject in environmentObject? Implementing a Redux like pattern requires the same approach, and I have been doing that on my projects. https://tech.mercari.com/entry/2019/12/11/150000

One small gotcha for this situation, all swiftUI views are supposed to have access to environment objects, however, currently Sheet views do not. to fix this you pass the environment object explicitly like this:

```<code>@EnvironmentObject var store: AppStore

.sheet(isPresented: $someBoolean, content: { SomeView().environmentObject(self.store)})
</code>```

Body:
After a successful log in from Firestore I want to call my /users table to fetch additional data for this user. Like rating, savedItems and other stuff like that.

What I have done is that I have created an UserEnvironmentObject which as the name says it's an EnvironmentObject. I'm storing here the User which I get back from Firestore and also a ClientViewModel

ClientViewModel is used also for ex: when a user request the profile of another user, thats why I went with this approach, to reuse my existing ClientViewModel. However the issue is that I do not feel it's ok to have an ObservableObject inside an EnvironmentObject. Is there A better way to achieve this ?

class UserEnvironmentObject: ObservableObject {
    @Published var user: User?
    @Published var clientViewModel: ClientViewModel?
    var handle: AuthStateDidChangeListenerHandle?

    func listen() {
        handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
            self.user = user

            self.firestoreService.fetchDocument(documentReference: documentReference) { (result: Result<Client, Error>) in
                switch result {
                case .success(let client):
                    let clientViewModel = ClientViewModel(client: client)
                    self.savedItems = client.savedItems
                    self.rating = clientViewModel.rating
                case .failure(let error):
                    print(error.localizedDescription)
                }
            }
        })
    }
}

class ClientViewModel: ObservableObject {
    @Published var client: Client?
    var firestoreService: FirestoreService = FirestoreService()

    init(client: Client?) {
        self.client = client
    }

    var rating: String {
        guard let ratings = client?.ratings else { return "5.0" }
        return Double(ratings.reduce(0, +) / ratings.count).roundToDecimal(1).description
    }

    func loadClient(documentReference: DocumentReference?) {
        if let documentReference = documentReference {
            firestoreService.fetchDocument(documentReference: documentReference) { (result: Result<Client, Error>) in
                switch result {
                case .success(let client):
                    self.client = client
                case .failure(let error):
                    print(error.localizedDescription)
                }
            }
        }
    }
}

Body:
What are your concerns about having an ObservableObject in environmentObject? Implementing a Redux like pattern requires the same approach, and I have been doing that on my projects. https://tech.mercari.com/entry/2019/12/11/150000

One small gotcha for this situation, all swiftUI views are supposed to have access to environment objects, however, currently Sheet views do not. to fix this you pass the environment object explicitly like this:

@EnvironmentObject var store: AppStore

.sheet(isPresented: $someBoolean, content: { SomeView().environmentObject(self.store)})


来源: stackexchange

问:
[Vue warn]: Error in render: "TypeError: Cannot read property 'NomeStr' of undefined"
I'm trying to show 'NameSrt' item array value in my template, but I'm getting the issue:
vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'NomeStr' of undefined"

NomeStr is inside to an object named: ImagemPrincipal.
Here is my code:

Bebidas

Frutas

Limpeza

Congelados

 0)">

{{produto.Estoques.Produto.NomeStr}}

R${{produto.PrecoDoub}}

R$ 12,50

2

```

<pre class="lang-js prettyprint-override"><code>import axios from 'axios';

export default {
    components: {
        Cart
    },
    data () {
    return {
            info: '',
            produtos: [],
            produto: '',
            NomeStr: '',
            IdImagem: '',
            image: ''
        }
    },

    async mounted () {
      const usuario =  { UsuarioStr: "admin", SenhaStr: "abc123" };
      const url = "https://localhost:3001/api/";

    const responseLogin = await axios.post(url + 'usuarioapimobile/login', usuario);
    if(responseLogin) {
        const { data } = responseLogin.data;
        const sendData = {
          IdEntrega: 0,
          IdTipoProduto: 0,
          IdVitrine: null,
          ListaIdCategoria: [],
          ListaIdEncarte: [],
          ImagemPrincipal: [],
          NomeProdutoPesquisaStr: '',
          IdPromocao:'',
          IdProduto: 0,
          NomeStr: '',
          IdImagem: 0,
          OrdemSecao: 0
        };
        const responseData = await axios.post(url + "PromocoesGeraisMobile?idLoja=10719&pagina=0&quantidadePorPagina=150",
         sendData, {
          headers: {'Authorization': `Bearer ${data.TokenStr}`
          }})
          .then(response => {
            this.produtos =(response.data.data.promocoesGerais)
            return { response }
          })
          .catch((err) => {
              console.error(err)
          })
        console.log(this.produtos)
        console.log('INFO', responseData)

    }
},
</code>```

Could you please help me to fix this issue

答:
I think the problem is here...

  ...

  ...

```

<p>Given that you're using <code>v-for="produto of produtos"</code> I think you are using <code>produtos.ImagemPrincipal.NomeStr</code> instead of <code>produto.ImagemPrincipal.NomeStr</code></p>

<p><em>To be clear, the error states that <code>produtos.ImagemPrincipal</code> is undefined</em></p>

<p>It's hard to tell the exact cause/fix without seeing the data. Most likely it is due to the structure not matching.</p>

<p>To troubleshoot I would usually do something like...<code>```{{JSON.stringify(mytroublevar,null,2)}}```</code></p>

```

 0)">
        ```{{JSON.stringify(produto,null,2)}}```

{{produto.Estoques.Produto.NomeStr}}

R${{produto.PrecoDoub}}

R$ 12,50

2

```

<p>this will show the <code>produto</code> object content, and then you can examine what went wrong. </p>

<p>another guess, maybe you want </p>

<pre class="lang-html prettyprint-override"><code><img class="miniatura" name="imagem" src="NomeStr"/>
</code>```

¯\_(ツ)_/¯

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to show 'NameSrt' item array value in my template, but I'm getting the issue:
vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'NomeStr' of undefined"

NomeStr is inside to an object named: ImagemPrincipal.
Here is my code:

Bebidas

Frutas

Limpeza

Congelados

 0)">

{{produto.Estoques.Produto.NomeStr}}

R${{produto.PrecoDoub}}

R$ 12,50

2

import axios from 'axios';

export default {
    components: {
        Cart
    },
    data () {
    return {
            info: '',
            produtos: [],
            produto: '',
            NomeStr: '',
            IdImagem: '',
            image: ''
        }
    },

    async mounted () {
      const usuario =  { UsuarioStr: "admin", SenhaStr: "abc123" };
      const url = "https://localhost:3001/api/";

    const responseLogin = await axios.post(url + 'usuarioapimobile/login', usuario);
    if(responseLogin) {
        const { data } = responseLogin.data;
        const sendData = {
          IdEntrega: 0,
          IdTipoProduto: 0,
          IdVitrine: null,
          ListaIdCategoria: [],
          ListaIdEncarte: [],
          ImagemPrincipal: [],
          NomeProdutoPesquisaStr: '',
          IdPromocao:'',
          IdProduto: 0,
          NomeStr: '',
          IdImagem: 0,
          OrdemSecao: 0
        };
        const responseData = await axios.post(url + "PromocoesGeraisMobile?idLoja=10719&pagina=0&quantidadePorPagina=150",
         sendData, {
          headers: {'Authorization': `Bearer ${data.TokenStr}`
          }})
          .then(response => {
            this.produtos =(response.data.data.promocoesGerais)
            return { response }
          })
          .catch((err) => {
              console.error(err)
          })
        console.log(this.produtos)
        console.log('INFO', responseData)

    }
},

Could you please help me to fix this issue

Body:
I think the problem is here...

<tr v-for="produto of produtos" :key="produto.IdProduto">
  ...
  <img class="miniatura" name="imagem" :src="produtos.ImagemPrincipal.NomeStr"/>
  ...
</tr>

Given that you're using v-for="produto of produtos" I think you are using produtos.ImagemPrincipal.NomeStr instead of produto.ImagemPrincipal.NomeStr

To be clear, the error states that produtos.ImagemPrincipal is undefined

It's hard to tell the exact cause/fix without seeing the data. Most likely it is due to the structure not matching.

To troubleshoot I would usually do something like...<pre>{{JSON.stringify(mytroublevar,null,2)}}</pre>

<tr v-for="produto of produtos" :key="produto.IdProduto">
    <td>
    <div v-if="(produto.lenght > 0)">
        <pre>{{JSON.stringify(produto,null,2)}}</pre>
        <img class="miniatura" name="imagem" __src="produtos.ImagemPrincipal.NomeStr"/>
    </div>
        <div class="text-box">
            <p class="title">{{produto.Estoques.Produto.NomeStr}}</p>
            <p class="price">R${{produto.PrecoDoub}}</p>
            <p class="promotional">R$ 12,50</p>
        </div>
        <div class="icons-box">
            <div class="btn-favorite"></div>
            <div class="btn-add"><div class="qtd"><p>2</p></div></div>
        </div>
    </td>
</tr>

this will show the produto object content, and then you can examine what went wrong.

another guess, maybe you want

<img class="miniatura" name="imagem" src="NomeStr"/>

¯\_(ツ)_/¯


问:
Unable to upload an DataFrame containing mixed-typed data with DolphinDB Python API
I tried to upload a DataFrame with DolphinDB Python API. It contained a column with mixed types.

```<code>import dolphindb as ddb
import pandas as pd

sess = ddb.session('localhost', 8848)
df = DataFrame({'a': [1, 1.0, 'a']})
sess.upload({'df': df})
</code>```

Then I got the following error message:

Traceback (most recent call last):

File "", line 1, in

File "/home/ynwang/.local/lib/python3.6/site-packages/dolphindb/session.py", line 64, in upload

return self.cpp.upload(nameObjectDict)

RuntimeError:  in upload: Failed to read response header from the socket with IO error type 1

And the session just disconnected. I would like to know why this is the case.

答:
Most, if not all of the differences between orca and pandas are due to the differences between DolphinDB and pandas. Here for your case, DolphinDB does not allow mixed data types in a table column. Therefore orca doesn't allow mixed type columns. They explained in section 4.1 of the following tutorial:

https://github.com/dolphindb/Orca/tree/master/totorial_EN

I guess this because DolphinDB aims to be a high-performance database, whereas pandas aims to be able to do anything. They are just different animals.

Body:
I tried to upload a DataFrame with DolphinDB Python API. It contained a column with mixed types.

import dolphindb as ddb
import pandas as pd

sess = ddb.session('localhost', 8848)
df = DataFrame({'a': [1, 1.0, 'a']})
sess.upload({'df': df})

Then I got the following error message:

Traceback (most recent call last):

File "", line 1, in

File "/home/ynwang/.local/lib/python3.6/site-packages/dolphindb/session.py", line 64, in upload

return self.cpp.upload(nameObjectDict)

RuntimeError:  in upload: Failed to read response header from the socket with IO error type 1

And the session just disconnected. I would like to know why this is the case.


问:
Laravel group by date and count
I'm trying to add extra information to a Laravel eloquent collection based on the counting number of start(date) field. so the scenario is I have an "appointments" table, I want to add extra attributes to the object in the collection that's returned by eloquent if any days have more than 10 appointments. I have tried many ways like group by and count but didn't work. anyway I have the code below that's I think I'm so close to it but I have been working on it but couldn't find how to make it achieve what I want. I think I'm stuck and I can't think any more. I have commented most of the lines.</p>

```<code>        $allAppointments = Appointment::get($columns); //returning all the appointments

        $days = Appointment::get()->groupBy(function ($val) {
                return Carbon::parse($val->start)->format('d');
            }); //here I'm returning appointments by group without the count

        $counter = [];

        foreach ($days as $day => $appointments) {
            foreach ($appointments as $appointment) {

                if (Carbon::parse($appointment->start)->format('d') == $day) {
                    $counter = [Carbon::parse($appointment->start)->format('d') => $day]; //here I'm trying to make an array and count the days but not working
                }
                dd($counter);
                foreach ($allAppointments as $allAppointment) {
                    if (Carbon::parse($allAppointment->start)->format('d') == $day && count($counter) == 10) //here I want to compare the dates and check if that day have more than 10 appointments
                        $allAppointment->setAttribute('backgroundColor', 'red'); //here I want to add the extra information
                }
            }
        }
</code>```

答:
Try the following:

```<code>    Appointment::select(DB::raw('if(count(*) > 10, true, false) as more_than_ten_appointment'))->groupBy(function ($val) {
            return Carbon::parse($val->start)->format('d');
        })->get();
</code>```

if DB class isn't exist add after namespace:

```<code>use DB;
</code>```

Title: Laravel group by date and count

Body:
I'm trying to add extra information to a Laravel eloquent collection based on the counting number of start(date) field. so the scenario is I have an "appointments" table, I want to add extra attributes to the object in the collection that's returned by eloquent if any days have more than 10 appointments. I have tried many ways like group by and count but didn't work. anyway I have the code below that's I think I'm so close to it but I have been working on it but couldn't find how to make it achieve what I want. I think I'm stuck and I can't think any more. I have commented most of the lines.

        $allAppointments = Appointment::get($columns); //returning all the appointments

        $days = Appointment::get()->groupBy(function ($val) {
                return Carbon::parse($val->start)->format('d');
            }); //here I'm returning appointments by group without the count

        $counter = [];

        foreach ($days as $day => $appointments) {
            foreach ($appointments as $appointment) {

                if (Carbon::parse($appointment->start)->format('d') == $day) {
                    $counter = [Carbon::parse($appointment->start)->format('d') => $day]; //here I'm trying to make an array and count the days but not working
                }
                dd($counter);
                foreach ($allAppointments as $allAppointment) {
                    if (Carbon::parse($allAppointment->start)->format('d') == $day && count($counter) == 10) //here I want to compare the dates and check if that day have more than 10 appointments
                        $allAppointment->setAttribute('backgroundColor', 'red'); //here I want to add the extra information
                }
            }
        }

Body:
Try the following:

    Appointment::select(DB::raw('if(count(*) > 10, true, false) as more_than_ten_appointment'))->groupBy(function ($val) {
            return Carbon::parse($val->start)->format('d');
        })->get();

if DB class isn't exist add after namespace:

use DB;


问:
C# label gives an iteration
I just started learning C# couple of days ago. When came learn goto statement, I found the example like this.

```<code>        ineligible:
            Console.WriteLine("Not eligible for voting");

            Console.WriteLine("Enter your age");
            int age = int.Parse(Console.ReadLine());

            if (age < 18)
            {
                goto ineligible;
            }
            else
            {
                Console.WriteLine("Voting request accepted");
            }
</code>```

Then, I changed the code like this.

```<code>            int age = int.Parse(Console.ReadLine());

        ineligible:
            Console.WriteLine("Not eligible for voting");

            if (age < 18)
            {
                goto ineligible;
            }
            else
            {
                Console.WriteLine("Voting request accepted");
            }
</code>```

and I got an infinite iteration Not eligible for voting. Image of the iteration

Why an iteration happened instead of printing Not eligible only once ?

Reference: javatpoint - C#(goto statement)

答:
You are not supposed to use this anywhere in your life. After reading this change the code, try once, learn it and then forget it.

Why your first case worked?

Because you have Console.Readline() so it will wait for your response.

```<code>ineligible:
        Console.WriteLine("Not eligible for voting");

        Console.WriteLine("Enter your age");
        int age = int.Parse(Console.ReadLine());

        if (age < 18)
        {
            goto ineligible;
        }
</code>```

Why second case leads to infinite loop?

Because you have brought ineligible: just below to Console.ReadLine() statement.

```<code>int age = int.Parse(Console.ReadLine());

        ineligible:
            Console.WriteLine("Not eligible for voting");
</code>```

So the loop will be forever and it wont expect your input or disturbance.

Again learn it and forget it.

Title: C# label gives an iteration

Body:
I just started learning C# couple of days ago. When came learn goto statement, I found the example like this.

        ineligible:
            Console.WriteLine("Not eligible for voting");

            Console.WriteLine("Enter your age");
            int age = int.Parse(Console.ReadLine());

            if (age < 18)
            {
                goto ineligible;
            }
            else
            {
                Console.WriteLine("Voting request accepted");
            }

Then, I changed the code like this.

            int age = int.Parse(Console.ReadLine());

        ineligible:
            Console.WriteLine("Not eligible for voting");

            if (age < 18)
            {
                goto ineligible;
            }
            else
            {
                Console.WriteLine("Voting request accepted");
            }

and I got an infinite iteration Not eligible for voting. Image of the iteration

Why an iteration happened instead of printing Not eligible only once ?

Reference: javatpoint - C#(goto statement)

Body:
You are not supposed to use this anywhere in your life. After reading this change the code, try once, learn it and then forget it.

Why your first case worked?

Because you have Console.Readline() so it will wait for your response.

ineligible:
        Console.WriteLine("Not eligible for voting");

        Console.WriteLine("Enter your age");
        int age = int.Parse(Console.ReadLine());

        if (age < 18)
        {
            goto ineligible;
        }

Why second case leads to infinite loop?

Because you have brought ineligible: just below to Console.ReadLine() statement.

int age = int.Parse(Console.ReadLine());

        ineligible:
            Console.WriteLine("Not eligible for voting");

So the loop will be forever and it wont expect your input or disturbance.

Again learn it and forget it.


问:
Trigger multiple files from one PHP file
The requirement is to run multiple PHP files from one single PHP File without any timeouts, having searched stack overflow the only solution seems to be using EXEC however this is not allowed on my host.

If I run all.php from CLI then it should run 1.php , 2.php and 3.php.

Now normally this would be straight forward and I would just require or include them into all.php however the function names in 1.php , 2.php and 3.php match and I am looking for a solution which runs the file and then forgets about functions, variables or anything else within the file.

Essentially I want 1.php , 2.php , 3.php to run separately and All.php is only needs to trigger these files.

One possible solution in my mind was using curl in all.php to trigger them files, however this would introduce webserver limits and timeouts which I am not looking to deal with.

Thanks for the help guys.
Apologies if the question is not very clear.

答:
From a comment on the question:
Not looking for them to run at the same time. All the files can run one after another. I just need to avoid a fatal error due to the same function names withing the multiple files.

THREEE OPTIONS

Option 1, put the shared functions into a separate file:

```<code><?php

require shared_functions.php

require 1.php
require 2.php
require 3.php

?>
</code>```

Option 2, wrap function declarations inside a check to see whether the function has been declared already.  Requires placing wrapped function declarations before code that calls them:

1.php

```<code><?php

if (!function_exists('shared_function1')):
  function 1(){
      // yadda yadda
  }
endif;

// rest of 1.php
?>
</code>```

2.php

```<code><?php

if (!function_exists('shared_function1')):
  function 1(){
      // yadda yadda
}
endif;

// rest of 2.php
?>
</code>```

If the only problem you are encountering is bombs on function delcarations for functions that already have been declared by another script, make the function names unique (explained at end of this option), then run the scripts with this:

Option 3 - all.php

```<code><?php

$scripts_to_run=array();
$scripts_to_run[]=1.php;
$scripts_to_run[]=2.php;
$scripts_to_run[]=3.php;
.
.
.
$scripts_to_run[]=10.php;

foreach ($scripts_to_run as $script):
  require $script;
endforeach;
</code>```

*TO MAKE THE FUNCTION NAMES UNIQUE, in 1.php, for each sharedfunctionname, search/replace sharedfunctionname with functionname_1 In 2.php, for each sharedfunctionname, search/replace sharedfunctionname with functionname_2 ... etc.

examples:
CURRENT SCRIPTS

```<code>1.php
<?php

$var_dry   = 'dry';
$var_wet   = 'wet';
$result=sharedfunctionname($var_dry, $var_wet);

function sharedfunctionname($var_1, $var_2){
   // mix two strings to make one with the letters from both intermingled
}

2.php
<?php

$var_dog   = 'dog';
$var_cat   = 'cat';
$result=sharedfunctionname($var_dog, $var_cat);

function sharedfunctionname($var_1, $var_2){
   // something completely different from mixing two strings....
}
</code>```

AFTER MAKING FUNCTION NAMES UNIQUE

```<code>1.php

<?php

$var_dry   = 'dry';
$var_wet   = 'wet';
$result=functionname_1($var_dry, $var_wet);

function functionname_1($var_1, $var_2){
   // mix two strings to make one with the letters from both intermingled
}

2.php
<?php

$var_dog   = 'dog';
$var_cat   = 'cat';
$result=functionname_2($var_dog, $var_cat);

function functionname_2($var_1, $var_2){
   // something completely different from mixing two strings....

}
</code>```

Body:
From a comment on the question:
Not looking for them to run at the same time. All the files can run one after another. I just need to avoid a fatal error due to the same function names withing the multiple files.

THREEE OPTIONS

Option 1, put the shared functions into a separate file:

<?php

require shared_functions.php

require 1.php
require 2.php
require 3.php

?>

Option 2, wrap function declarations inside a check to see whether the function has been declared already.  Requires placing wrapped function declarations before code that calls them:

1.php

<?php

if (!function_exists('shared_function1')):
  function 1(){
      // yadda yadda
  }
endif;

// rest of 1.php
?>

2.php

<?php

if (!function_exists('shared_function1')):
  function 1(){
      // yadda yadda
}
endif;

// rest of 2.php
?>

If the only problem you are encountering is bombs on function delcarations for functions that already have been declared by another script, make the function names unique (explained at end of this option), then run the scripts with this:

Option 3 - all.php

<?php

$scripts_to_run=array();
$scripts_to_run[]=1.php;
$scripts_to_run[]=2.php;
$scripts_to_run[]=3.php;
.
.
.
$scripts_to_run[]=10.php;

foreach ($scripts_to_run as $script):
  require $script;
endforeach;

*TO MAKE THE FUNCTION NAMES UNIQUE, in 1.php, for each sharedfunctionname, search/replace sharedfunctionname with functionname_1 In 2.php, for each sharedfunctionname, search/replace sharedfunctionname with functionname_2 ... etc.

examples:
CURRENT SCRIPTS

1.php
<?php

$var_dry   = 'dry';
$var_wet   = 'wet';
$result=sharedfunctionname($var_dry, $var_wet);

function sharedfunctionname($var_1, $var_2){
   // mix two strings to make one with the letters from both intermingled
}

2.php
<?php

$var_dog   = 'dog';
$var_cat   = 'cat';
$result=sharedfunctionname($var_dog, $var_cat);

function sharedfunctionname($var_1, $var_2){
   // something completely different from mixing two strings....
}

AFTER MAKING FUNCTION NAMES UNIQUE

1.php

<?php

$var_dry   = 'dry';
$var_wet   = 'wet';
$result=functionname_1($var_dry, $var_wet);

function functionname_1($var_1, $var_2){
   // mix two strings to make one with the letters from both intermingled
}

2.php
<?php

$var_dog   = 'dog';
$var_cat   = 'cat';
$result=functionname_2($var_dog, $var_cat);

function functionname_2($var_1, $var_2){
   // something completely different from mixing two strings....

}


问:
Mapbox: How to correct Line overlapping over a Symbol
I'm using the SymbolManager to display two symbols on the map. Here is an example:

The dark symbol is because of the fact that I'm testing the project on the Emulator, but the Line goes under the symbol, as it should be. The problem comes with the other symbol (finish flag). After I'm ready with the drawing of the line, the following code block is called:

```<code>symbolManager = new SymbolManager(mapView,mMapboxMap,style);

symbolManager.setIconAllowOverlap(true);
symbolManager.setIconIgnorePlacement(true);

SymbolOptions symbolOptionsFinishFlag = new SymbolOptions()
              .withIconImage(IMAGE_FINISH_FLAG)
              .withIconSize(2.0f)
              .withLatLng(newLatLngs.get(newLatLngs.size()-1));

symbolManager.create(symbolOptionsFinishFlag);

LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.includes(newLatLngs);
LatLngBounds bounds = builder.build();

final CameraUpdate cu = new CameraUpdateFactory().newLatLngBounds(bounds,300);
mMapboxMap.easeCamera(cu,5000);
</code>```

I checked some examples in the Mapbox site and it seems to be correct. However, the Symbol is under the Line, how can I bring on top of it?

答: Although SymbolManagers can be useful means for providing an abstraction over the methods needed to add symbols to a map, you may get some more flexibility by working with native SymbolLayers directly. This example shows how to add symbol layer icons to a map, and this example shows how to specify layer ordering when new layers are added. So, by adding two symbol layers for your start and finish icons, and a line layer for the line between them, you could use style.addLayerBelow(finishFlagLayer, "name_of_line_layer").

Body:
I'm using the SymbolManager to display two symbols on the map. Here is an example:

The dark symbol is because of the fact that I'm testing the project on the Emulator, but the Line goes under the symbol, as it should be. The problem comes with the other symbol (finish flag). After I'm ready with the drawing of the line, the following code block is called:

symbolManager = new SymbolManager(mapView,mMapboxMap,style);

symbolManager.setIconAllowOverlap(true);
symbolManager.setIconIgnorePlacement(true);

SymbolOptions symbolOptionsFinishFlag = new SymbolOptions()
              .withIconImage(IMAGE_FINISH_FLAG)
              .withIconSize(2.0f)
              .withLatLng(newLatLngs.get(newLatLngs.size()-1));

symbolManager.create(symbolOptionsFinishFlag);

LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.includes(newLatLngs);
LatLngBounds bounds = builder.build();

final CameraUpdate cu = new CameraUpdateFactory().newLatLngBounds(bounds,300);
mMapboxMap.easeCamera(cu,5000);

I checked some examples in the Mapbox site and it seems to be correct. However, the Symbol is under the Line, how can I bring on top of it?


问:
Adding 20 minutes to number in java
So I need a variable that shows times in 24HR format (01:00, 09:00) and every time I loop through it, to add 20 mins to the time? I then need to use this value in a string.

The time needs to start at any given time. like 00:00
Any ideas how should I go with it?

and output like this 00:00-00:20,00:20-..00:40,00:40-01:00 and so on....

答:
This code will print timestamps in HH:mm format for each 20 minutes:

```<code>LocalDateTime dt = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
System.out.println(dt.format(df));
for (int i = 0; i < 24 * 3; i++) {
    dt = dt.plusMinutes(20);
    System.out.println(dt.format(df));
}
</code>```

Its output is as follows:

```<code>00:00
00:20
00:40
01:00
01:20
...
</code>```

Update

Sorry, it could be done with simple loop:

```<code>for (int min = 0; min < 24 * 60; min += 20) {
    int next = min + 20;
    String timestamp = String.format("%02d:%02d - %02d:%02d", min/60, min%60, next/60, next%60);
    System.out.println(timestamp);
}
/////
00:00 - 00:20
00:20 - 00:40
00:40 - 01:00
...
</code>```

Title: Adding 20 minutes to number in java

Body:
This code will print timestamps in HH:mm format for each 20 minutes:

LocalDateTime dt = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
System.out.println(dt.format(df));
for (int i = 0; i < 24 * 3; i++) {
    dt = dt.plusMinutes(20);
    System.out.println(dt.format(df));
}

Its output is as follows:

00:00
00:20
00:40
01:00
01:20
...

Update

Sorry, it could be done with simple loop:

for (int min = 0; min < 24 * 60; min += 20) {
    int next = min + 20;
    String timestamp = String.format("%02d:%02d - %02d:%02d", min/60, min%60, next/60, next%60);
    System.out.println(timestamp);
}
/////
00:00 - 00:20
00:20 - 00:40
00:40 - 01:00
...


问:
Is there a way to change the side/position of a single tooltipster tooltip without having multiple classes?
I'm currently labelling anatomy diagrams and in order to minimize the labels overlapping the diagrams too much, I want to set only SOME of the tooltips to show from the bottom of the svg that I'm tagging. In the example I include it would be setting the tooltip for the svg with id "mud_levator_mandibulae_externus" to show at the bottom instead of the top.

I know I can separate each group of tooltips into different classes, but I would like to keep them all under one class if I can since I have JavaScript code that would be tedious to change if I had different classes.

I thought you could add the function specific to the id to the  tag after my tooltips initialization but it's not working. Adding it into the document ready function doesn't work either.

$(document).ready(function() {
            $('.tooltip').tooltipster({
             theme: ['tooltipster-shadow', 'tooltipster-shadow-customized'],
             trigger: 'click',
             });
        });

$('#mud_levator_mandibulae_externus').tooltipster({
 side:'bottom'
});```

答:
You could add one more css class to your element, like class="tooltip tooltip-left" and then have your functionInit detect it and change the side option accordingly, something like

functionInit (instance, helper) {
  if ($(instance.origin).hasClass('tooltip-left')) {
    instance.option('side', 'left')
  }
}
```


问:
Upgrading Grapecity Active Reports from version 9 to version 14
I have successfully modified my application to use Grapecity active reports 14 which was using only Grapecity active reports 9. Right now I need to support both 9 and 14 since I have more than 100 projects already referring 9.

The current implementation have a common report project has one base class with required methods needed to generate a pdf and excel report using active reports 9 and one more base class with replication of code for active reports 14. I have referred this base project to create any report using 9 and 14.

```<code>Below is an example to represent how my solution looks like

 MyProjectSolution
    BaseReportProject
        BaseReport9.cs
        BaseReport14.cs
    ProjectReport1
        Report.cs : BaseReport9.cs
    ProjectReport2
        Report.cs : BaseReport14.cs
</code>```

My confusion here is, is there any better approach for doing this? When there is a need to include another active report version as per current implementation I need to add one more base class.

Is there a better approach to implement this type of requirement?

I am not sure if this is a valid question.If yes,any suggestion would be appreciated

答:
A better approach to this is to have three separate projects:

A project for your v9 reports

A project for your v14 reports

A project that can call project #1 or #2

The reason we suggest this is that there have been significant changes from v9 to v14 so you may encounter conflicts with both reports in the same projects.

For more information about the changes, please refer to the documentation below:
https://www.grapecity.com/activereports/docs/v14/online/whats-new.html
https://www.grapecity.com/activereports/docs/v14/online/breaking-changes.html?highlight=breaking%2C

If you have any other questions, feel free to reach out to our support team!

Sincerely,

GrapeCity Support Team

Body:
I have successfully modified my application to use Grapecity active reports 14 which was using only Grapecity active reports 9. Right now I need to support both 9 and 14 since I have more than 100 projects already referring 9.

The current implementation have a common report project has one base class with required methods needed to generate a pdf and excel report using active reports 9 and one more base class with replication of code for active reports 14. I have referred this base project to create any report using 9 and 14.

Below is an example to represent how my solution looks like

 MyProjectSolution
    BaseReportProject
        BaseReport9.cs
        BaseReport14.cs
    ProjectReport1
        Report.cs : BaseReport9.cs
    ProjectReport2
        Report.cs : BaseReport14.cs

My confusion here is, is there any better approach for doing this? When there is a need to include another active report version as per current implementation I need to add one more base class.

Is there a better approach to implement this type of requirement?

I am not sure if this is a valid question.If yes,any suggestion would be appreciated


问:
exctract values by column from arrays of arrays, seperated in different arrays
I have an array of arrays as it is shown :

I want to collect all the values of the first column (118,117,115 etc) but seperated in different array for values that are in different arrays on my initial array of arrays. In more detail I want to have my value as:

```<code>array([118,117,115,...]),
array([461,460,459,...])
</code>```

Thank you in advance

答:
It is normally not helpful to place your text in an image. You force other people to type out your text, instead of being able to copy and paste. With that said, </p>

<p>Accessing information in numpy arrays is an extremely useful skill and something worth reading several tutorials about. I would google numpy and read how to use numpy arrays. For example, </p>

```<code># This is similar to your data, two 3x2 arrays. Here I put them in one large array.
data = np.array([[[1,2],
                  [3,4],
                  [5,6]],
                 [[7,8],
                  [9,10],
                  [11,12]]])

print(data.shape)  # There are three axis, which indicate how data is accessed.
                   # This also shows how much data is in each axis.
print(data[0,0,0]) # Access the value "1", located at 0,0,0 in the array.

print(data[0])     # Access the first 3x2 array.

print(data[1,0])   # Access the second 3x2 and then the first row of that.

print(data[1,0:2]) # Access the second 3x2 and the 0th and 1st rows.

print(data[:,:,0]) # Access both arrays, all rows, and only the 0th column.
</code>```

Body:
I have an array of arrays as it is shown :

I want to collect all the values of the first column (118,117,115 etc) but seperated in different array for values that are in different arrays on my initial array of arrays. In more detail I want to have my value as:

array([118,117,115,...]),
array([461,460,459,...])

Thank you in advance

Body:
It is normally not helpful to place your text in an image. You force other people to type out your text, instead of being able to copy and paste. With that said,

Accessing information in numpy arrays is an extremely useful skill and something worth reading several tutorials about. I would google numpy and read how to use numpy arrays. For example,

# This is similar to your data, two 3x2 arrays. Here I put them in one large array.
data = np.array([[[1,2],
                  [3,4],
                  [5,6]],
                 [[7,8],
                  [9,10],
                  [11,12]]])

print(data.shape)  # There are three axis, which indicate how data is accessed.
                   # This also shows how much data is in each axis.
print(data[0,0,0]) # Access the value "1", located at 0,0,0 in the array.

print(data[0])     # Access the first 3x2 array.

print(data[1,0])   # Access the second 3x2 and then the first row of that.

print(data[1,0:2]) # Access the second 3x2 and the 0th and 1st rows.

print(data[:,:,0]) # Access both arrays, all rows, and only the 0th column.


问:
Is it possible to hold multiple types of enums in a variable in C++?
Is it possible to do something like this in C++:

enum A {//Starts from 0 and has no enum with out of place value like 0,1,5,40, etc.
    eg1,
    eg2,
    eg3,
    ...
}

enum B {//Same structure as enum A
    e1,
    e2,
    e3,
    ...
}

some_data_type e = eg1;//No errors here
e = e2;//No errors here
```

I think it could be something like just an integer, but just to be safe is there another way to do this?

答:
If you're ok losing the distinction between the original types, then an integer would work.  If you want to be a little more restrictive and only allow assignment from and comparison against "compatible" enums, then a user-defined type with implicit conversion from both A and B is probably wanted.  Unfortunately you can't add conversions directly between two enums because conversion functions and converting constructors both have to be member functions, which enums don't allow.

If you want to keep them distinguished later, then boost::variant will do that.

Body:
Is it possible to do something like this in C++:

enum A {//Starts from 0 and has no enum with out of place value like 0,1,5,40, etc.
    eg1,
    eg2,
    eg3,
    ...
}

enum B {//Same structure as enum A
    e1,
    e2,
    e3,
    ...
}

some_data_type e = eg1;//No errors here
e = e2;//No errors here

I think it could be something like just an integer, but just to be safe is there another way to do this?

Body:
If you're ok losing the distinction between the original types, then an integer would work.  If you want to be a little more restrictive and only allow assignment from and comparison against "compatible" enums, then a user-defined type with implicit conversion from both A and B is probably wanted.  Unfortunately you can't add conversions directly between two enums because conversion functions and converting constructors both have to be member functions, which enums don't allow.

If you want to keep them distinguished later, then boost::variant<A, B> will do that.


问:
Proper structure of AJAX handler
My .NET project handles AJAX requests.  There are no UI controls at all, it simply responds with text to every AJAX post.

This is my current structure:

```<code><%
SynchLock DBNull.Value
  Main
End SynchLock
%>

<script language="VB" runat="Server">

Sub Main
  Dim a() As String = Request.Form("a").Split(" "c)
  ' a: (0) version, (1) config, (2) userid, (3) sessionid, (4) activity

  ' Initializations

  Using conn As DbConnection = sess.Connection
    Select Case a(4)
    Case 0
      ActivityOne
    Case 1
      ActivityTwo
    Case 2
      ActivityThree
    ...
    Case 28
      ActivityTwentyEight
    End Select
  End Using
End Sub

'All the activity functions and lots of other Functions

</script>
</code>```

This works but I think it can be improved; I'm not sure how to proceed.

Some of the activities call subfunctions and I'm looking at breaking some of the activities out even further.  In order to encapsulate all the functionality of an activity, I'm considering changing the activities from functions to classes, like so:

```<code>Select Case a(4)
Case 0
  Dim a1 As New ActivityOne
  a1.Execute
...
End Select
</code>```

Is this the right approach?  If I proceed with the classes, I have related questions:

(1) Do I code the "New" Sub of the classes or an "Execute" (or some other name) Sub?  If I code the "New" Sub, then I can reduce the above code to:

```<code>Select Case a(4)
Case 0
  New ActivityOne
...
End Select
</code>```

This seems easier, but are there disadvantages?

(2) The activities all rely on other Request.Form inputs.  Do I (a) pass access the HttpContext.Current object from within the classes or (b) pass the Request object to the activity or (c) pass the specific Request.Form variables needed by the activity?

e.g.

(a) New ActivityOne ' the class accesses HttpContext.Current.Form("b"), etc.

```<code>Class ActivityOne
  Sub New
    Dim p1 As String = HttpContext.Current.Form("b")
    ...
  End Sub
End Class
</code>```

(b) New ActivityOne(Request)

```<code>Class ActivityOne
  Sub New(req As HttpRequest)
    Dim p1 As String = req.Form("b")
    ...
  End Sub
End Class
</code>```

(c) New ActivityOne(Request.Form("b"))

```<code>Class ActivityOne
  Sub New(p1 As String)
    ...
  End Sub
End Class
</code>```

答:
The activities all rely on other Request.Form inputs. Do I (a) pass access the HttpContext.Current object from within the classes or (b) pass the Request object to the activity or (c) pass the specific Request.Form variables needed by the activity?

You could just pass the Request.Form NameValue collection.

Also, since you're using ASP.NET, you could consider using an ASP.NET AJAX enabled webservice click and make methods for each of your activities.  This would simplify your code.  You could also make a WCF REST service and call it with jQuery.

You don't need to be picking out querystring values or creating massive switch statements.  ASP.NET has the infrastructure in place to handle this sort of thing.

ContentLicense: CC BY-SA 3.0

Title: Proper structure of AJAX handler

Body:
My .NET project handles AJAX requests.  There are no UI controls at all, it simply responds with text to every AJAX post.

This is my current structure:

<%
SynchLock DBNull.Value
  Main
End SynchLock
%>

This works but I think it can be improved; I'm not sure how to proceed.

Some of the activities call subfunctions and I'm looking at breaking some of the activities out even further.  In order to encapsulate all the functionality of an activity, I'm considering changing the activities from functions to classes, like so:

Select Case a(4)
Case 0
  Dim a1 As New ActivityOne
  a1.Execute
...
End Select

Is this the right approach?  If I proceed with the classes, I have related questions:

(1) Do I code the "New" Sub of the classes or an "Execute" (or some other name) Sub?  If I code the "New" Sub, then I can reduce the above code to:

Select Case a(4)
Case 0
  New ActivityOne
...
End Select

This seems easier, but are there disadvantages?

(2) The activities all rely on other Request.Form inputs.  Do I (a) pass access the HttpContext.Current object from within the classes or (b) pass the Request object to the activity or (c) pass the specific Request.Form variables needed by the activity?

e.g.

(a) New ActivityOne ' the class accesses HttpContext.Current.Form("b"), etc.

Class ActivityOne
  Sub New
    Dim p1 As String = HttpContext.Current.Form("b")
    ...
  End Sub
End Class

(b) New ActivityOne(Request)

Class ActivityOne
  Sub New(req As HttpRequest)
    Dim p1 As String = req.Form("b")
    ...
  End Sub
End Class

(c) New ActivityOne(Request.Form("b"))

Class ActivityOne
  Sub New(p1 As String)
    ...
  End Sub
End Class


问:
converting class component to functional error
I am using the react-sortable-hoc package and want to use it in a functional component instead. I have tried to convert it but there is a line that is giving me an error.

The list shows up and I can drag any element but as soon as I drop it I get the error

Cannot read property 'slice' of undefined

It looks as if it is posting to this line:

```<code>items: arrayMove(items, oldIndex, newIndex),
</code>```

Here is the class based version:

```<code>import React, {Component} from 'react';
import {render} from 'react-dom';
import {sortableContainer, sortableElement} from 'react-sortable-hoc';
import arrayMove from 'array-move';

const SortableItem = sortableElement(({value}) => <li>{value}</li>);

const SortableContainer = sortableContainer(({children}) => {
  return <ul>{children}</ul>;
});

class App extends Component {
  state = {
    items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
  };

  onSortEnd = ({oldIndex, newIndex}) => {
    this.setState(({items}) => ({
      items: arrayMove(items, oldIndex, newIndex),
    }));
  };

  render() {
    const {items} = this.state;

    return (
      <SortableContainer onSortEnd={this.onSortEnd}>
        {items.map((value, index) => (
          <SortableItem key={`item-${value}`} index={index} value={value} />
        ))}
      </SortableContainer>
    );
  }
}

render(<App />, document.getElementById('root'));
</code>```

And the version I am trying to put together:

```<code>import React, { useState } from "react";
import { sortableContainer, sortableElement } from "react-sortable-hoc";
import arrayMove from "array-move";

const SortableItem = sortableElement(({ value }) => <li>{value}</li>);

const SortableContainer = sortableContainer(({ children }) => {
  return <ul>{children}</ul>;
});

const Dashboard = () => {
  const [items, setItems] = useState([
    "Item 1",
    "Item 2",
    "Item 3",
    "Item 4",
    "Item 5",
    "Item 6",
  ]);

  const onSortEnd = ({ oldIndex, newIndex }) => {
    setItems(({ items }) => ({
      items: arrayMove(items, oldIndex, newIndex),
    }));
  };

  return (
    <SortableContainer onSortEnd={onSortEnd}>
      {items.map((value, index) => (
        <SortableItem key={`item-${value}`} index={index} value={value} />
      ))}
    </SortableContainer>
  );
};

export default Dashboard;
</code>```

答:
You need not destructure items from setItems callback as state doesn't store the object in your case but an array. Also you must not set the value back as an object, instead it should be an array again

```<code>setItems((items) => arrayMove(items, oldIndex, newIndex));
</code>```

Body:
I am using the react-sortable-hoc package and want to use it in a functional component instead. I have tried to convert it but there is a line that is giving me an error.

The list shows up and I can drag any element but as soon as I drop it I get the error

Cannot read property 'slice' of undefined

It looks as if it is posting to this line:

items: arrayMove(items, oldIndex, newIndex),

Here is the class based version:

import React, {Component} from 'react';
import {render} from 'react-dom';
import {sortableContainer, sortableElement} from 'react-sortable-hoc';
import arrayMove from 'array-move';

const SortableItem = sortableElement(({value}) =>
{value}
);

const SortableContainer = sortableContainer(({children}) => {
  return
{children}
;
});

class App extends Component {
  state = {
    items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
  };

  onSortEnd = ({oldIndex, newIndex}) => {
    this.setState(({items}) => ({
      items: arrayMove(items, oldIndex, newIndex),
    }));
  };

  render() {
    const {items} = this.state;

    return (
      <SortableContainer onSortEnd={this.onSortEnd}>
        {items.map((value, index) => (
          <SortableItem key={`item-${value}`} index={index} value={value} />
        ))}
      </SortableContainer>
    );
  }
}

render(<App />, document.getElementById('root'));

And the version I am trying to put together:

import React, { useState } from "react";
import { sortableContainer, sortableElement } from "react-sortable-hoc";
import arrayMove from "array-move";

const SortableItem = sortableElement(({ value }) =>
{value}
);

const SortableContainer = sortableContainer(({ children }) => {
  return
{children}
;
});

const Dashboard = () => {
  const [items, setItems] = useState([
    "Item 1",
    "Item 2",
    "Item 3",
    "Item 4",
    "Item 5",
    "Item 6",
  ]);

  const onSortEnd = ({ oldIndex, newIndex }) => {
    setItems(({ items }) => ({
      items: arrayMove(items, oldIndex, newIndex),
    }));
  };

  return (
    <SortableContainer onSortEnd={onSortEnd}>
      {items.map((value, index) => (
        <SortableItem key={`item-${value}`} index={index} value={value} />
      ))}
    </SortableContainer>
  );
};

export default Dashboard;

Body:
You need not destructure items from setItems callback as state doesn't store the object in your case but an array. Also you must not set the value back as an object, instead it should be an array again

setItems((items) => arrayMove(items, oldIndex, newIndex));


问:
resize image with bilinear interpolation in python
I want to resize image with bilinear interpolation. I found new intensity value but I do not know how can I use it.. The code is below which is I written..

```<code>def resizeImageBI(im,width,height):
    temp = np.zeros((height,width),dtype=np.uint8)
    ratio_1 = float(im.size[0] - 1 )/ float(width - 1)
    ratio_0 = float(im.size[1] - 1) / float(height - 1)
    xx,yy = np.mgrid[:height, :width]
    xmap = np.around(xx * ratio_0)
    ymap = np.around(yy * ratio_1)

for i in xrange(0, height):
    for j in xrange(0,width):
        temp[i][j]=im.getpixel( ( ymap[i][j], xmap[i][j]) ) * getNewIntensity(i,j,ratio_1,ratio_0)

return Image.fromarray(temp)
</code>```

firstly get variable image width ratio and height ratio

```<code>lena.png 0.5 1
</code>```

Orginal image is here

That is output accorting to written code

答:
I just had to do this for a class and I haven't been graded yet, so you should check this out before using.

Basic Interpolation function

```<code>def interpolation(y0,x0, y1,x1, x):
    frac = (x - x0) / (x1 - x0)
    return y0*(1-frac) + y1 * frac
</code>```

Step 1: Map the original coordinates to the newly resized image

```<code>def get_coords(im, W, H):
    h,w = im.shape
    x = np.arange(0,w+1,1) * W/w
    y = np.arange(0,h+1,1) * H/h
    return x,y
</code>```

Step 2: Create a function to interpolate in the x-direction on all rows.

```<code>def im_interp(im, H,W):
    X = np.zeros(shape=(W,H))
    x, y = get_coords(im, W, H)
    for i,v in enumerate(X):
        y0_idx = np.argmax(y >i) - 1
        for j,_ in enumerate(v):
            # subtracting 1 because this is the first val
            # that is greater than j, want the idx before that
            x0_idx = np.argmax(x > j) - 1
            x1_idx = np.argmax(j < x)

            x0 = x[x0_idx]
            x1 = x[x1_idx]

            y0 = im[y0_idx, x0_idx - 1]
            y1 = im[y0_idx, x1_idx - 1]

            X[i,j] = interpolation(y0, x0, y1, x1, j)
    return X
</code>```

Step 3: Use function from the above step to interpolate twice.  First on the image in the x-direction, then on the transpose of the newly created image (y-direction)

```<code>def im_resize(im,H,W):
    X_lin = im_interp(im, H,W)
    X = im_interp(X_lin.T, H,W)
    return X_lin, X.T
</code>```

I return both images just to look at the difference.

Body:
I want to resize image with bilinear interpolation. I found new intensity value but I do not know how can I use it.. The code is below which is I written..

def resizeImageBI(im,width,height):
    temp = np.zeros((height,width),dtype=np.uint8)
    ratio_1 = float(im.size[0] - 1 )/ float(width - 1)
    ratio_0 = float(im.size[1] - 1) / float(height - 1)
    xx,yy = np.mgrid[:height, :width]
    xmap = np.around(xx * ratio_0)
    ymap = np.around(yy * ratio_1)

for i in xrange(0, height):
    for j in xrange(0,width):
        temp[i][j]=im.getpixel( ( ymap[i][j], xmap[i][j]) ) * getNewIntensity(i,j,ratio_1,ratio_0)

return Image.fromarray(temp)

firstly get variable image width ratio and height ratio

lena.png 0.5 1

Orginal image is here

That is output accorting to written code

Body:
I just had to do this for a class and I haven't been graded yet, so you should check this out before using.

Basic Interpolation function

def interpolation(y0,x0, y1,x1, x):
    frac = (x - x0) / (x1 - x0)
    return y0*(1-frac) + y1 * frac

Step 1: Map the original coordinates to the newly resized image

def get_coords(im, W, H):
    h,w = im.shape
    x = np.arange(0,w+1,1) * W/w
    y = np.arange(0,h+1,1) * H/h
    return x,y

Step 2: Create a function to interpolate in the x-direction on all rows.

def im_interp(im, H,W):
    X = np.zeros(shape=(W,H))
    x, y = get_coords(im, W, H)
    for i,v in enumerate(X):
        y0_idx = np.argmax(y >i) - 1
        for j,_ in enumerate(v):
            # subtracting 1 because this is the first val
            # that is greater than j, want the idx before that
            x0_idx = np.argmax(x > j) - 1
            x1_idx = np.argmax(j < x)

            x0 = x[x0_idx]
            x1 = x[x1_idx]

            y0 = im[y0_idx, x0_idx - 1]
            y1 = im[y0_idx, x1_idx - 1]

            X[i,j] = interpolation(y0, x0, y1, x1, j)
    return X

Step 3: Use function from the above step to interpolate twice.  First on the image in the x-direction, then on the transpose of the newly created image (y-direction)

def im_resize(im,H,W):
    X_lin = im_interp(im, H,W)
    X = im_interp(X_lin.T, H,W)
    return X_lin, X.T

I return both images just to look at the difference.


问:
Ternary operator in perl yields unexpected result when assigning a variable in the statement
I'm trying to make a transition from php to perl and expectedly running into some weirdness.  I cannot understand why one version of my code works vs another.

This fails:

```<code>sub tester
{
$return;
($_[0] < 10) ? $return = "youre a youngin" : $return = "youre an old person";
return $return;
}

print "how old are you?";
$a = <>;
chomp $a;

print  tester($a);  #both result in "youre an old person"
</code>```

however this one works:

```<code>sub tester
{
    return ($_[0] < 10) ? "youre a youngin" : "youre an old person";
}

print "how old are you?";
$a = <>;
chomp $a;
print  tester($a);
</code>```

what is the real difference here?!

答:
Ah, you've discovered why ?: is a bad idea except in trivial cases.

Operator precedence is the problem.  You most likely want to do this:

```<code>$return = ($_[0] < 10) ? "you're a youngin'" : "you're an old fart";
</code>```

There are a few other issues with your code, though.

You should declare your variables.  They aren't declared on first use as in PHP; you do it explicitly with the my operator.

You should always, always, always use strict and use warnings in Perl code.  These pragmas disable ancient Perl shenanigans and warn about suspicious operations that might be bugs.

The first line of a function should usually be unpacking @_; there's very little reason to use $_[0] directly in a function.  (And it's dangerous to do so, since @_ is aliased; you could change the caller's variables!)

So you probably want something more like this:

```<code>use strict;
use warnings;

sub tester {
    my ($age) = @_;
    if ($age < 10) {
        return "you're a youngin'";
    }
    else {
        return "you're an old fart";
    }
}

print "how old are you? ";
my $age = <>;
chomp $age;

print tester($age);
</code>```

Note that my $x = ... declares a single variable and assigns a single value, whereas my ($x, $y, $z) = ... declares multiple variables and unpacks a list into them.

my variables are called lexical and only exist within the block where you declare them; they aren't function-scoped like PHP variables.  Actually you should probably just read about them in perlsub.

Body:
I'm trying to make a transition from php to perl and expectedly running into some weirdness.  I cannot understand why one version of my code works vs another.

This fails:

sub tester
{
$return;
($_[0] < 10) ? $return = "youre a youngin" : $return = "youre an old person";
return $return;
}

print "how old are you?";
$a = <>;
chomp $a;

print  tester($a);  #both result in "youre an old person"

however this one works:

sub tester
{
    return ($_[0] < 10) ? "youre a youngin" : "youre an old person";
}

print "how old are you?";
$a = <>;
chomp $a;
print  tester($a);

what is the real difference here?!

Body:
Ah, you've discovered why ?: is a bad idea except in trivial cases.

Operator precedence is the problem.  You most likely want to do this:

$return = ($_[0] < 10) ? "you're a youngin'" : "you're an old fart";

There are a few other issues with your code, though.

You should declare your variables.  They aren't declared on first use as in PHP; you do it explicitly with the my operator.

You should always, always, always use strict and use warnings in Perl code.  These pragmas disable ancient Perl shenanigans and warn about suspicious operations that might be bugs.

The first line of a function should usually be unpacking @_; there's very little reason to use $_[0] directly in a function.  (And it's dangerous to do so, since @_ is aliased; you could change the caller's variables!)

So you probably want something more like this:

use strict;
use warnings;

sub tester {
    my ($age) = @_;
    if ($age < 10) {
        return "you're a youngin'";
    }
    else {
        return "you're an old fart";
    }
}

print "how old are you? ";
my $age = <>;
chomp $age;

print tester($age);

Note that my $x = ... declares a single variable and assigns a single value, whereas my ($x, $y, $z) = ... declares multiple variables and unpacks a list into them.

my variables are called lexical and only exist within the block where you declare them; they aren't function-scoped like PHP variables.  Actually you should probably just read about them in perlsub.


问:
Perforce integrating multiple changelists from one branch to another keeping them as separate changelists
I'm wondering if there's an easy solution to this workflow. I work using the perforce GUI (P4V), but I'm not adverse to using the command line for this. In any case, let's say I fix 3 bugs working on my personal development branch. Each one I submit to my personal devel branch in 3 different change lists.

Now I want to merge/integrate those to the main branch. Currently, when I do that all 3 change lists get squashed into a single one in the main branch. However, is there a simple way to do this so that all 3 changelists remain separated? The only other option I see is to cherry pick change lists -click on each changelist in the history tab,-- and merge them there one by one...

Suggestions would be appreciated!

Thanks,

Rodrigo

答:
If you want 3 changelists on the main branch, you have to submit 3 times:</p>

```<code>p4 integ my_dev/...@A,A main/...
p4 resolve -am
p4 submit -d "merged A to main from my_dev"

p4 integ my_dev/...@B,B main/...
p4 resolve -am
p4 submit -d "merged B to main from my_dev"

p4 integ my_dev/...@C,C main/...
p4 resolve -am
p4 submit -d "merged C to main from my_dev"
</code>```

Body:
If you want 3 changelists on the main branch, you have to submit 3 times:

p4 integ my_dev/...@A,A main/...
p4 resolve -am
p4 submit -d "merged A to main from my_dev"

p4 integ my_dev/...@B,B main/...
p4 resolve -am
p4 submit -d "merged B to main from my_dev"

p4 integ my_dev/...@C,C main/...
p4 resolve -am
p4 submit -d "merged C to main from my_dev"


问:
VB.net Excel set view to Page Layout
I´m trying to change the view in Excel document to Page Layout using vb.net.

```<code> objExcel = CreateObject("Excel.Application")
 objExcel.Visible = True
 objExcelWB = objExcel.Workbooks.Add
 objExcelWS = objExcelWB.ActiveSheet
</code>```

I have done my programming (in AutoCAD and Excel) and everything works.

I would like to have my created Excel documents in Page Layout view.

I can't see any method for the Worksheet or Workbook to access the view settings.

答: Set the View property of either the ActiveWindow object, or for all Window objects in the Windows collection for the target Workbook to xlPageLayoutView (3).

Title: VB.net Excel set view to Page Layout

Body:
I´m trying to change the view in Excel document to Page Layout using vb.net.

 objExcel = CreateObject("Excel.Application")
 objExcel.Visible = True
 objExcelWB = objExcel.Workbooks.Add
 objExcelWS = objExcelWB.ActiveSheet

I have done my programming (in AutoCAD and Excel) and everything works.

I would like to have my created Excel documents in Page Layout view.

I can't see any method for the Worksheet or Workbook to access the view settings.


问:
Can I disable/delete class in PyQt5 (i.e. QEvent.KeyPress)?
I am working on a PyQt5 based app. My GUI shows 21 buttons: letters from A to Z, I use them as input for

the main algorithm. I would like to be able to input the letters from the keyboard too.

So far following Get printable name of any QKeyEvent key value     I am able to achieve this.

Only problem is how to disable keyPressevent , and re-enable it after my app intro screen,

like I do with my letters button doing:

self.groupBox.hide() and re-enabling them after pressing the start new game

button. with self.groupBox.show()

I wrote down in my answer the solution to my problem provided by musicamante. Still I would like to now if is there a way to disable PyQt5 keyboard event processing in a way that my :

```<code>def keyPressEvent(self, event):
         print(keyevent_to_string(self, event))
         print('self.letters : ',self.letters)
         print('self.letters_guessed : ',self.letters_guessed )
         if keyevent_to_string(self, event) in self.letters:
                    print('inininininini'*5)
                    self.printo(keyevent_to_string(self, event))
</code>```

code piece sits there but doesnt produce any result when I press a keyboard key ?

I understood that KeyPressEvent is the handler for QEvent.KeyPress, so is there a way to disable/delete/remove  QEvent.KeyPress class in Pyqt5 ?

答:
following musicamante suggestions I modified my code with:

```<code>def keyPressEvent(self, event):
    if self.keyonoff:
         print(keyevent_to_string(self, event))
         print('self.letters : ',self.letters)
         print('self.letters_guessed : ',self.letters_guessed )
         if keyevent_to_string(self, event) in self.letters:
                    print('inininininini'*5)
                    self.printo(keyevent_to_string(self, event))

</code>```

then switched

self.keyonoff = True and   self.keyonoff = False

as needed by my code.

I am getting what I was looking for, not sure if there is another way to
do that: 'I understood that KeyPressEvent is the handler for QEvent.KeyPress, so is there a way to disable/delete/remove QEvent.KeyPress class in Pyqt5 ?'

Code below is not mine is just a keyPressEvent reimplamantation usefull to my purpose

```<code>from PyQt5.QtCore import Qt

def keyevent_to_string(self, event):
    self.keymap = {}
    for self.key, value in vars(Qt).items():
        if isinstance(value, Qt.Key):
            self.keymap[value] = self.key.partition('_')[2]

    self.modmap = {
        Qt.ControlModifier: self.keymap[Qt.Key_Control],
        Qt.AltModifier: self.keymap[Qt.Key_Alt],
        Qt.ShiftModifier: self.keymap[Qt.Key_Shift],
        Qt.MetaModifier: self.keymap[Qt.Key_Meta],
        Qt.GroupSwitchModifier: self.keymap[Qt.Key_AltGr],
        Qt.KeypadModifier: self.keymap[Qt.Key_NumLock],
        }
    self.sequence = []
    for modifier, text in self.modmap.items():
        if event.modifiers() & modifier:
            self.sequence.append(text)
    self.key = self.keymap.get(event.key(), event.text())
    if self.key not in self.sequence:
        self.sequence.append(self.key)
    return '+'.join(self.sequence)
</code>```

From Get printable name of any QKeyEvent key value

Edited Edited Edited

More on this hopefully I'll get my right to ask questions back:

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 29 10:49:58 2020

@author: Pietro
"""

import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import Qt, QEvent

class Window(QtWidgets.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.button = QtWidgets.QPushButton("activate", self)
        self.button2 = QtWidgets.QPushButton("deactivate", self)
        self.button.move(0,0)
        self.button2.move(100,100)
        self.button2.clicked.connect(self.deactivated)
        self.button.clicked.connect(self.activated)

    def activated(self):
        print('attivato')
        QWidget.setEnabled(self,True)

    def deactivated(self):
        print('deattivato')
        QWidget.setEnabled(self,False)

    def keyevent_to_string(self, event):
        self.keymap = {}
        for self.key, value in vars(Qt).items():
            if isinstance(value, Qt.Key):
                self.keymap[value] = self.key.partition('_')[2]

        self.modmap = {
            Qt.ControlModifier: self.keymap[Qt.Key_Control],
            Qt.AltModifier: self.keymap[Qt.Key_Alt],
            Qt.ShiftModifier: self.keymap[Qt.Key_Shift],
            Qt.MetaModifier: self.keymap[Qt.Key_Meta],
            Qt.GroupSwitchModifier: self.keymap[Qt.Key_AltGr],
            Qt.KeypadModifier: self.keymap[Qt.Key_NumLock],
            }
        self.sequence = []
        for modifier, text in self.modmap.items():
            if event.modifiers() & modifier:
                self.sequence.append(text)
        self.key = self.keymap.get(event.key(), event.text())
        if self.key not in self.sequence:
            self.sequence.append(self.key)
        return '+'.join(self.sequence)

    def keyPressEvent(self, event):
            print(self.keyevent_to_string(event))

if __name__ == '__main__':

    app = QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 300, 200)
    window.show()
    sys.exit(app.exec_())
</code>```

I ended up here

QWidget.setEnabled(False)

apparently disable both keyboard and mouse events. Any idea how to disable just keyboards events ?

Body:
I am working on a PyQt5 based app. My GUI shows 21 buttons: letters from A to Z, I use them as input for

the main algorithm. I would like to be able to input the letters from the keyboard too.

So far following Get printable name of any QKeyEvent key value     I am able to achieve this.

Only problem is how to disable keyPressevent , and re-enable it after my app intro screen,

like I do with my letters button doing:

self.groupBox.hide() and re-enabling them after pressing the start new game

button. with self.groupBox.show()

I wrote down in my answer the solution to my problem provided by musicamante. Still I would like to now if is there a way to disable PyQt5 keyboard event processing in a way that my :

def keyPressEvent(self, event):
         print(keyevent_to_string(self, event))
         print('self.letters : ',self.letters)
         print('self.letters_guessed : ',self.letters_guessed )
         if keyevent_to_string(self, event) in self.letters:
                    print('inininininini'*5)
                    self.printo(keyevent_to_string(self, event))

code piece sits there but doesnt produce any result when I press a keyboard key ?

I understood that KeyPressEvent is the handler for QEvent.KeyPress, so is there a way to disable/delete/remove  QEvent.KeyPress class in Pyqt5 ?

Body:
following musicamante suggestions I modified my code with:

def keyPressEvent(self, event):
    if self.keyonoff:
         print(keyevent_to_string(self, event))
         print('self.letters : ',self.letters)
         print('self.letters_guessed : ',self.letters_guessed )
         if keyevent_to_string(self, event) in self.letters:
                    print('inininininini'*5)
                    self.printo(keyevent_to_string(self, event))

then switched

self.keyonoff = True and   self.keyonoff = False

as needed by my code.

I am getting what I was looking for, not sure if there is another way to
do that: 'I understood that KeyPressEvent is the handler for QEvent.KeyPress, so is there a way to disable/delete/remove QEvent.KeyPress class in Pyqt5 ?'

Code below is not mine is just a keyPressEvent reimplamantation usefull to my purpose

from PyQt5.QtCore import Qt

def keyevent_to_string(self, event):
    self.keymap = {}
    for self.key, value in vars(Qt).items():
        if isinstance(value, Qt.Key):
            self.keymap[value] = self.key.partition('_')[2]

    self.modmap = {
        Qt.ControlModifier: self.keymap[Qt.Key_Control],
        Qt.AltModifier: self.keymap[Qt.Key_Alt],
        Qt.ShiftModifier: self.keymap[Qt.Key_Shift],
        Qt.MetaModifier: self.keymap[Qt.Key_Meta],
        Qt.GroupSwitchModifier: self.keymap[Qt.Key_AltGr],
        Qt.KeypadModifier: self.keymap[Qt.Key_NumLock],
        }
    self.sequence = []
    for modifier, text in self.modmap.items():
        if event.modifiers() & modifier:
            self.sequence.append(text)
    self.key = self.keymap.get(event.key(), event.text())
    if self.key not in self.sequence:
        self.sequence.append(self.key)
    return '+'.join(self.sequence)

From Get printable name of any QKeyEvent key value

Edited Edited Edited

More on this hopefully I'll get my right to ask questions back:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 29 10:49:58 2020

@author: Pietro
"""

import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import Qt, QEvent

class Window(QtWidgets.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.button = QtWidgets.QPushButton("activate", self)
        self.button2 = QtWidgets.QPushButton("deactivate", self)
        self.button.move(0,0)
        self.button2.move(100,100)
        self.button2.clicked.connect(self.deactivated)
        self.button.clicked.connect(self.activated)

    def activated(self):
        print('attivato')
        QWidget.setEnabled(self,True)

    def deactivated(self):
        print('deattivato')
        QWidget.setEnabled(self,False)

    def keyevent_to_string(self, event):
        self.keymap = {}
        for self.key, value in vars(Qt).items():
            if isinstance(value, Qt.Key):
                self.keymap[value] = self.key.partition('_')[2]

        self.modmap = {
            Qt.ControlModifier: self.keymap[Qt.Key_Control],
            Qt.AltModifier: self.keymap[Qt.Key_Alt],
            Qt.ShiftModifier: self.keymap[Qt.Key_Shift],
            Qt.MetaModifier: self.keymap[Qt.Key_Meta],
            Qt.GroupSwitchModifier: self.keymap[Qt.Key_AltGr],
            Qt.KeypadModifier: self.keymap[Qt.Key_NumLock],
            }
        self.sequence = []
        for modifier, text in self.modmap.items():
            if event.modifiers() & modifier:
                self.sequence.append(text)
        self.key = self.keymap.get(event.key(), event.text())
        if self.key not in self.sequence:
            self.sequence.append(self.key)
        return '+'.join(self.sequence)

    def keyPressEvent(self, event):
            print(self.keyevent_to_string(event))

if __name__ == '__main__':

    app = QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 300, 200)
    window.show()
    sys.exit(app.exec_())

I ended up here

QWidget.setEnabled(False)

apparently disable both keyboard and mouse events. Any idea how to disable just keyboards events ?


问:
Random number generator with conditions - Python
I am new to Python and trying to generate 5 numbers with 2 conditions:

There must be 3 even and 2 odd numbers

From those 5 numbers 3 must be low (1,51) and 2 high (51,100). Which number will be low or high is not of interest.

I have managed to solve the first part:

```<code>import random
rand_even = random.sample(range(0, 100, 2), 3)
rand_odd = random.sample(range(1, 100, 2), 2)
rand_total = rand_even,rand_odd
print(rand_total)
</code>```

Obviously this is not getting me anywhere
For the second part i thought i could use something like:

```<code>rand_low = random.sample(range(0, 51), 3)
rand_high = random.sample(range(51,100), 2)
</code>```

But obviously this is not the way as i am getting more than 5 numbers.

Any help would be appriciated.
Thank you

答:
```<code>from random import seed
from random import random
import math
odd=0
even=0
below_50=0
above_50=0
numbers=[]
#Providing seed value to random()
seed(2)
while len(numbers)<5:
    num=math.floor(random()*100)
    #checking to maintain unique elements
    if num not in numbers:
        if num%2==0 and even<3:
            if num>50 and above_50<2:
                even+=1
                above_50+=1
                numbers.append(num)
            elif num<50 and below_50<3:
                even+=1
                below_50+=1
                numbers.append(num)
        elif num%2==1 and odd<2:
            if num>50 and above_50<2:
                odd+=1
                above_50+=1
                numbers.append(num)
            elif num<50 and below_50<3:
                odd+=1
                below_50+=1
                numbers.append(num)
</code>```

Body:
I am new to Python and trying to generate 5 numbers with 2 conditions:

There must be 3 even and 2 odd numbers

From those 5 numbers 3 must be low (1,51) and 2 high (51,100). Which number will be low or high is not of interest.

I have managed to solve the first part:

import random
rand_even = random.sample(range(0, 100, 2), 3)
rand_odd = random.sample(range(1, 100, 2), 2)
rand_total = rand_even,rand_odd
print(rand_total)

Obviously this is not getting me anywhere
For the second part i thought i could use something like:

rand_low = random.sample(range(0, 51), 3)
rand_high = random.sample(range(51,100), 2)

But obviously this is not the way as i am getting more than 5 numbers.

Any help would be appriciated.
Thank you


问:
How to upload a blob form in Javascript to Django backend
I have an audio blob with the following code I'm looking to send to a form with javascript

```<code>function sendData(blob) {
  let fd = new FormData;
  fd.append('fname', 'test.wav');
  fd.append("recording", blob);
  let token = '{{csrf_token}}';

  $.ajax({
    url: 'landing/submit/',
    type: 'POST',
    headers: { 'X-CSRFToken': token },
    data: fd,
    cache: false,
    processData: false, // essential
    contentType: false, // essential, application/pdf doesn't work.
    enctype: 'multipart/form-data',
  });
}
</code>```

I am trying to send this to a django form, but i'm getting a 403 error. Here is the view it's being sent to:

```<code>views.py

def post_new(request):
    if request.method == 'POST':
        form = PostAudio(request.POST, request.FILES)
        if form.is_valid():

            form.save()
            return redirect('landing-home')
    else:
        form = PostAudio()
    return render(request, 'landing/submit.html', {'form': form})
</code>```

What am I missing? Most other folks posting online say this has to do with not using CSRF tokens, but I included them in my headers.

答:
Try using the @csrf_token decorator in django . I had a  similar problem that solved it.

try this

```<code>@csrf_exempt
def post_new(request):

</code>```

Body:
I have an audio blob with the following code I'm looking to send to a form with javascript

function sendData(blob) {
  let fd = new FormData;
  fd.append('fname', 'test.wav');
  fd.append("recording", blob);
  let token = '{{csrf_token}}';

  $.ajax({
    url: 'landing/submit/',
    type: 'POST',
    headers: { 'X-CSRFToken': token },
    data: fd,
    cache: false,
    processData: false, // essential
    contentType: false, // essential, application/pdf doesn't work.
    enctype: 'multipart/form-data',
  });
}

I am trying to send this to a django form, but i'm getting a 403 error. Here is the view it's being sent to:

views.py

def post_new(request):
    if request.method == 'POST':
        form = PostAudio(request.POST, request.FILES)
        if form.is_valid():

            form.save()
            return redirect('landing-home')
    else:
        form = PostAudio()
    return render(request, 'landing/submit.html', {'form': form})

What am I missing? Most other folks posting online say this has to do with not using CSRF tokens, but I included them in my headers.

Body:
Try using the @csrf_token decorator in django . I had a  similar problem that solved it.

try this

@csrf_exempt
def post_new(request):


问:
How to display/print unpacked type as hexadecimal in SystemVerilog?
I have an unpacked int array:

```<code>int wanna_print [];
wanna_print = new[1];
</code>```

It can be printed like this:

```<code>$display("in hex: c86E [in dec: 51310] == %p", wanna_print[0]);
</code>```

It will print it in decimal, but I need it in hexadecimal.

I tried %0h, %h instead of %p, but it gives this error:

Argument number 2 is an unpacked type, and may only be printed with the '%p' format.

How can I print it in hexadecimal?
Can %p maybe somehow extended?

I tried $sformatf too, but it behaves the same.

答:
Using $displayh works for me with VCS:

```<code>module tb;

int wanna_print [];

initial begin
    wanna_print = new[1];
    wanna_print[0] = 51310;
    $displayh("in hex: c86E [in dec: 51310] == %p", wanna_print[0]);
end

endmodule
</code>```

Outputs:

```<code>in hex: c86E [in dec: 51310] == 0000c86e
</code>```

$displayh is described in IEEE Std 1800-2017, section 21.2.1.2 Format specifications.

I get a compile error with Cadence, however.

Body:
I have an unpacked int array:

int wanna_print [];
wanna_print = new[1];

It can be printed like this:

$display("in hex: c86E [in dec: 51310] == %p", wanna_print[0]);

It will print it in decimal, but I need it in hexadecimal.

I tried %0h, %h instead of %p, but it gives this error:

Argument number 2 is an unpacked type, and may only be printed with the '%p' format.

How can I print it in hexadecimal?
Can %p maybe somehow extended?

I tried $sformatf too, but it behaves the same.

Body:
Using $displayh works for me with VCS:

module tb;

int wanna_print [];

initial begin
    wanna_print = new[1];
    wanna_print[0] = 51310;
    $displayh("in hex: c86E [in dec: 51310] == %p", wanna_print[0]);
end

endmodule

Outputs:

in hex: c86E [in dec: 51310] == 0000c86e

$displayh is described in IEEE Std 1800-2017, section 21.2.1.2 Format specifications.

I get a compile error with Cadence, however.


问:
Wrap the IsNumeric function of SqlFunctions
I'd like to wrap the SqlFunctions.IsNumeric function so that I can use it in other layer without the need to add reference to System.Data (no matter why).

Here is what I did -
In my Repository Interfaces:

```<code>public interface IUtils
{
    Expression<Func<bool>> IsNumeric(string str);
}
</code>```

In my ef layer:

```<code>public class EFUtils : IUtils
{
    public Expression<Func<bool>> IsNumeric(string str)
    {
        return () => SqlFunctions.IsNumeric(str) == 1;
    }
}
</code>```

In my business later:

```<code>public class RepositoryUtils
{
    protected static IUtils Utils { get; set; }

    static RepositoryUtils()
    {
        Utils = ObjectFactory.GetInstance<IUtils>(); //Using structureMap
    }

    public static Expression<Func< bool>> IsNumeric(string str)
    {
        return Utils.IsNumeric(str);
    }
}
</code>```

The problem is that now, after I exposed the method, I don't really know how to use it..

It is something like:

```<code>Customers.OrderBy(x=>**Order by is numeric on x.Name);
</code>```

Any idea?

答:
Something like that ?</p>

```<code>Customers.OrderBy(x=>RepositoryUtils.IsNumeric(x.Name));
</code>```

Body:
I'd like to wrap the SqlFunctions.IsNumeric function so that I can use it in other layer without the need to add reference to System.Data (no matter why).

Here is what I did -
In my Repository Interfaces:

public interface IUtils
{
    Expression<Func<bool>> IsNumeric(string str);
}

In my ef layer:

public class EFUtils : IUtils
{
    public Expression<Func<bool>> IsNumeric(string str)
    {
        return () => SqlFunctions.IsNumeric(str) == 1;
    }
}

In my business later:

public class RepositoryUtils
{
    protected static IUtils Utils { get; set; }

    static RepositoryUtils()
    {
        Utils = ObjectFactory.GetInstance<IUtils>(); //Using structureMap
    }

    public static Expression<Func< bool>> IsNumeric(string str)
    {
        return Utils.IsNumeric(str);
    }
}

The problem is that now, after I exposed the method, I don't really know how to use it..

It is something like:

Customers.OrderBy(x=>**Order by is numeric on x.Name);

Any idea?

Body:
Something like that ?

Customers.OrderBy(x=>RepositoryUtils.IsNumeric(x.Name));