问:
Advantage of switching from ASP.NET to bread & butter HTML/jQuery
I have been getting more and more sick of all the quirks about control ids, trying to get your data in serverside (based on client-side events). I seem to spend more time fighting with controls in asp.net, that I think it takes me more time than I gain by using it.

I was thinking about using plain html/javascript with jQuery and a web service that returns json for the data.

The only thing I think I would miss from webforms is the MasterPages, the session management, authentication based on windows login and possibly validators(although they have some quirks too). (In fact, maybe not for sessions and auth, but I have never developped webservices)

Is there something wrong with the way
I am thinking about this, or
something I didn't think about ?

Are there things in asp.net that you
think I will miss ?

Has anyone done this before and wants to share experience ?

Please, also take note, that I only have the Framework 2.0 available for development.

Edit: The kind of things giving me troubles in asp.net that makes me wonder for the switch:

Here is a sample of a page giving me problems.

There is a tree table (master / details)

You can edit fields on each child row.

When you press the save button, the data from the group row must be updated (just data from a select, no modification in database), as
the data from the child row.

I don't want to refresh the whole page because the displayed records are based from search criterias.

The Master / Details are generated using Repeaters

Trying to update a record from code behind is really quirky, and still have no clue about updating the display.

Using jQuery and a web service, my guess would be that i could update directly to the database, request what I want to be displayed and just update that record. This is the kind of things that make me wonder if asp.net is just getting in my way.

```

 ________________________________________________________________________
| -  Some             Details           About            Group           |
|________________________________________________________________________|
    |¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    |_______________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|

```

Edit2:
The problem I have about ASP.NET is not related to ajax. Yes, I use jQuery to make the interfaces more dynamic like showing / hiding the search section when not needed and collapsing details from the tree, but this is all I do with it.

What bothers me is that if I want to check which button has been clicked in this example, I have to use some tricks that feel a bit haky.

If you want to use databound comboboxes in a repeater, you have to use codebehind to set the selected value, it will be a pain to retreive the data selected.

Next, if you want to check what data was modified, you have to save the datatable in the viewstate, read data from all controls in the repeater, then compare with the datatable to make an update. This is this kind of things that bother me with asp.net.

答:
Creating a table in JavaScript/JQuery is not the most elegant code either.  So I would miss the Repeater control.

Also, there are workarounds for the ClientId issue.

I have a lot of code in my page that looks like this:

var myTextBoxId = '<%=MyTextBox.ClientID %>';

If there are a bunch of controls I need the client ID for I will put them in an object

var myControlIds = { MyTextBoxID: '<%=MyTextBox.ClientID %>' };

Another work around is to put specific css classes on your controls or custom attribute name/values.

So your textbox could be:

And my final trick is to use the "Ends With" attribute finder.

So your JQuery, instead of

$("#MyTextBox")  // doesn't work because of client id mangalling

instead do:
$("[id $=MyTextBox]")

This searches the 'id' attribute of all controls to find one with a value that ends with "MyTextBox"

OwnerDisplayName: Martin

ContentLicense: CC BY-SA 2.5

Body:
I have been getting more and more sick of all the quirks about control ids, trying to get your data in serverside (based on client-side events). I seem to spend more time fighting with controls in asp.net, that I think it takes me more time than I gain by using it.

I was thinking about using plain html/javascript with jQuery and a web service that returns json for the data.

The only thing I think I would miss from webforms is the MasterPages, the session management, authentication based on windows login and possibly validators(although they have some quirks too). (In fact, maybe not for sessions and auth, but I have never developped webservices)

Is there something wrong with the way
I am thinking about this, or
something I didn't think about ?

Are there things in asp.net that you
think I will miss ?

Has anyone done this before and wants to share experience ?

Please, also take note, that I only have the Framework 2.0 available for development.

Edit: The kind of things giving me troubles in asp.net that makes me wonder for the switch:

Here is a sample of a page giving me problems.

There is a tree table (master / details)

You can edit fields on each child row.

When you press the save button, the data from the group row must be updated (just data from a select, no modification in database), as
the data from the child row.

I don't want to refresh the whole page because the displayed records are based from search criterias.

The Master / Details are generated using Repeaters

Trying to update a record from code behind is really quirky, and still have no clue about updating the display.

Using jQuery and a web service, my guess would be that i could update directly to the database, request what I want to be displayed and just update that record. This is the kind of things that make me wonder if asp.net is just getting in my way.

 ________________________________________________________________________
| -  Some             Details           About            Group           |
|________________________________________________________________________|
    |¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    |_______________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|

Edit2:
The problem I have about ASP.NET is not related to ajax. Yes, I use jQuery to make the interfaces more dynamic like showing / hiding the search section when not needed and collapsing details from the tree, but this is all I do with it.

What bothers me is that if I want to check which button has been clicked in this example, I have to use some tricks that feel a bit haky.

If you want to use databound comboboxes in a repeater, you have to use codebehind to set the selected value, it will be a pain to retreive the data selected.

Next, if you want to check what data was modified, you have to save the datatable in the viewstate, read data from all controls in the repeater, then compare with the datatable to make an update. This is this kind of things that bother me with asp.net.

LastEditorDisplayName: Martin

OwnerDisplayName: Chris Brandsma


来源: stackexchange

问:
Command not found after npm install in zsh
I'm having some problems installing vows via npm in zsh. Here's what I get. I tried installing it with and without the -g option. Do you have any idea what's wrong here?</p>
```<code>[❤  ~/Desktop/sauce-node-demo:master] npm install -g vows
npm http GET https://registry.npmjs.org/vows
npm http 304 https://registry.npmjs.org/vows
npm http GET https://registry.npmjs.org/eyes
npm http GET https://registry.npmjs.org/diff
npm http 304 https://registry.npmjs.org/eyes
npm http 304 https://registry.npmjs.org/diff
/usr/local/share/npm/bin/vows -> /usr/local/share/npm/lib/node_modules/vows/bin/vows
vows@0.6.4 /usr/local/share/npm/lib/node_modules/vows
├── eyes@0.1.8
└── diff@1.0.3
[❤  ~/Desktop/sauce-node-demo:master] vows
zsh: command not found: vows
</code>```

答:
Sometimes simple things work. Uninstalling node and installing again worked for me.</p>
```<code>brew uninstall node
brew install node
npm update
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having some problems installing vows via npm in zsh. Here's what I get. I tried installing it with and without the -g option. Do you have any idea what's wrong here?

[❤  ~/Desktop/sauce-node-demo:master] npm install -g vows
npm http GET https://registry.npmjs.org/vows
npm http 304 https://registry.npmjs.org/vows
npm http GET https://registry.npmjs.org/eyes
npm http GET https://registry.npmjs.org/diff
npm http 304 https://registry.npmjs.org/eyes
npm http 304 https://registry.npmjs.org/diff
/usr/local/share/npm/bin/vows -> /usr/local/share/npm/lib/node_modules/vows/bin/vows
vows@0.6.4 /usr/local/share/npm/lib/node_modules/vows
├── eyes@0.1.8
└── diff@1.0.3
[❤  ~/Desktop/sauce-node-demo:master] vows
zsh: command not found: vows

Body:
Sometimes simple things work. Uninstalling node and installing again worked for me.

brew uninstall node
brew install node
npm update


问:
Extracting values containing certain string froma list of dictionaries
I have the following list of dictionaries:

```<code>[{'symbol': 'ETHBTC', 'price': '0.07216700'},
 {'symbol': 'LTCBTC', 'price': '0.00299400'},
 {'symbol': 'BNBBTC', 'price': '0.00999600'},
 {'symbol': 'NEOBTC', 'price': '0.00054300'},
 {'symbol': 'QTUMETH', 'price': '0.00238900'},
 {'symbol': 'EOSETH', 'price': '0.00084200'},
 {'symbol': 'SNTETH', 'price': '0.00002096'},
 {'symbol': 'BNTETH', 'price': '0.00089400'},
 {'symbol': 'BCCBTC', 'price': '0.07908100'},
 {'symbol': 'GASBTC', 'price': '0.00012830'},
 {'symbol': 'BNBETH', 'price': '0.13850000'},
 {'symbol': 'BTCUSDT', 'price': '42580.58000000'},
 {'symbol': 'ETHUSDT', 'price': '3072.66000000'},
 {'symbol': 'HSRBTC', 'price': '0.00041400'},
 {'symbol': 'OAXETH', 'price': '0.00017780'},
 {'symbol': 'DNTETH', 'price': '0.00002801'},
 {'symbol': 'MCOETH', 'price': '0.00577200'},
 {'symbol': 'ICNETH', 'price': '0.00166300'},
 {'symbol': 'MCOBTC', 'price': '0.00021140'}]
</code>```

How can I extract from it all strings having 'BTC' as a part of them?
Also can I filter them while extracting to drop some predetermined?

Thanks

Body:
I have the following list of dictionaries:

[{'symbol': 'ETHBTC', 'price': '0.07216700'},
 {'symbol': 'LTCBTC', 'price': '0.00299400'},
 {'symbol': 'BNBBTC', 'price': '0.00999600'},
 {'symbol': 'NEOBTC', 'price': '0.00054300'},
 {'symbol': 'QTUMETH', 'price': '0.00238900'},
 {'symbol': 'EOSETH', 'price': '0.00084200'},
 {'symbol': 'SNTETH', 'price': '0.00002096'},
 {'symbol': 'BNTETH', 'price': '0.00089400'},
 {'symbol': 'BCCBTC', 'price': '0.07908100'},
 {'symbol': 'GASBTC', 'price': '0.00012830'},
 {'symbol': 'BNBETH', 'price': '0.13850000'},
 {'symbol': 'BTCUSDT', 'price': '42580.58000000'},
 {'symbol': 'ETHUSDT', 'price': '3072.66000000'},
 {'symbol': 'HSRBTC', 'price': '0.00041400'},
 {'symbol': 'OAXETH', 'price': '0.00017780'},
 {'symbol': 'DNTETH', 'price': '0.00002801'},
 {'symbol': 'MCOETH', 'price': '0.00577200'},
 {'symbol': 'ICNETH', 'price': '0.00166300'},
 {'symbol': 'MCOBTC', 'price': '0.00021140'}]

How can I extract from it all strings having 'BTC' as a part of them?
Also can I filter them while extracting to drop some predetermined?

Thanks

Body:
You can also use a generator

list = [{'symbol': 'ETHBTC', 'price': '0.07216700'}, {'symbol': 'LTCBTC', 'price': '0.00299400'}, {'symbol': 'BNBBTC', 'price': '0.00999600'}, {'symbol': 'NEOBTC', 'price': '0.00054300'}, {'symbol': 'QTUMETH', 'price': '0.00238900'}, {'symbol': 'EOSETH', 'price': '0.00084200'}, {'symbol': 'SNTETH', 'price': '0.00002096'}, {'symbol': 'BNTETH', 'price': '0.00089400'}, {'symbol': 'BCCBTC', 'price': '0.07908100'}, {'symbol': 'GASBTC', 'price': '0.00012830'}, {'symbol': 'BNBETH', 'price': '0.13850000'}, {'symbol': 'BTCUSDT', 'price': '42580.58000000'}, {'symbol': 'ETHUSDT', 'price': '3072.66000000'}, {'symbol': 'HSRBTC', 'price': '0.00041400'}, {'symbol': 'OAXETH', 'price': '0.00017780'}, {'symbol': 'DNTETH', 'price': '0.00002801'}, {'symbol': 'MCOETH', 'price': '0.00577200'}, {'symbol': 'ICNETH', 'price': '0.00166300'}, {'symbol': 'MCOBTC', 'price': '0.00021140'}]
try:
    output = (x for x in list if 'BTC' in x['symbol'])
    for i in output:
        print(i)
except StopIteration:
    pass


问:
Python states Key Error when creating a new variable in a data frame
I am in the process of cleaning many variables(columns in a data frame) to perform text analysis on said variables.

I have a data frame called econ_data.

Here I create a 'list' of all the variables that need to be transformed, for example transforming all text to lower case and removing stop words.

```<code>open_responses = ['choice_open_1_f', 'choice_open_1_m', 'choice_open_2_f ', 'choice_open_2_m']
</code>```

Then I want to create a for loop that cleans up these variables so that I can perform text analysis.

```<code>for z in open_responses:
    econ_data[z] = econ_data[z].astype(str).str.replace('/',' ')
    econ_data[z] = econ_data[z].apply(lambda x: " ".join(x.lower() for x in x.split()))
    locals()[econ_data[f"{z}_stop"]] = econ_data[f"{z}"].apply(lambda x: " ".join(x for x in x.split() if x not in stop_words))

</code>```

The first 2 lines in the for loop work, however, when I try to add a new variable to the data frame when stop words have been removed from the entry, I receive a Key Error message ("KeyError: 'choice_open_1_f_stop'").

Please can someone explain how I can solve this issue?

Many thanks!

答:
You get an error because you are trying to get value of locals()[econ_data[f"{z}_stop"]] which is not defined.
You should do a simple assignment econ_data[f"{z}_stop"] =  which dataframe handles and creates a key that does not exist if try to assign to it.

Body:
I am in the process of cleaning many variables(columns in a data frame) to perform text analysis on said variables.

I have a data frame called econ_data.

Here I create a 'list' of all the variables that need to be transformed, for example transforming all text to lower case and removing stop words.

open_responses = ['choice_open_1_f', 'choice_open_1_m', 'choice_open_2_f ', 'choice_open_2_m']

Then I want to create a for loop that cleans up these variables so that I can perform text analysis.

for z in open_responses:
    econ_data[z] = econ_data[z].astype(str).str.replace('/',' ')
    econ_data[z] = econ_data[z].apply(lambda x: " ".join(x.lower() for x in x.split()))
    locals()[econ_data[f"{z}_stop"]] = econ_data[f"{z}"].apply(lambda x: " ".join(x for x in x.split() if x not in stop_words))

The first 2 lines in the for loop work, however, when I try to add a new variable to the data frame when stop words have been removed from the entry, I receive a Key Error message ("KeyError: 'choice_open_1_f_stop'").

Please can someone explain how I can solve this issue?

Many thanks!


问:
How to call parent methods in Java/Groovy
I'm new to Java and groovy , I mostly code in Python.I'm trying to understand why the code doesn't work.
The error i'm getting is
groovy.lang.MissingMethodException: No signature of method: static HelloWorld.TestingProduct() is applicable for argument types: () values: []

I've been tasked to add eventdate as sysdate on a project, and I'm just trying to understand how to add it by testing locally

```<code>import groovy.transform.ToString
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter

public class HelloWorld{

     public static void main(String[] args){
        String testin = TestingProduct().Inventory()
        System.out.println(testin);
     }
}

class Parent {

   private String setDateNow() {
        OffsetDateTime now = OffsetDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
        return formatter.format(now);
    }
}

class TestingProduct extends Parent {
   private static ProductInventoryEvent Inventory(){
      def invent = new ProductInventoryEvent(
         productId:'1',
         productIdType:'2',
         eventType:'3',
         eventDate: setDateNow(),
      )
      return invent
   }
}

@Canonical()
@ToString(includeNames = true)
class ProductInventoryEvent {
    String productId
    String productIdType
    String eventType
    String eventDate

}
</code>```

答:
There are few things that are wrong in your code. Let me first start with the HelloWorld class.

You are trying to access/call static method Inventory of the TestingProduct in a wrong way. In order to access static methods you do not need any object instance of that class. So, instead of TestingProduct().Inventory() you should use TestingProduct.Inventory().

Second thing is that, your method Inventory() is returning ProductInventoryEvent and not a string. So you should change the type of the variable that you want to initialize. Here is how the code should look like:

```<code>public class HelloWorld {
    public static void main(String[] args){
      ProductInventoryEvent testin = TestingProduct.Inventory();
      System.out.println(testin);
    }
}
</code>```

Another thing that you should change is the access modifier of the Inventory() method in the TestingProduct class. Instead of private, you should use package private or public access modifier. So the code should look like:

```<code>public class TestingProduct {
   static ProductInventoryEvent Inventory(){
      def invent = new ProductInventoryEvent(
            productId:'1',
            productIdType:'2',
            eventType:'3',
            eventDate: setDateNow(),
      )
      return invent;
   }
}
</code>```

Body:
I'm new to Java and groovy , I mostly code in Python.I'm trying to understand why the code doesn't work.
The error i'm getting is
groovy.lang.MissingMethodException: No signature of method: static HelloWorld.TestingProduct() is applicable for argument types: () values: []

I've been tasked to add eventdate as sysdate on a project, and I'm just trying to understand how to add it by testing locally

import groovy.transform.ToString
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter

public class HelloWorld{

     public static void main(String[] args){
        String testin = TestingProduct().Inventory()
        System.out.println(testin);
     }
}

class Parent {

   private String setDateNow() {
        OffsetDateTime now = OffsetDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
        return formatter.format(now);
    }
}

class TestingProduct extends Parent {
   private static ProductInventoryEvent Inventory(){
      def invent = new ProductInventoryEvent(
         productId:'1',
         productIdType:'2',
         eventType:'3',
         eventDate: setDateNow(),
      )
      return invent
   }
}

@Canonical()
@ToString(includeNames = true)
class ProductInventoryEvent {
    String productId
    String productIdType
    String eventType
    String eventDate

}

Body:
There are few things that are wrong in your code. Let me first start with the HelloWorld class.

You are trying to access/call static method Inventory of the TestingProduct in a wrong way. In order to access static methods you do not need any object instance of that class. So, instead of TestingProduct().Inventory() you should use TestingProduct.Inventory().

Second thing is that, your method Inventory() is returning ProductInventoryEvent and not a string. So you should change the type of the variable that you want to initialize. Here is how the code should look like:

public class HelloWorld {
    public static void main(String[] args){
      ProductInventoryEvent testin = TestingProduct.Inventory();
      System.out.println(testin);
    }
}

Another thing that you should change is the access modifier of the Inventory() method in the TestingProduct class. Instead of private, you should use package private or public access modifier. So the code should look like:

public class TestingProduct {
   static ProductInventoryEvent Inventory(){
      def invent = new ProductInventoryEvent(
            productId:'1',
            productIdType:'2',
            eventType:'3',
            eventDate: setDateNow(),
      )
      return invent;
   }
}


问:
How do I create a subfolder with a specific name? (the date of data extraction)
I've created a variable "dt" which is the date of today.

Now I want to create a subfolder which name should be (Partial Update + str(dt)

```<code>dt = datetime.datetime.now()
subfolder_name = ("Partial Update - " + str(dt))

os.makedirs(os.path.join("H:\......\VICTOR KURC\",subfolder_name))
</code>```

My problem is that the subfolder is not being created with the name that is need, only with a standard name (using stantard lines of code).

How do I fix it?

答:
```<code>import os
from datetime import datetime

# place yourself in the same directory of the script you're running
os.chdir(os.path.dirname(__file__))

# format date without special characters
dt = datetime.now().strftime("%Y%m%d_%H%M%S")
subfolder_name = f"Partial Update - {dt}"

# if folder doesn't exist, create it
if not os.path.isdir(subfolder_name):
    os.mkdir(subfolder_name)
</code>```

Body:
I've created a variable "dt" which is the date of today.

Now I want to create a subfolder which name should be (Partial Update + str(dt)

dt = datetime.datetime.now()
subfolder_name = ("Partial Update - " + str(dt))

os.makedirs(os.path.join("H:\......\VICTOR KURC\",subfolder_name))

My problem is that the subfolder is not being created with the name that is need, only with a standard name (using stantard lines of code).

How do I fix it?


问:
How to keep the Lived documents in MongoDB as per the TTL index?
I know that the TTL index in MongoDB set a time to live for its documents. When they live for the specified time then those documents gets deleted. So what if I want to archive those documents without losing them. is there any way to do it?
I am sorry If I asked it in the wrong place.</p>

答: You can use a change stream to capture documents inserted and archive them somewhere. See also this answer on stackoverflow.</p>


问:
Not able to launch Flutter app on Android device
I am trying to launch my Flutter app on an Android device, I was able just until yesterday, but suddenly today I am getting this error when launching it:

```<code>Launching lib/main.dart on Moto G 5S in debug mode...
Running Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* What went wrong:
Could not open settings remapped class cache for 7yvt6la2007dno98lt3rzbguf (/Users/modestovascofornas/.gradle/caches/6.3/scripts-remapped/settings_bwqg3axqhj874bje5e9od2vqv/7yvt6la2007dno98lt3rzbguf/settingsdeec0faa97453e2ce860d75e6bf1604b).
> Could not open settings generic class cache for settings file '/Users/modestovascofornas/desarrollo/DESARROLLO 2022 SSD-2/2022-G2-CAPENERGY-FLUTTER-PROFESIONAL/FLUTTER/flutter_capenergy/android/settings.gradle' (/Users/modestovascofornas/.gradle/caches/6.3/scripts/7yvt6la2007dno98lt3rzbguf/settings/settingsdeec0faa97453e2ce860d75e6bf1604b).
   > BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 61

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 24s
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

I have tried deleting .gradle folder, but not working

EDIT

This is my ~/.zshrc file

```<code>export PATH=/Users/modestovascofornas/flutter/bin:$PATH
export PATH=/Users/modestovascofornas/flutter/.pub-cache/bin:$PATH
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk/Contents/Home
</code>```

答:
have you tried ./gradlew clean after you deleted .gradle ?

In Android Studio i've found it is always best to configure variables through the project structure dialog. Make sure you configured gradle, JDK & SDK for the project correctly there because the last error indicates a conflict with java/gradle version.

Try upgrading gradle via gradle-wrapper.properties:

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip
</code>```

and be sure that you are running java version 11 or lower - whatever version is Android Studio default.

edit: After seeing your edit, i would almost guarantee that the issue is with jdk-17.0.2.jdk
be sure to use the bundled JDK and configure the path through the project structure dialog.

Body:
I am trying to launch my Flutter app on an Android device, I was able just until yesterday, but suddenly today I am getting this error when launching it:

Launching lib/main.dart on Moto G 5S in debug mode...
Running Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* What went wrong:
Could not open settings remapped class cache for 7yvt6la2007dno98lt3rzbguf (/Users/modestovascofornas/.gradle/caches/6.3/scripts-remapped/settings_bwqg3axqhj874bje5e9od2vqv/7yvt6la2007dno98lt3rzbguf/settingsdeec0faa97453e2ce860d75e6bf1604b).
> Could not open settings generic class cache for settings file '/Users/modestovascofornas/desarrollo/DESARROLLO 2022 SSD-2/2022-G2-CAPENERGY-FLUTTER-PROFESIONAL/FLUTTER/flutter_capenergy/android/settings.gradle' (/Users/modestovascofornas/.gradle/caches/6.3/scripts/7yvt6la2007dno98lt3rzbguf/settings/settingsdeec0faa97453e2ce860d75e6bf1604b).
   > BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 61

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 24s
Exception: Gradle task assembleDebug failed with exit code 1

I have tried deleting .gradle folder, but not working

EDIT

This is my ~/.zshrc file

export PATH=/Users/modestovascofornas/flutter/bin:$PATH
export PATH=/Users/modestovascofornas/flutter/.pub-cache/bin:$PATH
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk/Contents/Home

Body:
have you tried ./gradlew clean after you deleted .gradle ?

In Android Studio i've found it is always best to configure variables through the project structure dialog. Make sure you configured gradle, JDK & SDK for the project correctly there because the last error indicates a conflict with java/gradle version.

Try upgrading gradle via gradle-wrapper.properties:

distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip

and be sure that you are running java version 11 or lower - whatever version is Android Studio default.

edit: After seeing your edit, i would almost guarantee that the issue is with jdk-17.0.2.jdk
be sure to use the bundled JDK and configure the path through the project structure dialog.


问:
How can I cut several sound files using a script?
I am new to Praat and wondering, if someone can help me to find out, how I can cut all my sound files with a script or anything.
I have like 100 sound files I need for my research. They all have a different length, some are 1 min and others are 3 min long.
I would like to have only the first 22 sec from each sound file.

Thanks in advance!
Kind regards
Olga

答:
The first step is to construct a script that extracts the initial 22 seconds of some specific sound object that is already open. In general, the easiest way to at least start a script is to do a thing manually once, and after you've done that, in a Praat script window, copy the command history (with ctrl-h) to see what the underlying commands are. The manual approach is to look for "Extract part" under "Convert", which corresponds to the command

```<code>Extract part: 0, 22, "rectangular", 1, "no"
</code>```

There is also a command to save a file as a wav file, so you would add that to the core of the script.

Then you need to add a loop that does this a number of times, to different files. You will (probably) need a file with wav file names, and some system for naming the output files, for example if you have "input1.wav", you might want to call the cut-down version "output1.wav". This implies some computation of the output file name based on the input file name, so you need to get familiar with how string manipulation works in Praat.

If you have that much sorted out, then the basic logic is

```<code>get next input file name file
compute output name
open the input file
extract from that file
save the extracted file
remove the extract
remove the original
loop until no more files
</code>```

I would plan on spending a lot of time trying to understand simple things like string variables, or object selection. I left out explicitly selecting objects since it is not necessarily required, but every command works on "the selected object" and it's easy to lose track of what is selected.

Another common approach is to beg a colleague to write it for you.

Body:
The first step is to construct a script that extracts the initial 22 seconds of some specific sound object that is already open. In general, the easiest way to at least start a script is to do a thing manually once, and after you've done that, in a Praat script window, copy the command history (with ctrl-h) to see what the underlying commands are. The manual approach is to look for "Extract part" under "Convert", which corresponds to the command

Extract part: 0, 22, "rectangular", 1, "no"

There is also a command to save a file as a wav file, so you would add that to the core of the script.

Then you need to add a loop that does this a number of times, to different files. You will (probably) need a file with wav file names, and some system for naming the output files, for example if you have "input1.wav", you might want to call the cut-down version "output1.wav". This implies some computation of the output file name based on the input file name, so you need to get familiar with how string manipulation works in Praat.

If you have that much sorted out, then the basic logic is

get next input file name file
compute output name
open the input file
extract from that file
save the extracted file
remove the extract
remove the original
loop until no more files

I would plan on spending a lot of time trying to understand simple things like string variables, or object selection. I left out explicitly selecting objects since it is not necessarily required, but every command works on "the selected object" and it's easy to lose track of what is selected.

Another common approach is to beg a colleague to write it for you.


问:
After adding mui icon material I get an invalid hook call, I tried looking for ways to solve this problem but I couldnt understand any
This is my code:

```<code>import React from 'react';
import './Contact.css';
import './ThePhoneBook';
import InfoIcon from '@mui/icons-material/Info';
import EditIcon from '@mui/icons-material/Edit';

function Contact(props) {
  return (
    <div class="contact">
      <div class="contactDetails">
        <div class="contactImageContainer">
          <img class="contactProfilePic" src={props.data.image} alt='' />
        </div>
        <div class="contactNameContainer">
          <p class="contactP">{props.data.name}</p>
        </div>
      </div>

      <span
        class="updateButton"
        onClick={() => props.callback.updateCurrentContact(props.data.id, 1)}
      >
      <EditIcon fontSize="large" />
      </span>
      <span
        class="infoButton"
        onClick={() => props.callback.updateCurrentContact(props.data.id, 2)}
      >
        <InfoIcon fontSize="large" />
      </span>
      <span
        class="deleteButton"
        onClick={() => props.callback.deleteContact(props.data)}
      >
        ❌
      </span>
    </div>
  );
}

export default Contact;
</code>```

Everything works perfectly when I hide the info and edit icon along with their imports. And on the console on google chrome I get this error message "Invalid hook call. Hooks can only be called inside of the body of a function component." I am not sure what I am supposed to do exactly to make this work.

This is my package.json:

```<code>{
  "name": "final-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

The error message with the blank page. I can't see any of my content because of the invalid hook call. Also ignore the warning messages.

答:
Your react and react-dom versions are > 17.0.0 , they said that it's added as a peerDependencies but it's cause a problem , i suggest to downgrade your react & react-dom versions
try to use this package.json
and then : npm install or yarn install

{
  "name": "final-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "react": "16.14.0",
    "react-dom": "16.14.0",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.4"
  },

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}```

Body:
This is my code:

import React from 'react';
import './Contact.css';
import './ThePhoneBook';
import InfoIcon from '@mui/icons-material/Info';
import EditIcon from '@mui/icons-material/Edit';

function Contact(props) {
  return (

{props.data.name}

       props.callback.updateCurrentContact(props.data.id, 1)}
      >
      <EditIcon fontSize="large" />

       props.callback.updateCurrentContact(props.data.id, 2)}
      >
        <InfoIcon fontSize="large" />

       props.callback.deleteContact(props.data)}
      >
        ❌

  );
}

export default Contact;

Everything works perfectly when I hide the info and edit icon along with their imports. And on the console on google chrome I get this error message "Invalid hook call. Hooks can only be called inside of the body of a function component." I am not sure what I am supposed to do exactly to make this work.

This is my package.json:

{
  "name": "final-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

The error message with the blank page. I can't see any of my content because of the invalid hook call. Also ignore the warning messages.


问:
MkDir Failed creating directory PHP
I am trying to create a directory using PHP this works:

```<code><?php
$uid = "user_615";
$thisdir = getcwd();

if(mkdir($thisdir ."/userpics/" . $uid , 0777))
{
   echo "Directory has been created successfully...";
}
else
{
   echo "Failed to create directory...";
}
?>
</code>```

but this does not work

```<code><?php
session_start();
$uid = $_SESSION['username'];
$thisdir = getcwd();

if(mkdir($thisdir ."/userpics/" . $uid , 0777))
{
   echo "Directory has been created successfully...";
}
else
{
   echo "Failed to create directory...";
}
?>
</code>```

Yes the session variable is populated with the exact same thing as above 'user_615' so why would the second one be failing?

EDIT:

So I took the suggestion of @stefgosselin and re-designed the code to be

```<code><?php
session_start();
$uid = $_SESSION['username'];
$thisdir = getcwd() . "/userpics" . $uid;

if(mkdir($thisdir , 0777))
{
   echo "Directory has been created successfully...";
}
else
{
   echo "Failed to create directory...";
   echo "Your thisdir Variable is:'" . $thisdir . "'" ;
}
?>
</code>```

And the output is

Failed to create directory...Your thisdir Variable is:'/unified/b/bis/www.mysite.com/jou/userpics/user_615

Any other ideas on what would cause the a Session variable not to be able to used in creating a directory?

答:
As a small tip, I would simply put all of $thisdir in a variable and check if the output of that adds up to the result you are expecting.

IE: Having  $thisdir ."/userpics/" . $uid defined in a variable would give you the possibility to easily output and  validate the argument value you are passing to mkdir.

Edit: Adjusted minor phrasing for better english translation.  Sorry above wasn't clear, Wesley understood the simple point I was clumsily trying to make.

ContentLicense: CC BY-SA 3.0

Title: MkDir Failed creating directory PHP

Body:
I am trying to create a directory using PHP this works:

<?php
$uid = "user_615";
$thisdir = getcwd();

if(mkdir($thisdir ."/userpics/" . $uid , 0777))
{
   echo "Directory has been created successfully...";
}
else
{
   echo "Failed to create directory...";
}
?>

but this does not work

<?php
session_start();
$uid = $_SESSION['username'];
$thisdir = getcwd();

if(mkdir($thisdir ."/userpics/" . $uid , 0777))
{
   echo "Directory has been created successfully...";
}
else
{
   echo "Failed to create directory...";
}
?>

Yes the session variable is populated with the exact same thing as above 'user_615' so why would the second one be failing?

EDIT:

So I took the suggestion of @stefgosselin and re-designed the code to be

<?php
session_start();
$uid = $_SESSION['username'];
$thisdir = getcwd() . "/userpics" . $uid;

if(mkdir($thisdir , 0777))
{
   echo "Directory has been created successfully...";
}
else
{
   echo "Failed to create directory...";
   echo "Your thisdir Variable is:'" . $thisdir . "'" ;
}
?>

And the output is

Failed to create directory...Your thisdir Variable is:'/unified/b/bis/www.mysite.com/jou/userpics/user_615

Any other ideas on what would cause the a Session variable not to be able to used in creating a directory?


问:
Retain duplicates in the given list using Stream API
I want to find the duplicates in a set of identifier objects.

Example:

NE , SN1

NE , SN

NE1 , SN

NE , SN1

The result should be NE, SN1 in the List.

```<code>class Identifier {

 String reference;//NE

 String number;//SN1

 String digiId; //Not used for duplicate identification

//getters and setters
}

public static List<Identifier> getDuplicates(List<Identifier> list) {
        Map<String, Map<String, Long>> noOfDupliactes = list.stream().
            collect(Collectors.groupingBy(Identifier::getReference,Collectors.groupingBy(Identifier::getNumber, Collectors.counting())));

**//How to process noOfDupliactes in Java8 using stream to get the List<Identifier>?**

}
</code>```

Any help would be appreciated.

答:
If I understood your expected output correctly, that should work:

```<code>public static List<Identifier> getDuplicates(List<Identifier> list) {
    return list.stream().collect(Collectors.groupingBy(Function.identity()))
            .entrySet()
            .stream()
            .filter(e -> e.getValue().size() > 1)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
}
</code>```

This is just one of the standard methods to get a list of duplicates in a list.

Just make sure to add proper .equals and .hashCode methods in your code, for example similar to this (but with your getters)

```<code>@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Identifier that = (Identifier) o;
    return Objects.equals(reference, that.reference) && Objects.equals(number, that.number);
}

@Override
public int hashCode() {
    return Objects.hash(reference, number);
}
</code>```

Body:
I want to find the duplicates in a set of identifier objects.

Example:

NE , SN1

NE , SN

NE1 , SN

NE , SN1

The result should be NE, SN1 in the List.

class Identifier {

 String reference;//NE

 String number;//SN1

 String digiId; //Not used for duplicate identification

//getters and setters
}

public static List<Identifier> getDuplicates(List<Identifier> list) {
        Map<String, Map<String, Long>> noOfDupliactes = list.stream().
            collect(Collectors.groupingBy(Identifier::getReference,Collectors.groupingBy(Identifier::getNumber, Collectors.counting())));

**//How to process noOfDupliactes in Java8 using stream to get the List<Identifier>?**

}

Any help would be appreciated.

Body:
If I understood your expected output correctly, that should work:

public static List<Identifier> getDuplicates(List<Identifier> list) {
    return list.stream().collect(Collectors.groupingBy(Function.identity()))
            .entrySet()
            .stream()
            .filter(e -> e.getValue().size() > 1)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
}

This is just one of the standard methods to get a list of duplicates in a list.

Just make sure to add proper .equals and .hashCode methods in your code, for example similar to this (but with your getters)

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Identifier that = (Identifier) o;
    return Objects.equals(reference, that.reference) && Objects.equals(number, that.number);
}

@Override
public int hashCode() {
    return Objects.hash(reference, number);
}


问:
Number plus number from array in loops
For example array [1, 2, 4, 5, 6] it must be 1 + 2 + 4 + 5 + 6. so how is the result in these loops? so look below the script</p>
```<code>
    number = [1, 2, 4, 5, 6]

    for x in number:
        x + x

    print(x)

</code>```

答:
Just add a += and a new variable like so:

```<code>number = [1, 2, 4, 5, 6]
y = 0 #new variable (output variable)
for x in number:
    y += x #add = sign here

print(y)
</code>```

Output:

```<code>18
</code>```

But it would be better to use:

```<code>y = sum(number)
print(y)
</code>```

Output:

```<code>18
</code>```

Title: Number plus number from array in loops

Body:
For example array [1, 2, 4, 5, 6] it must be 1 + 2 + 4 + 5 + 6. so how is the result in these loops? so look below the script

    number = [1, 2, 4, 5, 6]

    for x in number:
        x + x

    print(x)

Body:
Just add a += and a new variable like so:

number = [1, 2, 4, 5, 6]
y = 0 #new variable (output variable)
for x in number:
    y += x #add = sign here

print(y)

Output:

18

But it would be better to use:

y = sum(number)
print(y)

Output:

18


问:
MAIN not executed by Factor on command line
I'm not seeing any output from my Hello World program.

```<code>$ cat hello.factor
USE: io
IN: hello

: hello ( -- ) "Hello World!" print ;

MAIN: hello

$ factor hello.factor
$
</code>```

(No output)

```<code>$ factor -run=hello
Vocabulary does not exist
name "hello"

$ factor -run=hello hello.factor
$
</code>```

(No output)

答:
MAIN: defines an entry point for a vocabulary when the vocabulary is passed to run, not necessarily when it is "loaded" from the command line, as you're doing above.  The easiest way to make this work is to simply issue "hello" run from the UI listener.

To actually call the hello word as a script, simply place a call in the top level, like so:

```<code>USE: io
IN: hello

: hello ( -- ) "Hello World!" print ;

! This is the important part
hello
</code>```

Alternatively, you can load and run the vocabulary from the command line with the -run=vocab command line argument.  For instance, factor -run=hello.

There is some more information on this in the docs.  Try running "command-line" about in the listener.

Body:
I'm not seeing any output from my Hello World program.

$ cat hello.factor
USE: io
IN: hello

: hello ( -- ) "Hello World!" print ;

MAIN: hello

$ factor hello.factor
$

(No output)

$ factor -run=hello
Vocabulary does not exist
name "hello"

$ factor -run=hello hello.factor
$

(No output)

Body:
MAIN: defines an entry point for a vocabulary when the vocabulary is passed to run, not necessarily when it is "loaded" from the command line, as you're doing above.  The easiest way to make this work is to simply issue "hello" run from the UI listener.

To actually call the hello word as a script, simply place a call in the top level, like so:

USE: io
IN: hello

: hello ( -- ) "Hello World!" print ;

! This is the important part
hello

Alternatively, you can load and run the vocabulary from the command line with the -run=vocab command line argument.  For instance, factor -run=hello.

There is some more information on this in the docs.  Try running "command-line" about in the listener.


问:
How do I import python files within a package to upload to pypi?
I created a GUI app with following file structure:

MyApp ├──
      ├── LICENSE
      ├── README.md
      ├── setup.cfg
      ├── setup.py
      └── MyApp
          ├── data
          │   ├── dataset1.txt
          │   └── dataset2.txt
          ├── Controller.py
          ├── __init__.py
          ├── Model.py
          ├── MyApp.py
          └── View.py
```
<p>I uploaded it to Pypi and install it on my computer to check if it is working. But when I run it I got the following error:</p>
<pre class="lang-sh prettyprint-override"><code>ModuleNotFoundError: No module named 'View'
</code>```

I managed to solve the problem by relatively importing files within the package. Something like this:

from .View import *
```
<p>Everything worked fine after installation. So, uploading the file to Pypi was successful. But when I tried to edit the local code to release new update, I got the following error:</p>
<pre class="lang-sh prettyprint-override"><code>ImportError: attempted relative import with no known parent package
</code>```

Note that I got this error trying to edit the local code on my working space, not the installed one.
So now every time I want to edit my code on my computer I have to change relative import to absolute import and when I want to upload a new release to Pypi, in order to the installed version works fine, I have to change absolute import to relative import.

So logically there must be two solution to my problem:

How can I upload my code with importing files within the package using absolute import?
or

How can I work on my package locally using relative import?

The app is run on command line by typing its name. Here is my setup file:

import os
from setuptools import *

# The directory containing this file
HERE = os.path.abspath(os.path.dirname(__file__))

# The text of the README file
with open(os.path.join(HERE, "README.md")) as fid:
    README = fid.read()

setup(
    name="MyApp",
    version="v0.1",
    description="My description",
    long_description=README,
    long_description_content_type="text/markdown",
    author="My name",
    author_email="MyEmailAddress@mail.com",
    license="MIT",
    classifiers=[
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3.6"
    ],
    packages=find_packages(),
    package_dir={"MyApp": "MyApp"},
    package_data={
        "MyApp": [
            "data/*.txt"]
    },
    entry_points={
        "console_scripts": [
            "MyApp=MyApp.MyApp:MyApp",
        ]
    }
)
```
<p>Here is the content of <code>__init__.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>from .MyApp import *
</code>```

答:
You can run your app locally with the -m switch from outside the app directory. This allows to resolve relative imports correctly:

```<code>path/to/MyApp$ python -m MyApp.MyApp
</code>```

Body:
I created a GUI app with following file structure:

MyApp ├──
      ├── LICENSE
      ├── README.md
      ├── setup.cfg
      ├── setup.py
      └── MyApp
          ├── data
          │   ├── dataset1.txt
          │   └── dataset2.txt
          ├── Controller.py
          ├── __init__.py
          ├── Model.py
          ├── MyApp.py
          └── View.py

I uploaded it to Pypi and install it on my computer to check if it is working. But when I run it I got the following error:

ModuleNotFoundError: No module named 'View'

I managed to solve the problem by relatively importing files within the package. Something like this:

from .View import *

Everything worked fine after installation. So, uploading the file to Pypi was successful. But when I tried to edit the local code to release new update, I got the following error:

ImportError: attempted relative import with no known parent package

Note that I got this error trying to edit the local code on my working space, not the installed one.
So now every time I want to edit my code on my computer I have to change relative import to absolute import and when I want to upload a new release to Pypi, in order to the installed version works fine, I have to change absolute import to relative import.

So logically there must be two solution to my problem:

How can I upload my code with importing files within the package using absolute import?
or

How can I work on my package locally using relative import?

The app is run on command line by typing its name. Here is my setup file:

import os
from setuptools import *

# The directory containing this file
HERE = os.path.abspath(os.path.dirname(__file__))

# The text of the README file
with open(os.path.join(HERE, "README.md")) as fid:
    README = fid.read()

setup(
    name="MyApp",
    version="v0.1",
    description="My description",
    long_description=README,
    long_description_content_type="text/markdown",
    author="My name",
    author_email="MyEmailAddress@mail.com",
    license="MIT",
    classifiers=[
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3.6"
    ],
    packages=find_packages(),
    package_dir={"MyApp": "MyApp"},
    package_data={
        "MyApp": [
            "data/*.txt"]
    },
    entry_points={
        "console_scripts": [
            "MyApp=MyApp.MyApp:MyApp",
        ]
    }
)

Here is the content of __init__.py:

from .MyApp import *

Body:
You can run your app locally with the -m switch from outside the app directory. This allows to resolve relative imports correctly:

path/to/MyApp$ python -m MyApp.MyApp


问:
modifie style base on state with styled component
I have a function component as such

```<code>const Navbar = ({setNav, nav}) => {
  const [justify, setJustify] = useState('space-around')
  //get localStorage
  const user = JSON.parse(localStorage.getItem('user'));

  //change state of nav to display user details
  if(user){
    setNav(true)
  }
  console.log(nav)

  return (
    <Nav>
      <Img src={logo} alt='groupomania' />
      {nav  ? <UserDetail setNav={setNav}/> : ''}
    </Nav>
  );
};
</code>```

I would like to modify the justify-content styling based on the state

I have tried the following without success

```<code>const Nav = styled.nav`
  position: sticky;
  background: #eeeeee;
  min-height: 10vh;
  display: flex;
  flex-direction: row;
  justify-content: ${nav  ? 'space-between' : 'space-around'};
  align-items: center;
  border-bottom: solid 1px #e5e5e5;
  padding: 1rem 10rem;
  top: 0px;
`
</code>```

答:
While the answer of Bubai would work. However, I am not fond of inline styling.

After some trying around the more suitable solution would be:

```<code> <Nav>
   <Img src={logo} alt='groupomania' />
   {nav  ? <UserDetail setNav={setNav} nav={nav} /> : ''}
</Nav>
</code>```

I have added the nav={nav} prop to the component.
Then I can do the following:

```<code>const Nav = styled.nav`
  position: sticky;
  background: #eeeeee;
  min-height: 10vh;
  display: flex;
  flex-direction: row;
  justify-content: ${props => props.nav  ? 'space-between' : 'space-around'};
  align-items: center;
  border-bottom: solid 1px #e5e5e5;
  padding: 1rem 10rem;
  top: 0px;
`
</code>```

This link was very helpful https://styled-components.com/docs/advanced

Body:
I have a function component as such

const Navbar = ({setNav, nav}) => {
  const [justify, setJustify] = useState('space-around')
  //get localStorage
  const user = JSON.parse(localStorage.getItem('user'));

  //change state of nav to display user details
  if(user){
    setNav(true)
  }
  console.log(nav)

  return (

      {nav  ? <UserDetail setNav={setNav}/> : ''}

  );
};

I would like to modify the justify-content styling based on the state

I have tried the following without success

const Nav = styled.nav`
  position: sticky;
  background: #eeeeee;
  min-height: 10vh;
  display: flex;
  flex-direction: row;
  justify-content: ${nav  ? 'space-between' : 'space-around'};
  align-items: center;
  border-bottom: solid 1px #e5e5e5;
  padding: 1rem 10rem;
  top: 0px;
`

Body:
While the answer of Bubai would work. However, I am not fond of inline styling.

After some trying around the more suitable solution would be:

 <Nav>
   <Img src={logo} alt='groupomania' />
   {nav  ? <UserDetail setNav={setNav} nav={nav} /> : ''}
</Nav>

I have added the nav={nav} prop to the component.
Then I can do the following:

const Nav = styled.nav`
  position: sticky;
  background: #eeeeee;
  min-height: 10vh;
  display: flex;
  flex-direction: row;
  justify-content: ${props => props.nav  ? 'space-between' : 'space-around'};
  align-items: center;
  border-bottom: solid 1px #e5e5e5;
  padding: 1rem 10rem;
  top: 0px;
`

This link was very helpful https://styled-components.com/docs/advanced


问:
How can i change a text of a button without changing it's icon
i have a "Pause" button with a pause_circle_outline materialize icon, and when it clicked i want to change the text to "Resume" and changing the icon to play_circle_outline, but when i try to change the text it changed the text and deletes the icon. here is my code snippet example:

jQuery(document).ready(function($){

  $(document.getElementById("pause_btn")).click(function(){
      document.getElementById("pause_btn").innerText = "Resume"
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <script src = "Sources/js/select_require.js"></script>
    <script src = "Sources/js/routes.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <body>
    Pause<i class="material-icons right">pause_circle_outline</i>
  </body>
</html></code>```

答:
Both textContent and innerText remove child nodes when altered

Docs

Perhaps place your text within a span with an ID and change its textContent?

that way your i tag should remain untouched.

Body:
i have a "Pause" button with a pause_circle_outline materialize icon, and when it clicked i want to change the text to "Resume" and changing the icon to play_circle_outline, but when i try to change the text it changed the text and deletes the icon. here is my code snippet example:

jQuery(document).ready(function($){

  $(document.getElementById("pause_btn")).click(function(){
      document.getElementById("pause_btn").innerText = "Resume"
  });
})

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    Pausepause_circle_outline


问:
How to print out an XML String after it's become an object with PHP Simple XML
This is basically what I'm trying to do:

```<code>$xml = '<root><item attr="1"><notes>item 1 notes</notes></item><item attr="2"><notes>item 2 notes</notes></item></root>';

$xmlObject = simplexml_load_string(xml);

//The XML Info will be modified and updated via loops and other stuff in here.

$updatedXml = $xmlObject converted back to string
</code>```

To clarify, I'm converting an XML formatted string into a Simple XML object in PHP then in between i'm making alterations and updates to the XML object.

The thing I can't figure out is how to get it back into string format.

Thanks for any help!

答: Use the asXML function: http://www.php.net/manual/en/simplexmlelement.asxml.php

Body:
This is basically what I'm trying to do:

$xml = '<root><item attr="1"><notes>item 1 notes</notes></item><item attr="2"><notes>item 2 notes</notes></item></root>';

$xmlObject = simplexml_load_string(xml);

//The XML Info will be modified and updated via loops and other stuff in here.

$updatedXml = $xmlObject converted back to string

To clarify, I'm converting an XML formatted string into a Simple XML object in PHP then in between i'm making alterations and updates to the XML object.

The thing I can't figure out is how to get it back into string format.

Thanks for any help!


问:
Connect Microsoft Identity to Azure AD error
Can someone explain to me why am I getting the following error when trying to connect Microsoft Identity to my Azure account to enable Azure AD authentication in my web app?

答:
This error commonly occurs when Visual Studio or your method of authentication to your Azure subscription was done with a Microsoft Account and not an Azure Active Directory account.

If it is something like username@yourdomain.com,
Please try to add this identity in the office 365 subscribed azure active directory account as a new guest user by creating a user identity by filling name matching your Hotmail account and creating a password .So that identity is created as username@yourdomain.onmicrosoft.com.

The user must be recognized as a subscription owner.For that go to  subscription properties by searching for Subscriptions . If you have multiple subscriptions, please make sure to select the one you intend to use for your application. Once in the subscription properties, select the Access control (IAM) option > Role assignments > Add.

In the Add role assignment blade, select Owner from the Role drop-down list. Leave the Assign access to option at its default (User, group, or service principal). You’ll see all of the users listed. Select the newly created one and then save.

Then sign out of aad account , save and close visual studio .
Now Sign into azure ad account with this newly created identity and then try to add/Connect this identity in visual studio Microsoft identity platform.

In place of 2nd step
from Azure,you can  create a Free or Pay as you Go account using your Outlook.com email address (such as personal@outlook.com) or username@hotmail.com.

This creates an Azure subscription with a new Azure Active Directory and your account as the first user. It  forms the new directory's default domain name (personaloutlook.onmicrosoft.com) and you can add a custom domain name next similar to personal microsoft account if needed .

And then continue from step 3 to create owner role or admin to connect.

References:

Using Azure Active Directory Accounts with a Subscription Tied to a
Personal (aka Live) Account | The Data Farm

difference between a personal Microsoft account and a
work or school account? - Microsoft Tech Community

Connected services - Visual Studio (Windows) | Microsoft Docs


问:
C# Beginner, trying to change a fixed background color of a form with text in a textbox
I am a total beginner with c#, i am learning with Udemy.

I have done just a little start but now i want to test for my own.

i have learned how to use a button to change the background color of a form.

```<code>BackColor = Color.Red; etc.
</code>```

I am now trying to make a textbox where i can write in for example Red, Blue, Green ect and the click a button, then the form will change to that color.
I want to have fixed colors i can choose from so i am guessing i need to make fixed colors in the formload "tab"?

```<code>private void FrmColorCalculator_Load(object sender, EventArgs e)

            Color red = Color.Red;
            Color green = Color.Green;
</code>```

should this be in formload? how to make fixed colors? i get an errormessages saying "cannot convert system.drawing.color to string, but thats not what i want to do, i want the color to change.

If someone would be willing to kick me in the right direction?

答:
"I am now trying to make a textbox where i can write in for example Red, Blue, Green ect and the click a button, then the form will change to that color."

Use Color.FromName like this:

```<code>private void button1_Click_2(object sender, EventArgs e)
{
    try
    {
        this.BackColor = Color.FromName(textBox1.Text);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Invalid color: " + textBox1.Text);
    }
}
</code>```

Body:
I am a total beginner with c#, i am learning with Udemy.

I have done just a little start but now i want to test for my own.

i have learned how to use a button to change the background color of a form.

BackColor = Color.Red; etc.

I am now trying to make a textbox where i can write in for example Red, Blue, Green ect and the click a button, then the form will change to that color.
I want to have fixed colors i can choose from so i am guessing i need to make fixed colors in the formload "tab"?

private void FrmColorCalculator_Load(object sender, EventArgs e)

            Color red = Color.Red;
            Color green = Color.Green;

should this be in formload? how to make fixed colors? i get an errormessages saying "cannot convert system.drawing.color to string, but thats not what i want to do, i want the color to change.

If someone would be willing to kick me in the right direction?

Body:
"I am now trying to make a textbox where i can write in for example Red, Blue, Green ect and the click a button, then the form will change to that color."

Use Color.FromName like this:

private void button1_Click_2(object sender, EventArgs e)
{
    try
    {
        this.BackColor = Color.FromName(textBox1.Text);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Invalid color: " + textBox1.Text);
    }
}


问:
Get created object with all fields
I use DBIx::class and postgreSQL.
Imagine table 'Company'. It has fields:

```<code>id =>  {
  data_type         =>  'integer',
  is_auto_increment =>  1,
},
name => {
  data_type   =>  'text',
},
is_client => {
  data_type     =>  'boolean',
  default_value =>  'true',
},
</code>```

When I create new company passing the company name only, create method returns primery key and field I passed: id, name.
How can I get all fields with default values without additional request to DB?
In other words, I want the create method to return all fields with defaults to me.

答:
The DBIx::Class::ResultSet create method returns a DBIx::Class::Result object which has all column values filled.
On databases that support it, DBIx::Class uses RETURNING to get back server populated column values.
See https://metacpan.org/pod/DBIx::Class::ResultSource#retrieve_on_insert how to use that feature.</p>

Title: Get created object with all fields

Body:
I use DBIx::class and postgreSQL.
Imagine table 'Company'. It has fields:

id =>  {
  data_type         =>  'integer',
  is_auto_increment =>  1,
},
name => {
  data_type   =>  'text',
},
is_client => {
  data_type     =>  'boolean',
  default_value =>  'true',
},

When I create new company passing the company name only, create method returns primery key and field I passed: id, name.
How can I get all fields with default values without additional request to DB?
In other words, I want the create method to return all fields with defaults to me.


问:
What would be the best approach for this Java null check? Should I use an Optional?
I want to achieve the following:

```<code>LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("someString", object.getObjectField().getValue());
</code>```

If object.getObjectField() is null, then I get a NullPointerException. I can easily avoid it, with the following null check:

```<code>if(object.getObjectField() != null) {
    linkedHashMap.put("someString", object.getObjectField().getValue());
    } else {
    linkedHashMap.put("someString", "N/A");
}
</code>```

However, I was thinking to find a better and prettier implementation, using Java 8 Optional, but in this case I still receive a NullPointerException:

```<code>linkedHashMap.put("someString", Optional.ofNullable(object.getObjectField().getValue()).orElse("N/A");
</code>```

What would be the right approach in this case?

答:
but in this case I still receive a NullPointerException

That's because you would still be invoking getValue() even if getObjectField() is null.

You can use Optional.map to apply a function if present:

```<code>Optional.ofNullable(object.getObjectField()).map(ObjectType::getValue)
</code>```

If you want to use a default value, you can just add the orElse after that:

```<code>Optional.ofNullable(object.getObjectField()).map(ObjectType::getValue)
    .ofElse("N/A")
</code>```

Body:
I want to achieve the following:

LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("someString", object.getObjectField().getValue());

If object.getObjectField() is null, then I get a NullPointerException. I can easily avoid it, with the following null check:

if(object.getObjectField() != null) {
    linkedHashMap.put("someString", object.getObjectField().getValue());
    } else {
    linkedHashMap.put("someString", "N/A");
}

However, I was thinking to find a better and prettier implementation, using Java 8 Optional, but in this case I still receive a NullPointerException:

linkedHashMap.put("someString", Optional.ofNullable(object.getObjectField().getValue()).orElse("N/A");

What would be the right approach in this case?

Body:
but in this case I still receive a NullPointerException

That's because you would still be invoking getValue() even if getObjectField() is null.

You can use Optional.map to apply a function if present:

Optional.ofNullable(object.getObjectField()).map(ObjectType::getValue)

If you want to use a default value, you can just add the orElse after that:

Optional.ofNullable(object.getObjectField()).map(ObjectType::getValue)
    .ofElse("N/A")


问:
Add line break for string assignment (For html rendering)
I am trying to create a new line like so:

```<code>let myString= "";
for (const [key, value] of Object.entries(response)) {
   myString += response + "\n";
}
</code>```

But the HTML outputs space instead of line break

答:
By default in HTML, new lines, tabs and multiple spaces are collapsed to a single space, and only wrap lines if the width isn't enough.

If you want to preserve the original spacing in display use the CSS property white-space: pre;.

You can also use the variants pre-wrap which keeps wrapping to long lines in addition to the original spacing, or pre-line which keeps original linebreaks and wrap long lines but does not display multiple spaces.

Body:
I am trying to create a new line like so:

let myString= "";
for (const [key, value] of Object.entries(response)) {
   myString += response + "\n";
}

But the HTML outputs space instead of line break


问:
Is an incomplete array type compatible with a complete array type?
Question: are int (*)[] and int (*)[1] compatible?

Demo 1:

```<code>typedef int T0;
typedef T0  T1[];
typedef T1* T2[];

T1 x1 = { 13 };
T2 x2 = { &x1 };
</code>```

GCC, Clang, ICC generate no diagnostics.

MSVC generates:

```<code><source>(21): warning C4048: different array subscripts: 'T1 (*)' and 'T0 (*)[1]'
</code>```

Note: the T1 (*) is int (*)[], the T0 (*)[1] is int (*)[1].

Demo 2:

```<code>int c[][1] = {0};
int (*r)[] = c;
</code>```

GCC, Clang, ICC generate no diagnostics.

MSVC generates:

```<code><source>(30): warning C4048: different array subscripts: 'int (*)[0]' and 'int (*)[1]'
</code>```

Extra: C2x, 6.7.6.2 Array declarators, 6:

For two array types to be compatible, both shall have compatible element types, and if both size specifiers are present, and are integer constant expressions, then both size specifiers shall have the same constant value. If the two array types are used in a context which requires them to be compatible, it is undefined behavior if the two size specifiers evaluate to unequal values.

答:
I think you want to complicate things by adding identifiers and typedefs.

```<code>typedef int T0;
</code>```

T0 is equivalent to int so let's simplify and use int.

```<code>typedef T0 T1[]; ===>  int (T1[]); ===> int T1[];
</code>```

here, T1 is equivalent to an unspecified array type, so let's simplify and use int [].

```<code>typedef T1* T2[]; ===> int (*T2[])[];
</code>```

This is an array of pointers to integer arrays.

Here, T2 is equivalent to an unspecified array type, so let's simplify and use int (*[])[].

when you write

```<code>T1 x1 = { 13 }; ===>  int x1[] = { 13 }; ===> int x1[1] = { 13 };
</code>```

as the type is finally completely specified by the initializator, that assigns an array length of one element.

```<code>T2 x2 = { &x1 }; ===> int (*x2[])[] = { &x1 };
</code>```

where x1 is of type int *[1] (and so &x1 is of type int **[1].  This will fix the inner array dimension:

```<code>... ===> int (*x2[1])[];
</code>```

and, as there's only one initializer, this will fix also the outer array dimension:

```<code>... ===> int (*x2[1])[1];
</code>```

So finally x2 results in an array of one pointer to array of one int.

I'd suggest you to simplify your examples, to be able to understand incomplete type definitions yourself, by using only one incomplete type, and not three levels of them.  This way you would probably be capable of solving the problem without help.

Body:
Question: are int (*)[] and int (*)[1] compatible?

Demo 1:

typedef int T0;
typedef T0  T1[];
typedef T1* T2[];

T1 x1 = { 13 };
T2 x2 = { &x1 };

GCC, Clang, ICC generate no diagnostics.

MSVC generates:

<source>(21): warning C4048: different array subscripts: 'T1 (*)' and 'T0 (*)[1]'

Note: the T1 (*) is int (*)[], the T0 (*)[1] is int (*)[1].

Demo 2:

int c[][1] = {0};
int (*r)[] = c;

GCC, Clang, ICC generate no diagnostics.

MSVC generates:

<source>(30): warning C4048: different array subscripts: 'int (*)[0]' and 'int (*)[1]'

Extra: C2x, 6.7.6.2 Array declarators, 6:

For two array types to be compatible, both shall have compatible element types, and if both size specifiers are present, and are integer constant expressions, then both size specifiers shall have the same constant value. If the two array types are used in a context which requires them to be compatible, it is undefined behavior if the two size specifiers evaluate to unequal values.

Body:
I think you want to complicate things by adding identifiers and typedefs.

typedef int T0;

T0 is equivalent to int so let's simplify and use int.

typedef T0 T1[]; ===>  int (T1[]); ===> int T1[];

here, T1 is equivalent to an unspecified array type, so let's simplify and use int [].

typedef T1* T2[]; ===> int (*T2[])[];

This is an array of pointers to integer arrays.

Here, T2 is equivalent to an unspecified array type, so let's simplify and use int (*[])[].

when you write

T1 x1 = { 13 }; ===>  int x1[] = { 13 }; ===> int x1[1] = { 13 };

as the type is finally completely specified by the initializator, that assigns an array length of one element.

T2 x2 = { &x1 }; ===> int (*x2[])[] = { &x1 };

where x1 is of type int *[1] (and so &x1 is of type int **[1].  This will fix the inner array dimension:

... ===> int (*x2[1])[];

and, as there's only one initializer, this will fix also the outer array dimension:

... ===> int (*x2[1])[1];

So finally x2 results in an array of one pointer to array of one int.

I'd suggest you to simplify your examples, to be able to understand incomplete type definitions yourself, by using only one incomplete type, and not three levels of them.  This way you would probably be capable of solving the problem without help.


问:
How to add space in a code area using HTML CSS
I'm building a widget. So users have to copy-paste a code from my website into their HTML.

I want to do 2 things.

I want to add spaces in the code area like shown below. The space between different lines is to make code friendly to users.

There will be a copy code snippet button. On clicking on it users can copy the code.

I'm worried if I have
 in the code that will get copied
along as well. Which I don't want.

```<code><code>{` <!-- Start of  client code snippet -->

            <script>

                (function (w, d, s, o, f, js, fjs) {
                    w[o] =
                        w[o] ||
                        function () {
                            (w[o].q = w[o].q || []).push(arguments);
                        };
                    (js = d.createElement(s)), (fjs = d.getElementsByTagName(s)[0]);
                    js.id = o;
                    js.src = f;
                    js.async = 1;
                    fjs.parentNode.insertBefore(js, fjs);
                })(window, document, "script", "_hw", "./widget.js");
                _hw("init", { debug: true, clientID: "abcd" });

             </script>

            <!-- End of client code snippet -->

           `} </code>

</code>```

答:
Alternatively, you can use Syntax Highlighters like prismjs

https://prismjs.com/

<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.26.0/themes/prism-okaidia.min.css" rel="stylesheet" />

```
<code class="language-js">
        (function (w, d, s, o, f, js, fjs) {
            w[o] =
                w[o] ||
                function () {
                    (w[o].q = w[o].q || []).push(arguments);
                };
            (js = d.createElement(s)), (fjs = d.getElementsByTagName(s)[0]);
            js.id = o;
            js.src = f;
            js.async = 1;
            fjs.parentNode.insertBefore(js, fjs);
        })(window, document, "script", "_hw", "./widget.js");
        _hw("init", { debug: true, clientID: "abcd" });
    </code>
    ``````

Body:
I'm building a widget. So users have to copy-paste a code from my website into their HTML.

I want to do 2 things.

I want to add spaces in the code area like shown below. The space between different lines is to make code friendly to users.

There will be a copy code snippet button. On clicking on it users can copy the code.

I'm worried if I have
 in the code that will get copied
along as well. Which I don't want.

{`

           `}

Body:
Alternatively, you can use Syntax Highlighters like prismjs

https://prismjs.com/

<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.26.0/prism.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.26.0/themes/prism-okaidia.min.css" rel="stylesheet" />

<pre>
<code class="language-js">
        (function (w, d, s, o, f, js, fjs) {
            w[o] =
                w[o] ||
                function () {
                    (w[o].q = w[o].q || []).push(arguments);
                };
            (js = d.createElement(s)), (fjs = d.getElementsByTagName(s)[0]);
            js.id = o;
            js.src = f;
            js.async = 1;
            fjs.parentNode.insertBefore(js, fjs);
        })(window, document, "script", "_hw", "./widget.js");
        _hw("init", { debug: true, clientID: "abcd" });
    </code>
    </pre>


问:
How to get array of random doubles in C?
I want to generate an array with random doubles but get an "Segmentation Fault" instead of the result. When I use the same code but replace double with float, everything works. How is that?
Code below works:

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

int N = 1048576;

int main(void) {
    srand(time(NULL));

    float B[N];

    for (int i = 0; i < N; i++) {
        B[i] = (float)rand() / RAND_MAX;
    }

    printf("B[0]=%lf\n", B[0]);

    return 0;
}
</code>```

And code below gives me segmentation fault

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

int N = 1048576;

int main(void) {
    srand(time(NULL));

    double B[N];

    for (int i = 0; i < N; i++) {
        B[i] = (double)rand() / RAND_MAX;
    }

    printf("B[0]=%lf\n", B[0]);

    return 0;
}
</code>```

I'm a noob in C, so any detailed explanation would be appreciated.

答:
You define an array float B[N]; with automatic storage that is quite large (4MB), you are lucky the stack is large enough on your system to accommodate such an object.  Conversely changing the type to double also doubles the size of this local object, which seems definitely too large to allocate on the stack, invoking undefined behavior as you observe.

It is recommended to allocate large arrays from the heap using malloc or calloc.

Here is a modified version:

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

size_t N = 1048576;

int main(void) {
    srand(time(NULL));

    double *B = malloc(sizeof(*B) * N);
    if (B == NULL) {
        fprintf(stderr, "cannot allocate B\n");
        return 1;
    }

    for (size_t i = 0; i < N; i++) {
        B[i] = (double)rand() / RAND_MAX;
    }

    printf("B[0]=%f\n", B[0]);

    free(B);

    return 0;
}
</code>```

Body:
I want to generate an array with random doubles but get an "Segmentation Fault" instead of the result. When I use the same code but replace double with float, everything works. How is that?
Code below works:

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

int N = 1048576;

int main(void) {
    srand(time(NULL));

    float B[N];

    for (int i = 0; i < N; i++) {
        B[i] = (float)rand() / RAND_MAX;
    }

    printf("B[0]=%lf\n", B[0]);

    return 0;
}

And code below gives me segmentation fault

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

int N = 1048576;

int main(void) {
    srand(time(NULL));

    double B[N];

    for (int i = 0; i < N; i++) {
        B[i] = (double)rand() / RAND_MAX;
    }

    printf("B[0]=%lf\n", B[0]);

    return 0;
}

I'm a noob in C, so any detailed explanation would be appreciated.

Body:
You define an array float B[N]; with automatic storage that is quite large (4MB), you are lucky the stack is large enough on your system to accommodate such an object.  Conversely changing the type to double also doubles the size of this local object, which seems definitely too large to allocate on the stack, invoking undefined behavior as you observe.

It is recommended to allocate large arrays from the heap using malloc or calloc.

Here is a modified version:

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

size_t N = 1048576;

int main(void) {
    srand(time(NULL));

    double *B = malloc(sizeof(*B) * N);
    if (B == NULL) {
        fprintf(stderr, "cannot allocate B\n");
        return 1;
    }

    for (size_t i = 0; i < N; i++) {
        B[i] = (double)rand() / RAND_MAX;
    }

    printf("B[0]=%f\n", B[0]);

    free(B);

    return 0;
}


问:
React Router DOM not rendering the page
I am new to react js and I am trying to do page navigation with react-router-dom and I could not load the page even after trying many times.

index.js

```<code>import React from "react";
import ReactDOM from 'react-dom';

import 'bootstrap/dist/css/bootstrap.css';
import { App } from './App'
const element=  <App />;
ReactDOM.render(element, document.getElementById('root'));
</code>```

App.js

```<code>import React from 'react'
import {Route, BrowserRouter as Router, Link} from 'react-router-dom';
import Home from './components/Home';
import Hello from './components/Hello';
export function App()
{
    return(
        <div>
        <Router>
             <div className='container'>
                <div className='navbar-header'>
                    <ul className='nav navbar-nav'>
                        <li> <Link to={'./components/Home'}>Home</Link> </li>
                        <li><Link to={'./components/Hello'}>Hello</Link></li>
                    </ul>
                </div>
            </div>
        </ Router>
        </div>

    );
}
</code>```

src/components/Home.jsx

In Home.jsx, I am trying to get data from API and that page works fine.

Thanks.

答:
You are using react router wrong way. Link is just Router's implementation of  tag... it just change your url and redirect your youter.. you need to specify Route which should be displayed:

```<code>

export function App()
{
    return(
        <div>
        <Router>
             <div className='container'>
                <div className='navbar-header'>
                    <ul className='nav navbar-nav'>
                        <li> <Link to={'/'}>Home</Link> </li>
                        <li><Link to={'/hello'}>Hello</Link></li>
                    </ul>
                </div>
            </div>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/hello" component={Hello} />
</Switch>
        </ Router>
        </div>

    );
}
</code>```

Title: React Router DOM not rendering the page

Body:
I am new to react js and I am trying to do page navigation with react-router-dom and I could not load the page even after trying many times.

index.js

import React from "react";
import ReactDOM from 'react-dom';

import 'bootstrap/dist/css/bootstrap.css';
import { App } from './App'
const element=  <App />;
ReactDOM.render(element, document.getElementById('root'));

App.js

import React from 'react'
import {Route, BrowserRouter as Router, Link} from 'react-router-dom';
import Home from './components/Home';
import Hello from './components/Hello';
export function App()
{
    return(

        <Router>

 <Link to={'./components/Home'}>Home</Link>

<Link to={'./components/Hello'}>Hello</Link>

        </ Router>

    );
}

src/components/Home.jsx

In Home.jsx, I am trying to get data from API and that page works fine.

Thanks.

Body:
You are using react router wrong way. Link is just Router's implementation of <a> tag... it just change your url and redirect your youter.. you need to specify Route which should be displayed:

export function App()
{
    return(
        <div>
        <Router>
             <div className='container'>
                <div className='navbar-header'>
                    <ul className='nav navbar-nav'>
                        <li> <Link to={'/'}>Home</Link> </li>
                        <li><Link to={'/hello'}>Hello</Link></li>
                    </ul>
                </div>
            </div>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/hello" component={Hello} />
</Switch>
        </ Router>
        </div>

    );
}


问:
LoadFromXAML does not work with custom namespaces
I'm developing an App which needs to download and display XAML-Code from a webserver. Till now my code works like expected but now I need to display an WebView which needs to have access to GPS-Data (which be can used with a chrome-browser on android).
I tested the implementation and everything. When compiling the XAML-Code within the app-code, everything works like a charme. Even XAML-Hot-Reload works, but as soon as I try to load my content-page with following code:

public static class GUIFramework
    {
        public static readonly string PRE_FRAMEWORK_XAML = "<ContentPage xmlns=\"http://xamarin.com/schemas/2014/forms\" xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\" xmlns:local=\"clr-namespace:Buerger_App.Renderer;assembly=Buerger_App\" x:Class=\"Buerger_App.Views.Framework\"><ContentPage.Content>";
        public static readonly string POST_FRAMEWORK_XAML = "</ContentPage.Content></ContentPage>";

        ///
        /// This Dictionary is used for caching all of the generated CententPages in the memory.
        /// This is needed due to the Page-XAML-Code needs to be compiled JIT and this can cause noticable delay.
        /// The Caching automatically jumps in after a page was loaded once.
        ///
        private static Dictionary<string, ContentPage> CachedContentPages = new Dictionary<string, ContentPage>();

        ///
        /// Loads the given XAML string as a new ContentPage and binds the Framework Binding-Context
        ///
        /// <param name="XAML_Content">A string representing the XAML formatted code</param>
        /// <returns>The newly created ContentPage</returns>
        public static ContentPage LoadFramework(string XAML_Content, string Title = "")
        {
            string pre_XAML = PRE_FRAMEWORK_XAML;
            if (Title != "")
            {
                pre_XAML = pre_XAML.Replace("<ContentPage ", "<ContentPage Title=\"" + Title + "\" ");
            }
            string FinalXAML = pre_XAML + XAML_Content + POST_FRAMEWORK_XAML;
            ContentPage ContentPage = null;

            // Use caching and read the XAML live from the phone and/or cache
            string hash = SHA256Hash.GetHash(FinalXAML);
            if (CachedContentPages.ContainsKey(hash))
                ContentPage = CachedContentPages[hash];
            else
            {
                ContentPage = new ContentPage().LoadFromXaml(FinalXAML);
                CachedContentPages.Add(hash, ContentPage);
            }

            ContentPage.BindingContext = new FrameworkViewModel();
            return ContentPage;
        }
        // More code ...
    }
```
<p>I tried to load following XAML-Code (the full XAML-Code gets built using the <code>LoadFramework</code>-function):</p>
<pre class="lang-xml prettyprint-override"><code><StackLayout>
    <Image Source="logo_wide.jpg" Margin="0,0,0,25"/>
    <local:GeoWebView x:Name="WebView" Margin="10,0,10,0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Source="https://google.de" />
</StackLayout>
</code>```

The LoadFromXAML-extension runs without any error (no exception thrown). It only skips to create my custom GeoWebView (which I can verify in the childs of the newly created ContentPage in the debugger (the ContentPage only has 1 child and this is the image created before my custom WebView)).

答:
Ok, so i fiddled around a bit and found my solution.
The problem I had was also described here. The answer mentioned to add the assembly-key to the namespace in the XAML-code which should get dynamically loaded was generally correct but I did it wrong in my original question (I added the assembly-key but with an incrorrect assembly-name).

The problem on my tests was, that I've entered Buerger_App as the assembly which is my default namespace and not my assembly-name. My assembly-name is Buerger App.

After correcting the XAML-code it started to work like expected.

Body:
I'm developing an App which needs to download and display XAML-Code from a webserver. Till now my code works like expected but now I need to display an WebView which needs to have access to GPS-Data (which be can used with a chrome-browser on android).
I tested the implementation and everything. When compiling the XAML-Code within the app-code, everything works like a charme. Even XAML-Hot-Reload works, but as soon as I try to load my content-page with following code:

public static class GUIFramework
    {
        public static readonly string PRE_FRAMEWORK_XAML = "<ContentPage xmlns=\"http://xamarin.com/schemas/2014/forms\" xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\" xmlns:local=\"clr-namespace:Buerger_App.Renderer;assembly=Buerger_App\" x:Class=\"Buerger_App.Views.Framework\"><ContentPage.Content>";
        public static readonly string POST_FRAMEWORK_XAML = "</ContentPage.Content></ContentPage>";

        ///
        /// This Dictionary is used for caching all of the generated CententPages in the memory.
        /// This is needed due to the Page-XAML-Code needs to be compiled JIT and this can cause noticable delay.
        /// The Caching automatically jumps in after a page was loaded once.
        ///
        private static Dictionary<string, ContentPage> CachedContentPages = new Dictionary<string, ContentPage>();

        ///
        /// Loads the given XAML string as a new ContentPage and binds the Framework Binding-Context
        ///
        /// <param name="XAML_Content">A string representing the XAML formatted code</param>
        /// <returns>The newly created ContentPage</returns>
        public static ContentPage LoadFramework(string XAML_Content, string Title = "")
        {
            string pre_XAML = PRE_FRAMEWORK_XAML;
            if (Title != "")
            {
                pre_XAML = pre_XAML.Replace("<ContentPage ", "<ContentPage Title=\"" + Title + "\" ");
            }
            string FinalXAML = pre_XAML + XAML_Content + POST_FRAMEWORK_XAML;
            ContentPage ContentPage = null;

            // Use caching and read the XAML live from the phone and/or cache
            string hash = SHA256Hash.GetHash(FinalXAML);
            if (CachedContentPages.ContainsKey(hash))
                ContentPage = CachedContentPages[hash];
            else
            {
                ContentPage = new ContentPage().LoadFromXaml(FinalXAML);
                CachedContentPages.Add(hash, ContentPage);
            }

            ContentPage.BindingContext = new FrameworkViewModel();
            return ContentPage;
        }
        // More code ...
    }

I tried to load following XAML-Code (the full XAML-Code gets built using the LoadFramework-function):

<StackLayout>
    <Image Source="logo_wide.jpg" Margin="0,0,0,25"/>
    <local:GeoWebView x:Name="WebView" Margin="10,0,10,0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Source="https://google.de" />
</StackLayout>

The LoadFromXAML-extension runs without any error (no exception thrown). It only skips to create my custom GeoWebView (which I can verify in the childs of the newly created ContentPage in the debugger (the ContentPage only has 1 child and this is the image created before my custom WebView)).


问:
How do I use Jquery Mobile Slide Panel to slide up from the bottom?
I am working on an app and i need a panel to slide up from the bottom when something is selected.  I see in jquery mobile slide panel that you can set position to either left or right, but how do you set to bottom?</p>

答:
To create a bottom overlay panel with jQuery Mobile v1.4.5.

.ui-panel-display-overlay[data-position="bottom"] {
  top: auto;
  bottom: 0px;
  width: 100% !important;
  height: auto !important;
  min-height: auto;
}
.ui-panel-animate.ui-panel-display-overlay[data-position="bottom"] {
  right: 0;
  -webkit-transform: translate3d(0, 100vh, 0);
  -moz-transform: translate3d(0, 100vh, 0);
  transform: translate3d(0, 100vh, 0);
}
.ui-panel-display-overlay[data-position="bottom"].ui-panel-display-reveal,
.ui-panel-display-overlay[data-position="bottom"].ui-panel-open {
  bottom: 0;
}
.ui-panel-animate.ui-panel-open.ui-panel-display-overlay[data-position="bottom"] {
  -webkit-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
  -moz-transform: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://demos.jquerymobile.com/1.4.5/css/themes/default/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="https://demos.jquerymobile.com/1.4.5/_assets/css/jqm-demos.css">
<script src="https://demos.jquerymobile.com/1.4.5/js/jquery.js"></script>
<script src="https://demos.jquerymobile.com/1.4.5/_assets/js/index.js"></script>
<script src="https://demos.jquerymobile.com/1.4.5/js/jquery.mobile-1.4.5.min.js"></script>
<body
<div data-role="page" class="jqm-demos jqm-panel-page" data-quicklinks="true">
  <div role="main" class="ui-content jqm-content">
    Overlay
  </div>
</div>
<!-- bottompanel1 -->
<div data-role="panel" id="bottompanel1" data-position="bottom" data-display="overlay" data-theme="a">
  <h3>Bottom Panel: Overlay</h3>
  <p>This panel is positioned at the bottom with the overlay display mode. The panel markup is <em>after</em> the header, content and footer in the source order.</p>
  <p>To close, click off the panel, swipe left or right, hit the Esc key, or use the button below:</p>
  Close panel
</div>
<!-- /bottompanel1 -->
</body></code>```

Body:
To create a bottom overlay panel with jQuery Mobile v1.4.5.

.ui-panel-display-overlay[data-position="bottom"] {
  top: auto;
  bottom: 0px;
  width: 100% !important;
  height: auto !important;
  min-height: auto;
}
.ui-panel-animate.ui-panel-display-overlay[data-position="bottom"] {
  right: 0;
  -webkit-transform: translate3d(0, 100vh, 0);
  -moz-transform: translate3d(0, 100vh, 0);
  transform: translate3d(0, 100vh, 0);
}
.ui-panel-display-overlay[data-position="bottom"].ui-panel-display-reveal,
.ui-panel-display-overlay[data-position="bottom"].ui-panel-open {
  bottom: 0;
}
.ui-panel-animate.ui-panel-open.ui-panel-display-overlay[data-position="bottom"] {
  -webkit-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
  -moz-transform: none;
}

<link rel="stylesheet" href="https://demos.jquerymobile.com/1.4.5/css/themes/default/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="https://demos.jquerymobile.com/1.4.5/_assets/css/jqm-demos.css">
<script src="https://demos.jquerymobile.com/1.4.5/js/jquery.js"></script>
<script src="https://demos.jquerymobile.com/1.4.5/_assets/js/index.js"></script>
<script src="https://demos.jquerymobile.com/1.4.5/js/jquery.mobile-1.4.5.min.js"></script>
<body
<div data-role="page" class="jqm-demos jqm-panel-page" data-quicklinks="true">
  <div role="main" class="ui-content jqm-content">
    <a href="#bottompanel1" class="ui-btn ui-shadow ui-corner-all ui-btn-inline ui-btn-mini">Overlay</a>
  </div>
</div>
<!-- bottompanel1 -->
<div data-role="panel" id="bottompanel1" data-position="bottom" data-display="overlay" data-theme="a">
  <h3>Bottom Panel: Overlay</h3>
  <p>This panel is positioned at the bottom with the overlay display mode. The panel markup is <em>after</em> the header, content and footer in the source order.</p>
  <p>To close, click off the panel, swipe left or right, hit the Esc key, or use the button below:</p>
  <a href="#demo-links" data-rel="close" class="ui-btn ui-shadow ui-corner-all ui-btn-a ui-icon-delete ui-btn-icon-left ui-btn-inline">Close panel</a>
</div>
<!-- /bottompanel1 -->
</body>


问:
OfficeJs Addin - Get manifest fields
Developing an outlook addin I seach for a way to read the manifest fields, in particular the extension id via the provided office-js api.

Is there any way to read the properties defined in the addin manifest with the office js api?

答:
Currently, the feature to read manifest items via Office-Js APIs, you requested, is not a part of the product.

We track Outlook add-in feature requests on our Tech Community Page. Please submit your request there and choose the appropriate label(s). Feature requests on Tech Community are considered when we go through our planning process.

Title: OfficeJs Addin - Get manifest fields


问:
Git Source Control Provider hotkeys
I'm using the Git Source Control Provider extension for Visual Studio 2010, and I'd like to set a hotkey for Commit, but I can't make it work. I'd like to define a keyboard shortcut for whatever command is run by right-clicking anywhere in my solution, selecting "Git->Commit" (the one with the cow icon, not the one provided by TortoiseGit).

I've set a hotkey for GitPlugin.Connect.GitExtensionsCommit (Ctrl+G, Ctrl+C), to be used globally (yes, I had to disable some other hotkey settings that used Ctrl+G), but whenever I use it I get an error message saying that the command is not currently available.

How do I set hotkeys for the Git Source Control Provider?

答:
After playing around with this, I was able to get it working.

I configured Ctrl+\, Ctrl+K to be the shortcut (but you can set your own as long as there are no conflicts).

After that, if you select any project/file node and hit the shortcut, it'll trigger the commit.

The catch here is that you have to select a project or file in solution explorer which makes sense because otherwise, the provider doesn't know what to commit.

Title: Git Source Control Provider hotkeys


答:
You have to set the Routes first for each page then only you will be able to navigate to the pages .

Please go through this resource resource.

This is a very good resource to follow .
I hope this solves your issue :)

Title: React Router DOM not rendering the page