问:
Intersect doesn't work between Lists
I have a little strange problem.
 I use Visual Studio and I am developing a project with C#.

I have two custom classes "Attr" and "FD" and I use lists that includes their objects e.g.

```<code>List<Attr> attrList = new List<Attr>();
List<FD> fdList = new List<FD>();
</code>```

So when I try to find the intersection of two lists the result is not what I expect. To make it more simple I tried to Intersect similar Objects and the result is wrong again. What is going wrong?

This is the fd. It is an object of class FD.

This is the ff which is also an object of FD class.

As you can see these object contains exactly the same values.

The method GetLeft() returns a list that contains objects of class Attr.

So when I try to find the intersection between those two lists (fd.GetLeft() and ff.GetLeft() ) the result is nothing (it should be a list that contains an Attr object "A").

What did I miss?

P.S. These screenshots are from the debugg mode in Visual Studio.

答:
If you created your own class, and did not override the Equals-method in that class, the Intersect-method will only compare the references of the objects, and not the properties.

Take the following, really simple class:

```<code>class MyClass
{
  int Value { get; set; }

  public MyClass(int value)
  {
    this.Value = value;
  }
}
</code>```

Now, create two lists, with both containing one object. The properties of the objects are the same, but the instances are not:

```<code>  var list1 = new List<MyClass>
  {
    new MyClass(5)
  };

  var list2 = new List<MyClass>
  {
    new MyClass(5)
  };
</code>```

So the following will happen:

```<code>  list1[0].Equals(list2[0]); // false
  list1.Intersect(list2); // No matches
</code>```

If you want these methods to compare the properties of your MyClass-objects, implement IEqualityComparer<MyClass>, e.g. change the classes signature to:

```<code>class MyClass : IEqualityComparer<MyClass>
{
  ..
}
</code>```

Alternatively, you can just override Equals and GetHashCode, as then these methods will be called as default IEqualityComparer.

See the this answer on how to properly override Equals and GetHashCode.

Title: Intersect doesn't work between Lists

Body:
I have a little strange problem.
 I use Visual Studio and I am developing a project with C#.

I have two custom classes "Attr" and "FD" and I use lists that includes their objects e.g.

List<Attr> attrList = new List<Attr>();
List<FD> fdList = new List<FD>();

So when I try to find the intersection of two lists the result is not what I expect. To make it more simple I tried to Intersect similar Objects and the result is wrong again. What is going wrong?

This is the fd. It is an object of class FD.

This is the ff which is also an object of FD class.

As you can see these object contains exactly the same values.

The method GetLeft() returns a list that contains objects of class Attr.

So when I try to find the intersection between those two lists (fd.GetLeft() and ff.GetLeft() ) the result is nothing (it should be a list that contains an Attr object "A").

What did I miss?

P.S. These screenshots are from the debugg mode in Visual Studio.

Body:
If you created your own class, and did not override the Equals-method in that class, the Intersect-method will only compare the references of the objects, and not the properties.

Take the following, really simple class:

class MyClass
{
  int Value { get; set; }

  public MyClass(int value)
  {
    this.Value = value;
  }
}

Now, create two lists, with both containing one object. The properties of the objects are the same, but the instances are not:

  var list1 = new List<MyClass>
  {
    new MyClass(5)
  };

  var list2 = new List<MyClass>
  {
    new MyClass(5)
  };

So the following will happen:

  list1[0].Equals(list2[0]); // false
  list1.Intersect(list2); // No matches

If you want these methods to compare the properties of your MyClass-objects, implement IEqualityComparer<MyClass>, e.g. change the classes signature to:

class MyClass : IEqualityComparer<MyClass>
{
  ..
}

Alternatively, you can just override Equals and GetHashCode, as then these methods will be called as default IEqualityComparer.

See the this answer on how to properly override Equals and GetHashCode.


来源: stackexchange

问:
Android Google VrVideoView with RTSP source
I would like to use VrVideoView to show VR video in my Android App. Video is streamed via RTSP protocol. When I try to add such source to VrVideoView I've got

```<code>java.net.MalformedURLException: unknown protocol: rtsp
</code>```

I found this project RTSP-Java-UrlConnection which solve this exception, but shows another one:

```
ExoPlayerImplInternal: Internal track renderer error.
    com.google.android.exoplayer.ExoPlaybackException: com.google.android.exoplayer.upstream.Loader$UnexpectedLoaderException: Unexpected ClassCastException: com.net.rtsp.RtspURLConnection cannot be cast to java.net.HttpURLConnection
        at com.google.android.exoplayer.SampleSourceTrackRenderer.maybeThrowError(SampleSourceTrackRenderer.java:262)
        at com.google.android.exoplayer.SampleSourceTrackRenderer.maybeThrowError(SampleSourceTrackRenderer.java:148)
        at com.google.android.exoplayer.ExoPlayerImplInternal.incrementalPrepareInternal(ExoPlayerImplInternal.java:273)
        at com.google.android.exoplayer.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:203)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:148)
        at android.os.HandlerThread.run(HandlerThread.java:61)
        at com.google.android.exoplayer.util.PriorityHandlerThread.run(PriorityHandlerThread.java:40)
     Caused by: com.google.android.exoplayer.upstream.Loader$UnexpectedLoaderException: Unexpected ClassCastException: com.net.rtsp.RtspURLConnection cannot be cast to java.net.HttpURLConnection
        at com.google.android.exoplayer.upstream.Loader$LoadTask.run(Loader.java:235)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.ClassCastException: com.net.rtsp.RtspURLConnection cannot be cast to java.net.HttpURLConnection
        at com.google.android.exoplayer.upstream.DefaultHttpDataSource.makeConnection(DefaultHttpDataSource.java:384)
        at com.google.android.exoplayer.upstream.DefaultHttpDataSource.makeConnection(DefaultHttpDataSource.java:339)
        at com.google.android.exoplayer.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:189)
        at com.google.android.exoplayer.upstream.DefaultUriDataSource.open(DefaultUriDataSource.java:133)
        at com.google.android.exoplayer.extractor.ExtractorSampleSource$ExtractingLoadable.load(ExtractorSampleSource.java:823)
        at com.google.android.exoplayer.upstream.Loader$LoadTask.run(Loader.java:222)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
```

It looks like Google VrVideoView accepts only video with HTTP URL. What can I do to use VrVideoView with RTPS source?

答:
Here is an answer:

We don't have any plans to support live video in VR View. You can
  roll your own 360 viewer using the lower level GVR View classes,
  though. Source: https://github.com/googlevr/gvr-android-sdk/issues/217#issuecomment-244588848

ContentLicense: CC BY-SA 3.0

Body:
I would like to use VrVideoView to show VR video in my Android App. Video is streamed via RTSP protocol. When I try to add such source to VrVideoView I've got

java.net.MalformedURLException: unknown protocol: rtsp

I found this project RTSP-Java-UrlConnection which solve this exception, but shows another one:

ExoPlayerImplInternal: Internal track renderer error.
    com.google.android.exoplayer.ExoPlaybackException: com.google.android.exoplayer.upstream.Loader$UnexpectedLoaderException: Unexpected ClassCastException: com.net.rtsp.RtspURLConnection cannot be cast to java.net.HttpURLConnection
        at com.google.android.exoplayer.SampleSourceTrackRenderer.maybeThrowError(SampleSourceTrackRenderer.java:262)
        at com.google.android.exoplayer.SampleSourceTrackRenderer.maybeThrowError(SampleSourceTrackRenderer.java:148)
        at com.google.android.exoplayer.ExoPlayerImplInternal.incrementalPrepareInternal(ExoPlayerImplInternal.java:273)
        at com.google.android.exoplayer.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:203)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:148)
        at android.os.HandlerThread.run(HandlerThread.java:61)
        at com.google.android.exoplayer.util.PriorityHandlerThread.run(PriorityHandlerThread.java:40)
     Caused by: com.google.android.exoplayer.upstream.Loader$UnexpectedLoaderException: Unexpected ClassCastException: com.net.rtsp.RtspURLConnection cannot be cast to java.net.HttpURLConnection
        at com.google.android.exoplayer.upstream.Loader$LoadTask.run(Loader.java:235)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.ClassCastException: com.net.rtsp.RtspURLConnection cannot be cast to java.net.HttpURLConnection
        at com.google.android.exoplayer.upstream.DefaultHttpDataSource.makeConnection(DefaultHttpDataSource.java:384)
        at com.google.android.exoplayer.upstream.DefaultHttpDataSource.makeConnection(DefaultHttpDataSource.java:339)
        at com.google.android.exoplayer.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:189)
        at com.google.android.exoplayer.upstream.DefaultUriDataSource.open(DefaultUriDataSource.java:133)
        at com.google.android.exoplayer.extractor.ExtractorSampleSource$ExtractingLoadable.load(ExtractorSampleSource.java:823)
        at com.google.android.exoplayer.upstream.Loader$LoadTask.run(Loader.java:222)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)

It looks like Google VrVideoView accepts only video with HTTP URL. What can I do to use VrVideoView with RTPS source?


问:
How to declare different functions in different conditions?

Additionally, function declarations should never appear inside of
  block statements. For example, this code won’t behave as expected:

```<code>// Bad
if (condition) {
    function doSomething() {
    alert("Hi!");
  }
} else {
    function doSomething() {
    alert("Yo!");
  }
}
</code>```

Exactly how this will work from browser to browser will vary. Most
  browsers automatically take the second declaration without evaluating
  condition; Firefox evaluates condition and uses the appropriate
  function declaration. This is a gray area in the ECMAScript
  specification and should thus be avoided. Function declarations should
  be used only outside of conditional statements. This pattern is
  explicitly forbidden in the Google JavaScript Style Guide.

I find these words in the book Maintainable JavaScript in page 42, it says that declaring function in 'if' statement is basicly not allowed. So what's the proper method to declare different functions in different conditions? This book didn't give a solution on this issue.

答:
Function declarations and function variables are always moved (‘hoisted’) to the top of their JavaScript scope by the JavaScript interpreter.

Source: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

An if/else block doesn't create a new scope which means that approach won't work. There's plenty of ways to handle this case scenario, some of which are:

1 - Add the if (condition) internally to the function definition.

```<code>function doSomething(){
  var condition = .......
  if (condition) { ... }
  else { .... }
}
</code>```

2 - Send a parameter to the function to know which implementation to use (in case finding out the value of the condition doesn't suit inside the function).

```<code>function doSomething(condition){
  if (condition) { ... }
  else { .... }
}
</code>```

3 - Have two functions that do different things and call one or the other based on the condition.

```<code>if (condition) doSomething()
else doOtherThing()
</code>```

Body:
Additionally, function declarations should never appear inside of
  block statements. For example, this code won’t behave as expected:

// Bad
if (condition) {
    function doSomething() {
    alert("Hi!");
  }
} else {
    function doSomething() {
    alert("Yo!");
  }
}

Exactly how this will work from browser to browser will vary. Most
  browsers automatically take the second declaration without evaluating
  condition; Firefox evaluates condition and uses the appropriate
  function declaration. This is a gray area in the ECMAScript
  specification and should thus be avoided. Function declarations should
  be used only outside of conditional statements. This pattern is
  explicitly forbidden in the Google JavaScript Style Guide.

I find these words in the book Maintainable JavaScript in page 42, it says that declaring function in 'if' statement is basicly not allowed. So what's the proper method to declare different functions in different conditions? This book didn't give a solution on this issue.

Body:
Function declarations and function variables are always moved (‘hoisted’) to the top of their JavaScript scope by the JavaScript interpreter.

Source: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

An if/else block doesn't create a new scope which means that approach won't work. There's plenty of ways to handle this case scenario, some of which are:

1 - Add the if (condition) internally to the function definition.

function doSomething(){
  var condition = .......
  if (condition) { ... }
  else { .... }
}

2 - Send a parameter to the function to know which implementation to use (in case finding out the value of the condition doesn't suit inside the function).

function doSomething(condition){
  if (condition) { ... }
  else { .... }
}

3 - Have two functions that do different things and call one or the other based on the condition.

if (condition) doSomething()
else doOtherThing()


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
Pointers.

When I started programming in Turbo Pascal, I really couldn't understand, how the heck they write big programs. Memory was limited, and whatever I was trying to do - I would often hit the stack limits.

When I finally was introduced to pointers I was finally hooked, because I could finally start making something big! Not that I made anything big, but... :)

OwnerDisplayName: Michael Buen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Triptych

OwnerDisplayName: Paulius Maruška


问:
Web Mining Via Search Engines
I was apartment-shopping via Google Maps, copying various listings into a spreadsheet so I could more easily compare and attach notes, when I realized how unnecessarily repetitive and inefficient this was. I could easily write a script to automatically query Google and extract the data I need, but to get some of the data (e.g. contact phone number) requires that I follow a link to a listing-specific site and hunt-around for the data, and I've never written a web-crawler that dynamic. What are the common data-mining and/or machine learning techniques and tools for extracting a "best-guess" for a piece of info given arbitrary HTML?</p>

答:
This is called Information Extraction.

This video isn't bad. The guy is from Google:

http://videolectures.net/mlas06_nigam_tie/

Check out RapidMiner and its Information Extraction plugin.

Title: Web Mining Via Search Engines


问:
Awake app via BLE broadcast
I am finding a contradictory information on this so I need help from iOS BLE expert.

Namely, there is a device that can detect when someone is jamming it. In that case, it will send a broadcast message and a warning will appear in iOS app. This works perfectly when the app is in the foreground. When I put it to the background by pressing the home button, it stops reacting to jamming broadcast messages.

So, is it possible that app received BLE message when it's in the background?

If it is not possible, what is the workable solution to solve this use case? Please propose

答:
You have to add the background mode bluetooth-central in your app plist for the key UIBackgroundModes.

You can also do it via the Capabilities tab in your target properties, and set "Uses Bluetooth LE accessories" in Background Modes.

Title: Awake app via BLE broadcast


问:
Sharing data between two input fields by ngModel
I have 2 input fileds lets say input1 and input2. I have event such that  everything  I type in input1 it shows in input2.
Now the condition is if i manually change or type something in input2 , the event i had created above should not work.

I guess need to use count loop but I am confused.

html code:

```<code><input placeholder="Organization Name" [(ngModel)] = "orgName" (ngModelChange)="setdomain($event)">

<input placeholder="Business + Sub Domain" [(ngModel)] = "subdomain">
</code>```

fragment of TypeScript file:

```<code>subdomain : string;

setdomain(name) {
    this.subdomain = name.toLowerCase().replace(/ /g ,'');
}
</code>```

答:
cant you just the defaut value of input2 to that of input1. I think it should work.</p>

```<code><input placeholder="Organization Name" #input1>

<input value=input1.value placeholder="Business + Sub Domain">
</code>```

Body:
I have 2 input fileds lets say input1 and input2. I have event such that  everything  I type in input1 it shows in input2.
Now the condition is if i manually change or type something in input2 , the event i had created above should not work.

I guess need to use count loop but I am confused.

html code:

<input placeholder="Organization Name" [(ngModel)] = "orgName" (ngModelChange)="setdomain($event)">

<input placeholder="Business + Sub Domain" [(ngModel)] = "subdomain">

fragment of TypeScript file:

subdomain : string;

setdomain(name) {
    this.subdomain = name.toLowerCase().replace(/ /g ,'');
}

Body:
cant you just the defaut value of input2 to that of input1. I think it should work.

<input placeholder="Organization Name" #input1>

<input value=input1.value placeholder="Business + Sub Domain">


问:
Tensorflow: Single GPU vs. Multi GPU
Will it be better to use one good GPU like the Titan X with 12 GB Memory or two GTX 1080 with 8 GB Memory each to compute large CNNs.
Both will cost about the same.

Nvidia suggests the Titan X here, but why? What are the advantages having one GPU with much Memory than having two smaller GPUs which have more Memory when combined?

答:
So from my personal experience is tensorflow tends to only use one GPU. That might not always the case, but for the algorithms I'm running it seems to use only one.

Personally I would go for two gtx 1080 ti's or one gtx 1080ti. The cost for the titan for one more GB or gddr and a slightly faster bus doesn't make since.

I would go for two just so you can run multiple experiments at once.

8 Nvidia tesala's running tensorflow.

Title: Tensorflow: Single GPU vs. Multi GPU


问:
How to add ngClass type functionality to a row of Primeng p-datatable
I have been using Primeng for a while.

I have used Primeng Datatable (p-dataTable) in my component. The component what I am trying to do is inbox. I read messages from DB to a model named 'Message' in Angular 2. There is a field in model named Read. Its used as a flag. Its Boolean. My requirement is if Read is false, entire row elements should be in one colour, say color1. If Read is true, entire row elements should be another color, say color2.

I know how to do the same using ngClass.

Can someone please suggest me how I can do the same using p-dataTable. I tried many ways I can by referring many sites & didn't find any. What I want is a functionality similar to ngClass in p-dataTable

Here is my code

In HTML

```<code><p-dataTable [rowStyleClass]="readFlag" [value]="message" >
        <p-column [style]="{'width':'38px'}"  selectionMode="multiple"></p-column>
        <p-column field="SenderUserId"  header="From" [sortable]="true"></p-column>
        <p-column class="icon-mandatory" field="Subject" header="Message"></p-column>
        <p-column field="MessageDate" header="Time" [sortable]="true">
            <template let-col let-message="rowData" pTemplate type="body">
                <span>{{message.MessageDate | date: 'medium'}}</span>
            </template>
        </p-column>
</p-dataTable>
</code>```

In Component

```<code>readFlag(rowData: Message) { return rowData.Read ? 'inbox-Read' : 'inbox-Unread' ; }
</code>```

Message Model

```<code>export class Message
{
    public Subject: string;
    public Body: string;
    public MessageDate: any;
    public Read: boolean;
}
</code>```

答:
I found out the answer for my question

In HTML

```<code><p-dataTable [rowStyleClass]="applyReadFlagStyle" [value]="message">
        <p-column [style]="{'width':'38px'}"  selectionMode="multiple"></p-column>
        <p-column field="SenderUserId"  header="From" [sortable]="true"></p-column>
        <p-column field="Subject" header="Message"></p-column>
        <p-column field="MessageDate" header="Time" [sortable]="true">
            <template let-col let-message="rowData" pTemplate type="body">
                <span>{{message.MessageDate | date: 'medium'}}</span>
            </template>
</p-dataTable>
</code>```

In Component

```<code>applyReadFlagStyle(rowData: Message): string {
    return rowData.IsRead ? 'inbox-Read': 'inbox-UnRead'  ;
}
</code>```

Body:
I have been using Primeng for a while.

I have used Primeng Datatable (p-dataTable) in my component. The component what I am trying to do is inbox. I read messages from DB to a model named 'Message' in Angular 2. There is a field in model named Read. Its used as a flag. Its Boolean. My requirement is if Read is false, entire row elements should be in one colour, say color1. If Read is true, entire row elements should be another color, say color2.

I know how to do the same using ngClass.

Can someone please suggest me how I can do the same using p-dataTable. I tried many ways I can by referring many sites & didn't find any. What I want is a functionality similar to ngClass in p-dataTable

Here is my code

In HTML

            <template let-col let-message="rowData" pTemplate type="body">
                {{message.MessageDate | date: 'medium'}}
            </template>

In Component

readFlag(rowData: Message) { return rowData.Read ? 'inbox-Read' : 'inbox-Unread' ; }

Message Model

export class Message
{
    public Subject: string;
    public Body: string;
    public MessageDate: any;
    public Read: boolean;
}

Body:
I found out the answer for my question

In HTML

<p-dataTable [rowStyleClass]="applyReadFlagStyle" [value]="message">
        <p-column [style]="{'width':'38px'}"  selectionMode="multiple"></p-column>
        <p-column field="SenderUserId"  header="From" [sortable]="true"></p-column>
        <p-column field="Subject" header="Message"></p-column>
        <p-column field="MessageDate" header="Time" [sortable]="true">
            <template let-col let-message="rowData" pTemplate type="body">
                <span>{{message.MessageDate | date: 'medium'}}</span>
            </template>
</p-dataTable>

In Component

applyReadFlagStyle(rowData: Message): string {
    return rowData.IsRead ? 'inbox-Read': 'inbox-UnRead'  ;
}


问:
Resize image - keep ratio - without background image
Im trying to achieve the effect shown on this site:

http://fofwebdesign.co.uk/template/_testing/scale-img/target-ratio-resize.htm

BUT this site does it using a background image for a div. I cannot use the background image as the image is inside Wordpress and it's being brought in dynamically using the following code:

```<code><div class="featured-image">
   <?php the_post_thumbnail(); ?>
</div>
</code>```

So I have tried the same approach and tried the following things o try and bring the image in as a background image:

```<code>.featured-image {
  max-width: 960px;
  /* actual img width */
  max-height: 150px;
  /* actual img height */*
  height: 150px;
  /* actual img height - IE7 */
  background-image: <?php the_post_thumbnail(); ?>;
  background-size: cover;
  background-position: center;
}
</code>```

and using this:

```<code>background-image: url(<?php the_post_thumbnail(); ?>);
</code>```

Alas, I cant seem to get it to work - Im not even sure I can use PHP inside a CSS document...

So I'm looking for a way to achieve this image resize just on the following class without using a background image...

```<code><div class="featured-image">
   <?php the_post_thumbnail(); ?>
</div>
</code>```

Any help would be massively appreciated - I don't even know if I'm thinking about it correctly or I'm missing something - Thanks!

Example of what I'm trying to achieve here:

答:
To create the desired effect, they gave a padding-top property to the background-image wrapper class. And restricted the image to a max-height so, it doesn't grow bigger than that. Rest was all CSS.

As you wanted it to be dynamic image, now you can change the style tag value using your backend code

.section {
  position: relative;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  max-height: 150px;
  /* restricted image height */
}

.section:before {
  content: '';
  display: block;
  width: 100%;
  padding-top: 33.333%;
  /* this is not as per formula, but as a custom aspect ratio */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="section" style="background-image: url('http://fofwebdesign.co.uk/template/_testing/scale-img/students.jpg')">

</div>

<h1>When you want to keep the aspect ratio in background images use below formula</h1>
<code>((image height * 100%) / image width)</code></code>```

Body:
Im trying to achieve the effect shown on this site:

http://fofwebdesign.co.uk/template/_testing/scale-img/target-ratio-resize.htm

BUT this site does it using a background image for a div. I cannot use the background image as the image is inside Wordpress and it's being brought in dynamically using the following code:

   <?php the_post_thumbnail(); ?>

So I have tried the same approach and tried the following things o try and bring the image in as a background image:

.featured-image {
  max-width: 960px;
  /* actual img width */
  max-height: 150px;
  /* actual img height */*
  height: 150px;
  /* actual img height - IE7 */
  background-image: <?php the_post_thumbnail(); ?>;
  background-size: cover;
  background-position: center;
}

and using this:

background-image: url(<?php the_post_thumbnail(); ?>);

Alas, I cant seem to get it to work - Im not even sure I can use PHP inside a CSS document...

So I'm looking for a way to achieve this image resize just on the following class without using a background image...

   <?php the_post_thumbnail(); ?>

Any help would be massively appreciated - I don't even know if I'm thinking about it correctly or I'm missing something - Thanks!

Example of what I'm trying to achieve here:

Body:
To create the desired effect, they gave a padding-top property to the background-image wrapper class. And restricted the image to a max-height so, it doesn't grow bigger than that. Rest was all CSS.

As you wanted it to be dynamic image, now you can change the style tag value using your backend code

.section {
  position: relative;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  max-height: 150px;
  /* restricted image height */
}

.section:before {
  content: '';
  display: block;
  width: 100%;
  padding-top: 33.333%;
  /* this is not as per formula, but as a custom aspect ratio */
}

<div class="section" style="background-image: url('http://fofwebdesign.co.uk/template/_testing/scale-img/students.jpg')">

</div>

<h1>When you want to keep the aspect ratio in background images use below formula</h1>
<code>((image height * 100%) / image width)</code>


问:
How to log values which raised KeyError
Given this DataFrame, df:

```<code>     Player 1    Player 2
0    Thiem D.  Almagro N.
1  Almagro N.   Ferrer D.
2    Nadal R.    Thiem D.
</code>```

and mapping d:

```<code>d = {
    'Thiem D.': 'Dominic Thiem',
    'Nadal R.': 'Rafael Nadal',
    'Ferrer D.': 'David Ferrer',
}
</code>```

I want to rename player names and while doing so I want to keep track of elements not existing in the mapping (save to a file, or just print).

The first part of the assingment I can achieve with this line:

```<code>player_columns = ['Player 1', 'Player 2']
df[player_columns] = df[player_columns].applymap(lambda x: d.get(x, x))
</code>```

Which results in:

```<code>        Player 1       Player 2
0  Dominic Thiem     Almagro N.
1     Almagro N.   David Ferrer
2   Rafael Nadal  Dominic Thiem
</code>```

Almagro N. is not existing entry in the mapping hence why it could not be renamed. And I would like to capture this name.

I am aware I can subclass UserDict object and implement this behavoir there but I am curious if there is other way about doing it?

答:
You could try to split up your operation into multiple operations.

First you can do the mapping

```<code>df.applymap(d.get)

        Player 1       Player 2
0  Dominic Thiem           None
1           None   David Ferrer
2   Rafael Nadal  Dominic Thiem
</code>```

This gives you the players that cannot be mapped as None

Now you can check for the Nones

```<code>df[df.applymap(d.get).isnull()]

     Player 1    Player 2
0         NaN  Almagro N.
1  Almagro N.         NaN
2         NaN         NaN
</code>```

If you want these as a list of names that count not be mapped, you can simply do

```<code>unmappables = df[df.applymap(d.get).isnull()]
player1s = unmappables['Player 1'].values.tolist()
player2s = unmappables['Player 2'].values.tolist()
pd.Series((player1s + player2s)).dropna().unique()
</code>```

Gives

```<code>array(['Almagro N.'], dtype=object)
</code>```

Title: How to log values which raised KeyError

Body:
Given this DataFrame, df:

     Player 1    Player 2
0    Thiem D.  Almagro N.
1  Almagro N.   Ferrer D.
2    Nadal R.    Thiem D.

and mapping d:

d = {
    'Thiem D.': 'Dominic Thiem',
    'Nadal R.': 'Rafael Nadal',
    'Ferrer D.': 'David Ferrer',
}

I want to rename player names and while doing so I want to keep track of elements not existing in the mapping (save to a file, or just print).

The first part of the assingment I can achieve with this line:

player_columns = ['Player 1', 'Player 2']
df[player_columns] = df[player_columns].applymap(lambda x: d.get(x, x))

Which results in:

        Player 1       Player 2
0  Dominic Thiem     Almagro N.
1     Almagro N.   David Ferrer
2   Rafael Nadal  Dominic Thiem

Almagro N. is not existing entry in the mapping hence why it could not be renamed. And I would like to capture this name.

I am aware I can subclass UserDict object and implement this behavoir there but I am curious if there is other way about doing it?

Body:
You could try to split up your operation into multiple operations.

First you can do the mapping

df.applymap(d.get)

        Player 1       Player 2
0  Dominic Thiem           None
1           None   David Ferrer
2   Rafael Nadal  Dominic Thiem

This gives you the players that cannot be mapped as None

Now you can check for the Nones

df[df.applymap(d.get).isnull()]

     Player 1    Player 2
0         NaN  Almagro N.
1  Almagro N.         NaN
2         NaN         NaN

If you want these as a list of names that count not be mapped, you can simply do

unmappables = df[df.applymap(d.get).isnull()]
player1s = unmappables['Player 1'].values.tolist()
player2s = unmappables['Player 2'].values.tolist()
pd.Series((player1s + player2s)).dropna().unique()

Gives

array(['Almagro N.'], dtype=object)


答:
Probably you want to design better your code, like accepting an argument in the function to switch among different cases or having total separate functions.

A workaround is declaring both functions before the the if block, and the assign the function you need to a constant and call that constant where you need it:

```<code>function doSomething1() {
  alert("Yo!");
}

function doSomething2() {
  alert("Hi!");
}

const doSomething;

if (condition) {
  doSomething = doSomething1
} else {
  doSomething = doSomething2
}

doSomething()
</code>```

But again, that is not a good pattern, nor a well studied code

Title: How to declare different functions in different conditions?

Body:
Probably you want to design better your code, like accepting an argument in the function to switch among different cases or having total separate functions.

A workaround is declaring both functions before the the if block, and the assign the function you need to a constant and call that constant where you need it:

function doSomething1() {
  alert("Yo!");
}

function doSomething2() {
  alert("Hi!");
}

const doSomething;

if (condition) {
  doSomething = doSomething1
} else {
  doSomething = doSomething2
}

doSomething()

But again, that is not a good pattern, nor a well studied code


问:
How can I provide SBT credentials to my private Artifactory server from a Windows workstation?
I'm using sbt 0.13.13 behind a corporate firewall on a Windows desktop.

We have an Artifactory which seems to be working very well for other build-tools, but I also want to get SBT working, however I'm not even able to make sbt 0.13.x boot!

When I try to boot SBT I get this error from the launcher:

```<code>C:\workspace\aggregator2>c:\apps\sbt-0.13.13\sbt-launcher-packaging-0.13.13\bin\sbt
Getting org.scala-sbt sbt 0.13.13 ...

:: problems summary ::
:::: WARNINGS
                module not found: org.scala-sbt#sbt;0.13.13

        ==== local: tried

          C:\Users\USERNAME\.ivy2\local\org.scala-sbt\sbt\0.13.13\ivys\ivy.xml

          -- artifact org.scala-sbt#sbt;0.13.13!sbt.jar:

          C:\Users\USERNAME\.ivy2\local\org.scala-sbt\sbt\0.13.13\jars\sbt.jar

        ==== my-ivy-proxy-releases: tried

          http://artifactory.bigcompany.com:8081/artifactory/virtual-sbt/org.scala-sbt/sbt/0.13.13/ivys/ivy.xml

        ==== my-maven-proxy-releases: tried

          http://artifactory.bigcompany.com:8081/artifactory/virtual-sbt/org/scala-sbt/sbt/0.13.13/sbt-0.13.13.pom

          -- artifact org.scala-sbt#sbt;0.13.13!sbt.jar:

          http://artifactory.bigcompany.com:8081/artifactory/virtual-sbt/org/scala-sbt/sbt/0.13.13/sbt-0.13.13.jar

                ::::::::::::::::::::::::::::::::::::::::::::::

                ::          UNRESOLVED DEPENDENCIES         ::

                ::::::::::::::::::::::::::::::::::::::::::::::

                :: org.scala-sbt#sbt;0.13.13: not found

                ::::::::::::::::::::::::::::::::::::::::::::::
</code>```

Actually those URLs do exist - when I hit them with Chrome or Curl and provide credentials I am able to retrieve all the required resources.

When I look at the log I can see what's going on:

```<code>try to get credentials for: Artifactory Realm@artifactory.bigcompany.com
authentication: k='Artifactory Realm@artifactory.bigcompany.com' c='null'
HTTP response status: 401 url=http://artifactory.bigcompany.com:8081/artifactory/virtual-sbt/org.scala-sbt/sbt/0.13.13/ivys/ivy.xml
CLIENT ERROR: Unauthorized url=http://artifactory.bigcompany.com:8081/artifactory/virtual-sbt/org.scala-sbt/sbt/0.13.13/ivys/ivy.xml
    my-ivy-proxy-releases: resource not reachable for org.scala-sbt#sbt;0.13.13: res=http://artifactory.bigcompany.com:8081/artifactory/virtual-sbt/org.scala-sbt/sbt/0.13.13/ivys/ivy.xml
    my-ivy-proxy-releases: no ivy file found for org.scala-sbt#sbt;0.13.13
</code>```

So it's clear that no credentials (or the wrong credentials are being sent). So I looked at how I've got it set up. I have a credentials file which looks something like this in %USERPROFILE%/.sbt/.credentials

```<code>realm=Artifactory Realm
host=artifactory.bigcompany.com
user=USERNAME
password=<my api key>
</code>```

And I have a "plugin" file located at %USERPROFILE%.sbt\0.13\plugins\credentials.sbt which looks like this:

```<code>credentials += Credentials(Path.userHome / ".sbt" / ".credentials")
</code>```

And I'm invoking sbt like this:

```<code>c:\apps\sbt-0.13.13\sbt-launcher-packaging-0.13.13\bin\sbt
</code>```

Looking again at the logs - there's nothing at all which suggests that the credentials.sbt plugin has loaded, which in turn suggests that I've put the file in the wrong location or that there's something else about it that makes it unusable.

So can somebody help me - how do I need to tweak this setup so that it actually works? Is there some missing

答:
I think I've encountered the same problem.

Since you've already created a proper credential file under %USERPROFILE%/.sbt/.credentials, you might need to set a system or user environment variable:

set SBT_CREDENTIALS=%USERPROFILE%/.sbt/.credentials

Body:
I'm using sbt 0.13.13 behind a corporate firewall on a Windows desktop.

We have an Artifactory which seems to be working very well for other build-tools, but I also want to get SBT working, however I'm not even able to make sbt 0.13.x boot!

When I try to boot SBT I get this error from the launcher:

C:\workspace\aggregator2>c:\apps\sbt-0.13.13\sbt-launcher-packaging-0.13.13\bin\sbt
Getting org.scala-sbt sbt 0.13.13 ...

:: problems summary ::
:::: WARNINGS
                module not found: org.scala-sbt#sbt;0.13.13

        ==== local: tried

          C:\Users\USERNAME\.ivy2\local\org.scala-sbt\sbt\0.13.13\ivys\ivy.xml

          -- artifact org.scala-sbt#sbt;0.13.13!sbt.jar:

          C:\Users\USERNAME\.ivy2\local\org.scala-sbt\sbt\0.13.13\jars\sbt.jar

        ==== my-ivy-proxy-releases: tried

          http://artifactory.bigcompany.com:8081/artifactory/virtual-sbt/org.scala-sbt/sbt/0.13.13/ivys/ivy.xml

        ==== my-maven-proxy-releases: tried

          http://artifactory.bigcompany.com:8081/artifactory/virtual-sbt/org/scala-sbt/sbt/0.13.13/sbt-0.13.13.pom

          -- artifact org.scala-sbt#sbt;0.13.13!sbt.jar:

          http://artifactory.bigcompany.com:8081/artifactory/virtual-sbt/org/scala-sbt/sbt/0.13.13/sbt-0.13.13.jar

                ::::::::::::::::::::::::::::::::::::::::::::::

                ::          UNRESOLVED DEPENDENCIES         ::

                ::::::::::::::::::::::::::::::::::::::::::::::

                :: org.scala-sbt#sbt;0.13.13: not found

                ::::::::::::::::::::::::::::::::::::::::::::::

Actually those URLs do exist - when I hit them with Chrome or Curl and provide credentials I am able to retrieve all the required resources.

When I look at the log I can see what's going on:

try to get credentials for: Artifactory Realm@artifactory.bigcompany.com
authentication: k='Artifactory Realm@artifactory.bigcompany.com' c='null'
HTTP response status: 401 url=http://artifactory.bigcompany.com:8081/artifactory/virtual-sbt/org.scala-sbt/sbt/0.13.13/ivys/ivy.xml
CLIENT ERROR: Unauthorized url=http://artifactory.bigcompany.com:8081/artifactory/virtual-sbt/org.scala-sbt/sbt/0.13.13/ivys/ivy.xml
    my-ivy-proxy-releases: resource not reachable for org.scala-sbt#sbt;0.13.13: res=http://artifactory.bigcompany.com:8081/artifactory/virtual-sbt/org.scala-sbt/sbt/0.13.13/ivys/ivy.xml
    my-ivy-proxy-releases: no ivy file found for org.scala-sbt#sbt;0.13.13

So it's clear that no credentials (or the wrong credentials are being sent). So I looked at how I've got it set up. I have a credentials file which looks something like this in %USERPROFILE%/.sbt/.credentials

realm=Artifactory Realm
host=artifactory.bigcompany.com
user=USERNAME
password=<my api key>

And I have a "plugin" file located at %USERPROFILE%.sbt\0.13\plugins\credentials.sbt which looks like this:

credentials += Credentials(Path.userHome / ".sbt" / ".credentials")

And I'm invoking sbt like this:

c:\apps\sbt-0.13.13\sbt-launcher-packaging-0.13.13\bin\sbt

Looking again at the logs - there's nothing at all which suggests that the credentials.sbt plugin has loaded, which in turn suggests that I've put the file in the wrong location or that there's something else about it that makes it unusable.

So can somebody help me - how do I need to tweak this setup so that it actually works? Is there some missing


问:
Why can't I use the same Icon for more than 1 item in Menu?
I have a MenuItem like below

```<code><MenuItem Header="Edit">
    <MenuItem Header="Copy Direct Link" Icon="{StaticResource CopyIcon}" Command="{Binding CopyImageCommand}" />
    <MenuItem Header="Copy Image Data" Icon="{StaticResource CopyIcon}" Command="{Binding CopyImageDataCommand}" />
    <MenuItem Header="Paste" Icon="{StaticResource PasteIcon}" Command="{Binding PasteImageCommand}" />
</MenuItem>
</code>```

Notice the 1st 2 items use the same icon, I get something like below

I tried removing the 2nd item,

```<code><MenuItem Header="Edit">
    <MenuItem Header="Copy Direct Link" InputGestureText="Ctrl+C" Icon="{StaticResource CopyIcon}" Command="{Binding CopyImageCommand}" />
    <!--<MenuItem Header="Copy Image Data" InputGestureText="Ctrl+Alt+C" Icon="{StaticResource CopyIcon}" Command="{Binding CopyImageDataCommand}" />-->
    <MenuItem Header="Paste" InputGestureText="Ctrl+P" Icon="{StaticResource PasteIcon}" Command="{Binding PasteImageCommand}" />
</MenuItem>
</code>```

then I got something like

How can I reuse Icons?

答:
You're most likely declaring CopyIcon as Image type in your resource, something like this:

```<code><Window.Resources>
  <Image x:Key="CopyIcon" Source="yourcopyicon.ico"/>
</Window.Resources>
</code>```

So, the root cause of the problem is, Image is a visual element, since it derives from FrameworkElement (which is a visual element), and a visual element cannot have more than one parent at the same time. That is why the first MenuItem is not showing the icon, since the second MenuItem reset the parent of CopyIcon, making itself parent of the CopyIcon.

Hope this explanation is helpful to you. Now follow what Meleak has said in his response. :-)

Body:
I have a MenuItem like below

<MenuItem Header="Edit">
    <MenuItem Header="Copy Direct Link" Icon="{StaticResource CopyIcon}" Command="{Binding CopyImageCommand}" />
    <MenuItem Header="Copy Image Data" Icon="{StaticResource CopyIcon}" Command="{Binding CopyImageDataCommand}" />
    <MenuItem Header="Paste" Icon="{StaticResource PasteIcon}" Command="{Binding PasteImageCommand}" />
</MenuItem>

Notice the 1st 2 items use the same icon, I get something like below

I tried removing the 2nd item,

<MenuItem Header="Edit">
    <MenuItem Header="Copy Direct Link" InputGestureText="Ctrl+C" Icon="{StaticResource CopyIcon}" Command="{Binding CopyImageCommand}" />

    <MenuItem Header="Paste" InputGestureText="Ctrl+P" Icon="{StaticResource PasteIcon}" Command="{Binding PasteImageCommand}" />
</MenuItem>

then I got something like

How can I reuse Icons?

Body:
You're most likely declaring CopyIcon as Image type in your resource, something like this:

<Window.Resources>
  <Image x:Key="CopyIcon" Source="yourcopyicon.ico"/>
</Window.Resources>

So, the root cause of the problem is, Image is a visual element, since it derives from FrameworkElement (which is a visual element), and a visual element cannot have more than one parent at the same time. That is why the first MenuItem is not showing the icon, since the second MenuItem reset the parent of CopyIcon, making itself parent of the CopyIcon.

Hope this explanation is helpful to you. Now follow what Meleak has said in his response. :-)


问:
MYSQL Query : get date which was entered on same name of day
I have a bunch of data that contain date and some numbers. The table looks like this.

```<code>ID  |   date                   |   amount  |
--------------------------------------------
1   |   2017-01-01 00:00:00    |   100     |
2   |   2017-02-04 00:00:00    |   5       |
3   |   2017-03-11 00:00:00    |   100     |
4   |   2017-04-14 00:00:00    |   20      |
5   |   2017-05-07 00:00:00    |   5       |
</code>```

So let's say today is monday. What I have to do is get data from table which 'date' is monday, same as today.
I would like to know is there any way do this just using sql query.

答:
```<code>select * from table_name
where DAYNAME(`date`) =DAYNAME(CURRENT_DATE);
</code>```

Body:
I have a bunch of data that contain date and some numbers. The table looks like this.

ID  |   date                   |   amount  |
--------------------------------------------
1   |   2017-01-01 00:00:00    |   100     |
2   |   2017-02-04 00:00:00    |   5       |
3   |   2017-03-11 00:00:00    |   100     |
4   |   2017-04-14 00:00:00    |   20      |
5   |   2017-05-07 00:00:00    |   5       |

So let's say today is monday. What I have to do is get data from table which 'date' is monday, same as today.
I would like to know is there any way do this just using sql query.


问:
How to convert a specific string to integer?
Hi here is the scenario that I have strings like this;

```<code>$a="08";
$b="00";
$c="0";
</code>```

actually this is time part of a datetime i want to get these as integer

答:
You can simply typecast them like so:

```<code>$a=(int)"08";
$b=(int)"00";
$c=(int)"0";
</code>```

As suggested by @Stan Winiecki
An explicit typecast may help you go for:

```<code> $seconds = (int)$a * 3600
</code>```

Body:
Hi here is the scenario that I have strings like this;

$a="08";
$b="00";
$c="0";

actually this is time part of a datetime i want to get these as integer

Body:
You can simply typecast them like so:

$a=(int)"08";
$b=(int)"00";
$c=(int)"0";

As suggested by @Stan Winiecki
An explicit typecast may help you go for:

 $seconds = (int)$a * 3600


问:
Can't print the pattern
I created the code that should print a pattern like

```<code>12345
 2345
  345
   45
    5
</code>```

I have the code written below, the logic works fine in python but in java the output is different.

```<code>class Testing{
    public static void main(String args[])
    {
        for (int i = 1; i<6;i++)
        {

            for (int j =0; j<i-1;j++)
                {
                System.out.print(" ");
                }
                while (i < 6){
                    System.out.print(k);
                    System.out.println();
                    i++;
                }
        }
    }
}
</code>```

The output is just 12345. I don't understand why does it iterate over first for loop for only once.

答:
Following is a java-8 implementation of the problem:

```<code>IntStream.rangeClosed(1, MAX)
            .forEach(i -> IntStream.rangeClosed(1, MAX)
                    .mapToObj(j -> j == MAX ? j + "\n" : j >= i ? j : " ")
                    .forEach(System.out::print)
            );
</code>```

Set MAX = 5 and it will print your pattern.

Output:

```<code>12345
 2345
  345
   45
    5
</code>```

Title: Can't print the pattern

Body:
I created the code that should print a pattern like

12345
 2345
  345
   45
    5

I have the code written below, the logic works fine in python but in java the output is different.

class Testing{
    public static void main(String args[])
    {
        for (int i = 1; i<6;i++)
        {

            for (int j =0; j<i-1;j++)
                {
                System.out.print(" ");
                }
                while (i < 6){
                    System.out.print(k);
                    System.out.println();
                    i++;
                }
        }
    }
}

The output is just 12345. I don't understand why does it iterate over first for loop for only once.

Body:
Following is a java-8 implementation of the problem:

IntStream.rangeClosed(1, MAX)
            .forEach(i -> IntStream.rangeClosed(1, MAX)
                    .mapToObj(j -> j == MAX ? j + "\n" : j >= i ? j : " ")
                    .forEach(System.out::print)
            );

Set MAX = 5 and it will print your pattern.

Output:

12345
 2345
  345
   45
    5


问:
Notifying all properties of the viewmodel has changed with null or string empty
I'm coming from developing WPF solutions where to update all properties of the viewmodel was as simple as:

```<code>OnPropertyChanged(String.Empty);
</code>```

In the Universal Windows Platform scenario, I just have the same method to update/refresh the properties. This works fine in most of cases but sometimes it raise an error something like this:

COMException Error HRESULT E_FAIL has been returned from a call to a COM component.     at System.ComponentModel.PropertyChangedEventHandler.Invoke(Object sender, PropertyChangedEventArgs e)     at GeekyTool.Base.BindableBase.OnPropertyChanged(String propertyName)     at Pooo.set_Root(UserRoot value)     at Booo.d__26.MoveNext()  --- End of stack trace from previous location where exception was thrown ---     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)     at GeekyTool.Base.PageBase.d__1.MoveNext()  --- End of stack trace from previous location where exception was thrown ---     at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.b__6_0(Object state)     at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()

The OnPropertyChanged method with an INotifyPropertyChanged interface implementation look like this:

```<code>public abstract class BindableBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    public virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public virtual bool Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
    {
        if (object.Equals(storage, value))
            return false;
        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }
}
</code>```

You can explore the mvvm library, but nothing different on the INotifyPropertyChanged implementation.

GeekyTool Library on Github

答:
Thank's for all the answers, I was trying to fix an error that it isn't was there.

In the OnPropertyChanged(string.Empty) method raise the error because it comes with an sync context issue from the page before.

It happens when you are navigating between two page very fast and has some async calls in the OnNavigatedTo method where they aren't finished yet. The async method are awaited, but in this page was not handled that the user wait until this is finished.

Just to know that no need to apply @PedroLamas fix. Ensuring on the page before that all async calls are finished it's done.

Body:
I'm coming from developing WPF solutions where to update all properties of the viewmodel was as simple as:

OnPropertyChanged(String.Empty);

In the Universal Windows Platform scenario, I just have the same method to update/refresh the properties. This works fine in most of cases but sometimes it raise an error something like this:

COMException Error HRESULT E_FAIL has been returned from a call to a COM component.     at System.ComponentModel.PropertyChangedEventHandler.Invoke(Object sender, PropertyChangedEventArgs e)     at GeekyTool.Base.BindableBase.OnPropertyChanged(String propertyName)     at Pooo.set_Root(UserRoot value)     at Booo.d__26.MoveNext()  --- End of stack trace from previous location where exception was thrown ---     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)     at GeekyTool.Base.PageBase.d__1.MoveNext()  --- End of stack trace from previous location where exception was thrown ---     at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.b__6_0(Object state)     at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()

The OnPropertyChanged method with an INotifyPropertyChanged interface implementation look like this:

public abstract class BindableBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    public virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public virtual bool Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
    {
        if (object.Equals(storage, value))
            return false;
        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }
}

You can explore the mvvm library, but nothing different on the INotifyPropertyChanged implementation.

GeekyTool Library on Github


答:
You do not need to do this because PHP will handle it by itself.
If you want to explicitly convert it you can use</p>

```<code>$int = (int)$a;
</code>```

Title: How to convert a specific string to integer?

Body:
You do not need to do this because PHP will handle it by itself.
If you want to explicitly convert it you can use

$int = (int)$a;


问:
send PHP code in database
I am trying to post php code from my messages table. But it is not posting. For example:

```<code><textarea name="update">User can write php codes here for sending</textarea>
<div class="send">Send</div>
</code>```

When i click send button the text code <?php echo $message;?> must be in my messages table row post_text . But post_text is empty, you can see it in the screenshot.

What is the problem here. What i shoud do to fix this problem? Anyone can help me here ?

```<code><?php
include_once '../inc/inc.php';
if(isset($_POST['update'])) {

   $update=mysqli_real_escape_string($db,$_POST['update']);
   if($update){
      $data=$DoDo->InsertText($uid,$update);
      echo $update;
   }
}
?>
</code>```

InsertText function

```<code>public function InsertText($uid, $update) {

    $time=time();
    $ip=$_SERVER['REMOTE_ADDR'];
    mysqli_query($this->db,"SET character_set_client=utf8") or die(mysqli_error($this->db));
    mysqli_query($this->db,"SET character_set_connection=utf8") or die(mysqli_error($this->db));

    $query = mysqli_query($this->db,"SELECT post_id,post_text FROM `posts` WHERE uid_fk='$uid' order by post_id desc limit 1") or die(mysqli_error($this->db));
    $result = mysqli_fetch_array($query, MYSQLI_ASSOC);

     $query = mysqli_query($this->db,"INSERT INTO `posts` (post_text, uid_fk,time) VALUES (N'$update', '$uid','$time')") or die(mysqli_error($this->db));

     //The newquery to select for message
     $newquery = mysqli_query($this->db,"SELECT M.post_id, M.uid_fk, M.post_text, M.time,U.username FROM posts M, users U where M.uid_fk=U.uid and M.uid_fk='$uid' order by M.post_id desc limit 1 ") or die(mysqli_error($this->db));
     $result = mysqli_fetch_array($newquery, MYSQLI_ASSOC);
     return $result;
}
</code>```

Note: This problem will be come when i send just php code. If i send
  normal text then normal text sending from post_text.

I want to send php code like this screenshot.

答:
wait, you literally want the string '<?php echo $message;?>' to be inserted, not the value of $message ?

if that is the case, you need to either make sure that PHP sees it as a string:

```<code><textarea name="update"><?php echo '<?php echo $message;?>';?></textarea>
</code>```

... or maybe it would be enough to post only the code, not the php tags

```<code><textarea name="update">echo $message;</textarea>
</code>```

Title: send PHP code in database

Body:
I am trying to post php code from my messages table. But it is not posting. For example:

<textarea name="update">User can write php codes here for sending</textarea>

Send

When i click send button the text code <?php echo $message;?> must be in my messages table row post_text . But post_text is empty, you can see it in the screenshot.

What is the problem here. What i shoud do to fix this problem? Anyone can help me here ?

<?php
include_once '../inc/inc.php';
if(isset($_POST['update'])) {

   $update=mysqli_real_escape_string($db,$_POST['update']);
   if($update){
      $data=$DoDo->InsertText($uid,$update);
      echo $update;
   }
}
?>

InsertText function

public function InsertText($uid, $update) {

    $time=time();
    $ip=$_SERVER['REMOTE_ADDR'];
    mysqli_query($this->db,"SET character_set_client=utf8") or die(mysqli_error($this->db));
    mysqli_query($this->db,"SET character_set_connection=utf8") or die(mysqli_error($this->db));

    $query = mysqli_query($this->db,"SELECT post_id,post_text FROM `posts` WHERE uid_fk='$uid' order by post_id desc limit 1") or die(mysqli_error($this->db));
    $result = mysqli_fetch_array($query, MYSQLI_ASSOC);

     $query = mysqli_query($this->db,"INSERT INTO `posts` (post_text, uid_fk,time) VALUES (N'$update', '$uid','$time')") or die(mysqli_error($this->db));

     //The newquery to select for message
     $newquery = mysqli_query($this->db,"SELECT M.post_id, M.uid_fk, M.post_text, M.time,U.username FROM posts M, users U where M.uid_fk=U.uid and M.uid_fk='$uid' order by M.post_id desc limit 1 ") or die(mysqli_error($this->db));
     $result = mysqli_fetch_array($newquery, MYSQLI_ASSOC);
     return $result;
}

Note: This problem will be come when i send just php code. If i send
  normal text then normal text sending from post_text.

I want to send php code like this screenshot.

Body:
wait, you literally want the string '<?php echo $message;?>' to be inserted, not the value of $message ?

if that is the case, you need to either make sure that PHP sees it as a string:

<textarea name="update"><?php echo '<?php echo $message;?>';?></textarea>

... or maybe it would be enough to post only the code, not the php tags

<textarea name="update">echo $message;</textarea>


问:
python regex of a date in some text
How can I find as many date patterns as possible from a text file by python? The date pattern is defined as:

```<code>dd mmm yyyy
  ^   ^
  |   |
  +---+--- spaces
</code>```

where:

dd is a two digit number

mmm is three-character English month name (e.g. Jan, Mar, Dec)

yyyy is four digit year

there are two spaces as separators

Thanks!

答:
or you can use this for completelly</p>

```<code>date = re.findall(r'\d\d\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}', text)
print date
['30 November 2010 14:20', '30 November 2010 14:24']
</code>```

Title: python regex of a date in some text

Body:
How can I find as many date patterns as possible from a text file by python? The date pattern is defined as:

dd mmm yyyy
  ^   ^
  |   |
  +---+--- spaces

where:

dd is a two digit number

mmm is three-character English month name (e.g. Jan, Mar, Dec)

yyyy is four digit year

there are two spaces as separators

Thanks!

Body:
or you can use this for completelly

date = re.findall(r'\d\d\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}', text)
print date
['30 November 2010 14:20', '30 November 2010 14:24']


问:
Race condition in Producer-Consumer: limit notifications to when condition variable is waiting
I've implemented a simple Producer-Consumer message queue.

```<code>#include <chrono>
#include <iostream>
#include <thread>
#include <mutex>
#include <deque>

#define MESSAGE_QUIT 1

struct MessageQueue
{
    std::deque<int> message_ids;
    std::mutex mutex;
    std::condition_variable condition_variable;
};

void SleepFor(int time_in_millis)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(time_in_millis));
}

void ProcessMessage(int message_id)
{
    std::cout << "Processing Message #" << message_id << '\n';
}

void Producer(MessageQueue *messages)
{
    for (int message_id = 10; message_id >= MESSAGE_QUIT; --message_id) {
        std::unique_lock<std::mutex> guard(messages->mutex);
        messages->message_ids.push_back(message_id);
        guard.unlock();
        messages->condition_variable.notify_one();
        SleepFor(200);
    }
}

void Consumer(MessageQueue *messages)
{
    int next_message_id = -1;

    while (next_message_id != MESSAGE_QUIT) {
        std::unique_lock<std::mutex> guard(messages->mutex);
        messages->condition_variable.wait(guard);
        next_message_id = messages->message_ids.front();
        messages->message_ids.pop_front();
        guard.unlock();
        ProcessMessage(next_message_id);
    }
}

int main()
{
    MessageQueue messages;

    std::thread producer_thread(&Producer, &messages);
    std::thread consumer_thread(&Consumer, &messages);

    producer_thread.join();
    consumer_thread.join();
}
</code>```

The race condition: in some cases, the condition variable is calling notify_one() in the producer thread while it is not in the waiting state in the consumer thread. How would you solve this? I am not considering the case of spurious waking for now.

答:
Condition variables can spuriously wake up.

```<code>messages->condition_variable.wait(guard)
</code>```

So don't do this.  There are other reasons to not do this, including the fact that you can wait on a condition variable when there is data ready.

```<code>messages->condition_variable.wait(guard, [&]{return !messages->message_ids().empty();)
</code>```

This won't wait if there are already messages in the queue.  It also deals with spurious wakeups.

Body:
I've implemented a simple Producer-Consumer message queue.

#include <chrono>
#include <iostream>
#include <thread>
#include <mutex>
#include <deque>

#define MESSAGE_QUIT 1

struct MessageQueue
{
    std::deque<int> message_ids;
    std::mutex mutex;
    std::condition_variable condition_variable;
};

void SleepFor(int time_in_millis)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(time_in_millis));
}

void ProcessMessage(int message_id)
{
    std::cout << "Processing Message #" << message_id << '\n';
}

void Producer(MessageQueue *messages)
{
    for (int message_id = 10; message_id >= MESSAGE_QUIT; --message_id) {
        std::unique_lock<std::mutex> guard(messages->mutex);
        messages->message_ids.push_back(message_id);
        guard.unlock();
        messages->condition_variable.notify_one();
        SleepFor(200);
    }
}

void Consumer(MessageQueue *messages)
{
    int next_message_id = -1;

    while (next_message_id != MESSAGE_QUIT) {
        std::unique_lock<std::mutex> guard(messages->mutex);
        messages->condition_variable.wait(guard);
        next_message_id = messages->message_ids.front();
        messages->message_ids.pop_front();
        guard.unlock();
        ProcessMessage(next_message_id);
    }
}

int main()
{
    MessageQueue messages;

    std::thread producer_thread(&Producer, &messages);
    std::thread consumer_thread(&Consumer, &messages);

    producer_thread.join();
    consumer_thread.join();
}

The race condition: in some cases, the condition variable is calling notify_one() in the producer thread while it is not in the waiting state in the consumer thread. How would you solve this? I am not considering the case of spurious waking for now.

Body:
Condition variables can spuriously wake up.

messages->condition_variable.wait(guard)

So don't do this.  There are other reasons to not do this, including the fact that you can wait on a condition variable when there is data ready.

messages->condition_variable.wait(guard, [&]{return !messages->message_ids().empty();)

This won't wait if there are already messages in the queue.  It also deals with spurious wakeups.


问:
Adding non-osgi jars to RCP4 project
I have the following situation.  I rely on a 3rd party jar called foo.jar.  That jar has many non-osgi dependencies.  I created a new project "Plug-in from existing JAR archives", selected all of foo.jars non-osgi dependencies and exported it as a "deployable plugin and fragment" called foo.libs.jar.

My RCP4 project is a a feature-based product. In my main RCP project I go to the target file, navigate to the Content tab and checkmark foo.jar and foo.libs.jar.  I then go to my project file and select "validate" and receive the message "No problems were detected".

Any clue what I'm doing wrong or need to be doing to get this to work? Do I have to explicitly set foo.libs.jar as a dependency of foo.jar?  I've tried to do that in my main projects manifest->dependency tab and the runConfigurations->Plug-ins, and added foo.libs.jar to the feature.xmls->Included plug-ins tab but it didn't seem to work.

Thanks!

===UPDATE===

I think my issue may fall into the case of bundle fragments and embedded dependencies.  As an example:

```<code>- I create foo.libs.jar. One of the jars inside it is activemq.jar
  I need access to javax.jms.ExceptionListener
- The manifest for foo.libs.jar contains activemq.jar in the
  Bundle-ClassPath, and javax.jms in the Export-Package sections
- foo.jar contains foo.libs.jar in its Class-Path. It contains
  javax.jms in its Import-Package and Export-Package sections
- I created a "Plug-in from existing JAR archives" project which has
  foo.jar and foo.libs.jar in it.
- The manifest for the project has foo.jar and foo.libs.jar in the
  Bundle-Classpath section. The Import-Package section contains
  javax.jms
- If I export this bundle to my project, and run validate I get
  errors saying javax.jms cannot be found.
- If I omit the javax.jms from the bundles Import-Package there
  are no validation errors but I will get a ClassNotFoundException
</code>```

I kinda feel like this may be an issue with embedded jars and Bundle-ClassPaths...

My bundle has

```<code>Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: my.name
Bundle-SymbolicName: my.name
Bundle-Version: 1.0.0
Bundle-ClassPath: foo.jar
Export-Package: list_of_my_packages
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
</code>```

And foo.jar has

```<code>Manifest-Version: 1.0
Bnd-LastModified: 1489769501680
Bundle-ManifestVersion: 2
Bundle-Name: foo
Bundle-SymbolicName: foo
Bundle-Version: 1.0.0
Class-Path: foo.libs.jar
Created-By: 1.8.0_71 (Oracle Corporation)
Export-Package: javax.jms  (and other stuff, omitted)
Import-Package: javax.jms;resolution:=optional (and other stuff, omitted)
Require-Capability: osgi.ee;filter:="(&(osgi.ee=JavaSE)(version=1.8))"
Tool: Bnd-2.4.0.201411031536
</code>```

And foo.libs.jar has

```<code>Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Foo libs
Bundle-SymbolicName: foo.libs
Bundle-Version: 1.1.0
Bundle-ClassPath: activemq-all.jar, (and others which I ommitted)
Export-Package: javax.jms, (and others which I ommitted)
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
</code>```

答:
The question lacks details, but the issue with "no class found" is quite typical for OSGI.

Check the MANIFEST.MF of both of your bundles. foo.libs.jar must have a declaration of a package for your "missing" class in 'Export-Package' directive, while foo.jar must have same package in 'Import-Package'. Since you managed to reach to the point when you get an exception, it seems like you missing package declaration for some.class.in.a.jar.in.foo.libs.jar in 'Import-Package' of foo.jar.

Main rule is following: a bundle may access only the classes within itself + the ones, imported via manifest. There are exceptions like bundle fragments and embedded dependencies, but I believe we can omit them for this case.

Generally, problem is solved when you properly set both 'Import-' and 'Export-Package' directives in manifests of your bundles. If you need more detailed help, please provide more details about how you make foo.jar and foo.lib.jar (by hands, by maven plugin, by gradle, which settings you use etc.)

Title: Adding non-osgi jars to RCP4 project

Body:
I have the following situation.  I rely on a 3rd party jar called foo.jar.  That jar has many non-osgi dependencies.  I created a new project "Plug-in from existing JAR archives", selected all of foo.jars non-osgi dependencies and exported it as a "deployable plugin and fragment" called foo.libs.jar.

My RCP4 project is a a feature-based product. In my main RCP project I go to the target file, navigate to the Content tab and checkmark foo.jar and foo.libs.jar.  I then go to my project file and select "validate" and receive the message "No problems were detected".

Any clue what I'm doing wrong or need to be doing to get this to work? Do I have to explicitly set foo.libs.jar as a dependency of foo.jar?  I've tried to do that in my main projects manifest->dependency tab and the runConfigurations->Plug-ins, and added foo.libs.jar to the feature.xmls->Included plug-ins tab but it didn't seem to work.

Thanks!

===UPDATE===

I think my issue may fall into the case of bundle fragments and embedded dependencies.  As an example:

- I create foo.libs.jar. One of the jars inside it is activemq.jar
  I need access to javax.jms.ExceptionListener
- The manifest for foo.libs.jar contains activemq.jar in the
  Bundle-ClassPath, and javax.jms in the Export-Package sections
- foo.jar contains foo.libs.jar in its Class-Path. It contains
  javax.jms in its Import-Package and Export-Package sections
- I created a "Plug-in from existing JAR archives" project which has
  foo.jar and foo.libs.jar in it.
- The manifest for the project has foo.jar and foo.libs.jar in the
  Bundle-Classpath section. The Import-Package section contains
  javax.jms
- If I export this bundle to my project, and run validate I get
  errors saying javax.jms cannot be found.
- If I omit the javax.jms from the bundles Import-Package there
  are no validation errors but I will get a ClassNotFoundException

I kinda feel like this may be an issue with embedded jars and Bundle-ClassPaths...

My bundle has

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: my.name
Bundle-SymbolicName: my.name
Bundle-Version: 1.0.0
Bundle-ClassPath: foo.jar
Export-Package: list_of_my_packages
Bundle-RequiredExecutionEnvironment: JavaSE-1.8

And foo.jar has

Manifest-Version: 1.0
Bnd-LastModified: 1489769501680
Bundle-ManifestVersion: 2
Bundle-Name: foo
Bundle-SymbolicName: foo
Bundle-Version: 1.0.0
Class-Path: foo.libs.jar
Created-By: 1.8.0_71 (Oracle Corporation)
Export-Package: javax.jms  (and other stuff, omitted)
Import-Package: javax.jms;resolution:=optional (and other stuff, omitted)
Require-Capability: osgi.ee;filter:="(&(osgi.ee=JavaSE)(version=1.8))"
Tool: Bnd-2.4.0.201411031536

And foo.libs.jar has

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Foo libs
Bundle-SymbolicName: foo.libs
Bundle-Version: 1.1.0
Bundle-ClassPath: activemq-all.jar, (and others which I ommitted)
Export-Package: javax.jms, (and others which I ommitted)
Bundle-RequiredExecutionEnvironment: JavaSE-1.8


问:
Is it possible to Fit-to-page with Silverlight 4 Print API?
I have a silverlight control that prints to about 1.5 pages. I'd like to try and scale to fit onto a single page.

I'm using the new Printing API in Silverlight 4.

I've modified the docToPrint.PrintPage handler as follows :

```<code>    var renderHeight = item.RenderSize.Height;
    var printableHeight = args.PrintableArea.Height;

    var scale = printableHeight / renderHeight;

    item.RenderTransform = new ScaleTransform()
    {
        ScaleX = Math.Min(1, scale),    // dont zoom in
        ScaleY = Math.Min(1, scale)
    };

    item.UpdateLayout();
    args.PageVisual = item;
</code>```

This just calculates the transform needed to fit to page. In fact the on-screen rendered control shrinks accordingly - but it always prints out full size.

I know Shawn Wildermuth blogged about printing - and some of the comments at least suggest that transforms don't work for printing.

Is there a workaround for this yet? To be frank I don't actually need printing support - but was just adding it as a bonus feature - so I'll just have to split the page at an arbitrary point if i can't figure this out.

答:
Check solution on my blog:
Silverlight printing: fit to page.</p>

Body:
I have a silverlight control that prints to about 1.5 pages. I'd like to try and scale to fit onto a single page.

I'm using the new Printing API in Silverlight 4.

I've modified the docToPrint.PrintPage handler as follows :

    var renderHeight = item.RenderSize.Height;
    var printableHeight = args.PrintableArea.Height;

    var scale = printableHeight / renderHeight;

    item.RenderTransform = new ScaleTransform()
    {
        ScaleX = Math.Min(1, scale),    // dont zoom in
        ScaleY = Math.Min(1, scale)
    };

    item.UpdateLayout();
    args.PageVisual = item;

This just calculates the transform needed to fit to page. In fact the on-screen rendered control shrinks accordingly - but it always prints out full size.

I know Shawn Wildermuth blogged about printing - and some of the comments at least suggest that transforms don't work for printing.

Is there a workaround for this yet? To be frank I don't actually need printing support - but was just adding it as a bonus feature - so I'll just have to split the page at an arbitrary point if i can't figure this out.


问:
Apache Spark: Pre requisite questions
I am about to install Apache Spark 2.1.0 on Ubuntu 16.04 LTS. My goal is a standalone cluster, using Hadoop, with Scala and Python (2.7 is active)

Whilst downloading I get the choice: Prebuilt for Hadoop 2.7 and later (File is spark-2.1.0-bin-hadoop2.7.tgz)

Does this package actually include HADOOP 2.7 or does it need to be installed separately (first I assume)?

I have Java JRE 8 installed (Needed for other tasks). As the JDK 8 also seems to be a pre requisite as well, I also did a ' sudo apt install default-jdk', which indeed shows as installed:

default-jdk/xenial,now 2:1.8-56ubuntu2 amd64 [installed]

Checking java -version however doesn't show the JDK:

java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

Is this sufficient for the installation? Why doesn't it also show the JDK?

I want to use Scala 2.12.1. Does this version work well with the Spark2.1/Hadoop 2.7 combination or is another version more suitable?

Is the Scala SBT package also needed?

Been going back and forth trying to get everything working, but am stuck at this point.

Hope somebody can shed some light :)

答:
You need to install hadoop-2.7 more to whatever you are installing.

Java version is fine.

The mentioned configuration should work with scala 2.12.1.

Title: Apache Spark: Pre requisite questions


问:
How to create a WCF service
I want to learn step by step how to create a WCF service, starting from something very simple.

Can anyone help me?

答:
As for resources: there's the MSDN WCF Developer Center which has everything from beginner's tutorials to articles and sample code.

Also, check out the screen cast library up on MSDN for some really useful, 10-15 minute chunks of information on just about any topic related to WCF you might be interested in.

Also very good are The Service Station articles in MSDN magazine on various aspects of WCF - some more basic like Serialization in WCF or WCF Bindings in Depth, some more advanced and esoteric - but always worth a look!

Title: How to create a WCF service


问:
I need 2 formats needed in an excel spreadsheet column
I am not using .NET only excel.
1. I have a column of values from 1 - 10.
examples:

```<code>2,00
2,34
6,30
7,00
</code>```

(Comas because I live in Spain)
2. I don't want the whole numbers to show decimal points.
ie: I need

```<code>2
2,34
6,30
7
</code>```

答:
What is selected when you right click and go to Format Cells...?

I suspect it is a Number formatting, where the number of decimals must be specified. If you select General, this should get rid of zeros after the last non-zero significant figure.

Bear in mind this will mean you have:

```<code>2
2,34
6,3     <---- no zero here
7
</code>```

Alternatively you could format each cell with your specifications.

Body:
I am not using .NET only excel.
1. I have a column of values from 1 - 10.
examples:

2,00
2,34
6,30
7,00

(Comas because I live in Spain)
2. I don't want the whole numbers to show decimal points.
ie: I need

2
2,34
6,30
7

Body:
What is selected when you right click and go to Format Cells...?

I suspect it is a Number formatting, where the number of decimals must be specified. If you select General, this should get rid of zeros after the last non-zero significant figure.

Bear in mind this will mean you have:

2
2,34
6,3     <---- no zero here
7

Alternatively you could format each cell with your specifications.


问:
Xdebug Error: "Failed loading xdebug.so: xdebug.so: cannot open shared object file: No such file or directory"
I recently installed xdebug on my server but restricted it's use to our test site, which uses it's own php.ini file.

For example, the test sites php.ini is located at:

```<code>/home/test_site/public_html/subdomain_name/php.ini
</code>```

Inside this php.ini file I have the below for xdebug:

```<code>[XDebug]
zend_extension = /usr/local/lib/php/extensions/no-debug-non-zts-20090626/xdebug.so

xdebug.profiler_append = 0

xdebug.profiler_enable = 1

xdebug.profiler_enable_trigger = 0

xdebug.profiler_output_dir = /home/test_site/xdebug

xdebug.profiler_output_name = "cachegrind.out.%s-%u.%h_%r"
</code>```

Now, the thing is, xdebug works fine, no problems.

However, on our main site, which also has it's own php.ini file, which is located for example at:

```<code>/home/main_site/public_html/php.ini
</code>```

Inside this file I have nothing for xdebug in there.

Now, I recently setup a cron in cpanel for the main site such as:

```<code>php -f /home/main_site/public_html/cron_jobs/main_cron.php > /home/main_site/public_html/logs/main_cron.log 2>&1
</code>```

Now, upon checking the output of the cron inside the log file I get the output:

```<code>Failed loading xdebug.so:  xdebug.so: cannot open shared object file: No such file or directory
</code>```

Why am I getting this error when the main site shouldn't even be loading xdebug?

答:
Sometimes might be difficult from where the XDebug library is loaded since it can be done either by specifying the path in php.ini or by adding the lib in mods-available.

Firstly, run:

```<code>$ sudo grep 'xdebug' -r /etc/php/*
</code>```

This will give you the files that loads the extension.

Now identify which php.ini is in use:

```<code>$ php -i | grep php.ini
</code>```

This will give you the php version in use (in case you have multiple php versions). Now link the php version with the result from the first step.

Now, either you have to comment out the line where the xdebug extension is loaded or remove the xdebug.ini file (that loads the extension) from /etc/php/x.x/mods-available (where x.x stands for the php version in use).

Body:
I recently installed xdebug on my server but restricted it's use to our test site, which uses it's own php.ini file.

For example, the test sites php.ini is located at:

/home/test_site/public_html/subdomain_name/php.ini

Inside this php.ini file I have the below for xdebug:

[XDebug]
zend_extension = /usr/local/lib/php/extensions/no-debug-non-zts-20090626/xdebug.so

xdebug.profiler_append = 0

xdebug.profiler_enable = 1

xdebug.profiler_enable_trigger = 0

xdebug.profiler_output_dir = /home/test_site/xdebug

xdebug.profiler_output_name = "cachegrind.out.%s-%u.%h_%r"

Now, the thing is, xdebug works fine, no problems.

However, on our main site, which also has it's own php.ini file, which is located for example at:

/home/main_site/public_html/php.ini

Inside this file I have nothing for xdebug in there.

Now, I recently setup a cron in cpanel for the main site such as:

php -f /home/main_site/public_html/cron_jobs/main_cron.php > /home/main_site/public_html/logs/main_cron.log 2>&1

Now, upon checking the output of the cron inside the log file I get the output:

Failed loading xdebug.so:  xdebug.so: cannot open shared object file: No such file or directory

Why am I getting this error when the main site shouldn't even be loading xdebug?

Body:
Sometimes might be difficult from where the XDebug library is loaded since it can be done either by specifying the path in php.ini or by adding the lib in mods-available.

Firstly, run:

$ sudo grep 'xdebug' -r /etc/php/*

This will give you the files that loads the extension.

Now identify which php.ini is in use:

$ php -i | grep php.ini

This will give you the php version in use (in case you have multiple php versions). Now link the php version with the result from the first step.

Now, either you have to comment out the line where the xdebug extension is loaded or remove the xdebug.ini file (that loads the extension) from /etc/php/x.x/mods-available (where x.x stands for the php version in use).


问:
cakephp3- controller could not be found
I'm learning cakephp 3 framework. Its better to say I'm pretty much new at this.

I'm trying to make a plugin.
I baked a plugin like this bin/cake bake plugin myFirstPlugin
Then I baked a controller for this plugin using

bin/cake bake controller --plugin myFirstPlugin test

So inside my plugin's controller, I defined a function which does nothing other than outputting a message.

This is my plugin's controller

```<code><?php
namespace myFirstPlugin\Controller;

use myFirstPlugin\Controller\AppController;

class testController extends AppController
{
    public function index()
    {
        $msg = 'test';
        $this->set(compact('msg'));
        $this->set('_serialize', ['msg']);
    }
}
?>
</code>```

and in my application's route (not in plugin's route) I wrote this:

```<code>Router::scope('/myFirstPlugin/index', function (RouteBuilder $routes){
    $routes->connect('/', ['controller' => 'test', 'action' => 'index']);
});
</code>```

So, when I try to call this using the below url

```<code>http://localhost/myApplication/myFirstPlugin/index
</code>```

I got this error:

```<code>Error: testController could not be found.
Error: Create the class testController below in file: src\Controller\testController.php
</code>```

Why am I getting such an error even  though I created a controller. Thanks!

答:
You need to mention your plugin name within $routes->connect

```<code>Router::scope('/myFirstPlugin/index', function (RouteBuilder $routes){
    $routes->connect('/', ['plugin' => 'myFirstPlugin','controller' => 'test', 'action' => 'index']);
});
</code>```

Title: cakephp3- controller could not be found

Body:
I'm learning cakephp 3 framework. Its better to say I'm pretty much new at this.

I'm trying to make a plugin.
I baked a plugin like this bin/cake bake plugin myFirstPlugin
Then I baked a controller for this plugin using

bin/cake bake controller --plugin myFirstPlugin test

So inside my plugin's controller, I defined a function which does nothing other than outputting a message.

This is my plugin's controller

<?php
namespace myFirstPlugin\Controller;

use myFirstPlugin\Controller\AppController;

class testController extends AppController
{
    public function index()
    {
        $msg = 'test';
        $this->set(compact('msg'));
        $this->set('_serialize', ['msg']);
    }
}
?>

and in my application's route (not in plugin's route) I wrote this:

Router::scope('/myFirstPlugin/index', function (RouteBuilder $routes){
    $routes->connect('/', ['controller' => 'test', 'action' => 'index']);
});

So, when I try to call this using the below url

http://localhost/myApplication/myFirstPlugin/index

I got this error:

Error: testController could not be found.
Error: Create the class testController below in file: src\Controller\testController.php

Why am I getting such an error even  though I created a controller. Thanks!

Body:
You need to mention your plugin name within $routes->connect

Router::scope('/myFirstPlugin/index', function (RouteBuilder $routes){
    $routes->connect('/', ['plugin' => 'myFirstPlugin','controller' => 'test', 'action' => 'index']);
});


问:
How can I brighten/darken an image in PHP?
I guess I should be able to use GD to brighten or darken an image in PHP but don't find any info on it. Isn't that possible?</p>

答:
You can use the imagefilter function provided by PHP5 and up.

bool imagefilter ( resource $image , int $filtertype [, int $arg1 [, int $arg2 [, int $arg3 [, int $arg4 ]]]] )

You should be using the IMG_FILTER_BRIGHTNESS with a value from -255 to 255 to brighten/darken the image.

PHP Manual

Example from the manual

```<code><?php
$im = imagecreatefrompng('sean.png');

if($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20))
{
    echo 'Image brightness changed.';

    imagepng($im, 'sean.png');
    imagedestroy($im);
}
else
{
    echo 'Image brightness change failed.';
}
?>
</code>```

Body:
You can use the imagefilter function provided by PHP5 and up.

bool imagefilter ( resource $image , int $filtertype [, int $arg1 [, int $arg2 [, int $arg3 [, int $arg4 ]]]] )

You should be using the IMG_FILTER_BRIGHTNESS with a value from -255 to 255 to brighten/darken the image.

PHP Manual

Example from the manual

<?php
$im = imagecreatefrompng('sean.png');

if($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20))
{
    echo 'Image brightness changed.';

    imagepng($im, 'sean.png');
    imagedestroy($im);
}
else
{
    echo 'Image brightness change failed.';
}
?>


问:
How are locales persisted globally when setting it from a dropdown?
I am trying to persist a locale change based on the user setting the language from a bootstrap dropdown in a global navbar partial. It will change the language for the current page, but I don't know how to enable the locale for all subsequent routes.  The app works correctly when I manually insert the 2-char locale code (e.g., ru) into the URL (i.e., localhost:3000/en/about), so I know that the localizations are working correctly.  I'm not sure how to code a controller method so all routes/pages will use the locale.  Would greatly appreciate any guidance!

Snippet from my view:

```<code><li class="dropdown">
  <a class="dropdown-toggle" data-toggle="dropdown" href="#"><%= t(".dropdown.language") %> <span class="caret"></span></a>
  <ul class="dropdown-menu">
    <li><%= link_to t(".dropdown.english"), :locale=>:en %></li>
    <li><%= link_to t(".dropdown.thai"), :locale=>:th %></li>
    <li><%= link_to t(".dropdown.russian"), :locale=>:ru %></li>
  </ul>
</li>
</code>```

Code snippet from my I18n.rb initializer:

```<code># frozen_string_literal: true
I18n.available_locales = [:en, :th, :ru]
</code>```

Code snippets from my routes.rb:

```<code>  scope(
    '/(:locale)',
    locale: /#{I18n.available_locales.join('|')}/,
    defaults: { locale: I18n.default_locale }
  ) do
    get '/about' => 'pages#about'
    end
</code>```

and finally, here is the relevant route after rake:

```<code>about GET (/:locale)/about(.:format) pages#about {:locale=>/en|th|ru/}
</code>```

I had originally followed the guide to apply locale changes from within the application_controller.rb file as follows:

```<code>before_action :set_locale

def set_locale
  I18n.locale = params[:locale] || I18n.default_locale
end

def default_url_options
  { locale: I18n.locale }
end
</code>```

but this just causes the app to render a completely blank page (no log errors or warning at all, just an HTTP_RESPONSE: 200 with no content.

答:
You'll want to save the current value of I18n.locale to a session variable, and then fetch it back on each request. For example:

```<code>def set_locale
  # Note the ordering of params and session here, so that explicit params will still always override a saved setting
  I18n.locale = params[:locale] || session[:locale] || I18n.default_locale
  session[:locale] = I18n.locale
end
</code>```

Body:
I am trying to persist a locale change based on the user setting the language from a bootstrap dropdown in a global navbar partial. It will change the language for the current page, but I don't know how to enable the locale for all subsequent routes.  The app works correctly when I manually insert the 2-char locale code (e.g., ru) into the URL (i.e., localhost:3000/en/about), so I know that the localizations are working correctly.  I'm not sure how to code a controller method so all routes/pages will use the locale.  Would greatly appreciate any guidance!

Snippet from my view:

  <%= t(".dropdown.language") %>

<%= link_to t(".dropdown.english"), :locale=>:en %>

<%= link_to t(".dropdown.thai"), :locale=>:th %>

<%= link_to t(".dropdown.russian"), :locale=>:ru %>

Code snippet from my I18n.rb initializer:

# frozen_string_literal: true
I18n.available_locales = [:en, :th, :ru]

Code snippets from my routes.rb:

  scope(
    '/(:locale)',
    locale: /#{I18n.available_locales.join('|')}/,
    defaults: { locale: I18n.default_locale }
  ) do
    get '/about' => 'pages#about'
    end

and finally, here is the relevant route after rake:

about GET (/:locale)/about(.:format) pages#about {:locale=>/en|th|ru/}

I had originally followed the guide to apply locale changes from within the application_controller.rb file as follows:

before_action :set_locale

def set_locale
  I18n.locale = params[:locale] || I18n.default_locale
end

def default_url_options
  { locale: I18n.locale }
end

but this just causes the app to render a completely blank page (no log errors or warning at all, just an HTTP_RESPONSE: 200 with no content.

Body:
You'll want to save the current value of I18n.locale to a session variable, and then fetch it back on each request. For example:

def set_locale
  # Note the ordering of params and session here, so that explicit params will still always override a saved setting
  I18n.locale = params[:locale] || session[:locale] || I18n.default_locale
  session[:locale] = I18n.locale
end


问:
2D Vector not properly saved and loaded with boost::serialize library
I have a vector<vector<char>> object, that I want to save and load from a file:

```<code>class Bar {
  private:
    std::vector<std::vector<char>> _map;

    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int version) {
        for(int i=0; i<_map.size(); ++i){
            // ar & _map[i];
        }
        ar & _map;
    }
};
</code>```

While the for loop works, the direct approach with ar & _map; saves and load the map with wrong dimensions and values.

I tried to test it with the example code from boost:

```<code>// create and modify example object of class Bar here...
Bar s();
std::ofstream ofs("map_save.save");
{
    boost::archive::text_oarchive oa(ofs);
    oa << s;
}

Bar news();
{
    std::ifstream ifs("map_save.save");
    boost::archive::text_iarchive ia(ifs);
    ia >> news;
}
</code>```

This is how the different 2D vectors look like. (The right one is the one on top:

```<code>0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 C 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
------------
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 C 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
0 1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
1 1 1 1 1 1 0 0 0 0
1 1 0 0 1 1 0 0 0 0
1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0
</code>```

答:
You are doing something else wrong that you're not showing:

Live On Coliru

```<code>#include <fstream>
#include <iostream>
#include <iomanip>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>

using namespace std;

class Bar {
  public:
    void seed(std::vector<std::vector<char>> const& init) { _map = init; }
    bool operator==(Bar const& other) const {
        return _map == other._map;
    }
  private:
    std::vector<std::vector<char>> _map;

    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int /*version*/) {
        //for(size_t i=0; i<_map.size(); ++i){ ar & _map[i]; }
        ar & _map;
    }
};

int main()
{
    std::vector<std::vector<char>> seed = {
        {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '0', '0', '0', '0', 'C', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'},
    };

    // create and modify example object of class Bar here...
    {
        Bar s;
        s.seed(seed);
        std::ofstream ofs("map_save.save");
        boost::archive::text_oarchive oa(ofs);
        oa << s;
    }

    {
        Bar news;
        std::ifstream ifs("map_save.save");
        boost::archive::text_iarchive ia(ifs);
        ia >> news;

        Bar compareTo;
        compareTo.seed(seed);
        std::cout << "Comparison: " << std::boolalpha << (compareTo == news) << "\n";
    }
}*
</code>```

Prints:

```<code>Comparison: true
</code>```

Body:
I have a vector<vector<char>> object, that I want to save and load from a file:

class Bar {
  private:
    std::vector<std::vector<char>> _map;

    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int version) {
        for(int i=0; i<_map.size(); ++i){
            // ar & _map[i];
        }
        ar & _map;
    }
};

While the for loop works, the direct approach with ar & _map; saves and load the map with wrong dimensions and values.

I tried to test it with the example code from boost:

// create and modify example object of class Bar here...
Bar s();
std::ofstream ofs("map_save.save");
{
    boost::archive::text_oarchive oa(ofs);
    oa << s;
}

Bar news();
{
    std::ifstream ifs("map_save.save");
    boost::archive::text_iarchive ia(ifs);
    ia >> news;
}

This is how the different 2D vectors look like. (The right one is the one on top:

0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 C 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
------------
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 C 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
0 1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
1 1 1 1 1 1 0 0 0 0
1 1 0 0 1 1 0 0 0 0
1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0

Body:
You are doing something else wrong that you're not showing:

Live On Coliru

#include <fstream>
#include <iostream>
#include <iomanip>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>

using namespace std;

class Bar {
  public:
    void seed(std::vector<std::vector<char>> const& init) { _map = init; }
    bool operator==(Bar const& other) const {
        return _map == other._map;
    }
  private:
    std::vector<std::vector<char>> _map;

    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int /*version*/) {
        //for(size_t i=0; i<_map.size(); ++i){ ar & _map[i]; }
        ar & _map;
    }
};

int main()
{
    std::vector<std::vector<char>> seed = {
        {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '0', '0', '0', '0', 'C', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '1', '1', '0', '0', '0', '0', '0', '0', '0'},
        {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'},
    };

    // create and modify example object of class Bar here...
    {
        Bar s;
        s.seed(seed);
        std::ofstream ofs("map_save.save");
        boost::archive::text_oarchive oa(ofs);
        oa << s;
    }

    {
        Bar news;
        std::ifstream ifs("map_save.save");
        boost::archive::text_iarchive ia(ifs);
        ia >> news;

        Bar compareTo;
        compareTo.seed(seed);
        std::cout << "Comparison: " << std::boolalpha << (compareTo == news) << "\n";
    }
}*

Prints:

Comparison: true