问:
Subprocess not raising CalledProcessError
I have a script that loops through a few file paths in order execute some other python and bash scripts using subprocess.

I know that these scripts will occasionally fail, and I want to catch the exception and stop the loop/exit the calling script.  This seems like it should be very simple – but I'm going nuts getting it to work.

I've tried a number of subprocess methods, and I can't seem to catch a CalledProcessError from any of them (call, check_call, check_output Popen).

```<code># calling.py

for script in ['w', 'x', 'y']:
    try:
        subprocess.check_output('ipython {}.py'.format(script).split())
    except subprocess.CalledProcessError as e:
        print "Caught CalledProcessError"
        raise
    except Exception as e:
        print "Caught some other exception"
        raise
</code>```

Now imagine the first script throws an exception. I want it to cause the calling script to exit.

```<code># w.py

print "w"
a = {}
a[0]  # KeyError
</code>```

Instead none of the exceptions are caught by the calling script and the calling script continues the loop.

```<code>$ ipython calling.py
w
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/Users/h138124/git/exceptional/w.py in <module>()
      1 print "w"
      2 a = {}
----> 3 a[0]

KeyError: 0
x
y
</code>```

答:
Funnily enough I wanted to do exactly what is happening to you, and I could not, because I was not using try except (I am in python 2.7).
What happen if you simply do that?

```<code>for script in ['w', 'x', 'y']:
    out = subprocess.check_output('ipython {}.py'.format(script).split())
    print(out)
</code>```

As far as I can understand of this mysterious subprocess, if you want the program to stop you have to disentangle from the try except structure, as subprocess.check_output will stop by default when the exit status is 1.

Body:
I have a script that loops through a few file paths in order execute some other python and bash scripts using subprocess.

I know that these scripts will occasionally fail, and I want to catch the exception and stop the loop/exit the calling script.  This seems like it should be very simple – but I'm going nuts getting it to work.

I've tried a number of subprocess methods, and I can't seem to catch a CalledProcessError from any of them (call, check_call, check_output Popen).

# calling.py

for script in ['w', 'x', 'y']:
    try:
        subprocess.check_output('ipython {}.py'.format(script).split())
    except subprocess.CalledProcessError as e:
        print "Caught CalledProcessError"
        raise
    except Exception as e:
        print "Caught some other exception"
        raise

Now imagine the first script throws an exception. I want it to cause the calling script to exit.

# w.py

print "w"
a = {}
a[0]  # KeyError

Instead none of the exceptions are caught by the calling script and the calling script continues the loop.

$ ipython calling.py
w
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/Users/h138124/git/exceptional/w.py in <module>()
      1 print "w"
      2 a = {}
----> 3 a[0]

KeyError: 0
x
y

Body:
Funnily enough I wanted to do exactly what is happening to you, and I could not, because I was not using try except (I am in python 2.7).
What happen if you simply do that?

for script in ['w', 'x', 'y']:
    out = subprocess.check_output('ipython {}.py'.format(script).split())
    print(out)

As far as I can understand of this mysterious subprocess, if you want the program to stop you have to disentangle from the try except structure, as subprocess.check_output will stop by default when the exit status is 1.


来源: stackexchange

问:
Using ?: shorthand in laravel
I have a login function that i am using to login users using telephone numbers. I am getting the phone numbers from the user and then using the phone number to fetch the matching email address.

For that i have this code

```<code>public function processLogin(Request $request){
    $phone = $request->get('phone');
    $getEmail = User::where('users_telephone_number', '=',$phone )->first()->email;
    $email = $getEmail;
    $password = $request->get('password');
    //echo $email.$password;
    $data = array(
        'email' => $email,
        'password' => $password
        );

    if (Auth::attempt($data,true)) {
</code>```

When the number is wrong, i get this error

Trying to get property of non-object

To solve the problem i want to have the variable $getEmail to be equal to  none@dont.com which will fail well like all other wrong email and password combos.

How can i make sure i catch errors in this one line i am using to fetch the email

User::where('users_telephone_number', '=',$phone )->first()->email;

答:
```<code>$phone = $request->get('phone');
$getEmail = User::where('users_telephone_number', '=',$phone )->first();
$email = $getEmail ? $getEmail->email : null;
if(!$email)
    return abort(400);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Using ?: shorthand in laravel

Body:
I have a login function that i am using to login users using telephone numbers. I am getting the phone numbers from the user and then using the phone number to fetch the matching email address.

For that i have this code

public function processLogin(Request $request){
    $phone = $request->get('phone');
    $getEmail = User::where('users_telephone_number', '=',$phone )->first()->email;
    $email = $getEmail;
    $password = $request->get('password');
    //echo $email.$password;
    $data = array(
        'email' => $email,
        'password' => $password
        );

    if (Auth::attempt($data,true)) {

When the number is wrong, i get this error

Trying to get property of non-object

To solve the problem i want to have the variable $getEmail to be equal to  none@dont.com which will fail well like all other wrong email and password combos.

How can i make sure i catch errors in this one line i am using to fetch the email

User::where('users_telephone_number', '=',$phone )->first()->email;


问:
Find key different from given key when iterating list of dictionaries
I have list of dictionaries and in each one of them the key site exists.
So in other words, this code returns True:

```<code>all('site' in site for site in summary)
</code>```

Question is, what will be the pythonic way to iterate over the list of dictionaries and return True if a key different from site exists in any of the dictionaries?

Example: in the following list I would like to return True because of the existence of cost in the last dictionary BUT, I can't tell what will be the other key, it can be cost as in the example and it can be other strings; random keys for that matter.

```<code>[
    {"site": "site_A"},
    {"site": "site_B"},
    {"site": "site_C", "cost": 1000}
]
</code>```

答:
This is a bit longer version, but it gives you what you need. Just to give more options:</p>

```<code>any({k: v for k, v in site.items() if k != 'site'} for site in summary)
</code>```

Body:
I have list of dictionaries and in each one of them the key site exists.
So in other words, this code returns True:

all('site' in site for site in summary)

Question is, what will be the pythonic way to iterate over the list of dictionaries and return True if a key different from site exists in any of the dictionaries?

Example: in the following list I would like to return True because of the existence of cost in the last dictionary BUT, I can't tell what will be the other key, it can be cost as in the example and it can be other strings; random keys for that matter.

[
    {"site": "site_A"},
    {"site": "site_B"},
    {"site": "site_C", "cost": 1000}
]

Body:
This is a bit longer version, but it gives you what you need. Just to give more options:

any({k: v for k, v in site.items() if k != 'site'} for site in summary)


问:
Dragging a TButton from form to form
I have a Delphi GUI app (with RAD studio 2010) and I want the user to be able to rearrange his workspace. I know how to make TButtons draggable around in the same form, but not how to make the user able to drag a button from one form to another form. When you click and attempt to drag a TButton, I don't think it treats it like a drag-and-drop operation. How do you get a TButton to be drag-and-drop capable across multiple forms?</p>

答: Use the target form's OnDragDrop event to update the button's Parent property.</p>

ContentLicense: CC BY-SA 2.5

Title: Dragging a TButton from form to form


问:
Using Tuple in VS2017, build failed but show no Error
```<code>var range = (first: 1, end: 10);
</code>```

When I build the project, there is no error in Error List window.
but the output window writes:

1>....cs(41,38,41,39): error CS1026: ) expected

1>....cs(41,40,41,41): error CS1001: Identifier expected

1>....cs(41,40,41,41): error CS1002: ; expected

1>....cs(41,41,41,42): error CS1002: ; expected

1>....cs(41,41,41,42): error CS1513: } expected

========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

Only when I remove the code var range = (first: 1, end: 10); can this project build success.

By the way, I'm using .NET Framework 4.6.2 (not .Net Core) and I've installed the package System.ValueTuple

答: I had the same issue, and it got fixed by simply updating all NuGet packages.</p>

Body:
var range = (first: 1, end: 10);

When I build the project, there is no error in Error List window.
but the output window writes:

1>....cs(41,38,41,39): error CS1026: ) expected

1>....cs(41,40,41,41): error CS1001: Identifier expected

1>....cs(41,40,41,41): error CS1002: ; expected

1>....cs(41,41,41,42): error CS1002: ; expected

1>....cs(41,41,41,42): error CS1513: } expected

========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

Only when I remove the code var range = (first: 1, end: 10); can this project build success.

By the way, I'm using .NET Framework 4.6.2 (not .Net Core) and I've installed the package System.ValueTuple


问:
Circular dependency error while trying to add reference
In my solution, there are 2 projects: Helper and Service.Helper project has a reference to the service

In the helper project I have

Culture Helper

```<code> public static class CultureHelper
    {
    public static Location GetLocationBasedOnCulture(string cultureName)
            {
                Location location = Location.UK;
                if (cultureName == Constants.CultureConstants.Italy)
                {
                    location = Location.Italy;
                }
                return location;
            }
    }
</code>```

Culture Constants:

```<code>public static class CultureConstants
    {
        public static readonly string UK = "en-GB";
        public static readonly string Italy = "it-IT";

    }
</code>```

In the Service I am trying to add this method:

```<code>public Enum DetermineLocation()
        {
            var culture = CultureHelper.GetCurrentCulture();
            Location location = CultureHelper.GetLocationBasedOnCulture(culture);
            return location;
        }
</code>```

I am trying to add a method to the service that uses the static CultureHelper class but I am unable to add a reference to helper in service as it will lead to circular dependency. How do I go ahead with this. Is creating an interface going to solve this problem and how.

答:
You can not add reference of a project in that project which has already refereed your first project. Say

you have two project ProjectA and ProjectB
now you add reference of ProjectB in ProjectA
when you try to add reference of ProjectA in ProjectB you will get circular dependency as you are point one project to one another.

So to solve this problem you should create ProjectC that add reference to ProjectB and finally you can add reference of ProjectC in ProjectA

Body:
In my solution, there are 2 projects: Helper and Service.Helper project has a reference to the service

In the helper project I have

Culture Helper

 public static class CultureHelper
    {
    public static Location GetLocationBasedOnCulture(string cultureName)
            {
                Location location = Location.UK;
                if (cultureName == Constants.CultureConstants.Italy)
                {
                    location = Location.Italy;
                }
                return location;
            }
    }

Culture Constants:

public static class CultureConstants
    {
        public static readonly string UK = "en-GB";
        public static readonly string Italy = "it-IT";

    }

In the Service I am trying to add this method:

public Enum DetermineLocation()
        {
            var culture = CultureHelper.GetCurrentCulture();
            Location location = CultureHelper.GetLocationBasedOnCulture(culture);
            return location;
        }

I am trying to add a method to the service that uses the static CultureHelper class but I am unable to add a reference to helper in service as it will lead to circular dependency. How do I go ahead with this. Is creating an interface going to solve this problem and how.


问:
AWS Elastic Beanstalk: Add custom logs to CloudWatch?
How to add custom logs to CloudWatch? Defaults logs are sent but how to add a custom one?

I already added a file like this: (in .ebextensions)

```<code>files:
  "/opt/elasticbeanstalk/tasks/bundlelogs.d/applogs.conf" :
    mode: "000755"
    owner: root
    group: root
    content: |
      /var/app/current/logs/*

  "/opt/elasticbeanstalk/tasks/taillogs.d/cloud-init.conf" :
    mode: "000755"
    owner: root
    group: root
    content: |
      /var/app/current/logs/*
</code>```

As I did bundlelogs.d and taillogs.d these custom logs are now tailed or retrieved from the console or web, that's nice but they don't persist and are not sent on CloudWatch.

In CloudWatch I have the defaults logs like

 /aws/elasticbeanstalk/InstanceName/var/log/eb-activity.log

And I want to have another one like this

/aws/elasticbeanstalk/InstanceName/var/app/current/logs/mycustomlog.log

答:
Both bundlelogs.d and taillogs.d are logs retrieved from management console. What you want to do is extend default logs (e.g. eb-activity.log) to CloudWatch Logs. In order to extend the log stream, you need to add another configuration under /etc/awslogs/config/. The configuration should follow the Agent Configuration file Format.

I've successfully extended my logs for my custom ubuntu/nginx/php platform. Here is my extension file FYI. Here is an official sample FYI.

In your case, it could be like

```<code>files:
  "/etc/awslogs/config/my_app_log.conf" :
    mode: "000600"
    owner: root
    group: root
    content: |
      [/var/app/current/logs/xxx.log]
      log_group_name = `{"Fn::Join":["/", ["/aws/elasticbeanstalk", { "Ref":"AWSEBEnvironmentName" }, "var/app/current/logs/xxx.log"]]}`
      log_stream_name = {instance_id}
      file = /var/app/current/logs/xxx.log*
</code>```

Body:
How to add custom logs to CloudWatch? Defaults logs are sent but how to add a custom one?

I already added a file like this: (in .ebextensions)

files:
  "/opt/elasticbeanstalk/tasks/bundlelogs.d/applogs.conf" :
    mode: "000755"
    owner: root
    group: root
    content: |
      /var/app/current/logs/*

  "/opt/elasticbeanstalk/tasks/taillogs.d/cloud-init.conf" :
    mode: "000755"
    owner: root
    group: root
    content: |
      /var/app/current/logs/*

As I did bundlelogs.d and taillogs.d these custom logs are now tailed or retrieved from the console or web, that's nice but they don't persist and are not sent on CloudWatch.

In CloudWatch I have the defaults logs like

 /aws/elasticbeanstalk/InstanceName/var/log/eb-activity.log

And I want to have another one like this

/aws/elasticbeanstalk/InstanceName/var/app/current/logs/mycustomlog.log

Body:
Both bundlelogs.d and taillogs.d are logs retrieved from management console. What you want to do is extend default logs (e.g. eb-activity.log) to CloudWatch Logs. In order to extend the log stream, you need to add another configuration under /etc/awslogs/config/. The configuration should follow the Agent Configuration file Format.

I've successfully extended my logs for my custom ubuntu/nginx/php platform. Here is my extension file FYI. Here is an official sample FYI.

In your case, it could be like

files:
  "/etc/awslogs/config/my_app_log.conf" :
    mode: "000600"
    owner: root
    group: root
    content: |
      [/var/app/current/logs/xxx.log]
      log_group_name = `{"Fn::Join":["/", ["/aws/elasticbeanstalk", { "Ref":"AWSEBEnvironmentName" }, "var/app/current/logs/xxx.log"]]}`
      log_stream_name = {instance_id}
      file = /var/app/current/logs/xxx.log*

ContentLicense: CC BY-SA 4.0


答:
1) Create a third project (C) with types that are common for project A and B, and let A and B reference C.

2) Move types in B that depends on types in A to A (or vice-versa).

Title: Circular dependency error while trying to add reference


问:
Buildroot + QT5 + VC4 opengl - not all examples run ok
While learning buildroot i write this document
https://github.com/EliArad/MyDocuments/blob/master/Linux/Buildroot/Buildroot_image_with_Qt5_OPEGN_GLS_2.0_mesa_VC4_driver_in_32_bit.odt

That list the steps i make to get QT5 run with the VC4 driver.

The status for now is that i managed to get the device loaded.
I built image with buildroot with examples for qt5.

But not all the examples are working fine.
some works and the majority not.
for example, the marron game
and animation are not showing ( just gray screen)

many of the help out there are referring to vc4 + raspbian jessie
but i want to make it work using build root.

Can you please tell me what should be done to make it work perfectly
using buildroot?

答:
EDIT:
You have to select the PNG support on Qt5 package menu

is better to remove the output/built/qt5-(...) folder to recompile the Qt package


问:
How to color specific area on mayavi 2d array plotting
I'm using mayavi python library for plotting my 2d elevation array (Extracted from Raster DEM) and its generating 3d visualization using my elevation data perfectly. but i want to show some specific areas on different color.

I'm calculating risky slope areas and i want to show those areas on map using different color.

```<code>dataset = gdal.Open("elevation.tif", GA_ReadOnly)
band = dataset.GetRasterBand(1)
demArray =  band.ReadAsArray()

mlab.figure(size=(640, 800) , bgcolor=(1, 1, 1))
surf = mlab.surf(demArray, warp_scale=0.1 )
mlab.show()
</code>```

generated dem using mayavi

Could anyone can tell my how to mark specific area using different color in mayavi or any other alternative solution to my problem.

答: Finally i found a solution. Mayavi library support to add textures to its objects. So by creating blank image and mark specific areas on map, I could create perfectly overlapping texture to mark specific areas on my DEM.</p>

Body:
I'm using mayavi python library for plotting my 2d elevation array (Extracted from Raster DEM) and its generating 3d visualization using my elevation data perfectly. but i want to show some specific areas on different color.

I'm calculating risky slope areas and i want to show those areas on map using different color.

dataset = gdal.Open("elevation.tif", GA_ReadOnly)
band = dataset.GetRasterBand(1)
demArray =  band.ReadAsArray()

mlab.figure(size=(640, 800) , bgcolor=(1, 1, 1))
surf = mlab.surf(demArray, warp_scale=0.1 )
mlab.show()

generated dem using mayavi

Could anyone can tell my how to mark specific area using different color in mayavi or any other alternative solution to my problem.


问:
How to change background-color of Bootstrap column on hover?
I have a grid simulating a fake table made from divs using Bootstrap. I know how to change the background color of the row on hover. What I don't know is how to change the background of the div column on hover. I tried something but it's not working. Any ideas appreciated.

I've also made a JSFiddle.

My code so far:

.fake_table{
    background: #fdf6e3;
    overflow: hidden;
}
.istoric_row:hover{
 background: #FEFAEE;
}
.td, .th {
  position: relative;
}
.td:hover::after,
.th:hover::after {
  content: "";
  position: absolute;
  background-color: #ffa;
  left: 0;
  top: -5000px;
  height: 10000px;
  width: 100%;
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="fake_table istoric_calendar">
  <div class="ft_header">
    <div class="clearfix">
      <div class="col-md-4 th">Client</div>
      <div class="col-md-2 th">Added</div>
      <div class="col-md-6 th">
        <div class="clearfix">
          <div class="col-xs-6">
            <div class="clearfix">
              <div class="col-xs-3">
                L
              </div>
              <div class="col-xs-3">
                M
              </div>
              <div class="col-xs-3">
                Mi
              </div>
              <div class="col-xs-3">
                J
              </div>
            </div>
          </div>
          <div class="col-xs-6">
            <div class="clearfix">
              <div class="col-xs-3">
                V
              </div>
              <div class="col-xs-3">
                S
              </div>
              <div class="col-xs-3">
                D
              </div>
              <div class="col-xs-3">
                8
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="ft_content mCustomScrollbar _mCS_1 mCS_no_scrollbar">
    <div id="mCSB_1" class="mCustomScrollBox mCS-dark mCSB_vertical mCSB_inside" style="max-height: none;" tabindex="0">
      <div id="mCSB_1_container" class="mCSB_container mCS_y_hidden mCS_no_scrollbar_y" style="position:relative; top:0; left:0;" dir="ltr">
        <div class="clearfix istoric_row">
          <div class="col-md-4 td">Lorem ipsum dolor / Lorem ipsum dolor / Lorem ipsum dolor</div>
          <div class="col-md-2 td">6 months ago</div>
          <div class="col-md-6 td">
            <div class="clearfix">
              <div class="col-xs-6">
                <div class="clearfix">
                  <div class="col-xs-3">
                    1
                  </div>
                  <div class="col-xs-3">
                    2
                  </div>
                  <div class="col-xs-3">
                    3
                  </div>
                  <div class="col-xs-3">
                    4
                  </div>
                </div>
              </div>
              <div class="col-xs-6">
                <div class="clearfix">
                  <div class="col-xs-3">
                    5
                  </div>
                  <div class="col-xs-3">
                    6
                  </div>
                  <div class="col-xs-3">
                    7
                  </div>
                  <div class="col-xs-3">
                    8
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="clearfix istoric_row">
          <div class="col-md-4 td">Lorem ipsum dolor / Lorem ipsum dolor / Lorem ipsum dolor</div>
          <div class="col-md-2 td">6 months ago</div>
          <div class="col-md-6 td">
            <div class="clearfix">
              <div class="col-xs-6">
                <div class="clearfix">
                  <div class="col-xs-3">
                    1
                  </div>
                  <div class="col-xs-3">
                    2
                  </div>
                  <div class="col-xs-3">
                    3
                  </div>
                  <div class="col-xs-3">
                    4
                  </div>
                </div>
              </div>
              <div class="col-xs-6">
                <div class="clearfix">
                  <div class="col-xs-3">
                    5
                  </div>
                  <div class="col-xs-3">
                    6
                  </div>
                  <div class="col-xs-3">
                    7
                  </div>
                  <div class="col-xs-3">
                    8
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="clearfix istoric_row">
          <div class="col-md-4 td">Lorem ipsum dolor / Lorem ipsum dolor / Lorem ipsum dolor</div>
          <div class="col-md-2 td">6 months ago</div>
          <div class="col-md-6 td">
            <div class="clearfix">
              <div class="col-xs-6">
                <div class="clearfix">
                  <div class="col-xs-3">
                    1
                  </div>
                  <div class="col-xs-3">
                    2
                  </div>
                  <div class="col-xs-3">
                    3
                  </div>
                  <div class="col-xs-3">
                    4
                  </div>
                </div>
              </div>
              <div class="col-xs-6">
                <div class="clearfix">
                  <div class="col-xs-3">
                    5
                  </div>
                  <div class="col-xs-3">
                    6
                  </div>
                  <div class="col-xs-3">
                    7
                  </div>
                  <div class="col-xs-3">
                    8
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="clearfix istoric_row">
          <div class="col-md-4 td">Lorem ipsum dolor / Lorem ipsum dolor / Lorem ipsum dolor</div>
          <div class="col-md-2 td">6 months ago</div>
          <div class="col-md-6 td">
            <div class="clearfix">
              <div class="col-xs-6">
                <div class="clearfix">
                  <div class="col-xs-3">
                    1
                  </div>
                  <div class="col-xs-3">
                    2
                  </div>
                  <div class="col-xs-3">
                    3
                  </div>
                  <div class="col-xs-3">
                    4
                  </div>
                </div>
              </div>
              <div class="col-xs-6">
                <div class="clearfix">
                  <div class="col-xs-3">
                    5
                  </div>
                  <div class="col-xs-3">
                    6
                  </div>
                  <div class="col-xs-3">
                    7
                  </div>
                  <div class="col-xs-3">
                    8
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="clearfix istoric_row">
          <div class="col-md-4 td">Lorem ipsum dolor / Lorem ipsum dolor / Lorem ipsum dolor</div>
          <div class="col-md-2 td">6 months ago</div>
          <div class="col-md-6 td">
            <div class="clearfix">
              <div class="col-xs-6">
                <div class="clearfix">
                  <div class="col-xs-3">
                    1
                  </div>
                  <div class="col-xs-3">
                    2
                  </div>
                  <div class="col-xs-3">
                    3
                  </div>
                  <div class="col-xs-3">
                    4
                  </div>
                </div>
              </div>
              <div class="col-xs-6">
                <div class="clearfix">
                  <div class="col-xs-3">
                    5
                  </div>
                  <div class="col-xs-3">
                    6
                  </div>
                  <div class="col-xs-3">
                    7
                  </div>
                  <div class="col-xs-3">
                    8
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div id="mCSB_1_scrollbar_vertical" class="mCSB_scrollTools mCSB_1_scrollbar mCS-dark mCSB_scrollTools_vertical" style="display: none;">
        <div class="mCSB_draggerContainer">
          <div id="mCSB_1_dragger_vertical" class="mCSB_dragger" style="position: absolute; min-height: 30px; height: 0px; top: 0px;">
            <div class="mCSB_dragger_bar" style="line-height: 30px;"></div>
          </div>
          <div class="mCSB_draggerRail"></div>
        </div>
      </div>
    </div>
  </div>
  <div class="clearfix total_saptamanal">
    <div class="col-md-4 th">Total 123</div>
    <div class="col-md-2 th">Total daily 22</div>
    <div class="col-md-6 th">
      <div class="clearfix">
        <div class="col-xs-6">
          <div class="clearfix">
            <div class="col-xs-3">
              23
            </div>
            <div class="col-xs-3">
              44
            </div>
            <div class="col-xs-3">
              52
            </div>
            <div class="col-xs-3">
              21
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="clearfix">
            <div class="col-xs-3">
              55
            </div>
            <div class="col-xs-3">
              33
            </div>
            <div class="col-xs-3">
              11
            </div>
            <div class="col-xs-3">
              8
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div></code>```

答: You can give it an extra class or even an ID, and just apply background-color on .extraClass:hover . You can add that class to multiple columns, too.

Body:
I have a grid simulating a fake table made from divs using Bootstrap. I know how to change the background color of the row on hover. What I don't know is how to change the background of the div column on hover. I tried something but it's not working. Any ideas appreciated.

I've also made a JSFiddle.

My code so far:

.fake_table{
    background: #fdf6e3;
    overflow: hidden;
}
.istoric_row:hover{
 background: #FEFAEE;
}
.td, .th {
  position: relative;
}
.td:hover::after,
.th:hover::after {
  content: "";
  position: absolute;
  background-color: #ffa;
  left: 0;
  top: -5000px;
  height: 10000px;
  width: 100%;
  z-index: -1;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Client

Added

                L

                M

                Mi

                J

                V

                S

                D

                8

Lorem ipsum dolor / Lorem ipsum dolor / Lorem ipsum dolor

6 months ago

                    1

                    2

                    3

                    4

                    5

                    6

                    7

                    8

Lorem ipsum dolor / Lorem ipsum dolor / Lorem ipsum dolor

6 months ago

                    1

                    2

                    3

                    4

                    5

                    6

                    7

                    8

Lorem ipsum dolor / Lorem ipsum dolor / Lorem ipsum dolor

6 months ago

                    1

                    2

                    3

                    4

                    5

                    6

                    7

                    8

Lorem ipsum dolor / Lorem ipsum dolor / Lorem ipsum dolor

6 months ago

                    1

                    2

                    3

                    4

                    5

                    6

                    7

                    8

Lorem ipsum dolor / Lorem ipsum dolor / Lorem ipsum dolor

6 months ago

                    1

                    2

                    3

                    4

                    5

                    6

                    7

                    8

Total 123

Total daily 22

              23

              44

              52

              21

              55

              33

              11

              8


问:
I keep Getting Undefined
I'm Using ionic with parse and I'm trying to access the children from the res.results

I still get the undefined error

```<code> unfollow(){
      this.url ='https://meet-up-zionnite.c9users.io/app1/classes/friendslist';
     this.http.get(this.url, {headers : this.headers}).map(res => res.json()).subscribe(res =>{
     this.localstorage.set('friendslist_db_detail',res);
     console.log(res.results.my_id);
     if(res.results == this.my_id){
     console.log('hey over here');
     }else{
     console.log("Not Match");
     }
     });
    }
</code>```

This is what I need to access:

1) ObjectId

2) my_id

3) f_id

答:
wow, i receive a help from one of my online tutor and it solved it
  here is what have been missing

```<code>console.log(res.results[0]['my_id']);
</code>```

Title: I keep Getting Undefined

Body:
I'm Using ionic with parse and I'm trying to access the children from the res.results

I still get the undefined error

 unfollow(){
      this.url ='https://meet-up-zionnite.c9users.io/app1/classes/friendslist';
     this.http.get(this.url, {headers : this.headers}).map(res => res.json()).subscribe(res =>{
     this.localstorage.set('friendslist_db_detail',res);
     console.log(res.results.my_id);
     if(res.results == this.my_id){
     console.log('hey over here');
     }else{
     console.log("Not Match");
     }
     });
    }

This is what I need to access:

1) ObjectId

2) my_id

3) f_id

Body:
wow, i receive a help from one of my online tutor and it solved it
  here is what have been missing

console.log(res.results[0]['my_id']);


问:
Unity - Button Event to switch a value
I have followed this tutorial to create a simple clock: http://catlikecoding.com/unity/tutorials/clock/

Everything works perfectly fine but the tutorial has an internal switch for digital and analog display. Now I would like to add a simple button "ingame" to switch that bool to true/false.

How can I achieve that ?
thanks!

答:
Add a Button in your scene (under a canvas), and add the following code in your ClockAnimator script. Then, drag & drop the button gameobject inside the inspector of the script.

```<code>public UnityEngine.UI.Button button;

private void Start()
{
    // See https://docs.unity3d.com/ScriptReference/UI.Button-onClick.html
    if( button != null )
        button.onClick.AddListener( () => analog = !analog ) ;
}
</code>```

You could achieve the same using a Toggle instead of a button :

```<code>public UnityEngine.UI.Toggle toggle;

private void Start()
{
    // See https://docs.unity3d.com/ScriptReference/UI.Toggle-onValueChanged.html
    if( toggle != null )
        toggle.onValueChanged.AddListener( ( isOn ) => analog = isOn ) ;
}
</code>```

Title: Unity - Button Event to switch a value

Body:
Add a Button in your scene (under a canvas), and add the following code in your ClockAnimator script. Then, drag & drop the button gameobject inside the inspector of the script.

public UnityEngine.UI.Button button;

private void Start()
{
    // See https://docs.unity3d.com/ScriptReference/UI.Button-onClick.html
    if( button != null )
        button.onClick.AddListener( () => analog = !analog ) ;
}

You could achieve the same using a Toggle instead of a button :

public UnityEngine.UI.Toggle toggle;

private void Start()
{
    // See https://docs.unity3d.com/ScriptReference/UI.Toggle-onValueChanged.html
    if( toggle != null )
        toggle.onValueChanged.AddListener( ( isOn ) => analog = isOn ) ;
}


问:
MySql SELECT index benefits
Are there significant benefits between the two SQL select ?

```<code>SELECT * FROM table USE INDEX (cod_clie) WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;

SELECT * FROM table WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;
</code>```

cod_clie is an INDEX field, of course!

答:
Usually not, since mysql should use the index. To be 100% sure just append explain to your queries and compare the output.</p>

```<code>EXPLAIN SELECT * FROM table USE INDEX (cod_clie) WHERE cod_clie = 'example' AND pwd_clie = 'example' LIMIT 1;
EXPLAIN SELECT * FROM table WHERE cod_clie = 'example' AND pwd_clie = 'example' LIMIT 1;
</code>```

Title: MySql SELECT index benefits

Body:
Are there significant benefits between the two SQL select ?

SELECT * FROM table USE INDEX (cod_clie) WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;

SELECT * FROM table WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;

cod_clie is an INDEX field, of course!

Body:
Usually not, since mysql should use the index. To be 100% sure just append explain to your queries and compare the output.

EXPLAIN SELECT * FROM table USE INDEX (cod_clie) WHERE cod_clie = 'example' AND pwd_clie = 'example' LIMIT 1;
EXPLAIN SELECT * FROM table WHERE cod_clie = 'example' AND pwd_clie = 'example' LIMIT 1;


问:
MAC OpenGL shader error: "version '150' is not supported "
I follow the book "OpenGL SuperBible 5th Edition" to study openGL, the capture 6th demo to create shader by hand all not work. Like the demo of "ShadedTriangle",  to  create a triangle but only create a black ground window.

The error is:

```<code>The shader at ShadedIdentity.vp failed to compile with the following error:
ERROR: 0:5: '' :  version '150' is not supported"
</code>```

and I change the GLSL version to 330,440, 150 etc, but all not work.

and now my mac version is 10.12.5 (16F73) , and the version of code glGetString(GL_VERSION) is 2.1 INTEL-10.25.13

the follow is the full code:

```<code>#include <GLTools.h>            // OpenGL toolkit
#include <GLShaderManager.h>    // Shader Manager Class

#ifdef __APPLE__
#include <glut/glut.h>          // OS X version of GLUT
#else
#define FREEGLUT_STATIC
#include <GL/glut.h>            // Windows FreeGlut equivalent
#endif

GLBatch triangleBatch;
GLShaderManager shaderManager;

GLint   myIdentityShader;

///////////////////////////////////////////////////////////////////////////////
// Window has changed size, or has just been created. In either case, we need
// to use the window dimensions to set the viewport and the projection matrix.
void ChangeSize(int w, int h)
    {
    glViewport(0, 0, w, h);
    }

///////////////////////////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering context.
// This is the first opportunity to do any OpenGL related tasks.
void SetupRC()
    {
    // Blue background
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

    shaderManager.InitializeStockShaders();

    // Load up a triangle
    GLfloat vVerts[] = { -0.5f, 0.0f, 0.0f,
                          0.5f, 0.0f, 0.0f,
                          0.0f, 0.5f, 0.0f };

    GLfloat vColors [] = { 1.0f, 0.0f, 0.0f, 1.0f,
                           0.0f, 1.0f, 0.0f, 1.0f,
                           0.0f, 0.0f, 1.0f, 1.0f };

    triangleBatch.Begin(GL_TRIANGLES, 3);
    triangleBatch.CopyVertexData3f(vVerts);
    triangleBatch.CopyColorData4f(vColors);
    triangleBatch.End();

    myIdentityShader = gltLoadShaderPairWithAttributes("ShadedIdentity.vp", "ShadedIdentity.fp", 2,
                                    GLT_ATTRIBUTE_VERTEX, "vVertex", GLT_ATTRIBUTE_COLOR, "vColor");
    }

///////////////////////////////////////////////////////////////////////////////
// Cleanup
void ShutdownRC()
   {
   glDeleteProgram(myIdentityShader);

   }

///////////////////////////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
    {
    // Clear the window with current clearing color
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    glUseProgram(myIdentityShader);
    triangleBatch.Draw();

    // Perform the buffer swap to display back buffer
    glutSwapBuffers();
    }

///////////////////////////////////////////////////////////////////////////////
// Main entry point for GLUT based programs
int main(int argc, char* argv[])
    {
    gltSetWorkingDirectory(argv[0]);

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
    glutInitWindowSize(800, 600);
    glutCreateWindow("Shaded Triangle");
    glutReshapeFunc(ChangeSize);
    glutDisplayFunc(RenderScene);

    GLenum err = glewInit();
    if (GLEW_OK != err) {
        fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
        return 1;
        }

    SetupRC();

    const char* version = (const char*)glGetString(GL_VERSION);
    fprintf(stderr, "OpenGLVersion: %s\n", version);

    glutMainLoop();

    ShutdownRC();

    return 0;
    }
</code>```

and the ShadedIdentity.vp is :

```<code>// The ShadedIdentity Shader
// Vertex Shader
// Richard S. Wright Jr.
// OpenGL SuperBible
#version 150

in vec4 vColor;
in vec4 vVertex;

out vec4 vVaryingColor;

void main(void)
    {
    vVaryingColor = vColor;
    gl_Position = vVertex;
    }
</code>```

so ,how to solve this problem

答: 1.50 requires OpenGL 3.2 support. Unless you can get a newer driver (or a GPU), I think you're out of luck on this one.</p>

Body:
I follow the book "OpenGL SuperBible 5th Edition" to study openGL, the capture 6th demo to create shader by hand all not work. Like the demo of "ShadedTriangle",  to  create a triangle but only create a black ground window.

The error is:

The shader at ShadedIdentity.vp failed to compile with the following error:
ERROR: 0:5: '' :  version '150' is not supported"

and I change the GLSL version to 330,440, 150 etc, but all not work.

and now my mac version is 10.12.5 (16F73) , and the version of code glGetString(GL_VERSION) is 2.1 INTEL-10.25.13

the follow is the full code:

#include <GLTools.h>            // OpenGL toolkit
#include <GLShaderManager.h>    // Shader Manager Class

#ifdef __APPLE__
#include <glut/glut.h>          // OS X version of GLUT
#else
#define FREEGLUT_STATIC
#include <GL/glut.h>            // Windows FreeGlut equivalent
#endif

GLBatch triangleBatch;
GLShaderManager shaderManager;

GLint   myIdentityShader;

///////////////////////////////////////////////////////////////////////////////
// Window has changed size, or has just been created. In either case, we need
// to use the window dimensions to set the viewport and the projection matrix.
void ChangeSize(int w, int h)
    {
    glViewport(0, 0, w, h);
    }

///////////////////////////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering context.
// This is the first opportunity to do any OpenGL related tasks.
void SetupRC()
    {
    // Blue background
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

    shaderManager.InitializeStockShaders();

    // Load up a triangle
    GLfloat vVerts[] = { -0.5f, 0.0f, 0.0f,
                          0.5f, 0.0f, 0.0f,
                          0.0f, 0.5f, 0.0f };

    GLfloat vColors [] = { 1.0f, 0.0f, 0.0f, 1.0f,
                           0.0f, 1.0f, 0.0f, 1.0f,
                           0.0f, 0.0f, 1.0f, 1.0f };

    triangleBatch.Begin(GL_TRIANGLES, 3);
    triangleBatch.CopyVertexData3f(vVerts);
    triangleBatch.CopyColorData4f(vColors);
    triangleBatch.End();

    myIdentityShader = gltLoadShaderPairWithAttributes("ShadedIdentity.vp", "ShadedIdentity.fp", 2,
                                    GLT_ATTRIBUTE_VERTEX, "vVertex", GLT_ATTRIBUTE_COLOR, "vColor");
    }

///////////////////////////////////////////////////////////////////////////////
// Cleanup
void ShutdownRC()
   {
   glDeleteProgram(myIdentityShader);

   }

///////////////////////////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
    {
    // Clear the window with current clearing color
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    glUseProgram(myIdentityShader);
    triangleBatch.Draw();

    // Perform the buffer swap to display back buffer
    glutSwapBuffers();
    }

///////////////////////////////////////////////////////////////////////////////
// Main entry point for GLUT based programs
int main(int argc, char* argv[])
    {
    gltSetWorkingDirectory(argv[0]);

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
    glutInitWindowSize(800, 600);
    glutCreateWindow("Shaded Triangle");
    glutReshapeFunc(ChangeSize);
    glutDisplayFunc(RenderScene);

    GLenum err = glewInit();
    if (GLEW_OK != err) {
        fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
        return 1;
        }

    SetupRC();

    const char* version = (const char*)glGetString(GL_VERSION);
    fprintf(stderr, "OpenGLVersion: %s\n", version);

    glutMainLoop();

    ShutdownRC();

    return 0;
    }

and the ShadedIdentity.vp is :

// The ShadedIdentity Shader
// Vertex Shader
// Richard S. Wright Jr.
// OpenGL SuperBible
#version 150

in vec4 vColor;
in vec4 vVertex;

out vec4 vVaryingColor;

void main(void)
    {
    vVaryingColor = vColor;
    gl_Position = vVertex;
    }

so ,how to solve this problem


问:
scaling a canvas element and keeping the aspect ratio
i have a simple html5 page with a canvas element at a certain size. now i want that the canvas element always scales with the available size from the page but still keeps a certain aspect ratio.

also how can i get the current scale factor of the canvas element in javascript code?

thanks!

答:
If w is your width and h your height.
w/h is your ratio.

Now your page width is bigger or smaller.
Let's say your new width name is newW.
And you are searching newH.

To keep your ratio just do the math :
newH = newW / (w/h);

To get your width and height just use a document.getElementById("canvas").width/height


问:
How to call this Delete web api method in C#?
I have the following Delete WebAPI implemented, which is working fine and tested through swagger:

```<code>//Delete IVR Paycode Profiles
[System.Web.Http.HttpDelete, System.Web.Http.Route("PayCodeProfile")]
public System.Threading.Tasks.Task<ConfirmResponse> DeleteIVRPaycodeProfile(string profileIds)
{
    string orgoid = HttpContext.Current.Request.Headers["ORGOID"];
    SetContext(orgoid);
    return _implementation.DeleteIVRPaycodeProfileAsync(orgoid, profileIds);
}
</code>```

And I am calling from client like below:

```<code>var endpointURL = new Uri("http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile/1,2,3");
var request = WebRequest.Create(endpointURL) as HttpWebRequest;
if (request != null)
{
    request.Headers.Add("ORGOID", "G344G4GEJXDJJ9M5");

    // sending comma separated string of ids like 1,2,
    // not sure if the ContentType is correct
    request.ContentType = "text/html";

    request.Method = "DELETE";

    using (var response = request.GetResponse() as HttpWebResponse)
    {
        if (response != null)
        {
            var reader = new StreamReader(response.GetResponseStream());
            var result = reader.ReadToEnd();
            var resp = JsonConvert.DeserializeObject<ConfirmResponse>(result);
        }
    }
}
</code>```

But I am getting 404:Not Found error, I believe that somewhere I am making a mistake for ContentType.

答:
the problem is your url. at first you need to send the request to this address: "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile". then depend on your content type(by default it is json) create your request. if your content type is json try this:

```<code>private static T Call<T>(string url, string body, int timeOut = 60)
{
    var contentBytes = Encoding.UTF8.GetBytes(body);
    var request = (HttpWebRequest)WebRequest.Create(url);

    request.Timeout = timeOut * 1000;
    request.ContentLength = contentBytes.Length;
    request.Method = "DELETE";
    request.ContentType = @"application/json";

    using (var requestWritter = request.GetRequestStream())
        requestWritter.Write(contentBytes, 0, (int)request.ContentLength);

    var responseString = string.Empty;
    var webResponse = (HttpWebResponse)request.GetResponse();
    var responseStream = webResponse.GetResponseStream();
    using (var reader = new StreamReader(responseStream))
    {
        reader.BaseStream.ReadTimeout = timeOut * 1000;
        responseString = reader.ReadToEnd();
    }

    return JsonConvert.DeserializeObject<T>(responseString);
}
</code>```

then call it like this:

```<code>    var url = "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile";
    var body = JsonConvert.SerializeObject(new { profileIds = "1,2,3" });
    var output = Call<dynamic>(url, body);
</code>```

Body:
I have the following Delete WebAPI implemented, which is working fine and tested through swagger:

//Delete IVR Paycode Profiles
[System.Web.Http.HttpDelete, System.Web.Http.Route("PayCodeProfile")]
public System.Threading.Tasks.Task<ConfirmResponse> DeleteIVRPaycodeProfile(string profileIds)
{
    string orgoid = HttpContext.Current.Request.Headers["ORGOID"];
    SetContext(orgoid);
    return _implementation.DeleteIVRPaycodeProfileAsync(orgoid, profileIds);
}

And I am calling from client like below:

var endpointURL = new Uri("http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile/1,2,3");
var request = WebRequest.Create(endpointURL) as HttpWebRequest;
if (request != null)
{
    request.Headers.Add("ORGOID", "G344G4GEJXDJJ9M5");

    // sending comma separated string of ids like 1,2,
    // not sure if the ContentType is correct
    request.ContentType = "text/html";

    request.Method = "DELETE";

    using (var response = request.GetResponse() as HttpWebResponse)
    {
        if (response != null)
        {
            var reader = new StreamReader(response.GetResponseStream());
            var result = reader.ReadToEnd();
            var resp = JsonConvert.DeserializeObject<ConfirmResponse>(result);
        }
    }
}

But I am getting 404:Not Found error, I believe that somewhere I am making a mistake for ContentType.

Body:
the problem is your url. at first you need to send the request to this address: "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile". then depend on your content type(by default it is json) create your request. if your content type is json try this:

private static T Call<T>(string url, string body, int timeOut = 60)
{
    var contentBytes = Encoding.UTF8.GetBytes(body);
    var request = (HttpWebRequest)WebRequest.Create(url);

    request.Timeout = timeOut * 1000;
    request.ContentLength = contentBytes.Length;
    request.Method = "DELETE";
    request.ContentType = @"application/json";

    using (var requestWritter = request.GetRequestStream())
        requestWritter.Write(contentBytes, 0, (int)request.ContentLength);

    var responseString = string.Empty;
    var webResponse = (HttpWebResponse)request.GetResponse();
    var responseStream = webResponse.GetResponseStream();
    using (var reader = new StreamReader(responseStream))
    {
        reader.BaseStream.ReadTimeout = timeOut * 1000;
        responseString = reader.ReadToEnd();
    }

    return JsonConvert.DeserializeObject<T>(responseString);
}

then call it like this:

    var url = "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile";
    var body = JsonConvert.SerializeObject(new { profileIds = "1,2,3" });
    var output = Call<dynamic>(url, body);


问:
angular2 :host attr selector won't select [routerLink]
I am trying to apply a style to an angular component if it has the [routerLink] attribute.

```<code><component [routerLink]="'...'">
</code>```

But for some reason, the :host(selector) css selector does not seem to be able to attach itself to routerLink.

```<code>:host([routerLink]):hover{
    background-color: rgba(125, 91, 190, 1);
}
</code>```

On inspecting the html element I see that [routerLink] gets transmuted to [router-link] - does this have something to do with it? (note that I tried [router-link] as the selector to no avail).

I know that the selector syntax is correct because if I change the selector to a custom attribute, it works fine...

```<code><component [routerLink]="'...'" this-has-a-route>
// works
:host([this-has-a-route]):hover{
    background-color: rgba(125, 91, 190, 1);
}
</code>```

Why is this the case and is it possible to use routerLink as a selector?

答:
Yes there is work around for this. Where ever you use [routerLink] directive its gets converted to ng-reflect-router-link in browser you can inspect the code and see.

For Ex: demo exits in your temolate it converts like this in browser demo

So You can apply your css on this attribute for work around

```<code>      :host [ng-reflect-router-link]:hover {
        color: red !important;
      }

      :host [ng-reflect-router-link] {
        color: yellow !important;
      }
</code>```

Body:
I am trying to apply a style to an angular component if it has the [routerLink] attribute.

<component [routerLink]="'...'">

But for some reason, the :host(selector) css selector does not seem to be able to attach itself to routerLink.

:host([routerLink]):hover{
    background-color: rgba(125, 91, 190, 1);
}

On inspecting the html element I see that [routerLink] gets transmuted to [router-link] - does this have something to do with it? (note that I tried [router-link] as the selector to no avail).

I know that the selector syntax is correct because if I change the selector to a custom attribute, it works fine...

<component [routerLink]="'...'" this-has-a-route>
// works
:host([this-has-a-route]):hover{
    background-color: rgba(125, 91, 190, 1);
}

Why is this the case and is it possible to use routerLink as a selector?

Body:
Yes there is work around for this. Where ever you use [routerLink] directive its gets converted to ng-reflect-router-link in browser you can inspect the code and see.

For Ex: <a [routerLink]="['/demo']">demo</a> exits in your temolate it converts like this in browser <a ng-reflect-router-link="/demo">demo</a>

So You can apply your css on this attribute for work around

      :host [ng-reflect-router-link]:hover {
        color: red !important;
      }

      :host [ng-reflect-router-link] {
        color: yellow !important;
      }


问:
Cocoa macro-- unique question
I need help with a #define to do the following:

```<code>for (int i = 0; i < 47; ++i)  {     SETLABEL(i)     }
</code>```

the SETLABEL() macro should take the intValue of "i" and paste it into a label name:

when i == 1-->    label1.text = (stuff)

when i == 2-->    label2.text = (stuff)

Is this possible? The following fails miserably, because it pastes "i" in, rather than the value of "i":

```<code>#define SETLABEL(x)    [label##x setText: [foo stringValue]];
</code>```

EDIT:  Thanks for all the help. My code looks like this now:

the declaration for the int is iB[25]

```<code>-(void)stuff {
int x;
int labelGo = 1;

for (int i = 1; i < 25; ++i) {
    NSString * labelName = [NSString stringWithFormat:@"magicItemBoughtTot%d", i];
    UILabel * currentLabel = [self valueForKey:labelName];
    if (iB[i] == itemPH) { // if label is not empty
        [currentLabel setText: [NSString stringWithFormat:@"%i",
                                        ([currentLabel.text intValue] + 1)]];
        labelGo = 0;
    }
}
utilityNum = nil;
utilityNum = [NSNumber numberWithInt:labelGo];
</code>```

}

答: Have a look at NSArray, NSSet, and -makeObjectsPerformSelector:

Title: Cocoa macro-- unique question

Body:
I need help with a #define to do the following:

for (int i = 0; i < 47; ++i)  {     SETLABEL(i)     }

the SETLABEL() macro should take the intValue of "i" and paste it into a label name:

when i == 1-->    label1.text = (stuff)

when i == 2-->    label2.text = (stuff)

Is this possible? The following fails miserably, because it pastes "i" in, rather than the value of "i":

#define SETLABEL(x)    [label##x setText: [foo stringValue]];

EDIT:  Thanks for all the help. My code looks like this now:

the declaration for the int is iB[25]

-(void)stuff {
int x;
int labelGo = 1;

for (int i = 1; i < 25; ++i) {
    NSString * labelName = [NSString stringWithFormat:@"magicItemBoughtTot%d", i];
    UILabel * currentLabel = [self valueForKey:labelName];
    if (iB[i] == itemPH) { // if label is not empty
        [currentLabel setText: [NSString stringWithFormat:@"%i",
                                        ([currentLabel.text intValue] + 1)]];
        labelGo = 0;
    }
}
utilityNum = nil;
utilityNum = [NSNumber numberWithInt:labelGo];

}


问:
.NET App.config. How to replace file attribute?
Here is short summary of current situation:
In my solution (console application) I use app.config file with entry like this:

< appSettings file="Additional.config">
On our production environment this file is provided by separate routine and we don't want to put it in projects file repository. Still we need a convenient way to run the solution in dev environment.

We've come with an idea to replace the file attribute using SlowCheetach. It works just fine with replacing key-value entries but we are unable to make it run correctly.

Is there a way to replace file property with SlowCheetach or any other lightweight tool? We really want to avoid using build scripts to modify app.config output.

答:
Solution below is not working properly because id is not a valid schema element. Real solution at the bottom.

I've figured out a simple way to accomplish this. All that is needed to do is add another attribute to appSettings and set it as Match Selector so entry in app.config would look like:

```<code> <appSettings file="Additional.config" id="appconfig">
</code>```

and the one in App.Debug.config:

```<code><appSettings id="appconfig" file="New/Path/To/Additional.config" xdt:Transform="Replace" xdt:Locator="Match(id)">
</code>```

Real solution here:

It turns out that you can simply use transform in form:

```<code>   <appSettings xdt:Transform="RemoveAttributes(file)">
</code>```

which will remove only attributes passed to RemoveAttributes and leave rest of the config intact.

More about possible transform attributes can be read here

Body:
Solution below is not working properly because id is not a valid schema element. Real solution at the bottom.

I've figured out a simple way to accomplish this. All that is needed to do is add another attribute to appSettings and set it as Match Selector so entry in app.config would look like:

 <appSettings file="Additional.config" id="appconfig">

and the one in App.Debug.config:

<appSettings id="appconfig" file="New/Path/To/Additional.config" xdt:Transform="Replace" xdt:Locator="Match(id)">

Real solution here:

It turns out that you can simply use transform in form:

   <appSettings xdt:Transform="RemoveAttributes(file)">

which will remove only attributes passed to RemoveAttributes and leave rest of the config intact.

More about possible transform attributes can be read here


问:
How to read JSON {"success": true} in Retrofit 2?
In normal JSONObject jsonResponse, I simply use boolean success = jsonResponse.getBoolean("success"); . Now, I am required to use Retrofit library.
I know that the response is in GSON format. That's why I'm having a hard time figuring out how to deal with the $response["success"] in my php file.

I tried this:

```<code>   call.enqueue(new Callback<User_Account_Model>() {
        @Override
        public void onResponse(Call<User_Account_Model> call, Response<User_Account_Model> response) {

            try {
                JSONObject jsonResponse = new JSONObject(new Gson().toJson(response));
                boolean success = jsonResponse.getBoolean("success");
                Toast.makeText(MainActivity.this,String.valueOf(success),Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
</code>```

but what's inside the try and catch seems not to be executed. No Toast messages showing. Is my method correct and just missing something or it's completely wrong?

答:
Make a Class with only one boolean value

```<code>public class MyResponse{
  @SerializedName("success")
  private boolean success;

  public boolean getSuccess(){
   return success;
  }
  public void setSuccess(boolean _success){
   success = _success
  }

}
</code>```

Use this class in enqueue method.

```<code>   call.enqueue(new Callback<MyResponse>() {
    @Override
    public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {

        try {
              int statusCode = response.code();
              Log.d("Response Code: ", "status Code: " + statusCode);
              if (response.isSuccessful()){
                MyResponse mResponse = response.body();
              }
        } catch (JSONException e) {
            e.printStackTrace();
        }
</code>```

If you response only contain one node "success" then it will work.

Body:
In normal JSONObject jsonResponse, I simply use boolean success = jsonResponse.getBoolean("success"); . Now, I am required to use Retrofit library.
I know that the response is in GSON format. That's why I'm having a hard time figuring out how to deal with the $response["success"] in my php file.

I tried this:

   call.enqueue(new Callback<User_Account_Model>() {
        @Override
        public void onResponse(Call<User_Account_Model> call, Response<User_Account_Model> response) {

            try {
                JSONObject jsonResponse = new JSONObject(new Gson().toJson(response));
                boolean success = jsonResponse.getBoolean("success");
                Toast.makeText(MainActivity.this,String.valueOf(success),Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }

but what's inside the try and catch seems not to be executed. No Toast messages showing. Is my method correct and just missing something or it's completely wrong?

Body:
Make a Class with only one boolean value

public class MyResponse{
  @SerializedName("success")
  private boolean success;

  public boolean getSuccess(){
   return success;
  }
  public void setSuccess(boolean _success){
   success = _success
  }

}

Use this class in enqueue method.

   call.enqueue(new Callback<MyResponse>() {
    @Override
    public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {

        try {
              int statusCode = response.code();
              Log.d("Response Code: ", "status Code: " + statusCode);
              if (response.isSuccessful()){
                MyResponse mResponse = response.body();
              }
        } catch (JSONException e) {
            e.printStackTrace();
        }

If you response only contain one node "success" then it will work.


问:
Using ?: shorthand in laravel
I have a login function that i am using to login users using telephone numbers. I am getting the phone numbers from the user and then using the phone number to fetch the matching email address.

For that i have this code

```<code>public function processLogin(Request $request){
    $phone = $request->get('phone');
    $getEmail = User::where('users_telephone_number', '=',$phone )->first()->email;
    $email = $getEmail;
    $password = $request->get('password');
    //echo $email.$password;
    $data = array(
        'email' => $email,
        'password' => $password
        );

    if (Auth::attempt($data,true)) {
</code>```

When the number is wrong, i get this error

Trying to get property of non-object

To solve the problem i want to have the variable $getEmail to be equal to  none@dont.com which will fail well like all other wrong email and password combos.

How can i make sure i catch errors in this one line i am using to fetch the email

User::where('users_telephone_number', '=',$phone )->first()->email;

答:
Or testing null:

```<code>$user = User::where('users_telephone_number', '=',$phone )->first();
$email = $user ? $user->email : 'default string';
</code>```

If your query doesn't return any User instance, it will return a default null value.

Or... you could test the email

```<code>$password = $request->get('password');
$user = User::where('users_telephone_number', '=', $phone)->whereNotNull('email')->first();

if ($user && Auth::attempt([$user->email, $password], true)) {
    ...
}
</code>```

Title: Using ?: shorthand in laravel

Body:
I have a login function that i am using to login users using telephone numbers. I am getting the phone numbers from the user and then using the phone number to fetch the matching email address.

For that i have this code

public function processLogin(Request $request){
    $phone = $request->get('phone');
    $getEmail = User::where('users_telephone_number', '=',$phone )->first()->email;
    $email = $getEmail;
    $password = $request->get('password');
    //echo $email.$password;
    $data = array(
        'email' => $email,
        'password' => $password
        );

    if (Auth::attempt($data,true)) {

When the number is wrong, i get this error

Trying to get property of non-object

To solve the problem i want to have the variable $getEmail to be equal to  none@dont.com which will fail well like all other wrong email and password combos.

How can i make sure i catch errors in this one line i am using to fetch the email

User::where('users_telephone_number', '=',$phone )->first()->email;

Body:
Or testing null:

$user = User::where('users_telephone_number', '=',$phone )->first();
$email = $user ? $user->email : 'default string';

If your query doesn't return any User instance, it will return a default null value.

Or... you could test the email

$password = $request->get('password');
$user = User::where('users_telephone_number', '=', $phone)->whereNotNull('email')->first();

if ($user && Auth::attempt([$user->email, $password], true)) {
    ...
}


问:
Formatting Date and Time with a function in C#
So I am getting the driver date from graphic card and display it into a TextBox but the value comes like this 20161216000000.000000-000 and I want to convert it into a real date.

I already got a function to convert this kind of dates, but it this case does does not work and after using it shows me like this 01-01-0001 00:00:00.

This is my function code:

```<code>private static string FormatDateTime(object ObjInstallDate)
{
    object FinalDate = DBNull.Value;
    string strDate = Convert.ToString(ObjInstallDate);
    DateTime dtm;
    DateTime.TryParseExact(strDate, new string[] { "yyyyMMdd", "yyyy-MM-dd", "dd-MM-yyyy" },
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, out dtm);
    if (!String.IsNullOrEmpty(strDate))
    {
        FinalDate = dtm;
    }
    return FinalDate.ToString();
}
</code>```

Do you have any idea how I can get in this case 20161216000000.000000-000 something like 2016-12-16?

答:
After looking at your code and question it looks like the date you are passing to the function is not in correct/expected format that c# supports, that's why it is giving you the default system's beginnning date which is 01-01-0001 00:00:00 here.

But, as a workl around, as I can observe first 8 digit of the input value is date part, so you can use that in following way:

```<code>DateTime.TryParseExact(strDate.Substring(0, 8), "yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtm);

return dtm.ToString("yyyy-MM-dd");
</code>```

Body:
So I am getting the driver date from graphic card and display it into a TextBox but the value comes like this 20161216000000.000000-000 and I want to convert it into a real date.

I already got a function to convert this kind of dates, but it this case does does not work and after using it shows me like this 01-01-0001 00:00:00.

This is my function code:

private static string FormatDateTime(object ObjInstallDate)
{
    object FinalDate = DBNull.Value;
    string strDate = Convert.ToString(ObjInstallDate);
    DateTime dtm;
    DateTime.TryParseExact(strDate, new string[] { "yyyyMMdd", "yyyy-MM-dd", "dd-MM-yyyy" },
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, out dtm);
    if (!String.IsNullOrEmpty(strDate))
    {
        FinalDate = dtm;
    }
    return FinalDate.ToString();
}

Do you have any idea how I can get in this case 20161216000000.000000-000 something like 2016-12-16?

Body:
After looking at your code and question it looks like the date you are passing to the function is not in correct/expected format that c# supports, that's why it is giving you the default system's beginnning date which is 01-01-0001 00:00:00 here.

But, as a workl around, as I can observe first 8 digit of the input value is date part, so you can use that in following way:

DateTime.TryParseExact(strDate.Substring(0, 8), "yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtm);

return dtm.ToString("yyyy-MM-dd");


答:
The input dataset seems to be data.table.  We transpose (t) the dataset, convert it to a vector and create a new data.table

```<code>library(data.table)
d1 <- data.table(v1 = c(t(df)))
head(d1, 4)
#       v1
#1: 1.1111
#2: 1.1111
#3: 1.1111
#4: 1.1111
</code>```

Or it can be also done by

```<code>df[, .(v1 = t(.SD))]
</code>```

Body:
How to combine and convert multiple rows into one column?
I have been searching but can't find a suitable solution for my question.
eg: please see Example df, how do I convert every rows into column and combine then them into one column, so the new df should have 25 rows with 1 column. Just like Expected Outcome
Thanks.

Example df

   Size   H-Size L-Size A-Size S-Size
1: 1.1111 1.1111 1.1111 1.1111 11465
2: 2.2222 2.2222 2.2222 2.2222 11419
3: 3.3333 3.3333 3.3333 3.3333 11534
4: 4.4444 4.4444 4.4444 4.4444 11154
5: 5.5555 5.5555 5.5555 5.5555 11640

Expected Outcome

   V1
1: 1.1111
2: 1.1111
3: 1.1111
4: 1.1111
5: 11465
6: 2.2222
7: 2.2222
8: 2.2222
9: 2.2222
10: 11419
11: 3.3333
12: 3.3333
13: 3.3333
14: 3.3333
15: 11534
16: 4.4444
17: 4.4444
18: 4.4444
19: 4.4444
20: 11154
21: 5.5555
22: 5.5555
23: 5.5555
24: 5.5555
25: 11640

Body:
The input dataset seems to be data.table.  We transpose (t) the dataset, convert it to a vector and create a new data.table

library(data.table)
d1 <- data.table(v1 = c(t(df)))
head(d1, 4)
#       v1
#1: 1.1111
#2: 1.1111
#3: 1.1111
#4: 1.1111

Or it can be also done by

df[, .(v1 = t(.SD))]


问:
iOS Floating Video Window like Youtube App
Does anyone know of any existing library, or any techniques on how to get the same effect as is found on the Youtube App.

The video can be "minimised" and hovers at the bottom of the screen - which can then be swiped to close or touched to re-maximised.

See:

Video Playing Normally: https://www.dropbox.com/s/o8c1ntfkkp4pc4q/2014-06-07%2001.19.20.png

Video Minimized: https://www.dropbox.com/s/w0syp3infu21g08/2014-06-07%2001.19.27.png

(Notice how the video is now in a small floating window on the bottom right of the screen).

Anyone have any idea how this was achieved, and if there are any existing tutorials or libraries that can be used to get this same effect?

答:
This is a swift 3 version for the answer @danh had provided earlier.

https://stackoverflow.com/a/24107949/1211470

```<code>import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var tallMpContainer: UIView!
    @IBOutlet weak var mpContainer: UIView!

    var swipeDown: UISwipeGestureRecognizer?
    var swipeUp: UISwipeGestureRecognizer?

    override func viewDidLoad() {
        super.viewDidLoad()
        swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(swipeDownAction))

        swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(swipeUpAction))

        swipeDown?.direction = .down
        swipeUp?.direction = .up

        self.mpContainer.addGestureRecognizer(swipeDown!)
        self.mpContainer.addGestureRecognizer(swipeUp!)
    }

    @objc func swipeDownAction() {
        minimizeWindow(minimized: true, animated: true)
    }

    @objc func swipeUpAction() {
        minimizeWindow(minimized: false, animated: true)
    }

    func isMinimized() -> Bool {
        return CGFloat((self.tallMpContainer?.frame.origin.y)!) > CGFloat(20)
    }

    func minimizeWindow(minimized: Bool, animated: Bool) {
        if isMinimized() == minimized {
            return
        }

        var tallContainerFrame: CGRect
        var containerFrame: CGRect

        var tallContainerAlpha: CGFloat

        if minimized == true {

            let mpWidth: CGFloat = 160
            let mpHeight: CGFloat = 90

            let x: CGFloat = 320-mpWidth
            let y: CGFloat = self.view.bounds.size.height - mpHeight;

            tallContainerFrame = CGRect(x: x, y: y, width: 320, height: self.view.bounds.size.height)
            containerFrame = CGRect(x: x, y: y, width: mpWidth, height: mpHeight)
            tallContainerAlpha = 0.0

        } else {

            tallContainerFrame = self.view.bounds
            containerFrame = CGRect(x: 0, y: 0, width: 320, height: 180)
            tallContainerAlpha = 1.0

        }

        let duration: TimeInterval = (animated) ? 0.5 : 0.0
        UIView.animate(withDuration: duration, animations: {
            self.tallMpContainer.frame = tallContainerFrame
            self.mpContainer.frame = containerFrame
            self.tallMpContainer.alpha = tallContainerAlpha
        })
    }

}
</code>```

Body:
This is a swift 3 version for the answer @danh had provided earlier.

https://stackoverflow.com/a/24107949/1211470

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var tallMpContainer: UIView!
    @IBOutlet weak var mpContainer: UIView!

    var swipeDown: UISwipeGestureRecognizer?
    var swipeUp: UISwipeGestureRecognizer?

    override func viewDidLoad() {
        super.viewDidLoad()
        swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(swipeDownAction))

        swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(swipeUpAction))

        swipeDown?.direction = .down
        swipeUp?.direction = .up

        self.mpContainer.addGestureRecognizer(swipeDown!)
        self.mpContainer.addGestureRecognizer(swipeUp!)
    }

    @objc func swipeDownAction() {
        minimizeWindow(minimized: true, animated: true)
    }

    @objc func swipeUpAction() {
        minimizeWindow(minimized: false, animated: true)
    }

    func isMinimized() -> Bool {
        return CGFloat((self.tallMpContainer?.frame.origin.y)!) > CGFloat(20)
    }

    func minimizeWindow(minimized: Bool, animated: Bool) {
        if isMinimized() == minimized {
            return
        }

        var tallContainerFrame: CGRect
        var containerFrame: CGRect

        var tallContainerAlpha: CGFloat

        if minimized == true {

            let mpWidth: CGFloat = 160
            let mpHeight: CGFloat = 90

            let x: CGFloat = 320-mpWidth
            let y: CGFloat = self.view.bounds.size.height - mpHeight;

            tallContainerFrame = CGRect(x: x, y: y, width: 320, height: self.view.bounds.size.height)
            containerFrame = CGRect(x: x, y: y, width: mpWidth, height: mpHeight)
            tallContainerAlpha = 0.0

        } else {

            tallContainerFrame = self.view.bounds
            containerFrame = CGRect(x: 0, y: 0, width: 320, height: 180)
            tallContainerAlpha = 1.0

        }

        let duration: TimeInterval = (animated) ? 0.5 : 0.0
        UIView.animate(withDuration: duration, animations: {
            self.tallMpContainer.frame = tallContainerFrame
            self.mpContainer.frame = containerFrame
            self.tallMpContainer.alpha = tallContainerAlpha
        })
    }

}


问:
UWP project referencing the wrong sqlite dll
somewhere along the line I was playing around and renamed a sqlite3.dll to sqlite3.copydll.  Now my UWP project is referencing that dll.  I have since changed it back to Sqlite3.dll what it should be but I keep getting the below when I build my project

Could not copy the file "C:\Users[username].nuget\packages\SQLite\3.13.0\runtimes\win10-x86\nativeassets\uap10.0\sqlite3.copydll" because it was not found.

I cant find where in my project it is still referencing this dll name.

Can anybody help

答: Open your .csproj as text and search for it there. Or remove reference to SQLite in VS and add it back.</p>


问:
Batch file that can read and process its own output in realtime?
I have a batch file which runs a python script. The python script after completion sends a number like shown below:
I need my batch file to read its own output as it runs and then use this (the number 3 shown in figure below to do some processing
Is this possible with batch?

EDITED FOR CLARITY:

I want to have a script which uses "net use" command.
The output from this specific command is as shown below... which will be printed to cmd window in which script is running ! Now I want my script to read this output ..like if a certain address is found in the already mapped drives list it will do something..like unmap the drive

答:
I don't understand quite well what your purpose is, what has to do python to do with capture the net use command output?

As a rule of thumb, to capture any command output, you must use a for loop (i.e. here capturing clipboard content using powershell

```<code>rem get clipboard content into variable
set "psCmd=powershell -Command "add-type -an system.windows.forms; [System.Windows.Forms.Clipboard]::GetText()""
for /F "usebackq delims=" %%# in (`%psCmd%`) do set "clipContent=%%#"
</code>```

So, in order to grab the output of net use

```<code>@echo off
for /f "skip=6 tokens=2,3" %%a in ('net use') do (
  echo/%%a | find ":">NUL && echo/Drive letter %%a - Remote name %%b
)
exit/B
</code>```

But, I suggest that you better use wmic (following two are similar)

```<code>@echo off
for /f "useback skip=1 tokens=1,2" %%a in (`"wmic path Win32_LogicalDisk Where DriveType="4" get DeviceID, ProviderName"`) do (
  echo/%%a | find ":">NUL && echo/Drive letter %%a - Remote name %%b
)
exit/B
</code>```

or

```<code>@echo off
for /f "useback skip=1 tokens=1,2" %%a in (`"wmic path Win32_MappedLogicalDisk get DeviceID, ProviderName"`) do (
  echo/%%a | find ":">NUL && echo/Drive letter %%a - Remote name %%b
)
exit/B
</code>```

Since, you may add the /node:"some_other_computer_name" switch to wmic and may list mapped drives from any computer on the net, i.e

```<code>@echo off
for /f "useback skip=1 tokens=1,2" %%a in (`"wmic /node:"hp-ml110" path Win32_MappedLogicalDisk Where DriveType="4" get DeviceID, ProviderName"`) do (
  echo/%%a | find ":">NUL && echo/Drive letter %%a - Remote name %%b
)
exit/B
</code>```

Hope it helps.

Body:
I don't understand quite well what your purpose is, what has to do python to do with capture the net use command output?

As a rule of thumb, to capture any command output, you must use a for loop (i.e. here capturing clipboard content using powershell

rem get clipboard content into variable
set "psCmd=powershell -Command "add-type -an system.windows.forms; [System.Windows.Forms.Clipboard]::GetText()""
for /F "usebackq delims=" %%# in (`%psCmd%`) do set "clipContent=%%#"

So, in order to grab the output of net use

@echo off
for /f "skip=6 tokens=2,3" %%a in ('net use') do (
  echo/%%a | find ":">NUL && echo/Drive letter %%a - Remote name %%b
)
exit/B

But, I suggest that you better use wmic (following two are similar)

@echo off
for /f "useback skip=1 tokens=1,2" %%a in (`"wmic path Win32_LogicalDisk Where DriveType="4" get DeviceID, ProviderName"`) do (
  echo/%%a | find ":">NUL && echo/Drive letter %%a - Remote name %%b
)
exit/B

or

@echo off
for /f "useback skip=1 tokens=1,2" %%a in (`"wmic path Win32_MappedLogicalDisk get DeviceID, ProviderName"`) do (
  echo/%%a | find ":">NUL && echo/Drive letter %%a - Remote name %%b
)
exit/B

Since, you may add the /node:"some_other_computer_name" switch to wmic and may list mapped drives from any computer on the net, i.e

@echo off
for /f "useback skip=1 tokens=1,2" %%a in (`"wmic /node:"hp-ml110" path Win32_MappedLogicalDisk Where DriveType="4" get DeviceID, ProviderName"`) do (
  echo/%%a | find ":">NUL && echo/Drive letter %%a - Remote name %%b
)
exit/B

Hope it helps.


问:
How do I convert a JSON string to a function in javascript?
How can I convert a string in javascript/jquery to a function?

I am trying to use a JSON parameter list to initialize a function.  However, one of the parameters is a function, which I store as a string, and I get an error when I try to use eval() to return the function.

For example, if my JSON is:

```<code>json = { "one": 700, "two": "function(e){alert(e);}" }
</code>```

Then in my code:

```<code>parameters = eval(json);
$('myDiv').addThisFeature({
 parameter_1: json.one,
 parameter_2: eval(json.two)  // <= generates error
})
</code>```

答:
Use this:

```<code>parameters = eval('(' + json + ')');
$('#myDiv').addThisFeature({
 parameter_1: parameters.one,
 parameter_2: eval('(' + parameters.two + ')')  // <= does not generate an error
});
</code>```

Adding the parentheses at the beginning and end of the string prevents the syntax error.

Note, however, that you are parsing JSON using eval (which in some cases has security risks, but I assume that is irrelevant because you do want to run arbitrary code sent by the server). If you have the server-side flexibility (to send invalid JSON), you could just send the function not quoted as a string and eval should be able to parse that just fine.

Body:
How can I convert a string in javascript/jquery to a function?

I am trying to use a JSON parameter list to initialize a function.  However, one of the parameters is a function, which I store as a string, and I get an error when I try to use eval() to return the function.

For example, if my JSON is:

json = { "one": 700, "two": "function(e){alert(e);}" }

Then in my code:

parameters = eval(json);
$('myDiv').addThisFeature({
 parameter_1: json.one,
 parameter_2: eval(json.two)  // <= generates error
})

Body:
Use this:

parameters = eval('(' + json + ')');
$('#myDiv').addThisFeature({
 parameter_1: parameters.one,
 parameter_2: eval('(' + parameters.two + ')')  // <= does not generate an error
});

Adding the parentheses at the beginning and end of the string prevents the syntax error.

Note, however, that you are parsing JSON using eval (which in some cases has security risks, but I assume that is irrelevant because you do want to run arbitrary code sent by the server). If you have the server-side flexibility (to send invalid JSON), you could just send the function not quoted as a string and eval should be able to parse that just fine.


问:
How to properly use target_include_directories with lists of includes
I have a setup where I collect multiple include directories that I want to set as include directories, as in this mock up:

```<code>add_library(testlib SHARED "")
set_target_properties(testlib PROPERTIES LINKER_LANGUAGE CXX)
list(APPEND includePath "/some/dir" "/some/other/dir")
target_include_directories(testlib PUBLIC
  $<BUILD_INTERFACE:${includePath}>
)
</code>```

The problem now is the following

```<code>get_target_property(debug testlib INTERFACE_INCLUDE_DIRECTORIES)
message("${debug}")
</code>```

prints

```<code>/home/user/test-proj/$<BUILD_INTERFACE:/some/dir;/some/other/dir>
</code>```

where the absolute path to the project is for some reason prepended to the include directories. This leads to cmake proclaiming, somewhere down the line:

```<code>CMake Error in src/hypro/CMakeLists.txt:
  Target "testlib" INTERFACE_INCLUDE_DIRECTORIES property contains path:

    "/home/user/test-proj/"

  which is prefixed in the source directory.
</code>```

Can I somehow use a list with $<BUILD_INTERFACE>?

答:
As @Florian writes in a comment, indeed putting $<BUILD_INTERFACE:> in quotes does the job:

```<code>target_include_directories(testlib PUBLIC
  "$<BUILD_INTERFACE:${includePath}>"
)
</code>```

The reason is that includePath is a list here, and thus contains a ;, which cmake doesn't like outside a string.

Body:
I have a setup where I collect multiple include directories that I want to set as include directories, as in this mock up:

add_library(testlib SHARED "")
set_target_properties(testlib PROPERTIES LINKER_LANGUAGE CXX)
list(APPEND includePath "/some/dir" "/some/other/dir")
target_include_directories(testlib PUBLIC
  $<BUILD_INTERFACE:${includePath}>
)

The problem now is the following

get_target_property(debug testlib INTERFACE_INCLUDE_DIRECTORIES)
message("${debug}")

prints

/home/user/test-proj/$<BUILD_INTERFACE:/some/dir;/some/other/dir>

where the absolute path to the project is for some reason prepended to the include directories. This leads to cmake proclaiming, somewhere down the line:

CMake Error in src/hypro/CMakeLists.txt:
  Target "testlib" INTERFACE_INCLUDE_DIRECTORIES property contains path:

    "/home/user/test-proj/"

  which is prefixed in the source directory.

Can I somehow use a list with $<BUILD_INTERFACE>?

Body:
As @Florian writes in a comment, indeed putting $<BUILD_INTERFACE:> in quotes does the job:

target_include_directories(testlib PUBLIC
  "$<BUILD_INTERFACE:${includePath}>"
)

The reason is that includePath is a list here, and thus contains a ;, which cmake doesn't like outside a string.


答:
The index is here to speed up your SQL search.
https://dev.mysql.com/doc/refman/5.7/en/mysql-indexes.html

If you don't have any index, SQL will go trough the whole table when you're looking for a specific value (WHERE cod_clie = "example").

If you have big databases with a lot of data you'll realize a quite big difference in performance time.

Title: MySql SELECT index benefits

Body:
Are there significant benefits between the two SQL select ?

SELECT * FROM table USE INDEX (cod_clie) WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;

SELECT * FROM table WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;

cod_clie is an INDEX field, of course!


问:
How to set the video (in slider) to auto start only it appears
I am working on a slider, one of the slides is a video, how to not to let it plays while other slides are sliding and to autoplay right at the moment it appears. The video last 30 sec.</p>

答:
I don't think there's a nice way for auto playing the video when it appears using only the autoplay html attribute on the element. But you should be able to get the desired effect with some simple javascript.

If you are using an HTML5 video element remove the autoplay attribute to prevent it from starting to play when it is not visible. On slide change, check whether the currently visible element is your video and if so call .play() on the video element to start it. Once it is not visible anymore (on the next slide change) call .pause() on the element to stop execution.

If you want to start the video from the beginning next time it is visible call .load() once it is not visible anymore to reload the video and start it from the beginning next time. Otherwise it will continue playing where it left off last time it was visible.

Check this for a reference of methods available on the video element:
https://developer.mozilla.org/en/docs/Web/API/HTMLMediaElement


问:
Code working in one Addin but doing nothing in another
```<code>FilteredElementCollector Lincoln = new FilteredElementCollector(doc);
Lincoln.OfCategory(BuiltInCategory.OST_RvtLinks); Autodesk.Revit.DB.View CurrentView = uiDoc.ActiveView;
ICollection<ElementId> Toggle_On = Lincoln.ToElementIds(); Toggle_On.Clear();
ICollection<ElementId> Toggle_Off = Lincoln.ToElementIds(); Toggle_Off.Clear();
List<Element> Processed = new List<Element>();
List<string> Revit_On = new List<string>(); List<string> Revit_Off = new List<string>();
List<string> Revit_Names = new List<string>();
foreach (Element One_Link in Lincoln)
{
    string Revit_Name = One_Link.Name;
    if (!Revit_Names.Contains(Revit_Name))//prevents processing same link twice;/but does NOT change anyway!!!!
    {
        Revit_Names.Add(Revit_Name);
        Boolean Is_Hidden = One_Link.IsHidden(CurrentView);//
        if (Is_Hidden)
        {
            Toggle_On.Add(One_Link.Id); Revit_On.Add(One_Link.Name);
        }//this apparently does detect what is hidden;
        else
        {
            Toggle_Off.Add(One_Link.Id); Revit_Off.Add(One_Link.Name);
        }
    }
}
Transaction Do_Toggle = new Transaction(doc, "DoToggle");
Do_Toggle.Start();
if (!Toggle_Off.Count.Equals(0)) { CurrentView.HideElements(Toggle_Off); }
if (!Toggle_On.Count.Equals(0)) { CurrentView.UnhideElements(Toggle_On); }
Do_Toggle.Commit();
</code>```

Is somehow the transaction failing?  Undo is not available, so it doesn't think it has done anything that might need to be undone.  Note that this EXACT code is used in another one of my addins (in which multiple optional sub-programs are controlled by picking radio options on a form).  But when I am trying to use the code in a standalone version, it fails (without errors).  Note also that I've inserted multiple TaskDialog entries to verify that it is indeed finding the RvtLinks that are either visible or hidden in the current view.  But it is simply refusing to actually change their visibility.  If I run the dialog controlled version, everything toggles, but if I immediately run the standalone, nothing toggles (proving it isn't uneditable pinned links).  I have made this option available to users by making "Toggle Links" the default so they can call up my collected program and just hit a carriage return, but I need this to be a true standalone.

答:
You code confuses me. For instance, why do you initialise the Toggle_On and Toggle_Off collections with member values, only to clear them immediately afterwards?

In any case, you use of the transaction does not follow the recommended pattern of enclosing it in a using statement.

Please refer to The Building Coder topic group on Handling Transactions and Transaction Groups for more information on using transactions in the Revit API.

Body:
FilteredElementCollector Lincoln = new FilteredElementCollector(doc);
Lincoln.OfCategory(BuiltInCategory.OST_RvtLinks); Autodesk.Revit.DB.View CurrentView = uiDoc.ActiveView;
ICollection<ElementId> Toggle_On = Lincoln.ToElementIds(); Toggle_On.Clear();
ICollection<ElementId> Toggle_Off = Lincoln.ToElementIds(); Toggle_Off.Clear();
List<Element> Processed = new List<Element>();
List<string> Revit_On = new List<string>(); List<string> Revit_Off = new List<string>();
List<string> Revit_Names = new List<string>();
foreach (Element One_Link in Lincoln)
{
    string Revit_Name = One_Link.Name;
    if (!Revit_Names.Contains(Revit_Name))//prevents processing same link twice;/but does NOT change anyway!!!!
    {
        Revit_Names.Add(Revit_Name);
        Boolean Is_Hidden = One_Link.IsHidden(CurrentView);//
        if (Is_Hidden)
        {
            Toggle_On.Add(One_Link.Id); Revit_On.Add(One_Link.Name);
        }//this apparently does detect what is hidden;
        else
        {
            Toggle_Off.Add(One_Link.Id); Revit_Off.Add(One_Link.Name);
        }
    }
}
Transaction Do_Toggle = new Transaction(doc, "DoToggle");
Do_Toggle.Start();
if (!Toggle_Off.Count.Equals(0)) { CurrentView.HideElements(Toggle_Off); }
if (!Toggle_On.Count.Equals(0)) { CurrentView.UnhideElements(Toggle_On); }
Do_Toggle.Commit();

Is somehow the transaction failing?  Undo is not available, so it doesn't think it has done anything that might need to be undone.  Note that this EXACT code is used in another one of my addins (in which multiple optional sub-programs are controlled by picking radio options on a form).  But when I am trying to use the code in a standalone version, it fails (without errors).  Note also that I've inserted multiple TaskDialog entries to verify that it is indeed finding the RvtLinks that are either visible or hidden in the current view.  But it is simply refusing to actually change their visibility.  If I run the dialog controlled version, everything toggles, but if I immediately run the standalone, nothing toggles (proving it isn't uneditable pinned links).  I have made this option available to users by making "Toggle Links" the default so they can call up my collected program and just hit a carriage return, but I need this to be a true standalone.


问:
VMWare - Virtual operating system static IP address
What is the best way to have a virtual operating system have a static IP address in VMWware. I would like to keep the IP address static since it is a virtual server.</p>

答:
Assuming you're not using NAT-based VMWare networking, the answer isn't any different for a virtual (guest) server than for a real one. You can:

Assign a static IP via whatever mechanism the guest operating system supports.

Configure the guest operating system to get its IP address from a DHCP server, and configure the DHCP server to return a static IP address for the VMWare instance's MAC address.

OwnerDisplayName: Dan K.

LastEditorDisplayName: sascha

OwnerDisplayName: Brian Clapper


问:
How to select top 1 and ordered by date in Oracle SQL?
There is a clear answer how to select top 1:

```<code>select * from table_name where rownum = 1
</code>```

and how to order by date in descending order:

```<code>select * from table_name order by trans_date desc
</code>```

but they does not work togeather (rownum is not generated according to trans_date):

```<code>... where rownum = 1 order by trans_date desc
</code>```

The question is how to select top 1 also ordered by date?

答:
There should be subquery so the combination rownum & order could work:

```<code>select * from (select * from table_name order by trans_date desc) AS tb where rownum = 1
</code>```

Body:
There is a clear answer how to select top 1:

select * from table_name where rownum = 1

and how to order by date in descending order:

select * from table_name order by trans_date desc

but they does not work togeather (rownum is not generated according to trans_date):

... where rownum = 1 order by trans_date desc

The question is how to select top 1 also ordered by date?

Body:
There should be subquery so the combination rownum & order could work:

select * from (select * from table_name order by trans_date desc) AS tb where rownum = 1


问:
VertX: download files from server
I want to open the browser built-in pop-up to download a file when going to this url?

http://localhost:8080/retrieval

Now on the server side I have:

```<code>router.get("/retrieval").handler(rc -> {
        rc.response().sendFile("J1.txt");
    });
</code>```

Instead I see the content of the file in the browser. What should I do? Is there some specific headers that need to be sent?

Thanks

答:
Sorry I found out :)

The solution is as I thought using some headers:

```<code>rc.response()
        .putHeader(HttpHeaders.CONTENT_TYPE, "text/plain")
        .putHeader("Content-Disposition", "attachment; filename=\"J1.txt\"")
        .putHeader(HttpHeaders.TRANSFER_ENCODING, "chunked")
        .sendFile("J1.txt").end();
</code>```

Title: VertX: download files from server

Body:
I want to open the browser built-in pop-up to download a file when going to this url?

http://localhost:8080/retrieval

Now on the server side I have:

router.get("/retrieval").handler(rc -> {
        rc.response().sendFile("J1.txt");
    });

Instead I see the content of the file in the browser. What should I do? Is there some specific headers that need to be sent?

Thanks

Body:
Sorry I found out :)

The solution is as I thought using some headers:

rc.response()
        .putHeader(HttpHeaders.CONTENT_TYPE, "text/plain")
        .putHeader("Content-Disposition", "attachment; filename=\"J1.txt\"")
        .putHeader(HttpHeaders.TRANSFER_ENCODING, "chunked")
        .sendFile("J1.txt").end();