问:
I am trying to nest a map into a filter in RxJava2, so I can remove all objects that don't have the correct platform. But can't build it
```<code>override fun getVideoGamesRepository(platformName: String) {
    gameRepo = VideoGameRepositoryImpl()
    compositeDisposable.add(gameRepo.returnVideoGames()
        .filter { gameModel -> gameModel.gamesResults.map {  } }
        .subscribe())
}
</code>```

Here is the method I have for filtering the data from the api. I will include a snippet of the data only for what is relevant.

I am trying to compare the value of the platform name in the database with the platform name I have entered in the previous activity. But the .map is underlined red at .map inside the filter.

```<code>{
"count": 363773,
"next": "https://api.rawg.io/api/games?page=3",
"previous": "https://api.rawg.io/api/games",
"results": [
    {
        "id": 28,
        "slug": "red-dead-redemption-2",
        "name": "Red Dead Redemption 2",
        "released": "2018-10-26",
        "tba": false,
        "background_image": "https://media.rawg.io/media/games/511/5118aff5091cb3efec399c808f8c598f.jpg",
        "rating": 4.54,
        "rating_top": 5,
        "ratings": [
            {
                "id": 5,
                "title": "exceptional",
                "count": 1466,
                "percent": 70.28
            },
            {
                "id": 4,
                "title": "recommended",
                "count": 409,
                "percent": 19.61
            },
            {
                "id": 3,
                "title": "meh",
                "count": 143,
                "percent": 6.86
            },
            {
                "id": 1,
                "title": "skip",
                "count": 68,
                "percent": 3.26
            }
        ],
        "ratings_count": 2056,
        "reviews_text_count": 25,
        "added": 6296,
        "added_by_status": {
            "yet": 284,
            "owned": 3522,
            "beaten": 912,
            "toplay": 951,
            "dropped": 161,
            "playing": 466
        },
        "metacritic": null,
        "playtime": 22,
        "suggestions_count": 630,
        "user_game": null,
        "reviews_count": 2086,
        "saturated_color": "0f0f0f",
        "dominant_color": "0f0f0f",
        "platforms": [
            {
                "platform": {
                    "id": 4,
                    "name": "PC",
                    "slug": "pc",
                    "image": null,
                    "year_end": null,
                    "year_start": null,
                    "games_count": 203916,
                    "image_background": "https://media.rawg.io/media/games/8e0/8e032ac4faf1136e7d708bb3ac61af23.jpg"
                },
                "released_at": "2018-10-26",
                "requirements_en": null,
                "requirements_ru": null
            },
            {
                "platform": {
                    "id": 1,
                    "name": "Xbox One",
                    "slug": "xbox-one",
                    "image": null,
                    "year_end": null,
                    "year_start": null,
                    "games_count": 3085,
                    "image_background": "https://media.rawg.io/media/games/c24/c24ec439abf4a2e92f3429dfa83f7f94.jpg"
                },
                "released_at": "2018-10-26",
                "requirements_en": null,
                "requirements_ru": null
            },
            {
                "platform": {
                    "id": 18,
                    "name": "PlayStation 4",
                    "slug": "playstation4",
                    "image": null,
                    "year_end": null,
                    "year_start": null,
                    "games_count": 4504,
                    "image_background": "https://media.rawg.io/media/games/4be/4be6a6ad0364751a96229c56bf69be59.jpg"
                },
                "released_at": "2018-10-26",
                "requirements_en": null,
                "requirements_ru": null
            }
        ],
</code>```

答:
filter method takes predicate as a parameter. So you have to define a condition that returns true or false for your filter.

According to your model following code should return game results which contains your desired platform.

```<code>compositeDisposable.add(gameRepo.returnVideoGames()
  .map { gameModel ->
    gameModel.gamesResults.filter { gameResult -> gameResult.platforms.any { platform -> platform.name == platformName } }
  }
  .subscribe())
</code>```

Also it seems you're storing the whole response object in your database. But I think this is unnecessary and not quite practical. Instead you could store the game result objects. Thus allowing you to reduce number of operations to achieve the same result. For example:

```<code>compositeDisposable.add(gameRepo.returnVideoGames()
  .filter { gameResult -> gameResult.platforms.any { platform -> platform.name == platformName } }
  .subscribe())
</code>```

Body:
override fun getVideoGamesRepository(platformName: String) {
    gameRepo = VideoGameRepositoryImpl()
    compositeDisposable.add(gameRepo.returnVideoGames()
        .filter { gameModel -> gameModel.gamesResults.map {  } }
        .subscribe())
}

Here is the method I have for filtering the data from the api. I will include a snippet of the data only for what is relevant.

I am trying to compare the value of the platform name in the database with the platform name I have entered in the previous activity. But the .map is underlined red at .map inside the filter.

{
"count": 363773,
"next": "https://api.rawg.io/api/games?page=3",
"previous": "https://api.rawg.io/api/games",
"results": [
    {
        "id": 28,
        "slug": "red-dead-redemption-2",
        "name": "Red Dead Redemption 2",
        "released": "2018-10-26",
        "tba": false,
        "background_image": "https://media.rawg.io/media/games/511/5118aff5091cb3efec399c808f8c598f.jpg",
        "rating": 4.54,
        "rating_top": 5,
        "ratings": [
            {
                "id": 5,
                "title": "exceptional",
                "count": 1466,
                "percent": 70.28
            },
            {
                "id": 4,
                "title": "recommended",
                "count": 409,
                "percent": 19.61
            },
            {
                "id": 3,
                "title": "meh",
                "count": 143,
                "percent": 6.86
            },
            {
                "id": 1,
                "title": "skip",
                "count": 68,
                "percent": 3.26
            }
        ],
        "ratings_count": 2056,
        "reviews_text_count": 25,
        "added": 6296,
        "added_by_status": {
            "yet": 284,
            "owned": 3522,
            "beaten": 912,
            "toplay": 951,
            "dropped": 161,
            "playing": 466
        },
        "metacritic": null,
        "playtime": 22,
        "suggestions_count": 630,
        "user_game": null,
        "reviews_count": 2086,
        "saturated_color": "0f0f0f",
        "dominant_color": "0f0f0f",
        "platforms": [
            {
                "platform": {
                    "id": 4,
                    "name": "PC",
                    "slug": "pc",
                    "image": null,
                    "year_end": null,
                    "year_start": null,
                    "games_count": 203916,
                    "image_background": "https://media.rawg.io/media/games/8e0/8e032ac4faf1136e7d708bb3ac61af23.jpg"
                },
                "released_at": "2018-10-26",
                "requirements_en": null,
                "requirements_ru": null
            },
            {
                "platform": {
                    "id": 1,
                    "name": "Xbox One",
                    "slug": "xbox-one",
                    "image": null,
                    "year_end": null,
                    "year_start": null,
                    "games_count": 3085,
                    "image_background": "https://media.rawg.io/media/games/c24/c24ec439abf4a2e92f3429dfa83f7f94.jpg"
                },
                "released_at": "2018-10-26",
                "requirements_en": null,
                "requirements_ru": null
            },
            {
                "platform": {
                    "id": 18,
                    "name": "PlayStation 4",
                    "slug": "playstation4",
                    "image": null,
                    "year_end": null,
                    "year_start": null,
                    "games_count": 4504,
                    "image_background": "https://media.rawg.io/media/games/4be/4be6a6ad0364751a96229c56bf69be59.jpg"
                },
                "released_at": "2018-10-26",
                "requirements_en": null,
                "requirements_ru": null
            }
        ],

Body:
filter method takes predicate as a parameter. So you have to define a condition that returns true or false for your filter.

According to your model following code should return game results which contains your desired platform.

compositeDisposable.add(gameRepo.returnVideoGames()
  .map { gameModel ->
    gameModel.gamesResults.filter { gameResult -> gameResult.platforms.any { platform -> platform.name == platformName } }
  }
  .subscribe())

Also it seems you're storing the whole response object in your database. But I think this is unnecessary and not quite practical. Instead you could store the game result objects. Thus allowing you to reduce number of operations to achieve the same result. For example:

compositeDisposable.add(gameRepo.returnVideoGames()
  .filter { gameResult -> gameResult.platforms.any { platform -> platform.name == platformName } }
  .subscribe())


来源: stackexchange

问:
MaterialTable Sticky Header and Columns
I have a problem with materialTable https://material-table.com/#/ because I can't combine fixing the header and fixing columns on the left </p>

答:
It does'n have that feature, but you can add it with custom css</p>

```<code>table {
  position: relative;
  border-collapse: collapse;
}
th {
  position: sticky;
  top: 0;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: MaterialTable Sticky Header and Columns

Body:
It does'n have that feature, but you can add it with custom css

table {
  position: relative;
  border-collapse: collapse;
}
th {
  position: sticky;
  top: 0;
}


问:
Why is the exe I made using pyinstaller requiring administrator login?
I made an exe with pyinstaller but it requires an administrator login whenever it is run. I checked the manifest file and it matches the name of the executable. I have made executable files from py files before without the executables requiring administrator login so I am not sure what is going wrong.

I searched stackoverflow to see if anyone had a similar problem but all the solutions I found pointed to the manifest file's name being different from the executable's name which is not the problem in my case.

If it helps, I am using -F for onefile. Also, according to the window asking for administrator permission whenever the exe is run, administrator login is required because the exe has an unknown publisher.

答:
I don't know it this will solve your issue.
Few months ago, I was looking for the same thing and it came up that I need a real certificate. Never done it.

Trusted Publishers Certificate Store

The Trusted Publishers certificate store contains information about
  the Authenticode (signing) certificates of trusted publishers that are
  installed on a computer. In order to test and debug your driver
  packages within your organization, your company should install the
  Authenticode certificates that are used to sign driver packages in the
  Trusted Publishers certificate store. Install the Authenticode
  certificates on each computer in the workgroup or organizational unit
  that runs signed code. The name of the Trusted Publishers certificate
  store is trustedpublisher.


问:
C# destructor not called even after code scope + GC?
I've got a simple test code in Nunit+.net core 2.0 under VS2019:

```<code>public class Tests
{
    public static int i = 0;
    class First
    {
        ~First()
        {
            i += 1;
            Console.WriteLine("First's destructor is called.");
        }
    }

    class Second : First
    {
        ~Second() { i += 10; Console.WriteLine("Second's destructor is called."); }
    }

    class Third : Second
    {
        ~Third() { i += 100; Console.WriteLine("Third's destructor is called."); }
    }
    [Test]
    public static void Test()
    {
        {
            Third t = new Third();
        }
        Thread.Sleep(1000);
        System.GC.Collect();
        Assert.AreEqual(111, i);
    }
}
</code>```

It always fails, while I found finally i=0, and the destructors are called right after Test(). But you can see the "t" is in a code block, and is invalid after the code block, and I also called

```<code>System.GC.Collect();
</code>```

before my "Assert".

Why destructor is not called even after GC? How to fix my code to make the test pass?

Thanks a lot.

答:
Use using statement and the IDisposable interface instead destructor;

```<code> public class Tests
{
    public static int i = 0;
    class First : IDisposable
    {
        public virtual void Dispose()
        {
            i += 1; Console.WriteLine("First's Dispose is called.");
        }
    }

    class Second : First
    {
        public override void Dispose()
        {
            i += 10; Console.WriteLine("Second's Dispose is called.");
            base.Dispose();
        }
    }

    class Third : Second
    {
        public override void Dispose()
        {
            i += 100; Console.WriteLine("Third's Dispose is called.");
            base.Dispose();
        }
    }
    public static void Test()
    {
        using (Third t = new Third()) {
            Console.WriteLine("Now everything will be ok, after leaving this block");
            Console.WriteLine("t object will be dispose");
        }
        Thread.Sleep(1000);
        System.GC.Collect();
        Assert.AreEqual(111, i);
    }
}
</code>```

You can call System.GC.Collect() but it is not matter. The destructor will not be call immediately as you expect. (In above code you don't need System.GC.Collect())

It is strange to me why Microsoft does not make this clearer, instead of the old definition "Forces an immediate garbage collection of all generations." which leads developers to think they should expect an immediate result and GC.Collect() should wait for garbage collection to be complete before it returns?!

GC.Collect Method(System) - Microsoft Docs

Even more strange to me is that the code they give as an example for using of GC.Collect() don't work as they claim, for the same reason. You can try yourself by commenting GC.Collect(); line. I don't know, maybe they just don't update their documents as often. Maybe the situation was different before with GC.Collect()?! GC.CollectRequest() would be a more appropriate name for this function, if you ask me.

P.s. I'm new to C# so please, excuse me if I say things that do not fully understand or something I'm wrong in the code I write.

Body:
I've got a simple test code in Nunit+.net core 2.0 under VS2019:

public class Tests
{
    public static int i = 0;
    class First
    {
        ~First()
        {
            i += 1;
            Console.WriteLine("First's destructor is called.");
        }
    }

    class Second : First
    {
        ~Second() { i += 10; Console.WriteLine("Second's destructor is called."); }
    }

    class Third : Second
    {
        ~Third() { i += 100; Console.WriteLine("Third's destructor is called."); }
    }
    [Test]
    public static void Test()
    {
        {
            Third t = new Third();
        }
        Thread.Sleep(1000);
        System.GC.Collect();
        Assert.AreEqual(111, i);
    }
}

It always fails, while I found finally i=0, and the destructors are called right after Test(). But you can see the "t" is in a code block, and is invalid after the code block, and I also called

System.GC.Collect();

before my "Assert".

Why destructor is not called even after GC? How to fix my code to make the test pass?

Thanks a lot.

Body:
Use using statement and the IDisposable interface instead destructor;

 public class Tests
{
    public static int i = 0;
    class First : IDisposable
    {
        public virtual void Dispose()
        {
            i += 1; Console.WriteLine("First's Dispose is called.");
        }
    }

    class Second : First
    {
        public override void Dispose()
        {
            i += 10; Console.WriteLine("Second's Dispose is called.");
            base.Dispose();
        }
    }

    class Third : Second
    {
        public override void Dispose()
        {
            i += 100; Console.WriteLine("Third's Dispose is called.");
            base.Dispose();
        }
    }
    public static void Test()
    {
        using (Third t = new Third()) {
            Console.WriteLine("Now everything will be ok, after leaving this block");
            Console.WriteLine("t object will be dispose");
        }
        Thread.Sleep(1000);
        System.GC.Collect();
        Assert.AreEqual(111, i);
    }
}

You can call System.GC.Collect() but it is not matter. The destructor will not be call immediately as you expect. (In above code you don't need System.GC.Collect())

It is strange to me why Microsoft does not make this clearer, instead of the old definition "Forces an immediate garbage collection of all generations." which leads developers to think they should expect an immediate result and GC.Collect() should wait for garbage collection to be complete before it returns?!

GC.Collect Method(System) - Microsoft Docs

Even more strange to me is that the code they give as an example for using of GC.Collect() don't work as they claim, for the same reason. You can try yourself by commenting GC.Collect(); line. I don't know, maybe they just don't update their documents as often. Maybe the situation was different before with GC.Collect()?! GC.CollectRequest() would be a more appropriate name for this function, if you ask me.

P.s. I'm new to C# so please, excuse me if I say things that do not fully understand or something I'm wrong in the code I write.


问:
How to provide fixed 'key values' within a class?
I'm new to C#, and this is a very simple question, but as I can't figure out the right terminology for what I'm looking for, I'm struggling to google this for the simple answer.

I'd like the user of a class to be able to retrieve certain fixed values by name from within the class. As below:

```<code>byte mode = MyClass.Modes.ModeC;
</code>```

Where ModeC is a specific value of byte that the user will need to use.

I've seen this used everywhere, but I can't figure out what the best way to implement it is.

I've tried:

```<code>public class MyClass
{
    public class Modes
    {
        public static byte ModeA = 0x01;
        public static byte ModeB = 0x03;
        public static byte ModeC = 0x06;
        //etc
    }
}
</code>```

It seems to work.
Is this a sensible way to achieve this? What is this practice called?

Sorry for the very obvious question, but I'd appreciate any help I could get!

答:
One easy way can be using a static class with public const values.

```<code>public static class ApplicationConsts
{
    public const byte ModeA = 0x01;
    public const byte ModeB = 0x03;
    public const byte ModeC = 0x06;
}
</code>```

Then you would be able to use it as

```<code>var modeA = ApplicationConsts.ModeA;
</code>```

Body:
I'm new to C#, and this is a very simple question, but as I can't figure out the right terminology for what I'm looking for, I'm struggling to google this for the simple answer.

I'd like the user of a class to be able to retrieve certain fixed values by name from within the class. As below:

byte mode = MyClass.Modes.ModeC;

Where ModeC is a specific value of byte that the user will need to use.

I've seen this used everywhere, but I can't figure out what the best way to implement it is.

I've tried:

public class MyClass
{
    public class Modes
    {
        public static byte ModeA = 0x01;
        public static byte ModeB = 0x03;
        public static byte ModeC = 0x06;
        //etc
    }
}

It seems to work.
Is this a sensible way to achieve this? What is this practice called?

Sorry for the very obvious question, but I'd appreciate any help I could get!

Body:
One easy way can be using a static class with public const values.

public static class ApplicationConsts
{
    public const byte ModeA = 0x01;
    public const byte ModeB = 0x03;
    public const byte ModeC = 0x06;
}

Then you would be able to use it as

var modeA = ApplicationConsts.ModeA;


问:
Keycloak API, best way to get users by a list of ids
I´m using the official Keycloak API. I have a list of ids and would like to get all users represented by the ids. So let´s say i have a list with ids 1, 7, 9. Optimally i would would want to have a GET endpoint which accepts a list/array of ids as a PathVariable. But it seems like there´s no method like this. So i think i either have to send a seperate request for each id in the list and get the according user(which would result in n requests with a list of size n) or i have to get all users and filter them afterwards. Is there no better way?

答: You can create your own Keycloak extension like this one: https://github.com/cloudtrust/keycloak-rest-api-extensions. </p>


问:
Fail to alert input text value
I have a simple <input id="editfileFormTitleinput" type="text>. I want to alert the text within the input text field but I fail. This is what I've tried:

```<code>$('#editfileFormTitleinput').on('input', function() {
    alert($(this).attr('value'));
});
</code>```

I keep typing in the input text field things, but it only alerts undefined. How do I get the value of the input text field if not in this way?

答:
$('#editfileFormTitleinput').on('input', function() {
    alert($(this).val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id = "editfileFormTitleinput" ></code>```

Title: Fail to alert input text value

Body:
I have a simple <input id="editfileFormTitleinput" type="text>. I want to alert the text within the input text field but I fail. This is what I've tried:

$('#editfileFormTitleinput').on('input', function() {
    alert($(this).attr('value'));
});

I keep typing in the input text field things, but it only alerts undefined. How do I get the value of the input text field if not in this way?

Body:
$('#editfileFormTitleinput').on('input', function() {
    alert($(this).val());
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id = "editfileFormTitleinput" >


问:
Autolayout constraint disappearing at runtime
I have a simple table view cell containing two labels whose positioning constraints disappear at runtime (the width and aspect ration remain). There are no warnings, no errors in the storyboard view, no console log and I don't use size classes.

The views are misplaced (they stick to the top left corner) and when I launch the Debug View Hierarchy there is an exclamation mark on a purple background indicating an ambiguous position. Upon inspection it turns out that the position constraints are not there anymore.

I have tried removing and adding them again, I have compared almost every IB inspector in the view hierarchy with a working implementation and couldn't figure out a difference. I have inspected the views with lldb and the _autolayoutTrace doesn't show the constraints.

I know I can remove the controller in Interface Builder and rebuild it but I would appreciate an insight into debugging that kind of issue.

Here is the part of the storyboard describing the table view controller and prototype cell :

```<code><tableViewController id="RTg-bl-d8Z" customClass="ChekListViewController" customModule="Todo_app" customModuleProvider="target" sceneMemberID="viewController">
    <tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="5dF-Vx-S1N">
        <rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
        <color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
        <prototypes>
            <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" accessoryType="detailDisclosureButton" indentationWidth="10" reuseIdentifier="checkListItem" id="a6e-eR-CO4" customClass="CheckListItemCell" customModule="Todo_app" customModuleProvider="target">
                <rect key="frame" x="0.0" y="28" width="414" height="57.5"/>
                <autoresizingMask key="autoresizingMask"/>
                <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="a6e-eR-CO4" id="EUI-T4-UFi" customClass="CheckListItemCell" customModule="Todo_app" customModuleProvider="target">
                    <rect key="frame" x="0.0" y="0.0" width="351" height="57.5"/>
                    <autoresizingMask key="autoresizingMask"/>
                    <subviews>
                        <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="✔" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="KM3-zM-YXK">
                            <rect key="frame" x="28" y="11" width="25.5" height="35.5"/>
                            <constraints>
                                <constraint firstAttribute="width" constant="25" id="uyC-B0-CMt"/>
                                <constraint firstAttribute="width" secondItem="KM3-zM-YXK" secondAttribute="height" multiplier="25:35" id="yPH-cC-BhV"/>
                            </constraints>
                            <fontDescription key="fontDescription" type="system" pointSize="17"/>
                            <nil key="textColor"/>
                            <nil key="highlightedColor"/>
                        </label>
                        <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="I1F-jX-unK">
                            <rect key="frame" x="61.5" y="18.5" width="281.5" height="21"/>
                            <fontDescription key="fontDescription" type="system" pointSize="17"/>
                            <nil key="textColor"/>
                            <nil key="highlightedColor"/>
                        </label>
                    </subviews>
                    <constraints>
                        <constraint firstAttribute="trailingMargin" secondItem="I1F-jX-unK" secondAttribute="trailing" id="2DJ-vu-eZH"/>
                        <constraint firstItem="I1F-jX-unK" firstAttribute="centerY" secondItem="KM3-zM-YXK" secondAttribute="centerY" id="5sk-xI-Lws"/>
                        <constraint firstItem="KM3-zM-YXK" firstAttribute="leading" secondItem="EUI-T4-UFi" secondAttribute="leadingMargin" constant="8" id="T2a-1U-YX9"/>
                        <constraint firstItem="I1F-jX-unK" firstAttribute="leading" secondItem="KM3-zM-YXK" secondAttribute="trailing" constant="8" id="a2G-6H-iVm"/>
                        <constraint firstItem="KM3-zM-YXK" firstAttribute="bottom" secondItem="EUI-T4-UFi" secondAttribute="bottomMargin" id="c6K-zY-2tu"/>
                        <constraint firstItem="KM3-zM-YXK" firstAttribute="top" secondItem="EUI-T4-UFi" secondAttribute="topMargin" id="z4V-Rz-c6k"/>
                    </constraints>
                </tableViewCellContentView>
                <connections>
                    <outlet property="checkMark" destination="KM3-zM-YXK" id="qY4-JT-7iv"/>
                    <outlet property="textItem" destination="I1F-jX-unK" id="eID-MO-fVV"/>
                    <segue destination="Kuh-LZ-DVA" kind="presentation" identifier="editItem" trigger="accessoryAction" id="DeL-Ql-cQq"/>
                </connections>
            </tableViewCell>
        </prototypes>
        <sections/>
        <connections>
            <outlet property="dataSource" destination="RTg-bl-d8Z" id="34r-cH-2bg"/>
            <outlet property="delegate" destination="RTg-bl-d8Z" id="CsE-gc-hUN"/>
        </connections>
    </tableView>
    <navigationItem key="navigationItem" title="Name of the list" id="05Z-xs-cMG">
        <barButtonItem key="rightBarButtonItem" systemItem="add" id="oSl-fh-Gh3">
            <connections>
                <segue destination="Kuh-LZ-DVA" kind="presentation" identifier="addItem" id="6cn-yq-cSG"/>
            </connections>
        </barButtonItem>
    </navigationItem>
</tableViewController>
</code>```

答:
OK, that was not obvious... until it was :)

Somehow - either by an "oops" click or some Xcode / IB quirk - your cell's Content View got its class set to CheckListItemCell:

Select the cell's Content View, go to the Identity Inspector pane, and change the Custom Class back to the default UIView:

Better result:

Body:
I have a simple table view cell containing two labels whose positioning constraints disappear at runtime (the width and aspect ration remain). There are no warnings, no errors in the storyboard view, no console log and I don't use size classes.

The views are misplaced (they stick to the top left corner) and when I launch the Debug View Hierarchy there is an exclamation mark on a purple background indicating an ambiguous position. Upon inspection it turns out that the position constraints are not there anymore.

I have tried removing and adding them again, I have compared almost every IB inspector in the view hierarchy with a working implementation and couldn't figure out a difference. I have inspected the views with lldb and the _autolayoutTrace doesn't show the constraints.

I know I can remove the controller in Interface Builder and rebuild it but I would appreciate an insight into debugging that kind of issue.

Here is the part of the storyboard describing the table view controller and prototype cell :

<tableViewController id="RTg-bl-d8Z" customClass="ChekListViewController" customModule="Todo_app" customModuleProvider="target" sceneMemberID="viewController">
    <tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="5dF-Vx-S1N">
        <rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
        <color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
        <prototypes>
            <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" accessoryType="detailDisclosureButton" indentationWidth="10" reuseIdentifier="checkListItem" id="a6e-eR-CO4" customClass="CheckListItemCell" customModule="Todo_app" customModuleProvider="target">
                <rect key="frame" x="0.0" y="28" width="414" height="57.5"/>
                <autoresizingMask key="autoresizingMask"/>
                <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="a6e-eR-CO4" id="EUI-T4-UFi" customClass="CheckListItemCell" customModule="Todo_app" customModuleProvider="target">
                    <rect key="frame" x="0.0" y="0.0" width="351" height="57.5"/>
                    <autoresizingMask key="autoresizingMask"/>
                    <subviews>

                            <rect key="frame" x="28" y="11" width="25.5" height="35.5"/>
                            <constraints>
                                <constraint firstAttribute="width" constant="25" id="uyC-B0-CMt"/>
                                <constraint firstAttribute="width" secondItem="KM3-zM-YXK" secondAttribute="height" multiplier="25:35" id="yPH-cC-BhV"/>
                            </constraints>
                            <fontDescription key="fontDescription" type="system" pointSize="17"/>
                            <nil key="textColor"/>
                            <nil key="highlightedColor"/>

                            <rect key="frame" x="61.5" y="18.5" width="281.5" height="21"/>
                            <fontDescription key="fontDescription" type="system" pointSize="17"/>
                            <nil key="textColor"/>
                            <nil key="highlightedColor"/>

                    </subviews>
                    <constraints>
                        <constraint firstAttribute="trailingMargin" secondItem="I1F-jX-unK" secondAttribute="trailing" id="2DJ-vu-eZH"/>
                        <constraint firstItem="I1F-jX-unK" firstAttribute="centerY" secondItem="KM3-zM-YXK" secondAttribute="centerY" id="5sk-xI-Lws"/>
                        <constraint firstItem="KM3-zM-YXK" firstAttribute="leading" secondItem="EUI-T4-UFi" secondAttribute="leadingMargin" constant="8" id="T2a-1U-YX9"/>
                        <constraint firstItem="I1F-jX-unK" firstAttribute="leading" secondItem="KM3-zM-YXK" secondAttribute="trailing" constant="8" id="a2G-6H-iVm"/>
                        <constraint firstItem="KM3-zM-YXK" firstAttribute="bottom" secondItem="EUI-T4-UFi" secondAttribute="bottomMargin" id="c6K-zY-2tu"/>
                        <constraint firstItem="KM3-zM-YXK" firstAttribute="top" secondItem="EUI-T4-UFi" secondAttribute="topMargin" id="z4V-Rz-c6k"/>
                    </constraints>
                </tableViewCellContentView>
                <connections>
                    <outlet property="checkMark" destination="KM3-zM-YXK" id="qY4-JT-7iv"/>
                    <outlet property="textItem" destination="I1F-jX-unK" id="eID-MO-fVV"/>
                    <segue destination="Kuh-LZ-DVA" kind="presentation" identifier="editItem" trigger="accessoryAction" id="DeL-Ql-cQq"/>
                </connections>
            </tableViewCell>
        </prototypes>
        <sections/>
        <connections>
            <outlet property="dataSource" destination="RTg-bl-d8Z" id="34r-cH-2bg"/>
            <outlet property="delegate" destination="RTg-bl-d8Z" id="CsE-gc-hUN"/>
        </connections>
    </tableView>
    <navigationItem key="navigationItem" title="Name of the list" id="05Z-xs-cMG">
        <barButtonItem key="rightBarButtonItem" systemItem="add" id="oSl-fh-Gh3">
            <connections>
                <segue destination="Kuh-LZ-DVA" kind="presentation" identifier="addItem" id="6cn-yq-cSG"/>
            </connections>
        </barButtonItem>
    </navigationItem>
</tableViewController>


问:
How to fix the aws CODE BUILD COMMAND_EXECUTION_ERROR exit status 255
Iam configuring CICD piepline usng aws services code build pilepileline etc, to update the deploymnet in my ecs fargate cluster, In my buildspec.yml file  aws ecs cli commands are  failing throwing "COMMAND_EXECUTION_ERROR: Error while executing command: aws ecs update-service --services xxxxx. Reason: exit status 255" </p>

<p>I have tried providing permission to the codebuild role with "AmazonECS_FullAccess" policy. </p>

```<code>post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker images...
      - docker push $REPOSITORY_URI:latest
      - docker push $REPOSITORY_URI:$IMAGE_TAG
      - echo Writing image definitions file...
      - printf '[{"name":"xxxxxxx","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json
      - cat imagedefinitions.json
      - echo Updating ECSfargate service ...
      - aws ecs describe-services --services xxxxxxxxxxxxxxxxx
      - aws ecs update-service --service xxxxxxxxxxxxxxxxx --desired-count 2 --no-force-new-deployment

</code>```

答: Attaching a policy of AmazonEC2ContainerRegistryPowerUser fixed this issue for me.

Body:
Iam configuring CICD piepline usng aws services code build pilepileline etc, to update the deploymnet in my ecs fargate cluster, In my buildspec.yml file  aws ecs cli commands are  failing throwing "COMMAND_EXECUTION_ERROR: Error while executing command: aws ecs update-service --services xxxxx. Reason: exit status 255"

I have tried providing permission to the codebuild role with "AmazonECS_FullAccess" policy.

post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker images...
      - docker push $REPOSITORY_URI:latest
      - docker push $REPOSITORY_URI:$IMAGE_TAG
      - echo Writing image definitions file...
      - printf '[{"name":"xxxxxxx","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json
      - cat imagedefinitions.json
      - echo Updating ECSfargate service ...
      - aws ecs describe-services --services xxxxxxxxxxxxxxxxx
      - aws ecs update-service --service xxxxxxxxxxxxxxxxx --desired-count 2 --no-force-new-deployment


问:
Angular add a random JPG image?
I have created an Angular app that has a button which adds a new item to the list, here is a picture of it:

I searched for sites that provide random images and found "picsum.photos" (Lorem Picsum), which upon refresh indeed gives me a random picture each time.

I've tried implementing this in the code, but I'm getting the same image every time.

TypeScript Code:

```<code>imgUrl = 'https://some_long_path.jpeg';
randomImgUrl = 'https://picsum.photos/536/354';

recipes1: Recipes[] = [
    new Recipes('A Test Recipe',
      'This is simply a test', this.imgUrl)
];

addRecipe() {
   this.recipes1.push(new Recipes('name', 'description', this.randomImgUrl));
}
</code>```

HTML Code:

```<code><button class="btn btn-success" (click)="addRecipe()" (keyup.d)="removeRecipe()">New Recipe</button>
</code>```

It seems only one random image link gets saved into the variable 'randomImgUrl'...

Does anyone know what is the issue? How can I get a random image each time I call the addRecipe() function?

Thank you!

答:
use random number in randomImgUrl</p>

```<code>addRecipe() {
this.randomImgUrl=`https://i.picsum.photos/id/${Math.round(Math.random() * 1000)}/535/535.jpg`;
   this.recipes1.push(new Recipes('name', 'description', this.randomImgUrl));
}
</code>```

Title: Angular add a random JPG image?

Body:
I have created an Angular app that has a button which adds a new item to the list, here is a picture of it:

I searched for sites that provide random images and found "picsum.photos" (Lorem Picsum), which upon refresh indeed gives me a random picture each time.

I've tried implementing this in the code, but I'm getting the same image every time.

TypeScript Code:

imgUrl = 'https://some_long_path.jpeg';
randomImgUrl = 'https://picsum.photos/536/354';

recipes1: Recipes[] = [
    new Recipes('A Test Recipe',
      'This is simply a test', this.imgUrl)
];

addRecipe() {
   this.recipes1.push(new Recipes('name', 'description', this.randomImgUrl));
}

HTML Code:

<button class="btn btn-success" (click)="addRecipe()" (keyup.d)="removeRecipe()">New Recipe</button>

It seems only one random image link gets saved into the variable 'randomImgUrl'...

Does anyone know what is the issue? How can I get a random image each time I call the addRecipe() function?

Thank you!

Body:
use random number in randomImgUrl

addRecipe() {
this.randomImgUrl=`https://i.picsum.photos/id/${Math.round(Math.random() * 1000)}/535/535.jpg`;
   this.recipes1.push(new Recipes('name', 'description', this.randomImgUrl));
}


问:
Date Time in SQL Server 2005
I have a datetime column in table that has time component.

Is there anyway I can set '2011-03-14 11:46:31' to '2011-03-14 00:00:00'?

答:
As all the previous answers are the same, I'll add the other "good" option I know of:

```<code>SELECT DateAdd(Day, 0, DateDiff(Day, 0, GetDate()))
</code>```

This is preferred by some/many people because it doesn't rely on the undocumented/unsupported fact that days are represented by integers in DateTime/SmallDateTime.

There have been interesting discussions on this topic in the SqlServerCentral.com forums, but I couldn't quickly find a link, sorry.

UPDATE: Gail Shaw posted a nice quick performance comparison of the common methods (this one apparently is fastest, but only by a v small amount): http://sqlinthewild.co.za/index.php/2008/09/04/comparing-date-truncations/

ContentLicense: CC BY-SA 3.0

Title: Date Time in SQL Server 2005

Body:
As all the previous answers are the same, I'll add the other "good" option I know of:

SELECT DateAdd(Day, 0, DateDiff(Day, 0, GetDate()))

This is preferred by some/many people because it doesn't rely on the undocumented/unsupported fact that days are represented by integers in DateTime/SmallDateTime.

There have been interesting discussions on this topic in the SqlServerCentral.com forums, but I couldn't quickly find a link, sorry.

UPDATE: Gail Shaw posted a nice quick performance comparison of the common methods (this one apparently is fastest, but only by a v small amount): http://sqlinthewild.co.za/index.php/2008/09/04/comparing-date-truncations/


答:
You can make it even more simpler like this </p>

```<code>$('#editfileFormTitleinput').on('input', function() {
  alert(this.value)
});
</code>```

Title: Fail to alert input text value

Body:
You can make it even more simpler like this

$('#editfileFormTitleinput').on('input', function() {
  alert(this.value)
});


问:
How to make internal link to go to another component's ID element - Angular
Problem Statement

I cannot seem to use an internal link in the  tag to go to another component's specific section by HTML ID.

What I've tried

I went to this site: https://www.w3schools.com/html/html_links.asp and found nothing related to what I am doing.

Also, I went to this site https://www.yourhtmlsource.com/text/internallinks.html and found the thing that is related to my problem. The part is called: "Linking to parts of other documents" and this doesn't seem to work: href="http://www.yourhtmlsource.com/text/internallinks.html#section-names">. It basically links to another document and it goes to a specific section of that site, but alas, it does not work for me.

My Code

This is the page I am linking from:

```<code><a href="../products/products.component.html#backToTopBtn"><button mat-raised-button class="productsServicesBtn">Products
      <br>Services</button></a>
</code>```

This is the page I want to link to:

```<code><body>
  <button mat-raised-button id="backToTopBtn">Back to Top</button>
</body>
</code>```

Please Note: These are two different Angular components.

Explanation Of Code

As you can see, I am using what the second website has told me to do inside the href with the HTML ID at the end of the link to tell the browser which section to go to. It does not work.

FYI, the ID at the end is called a "fragment identifier".

Expected Results

The "internal" link opens up the other page and goes to the specific section which I mentioned.

Actual Results

The link does nothing and does not go anywhere.

答:
Firstly, you should set up your links using the routerLink directive.

```<code><a routerLink="/products">
  <button mat-raised-button class="productsServicesBtn">
    Products<br>Services
  </button>
</a>
</code>```

This is assuming you have set up your route. You should read up on routing if not.

```<code>  { path: 'products', component: ProductsComponent }
</code>```

Secondly, you specify the fragment via the fragment input of the routerLink directive:

```<code><a routerLink="/products" fragment="backToTopBtn">
  <button mat-raised-button class="productsServicesBtn">
    Products<br>Services
  </button>
</a>
</code>```

Finally, you need to enable anchor scrolling when you import the router module, as scrolling to the fragment is disabled by default:

```<code>imports: [
  RouterModule.forRoot([
    { path: 'products', component: ProductsComponent }
  ], { anchorScrolling: 'enabled' })
]
</code>```

DEMO: https://stackblitz.com/edit/router-template-4uagmq

Body:
Problem Statement

I cannot seem to use an internal link in the  tag to go to another component's specific section by HTML ID.

What I've tried

I went to this site: https://www.w3schools.com/html/html_links.asp and found nothing related to what I am doing.

Also, I went to this site https://www.yourhtmlsource.com/text/internallinks.html and found the thing that is related to my problem. The part is called: "Linking to parts of other documents" and this doesn't seem to work: . It basically links to another document and it goes to a specific section of that site, but alas, it does not work for me.

My Code

This is the page I am linking from:

<button mat-raised-button class="productsServicesBtn">Products

Services</button>

This is the page I want to link to:

  <button mat-raised-button id="backToTopBtn">Back to Top</button>

Please Note: These are two different Angular components.

Explanation Of Code

As you can see, I am using what the second website has told me to do inside the href with the HTML ID at the end of the link to tell the browser which section to go to. It does not work.

FYI, the ID at the end is called a "fragment identifier".

Expected Results

The "internal" link opens up the other page and goes to the specific section which I mentioned.

Actual Results

The link does nothing and does not go anywhere.

Body:
Firstly, you should set up your links using the routerLink directive.

<a routerLink="/products">
  <button mat-raised-button class="productsServicesBtn">
    Products<br>Services
  </button>
</a>

This is assuming you have set up your route. You should read up on routing if not.

  { path: 'products', component: ProductsComponent }

Secondly, you specify the fragment via the fragment input of the routerLink directive:

<a routerLink="/products" fragment="backToTopBtn">
  <button mat-raised-button class="productsServicesBtn">
    Products<br>Services
  </button>
</a>

Finally, you need to enable anchor scrolling when you import the router module, as scrolling to the fragment is disabled by default:

imports: [
  RouterModule.forRoot([
    { path: 'products', component: ProductsComponent }
  ], { anchorScrolling: 'enabled' })
]

DEMO: https://stackblitz.com/edit/router-template-4uagmq


问:
How to exclude some files from the loop in shell script
```<code>#! /bin/sh
for file in $Files/*.txt; do
    chmod 777 $file
done
</code>```

It will give permission 777 to all .txt files but I've 7 other .txt file for which I don't want to give 777 permission. How can I do that?

答:
you can add a conditional check as below. As there's no clear attribute differentiating the files you want to exclude, you'd need to specifically check for each name :</p>

```<code>for file in $Files/*.txt
do
    if [ "$file" = abra.txt -o "$file" = aura.txt -o "$file" = cab.txt -o "$file" = college.txt -o "$file" = jamla.txt -o "$file" = kalut.txt -o "$file" = school.txt  ]
    then
       continue
    fi
    chmod 777 "$file"
done
</code>```

Body:
#! /bin/sh
for file in $Files/*.txt; do
    chmod 777 $file
done

It will give permission 777 to all .txt files but I've 7 other .txt file for which I don't want to give 777 permission. How can I do that?

Body:
you can add a conditional check as below. As there's no clear attribute differentiating the files you want to exclude, you'd need to specifically check for each name :

for file in $Files/*.txt
do
    if [ "$file" = abra.txt -o "$file" = aura.txt -o "$file" = cab.txt -o "$file" = college.txt -o "$file" = jamla.txt -o "$file" = kalut.txt -o "$file" = school.txt  ]
    then
       continue
    fi
    chmod 777 "$file"
done


问:
Add componentDidMount in export default function and get the error of "Unexpected token, expected ";"
I was just take the drawer component from material-ui components. but I wan to change some code inside to call out my api. So I use the method of componentDidMount, but I get the error of Parsing error: Unexpected token, expected ";" in the componentDidMount. I also try to put it inside export default function but also get fail. I am not sure is it anyway I make a mistake? or is it any way I can get the fetch my API?

consider code below:

```<code>componentDidMount() {
  const loginEmail = localStorage.getItem('loginEmail');
  this.setState({loginEmail})
  console.log(loginEmail)
  fetch(`http://localhost:9000/api/item/view${loginEmail}`,)
    .then((resp) => {
      resp.json()
        .then((res) => {
          console.log(res.data.user_info.id);
          //  localStorage.setItem('id', res.data.user_info.id);
          this.setState({data: res.data});
        })
    })
}
}

export default function PermanentDrawerLeft() {
  const classes = useStyles();
  return (
   ...// the drawer code take from material-ui.com
  );
}
</code>```

答:
Other than a possible bad copy/paste job, you have a dangling comma in your fetch and an extra closing }.

```<code>componentDidMount() {
  const loginEmail = localStorage.getItem('loginEmail');
  this.setState({loginEmail})
  console.log(loginEmail)
  fetch(`http://localhost:9000/api/item/view${loginEmail}`,) // <- dangling comma
    .then((resp) => {
      resp.json()
        .then((res) => {
          console.log(res.data.user_info.id);
          //  localStorage.setItem('id', res.data.user_info.id);
          this.setState({data: res.data});
        })
    })
}
</code>```

Remove the comma and unnest (i.e. flatten) your promise chain, and consistently use semicolons to end your expressions.

```<code>componentDidMount() {
  const loginEmail = localStorage.getItem('loginEmail');
  this.setState({loginEmail});
  console.log(loginEmail);
  fetch(`http://localhost:9000/api/item/view${loginEmail}`)
    .then(resp => resp.json())
    .then(res => {
      console.log(res.data.user_info.id);
      //  localStorage.setItem('id', res.data.user_info.id);
      this.setState({data: res.data});
    });
}
</code>```

Also, I think you've confused functional components and class-based components.componentDidMount is a class-based react component lifecycle function only; it doesn't work the same way in a functional component. As written, it isn't valid syntax; it would need to be inside an object or class (i.e. like a class-based component). The correct syntax to declare standalone functions is to use the keyword function.

```<code>function componentDidMount() {
  const loginEmail = localStorage.getItem('loginEmail');
  this.setState({loginEmail});
  console.log(loginEmail);
  fetch(`http://localhost:9000/api/item/view${loginEmail}`)
    .then(resp => resp.json())
    .then(res => {
      console.log(res.data.user_info.id);
      //  localStorage.setItem('id', res.data.user_info.id);
      this.setState({data: res.data});
    });
}
</code>```

Body:
I was just take the drawer component from material-ui components. but I wan to change some code inside to call out my api. So I use the method of componentDidMount, but I get the error of Parsing error: Unexpected token, expected ";" in the componentDidMount. I also try to put it inside export default function but also get fail. I am not sure is it anyway I make a mistake? or is it any way I can get the fetch my API?

consider code below:

componentDidMount() {
  const loginEmail = localStorage.getItem('loginEmail');
  this.setState({loginEmail})
  console.log(loginEmail)
  fetch(`http://localhost:9000/api/item/view${loginEmail}`,)
    .then((resp) => {
      resp.json()
        .then((res) => {
          console.log(res.data.user_info.id);
          //  localStorage.setItem('id', res.data.user_info.id);
          this.setState({data: res.data});
        })
    })
}
}

export default function PermanentDrawerLeft() {
  const classes = useStyles();
  return (
   ...// the drawer code take from material-ui.com
  );
}

Body:
Other than a possible bad copy/paste job, you have a dangling comma in your fetch and an extra closing }.

componentDidMount() {
  const loginEmail = localStorage.getItem('loginEmail');
  this.setState({loginEmail})
  console.log(loginEmail)
  fetch(`http://localhost:9000/api/item/view${loginEmail}`,) // <- dangling comma
    .then((resp) => {
      resp.json()
        .then((res) => {
          console.log(res.data.user_info.id);
          //  localStorage.setItem('id', res.data.user_info.id);
          this.setState({data: res.data});
        })
    })
}

Remove the comma and unnest (i.e. flatten) your promise chain, and consistently use semicolons to end your expressions.

componentDidMount() {
  const loginEmail = localStorage.getItem('loginEmail');
  this.setState({loginEmail});
  console.log(loginEmail);
  fetch(`http://localhost:9000/api/item/view${loginEmail}`)
    .then(resp => resp.json())
    .then(res => {
      console.log(res.data.user_info.id);
      //  localStorage.setItem('id', res.data.user_info.id);
      this.setState({data: res.data});
    });
}

Also, I think you've confused functional components and class-based components.componentDidMount is a class-based react component lifecycle function only; it doesn't work the same way in a functional component. As written, it isn't valid syntax; it would need to be inside an object or class (i.e. like a class-based component). The correct syntax to declare standalone functions is to use the keyword function.

function componentDidMount() {
  const loginEmail = localStorage.getItem('loginEmail');
  this.setState({loginEmail});
  console.log(loginEmail);
  fetch(`http://localhost:9000/api/item/view${loginEmail}`)
    .then(resp => resp.json())
    .then(res => {
      console.log(res.data.user_info.id);
      //  localStorage.setItem('id', res.data.user_info.id);
      this.setState({data: res.data});
    });
}


答:
You can do this :

```<code>find . ! -iregex '.*/school\.txt\|.*/college.txt\|.*/abra\.txt\|.*/cab\.txt\|.*/jamla\.txt\|.*/kalut\.txt\|.*/aura\.txt' -exec chmod 777 {} \;
</code>```

And it will do. Let me know if it helps!

Title: How to exclude some files from the loop in shell script

Body:
You can do this :

find . ! -iregex '.*/school\.txt\|.*/college.txt\|.*/abra\.txt\|.*/cab\.txt\|.*/jamla\.txt\|.*/kalut\.txt\|.*/aura\.txt' -exec chmod 777 {} \;

And it will do. Let me know if it helps!


问:
Using query with group_concat to loop values but show lowest price
I am using the query below to get all results and then then group them. It all works well. I now have multiple rows of identical data but with a different price.

How can I do the same query but get just the row with the cheapest price when all other data is identical. I have spent ages but no joy at all. Please help.

```<code>$results = $wpdb->get_results($wpdb->prepare("

SELECT *,
group_concat(date,':',SUBSTRING_INDEX(flights,'|',2),':',price,':',board,':',$tablename.id separator ',') as itemx

FROM $tablename
WHERE post_type = 'product'
GROUP BY brochure
LIMIT 20
"));
</code>```

答:
Presumably, you want something like this:

```<code>SELECT t.*,
FROM $tablename t
WHERE t.post_type = 'product' AND
      t.price = (SELECT MIN(t2.price)
                 FROM $tablename t2
                 WHERE t2.post_type = 'product' AND
                       t2.brochure = t.brochure
                );
</code>```

This is at least a correctly constructed query that gets the minimum price for each brochure.

Body:
I am using the query below to get all results and then then group them. It all works well. I now have multiple rows of identical data but with a different price.

How can I do the same query but get just the row with the cheapest price when all other data is identical. I have spent ages but no joy at all. Please help.

$results = $wpdb->get_results($wpdb->prepare("

SELECT *,
group_concat(date,':',SUBSTRING_INDEX(flights,'|',2),':',price,':',board,':',$tablename.id separator ',') as itemx

FROM $tablename
WHERE post_type = 'product'
GROUP BY brochure
LIMIT 20
"));

Body:
Presumably, you want something like this:

SELECT t.*,
FROM $tablename t
WHERE t.post_type = 'product' AND
      t.price = (SELECT MIN(t2.price)
                 FROM $tablename t2
                 WHERE t2.post_type = 'product' AND
                       t2.brochure = t.brochure
                );

This is at least a correctly constructed query that gets the minimum price for each brochure.


问:
Calling viewDidLoad in UITextField
What's the code for calling viewDidLoad in UITextField, I only seem to find mixed answers:

```<code>    @IBOutlet weak var providerForm: UITextField!
</code>```

// What to insert here to call the viewDidLoad function?

```<code>    override func viewDidLoad() {
    super.viewDidLoad()

    self.viewDidLoad()
    self.blockchain = Blockchain(genesisBlock: genesisBlock)
    // Do any additional setup after loading the view.
    self.generateDummyTransactions()
    self.providerForm = providerForm
    self.destinatorForm = destinatorForm
    self.amountSum = amountSum

func generateDummyTransactions() {

    let transaction = Transaction(from: "Mary", to: "Steve", amount: 20.0, transactionType: TransactionType.domestic)
    let block1 = Block()
    block1.addTransaction(transaction: transaction)
}
</code>```

答:
Call generateDummyTransactions() from sendButton's IBAction method and then fetch the textField's text there, i.e.

```<code>class VC: UIViewController {
    @IBOutlet weak var providerForm: UITextField!

    @IBAction func onTapSendButton(_ sender: UIButton) {
        self.generateDummyTransactions()
    }

    func generateDummyTransactions() {
        if let text = self.providerForm.text {
            //use text here...
        }
    }
}
</code>```

Title: Calling viewDidLoad in UITextField

Body:
What's the code for calling viewDidLoad in UITextField, I only seem to find mixed answers:

    @IBOutlet weak var providerForm: UITextField!

// What to insert here to call the viewDidLoad function?

    override func viewDidLoad() {
    super.viewDidLoad()

    self.viewDidLoad()
    self.blockchain = Blockchain(genesisBlock: genesisBlock)
    // Do any additional setup after loading the view.
    self.generateDummyTransactions()
    self.providerForm = providerForm
    self.destinatorForm = destinatorForm
    self.amountSum = amountSum

func generateDummyTransactions() {

    let transaction = Transaction(from: "Mary", to: "Steve", amount: 20.0, transactionType: TransactionType.domestic)
    let block1 = Block()
    block1.addTransaction(transaction: transaction)
}

Body:
Call generateDummyTransactions() from sendButton's IBAction method and then fetch the textField's text there, i.e.

class VC: UIViewController {
    @IBOutlet weak var providerForm: UITextField!

    @IBAction func onTapSendButton(_ sender: UIButton) {
        self.generateDummyTransactions()
    }

    func generateDummyTransactions() {
        if let text = self.providerForm.text {
            //use text here...
        }
    }
}


问:
SSH: Self-signed- The authenticity if host cant be established
I get the next message from SSH client every time I try to connect to my server:

The authenticity of host "XXX" can't be established. ECDSA key fingerprint is SHA256:...
  Are you sure you want to continue connecting(yes/no/[fingerprint])?

I Understand that this message should only apear my first time connecting, not each and every time.
Why does it happen?

Does it mean that it is a self signed ceetificate?

Have a good day!

答:
There are few things you can try:

Make sure ~/.ssh/known_hosts is writable. Because system will try and add the host key into this file.

Depending on your ssh client, you can set the StrictHostKeyChecking option to no on the command line, and/or send the key to a null known_hosts file. You can also set these options in your config file, either for all hosts or for a given set of IP addresses or host names.

ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no

This option is not very secure as it may open up Man in the middle attacks. Please carefully consider before doing this.

https://linuxcommando.blogspot.com/2008/10/how-to-disable-ssh-host-key-checking.html

[NOT SECURE] Another way is to use 'BatchMode' in addition to 'StrictHostKeyChecking'. This way, your script will accept a new hostname and write it to the known_hosts file, but won't require yes/no intervention.

ssh -o BatchMode=yes -o StrictHostKeyChecking=no user@server.example.com "uptime"


问:
Show dfsdatabase in DolphinDB
```<code>db=database("dfs://valueDATABASE", VALUE, 2006.01.01..2006.01.31)
getDFSDatabases()
</code>```

It didn't show database "dfs://valueDATABASE".

答: getDFSDatabases only shows distributed databases that contains concrete data.

Title: Show dfsdatabase in DolphinDB

Body:
db=database("dfs://valueDATABASE", VALUE, 2006.01.01..2006.01.31)
getDFSDatabases()

It didn't show database "dfs://valueDATABASE".


问:
regex : match dot with no space after
I would like to search for all punctuations in a string except /, #, $ and dot with no space after (.net for example)

I have done this so far.

```<code>?!['\/#$])\p{P}
</code>```

Now I need to handle the dot with no space after.

If anyone has an idea...

I am using Java.

For example I need to replace all punctuations by "" (empty character)  except for dot with no space after:

.net, asp.net hello. world, c#

becomes

.net asp.net hello world c#

答:
This regex appears to satisfy your use case:

```<code>(?!\.\w)(?!['\/#$])\p{P}
</code>```

You may need to make changes (such as to the \p{P}) for use in Java, see Regular Expressions on Punctuation

https://regex101.com/r/xtBfYt/1

Title: regex : match dot with no space after

Body:
I would like to search for all punctuations in a string except /, #, $ and dot with no space after (.net for example)

I have done this so far.

?!['\/#$])\p{P}

Now I need to handle the dot with no space after.

If anyone has an idea...

I am using Java.

For example I need to replace all punctuations by "" (empty character)  except for dot with no space after:

.net, asp.net hello. world, c#

becomes

.net asp.net hello world c#

Body:
This regex appears to satisfy your use case:

(?!\.\w)(?!['\/#$])\p{P}

You may need to make changes (such as to the \p{P}) for use in Java, see Regular Expressions on Punctuation

https://regex101.com/r/xtBfYt/1


问:
Exclude category from list
i need to exclude a category from category list in wordpress. i have used below code.
wants to exclude category = "featured_home"

```<code>   $categories = get_categories();
   foreach($categories as $category) {
   echo '<button class="button" data-filter=".' .$category->name. '">'.$category->name.'</button>';
                    }
</code>```

Please help me as soon as possible.

Thanks in advance.

答:
If you know the key of the category you want to exclude you can do this:

```<code>global $test;
$categories = get_the_category($test->ID);
foreach( $categories as $key => $category ):  // add $key to foreach
    if ($key != 5): // check if key is not the one you want to exlude
?>
<div class="blog-img <?php echo $category->cat_name; ?>">
<?php
    endif;
endforeach; ?>
</code>```

If you want to exlude category by name, just change if statement to this:

```<code> if($category->cat_name != 'Category1'): ...
</code>```

Title: Exclude category from list

Body:
i need to exclude a category from category list in wordpress. i have used below code.
wants to exclude category = "featured_home"

   $categories = get_categories();
   foreach($categories as $category) {
   echo '<button class="button" data-filter=".' .$category->name. '">'.$category->name.'</button>';
                    }

Please help me as soon as possible.

Thanks in advance.

Body:
If you know the key of the category you want to exclude you can do this:

global $test;
$categories = get_the_category($test->ID);
foreach( $categories as $key => $category ):  // add $key to foreach
    if ($key != 5): // check if key is not the one you want to exlude
?>
<div class="blog-img <?php echo $category->cat_name; ?>">
<?php
    endif;
endforeach; ?>

If you want to exlude category by name, just change if statement to this:

 if($category->cat_name != 'Category1'): ...


问:
Regex solution for Objective-C
What is the best method for using Regular Expressions within Objective-C?

There seems to be some open source project that provide regex support, can any one recommend one?

Also I looked at NSPredicate, can anyone suggest any regex examples?

Background: I want use regex mainly for validation, IP's, email addresses, internal ID's etc

答:
Try the official NSRegualExpression that's available since iOS 4.0:

http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

ContentLicense: CC BY-SA 2.5

Title: Regex solution for Objective-C


问:
Fill complex object property List<T> based on string.split condition
I have a complex object and need to fill the data based on split condition that I get from reader.
Below object need to filter data based on "--" ( Example given below).

```<code>Class Employee {
    public string fName {get;} {set;}
    public List<string> Departments {get;} {set;}
}
</code>```

once I get the data from reader, I am looping and one of the column Department has value like {"Sales -- Payroll -- HR"}

```<code>while (dr.read())
{
    new Employee() {
        fname = dr["name],
            Departments = new List<string>
            {
                dr["Department"].ToString().Split(
                    new string[] {" -- "},
                    StringSplitOptions.None).ToString()
            }
    }
}
</code>```

I tried above option but still not getting desired results.. I need 3 string array based on above example part of Departments property.

Any idea what I am missing?

答:
Please try this:

```<code>var departments = dr["Department"]; //"A--B--C";
// Split returns string collection of type string[].
string[] deptArray = departments.Split(separator: new[] { "--" }, options: StringSplitOptions.RemoveEmptyEntries);
// Use ToList on deptArray to get final list.
List<string> depts = deptArray.ToList();
</code>```

instead of using deptArray, you can combine those two statements into one:

```<code>var depts = departments.Split(separator: new[] { "--" }, options: StringSplitOptions.RemoveEmptyEntries).ToList();
</code>```

So, your final while loop will be:

```<code>var employees = new List<Employee>();
while (dr.read())
{
    employees.Add(new Employee
        {
            fname = dr["name],
            Departments = dr["Department"].ToString() // I don't think you need ToString here.
                           .Split(new[] {"--"}, StringSplitOptions.RemoveEmptyEntries).ToList()

    });
}
</code>```

Body:
I have a complex object and need to fill the data based on split condition that I get from reader.
Below object need to filter data based on "--" ( Example given below).

Class Employee {
    public string fName {get;} {set;}
    public List<string> Departments {get;} {set;}
}

once I get the data from reader, I am looping and one of the column Department has value like {"Sales -- Payroll -- HR"}

while (dr.read())
{
    new Employee() {
        fname = dr["name],
            Departments = new List<string>
            {
                dr["Department"].ToString().Split(
                    new string[] {" -- "},
                    StringSplitOptions.None).ToString()
            }
    }
}

I tried above option but still not getting desired results.. I need 3 string array based on above example part of Departments property.

Any idea what I am missing?

Body:
Please try this:

var departments = dr["Department"]; //"A--B--C";
// Split returns string collection of type string[].
string[] deptArray = departments.Split(separator: new[] { "--" }, options: StringSplitOptions.RemoveEmptyEntries);
// Use ToList on deptArray to get final list.
List<string> depts = deptArray.ToList();

instead of using deptArray, you can combine those two statements into one:

var depts = departments.Split(separator: new[] { "--" }, options: StringSplitOptions.RemoveEmptyEntries).ToList();

So, your final while loop will be:

var employees = new List<Employee>();
while (dr.read())
{
    employees.Add(new Employee
        {
            fname = dr["name],
            Departments = dr["Department"].ToString() // I don't think you need ToString here.
                           .Split(new[] {"--"}, StringSplitOptions.RemoveEmptyEntries).ToList()

    });
}


问:
System out print incorrect. Possible Accessor or Mutator mistake
Having an issue with this section of code first stated below

```<code>  customer.setcustomerDiscount(customerPurchase);
  System.out.println("Percent off: "+ customer.getcustomerDiscount());
</code>```

It is printing "5%Percent off: 5%"

But when I remove the front 5% the code will print Percent off: null

I am looking to find a way for it to instead print "Percent off: 5%"

Possible problem area is in the setter, and wondering if i should move the if else statement to have the getter grab it instead.

Working with the code and moving pieces around trying to solve the puzzle
code in its current state works perfectly other then that

Full Code

```<code>package driver2;
import java.util.Scanner;
import java.text.DecimalFormat;

class Person{
private String name;
private String address;
private String number;
private double customerPurchase = 0;

//////// Constructors /////////
public Person(String name, String address, String number, int customerPurchase){
  this.name = name;
  this.address = address;
  this.number = number;
  this.customerPurchase = customerPurchase;
}

public Person(){}

//////// Accessors /////////
public String getName(){
  return this.name;
}
public String getAddress(){
  return this.address;
}
public String getNumber(){
  return this.number;
}
public double getcustomerPurchase(){
  return this.customerPurchase;
}

//////// Mutators /////////
public void setName(String n){
  this.name = n;
}
public void setAddress(String a){
  this.address = a;
}
public void setNumber(String n){
  this.number = n;
}
public void setcustomerPurchase(int a){
  this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private String customerDiscount;

//////// Constructors /////////
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
  super(name, address, number, customerPurchase);
  this.customerNumber = customerN;
  this.recieveMail = rm;
}
public Customer(){}

//////// Accessors /////////
public String getCustomerNumber(){
  return this.customerNumber;
}
public boolean getRecieveMail(){
  return this.recieveMail;
}
public String getcustomerDiscount(){
  return customerDiscount;
}

//////// Mutators /////////
public void setCustomerNumber(String c){
  this.customerNumber = c;
}
public void setRecieveMail(boolean r){
  this.recieveMail = r;
}
@Override
public void setcustomerDiscount(int r){
  String customerDiscount = "";
  if (r >= 2000){
    customerDiscount="10%";
      System.out.print("10%");
  }else if (r >= 1500){
    customerDiscount="7%";
      System.out.print("7%");
  }else if (r >= 1000){
    customerDiscount="6%";
      System.out.print("6%");
  }else if (r > 500){
    customerDiscount="5%";
      System.out.print("5%");
  }else{
      System.out.print("");
  }
  this.customerDiscount = customerDiscount;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
public class Driver2{
public static void main(String args[]){
  Scanner scanner = new Scanner(System.in);

  System.out.print("Enter name of customer:");
  String name1 = scanner.nextLine();
  System.out.print("Enter address of customer:");
  String address1 = scanner.nextLine();
  System.out.print("Enter phone number of customer:");
  String number1 = scanner.nextLine();
  System.out.print("Enter customer number:");
  String customerNumber = scanner.nextLine();
  System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
  String answer = scanner.nextLine();
  boolean recieveMail = (answer.equals("yes"));
  System.out.print("Enter amount customer has spent:");
  int customerPurchase = scanner.nextInt();
  scanner.close();

  Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);

  System.out.println("\nCustomer: ");
  System.out.println("Name: "+customer.getName());
  System.out.println("Address: "+customer.getAddress());
  System.out.println("Phone Number: "+customer.getNumber());
  System.out.println("Customer Number: "+customer.getCustomerNumber());
  System.out.println("Recieve Mail?: "+customer.getRecieveMail());
  DecimalFormat ft = new DecimalFormat("####");
  ft = new DecimalFormat("$0.00");
  System.out.println("Amount Purchased: "+ft.format(customer.getcustomerPurchase()));
  customer.setcustomerDiscount(customerPurchase);
  System.out.println("Percent off: "+ customer.getcustomerDiscount());

}
}
</code>```

答:
The problem is this:

```<code>customerDiscount="5%";
  System.out.print("5%"); // remove this
</code>```

That prints the "5%" before you print the rest:

```<code>System.out.println("Percent off: "+ customer.getcustomerDiscount());
</code>```

If you remove the first print (with "remove this" comment above), you'll print what you intended.

Body:
Having an issue with this section of code first stated below

  customer.setcustomerDiscount(customerPurchase);
  System.out.println("Percent off: "+ customer.getcustomerDiscount());

It is printing "5%Percent off: 5%"

But when I remove the front 5% the code will print Percent off: null

I am looking to find a way for it to instead print "Percent off: 5%"

Possible problem area is in the setter, and wondering if i should move the if else statement to have the getter grab it instead.

Working with the code and moving pieces around trying to solve the puzzle
code in its current state works perfectly other then that

Full Code

package driver2;
import java.util.Scanner;
import java.text.DecimalFormat;

class Person{
private String name;
private String address;
private String number;
private double customerPurchase = 0;

//////// Constructors /////////
public Person(String name, String address, String number, int customerPurchase){
  this.name = name;
  this.address = address;
  this.number = number;
  this.customerPurchase = customerPurchase;
}

public Person(){}

//////// Accessors /////////
public String getName(){
  return this.name;
}
public String getAddress(){
  return this.address;
}
public String getNumber(){
  return this.number;
}
public double getcustomerPurchase(){
  return this.customerPurchase;
}

//////// Mutators /////////
public void setName(String n){
  this.name = n;
}
public void setAddress(String a){
  this.address = a;
}
public void setNumber(String n){
  this.number = n;
}
public void setcustomerPurchase(int a){
  this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private String customerDiscount;

//////// Constructors /////////
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
  super(name, address, number, customerPurchase);
  this.customerNumber = customerN;
  this.recieveMail = rm;
}
public Customer(){}

//////// Accessors /////////
public String getCustomerNumber(){
  return this.customerNumber;
}
public boolean getRecieveMail(){
  return this.recieveMail;
}
public String getcustomerDiscount(){
  return customerDiscount;
}

//////// Mutators /////////
public void setCustomerNumber(String c){
  this.customerNumber = c;
}
public void setRecieveMail(boolean r){
  this.recieveMail = r;
}
@Override
public void setcustomerDiscount(int r){
  String customerDiscount = "";
  if (r >= 2000){
    customerDiscount="10%";
      System.out.print("10%");
  }else if (r >= 1500){
    customerDiscount="7%";
      System.out.print("7%");
  }else if (r >= 1000){
    customerDiscount="6%";
      System.out.print("6%");
  }else if (r > 500){
    customerDiscount="5%";
      System.out.print("5%");
  }else{
      System.out.print("");
  }
  this.customerDiscount = customerDiscount;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
public class Driver2{
public static void main(String args[]){
  Scanner scanner = new Scanner(System.in);

  System.out.print("Enter name of customer:");
  String name1 = scanner.nextLine();
  System.out.print("Enter address of customer:");
  String address1 = scanner.nextLine();
  System.out.print("Enter phone number of customer:");
  String number1 = scanner.nextLine();
  System.out.print("Enter customer number:");
  String customerNumber = scanner.nextLine();
  System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
  String answer = scanner.nextLine();
  boolean recieveMail = (answer.equals("yes"));
  System.out.print("Enter amount customer has spent:");
  int customerPurchase = scanner.nextInt();
  scanner.close();

  Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);

  System.out.println("\nCustomer: ");
  System.out.println("Name: "+customer.getName());
  System.out.println("Address: "+customer.getAddress());
  System.out.println("Phone Number: "+customer.getNumber());
  System.out.println("Customer Number: "+customer.getCustomerNumber());
  System.out.println("Recieve Mail?: "+customer.getRecieveMail());
  DecimalFormat ft = new DecimalFormat("####");
  ft = new DecimalFormat("$0.00");
  System.out.println("Amount Purchased: "+ft.format(customer.getcustomerPurchase()));
  customer.setcustomerDiscount(customerPurchase);
  System.out.println("Percent off: "+ customer.getcustomerDiscount());

}
}

Body:
The problem is this:

customerDiscount="5%";
  System.out.print("5%"); // remove this

That prints the "5%" before you print the rest:

System.out.println("Percent off: "+ customer.getcustomerDiscount());

If you remove the first print (with "remove this" comment above), you'll print what you intended.


问:
Grabbing one item out of an array in the VUEX store
This is my first time diving into vuex, and so far it is going well! I have been able to store a list of "projects" and display them on my home page.

However, I am a bit stuck as to how to interact with the stored array on another page.

Currently, I have 3 projects "project 1, project 2 and project 3". I display all of them on my home page in a list, and clicking one sends me to "www.mywebsite.com/project-1".

My question is, how do i go into my state and grab just "project 1" from the object? Or, I guess, a better question is how do i reference the stored state to do stuff/use it?

答:
Use a getter

e.g.,

state: {
  projects: [{id: 'project 1', ... }, {id: 'project 2', ...} , {id: 'project 3', ...}],
};
getters: {
  getbyId(state) {
    return (id) => state.projects.find(project => project.id === id);
  },
};
```
<p>Then in your in your implementation</p>
<pre class="lang-js prettyprint-override"><code>const project = this.$store.getters.getById('project 1');
</code>```

Body:
Use a getter

e.g.,

state: {
  projects: [{id: 'project 1', ... }, {id: 'project 2', ...} , {id: 'project 3', ...}],
};
getters: {
  getbyId(state) {
    return (id) => state.projects.find(project => project.id === id);
  },
};

Then in your in your implementation

const project = this.$store.getters.getById('project 1');


问:
Define struct field with circular reference
I have the following code where a struct field depends on a struct field that is not declared yet, because that struct in turn might depend on the struct that I am trying to declare.

How can I design this so that it compiles? Or am I missing an obvious way to get rid of the union struct for keeping several struct definitions together?

```<code>typedef struct expression {
    expression_type type;
    union {
        bool_expression bool;
        identifier_expression ident;
        integer_expression _int;
        prefix_expression prefix;
        infix_expression infix;

        // TODO: Fix this
        if_expression _if;
    };
} expression;

typedef struct statement {
    token token;
    identifier name;
    expression * value;
} statement;

typedef struct block_statement {
    token token;
    statement *statements;
} block_statement;

typedef struct if_expression {
    token token;
    expression condition;
    block_statement *consequence;
    block_statement *alternative;
} if_expression;
</code>```

答:
You better remove the typedefs, at least initially, so you can better understand your types.

You should change your structs to point (rather than include) other structs, for example:

```<code>struct if_expression {
    /* struct? */ token *token;
    struct expression *condition;
    struct block_statement *consequence;
    struct block_statement *alternative;
}
</code>```

Of course that will impose some judiciously use of malloc() and free() calls. In some cases you can later revert to inclusion (like token above, as it isn't expected that it points to your other structs, and copying tokens around is - perhaps - a cheap operation).

For the circularity of references you can forward declarations in C, that is you tell the compiler "hey, there is a struct named expression, whose internal structure you don't know yet, but bear with me, you will soon":

```<code>struct expression;
</code>```

If you later decide to use typedef - so your code gets more streamlined - bear in mind that the structs can have a name, and typedefs define names, and those names don't share the same namespace. In examples:

```<code>typedef struct {
    /* ...internal structure omited... */
} type_a;

typedef struct type_b {
    /* ...internal structure omited... */
} type_b;

typedef struct struct_c {
    /* ...internal structure omited... */
} type_c;

</code>```

Here type_a is a type whose definition is an anonymous struct. And type_b is a type whose definition is struct type_b, that is a named (type_b)  structure. And type_c is a type whose definition is struct struct_c, that is a named (struct_c) structure.

Now put it all together, you can:

```<code>/* forward all your structs */
struct expression;
struct if_expression;
struct block_statement;

/* typedef them all */
typedef struct expression expression;
typedef struct if_expression if_expression;

/* actually define them */
struct expression {
    /* ... */
}
</code>```

As a footnote, you can learn a lot about C language by understanding the difference between declaration and definition.

Body:
I have the following code where a struct field depends on a struct field that is not declared yet, because that struct in turn might depend on the struct that I am trying to declare.

How can I design this so that it compiles? Or am I missing an obvious way to get rid of the union struct for keeping several struct definitions together?

typedef struct expression {
    expression_type type;
    union {
        bool_expression bool;
        identifier_expression ident;
        integer_expression _int;
        prefix_expression prefix;
        infix_expression infix;

        // TODO: Fix this
        if_expression _if;
    };
} expression;

typedef struct statement {
    token token;
    identifier name;
    expression * value;
} statement;

typedef struct block_statement {
    token token;
    statement *statements;
} block_statement;

typedef struct if_expression {
    token token;
    expression condition;
    block_statement *consequence;
    block_statement *alternative;
} if_expression;

Body:
You better remove the typedefs, at least initially, so you can better understand your types.

You should change your structs to point (rather than include) other structs, for example:

struct if_expression {
    /* struct? */ token *token;
    struct expression *condition;
    struct block_statement *consequence;
    struct block_statement *alternative;
}

Of course that will impose some judiciously use of malloc() and free() calls. In some cases you can later revert to inclusion (like token above, as it isn't expected that it points to your other structs, and copying tokens around is - perhaps - a cheap operation).

For the circularity of references you can forward declarations in C, that is you tell the compiler "hey, there is a struct named expression, whose internal structure you don't know yet, but bear with me, you will soon":

struct expression;

If you later decide to use typedef - so your code gets more streamlined - bear in mind that the structs can have a name, and typedefs define names, and those names don't share the same namespace. In examples:

typedef struct {
    /* ...internal structure omited... */
} type_a;

typedef struct type_b {
    /* ...internal structure omited... */
} type_b;

typedef struct struct_c {
    /* ...internal structure omited... */
} type_c;

Here type_a is a type whose definition is an anonymous struct. And type_b is a type whose definition is struct type_b, that is a named (type_b)  structure. And type_c is a type whose definition is struct struct_c, that is a named (struct_c) structure.

Now put it all together, you can:

/* forward all your structs */
struct expression;
struct if_expression;
struct block_statement;

/* typedef them all */
typedef struct expression expression;
typedef struct if_expression if_expression;

/* actually define them */
struct expression {
    /* ... */
}

As a footnote, you can learn a lot about C language by understanding the difference between declaration and definition.


问:
I have two tuple comparison. Almost the same data. Why this error:
```<code>print( ('abc', 1, 2) > ('aaa', 777, 'ssst..') )

print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )
</code>```

Result:

```<code>True

Traceback (most recent call last):
  File "//frserv-bu.playtika.local/users$/constantinio/Documents/Python_course/Sedinta3/ex.py", line 33, in <module>
    print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )
TypeError: '>' not supported between instances of 'int' and 'str'

Process finished with exit code 1
</code>```

答:
In the first case the comparison between 'abc' and 'aaa' already gives a result ('abc' is lexicographically "larger" than 'aaa'), so the remaining comparisons are not performed (the comparison is "short-circuited").

In the second case the comparison is performed up to the last elements, since all previous elements are equal. The comparison between 2 and 'ssst...' fails with an exception, because the former is of type int and the latter of type str.

Body:
print( ('abc', 1, 2) > ('aaa', 777, 'ssst..') )

print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )

Result:

True

Traceback (most recent call last):
  File "//frserv-bu.playtika.local/users$/constantinio/Documents/Python_course/Sedinta3/ex.py", line 33, in <module>
    print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )
TypeError: '>' not supported between instances of 'int' and 'str'

Process finished with exit code 1


问:
Regex pattern not being detected properly in C#
I have a specific pattern I want to follow but the extraction process is not working as expected. I assume the pattern I developed is not correct, but I can't find the issue in it.

I have the string string test1 = "R1 0.1uF" and the pattern

"(?<des>^[a-zA-Z]+)|(?<number>\d+\s+)|(?<val>[0-9]*.?[0-9]+)|(?<units>[^,]*)";

I want it to be extracted as follows:

des: R

number: 1

val: 0.1

units: uF

Currently, des is working properly and it's finding R but the others return an empty string.

Here's my code

const string pattern = @"(?<des>^[a-zA-Z]+)|(?<number>\d+\s+)|(?<val>[0-9]*.?[0-9]+)|(?<units>[^,]*)";

string test1 = "R1 0.1uF";

Regex r = new Regex(pattern, RegexOptions.Compiled);

Match m = r.Match(test1);
string des = m.Groups["des"].Value;
string number = m.Groups["number"].Value;
string val = m.Groups["val"].Value;
string units = m.Groups["units"].Value;

```

答:
Two comments:

Remove all the |s because you don't want to match des OR number OR val OR units but des followed by number followed by val followed by units

Escape the dot: \. because you want to match a dot, not some random character.

So, your regex becomes

```<code>(?<des>^[a-zA-Z]+)(?<number>\d+\s+)(?<val>[0-9]*\.?[0-9]+)(?<units>[^,]*)
</code>```

Look at regex101

Some little improvements, if I may:

Move the caret ^ to the front. It doesn't belong in the first group.

Do not capture the space(s) in the group number.

Like this:

```<code>^(?<des>[a-zA-Z]+)(?:(?<number>\d+)\s+)(?<val>[0-9]*\.?[0-9]+)(?<units>[^,]*)
</code>```

See regex101

Body:
Two comments:

Remove all the |s because you don't want to match des OR number OR val OR units but des followed by number followed by val followed by units

Escape the dot: \. because you want to match a dot, not some random character.

So, your regex becomes

(?<des>^[a-zA-Z]+)(?<number>\d+\s+)(?<val>[0-9]*\.?[0-9]+)(?<units>[^,]*)

Look at regex101

Some little improvements, if I may:

Move the caret ^ to the front. It doesn't belong in the first group.

Do not capture the space(s) in the group number.

Like this:

^(?<des>[a-zA-Z]+)(?:(?<number>\d+)\s+)(?<val>[0-9]*\.?[0-9]+)(?<units>[^,]*)

See regex101


问:
does an MVC Action have to return an actionResult?
Can a so called action in my controller just be a regular function that returns anything I want or does the return of an ActionResult declare whether its an "action" or not?

I was wondering if i could call functions in my ActionLink in the "actionname" that didn't return actionresults.

答:
Yes, all actions should return an ActionResult. The MVC engine only know to handle an ActionResult (or a derivative).

I don't understand what you mean with "call functions in my ActionLink that don't return ActionResults". Even if you don't want to return any meaning, you still have to return an ActionResult.

What is it you want to accomplish?

OwnerDisplayName: Dacrocky

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: Inferis


问:
appengine: ReferencePropertyResolveError: ReferenceProperty failed to be resolved: [u'User', xxxxxxxxxxxxx]
I have code to fetch participants and display them. The logic that controls the view is below:

```<code>    def fetch_participants(self, count=12):
        memcache_key = 'mission_participants:%d:%d' % (self.key().id(), count)
        participants = utils.deserialize_entities(memcache.get(memcache_key))
        if participants is None:
            participants = self.fetch_participants_datastore(count)
            memcache.set(memcache_key, utils.serialize_entities(participants), 3600)
        return participants
</code>```

The problem is that appengine is throwing the following error:

```<code>  File "site/templates/participant_base.html", line 209, in block "content"
    {% set participants = mission.fetch_participants(40) %}
  File "/base/data/home/apps/proj/32.424491487021355902/models/mission.py", line 311, in fetch_participants
    participants = self.fetch_participants_datastore(count)
  File "/base/data/home/apps/proj/32.424491487021355902/models/mission.py", line 301, in fetch_participants_datastore
    users = [join.user for join in joins]
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/9fae800fb98bd45d/python27/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 3734, in __get__
    reference_id.to_path())
ReferencePropertyResolveError: ReferenceProperty failed to be resolved: [u'User', xxxxxxxxxxx]
</code>```

The error appears to be this line:

```<code>participants = self.fetch_participants_datastore(count)
</code>```

A user on stackoverflow has asked a simmilar question:

https://stackoverflow.com/a/9835787/10543735

This happens when you attempt to resolve a reference property (by
  dereferencing it - for instance, (MyModel.MyReferenceProp.foo), and
  the property being referenced no longer exists - because it has been
  deleted.

You need to modify your code to catch this exception when you
  dereference an entity that may have been deleted, and handle it
  appropriately.

I am thinking i have to do something similar, problem is am do not know how to modify the code to catch the exception. Is thee a way to filter the participants to not include the referenced participants? Is there a better alternative?

```<code>def fetch_participants_datastore(self, count=12):
    joins = self.mission_joins.order('-created').fetch(count * 2)
    utils.prefetch_refprops(joins, MissionJoin.user)
    users = [join.user for join in joins]
    with_avatars = [user for user in users if user.has_avatar()]
    without_avatars = [user for user in users if not user.has_avatar()]
    users = with_avatars + without_avatars
    return users[:count]
</code>```

Edit:

```<code>for join in joins:
     try:
          users = join.user
     except:
          pass
</code>```

答: Break line 301 of your code into a for loop and add a try/except block around the line with join.user</p>

Body:
I have code to fetch participants and display them. The logic that controls the view is below:

    def fetch_participants(self, count=12):
        memcache_key = 'mission_participants:%d:%d' % (self.key().id(), count)
        participants = utils.deserialize_entities(memcache.get(memcache_key))
        if participants is None:
            participants = self.fetch_participants_datastore(count)
            memcache.set(memcache_key, utils.serialize_entities(participants), 3600)
        return participants

The problem is that appengine is throwing the following error:

  File "site/templates/participant_base.html", line 209, in block "content"
    {% set participants = mission.fetch_participants(40) %}
  File "/base/data/home/apps/proj/32.424491487021355902/models/mission.py", line 311, in fetch_participants
    participants = self.fetch_participants_datastore(count)
  File "/base/data/home/apps/proj/32.424491487021355902/models/mission.py", line 301, in fetch_participants_datastore
    users = [join.user for join in joins]
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/9fae800fb98bd45d/python27/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 3734, in __get__
    reference_id.to_path())
ReferencePropertyResolveError: ReferenceProperty failed to be resolved: [u'User', xxxxxxxxxxx]

The error appears to be this line:

participants = self.fetch_participants_datastore(count)

A user on stackoverflow has asked a simmilar question:

https://stackoverflow.com/a/9835787/10543735

This happens when you attempt to resolve a reference property (by
  dereferencing it - for instance, (MyModel.MyReferenceProp.foo), and
  the property being referenced no longer exists - because it has been
  deleted.

You need to modify your code to catch this exception when you
  dereference an entity that may have been deleted, and handle it
  appropriately.

I am thinking i have to do something similar, problem is am do not know how to modify the code to catch the exception. Is thee a way to filter the participants to not include the referenced participants? Is there a better alternative?

def fetch_participants_datastore(self, count=12):
    joins = self.mission_joins.order('-created').fetch(count * 2)
    utils.prefetch_refprops(joins, MissionJoin.user)
    users = [join.user for join in joins]
    with_avatars = [user for user in users if user.has_avatar()]
    without_avatars = [user for user in users if not user.has_avatar()]
    users = with_avatars + without_avatars
    return users[:count]

Edit:

for join in joins:
     try:
          users = join.user
     except:
          pass


问:
How to redirect to Index from another controller?
I have been looking through trying to find some way to redirect to an Index view from another controller.

```<code>public ActionResult Index()
{
     ApplicationController viewModel = new ApplicationController();
     return RedirectToAction("Index", viewModel);
}
</code>```

This is what I tried right now. Now the code I was given to has a ActionLink that links to the page I need to Redirect too.

```<code>@Html.ActionLink("Bally Applications","../Application")
</code>```

答:
Complete answer (.Net Core 3.1)

Most answers here are correct but taken a bit out of context, so I will provide a full-fledged answer which works for Asp.Net Core 3.1. For completeness' sake:

[Route("health")]
[ApiController]
public class HealthController : Controller
{
    [HttpGet("some_health_url")]
    public ActionResult SomeHealthMethod() {}
}

[Route("v2")]
[ApiController]
public class V2Controller : Controller
{
    [HttpGet("some_url")]
    public ActionResult SomeV2Method()
    {
        return RedirectToAction("SomeHealthMethod", "Health"); // omit "Controller"
    }
}
```

If you try to use any of the url-specific strings, e.g. "some_health_url", it will not work!

Body:
I have been looking through trying to find some way to redirect to an Index view from another controller.

public ActionResult Index()
{
     ApplicationController viewModel = new ApplicationController();
     return RedirectToAction("Index", viewModel);
}

This is what I tried right now. Now the code I was given to has a ActionLink that links to the page I need to Redirect too.

@Html.ActionLink("Bally Applications","../Application")

Body:
Complete answer (.Net Core 3.1)

Most answers here are correct but taken a bit out of context, so I will provide a full-fledged answer which works for Asp.Net Core 3.1. For completeness' sake:

[Route("health")]
[ApiController]
public class HealthController : Controller
{
    [HttpGet("some_health_url")]
    public ActionResult SomeHealthMethod() {}
}

[Route("v2")]
[ApiController]
public class V2Controller : Controller
{
    [HttpGet("some_url")]
    public ActionResult SomeV2Method()
    {
        return RedirectToAction("SomeHealthMethod", "Health"); // omit "Controller"
    }
}

If you try to use any of the url-specific strings, e.g. "some_health_url", it will not work!