问:
How to place imageView inside AutocompleteTextView
I am trying to align the ImageView inside the Autocomplete textView. I did this but the ImageView appears below the AutocomplteTextView. I changed the width of textView but same problem arises. I am looking for something like this:

Is there any way I can achieve this?

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.kalpu.placepick.SearchFragment">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <AutoCompleteTextView
            android:id="@+id/acTextView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:completionHint="From"
            android:dropDownHeight="match_parent"
            android:hint="From"
            android:visibility="visible"
            />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@id/image"
            android:padding="5dp"
            android:layout_alignTop="@id/acTextView1"
            android:layout_alignBottom="@id/acTextView1"
            android:layout_alignRight="@id/acTextView1"
            android:src="@mipmap/ic_arrow_drop_down"

            />

        <AutoCompleteTextView
            android:id="@+id/acTextView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/acTextView1"
            android:completionHint="From"
            android:dropDownHeight="match_parent"
            android:hint="Intermediate (Optional) "
            android:paddingTop="50dp"
            android:visibility="visible" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@id/image"
            android:padding="5dp"
            android:layout_alignTop="@id/acTextView2"
            android:layout_alignBottom="@id/acTextView2"
            android:layout_alignRight="@id/acTextView1"
            android:src="@mipmap/ic_arrow_drop_down"

            />
 </LinearLayout>
</RelativeLayout>
</code>```

答:
Try below code:</p>

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <AutoCompleteTextView
        android:id="@+id/acTextView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:completionHint="From"
        android:dropDownHeight="match_parent"
        android:hint="From"
        android:padding="20dp"
        android:visibility="visible"
        />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@id/image"
        android:layout_alignParentRight="true"
        android:src="@mipmap/your_image"
        />
</RelativeLayout>

<RelativeLayout
    android:id="@+id/relativeLayout2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingTop="20dp">

    <AutoCompleteTextView
        android:id="@+id/acTextView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:completionHint="From"
        android:padding="20dp"
        android:dropDownHeight="match_parent"
        android:hint="Intermediate (Optional) "
        android:visibility="visible" />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@id/image"
        android:src="@mipmap/your_image"
        android:layout_alignParentRight="true"

        />
</RelativeLayout></LinearLayout>
</code>```

Body:
I am trying to align the ImageView inside the Autocomplete textView. I did this but the ImageView appears below the AutocomplteTextView. I changed the width of textView but same problem arises. I am looking for something like this:

Is there any way I can achieve this?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.kalpu.placepick.SearchFragment">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <AutoCompleteTextView
            android:id="@+id/acTextView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:completionHint="From"
            android:dropDownHeight="match_parent"
            android:hint="From"
            android:visibility="visible"
            />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@id/image"
            android:padding="5dp"
            android:layout_alignTop="@id/acTextView1"
            android:layout_alignBottom="@id/acTextView1"
            android:layout_alignRight="@id/acTextView1"
            android:src="@mipmap/ic_arrow_drop_down"

            />

        <AutoCompleteTextView
            android:id="@+id/acTextView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/acTextView1"
            android:completionHint="From"
            android:dropDownHeight="match_parent"
            android:hint="Intermediate (Optional) "
            android:paddingTop="50dp"
            android:visibility="visible" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@id/image"
            android:padding="5dp"
            android:layout_alignTop="@id/acTextView2"
            android:layout_alignBottom="@id/acTextView2"
            android:layout_alignRight="@id/acTextView1"
            android:src="@mipmap/ic_arrow_drop_down"

            />
 </LinearLayout>
</RelativeLayout>

Body:
Try below code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <AutoCompleteTextView
        android:id="@+id/acTextView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:completionHint="From"
        android:dropDownHeight="match_parent"
        android:hint="From"
        android:padding="20dp"
        android:visibility="visible"
        />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@id/image"
        android:layout_alignParentRight="true"
        android:src="@mipmap/your_image"
        />
</RelativeLayout>

<RelativeLayout
    android:id="@+id/relativeLayout2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingTop="20dp">

    <AutoCompleteTextView
        android:id="@+id/acTextView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:completionHint="From"
        android:padding="20dp"
        android:dropDownHeight="match_parent"
        android:hint="Intermediate (Optional) "
        android:visibility="visible" />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@id/image"
        android:src="@mipmap/your_image"
        android:layout_alignParentRight="true"

        />
</RelativeLayout></LinearLayout>


来源: stackexchange

问:
How to change module position through its display string from omnetpp.ini?
I have a network of several modules, one of which uses StationaryMobility as  mobility module. Minimal example:

```<code>network World {
  submodules:
    station1: station {
      @display("p=800,800;is=vl");
    }
}
</code>```

with

```<code>import inet.mobility.static.StationaryMobility;

module station {
  submodules:
    mobility: StationaryMobility
    { }
}
</code>```

station is a foreign module and I may not apply changes to it.

I now want to change the position of this module through changes in the omnetpp.ini so I can comfortably move station1 around from run to run.

I tried parameterizing it as shown in https://omnetpp.org/doc/omnetpp/manual/#sec:graphics:displaystring-parameter-substitution :

```<code>network World {
  parameters:
    posX = 800;
    posY = 800;
  submodules:
    station1: station {
      @display("p=$posX,$posY;is=vl");
    }
}
</code>```

so I could do this in omnetpp.ini:

```<code>*.posX = 1600
*.posY = 2400
</code>```

But StationaryMobility doesn't like it:

```<code><!> Error in module (inet::StationaryMobility) scenario.station1.mobility (id=28) during network initialization: Mobility position is not a finite number after initialize (x=-nan,y=-nan,z=-nan).
</code>```

Unfortunately I can neither find the display string which was generated nor have I found a way through manipulating StationaryMobility directly.

How can I change the position of station1 from within the omnetpp.ini?

答:
I think you are mixing two things here.
The displayString can be used to modify the position of a module in the NED editor and the GUI, but this isn't necessarily the position that the mobility models (like StationaryMobility) from INET use.

Take a look at StationaryMobility.ned first, to find out which parameters the module has, so that you can later edit them the omnetpp.ini for example.

The most important parameters are:

double initialX

double initialY

double initialZ

bool initFromDisplayString

The last one (initFromDisplayString) enables the initial setting of the position parameters based on the displayString (specifically the p parameters in @display("p=x,y;") ).

If you want to substitute the display string parameters, you would need to define the X and Y position as double parameters just like its done in the manual. But you forgot to define the parameter type double, so OMNeT does not know what 1600 is (in this example).

Setting the posX/posY variables in the omnetpp.ini file also might require double asterisks, depending on your NED structure: asterisk vs double asterisks

Getting back to the actual StationaryMobility model.
Instead of using the displayString, you can already set the initial positions directly in your omnetpp.ini file, just like this:

```<code>**.constraintAreaMinX = 0m
**.constraintAreaMinY = 0m
**.constraintAreaMinZ = 0m
**.constraintAreaMaxX = 100m  # example value
**.constraintAreaMaxY = 100m  # example value
**.constraintAreaMaxZ = 0m
**.mobility.initFromDisplayString = false # ignore displayString positions
station1.mobility.initialX = 50m
station1.mobility.initialY = 50m
</code>```

Depending on your network structure and module hierarchy, you need to adjust the path for station1.mobility.initialX or you can simplify it via asterisks operators.

Things like run-dependent position settings, iterations for different runs, etc are all possible in the omnetpp.ini then.

ContentLicense: CC BY-SA 3.0

Body:
I have a network of several modules, one of which uses StationaryMobility as  mobility module. Minimal example:

network World {
  submodules:
    station1: station {
      @display("p=800,800;is=vl");
    }
}

with

import inet.mobility.static.StationaryMobility;

module station {
  submodules:
    mobility: StationaryMobility
    { }
}

station is a foreign module and I may not apply changes to it.

I now want to change the position of this module through changes in the omnetpp.ini so I can comfortably move station1 around from run to run.

I tried parameterizing it as shown in https://omnetpp.org/doc/omnetpp/manual/#sec:graphics:displaystring-parameter-substitution :

network World {
  parameters:
    posX = 800;
    posY = 800;
  submodules:
    station1: station {
      @display("p=$posX,$posY;is=vl");
    }
}

so I could do this in omnetpp.ini:

*.posX = 1600
*.posY = 2400

But StationaryMobility doesn't like it:

<!> Error in module (inet::StationaryMobility) scenario.station1.mobility (id=28) during network initialization: Mobility position is not a finite number after initialize (x=-nan,y=-nan,z=-nan).

Unfortunately I can neither find the display string which was generated nor have I found a way through manipulating StationaryMobility directly.

How can I change the position of station1 from within the omnetpp.ini?

Body:
I think you are mixing two things here.
The displayString can be used to modify the position of a module in the NED editor and the GUI, but this isn't necessarily the position that the mobility models (like StationaryMobility) from INET use.

Take a look at StationaryMobility.ned first, to find out which parameters the module has, so that you can later edit them the omnetpp.ini for example.

The most important parameters are:

double initialX

double initialY

double initialZ

bool initFromDisplayString

The last one (initFromDisplayString) enables the initial setting of the position parameters based on the displayString (specifically the p parameters in @display("p=x,y;") ).

If you want to substitute the display string parameters, you would need to define the X and Y position as double parameters just like its done in the manual. But you forgot to define the parameter type double, so OMNeT does not know what 1600 is (in this example).

Setting the posX/posY variables in the omnetpp.ini file also might require double asterisks, depending on your NED structure: asterisk vs double asterisks

Getting back to the actual StationaryMobility model.
Instead of using the displayString, you can already set the initial positions directly in your omnetpp.ini file, just like this:

**.constraintAreaMinX = 0m
**.constraintAreaMinY = 0m
**.constraintAreaMinZ = 0m
**.constraintAreaMaxX = 100m  # example value
**.constraintAreaMaxY = 100m  # example value
**.constraintAreaMaxZ = 0m
**.mobility.initFromDisplayString = false # ignore displayString positions
station1.mobility.initialX = 50m
station1.mobility.initialY = 50m

Depending on your network structure and module hierarchy, you need to adjust the path for station1.mobility.initialX or you can simplify it via asterisks operators.

Things like run-dependent position settings, iterations for different runs, etc are all possible in the omnetpp.ini then.


问:
JButtons in JPanel take too much space
i have a problem with some buttons and panels. I created a JPanel with a GridBagLayout 6x1.

```<code>        GraphicPaintedPanel deck = new GraphicPaintedPanel();
        GridBagLayout gblDecks = new GridBagLayout();
        gblDecks.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
        gblDecks.rowHeights = new int[]{0, 0};
        gblDecks.columnWeights = new double[]{0.15, 0.15, 0.15, 0.15, 0.15, 0.15, Double.MIN_VALUE};
        gblDecks.rowWeights = new double[]{1.0, Double.MIN_VALUE};
        deck.setLayout(gblDecks);
</code>```

The problem comes when i try to add buttons to this panel as they take space based on how many they are, even tho they should have fixed size. For example if I do

```<code>            for(int j=0; j<4; j++){
            JButton activate= new JButton("ACTIVATE LEADER CARD");
            GridBagConstraints gbcActivate = new GridBagConstraints();
            gbcActivate.gridx = j;
            gbcActivate.fill = GridBagConstraints.BOTH;
            deck.add(activate, gbcActivate);
            }
</code>```

I create 4 buttons and the panel is supposed to have 4 button and 2 "empty spaces". But instead it ha 4 buttons that take all the space they can.

If i do

```<code>            for(int j=0; j<6; j++){
            JButton activate= new JButton("ACTIVATE LEADER CARD");
            GridBagConstraints gbcActivate = new GridBagConstraints();
            gbcActivate.gridx = j;
            gbcActivate.fill = GridBagConstraints.BOTH;
            deck.add(activate, gbcActivate);
            }
</code>```

I get this instead

Shouldn't the dimensions be fixed? Can anyone help me?

答:
gbcActivate.fill = GridBagConstraints.BOTH

If we go to the tutorial it says:

fill

  Used when the component's display area is larger than the component's requested size to determine whether and how to resize the component. Valid values (defined as GridBagConstraints constants) include NONE (the default), HORIZONTAL (make the component wide enough to fill its display area horizontally, but do not change its height), VERTICAL (make the component tall enough to fill its display area vertically, but do not change its width), and BOTH (make the component fill its display area entirely).

So, it will fill the display area independtly of what you specify for the columnWeights, etc. Try removing it or changing it for GridBagConstraints.NONE

Or as suggested in the comments above, use another layout manager such as FlowLayout

Title: JButtons in JPanel take too much space

Body:
i have a problem with some buttons and panels. I created a JPanel with a GridBagLayout 6x1.

        GraphicPaintedPanel deck = new GraphicPaintedPanel();
        GridBagLayout gblDecks = new GridBagLayout();
        gblDecks.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
        gblDecks.rowHeights = new int[]{0, 0};
        gblDecks.columnWeights = new double[]{0.15, 0.15, 0.15, 0.15, 0.15, 0.15, Double.MIN_VALUE};
        gblDecks.rowWeights = new double[]{1.0, Double.MIN_VALUE};
        deck.setLayout(gblDecks);

The problem comes when i try to add buttons to this panel as they take space based on how many they are, even tho they should have fixed size. For example if I do

            for(int j=0; j<4; j++){
            JButton activate= new JButton("ACTIVATE LEADER CARD");
            GridBagConstraints gbcActivate = new GridBagConstraints();
            gbcActivate.gridx = j;
            gbcActivate.fill = GridBagConstraints.BOTH;
            deck.add(activate, gbcActivate);
            }

I create 4 buttons and the panel is supposed to have 4 button and 2 "empty spaces". But instead it ha 4 buttons that take all the space they can.

If i do

            for(int j=0; j<6; j++){
            JButton activate= new JButton("ACTIVATE LEADER CARD");
            GridBagConstraints gbcActivate = new GridBagConstraints();
            gbcActivate.gridx = j;
            gbcActivate.fill = GridBagConstraints.BOTH;
            deck.add(activate, gbcActivate);
            }

I get this instead

Shouldn't the dimensions be fixed? Can anyone help me?


问:
How can I use Sidekiq delay with a worker
I have a situation where I have a worker that makes multiple calls to an external API. The problem is that we have a threshold of many calls we can make to this API per hour.

What I'd like to do is to create a worker which will make these many sequential calls to this external API. If in between these calls we get an error because we've reached the number of connections we're allowed in that hour, the worker would then save the document and schedule a new worker to complete the remaining API calls at a later time (maybe 1, 2 hours later. Ideally this should be configurable e.g.: 10mins, 1hour, etc).

Is there someway I could achieve this?

答:
You want Sidekiq Enterprise and its Rate Limiting API.  The alternative is tracking the rate limit yourself and rescheduling the job manually.

https://github.com/mperham/sidekiq/wiki/Ent-Rate-Limiting


问:
Windows: install fonts from cmd/.bat file
anyone know how to install font files (.ttf, .TTF, .otf, .OTF, etc etc) through the command prompt on windows?

as i understand it, it requires moving the text file to the correct folder and then also creating a registry value i think? but I havent been able to find one that is confirmed working.

a note: I am using windows 8 so that might make a difference.

another note: what I am trying to do is batch install fonts that I ripped from MKV files. (so this will be a function that is part of a larger .bat file, i can post the code if needed)

答:
Batch file sample. It works in the current directory.</p>

```<code>IF  "%*" NEQ "" SET FONT=%*  (

FOR /F %%i in ('dir /b "%FONT%*.*tf"') DO CALL :DEST %%i

) else (

EXIT

)

:DEST

SET FONTFILE=%~n1%~x1
SET FONTNAME=%~n1

IF "%~x1"==".ttf" SET FONTTYPE=TrueType
IF "%~x1"==".otf" SET FONTTYPE=OpenType

ECHO FILE = %FONTFILE%
ECHO NAME = %FONTNAME:-= %
ECHO TYPE = %FONTTYPE%

fontview  %~dp0%FONTFILE%

GOTO :EXIT
</code>```

Body:
Batch file sample. It works in the current directory.

IF  "%*" NEQ "" SET FONT=%*  (

FOR /F %%i in ('dir /b "%FONT%*.*tf"') DO CALL :DEST %%i

) else (

EXIT

)

:DEST

SET FONTFILE=%~n1%~x1
SET FONTNAME=%~n1

IF "%~x1"==".ttf" SET FONTTYPE=TrueType
IF "%~x1"==".otf" SET FONTTYPE=OpenType

ECHO FILE = %FONTFILE%
ECHO NAME = %FONTNAME:-= %
ECHO TYPE = %FONTTYPE%

fontview  %~dp0%FONTFILE%

GOTO :EXIT

ContentLicense: CC BY-SA 4.0


问:
Offline installation of Visual Studio 2017 Update 2 (26430.04) fails
I'm running the command mu_visual_studio_enterprise_2017_x86_x64_10049783.exe --layout c:\vs2017offline --lang en-US to create an offline Visual Studio 2017 installer with the latest update 15.2 (26430.04). I have followed the instructions for offline installation and imported the certs etc. Still, on a machine without internet connection the installation fails. This has caused me major headaches as the failed installation corrupted my dev machine. Installation log attached below:

The product failed to install the listed workloads and components due to one or more package failures.
Incomplete workloads
    .NET Core cross-platform development (Microsoft.VisualStudio.Workload.NetCoreTools,version=15.0.26323.1)
    .NET desktop development (Microsoft.VisualStudio.Workload.ManagedDesktop,version=15.0.26412.1)
    ASP.NET and web development (Microsoft.VisualStudio.Workload.NetWeb,version=15.0.26412.1)
    Azure development (Microsoft.VisualStudio.Workload.Azure,version=15.0.26412.1)
    Data storage and processing (Microsoft.VisualStudio.Workload.Data,version=15.0.26208.0)
    Universal Windows Platform development (Microsoft.VisualStudio.Workload.Universal,version=15.0.26403.0)
Incomplete components
    .NET desktop development tools (Microsoft.VisualStudio.Component.ManagedDesktop.Prerequisites,version=15.0.26323.1)
    ASP.NET and web development tools (Microsoft.VisualStudio.Component.Web,version=15.0.26323.1)
    Azure Cloud Services core tools (Microsoft.VisualStudio.Component.Azure.Waverton,version=15.0.26208.0)
    Azure Cloud Services tools (Microsoft.VisualStudio.ComponentGroup.Azure.CloudServices,version=15.0.26208.0)
    Azure Data Lake Tools (Microsoft.Component.Azure.DataLake.Tools,version=15.0.26208.0)
    Azure development prerequisites (Microsoft.VisualStudio.ComponentGroup.Azure.Prerequisites,version=15.0.26323.1)
    Azure Resource Manager core tools (Microsoft.VisualStudio.Component.Azure.ResourceManager.Tools,version=15.0.26208.0)
    Azure Resource Manager tools (Microsoft.VisualStudio.ComponentGroup.Azure.ResourceManager.Tools,version=15.0.26323.1)
    C# and Visual Basic (Microsoft.VisualStudio.Component.Roslyn.LanguageServices,version=15.0.26208.0)
    Data sources for SQL Server support (Microsoft.VisualStudio.Component.SQL.DataSources,version=15.0.26208.0)
    Live Unit Testing (Microsoft.VisualStudio.Component.LiveUnitTesting,version=15.0.26208.0)
    Managed Desktop Workload Core (Microsoft.VisualStudio.Component.ManagedDesktop.Core,version=15.0.26419.1)
    Microsoft Test Manager (Microsoft.VisualStudio.Component.TestTools.MicrosoftTestManager,version=15.0.26228.0)
    OzCode (Component.6c84f75d-38c3-48a2-9e54-d362238686b5,version=3.0.0.3597)
    PowerShell Tools for Visual Studio 2017 (Component.PowerShellTools.VS2017,version=3.0.539)
    ReadyRoll for VS2017 (Component.Redgate.ReadyRoll,version=1.13.23.3401)
    SQL Prompt Core (Component.Redgate.SQLPrompt.VsPackage,version=7.5.1.1087)
    SQL Search (Component.Redgate.SQLSearch.VSExtension,version=2.4.2.1321)
    SQL Server Data Tools (Microsoft.VisualStudio.Component.SQL.SSDT,version=15.0.26208.0)
    Testing tools core features (Microsoft.VisualStudio.Component.TestTools.Core,version=15.0.26208.0)
    Universal Windows Platform tools (Microsoft.VisualStudio.Component.UWP.Support,version=15.0.26412.1)
    Universal Windows Platform tools for Xamarin (Microsoft.VisualStudio.ComponentGroup.UWP.Xamarin,version=15.0.26403.0)
    Web performance and load testing tools (Microsoft.VisualStudio.Component.TestTools.WebLoadTest,version=15.0.26208.0)
    Windows Communication Foundation (Microsoft.VisualStudio.Component.Wcf.Tooling,version=15.0.26208.0)
    Windows Workflow Foundation (Microsoft.VisualStudio.Component.Workflow,version=15.0.26208.0)
You can search for solutions using the information below, modify your selections for the above workloads and components and retry the installation, or remove the product from your machine.
Following is a collection of individual package failures that led to the incomplete workloads and components above. To search for existing reports of these specific problems, please copy and paste the URL from each package failure into a web browser. If the issue has already been reported, you can find solutions or workarounds there. If the issue has not been reported, you can create a new issue where other people will be able to find solutions or workarounds.
Package 'Microsoft.CodeAnalysis.VisualStudio.InteractiveComponents.Resources,version=15.0.26412.1,language=en-US' failed to download from 'https://download.microsoft.com/download/1/9/A/19A9B545-B70C-4B0E-871D-CEF22A55E2A8/microsoft.codeanalysis.visualstudio.interactivecomponents.resources.vsix'.
    Search URL: https://aka.ms/VSSetupErrorReports?q=PackageId=Microsoft.CodeAnalysis.VisualStudio.InteractiveComponents.Resources;PackageAction=DownloadPackage;ReturnCode=0x80072ee7
    Impacted workloads
        .NET Core cross-platform development (Microsoft.VisualStudio.Workload.NetCoreTools,version=15.0.26323.1)
        .NET desktop development (Microsoft.VisualStudio.Workload.ManagedDesktop,version=15.0.26412.1)
        ASP.NET and web development (Microsoft.VisualStudio.Workload.NetWeb,version=15.0.26412.1)
        Azure development (Microsoft.VisualStudio.Workload.Azure,version=15.0.26412.1)
        Data storage and processing (Microsoft.VisualStudio.Workload.Data,version=15.0.26208.0)
        Universal Windows Platform development (Microsoft.VisualStudio.Workload.Universal,version=15.0.26403.0)
    Impacted components
        .NET desktop development tools (Microsoft.VisualStudio.Component.ManagedDesktop.Prerequisites,version=15.0.26323.1)
        ASP.NET and web development tools (Microsoft.VisualStudio.Component.Web,version=15.0.26323.1)
        Azure Cloud Services core tools (Microsoft.VisualStudio.Component.Azure.Waverton,version=15.0.26208.0)
        Azure Cloud Services tools (Microsoft.VisualStudio.ComponentGroup.Azure.CloudServices,version=15.0.26208.0)
        Azure Data Lake Tools (Microsoft.Component.Azure.DataLake.Tools,version=15.0.26208.0)
        Azure Resource Manager core tools (Microsoft.VisualStudio.Component.Azure.ResourceManager.Tools,version=15.0.26208.0)
        Azure Resource Manager tools (Microsoft.VisualStudio.ComponentGroup.Azure.ResourceManager.Tools,version=15.0.26323.1)
        C# and Visual Basic (Microsoft.VisualStudio.Component.Roslyn.LanguageServices,version=15.0.26208.0)
        Data sources for SQL Server support (Microsoft.VisualStudio.Component.SQL.DataSources,version=15.0.26208.0)
        Live Unit Testing (Microsoft.VisualStudio.Component.LiveUnitTesting,version=15.0.26208.0)
        Managed Desktop Workload Core (Microsoft.VisualStudio.Component.ManagedDesktop.Core,version=15.0.26419.1)
        OzCode (Component.6c84f75d-38c3-48a2-9e54-d362238686b5,version=3.0.0.3597)
        PowerShell Tools for Visual Studio 2017 (Component.PowerShellTools.VS2017,version=3.0.539)
        ReadyRoll for VS2017 (Component.Redgate.ReadyRoll,version=1.13.23.3401)
        SQL Prompt Core (Component.Redgate.SQLPrompt.VsPackage,version=7.5.1.1087)
        SQL Search (Component.Redgate.SQLSearch.VSExtension,version=2.4.2.1321)
        SQL Server Data Tools (Microsoft.VisualStudio.Component.SQL.SSDT,version=15.0.26208.0)
        Universal Windows Platform tools (Microsoft.VisualStudio.Component.UWP.Support,version=15.0.26412.1)
        Web performance and load testing tools (Microsoft.VisualStudio.Component.TestTools.WebLoadTest,version=15.0.26208.0)
        Windows Communication Foundation (Microsoft.VisualStudio.Component.Wcf.Tooling,version=15.0.26208.0)
        Windows Workflow Foundation (Microsoft.VisualStudio.Component.Workflow,version=15.0.26208.0)
    Details
        WebClient download failed: The remote name could not be resolved: 'download.microsoft.com'
        Bits download failed: File not found.
        WinInet download failed: Function: InternetOpenUrl, HR: -2147012889, Message: Unknown error 12007
Package 'Microsoft.VisualStudio.TestTools.TestPlatform.Legacy.Core.Resources,version=15.0.26424.2,language=en-US' failed to download from 'https://download.microsoft.com/download/D/3/0/D3037781-3854-46BA-B6BC-7744B2A41FF1/microsoft.visualstudio.testtools.testplatform.legacy.core.resources.vsix'.
    Search URL: https://aka.ms/VSSetupErrorReports?q=PackageId=Microsoft.VisualStudio.TestTools.TestPlatform.Legacy.Core.Resources;PackageAction=DownloadPackage;ReturnCode=0x80072ee7
    Impacted workloads
        .NET Core cross-platform development (Microsoft.VisualStudio.Workload.NetCoreTools,version=15.0.26323.1)
        .NET desktop development (Microsoft.VisualStudio.Workload.ManagedDesktop,version=15.0.26412.1)
        ASP.NET and web development (Microsoft.VisualStudio.Workload.NetWeb,version=15.0.26412.1)
        Azure development (Microsoft.VisualStudio.Workload.Azure,version=15.0.26412.1)
        Data storage and processing (Microsoft.VisualStudio.Workload.Data,version=15.0.26208.0)
        Universal Windows Platform development (Microsoft.VisualStudio.Workload.Universal,version=15.0.26403.0)
    Impacted components
        .NET desktop development tools (Microsoft.VisualStudio.Component.ManagedDesktop.Prerequisites,version=15.0.26323.1)
        ASP.NET and web development tools (Microsoft.VisualStudio.Component.Web,version=15.0.26323.1)
        Azure Cloud Services core tools (Microsoft.VisualStudio.Component.Azure.Waverton,version=15.0.26208.0)
        Azure Cloud Services tools (Microsoft.VisualStudio.ComponentGroup.Azure.CloudServices,version=15.0.26208.0)
        Azure Data Lake Tools (Microsoft.Component.Azure.DataLake.Tools,version=15.0.26208.0)
        Azure development prerequisites (Microsoft.VisualStudio.ComponentGroup.Azure.Prerequisites,version=15.0.26323.1)
        Azure Resource Manager core tools (Microsoft.VisualStudio.Component.Azure.ResourceManager.Tools,version=15.0.26208.0)
        Azure Resource Manager tools (Microsoft.VisualStudio.ComponentGroup.Azure.ResourceManager.Tools,version=15.0.26323.1)
        Data sources for SQL Server support (Microsoft.VisualStudio.Component.SQL.DataSources,version=15.0.26208.0)
        Managed Desktop Workload Core (Microsoft.VisualStudio.Component.ManagedDesktop.Core,version=15.0.26419.1)
        Microsoft Test Manager (Microsoft.VisualStudio.Component.TestTools.MicrosoftTestManager,version=15.0.26228.0)
        PowerShell Tools for Visual Studio 2017 (Component.PowerShellTools.VS2017,version=3.0.539)
        ReadyRoll for VS2017 (Component.Redgate.ReadyRoll,version=1.13.23.3401)
        SQL Prompt Core (Component.Redgate.SQLPrompt.VsPackage,version=7.5.1.1087)
        SQL Search (Component.Redgate.SQLSearch.VSExtension,version=2.4.2.1321)
        SQL Server Data Tools (Microsoft.VisualStudio.Component.SQL.SSDT,version=15.0.26208.0)
        Testing tools core features (Microsoft.VisualStudio.Component.TestTools.Core,version=15.0.26208.0)
        Universal Windows Platform tools (Microsoft.VisualStudio.Component.UWP.Support,version=15.0.26412.1)
        Universal Windows Platform tools for Xamarin (Microsoft.VisualStudio.ComponentGroup.UWP.Xamarin,version=15.0.26403.0)
        Web performance and load testing tools (Microsoft.VisualStudio.Component.TestTools.WebLoadTest,version=15.0.26208.0)
        Windows Workflow Foundation (Microsoft.VisualStudio.Component.Workflow,version=15.0.26208.0)
    Details
        WebClient download failed: The remote name could not be resolved: 'download.microsoft.com'
        Bits download failed: File not found.
        WinInet download failed: Function: InternetOpenUrl, HR: -2147012889, Message: Unknown error 12007
Package 'Microsoft.VisualStudio.TestTools.TestManagement.MicrosoftTestManager.Resources,version=15.0.26424.2,language=en-US' failed to download from 'https://download.microsoft.com/download/6/3/5/635106B1-58AD-4D74-B069-9942F0654B95/MS.VS.TestTools.TestManagement.MSTestManager.Resources.vsix'.
    Search URL: https://aka.ms/VSSetupErrorReports?q=PackageId=Microsoft.VisualStudio.TestTools.TestManagement.MicrosoftTestManager.Resources;PackageAction=DownloadPackage;ReturnCode=0x80072ee7
    Impacted components
        Microsoft Test Manager (Microsoft.VisualStudio.Component.TestTools.MicrosoftTestManager,version=15.0.26228.0)
    Details
        WebClient download failed: The remote name could not be resolved: 'download.microsoft.com'
        Bits download failed: File not found.
        WinInet download failed: Function: InternetOpenUrl, HR: -2147012889, Message: Unknown error 12007

答:
The problem is: The --layout switch should be used ONLY when downloading a new workload or updating one, which off-course need to be done online, which makes the above error.

By just saying --layout you ask setup: "please update the components in this layout, I'm online now.", which 1st downlaod ~ 60MB file saying "Give us more time, we'll be done soon", then start updating.

When you want to setup vs2017:

Open the 3 certificates in [layoutFolder]\certificates, press enter
or next on each dialog till you finish, don't change anything.

Run [layoutFolder]\vs_*.exe.

However, Its highly recommended to automate the run of vs_*.exe (for setup to choose the exactly Required components) like that:

.\layout\vs_setup.exe --add microsoft.visualstudio.workload.ManagedDesktop --nocache

You don't need to even specify: --lang en-US. --nocache will save your C: from same-as-installed-workload-size additional GB's.


问:
Saving list of objects in Python
I've run a regression 5,693 times and want to save the output, since it took several hours to run. I've captured it in a list called res, and the object (if it matters) is a MarkovRegressionResultsWrapper object from package statsmodels.

I thought the way to go was pickle. I'm saving to a private directory for my own use, so security isn't an issue, and JSON doesn't seem to work for objects (I'm new, so perhaps this is wrong?).

Here is an example I found that works fine:

```<code>import pickle
a = ['test value','test value 2','test value 3']

file_Name = "testfile"
# open the file for writing
fileObject = open(file_Name,'wb')

# this writes the object a to the
# file named 'testfile'
pickle.dump(a,fileObject)

# here we close the fileObject
fileObject.close()
</code>```

However, when I use the exact same code, but save my list res, it gives an error:

```<code>file_Name = "testfile"
# open the file for writing
fileObject = open(file_Name,'wb')

# this writes the object a to the
# file named 'testfile'
pickle.dump(res,fileObject)

# here we close the fileObject
fileObject.close()

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-43-ab4800ac1a51> in <module>()
      7 # this writes the object a to the
      8 # file named 'testfile'
----> 9 pickle.dump(res,fileObject)
     10
     11 # here we close the fileObject

OSError: [Errno 22] Invalid argument
</code>```

I'm using Python 3.6 with Jupyter Notebook on a Macbook Pro. Both a and res are of type list, so the only thing that is different is what the list contains. Why am I getting this error? Is this the best way to save this list of objects or should I be doing something different?

答:
@ChristianDean provided the answer in the comments. This is related to a known bug in pickle in Python 3.6 on Mac OSX only.
Python 3 - Can pickle handle byte objects larger than 4GB?

Title: Saving list of objects in Python

Body:
I've run a regression 5,693 times and want to save the output, since it took several hours to run. I've captured it in a list called res, and the object (if it matters) is a MarkovRegressionResultsWrapper object from package statsmodels.

I thought the way to go was pickle. I'm saving to a private directory for my own use, so security isn't an issue, and JSON doesn't seem to work for objects (I'm new, so perhaps this is wrong?).

Here is an example I found that works fine:

import pickle
a = ['test value','test value 2','test value 3']

file_Name = "testfile"
# open the file for writing
fileObject = open(file_Name,'wb')

# this writes the object a to the
# file named 'testfile'
pickle.dump(a,fileObject)

# here we close the fileObject
fileObject.close()

However, when I use the exact same code, but save my list res, it gives an error:

file_Name = "testfile"
# open the file for writing
fileObject = open(file_Name,'wb')

# this writes the object a to the
# file named 'testfile'
pickle.dump(res,fileObject)

# here we close the fileObject
fileObject.close()

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-43-ab4800ac1a51> in <module>()
      7 # this writes the object a to the
      8 # file named 'testfile'
----> 9 pickle.dump(res,fileObject)
     10
     11 # here we close the fileObject

OSError: [Errno 22] Invalid argument

I'm using Python 3.6 with Jupyter Notebook on a Macbook Pro. Both a and res are of type list, so the only thing that is different is what the list contains. Why am I getting this error? Is this the best way to save this list of objects or should I be doing something different?


问:
How to set text a textview in drawer header from shared preference?
Sorry for my English,
I already set a text in drawer header from shared preferences
MainActivity.Java :

```<code> View header = navigationView.getHeaderView(0);
    setNama((TextView) header.findViewById(R.id.headerName));
    setEmail((TextView) header.findViewById(R.id.headerEmail));
    setGambar((CircleImageView)header.findViewById(R.id.gambar));
    gambarProfil=(CircleImageView)header.findViewById(R.id.gambar);
    sp = getApplicationContext().getSharedPreferences(name, mode);

    getNama().setText(sp.getString("fullname", ""));
    getEmail().setText(sp.getString("username", ""));

    Picasso.with(getApplicationContext()).load(base_url+"foto_user/"+sp.getString("username","")+".jpg")
            .placeholder(R.drawable.blank).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
            .networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE)
            .into(gambarProfil);
</code>```

Then i have activity to change my fullname, username and picture profile

Change Profile.java :

```<code> private void saveProfilPreferences(){
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("fullname", fullname.getText().toString());
    editor.putString("no_hp",no_hp.getText().toString());
    editor.putString("foto",username.getText().toString());
    editor.commit();

    //nama.setText(fullname.getText().toString());
}
</code>```

My shared preferences value is already changed, but my drawer header keep storing an old value of my shared preferences, i think its because i must refresh the drawer but i don't know how to do that.

答:
Add DrawerListener to your DrawerLayout and update NavigationView header text from method onDrawerOpened(). This method will be called when its opened by clicking on drawer toggle icon or finger swipe from left to right.

Update your code as below:

```<code>// DrawerLayout
DrawerLayout mDrawerLayout;

// ActionBarDrawerToggle
ActionBarDrawerToggle mActionBarDrawerToggle;

// NavigationView
NavigationView mNavigationView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Views
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mNavigationView = (NavigationView) findViewById(R.id.navigation_view);

    // ActionBarDrawerToggle
    mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolBar, R.string.drawer_open, R.string.drawer_close){

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);

            // Update navigation header text
            updateNavigationViewHeader();
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);

        }
    };

    // DrawerLayout
    mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
    mActionBarDrawerToggle.syncState();

    .........
    ..................
}

public void updateNavigationViewHeader() {
    View header = mNavigationView.getHeaderView(0);
    setNama((TextView) header.findViewById(R.id.headerName));
    setEmail((TextView) header.findViewById(R.id.headerEmail));
    setGambar((CircleImageView)header.findViewById(R.id.gambar));
    gambarProfil=(CircleImageView)header.findViewById(R.id.gambar);
    sp = getApplicationContext().getSharedPreferences(name, mode);

    getNama().setText(sp.getString("fullname", ""));
    getEmail().setText(sp.getString("username", ""));
    Picasso.with(getApplicationContext()).load(base_url+"foto_user/"+sp.getString("username","")+".jpg")
            .placeholder(R.drawable.blank).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
            .networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE)
            .into(gambarProfil);

}
</code>```

Body:
Sorry for my English,
I already set a text in drawer header from shared preferences
MainActivity.Java :

 View header = navigationView.getHeaderView(0);
    setNama((TextView) header.findViewById(R.id.headerName));
    setEmail((TextView) header.findViewById(R.id.headerEmail));
    setGambar((CircleImageView)header.findViewById(R.id.gambar));
    gambarProfil=(CircleImageView)header.findViewById(R.id.gambar);
    sp = getApplicationContext().getSharedPreferences(name, mode);

    getNama().setText(sp.getString("fullname", ""));
    getEmail().setText(sp.getString("username", ""));

    Picasso.with(getApplicationContext()).load(base_url+"foto_user/"+sp.getString("username","")+".jpg")
            .placeholder(R.drawable.blank).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
            .networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE)
            .into(gambarProfil);

Then i have activity to change my fullname, username and picture profile

Change Profile.java :

 private void saveProfilPreferences(){
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("fullname", fullname.getText().toString());
    editor.putString("no_hp",no_hp.getText().toString());
    editor.putString("foto",username.getText().toString());
    editor.commit();

    //nama.setText(fullname.getText().toString());
}

My shared preferences value is already changed, but my drawer header keep storing an old value of my shared preferences, i think its because i must refresh the drawer but i don't know how to do that.

Body:
Add DrawerListener to your DrawerLayout and update NavigationView header text from method onDrawerOpened(). This method will be called when its opened by clicking on drawer toggle icon or finger swipe from left to right.

Update your code as below:

// DrawerLayout
DrawerLayout mDrawerLayout;

// ActionBarDrawerToggle
ActionBarDrawerToggle mActionBarDrawerToggle;

// NavigationView
NavigationView mNavigationView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Views
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mNavigationView = (NavigationView) findViewById(R.id.navigation_view);

    // ActionBarDrawerToggle
    mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolBar, R.string.drawer_open, R.string.drawer_close){

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);

            // Update navigation header text
            updateNavigationViewHeader();
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);

        }
    };

    // DrawerLayout
    mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
    mActionBarDrawerToggle.syncState();

    .........
    ..................
}

public void updateNavigationViewHeader() {
    View header = mNavigationView.getHeaderView(0);
    setNama((TextView) header.findViewById(R.id.headerName));
    setEmail((TextView) header.findViewById(R.id.headerEmail));
    setGambar((CircleImageView)header.findViewById(R.id.gambar));
    gambarProfil=(CircleImageView)header.findViewById(R.id.gambar);
    sp = getApplicationContext().getSharedPreferences(name, mode);

    getNama().setText(sp.getString("fullname", ""));
    getEmail().setText(sp.getString("username", ""));
    Picasso.with(getApplicationContext()).load(base_url+"foto_user/"+sp.getString("username","")+".jpg")
            .placeholder(R.drawable.blank).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
            .networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE)
            .into(gambarProfil);

}


问:
How to assign addEventListener as ON in JavaScript?
How to assign addEventListener as on
in pure JavaScript? Not jQuery.

// i can do this
// assigning document as d
// assigning querySelector as $

const d = document
const $ = x => d.querySelector(x)

//but how to do this

$('button').addEventListener('click',doSomething)

//to

$('button').on('click',doSomething)

//assiging addEventListener as on ```

答:
Not sure what you mean by saying simple, but here is the alternative way:</p>

```<code>document.getElementById("id").onclick = doSomething;
</code>```

Body:
Not sure what you mean by saying simple, but here is the alternative way:

document.getElementById("id").onclick = doSomething;


问:
How can I handle a HashMap with (potentially) multiple types in its values being passed to a function?
I need to pass a HashMap to a function, but this HashMap could theoretically have both integers and strings as values. How do I form the type signature of the function in question for this? I'm new to Rust, and after trying fn do_thing(params: &HashMap<String, _>) and meeting with failure, I ran out of ideas.

```<code>fn do_thing(params: &HashMap<String, _>) {
    // Irrelevant - regardless, the compiler fails because I cannot use the type placeholder in a function's type sig.
}

fn main() {
    let params = HashMap::new();
    params.insert(field, value); // field will always be a string, value could be a string or an integer
    do_thing(&params)
}
</code>```

This is not a duplicate of the suggested question - constructing a HashMap does not require type declarations, whereas this concerns the HashMap being a function's parameter, which does.

答:
If your value can be int or string, use an enum as follow:

```<code>use std::collections::HashMap;

enum Value {
    Int(i32),
    String(String),
}

fn do_thing(params: &HashMap<String, Value>) {
    // each value of params can be Int or String. Check it with a match.
}
</code>```

Check with a match if Value is Int or String:

```<code>match val {
    Value::Int(i)    => //do something with i
    Value::String(s) => //do something with s
}
</code>```

Body:
I need to pass a HashMap to a function, but this HashMap could theoretically have both integers and strings as values. How do I form the type signature of the function in question for this? I'm new to Rust, and after trying fn do_thing(params: &HashMap<String, _>) and meeting with failure, I ran out of ideas.

fn do_thing(params: &HashMap<String, _>) {
    // Irrelevant - regardless, the compiler fails because I cannot use the type placeholder in a function's type sig.
}

fn main() {
    let params = HashMap::new();
    params.insert(field, value); // field will always be a string, value could be a string or an integer
    do_thing(&params)
}

This is not a duplicate of the suggested question - constructing a HashMap does not require type declarations, whereas this concerns the HashMap being a function's parameter, which does.

Body:
If your value can be int or string, use an enum as follow:

use std::collections::HashMap;

enum Value {
    Int(i32),
    String(String),
}

fn do_thing(params: &HashMap<String, Value>) {
    // each value of params can be Int or String. Check it with a match.
}

Check with a match if Value is Int or String:

match val {
    Value::Int(i)    => //do something with i
    Value::String(s) => //do something with s
}


问:
Calling getInitialProps in children using NextJs
I am implementing data fetching in Next.js using this example:

https://github.com/zeit/next.js/blob/master/examples/data-fetch/pages/index.js

I first tried it by adding the getInitialProps bit in one of my components but it does not get called unless I put it in one of the main pages.  I read some somewhat related discussions that I may need to call the children's getInitialProps from the pages/parent getInitialProps but not clear on how to do so. Also I am wondering if perhaps I should keep the call in the page itself as far as proper technique.

答:
Ah.. right from he NextJS docs :)

Note: getInitialProps can not be used in children components. Only in pages.


问:
Charles Proxy Not Showing Same as Network on Browser
I went to browser and went to inspect element (F12) and chose Network, however I'm seeing more in Network than I see in Charles. I went to sequence in Charles and most of the methods I'm seeing there is just CONNECT, a few GET, and a few POST. However in the network section (just viewing JS), I am seeing a bunch of POST methods that Charles isn't showing. Is Charles supposed to show that or is there a reason it's not showing?</p>

答:
Probably your browser is caching many of those resources not appearing in Charles. You can avoid cache by:

Refresh your page with Ctrl + F5, or

Clear caché (in most browsers Ctrl + Shift + Supr), or

Use the incognito mode (in most browsers: Ctrl + Shift + N), or

If using Chrome: open the inspector and select "Disable cache" under the network tab.


问:
JAXB check if XML-Tag has specific attribute
I'm working at a Method to filter a collection (FileList) of xml-files if a specific xml-tag has an attribute...

In detail... I want to filter all xml-files where the xml-tag  has an attribute "is_special", but I've problems to setup my model-classes for the attribute.

At the end I want to store the name of the file and a list of its items, where the value has the attribute is_special="true"

Also I'm using the JAXB Framework with the Moxy extension...

The XML-Structure as followed:

```<code><document>
<id>75C8866AB078DCE541256D16002CF636</id>
<size>806220</size>
<author>xxx</author>
<last_modified>2017.06.12 07:15:41 GMT</last_modified>
<added_to_file>2016.07.05 09:50:44 GMT</added_to_file>
<created>2003.04.28 08:11:06 GMT</created>
<items>
    <item>
        <name>someName/name>
        <type>LNITEMTYPE_DATETIMES</type>
        <values>
            <value is_special="true"/>
        </values>
        <last_modified>2003.04.28 08:11:10 GMT</last_modified>
        ...
    </item>
    <item>
        <name>someName/name>
        <type>LNITEMTYPE_TEXT</type>
        <values>
            <value>SOMETEXT</value>
            <value>SOMETEXT</value>
        </values>
        <last_modified>2003.04.28 08:11:10 GMT</last_modified>
        ...
    </item>
</items>
</code>```

Therefor I've got 3 Classes for the XML-File...

"XMLDocument.java" implements the list of "Items.java" which implements the list of "Value.java"

XMLDocument.java

```<code>@XmlRootElement(name = "notes_document")
public class XMLDocument {

...
private List<Item> items;

...

@XmlElementWrapper(name = "items")
@XmlElement(name = "item")
public List<Item> getItems() {
    return items;
}

public void setItems(List<Item> items) {
    this.items = items;
}
}
</code>```

item.java

```<code>@XmlRootElement(name = "items")
public class Item {

    private String name;
    private List<String> values;
    private boolean valueIsSpecial;

    @XmlElement(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlElementWrapper(name = "values")
    @XmlElement(name = "value")
    public List<String> getValues() {
        return values;
    }

    public void setValues(List<String> values) {
        this.values = values;
    }

    @XmlPath("value/@is_special")
    public boolean getValueIsSpecial() {
        return valueIsSpecial;
    }

    public void setValueIsSpecial(boolean valueIsSpecial) {
        this.valueIsSpecial = valueIsSpecial;
    }
}
</code>```

value.java

```<code>@XmlRootElement(name = "values")
public class Value {
    @XmlElement(name = "value")
    private String itemValue;
    @XmlPath("value/@is_special")
    private boolean isSpecial;

    public String getValue() {
        return itemValue;
    }

    public void setValue(String value) {
        this.itemValue = value;
    }

    public boolean getValueIsSpecial() {
        return isSpecial;
    }

    public void setValueIsSpecial(boolean isSpecial) {
        this.isSpecial = isSpecial;
    }
}
</code>```

My Method so far...

```<code>public void FilterTree_isSpecial() throws JAXBException, FileNotFoundException {

        for(String file: FileList) {
            if (file.endsWith(".xml") && !file.contains("databaseinfo.xml")) {

                JAXBContext context = JAXBContext.newInstance(NotesDocumentMetaFile.class);
                Unmarshaller um = context.createUnmarshaller();
                NotesDocumentMetaFile docMetaFile = (XMLDocument) um.unmarshal(new FileReader(file));
                for (int i = 0; i < docMetaFile.getItems().size(); i++) {

                    // CHECK IF THE <value> OF THIS ITEM HAS ATTRIBUTE is_special

                }
            }
        }
    }
</code>```

Much text... I hope anyone can give me a solution :/

答:
Actually the xpath in your Item.java needs to be : values/value/@is_special like @XmlPath("values/value/@is_special")

If you want the is_special in your Value.java also your xpath should be :

@is_special like : @XmlPath(@is_special)

Also your Item.java, Value.java needs a little change. You don't need @XmlRootElement, you already had it in your XmlDocument.java

Your Item.java should be :

```<code>public class Item
{

    private String name;

    private String type;

    private String lastModified;

    private List<Value> values;

    private String isSpecial;

    @XmlPath("values/value/@is_special")
    public String getIsSpecial() {
        return isSpecial;
    }

    public void setIsSpecial(String isSpecial) {
       this.isSpecial = isSpecial;
    }

    @XmlElement(name="type")
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @XmlElement(name="last_modified")
    public String getLastModified() {
        return lastModified;
    }

    public void setLastModified(String lastModified) {
        this.lastModified = lastModified;
    }

    @XmlElement(name="name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlElementWrapper(name="values")
    @XmlElement(name="value")
    public List<Value> getValues() {
        return values;
    }

    public void setValues(List<Value> values) {
        this.values = values;
    }

}
</code>```

Your Value.java should be :

```<code>public class Value
{

    @XmlPath("text()")
    private String value;

    @XmlPath("@is_special")
    private String isSpecial;

    public String getIsSpecial() {
        return isSpecial;
    }

    public void setIsSpecial(String isSpecial) {
        this.isSpecial = isSpecial;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}
</code>```

Note that to get value and is_special in Value.java, you could use @XmlPath.

Now you can call getIsSpecial() on Item.java to check if it is special.

Body:
I'm working at a Method to filter a collection (FileList) of xml-files if a specific xml-tag has an attribute...

In detail... I want to filter all xml-files where the xml-tag  has an attribute "is_special", but I've problems to setup my model-classes for the attribute.

At the end I want to store the name of the file and a list of its items, where the value has the attribute is_special="true"

Also I'm using the JAXB Framework with the Moxy extension...

The XML-Structure as followed:

<document>
<id>75C8866AB078DCE541256D16002CF636</id>
<size>806220</size>
<author>xxx</author>
<last_modified>2017.06.12 07:15:41 GMT</last_modified>
<added_to_file>2016.07.05 09:50:44 GMT</added_to_file>
<created>2003.04.28 08:11:06 GMT</created>
<items>
    <item>
        <name>someName/name>
        <type>LNITEMTYPE_DATETIMES</type>
        <values>
            <value is_special="true"/>
        </values>
        <last_modified>2003.04.28 08:11:10 GMT</last_modified>
        ...
    </item>
    <item>
        <name>someName/name>
        <type>LNITEMTYPE_TEXT</type>
        <values>
            <value>SOMETEXT</value>
            <value>SOMETEXT</value>
        </values>
        <last_modified>2003.04.28 08:11:10 GMT</last_modified>
        ...
    </item>
</items>

Therefor I've got 3 Classes for the XML-File...

"XMLDocument.java" implements the list of "Items.java" which implements the list of "Value.java"

XMLDocument.java

@XmlRootElement(name = "notes_document")
public class XMLDocument {

...
private List<Item> items;

...

@XmlElementWrapper(name = "items")
@XmlElement(name = "item")
public List<Item> getItems() {
    return items;
}

public void setItems(List<Item> items) {
    this.items = items;
}
}

item.java

@XmlRootElement(name = "items")
public class Item {

    private String name;
    private List<String> values;
    private boolean valueIsSpecial;

    @XmlElement(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlElementWrapper(name = "values")
    @XmlElement(name = "value")
    public List<String> getValues() {
        return values;
    }

    public void setValues(List<String> values) {
        this.values = values;
    }

    @XmlPath("value/@is_special")
    public boolean getValueIsSpecial() {
        return valueIsSpecial;
    }

    public void setValueIsSpecial(boolean valueIsSpecial) {
        this.valueIsSpecial = valueIsSpecial;
    }
}

value.java

@XmlRootElement(name = "values")
public class Value {
    @XmlElement(name = "value")
    private String itemValue;
    @XmlPath("value/@is_special")
    private boolean isSpecial;

    public String getValue() {
        return itemValue;
    }

    public void setValue(String value) {
        this.itemValue = value;
    }

    public boolean getValueIsSpecial() {
        return isSpecial;
    }

    public void setValueIsSpecial(boolean isSpecial) {
        this.isSpecial = isSpecial;
    }
}

My Method so far...

public void FilterTree_isSpecial() throws JAXBException, FileNotFoundException {

        for(String file: FileList) {
            if (file.endsWith(".xml") && !file.contains("databaseinfo.xml")) {

                JAXBContext context = JAXBContext.newInstance(NotesDocumentMetaFile.class);
                Unmarshaller um = context.createUnmarshaller();
                NotesDocumentMetaFile docMetaFile = (XMLDocument) um.unmarshal(new FileReader(file));
                for (int i = 0; i < docMetaFile.getItems().size(); i++) {

                    // CHECK IF THE <value> OF THIS ITEM HAS ATTRIBUTE is_special

                }
            }
        }
    }

Much text... I hope anyone can give me a solution :/

Body:
Actually the xpath in your Item.java needs to be : values/value/@is_special like @XmlPath("values/value/@is_special")

If you want the is_special in your Value.java also your xpath should be :

@is_special like : @XmlPath(@is_special)

Also your Item.java, Value.java needs a little change. You don't need @XmlRootElement, you already had it in your XmlDocument.java

Your Item.java should be :

public class Item
{

    private String name;

    private String type;

    private String lastModified;

    private List<Value> values;

    private String isSpecial;

    @XmlPath("values/value/@is_special")
    public String getIsSpecial() {
        return isSpecial;
    }

    public void setIsSpecial(String isSpecial) {
       this.isSpecial = isSpecial;
    }

    @XmlElement(name="type")
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @XmlElement(name="last_modified")
    public String getLastModified() {
        return lastModified;
    }

    public void setLastModified(String lastModified) {
        this.lastModified = lastModified;
    }

    @XmlElement(name="name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlElementWrapper(name="values")
    @XmlElement(name="value")
    public List<Value> getValues() {
        return values;
    }

    public void setValues(List<Value> values) {
        this.values = values;
    }

}

Your Value.java should be :

public class Value
{

    @XmlPath("text()")
    private String value;

    @XmlPath("@is_special")
    private String isSpecial;

    public String getIsSpecial() {
        return isSpecial;
    }

    public void setIsSpecial(String isSpecial) {
        this.isSpecial = isSpecial;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}

Note that to get value and is_special in Value.java, you could use @XmlPath.

Now you can call getIsSpecial() on Item.java to check if it is special.


问:
getting two usernames based on ids from one row
So what I'm trying to do is this, basically I have a table called games which has

creator_id
and
guest_id

now what i want to do is when i want to list all games i want to join two tables and get for example if creator_id is John and guest_id is Mary

i want to list all the "games" with their names

ID: 322   |     Creator Name: John   |     Guest Name: Mary

and so on, this is what i got so far:

Controller:

```<code>class AdminController extends Controller
{
    public function index()
    {
        return view('admin.home');
    }

    public function listGames()
    {
        $games = Game::get();
        return view('admin.games.list', compact('games'));
    }
}
</code>```

View:

```<code>@extends('admin.content')

@section('title', 'List games')

@section('content')

<table class="table table-hover">

@foreach($games as $game)

// now i want to list that here

@endforeach
</table>

@endsection
</code>```

答:
Add relation methods in Game model

```<code>public function creator() {
    return $this->hasOne(User::class, 'creator_id');
}

public function guest() {
    return $this->hasOne(User::class, 'guest_id');
}
</code>```

Eager load in your controller

```<code>public function index() {
    $games = Game::with('creator', 'guest')->get();
    return view('admin.games.list', compact('games'));
}
</code>```

Now, in your view

```<code>@foreach($games as $game)
    Creator: {{ $game->creator->name }}
    Guest: {{ $game->guest->name }}
@endforeach
</code>```

Body:
So what I'm trying to do is this, basically I have a table called games which has

creator_id
and
guest_id

now what i want to do is when i want to list all games i want to join two tables and get for example if creator_id is John and guest_id is Mary

i want to list all the "games" with their names

ID: 322   |     Creator Name: John   |     Guest Name: Mary

and so on, this is what i got so far:

Controller:

class AdminController extends Controller
{
    public function index()
    {
        return view('admin.home');
    }

    public function listGames()
    {
        $games = Game::get();
        return view('admin.games.list', compact('games'));
    }
}

View:

@extends('admin.content')

@section('title', 'List games')

@section('content')

@foreach($games as $game)

// now i want to list that here

@endforeach

@endsection

Body:
Add relation methods in Game model

public function creator() {
    return $this->hasOne(User::class, 'creator_id');
}

public function guest() {
    return $this->hasOne(User::class, 'guest_id');
}

Eager load in your controller

public function index() {
    $games = Game::with('creator', 'guest')->get();
    return view('admin.games.list', compact('games'));
}

Now, in your view

@foreach($games as $game)
    Creator: {{ $game->creator->name }}
    Guest: {{ $game->guest->name }}
@endforeach


问:
jQuery Alert if paragraph is selected and has specific class
I have html code like below.

```<code><div id='p1' class='thread'>
<p>First Paragraph</p>
<p>Abbot and Costello - Africa Screams</p>
</div>

<div id='p2' class='thread selected'>
<p>Second Paragraph</p>
<p class='flag'>Abbot and Costello - Frank/Meet</p>
</div>

<div id='p3' class='thread'>
<p>Third Paragraph</p>
<p>addin</p>
</div>

<div id='p4' class='thread'>
<p>Forth Paragraph</p>
<p>Begins</p>
</div>
</code>```

Every time user clicks on paragraph new class "selected" is added and previous one is removed.

I want to alert('flag'); if a
 has class selected and
 has class flag like in Second Paragraph.

how can I achieve this using "jQuery".

any help is appreciated, Thanks.

答:
Try this:</p>

```<code>$("p").click(function(){
if($(this).attr('class') == 'flag) {
alert('flag');
}
}
</code>```

Body:
I have html code like below.

First Paragraph

Abbot and Costello - Africa Screams

Second Paragraph

Abbot and Costello - Frank/Meet

Third Paragraph

addin

Forth Paragraph

Begins

Every time user clicks on paragraph new class "selected" is added and previous one is removed.

I want to alert('flag'); if a
 has class selected and
 has class flag like in Second Paragraph.

how can I achieve this using "jQuery".

any help is appreciated, Thanks.

Body:
Try this:

$("p").click(function(){
if($(this).attr('class') == 'flag) {
alert('flag');
}
}


问:
NetLogo: neighbors and eigenvector
I want to count the neighbors and the neighbors neighbors of a turtle to kind of find out a way to calculate the eigenvector-centrality. Since I can´t get the NW:extensions to work and my prof neither. I thought of building a method myself. Since I don´t have that much time until the first round of presentation, I try my best to just count the neighbors and the neighbors neighbors of a turtle.
I decided to have a turtles-own, which counts all neighbors and then sum all the neighbors and neighbors neighbors. But I am stuck in my head and cant get it to work.
set Neighborscount count(link-neighbors)

Anyone has any ideas?
Also a final way to get the eigenvector-centrality to work would be very much appreciated.

答:
First, my main recommendation is to get NW working. I'd be happy to help with that.

Barring that, the below assumes you're working with undirected networks. If that's not the cast, let me know.

The problem with the method that you describe is that it will count some neighbors-of-neighbors multiple times. Instead, you can get the agent-set of neighbors-of-neighbors, and then just count it:

```<code>to-report neighbors-of-neighbors
  report turtle-set [ link-neighbors ] of link-neighbors
end
</code>```

Then, [ count neighbors-of-neighbors ] of turtle 0 will give the number of neighbors of neighbors of turtle 0.

Now, a few points:

This will include the turtle itself, since a turtle is always a link neighbor of its link neighbors. If you don't want to include the turtle itself, you can just throw an other in there: [ count other neighbors-of-neighbors ] of turtle 0.

This won't include turtles that are link neighbors of turtle 0, but are not linked to any other neighbors of turtle 0. To add those in, you might consider a procedure like this:

```<code>to-report turtles-in-link-radius [ n ]
  let result turtle-set self
  repeat n [
    set result (turtle-set result [ link-neighbors ] of result)
  ]
  report result
end
</code>```

This can then be used, for instance, like so: [ count turtle-in-link-radius 2 ] of turtle 0 to count all turtles at most 2 hops from turtle 0. This reporter has the same behavior as nw:turtles-in-radius, though it will be significantly slower.

Now, I first noted that your idea would count some turtles multiple times. Given that you're interested in something like eigenvector-centrality, maybe this is what you want. In that case you can do this: [ sum [ count link-neighbors ] of link-neighbors ] of turtle 0 to get it without having to bother with a turtles-own. That said, if you do use a turtles-own, you can actually calculate the eigenvector centrality itself:

```<code>turtles-own [
  ...
  next-ec ;; helper variable for iteratively computing eigenvector-centrality
  eigenvector-centrality
  ...
]

to calculate-eigenvector-centralities
  ask turtles [
    set eigenvector-centrality 1
  ]
  repeat 100 [  ;; the higher this number, the more accurate the value. NW uses 100
    ask turtles [
      set next-ec sum [ eigenvector-centrality ] of link-neighbors
    ]
    let max-ec max [ next-ec ] of turtles
    ask turtles [
      set eigenvector-centrality next-ec / max-ec ;; normalize
    ]
  ]
end
</code>```

Call calculate-eigenvector-centralities to calculate all turtles eigenvector centralities. The turtles' eigenvector centralities will then be stored in eigenvector-centrality. Note that this code won't work for disconnected networks: each component has to be normalized independently, which is what NW does, but there's no easy way to do that in NetLogo without using NW.

Title: NetLogo: neighbors and eigenvector

Body:
First, my main recommendation is to get NW working. I'd be happy to help with that.

Barring that, the below assumes you're working with undirected networks. If that's not the cast, let me know.

The problem with the method that you describe is that it will count some neighbors-of-neighbors multiple times. Instead, you can get the agent-set of neighbors-of-neighbors, and then just count it:

to-report neighbors-of-neighbors
  report turtle-set [ link-neighbors ] of link-neighbors
end

Then, [ count neighbors-of-neighbors ] of turtle 0 will give the number of neighbors of neighbors of turtle 0.

Now, a few points:

This will include the turtle itself, since a turtle is always a link neighbor of its link neighbors. If you don't want to include the turtle itself, you can just throw an other in there: [ count other neighbors-of-neighbors ] of turtle 0.

This won't include turtles that are link neighbors of turtle 0, but are not linked to any other neighbors of turtle 0. To add those in, you might consider a procedure like this:

to-report turtles-in-link-radius [ n ]
  let result turtle-set self
  repeat n [
    set result (turtle-set result [ link-neighbors ] of result)
  ]
  report result
end

This can then be used, for instance, like so: [ count turtle-in-link-radius 2 ] of turtle 0 to count all turtles at most 2 hops from turtle 0. This reporter has the same behavior as nw:turtles-in-radius, though it will be significantly slower.

Now, I first noted that your idea would count some turtles multiple times. Given that you're interested in something like eigenvector-centrality, maybe this is what you want. In that case you can do this: [ sum [ count link-neighbors ] of link-neighbors ] of turtle 0 to get it without having to bother with a turtles-own. That said, if you do use a turtles-own, you can actually calculate the eigenvector centrality itself:

turtles-own [
  ...
  next-ec ;; helper variable for iteratively computing eigenvector-centrality
  eigenvector-centrality
  ...
]

to calculate-eigenvector-centralities
  ask turtles [
    set eigenvector-centrality 1
  ]
  repeat 100 [  ;; the higher this number, the more accurate the value. NW uses 100
    ask turtles [
      set next-ec sum [ eigenvector-centrality ] of link-neighbors
    ]
    let max-ec max [ next-ec ] of turtles
    ask turtles [
      set eigenvector-centrality next-ec / max-ec ;; normalize
    ]
  ]
end

Call calculate-eigenvector-centralities to calculate all turtles eigenvector centralities. The turtles' eigenvector centralities will then be stored in eigenvector-centrality. Note that this code won't work for disconnected networks: each component has to be normalized independently, which is what NW does, but there's no easy way to do that in NetLogo without using NW.


问:
Removing keyword from list after matching the keyword with answer
I'm trying to keep score after certain keywords are matched with output from a chatbot. I got it to count a score for every match, but I dont want to match it again if there will be a match with the same keyword. I'm  trying to do this by removing the keyword from the list, but it continues to add score.

i.e. I want to add score if chatbot say hi, but only once.

I'm tring this

```<code>public void SendQuestionToRobot()
{

    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        List<string> sPattern = new List<string> { "hi", "a painkiller" };

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                sPattern.Remove(s);
                break;
            }
        }

    }
}
</code>```

and

```<code>public void SendQuestionToRobot()
{

    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        List<string> sPattern = new List<string> { "hi", "a painkiller" };

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                break;
            }
        }
        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                sPattern.Remove(s);

            }
        }
    }
}
</code>```

but in both cases the score continues to be added

答:
Don't forget to renew sPattern when needed.</p>

```<code>List<string> sPattern = new List<string> { "hi", "a painkiller" };

public void SendQuestionToRobot()
{
    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                sPattern.Remove(s);
                break;
            }
        }
    }
}
</code>```

Body:
I'm trying to keep score after certain keywords are matched with output from a chatbot. I got it to count a score for every match, but I dont want to match it again if there will be a match with the same keyword. I'm  trying to do this by removing the keyword from the list, but it continues to add score.

i.e. I want to add score if chatbot say hi, but only once.

I'm tring this

public void SendQuestionToRobot()
{

    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        List<string> sPattern = new List<string> { "hi", "a painkiller" };

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                sPattern.Remove(s);
                break;
            }
        }

    }
}

and

public void SendQuestionToRobot()
{

    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        List<string> sPattern = new List<string> { "hi", "a painkiller" };

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                break;
            }
        }
        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                sPattern.Remove(s);

            }
        }
    }
}

but in both cases the score continues to be added

Body:
Don't forget to renew sPattern when needed.

List<string> sPattern = new List<string> { "hi", "a painkiller" };

public void SendQuestionToRobot()
{
    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                sPattern.Remove(s);
                break;
            }
        }
    }
}


问:
Simple VBA Throwing Object Error 1004
This loops through each worksheet and inserts a VLOOKUP formula (which references a closed workbook). The code will start with the first sheet, find and open the corresponding workbook, and perform the VLOOKUP, then onto the next sheet/corresponding workbook. Everything works until I hit .Cells which is where i run into the Object error. What am I missing? I run this macro from the original workbook, then it opens the external workbook</p>

```<code>For Each ws In ThisWorkbook.Worksheets
    If (ws.Name <> "Sheet1") And (ws.Name <> "Sheet2") Then
        Set wbPath2 = Workbooks.Open("C:\MyDirectory\MyFile1.csv")
        sourceSheet = "[MySheet.csv]"

        With ws
            .Cells(Application.WorksheetFunction.Match("Account1", .Range("A:A"), 0), Application.WorksheetFunction.Match(ComboBox1.Value & " " & Year(Date), .Range("A6:BZ6"), 0)).Formula = "=VLOOKUP(""Account1 Service"",'" & Root & sourceSheet & ws.Name & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$A:$G,4,FALSE)"
</code>```

答: It turns out I forgot to concatenate something in my file path pointer. Thank you to @Jordan for the Debug tips.</p>

Title: Simple VBA Throwing Object Error 1004

Body:
This loops through each worksheet and inserts a VLOOKUP formula (which references a closed workbook). The code will start with the first sheet, find and open the corresponding workbook, and perform the VLOOKUP, then onto the next sheet/corresponding workbook. Everything works until I hit .Cells which is where i run into the Object error. What am I missing? I run this macro from the original workbook, then it opens the external workbook

For Each ws In ThisWorkbook.Worksheets
    If (ws.Name <> "Sheet1") And (ws.Name <> "Sheet2") Then
        Set wbPath2 = Workbooks.Open("C:\MyDirectory\MyFile1.csv")
        sourceSheet = "[MySheet.csv]"

        With ws
            .Cells(Application.WorksheetFunction.Match("Account1", .Range("A:A"), 0), Application.WorksheetFunction.Match(ComboBox1.Value & " " & Year(Date), .Range("A6:BZ6"), 0)).Formula = "=VLOOKUP(""Account1 Service"",'" & Root & sourceSheet & ws.Name & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$A:$G,4,FALSE)"


问:
Angular - get synchronously from Promise
I want to print history of products. I have an id of product in ActivatedRoute.params. In ngOnInit method I have to get all history of product and assign to variable. Then I want to map product to productHistory, because I want to have last version with history toghether. But the problem is with getting history. Method to getting history return Promise and I cannot get length of productsHistory when I use this property and I get undefined. How can I get this property after loading from service?

I want to execute method after execution getHistory().

My code:

ProductService.ts:

```<code>import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

// rest imports

@Injectable()
export class ProductService {

    // URL to web api
    private projectsUrl = 'http://localhost:8080/products';

    private headers = new Headers({'Content-Type': 'application/json'});

    constructor(private http: Http) {}

    getHistory(id: number): Promise<ProductHistory[]> {
        const url = `${this.projectsUrl}/projectId/${id}`;
        return this.http.get(url)
            .toPromise()
            .then(response => response.json() as ProductHistory[])
            .catch(this.handleError);
    }

    handleError() {
        //...
        // implementation is irrelevant
    }
}
</code>```

ProductHistoryComponent.ts:

```<code>import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

import { ProductService } from './product.service';

import { ProductHistory } from './product-history';
import { Product } from './model/product';

import 'rxjs/add/operator/switchMap';

@Component({
    selector: 'product-history',
    templateUrl: './product-history.component.html',
    styleUrls: [ './product-history.component.css' ]
})
export class ProductHistoryComponent implements OnInit {

    auditProducts: ProductHistory[] = new Array<ProductHistory[]>();
    selectedProduct: ProductHistory;

    constructor(
        private route: ActivatedRoute,
        private location: Location,
        private productService: ProductService
    ) {}

    ngOnInit(): void {
        let id: number = this.route.snapshot.params['id'];

        this.productService.getHistory(id)
            .then(history => this.historyProducts = history);

        this.productService.getProduct(id)
            .then(product => {
                let lastVersion: ProductHistory = this.createLastVersion(product);
                this.auditProducts.push(lastVersion);
            });
    }

    onSelect(ProductHistory: ProductHistory): void {
        this.selectedProduct = ProductHistory;
        this.compare(this.selectedProduct);
    }

    goBack(): void {
        this.location.back();
    }

    compare(history: ProductHistory): void {
        let previous: ProductHistory;
        if (history.changeNumber != null && history.changeNumber > 1) {
            previous = this.historyProducts[history.changeNumber - 2];
            if (typeof previous != 'undefined') {
                this.setPreviousDiffsFalse(previous);
                if (previous.name !== history.name) {
                    history.nameDiff = true;
                }
                if (previous.price !== history.price) {
                    history.priceDiff = true;
                }
            }
        }
    }

    createLastVersion(product: Product): ProductHistory {
        let lastVersionProduct: ProductHistory = new ProductHistory();
        lastVersionProduct.id = this.historyProducts.length + 1;
        lastVersionProduct.name = product.name;
        lastVersionProduct.price = product.price;
        lastVersionProduct.changeNumber = this.historyProducts[this.historyProducts.length - 1].changeNumber + 1;
        return lastVersionProduct;
    }

    setPreviousDiffsFalse(previous: ProductHistory): void {
        previous.nameDiff = false;
        previous.priceDiff = false;
    }

}
</code>```

答:
You can't run it synchronously, you have to wait  for each promise to return a result before you can do something with that result. The normal way to do this is to nest code inside then blocks when using promises. Alternatively you can also use async/await with the latest version of typescript and you only have to change your component code as you are already returning the Promise type from your service. This makes code easier to read (IMO) although the emitted javascript code will still use function/callback nesting (unless you are targeting es7 I believe, maybe someone will correct or confirm this).

```<code>// note the use of async and await which gives the appearance of synchronous execution
async ngOnInit() {
    let id: number = this.route.snapshot.params['id'];

    const history = await this.productService.getHistory(id);
    this.historyProducts = history;

    const product = await this.productService.getProduct(id);
    let lastVersion: ProductHistory = this.createLastVersion(product);
    this.auditProducts.push(lastVersion);
}
</code>```

Body:
I want to print history of products. I have an id of product in ActivatedRoute.params. In ngOnInit method I have to get all history of product and assign to variable. Then I want to map product to productHistory, because I want to have last version with history toghether. But the problem is with getting history. Method to getting history return Promise and I cannot get length of productsHistory when I use this property and I get undefined. How can I get this property after loading from service?

I want to execute method after execution getHistory().

My code:

ProductService.ts:

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

// rest imports

@Injectable()
export class ProductService {

    // URL to web api
    private projectsUrl = 'http://localhost:8080/products';

    private headers = new Headers({'Content-Type': 'application/json'});

    constructor(private http: Http) {}

    getHistory(id: number): Promise<ProductHistory[]> {
        const url = `${this.projectsUrl}/projectId/${id}`;
        return this.http.get(url)
            .toPromise()
            .then(response => response.json() as ProductHistory[])
            .catch(this.handleError);
    }

    handleError() {
        //...
        // implementation is irrelevant
    }
}

ProductHistoryComponent.ts:

import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

import { ProductService } from './product.service';

import { ProductHistory } from './product-history';
import { Product } from './model/product';

import 'rxjs/add/operator/switchMap';

@Component({
    selector: 'product-history',
    templateUrl: './product-history.component.html',
    styleUrls: [ './product-history.component.css' ]
})
export class ProductHistoryComponent implements OnInit {

    auditProducts: ProductHistory[] = new Array<ProductHistory[]>();
    selectedProduct: ProductHistory;

    constructor(
        private route: ActivatedRoute,
        private location: Location,
        private productService: ProductService
    ) {}

    ngOnInit(): void {
        let id: number = this.route.snapshot.params['id'];

        this.productService.getHistory(id)
            .then(history => this.historyProducts = history);

        this.productService.getProduct(id)
            .then(product => {
                let lastVersion: ProductHistory = this.createLastVersion(product);
                this.auditProducts.push(lastVersion);
            });
    }

    onSelect(ProductHistory: ProductHistory): void {
        this.selectedProduct = ProductHistory;
        this.compare(this.selectedProduct);
    }

    goBack(): void {
        this.location.back();
    }

    compare(history: ProductHistory): void {
        let previous: ProductHistory;
        if (history.changeNumber != null && history.changeNumber > 1) {
            previous = this.historyProducts[history.changeNumber - 2];
            if (typeof previous != 'undefined') {
                this.setPreviousDiffsFalse(previous);
                if (previous.name !== history.name) {
                    history.nameDiff = true;
                }
                if (previous.price !== history.price) {
                    history.priceDiff = true;
                }
            }
        }
    }

    createLastVersion(product: Product): ProductHistory {
        let lastVersionProduct: ProductHistory = new ProductHistory();
        lastVersionProduct.id = this.historyProducts.length + 1;
        lastVersionProduct.name = product.name;
        lastVersionProduct.price = product.price;
        lastVersionProduct.changeNumber = this.historyProducts[this.historyProducts.length - 1].changeNumber + 1;
        return lastVersionProduct;
    }

    setPreviousDiffsFalse(previous: ProductHistory): void {
        previous.nameDiff = false;
        previous.priceDiff = false;
    }

}

Body:
You can't run it synchronously, you have to wait  for each promise to return a result before you can do something with that result. The normal way to do this is to nest code inside then blocks when using promises. Alternatively you can also use async/await with the latest version of typescript and you only have to change your component code as you are already returning the Promise type from your service. This makes code easier to read (IMO) although the emitted javascript code will still use function/callback nesting (unless you are targeting es7 I believe, maybe someone will correct or confirm this).

// note the use of async and await which gives the appearance of synchronous execution
async ngOnInit() {
    let id: number = this.route.snapshot.params['id'];

    const history = await this.productService.getHistory(id);
    this.historyProducts = history;

    const product = await this.productService.getProduct(id);
    let lastVersion: ProductHistory = this.createLastVersion(product);
    this.auditProducts.push(lastVersion);
}


问:
Excel if text string contains todays date
A colleague of mine is trying to come up with a formula to see if a text string contains today's date, so it would be something like

```<code>=IF(A1=TODAY(),1,0)
</code>```

Except the date is contained in a text string, not just on it's own, so like

```<code>=IF(A1="TODAY()",1,0)
</code>```

Though of course that doesn't work. Essentially it's how can you place wildcards on the side of a formula like that to make it work?

答:
Use the SEARCH function to search a string for a substring. Alternatively you can use the FIND function however this is case-sensitive.

The issue you're going to face is that the TODAY() function actually outputs a serial number, not a formatted date so you will need to first format this number within the formula using the TEXT function (provided you know what format the date will be in). You can then use ISNUMBER to check whether the SEARCH function returns a hit, like this:

```<code>=IF(ISNUMBER(SEARCH(TEXT(TODAY(),"dd/mm/yyyy"), A1)),1,0)
</code>```

This will only work if you know the format of the date.

If the date could be in multiple different formats you could combine these together with an OR statement to check the different formats like this:

```<code>=IF(OR(ISNUMBER(SEARCH(TEXT(TODAY(),"dd/mm/yyyy"), A1)),ISNUMBER(SEARCH(TEXT(TODAY(),"dd/mm/yy"), A1)),ISNUMBER(SEARCH(TEXT(TODAY(),"d/m/yy"), A1))),1,0)
</code>```

Body:
A colleague of mine is trying to come up with a formula to see if a text string contains today's date, so it would be something like

=IF(A1=TODAY(),1,0)

Except the date is contained in a text string, not just on it's own, so like

=IF(A1="TODAY()",1,0)

Though of course that doesn't work. Essentially it's how can you place wildcards on the side of a formula like that to make it work?

Body:
Use the SEARCH function to search a string for a substring. Alternatively you can use the FIND function however this is case-sensitive.

The issue you're going to face is that the TODAY() function actually outputs a serial number, not a formatted date so you will need to first format this number within the formula using the TEXT function (provided you know what format the date will be in). You can then use ISNUMBER to check whether the SEARCH function returns a hit, like this:

=IF(ISNUMBER(SEARCH(TEXT(TODAY(),"dd/mm/yyyy"), A1)),1,0)

This will only work if you know the format of the date.

If the date could be in multiple different formats you could combine these together with an OR statement to check the different formats like this:

=IF(OR(ISNUMBER(SEARCH(TEXT(TODAY(),"dd/mm/yyyy"), A1)),ISNUMBER(SEARCH(TEXT(TODAY(),"dd/mm/yy"), A1)),ISNUMBER(SEARCH(TEXT(TODAY(),"d/m/yy"), A1))),1,0)


问:
How does PHP actually work?
Is there some guide out there that describes how the PHP internals?

How files are loaded (required, included)?

How they are parsed and executed?

How memory is allocated?

How objects are created/destroyed?

How external modules are loaded?

How the stack/heap works?

How opcode caching actually work?

Common hacks and performance tips?

答:
Sounds to me like you're you should look for resources on PHP Internal development. Looking for this information elsewhere will be really scattered.

I suggest picking up a PHP Core development book from your local book store and giving it a read. PHP.net has an underdeveloped beginners reference if you wanted to start there.

Title: How does PHP actually work?

ContentLicense: CC BY-SA 2.5