问:
repeatable marquee that's optional based on text width
I've spent most of my morning trying to resolve how to create a scrolling marquee on an Angular app; my goal is when the dynamic text is longer than its viewport, it will scroll (repeating, meaning you don't have to wait for the entire title to scroll off the page before you see it again) but when it's short enough to display without being cut off in the viewport width, it does not scroll.

I like examples I'm seeing but need to combine them somehow and I am very beginner when it comes to adding any kind of javascript.

One is using jQuery and marquee:

```<code>$('.marquee').marquee({
  duplicated: true
});
</code>```

This one is great because it repeats the text and continues without it having to completely leave the screen to start again. But, my trouble comes when trying to figure out a way to add in javascript to figure out how wide that text will be; either to have it be static or scroll.

For some reason, I am unable to understand how to link to codepen or jsfiddle of the examples I've found that hit close to home. Hoping my inquiry above is enough information. I know commenters can be a bit rough—please be patient with me.

答:
You could use text-shadow(to clone text) and animation if it is only about text.

JS will be necessary to get the width(from text lenght) of the piece to scroll and to update/insert css rule's values.

example inspired from your jsfiddle

function isElementOverflowing(element) {
  var overflowX = element.offsetWidth < element.scrollWidth,
    overflowY = element.offsetHeight < element.scrollHeight;
  return (overflowX || overflowY);
}

// below css updated and injected . can be shorten and nicely rewritten
var element = document.getElementById('ov1');

if (isElementOverflowing(element)) {
  var toscroll = element.scrollWidth;
  element.style.textShadow = toscroll + 'px 0 ';
  element.style.animation = 'marqueeme 5s infinite linear';
  var csstyle = document.createElement('style');
  csstyle.innerText = '@keyframes marqueeme {100%{ text-indent:-' + toscroll + 'px;}}';
  element.appendChild(csstyle)
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#marquee {
  max-width: 15em;
  overflow: hidden;
}

#ov1 {
  white-space: nowrap;
  margin: 0;
}</code>```

    Yadda yadda overflowing text this line is too long oh noes!

```

example here is using text-indent within the animation, but negative margin-left or translateX will do the same visual.

Another example with

a text-shadow of different color

transform to see it working instead text-indent.

It also sets speed according to text length

@ https://codepen.io/gc-nomade/pen/owPNZg

Body:
I've spent most of my morning trying to resolve how to create a scrolling marquee on an Angular app; my goal is when the dynamic text is longer than its viewport, it will scroll (repeating, meaning you don't have to wait for the entire title to scroll off the page before you see it again) but when it's short enough to display without being cut off in the viewport width, it does not scroll.

I like examples I'm seeing but need to combine them somehow and I am very beginner when it comes to adding any kind of javascript.

One is using jQuery and marquee:

$('.marquee').marquee({
  duplicated: true
});

This one is great because it repeats the text and continues without it having to completely leave the screen to start again. But, my trouble comes when trying to figure out a way to add in javascript to figure out how wide that text will be; either to have it be static or scroll.

For some reason, I am unable to understand how to link to codepen or jsfiddle of the examples I've found that hit close to home. Hoping my inquiry above is enough information. I know commenters can be a bit rough—please be patient with me.

Body:
You could use text-shadow(to clone text) and animation if it is only about text.

JS will be necessary to get the width(from text lenght) of the piece to scroll and to update/insert css rule's values.

example inspired from your jsfiddle

function isElementOverflowing(element) {
  var overflowX = element.offsetWidth < element.scrollWidth,
    overflowY = element.offsetHeight < element.scrollHeight;
  return (overflowX || overflowY);
}

// below css updated and injected . can be shorten and nicely rewritten
var element = document.getElementById('ov1');

if (isElementOverflowing(element)) {
  var toscroll = element.scrollWidth;
  element.style.textShadow = toscroll + 'px 0 ';
  element.style.animation = 'marqueeme 5s infinite linear';
  var csstyle = document.createElement('style');
  csstyle.innerText = '@keyframes marqueeme {100%{ text-indent:-' + toscroll + 'px;}}';
  element.appendChild(csstyle)
}

#marquee {
  max-width: 15em;
  overflow: hidden;
}

#ov1 {
  white-space: nowrap;
  margin: 0;
}

<div id="marquee">
  <p id="ov1">
    Yadda yadda overflowing text this line is too long oh noes!
  </p>
</div>

example here is using text-indent within the animation, but negative margin-left or translateX will do the same visual.

Another example with

a text-shadow of different color

transform to see it working instead text-indent.

It also sets speed according to text length

@ https://codepen.io/gc-nomade/pen/owPNZg


来源: stackexchange

问:
Show more info in React
I want to show more info onclick, but I have different divs to show/hide .
So. I do it this way :
The state is :

```<code>this.state = {
        showMore: false,
        showRewards: false,
        fees: false,
        showFees: false
    };
</code>```

One of the divs:

```<code>                      <div className='some'>
                          <h3 >Rewards <i className="icon-im-rewards"></i></h3>
                                  <h5 className="showMoreDetails" onClick={ () => this.show('rewards') }>{ showRewards ? '-' : '+' } { showRewards ? 'Show Less' : 'Show More' }</h5>
                          {   showRewards && detail.rewards.reward.map((name, i) =>
                                  <p key={i}> { name }</p>
                              )
                          }
                      </div>
</code>```

The function :

show (name) {
    let { showMore, showRewards, showFees } = this.state;

```<code>if (name === 'hightlights' && showMore === false) {
    this.setState({
        showMore: true
    });
} else {
    this.setState({
        showMore: false
    });
}

if (name === 'rewards' && showRewards === false) {
    this.setState({
        showRewards: true
    });
} else {
    this.setState({
        showRewards: false
    });
}

if (name === 'fees' && showFees === false) {
    this.setState({
        showFees: true
    });
} else {
    this.setState({
        showFees: false
    });
}
</code>```

This is too long, ugly and doesn't work correct (I can only see one expanded div at a time) How to improve it?

答:
This is a better and a cleaner way:    </p>

```<code>function show (name) {

  let { showMore, showRewards, showFees } = this.state;
  showMore = name === 'hightlights' && showMore === false;
  showRewards = name === 'rewards' && showRewards === false;
  showFees = name === 'fees' && showFees === false;

  this.setState({
    showFees,
    showRewards,
    showMore
  });
</code>```

ContentLicense: CC BY-SA 3.0

Title: Show more info in React

Body:
I want to show more info onclick, but I have different divs to show/hide .
So. I do it this way :
The state is :

this.state = {
        showMore: false,
        showRewards: false,
        fees: false,
        showFees: false
    };

One of the divs:

Rewards

 this.show('rewards') }>{ showRewards ? '-' : '+' } { showRewards ? 'Show Less' : 'Show More' }

                          {   showRewards && detail.rewards.reward.map((name, i) =>

 { name }

                              )
                          }

The function :

show (name) {
    let { showMore, showRewards, showFees } = this.state;

if (name === 'hightlights' && showMore === false) {
    this.setState({
        showMore: true
    });
} else {
    this.setState({
        showMore: false
    });
}

if (name === 'rewards' && showRewards === false) {
    this.setState({
        showRewards: true
    });
} else {
    this.setState({
        showRewards: false
    });
}

if (name === 'fees' && showFees === false) {
    this.setState({
        showFees: true
    });
} else {
    this.setState({
        showFees: false
    });
}

This is too long, ugly and doesn't work correct (I can only see one expanded div at a time) How to improve it?

Body:
This is a better and a cleaner way:

function show (name) {

  let { showMore, showRewards, showFees } = this.state;
  showMore = name === 'hightlights' && showMore === false;
  showRewards = name === 'rewards' && showRewards === false;
  showFees = name === 'fees' && showFees === false;

  this.setState({
    showFees,
    showRewards,
    showMore
  });


问:
Custom federated web service authenticators
I need to authenticate users against a corporate web service in WSO2 Identity Server. I have found this blog:

http://techreadme.blogspot.com.es/2015/08/wso2-identity-server-use-case.html

and download the code from git. I need to implement a custom federated authenticator.
The sample code doesn`t work, maven does not look for the correct urls and the POM.xml does not seem to be correct.
¿Did someone get the code working?. Thank you.

答:
The sample may not be working due to missing wso2 nexus repository references. Try adding that section from here to the sample's root pom.

On a related note, the above sample seems to have written for IS 5.0.0. So ,some of the dependencies may need to be updated if you are writing this for latest IS version (5.3.0)


问:
Checking if a user inputed string is in an array
So this is more than just checking if a user input string in an array because if the string is actually in the array and the bool returns true I want it to write some custom text.

```<code>{
    static void Main(string[] args)
    {
        string[] name= {"Bob","Bob2","Bob3","Bob4"};

        bool exists = name.Contains(string userName= Console.ReadLine());

        if (exists == true)
            Console.WriteLine("Hi " + userName);

        Console.ReadLine();
    }
}
</code>```

I know I can't run the code like this but I'm looking for a similar way to run it but I'm not sure how to store user input and still have the bool check if the user inuputed string is in the string array.

答:
I came up with this...

```<code>import java.util.Scanner;

public class inp {
public static void main (String args[]) {
    String[] name = new String[] {
    "Ben",
    "Sam"
    };
    int max = name.length;
    int current = 0;
    boolean is = false;

    System.out.println("What name tho?");
    Scanner inp = new Scanner(System.in);
    String nameInq = inp.next();

    while(is == false && current<max) {
        if(name[current].equals(nameInq)) {
            is = true;
        }else {
           current++;

        }
    }
 if(is) {
    System.out.println("They are in the list");
 }else {
    System.out.println("nah");
 }

 }
 }
</code>```

Not quite as efficent but gets the job done.

Body:
So this is more than just checking if a user input string in an array because if the string is actually in the array and the bool returns true I want it to write some custom text.

{
    static void Main(string[] args)
    {
        string[] name= {"Bob","Bob2","Bob3","Bob4"};

        bool exists = name.Contains(string userName= Console.ReadLine());

        if (exists == true)
            Console.WriteLine("Hi " + userName);

        Console.ReadLine();
    }
}

I know I can't run the code like this but I'm looking for a similar way to run it but I'm not sure how to store user input and still have the bool check if the user inuputed string is in the string array.

Body:
I came up with this...

import java.util.Scanner;

public class inp {
public static void main (String args[]) {
    String[] name = new String[] {
    "Ben",
    "Sam"
    };
    int max = name.length;
    int current = 0;
    boolean is = false;

    System.out.println("What name tho?");
    Scanner inp = new Scanner(System.in);
    String nameInq = inp.next();

    while(is == false && current<max) {
        if(name[current].equals(nameInq)) {
            is = true;
        }else {
           current++;

        }
    }
 if(is) {
    System.out.println("They are in the list");
 }else {
    System.out.println("nah");
 }

 }
 }

Not quite as efficent but gets the job done.


问:
Worksheet not displayed in VBE Microsoft Excel Objects
I got a workbook from my colleague and I can see a worksheet in the regular Excel interface, but when I open VBE, I found that the worksheet is not displayed under

Project window>VBAProject (ThisWorkbook's name)>Microsoft Excel Objects.

Are the worksheet object hidden somehow in the VBE?

答:
It may be ae Excel 4 Macro Sheet or an Excel 4 International Macro Sheet.  These things look just like worksheets, and if they are the Activesheet, the TypeName will still return 'worksheet'.  However, they don't behave like a worksheet - if you (say) put =A1*5 in cell B1, it will just appear as text.

You can list all of these macro sheets in the IDE by enumerating the relevant collections:

```<code>Option Explicit

Public Sub ListObjects()
Dim oMacroSheet As Object

'//Find all Excel4MacroSheets
Debug.Print "------- Excel 4 Macro Sheets ----------"
For Each oMacroSheet In ThisWorkbook.Excel4MacroSheets
    Debug.Print oMacroSheet.Name
Next oMacroSheet

    '//Find all Excel4InternationalMacroSheets
    Debug.Print "------- Excel 4 International Macro Sheets ----------"
    For Each oMacroSheet In ThisWorkbook.Excel4IntlMacroSheets
        Debug.Print oMacroSheet.Name
    Next oMacroSheet
End Sub
</code>```

Body:
It may be ae Excel 4 Macro Sheet or an Excel 4 International Macro Sheet.  These things look just like worksheets, and if they are the Activesheet, the TypeName will still return 'worksheet'.  However, they don't behave like a worksheet - if you (say) put =A1*5 in cell B1, it will just appear as text.

You can list all of these macro sheets in the IDE by enumerating the relevant collections:

Option Explicit

Public Sub ListObjects()
Dim oMacroSheet As Object

'//Find all Excel4MacroSheets
Debug.Print "------- Excel 4 Macro Sheets ----------"
For Each oMacroSheet In ThisWorkbook.Excel4MacroSheets
    Debug.Print oMacroSheet.Name
Next oMacroSheet

    '//Find all Excel4InternationalMacroSheets
    Debug.Print "------- Excel 4 International Macro Sheets ----------"
    For Each oMacroSheet In ThisWorkbook.Excel4IntlMacroSheets
        Debug.Print oMacroSheet.Name
    Next oMacroSheet
End Sub


问:
Can I detect XHTML parsing errors using Javascript?
When I have a markup error in my XHTML page, Mozilla Firefox displays the "Yellow Screen of Death", showing only a large red error message on a yellow background.

While these errors are rare, they are extremely user-unfriendly.

Is there a way I can detect these using Javascript, and thereby send a message back to the server?

What I've discovered so far:
 - Scripts placed before the parsing error still run. (Of course.)
 - Timeouts and intervals that were set in these scripts will still execute after the parsing error.
 - In Firefox, the DOM is a <parsererror> with a <sourcetext> inside it. I can detect this if I query document.firstChild.tagName.

Remaining questions:
 - What events are available that I could listen for to detect this happening? (Polling sucks.)
 - How can I detect this in other browsers?

答:
Catching parse errors on the client might be possible, but it's really solving the wrong problem.

I know this isn't what you asked for, but unless you're doing something truly XHTML-specific like embedding some other markup language, you should serve your page as text/html instead of application/xhtml+xml. Even if it's XHTML. By serving it as text/html you'll avoid the problem you're running into and allow your page to work in IE as well. Note that it's the MIME type and not the doctype declaration that determines which parser is used -- using a transitional doctype won't do it.

That said, if you're really sure you want your page parsed as XHTML, it's better to handle this kind of error on the server. Generate your page by building up a DOM and then send the result of serializing it. If that's not an option, then start by generating the page as you do now but don't transmit it to the client yet. Take the XHTML that you've generated and parse it server-side with a validating XHTML parser (or at the very least, a generic XML parser). If you get errors, display whatever error page you want. Otherwise, serialize the parsed DOM and send that to the client.

In summary, the basic rules for using application/xhtml+xml are:

Don't.

(For advanced users) Don't, unless you've proven that you're doing something that won't work if the page is served as text/html. This applies to a tiny, tiny fraction of a percent of XHTMl documents.

If you must serve your page as application/xhtml+xml, generate it with some method that guarantees validity.

Unless you really know what you're doing, never use application/xhtml+xml for a page that includes user input.

Remember that XHTML is just a reformulation of HTML 4 plus the ability to embed other languages. If you don't use the embedding, what you have is HTML 4 with a different but almost completely compatible syntax. The overwhelming majority of XHTML documents out there are served as text/html and thus treated like HTML 4 by browsers.

OwnerDisplayName: phyzome

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: CantFindMyOpenidPassword


问:
How to change a large number of elements' positions without lag
I'm creating an Angular component which functions as a timeline for editing video files. (something like this):

I'm running into some issues when determining the position of all the measure bars on the timeline, though, and I'm trying to figure out a better way to position each of them. Currently, I am using conversion functions (pxToFrame and frameToPx) to convert frame values to pixel values in order to know where to position each measure bar.  When we are very zoomed in (meaning most of the timeline is off-screen, and we are scrolled to our zoomed in section), this has to be done for every pixel bar, which means the action is performed for every frame in the video file (a lot!) This causes the component to behave VERY slowly when I zoom in enough to render many measure lines. This becomes such a costly reFlow that it hangs the browser for many seconds.

I am wondering what is the best way to prevent this lag created by rendering position styles for thousands of elements?

I have tried implementing angular2-virtual-scroll, in an attempt to only render the in-view elements, instead of all of them, but the component does not have an implementation for horizontal scroll yet.

Any ideas on a better strategy to approach this with, or a way of reducing the number of reFlows when rendering this component? We are working with 10s of 1000s of measure bar elements here (for each frame in a video file), so it needs to be a pretty drastic reduction.

Thanks!

For reference,
This is my html:

```<code><div
    // this.measureLineArray holds an array of numbers that represent the frames at which there should be a line
    *ngFor="let frame of this.measureLineArray"

    class="measure-line-container"

    // This ngStyle binding is how I have been changing the position property, but it's deathly slow when we are dealing with many measure lines
    [ngStyle]="getMeasureLinePxFromFrame(frame)"
>
    // This is the class for labeled lines
    <div
        class="measure-line-label"
        *ngIf="frame % this.labelInterval === 0"
    >
        <div class="text">{{frame.toString()}}</div>

        <div class="bar"></div>

   </div>

   // This is the class for unlabeled lines
   <div
        class="measure-line"
        *ngIf="!(frame % this.labelInterval === 0)"
   >
        <div class="bar"></div>

   </div>

</div>
</code>```

Here are the problematic functions that create the delay

```<code>// Here is the function that returns the position styling for each measure line

private getMeasureLinePxFromFrame(frame : Frame) : any
{
  let measureLineStyle = {
    'left': this.frameToPx(frame) + 'px'
  }
  return measureLineStyle;
}

// This is the conversion function, utilizing the width of the container element to determine of each measure-line

private frameToPx(frame : number) : number
{
  let currentProgress : number = frame / this.numFrames;

  return Math.floor(this.Timeline.clientWidth * currentProgress);
}
</code>```

And here is the relevant CSS:

```<code>.measure-line-container {
    display: inline-flex;
    position: absolute;
    height: 100%;
    flex-direction: column;
    justify-content: flex-end;
}

.measure-line {
    position: relative;
    bottom: 0px;

    .bar {
        width: 1px;
        height: 10px;
        background-color: black;
    }
}

.measure-line-label {
    position: relative;
    height: 50%;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;

    .bar {
        position: relative;
        bottom: 0px;
        left: 0px;
        width: 1px;
        height: 100%;
        background-color: black;
    }

    .text {
        position: absolute;
        top: 0px;
        margin-left: 3px;
        color: black;
        font-size: 8px;
        text-align: center;
        user-select: none;
    }
}
</code>```

答:
Read these topics:
https://blog.thoughtram.io/angular/2017/02/21/using-zones-in-angular-for-better-performance.html
and
https://blog.thoughtram.io/angular/2017/02/02/making-your-angular-app-fast.html

Moreover, you will get lots of benefits if you spend sometime reading about change detection in Angular. There are couple suggestions how to improve that. In general, OnPush strategy should help. But in any case, all workarounds related to updating exact element(s) that needs to be updated. I.e. you still have to determine only list of elements that needs to be rendered/shown on page at exact time, which leads to what you call "Virtual scroll".

You can put all slides on screen, but move only 10-20 of them at the same time. When slide is out of bounds -> remove it from activeFrames array and pick next from leftFrames or rightFrames.

Body:
I'm creating an Angular component which functions as a timeline for editing video files. (something like this):

I'm running into some issues when determining the position of all the measure bars on the timeline, though, and I'm trying to figure out a better way to position each of them. Currently, I am using conversion functions (pxToFrame and frameToPx) to convert frame values to pixel values in order to know where to position each measure bar.  When we are very zoomed in (meaning most of the timeline is off-screen, and we are scrolled to our zoomed in section), this has to be done for every pixel bar, which means the action is performed for every frame in the video file (a lot!) This causes the component to behave VERY slowly when I zoom in enough to render many measure lines. This becomes such a costly reFlow that it hangs the browser for many seconds.

I am wondering what is the best way to prevent this lag created by rendering position styles for thousands of elements?

I have tried implementing angular2-virtual-scroll, in an attempt to only render the in-view elements, instead of all of them, but the component does not have an implementation for horizontal scroll yet.

Any ideas on a better strategy to approach this with, or a way of reducing the number of reFlows when rendering this component? We are working with 10s of 1000s of measure bar elements here (for each frame in a video file), so it needs to be a pretty drastic reduction.

Thanks!

For reference,
This is my html:

    // This is the class for labeled lines

{{frame.toString()}}

   // This is the class for unlabeled lines

Here are the problematic functions that create the delay

// Here is the function that returns the position styling for each measure line

private getMeasureLinePxFromFrame(frame : Frame) : any
{
  let measureLineStyle = {
    'left': this.frameToPx(frame) + 'px'
  }
  return measureLineStyle;
}

// This is the conversion function, utilizing the width of the container element to determine of each measure-line

private frameToPx(frame : number) : number
{
  let currentProgress : number = frame / this.numFrames;

  return Math.floor(this.Timeline.clientWidth * currentProgress);
}

And here is the relevant CSS:

.measure-line-container {
    display: inline-flex;
    position: absolute;
    height: 100%;
    flex-direction: column;
    justify-content: flex-end;
}

.measure-line {
    position: relative;
    bottom: 0px;

    .bar {
        width: 1px;
        height: 10px;
        background-color: black;
    }
}

.measure-line-label {
    position: relative;
    height: 50%;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;

    .bar {
        position: relative;
        bottom: 0px;
        left: 0px;
        width: 1px;
        height: 100%;
        background-color: black;
    }

    .text {
        position: absolute;
        top: 0px;
        margin-left: 3px;
        color: black;
        font-size: 8px;
        text-align: center;
        user-select: none;
    }
}


问:
Wamp and xampp on same machine
I use wamp2.2 for all the time, but i had to install xamp1.6.8 cause i've got to work with project created for old php version. Xamp installation goes fine but when i run it i cant get localhost site. Ive got blank page with favicon of wamp and comunicate that site is unavaible. I know that this is configuration case. Anybody know how to fix this?

I want to run only one of them at once, and i have configured some virtualhosts for wamp they dont have to be accesible while xamp is running i need xamp only for one project.

答:
for run xampp and wamp in same computer you can use this tutorial from arasjoomla website: http://arasjoomla.ir/joomla-tutorial/how-to-run-xampp-and-wamp-on-same-computer
for example we used wamp with default port and setting and set changed in xampp:

Change xampp apache port 80 to example 8080 in httpd.conf from
directory C:\xampp\apache\conf

In my.ini from C:\xampp\mysql\bin change port=3306 to port=3307

In config.inc.php from C:\xampp\phpMyAdmin after this code:

$cfg['Servers'][$i]['AllowNoPassword'] = true;

add this code:

$cfg['Servers'][$i]['port'] = '3307';

restart xampp now we cab use xampp and wamp for example use this
code in xampp port 3307 for connection database:

```<code>$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_db";
$port = '3307';

$conn = mysqli_connect($servername, $username, $password, $dbname,$port);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, name FROM users";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
   while($row = mysqli_fetch_assoc($result)) {
    echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
   }
 } else
     echo "0 results";

mysqli_close($conn);
</code>```

Title: Wamp and xampp on same machine

Body:
for run xampp and wamp in same computer you can use this tutorial from arasjoomla website: http://arasjoomla.ir/joomla-tutorial/how-to-run-xampp-and-wamp-on-same-computer
for example we used wamp with default port and setting and set changed in xampp:

Change xampp apache port 80 to example 8080 in httpd.conf from
directory C:\xampp\apache\conf

In my.ini from C:\xampp\mysql\bin change port=3306 to port=3307

In config.inc.php from C:\xampp\phpMyAdmin after this code:

$cfg['Servers'][$i]['AllowNoPassword'] = true;

add this code:

$cfg['Servers'][$i]['port'] = '3307';

restart xampp now we cab use xampp and wamp for example use this
code in xampp port 3307 for connection database:

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_db";
$port = '3307';

$conn = mysqli_connect($servername, $username, $password, $dbname,$port);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, name FROM users";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
   while($row = mysqli_fetch_assoc($result)) {
    echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
   }
 } else
     echo "0 results";

mysqli_close($conn);


问:
How to get YouTube video Id by the video name?
I am developing an android app, and I am trying to display a YouTube video, using the video name (with YouTubePlayer and YouTubeBaceActivity).

I am able to display the video if I have the video Id, but I don't know how to display the video by using only the video name.

I have tried to use HttoUrlConnaction by enter:

https://www.googleapis.com/youtube/v3/search?part=snippet&q=<MOVIE_NAME>&type=video&key=<APIKEY>

but it doesn't work for some reason and returns FileNotFoundException even though it works when I type the URL in google...

So how can I get the video Id, or how can I get the video only with the video name?

Thank You!

答:
You can find how to get the Video ID's or video list here. They have all the Request information needed for your youtube API calls.

As for why you are getting your FileNotFoundException even when it works when you type in the URL in google, Usually this problem occurs when the developer forgets to add their oAuthToken as part of their headers, or plain and simple -- The url is wrong

Using HttpURLConnection, here is an example of how you can set request headers using the .setRequestProperty() method.

```<code>HttpURLConnection urlConnection = null;
        String response = null;

        try{
            //Create connection
            String url = requestURL;
            URL u = new URL(url);
            urlConnection = (HttpURLConnection) u.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Authorization", youtubeAuthToken);

            //Get Response, etc ,etc}
</code>```

Body:
You can find how to get the Video ID's or video list here. They have all the Request information needed for your youtube API calls.

As for why you are getting your FileNotFoundException even when it works when you type in the URL in google, Usually this problem occurs when the developer forgets to add their oAuthToken as part of their headers, or plain and simple -- The url is wrong

Using HttpURLConnection, here is an example of how you can set request headers using the .setRequestProperty() method.

HttpURLConnection urlConnection = null;
        String response = null;

        try{
            //Create connection
            String url = requestURL;
            URL u = new URL(url);
            urlConnection = (HttpURLConnection) u.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Authorization", youtubeAuthToken);

            //Get Response, etc ,etc}


问:
Cron compress files
I would like to introduce a Cron tak that will 'gzip' files with the following rule:

Locate files in a folder name '/log' (can be located anywhere in the filesystem) and

gzip files, older than 2 days, that have './log' in the file name handle

I have written a the script below - which does not work - am I close? What is required to make it work? Thanks.

/usr/bin/find ./logs -mtime +2 -name "*.log*"|xargs gzip

答:
In my crontab, I call:

```<code>/usr/sbin/logrotate -s ~/.logrotate/status ~/.logrotate/logrotate.conf
</code>```

In my ~/.logrotate/logrotate.conf:

```<code># rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4

## compression

# gzip(1)
#compresscmd /usr/bin/gzip
#compressoptions -9
#uncompresscmd /usr/bin/gunzip
#compressext .gz

# xz(1)
compresscmd /usr/bin/xz
uncompresscmd /usr/bin/xzdec
compressext .xz

/home/h3xx/.log/*.log /home/h3xx/.log/jack/*.log {
    # copy and truncate original (for always-open file handles
    # [read: tail -f])
    copytruncate

    # enable compression
    compress
}

/home/h3xx/.usage/*.db {
    # back up databases
    copy

    # enable compression
    compress
}
</code>```

Title: Cron compress files

Body:
In my crontab, I call:

/usr/sbin/logrotate -s ~/.logrotate/status ~/.logrotate/logrotate.conf

In my ~/.logrotate/logrotate.conf:

# rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4

## compression

# gzip(1)
#compresscmd /usr/bin/gzip
#compressoptions -9
#uncompresscmd /usr/bin/gunzip
#compressext .gz

# xz(1)
compresscmd /usr/bin/xz
uncompresscmd /usr/bin/xzdec
compressext .xz

/home/h3xx/.log/*.log /home/h3xx/.log/jack/*.log {
    # copy and truncate original (for always-open file handles
    # [read: tail -f])
    copytruncate

    # enable compression
    compress
}

/home/h3xx/.usage/*.db {
    # back up databases
    copy

    # enable compression
    compress
}


问:
How to make a circular UIView
I want to make a UIView or UIImageView that is a circle. Or a circle that i can change the size of using a slider, and the color of with a pickerview.</p>

答:
As mentioned in some comments, @IBDesignable makes this much easier now, so you can use Interface Builder to configure your rounded UIImageView.

First create a class named RoundedImageView.swift and paste this code to it:

```<code>import UIKit

@IBDesignable public class RoundedImageView: UIImageView {

    override public func layoutSubviews() {
        super.layoutSubviews()

        //hard-coded this since it's always round
        layer.cornerRadius = 0.5 * bounds.size.width
    }
}
</code>```

Select the UIImageView in InterfaceBuilder and change the class from UIImageView to the custom RoundedImageView:

Set Clip to Bounds to true (or the pic will extend beyond the circle):

It should now round itself right there in InterfaceBuilder, which is pretty nifty. Be sure to set the width and height to the same values or it'll be shaped like a zeppelin!

Title: How to make a circular UIView

Body:
As mentioned in some comments, @IBDesignable makes this much easier now, so you can use Interface Builder to configure your rounded UIImageView.

First create a class named RoundedImageView.swift and paste this code to it:

import UIKit

@IBDesignable public class RoundedImageView: UIImageView {

    override public func layoutSubviews() {
        super.layoutSubviews()

        //hard-coded this since it's always round
        layer.cornerRadius = 0.5 * bounds.size.width
    }
}

Select the UIImageView in InterfaceBuilder and change the class from UIImageView to the custom RoundedImageView:

Set Clip to Bounds to true (or the pic will extend beyond the circle):

It should now round itself right there in InterfaceBuilder, which is pretty nifty. Be sure to set the width and height to the same values or it'll be shaped like a zeppelin!


问:
Adobe breaks stamped PDF when saving as new file / what is difference in Adobe 'save as' vs. Foxit Reader 'save as' feature
I'm reaching out to larger community of developers in seek of help to understand the real cause and possibly finding a fix. I have asked questions from Aspose, and they have also tracked the issue (PDFNET-42880) in their system. I think they are not going to investigate this anytime soon as it is very specific case. And now I am posting this here to ask more details about:

What is difference in Adobe 'save as' vs. Foxit Reader 'save as' vs. Windows Reader 'save as' feature?

Issues with Adobe product that are not so obvious to figure out. I don't even know what to ask :D

Link to their (Aspose) old forum: https://www.aspose.com/community/forums/thread/845549/removing-stamps-fails-after-saving-stamped-file-from-adobe-acrobat.aspx

Case:
Created PDF with forms using OpenOffice (version 3.4.0), stamped with Aspose PDF, opened with Adobe Reader DC (or Adobe Acrobat XI), filled, saved as new file. Now this new file is fine, but when I try to remove stamps using Aspose (and replace with new stamp later), this is where things get interesting.

Files that I've tested with: https://1drv.ms/f/s!Auvpijam7a73iDzOqc6wZPuY9l81

Stamp_Location.png

OoPdfFormExample_WithStamp.pdf

OoPdfFormExample_WithStamp_StampRemoved.pdf

OoPdfFormExample_WithStamp_SavedFromFoxit.pdf

OoPdfFormExample_WithStamp_SavedFromFoxit_StampRemoved.pdf

OoPdfFormExample_WithStamp_SavedFromWindowsReader.pdf

OoPdfFormExample_WithStamp_SavedFromWindowsReader_StampRemoved.pdf

OoPdfFormExample_WithStamp_SavedFromAdobeReader.pdf

OoPdfFormExample_WithStamp_SavedFromAcrobat_StampRemoved.pdf

C# code that is used to remove the stamp(s):

```<code>/// <summary>
/// Removes stamps from PDF file.
/// </summary>
/// <param name="pdfFile"></param>
private static void RemoveStamps( string pdfFile )
{
    // Create PDF content editor.
    Aspose.Pdf.Facades.PdfContentEditor contentEditor = new Aspose.Pdf.Facades.PdfContentEditor();

    // Open the temp file.
    contentEditor.BindPdf( pdfFile );

    // Process all pages.
    foreach ( Page page in contentEditor.Document.Pages )
    {
        // Get the stamp infos.
        Aspose.Pdf.Facades.StampInfo[] stampInfos = contentEditor.GetStamps( page.Number );

        //Process all stamp infos
        foreach ( Aspose.Pdf.Facades.StampInfo stampInfo in stampInfos )
        {
            // Use try catch so we can output possible error w/out break point.
            try
            {
                contentEditor.DeleteStampById( stampInfo.StampId );
            }
            catch ( Exception e )
            {
                Console.WriteLine( e );
            }
        }
    }

    // Save changes to the temp file.
    contentEditor.Save( StampRemovedPdfFile );
}
</code>```

Using Adobe: The process of removing stamp works fine, but trying to open the file will end up having an issue with the file.

"An error exists on this Page. Acrobat may not display the page correctly. Please contact the person who created the PDF document to correct the problem."

EDIT: After testing more, and just opening file to Aspose, and saving it without modifications, that didn't break the file, only once the stamp was removed with Aspose method it was broken.

Using Foxit: Only difference in the process is that opening the file to Foxit Reader and save form there. The stamp is removed and file is fine, works with any PDF reader.

Using Windows (10) Reader: Only difference in the process is that opening the file to Windows Reader and save from there. The stamp is removed and file is fine, works with any PDF reader.

答:
Ok - The thing you are referring to is not a stamp annotation. It's an XObject that gets drawn into the page content. Why Aspose refers to it as a Stamp is... well... a mystery. When you remove the "stamp" (not a stamp) Aspose seems to be removing the XObject but not the instructions to draw it from the page Contents stream... that's why you're getting the error in Acrobat. The other applications are more permissive with bad PDF and my guess is when they write out the file, they are removing references to non-existent objects. You can make Acrobat attempt to fix problems like this by selecting Save As Optimized PDF. However, you are far better off removing the drawing instruction in addition to the XObject.

Because of the way you've created the file and added the "stamp", your page content stream is an array of streams. Remove the last item in the array, which is the instruction to draw the XObject, and you file will work without errors in all the viewers. Note: It won't always be the case that the last item in the content array will be your stamp. It's just that your stamp is the last thing to get drawn so it goes at the end.

If your intention is to "replace" the "stamp", you'll want to do so by removing the XObject as you are doing now, then remove the instruction, then add the new "stamp".

Body:
I'm reaching out to larger community of developers in seek of help to understand the real cause and possibly finding a fix. I have asked questions from Aspose, and they have also tracked the issue (PDFNET-42880) in their system. I think they are not going to investigate this anytime soon as it is very specific case. And now I am posting this here to ask more details about:

What is difference in Adobe 'save as' vs. Foxit Reader 'save as' vs. Windows Reader 'save as' feature?

Issues with Adobe product that are not so obvious to figure out. I don't even know what to ask :D

Link to their (Aspose) old forum: https://www.aspose.com/community/forums/thread/845549/removing-stamps-fails-after-saving-stamped-file-from-adobe-acrobat.aspx

Case:
Created PDF with forms using OpenOffice (version 3.4.0), stamped with Aspose PDF, opened with Adobe Reader DC (or Adobe Acrobat XI), filled, saved as new file. Now this new file is fine, but when I try to remove stamps using Aspose (and replace with new stamp later), this is where things get interesting.

Files that I've tested with: https://1drv.ms/f/s!Auvpijam7a73iDzOqc6wZPuY9l81

Stamp_Location.png

OoPdfFormExample_WithStamp.pdf

OoPdfFormExample_WithStamp_StampRemoved.pdf

OoPdfFormExample_WithStamp_SavedFromFoxit.pdf

OoPdfFormExample_WithStamp_SavedFromFoxit_StampRemoved.pdf

OoPdfFormExample_WithStamp_SavedFromWindowsReader.pdf

OoPdfFormExample_WithStamp_SavedFromWindowsReader_StampRemoved.pdf

OoPdfFormExample_WithStamp_SavedFromAdobeReader.pdf

OoPdfFormExample_WithStamp_SavedFromAcrobat_StampRemoved.pdf

C# code that is used to remove the stamp(s):

///
/// Removes stamps from PDF file.
///
/// <param name="pdfFile"></param>
private static void RemoveStamps( string pdfFile )
{
    // Create PDF content editor.
    Aspose.Pdf.Facades.PdfContentEditor contentEditor = new Aspose.Pdf.Facades.PdfContentEditor();

    // Open the temp file.
    contentEditor.BindPdf( pdfFile );

    // Process all pages.
    foreach ( Page page in contentEditor.Document.Pages )
    {
        // Get the stamp infos.
        Aspose.Pdf.Facades.StampInfo[] stampInfos = contentEditor.GetStamps( page.Number );

        //Process all stamp infos
        foreach ( Aspose.Pdf.Facades.StampInfo stampInfo in stampInfos )
        {
            // Use try catch so we can output possible error w/out break point.
            try
            {
                contentEditor.DeleteStampById( stampInfo.StampId );
            }
            catch ( Exception e )
            {
                Console.WriteLine( e );
            }
        }
    }

    // Save changes to the temp file.
    contentEditor.Save( StampRemovedPdfFile );
}

Using Adobe: The process of removing stamp works fine, but trying to open the file will end up having an issue with the file.

"An error exists on this Page. Acrobat may not display the page correctly. Please contact the person who created the PDF document to correct the problem."

EDIT: After testing more, and just opening file to Aspose, and saving it without modifications, that didn't break the file, only once the stamp was removed with Aspose method it was broken.

Using Foxit: Only difference in the process is that opening the file to Foxit Reader and save form there. The stamp is removed and file is fine, works with any PDF reader.

Using Windows (10) Reader: Only difference in the process is that opening the file to Windows Reader and save from there. The stamp is removed and file is fine, works with any PDF reader.


问:
In Xcode, my instagram app cannot get url callback
I am taking a Coursera class and have followed the instructors code verbatim.  However, upon logging in to Instagram, I am sent to a website and not my example app I am trying to use.</p>

答:
I assume the course is not built for iOS 9+.

From iOS 9, you needs to provide a LSApplicationQueriesSchemes entry in its plist file, declaring which schemes it attempts to query.

```<code> <key>LSApplicationQueriesSchemes</key>
   <array>
     <string>instagram</string>
   </array>
</key>
</code>```

Body:
I assume the course is not built for iOS 9+.

From iOS 9, you needs to provide a LSApplicationQueriesSchemes entry in its plist file, declaring which schemes it attempts to query.

 <key>LSApplicationQueriesSchemes</key>
   <array>
     <string>instagram</string>
   </array>
</key>


问:
Visual Studio 2017 UI ignores CSPROJ <PackageVersion>
I have a simple .NetCoreApp 1.1 Class Library, currently open in Visual Studio 2017 15.2 (26430.13).
I'd like to create a NuGet package on build, and have configured the "Package" tab of my project settings; including the "Generate NuGet package on build".
On that tab I set the "Package id" and "Package version".
I see the Package id stored in the CSPROJ<PackageId> element.
However, I do not see the Package version being stored in the <PackageVersion> element.
The NuGet package gets built using the CSPROJ<PackageVersion> value; and the different value shown in the project properties "Package" tab is stored in some magical location I cannot find.

Is this a bug?

-John

答:
The PackageVersion is defaulted to Version if it isn't set explicitly in the project itself, so editing Version alone will also set the resulting nuget package's version. In addition, Version - in contrast to PackageVersion - will also be used as a default for the autogenerated AssemblyInfo.cs so in many cases, you'd want to set Version anyway to affect both assembly metadata and the nuget's package version.

If you think that this behaviour is incorrect - especially when you define a custom PackageVersion in the project itself - this can be considered a bug, or a missing feature for the case when you set PackageVersion manually. You could open an issue on the project system's GitHub repo to discuss this behaviour.


问:
Giving constraints in Optimization using Pulp
I am currently working on an Optimization problem using Pulp module in Python. I want to set my variables to be integral multiple of 7500.So I created a constriant as given below but it is showing error.

```<code>import pandas as pd
import numpy as np
from pulp import *

prob = LpProblem('Cost minimization' , LpMinimize)
X = LpVariable.dicts('',tsap.varName, lowBound=0, upBound=None,     cat=LpInteger)
prob += lpSum( X[i] * j for i,j in zip(tsap.varName, tsap.coeff)),'Total cost'

l=7500

for i in X:
prob += i % l == 0

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-73548ad8b39f> in <module>()
        1 for i in X:
  ----> 2     prob += i % l == 0
        3

TypeError: not all arguments converted during string formatting
</code>```

Is there any way to achieve the desired goal?

答:
You can't use the modulo operator in pulp as that would become a non-linear problem.

However, the simple solution is to keep X[i] integer and then in you constraints use 7500*X[i] and report the solution accordingly.

Body:
I am currently working on an Optimization problem using Pulp module in Python. I want to set my variables to be integral multiple of 7500.So I created a constriant as given below but it is showing error.

import pandas as pd
import numpy as np
from pulp import *

prob = LpProblem('Cost minimization' , LpMinimize)
X = LpVariable.dicts('',tsap.varName, lowBound=0, upBound=None,     cat=LpInteger)
prob += lpSum( X[i] * j for i,j in zip(tsap.varName, tsap.coeff)),'Total cost'

l=7500

for i in X:
prob += i % l == 0

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-73548ad8b39f> in <module>()
        1 for i in X:
  ----> 2     prob += i % l == 0
        3

TypeError: not all arguments converted during string formatting

Is there any way to achieve the desired goal?


问:
ActiveRecord::RecordInvalid: Validation failed: User must exist
I'm working on a issue with Single Table Inheritance. I have two different types of Users. User model and Trainer model, Trainer user should inherit attributes from the User model. I created a User in the rails console and everything worked. As soon as I attempted to create a Trainer I get the following error.
Rails 5.0.4

```<code>ActiveRecord::RecordInvalid: Validation failed: User must exist
</code>```

Am I setting up my model associations incorrectly?

Here is my User Model

```<code>class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end
</code>```

My Trainer Model

```<code>class Trainer < User

  has_many :appointments
  has_many :clients, through: :appointments
end
</code>```

Schema for models

```<code>create_table "trainers", force: :cascade do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "type"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end
</code>```

As you can see from my User model, I added the required :type column

Here is the schema for my client and appointment

```<code>create_table "appointments", force: :cascade do |t|
    t.integer  "client_id"
    t.integer  "trainer_id"
    t.datetime "appointment_date"
    t.datetime "created_at",                   null: false
    t.datetime "updated_at",                   null: false
    t.datetime "start_time"
    t.datetime "end_time"
    t.integer  "status",           default: 0
  end

  create_table "clients", force: :cascade do |t|
    t.string   "name"
    t.string   "phone_number"
    t.integer  "price"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
  end
</code>```

First I created a user in the console

```<code>User.create!(email:'ryan@test.com', password:'asdfasdf', password_confirmation:'asdfasdf')
</code>```

Then I when on to create a Trainer

```<code>Trainer.create!(first_name:'Ryan', last_name:'Bent')
</code>```

Trainers and Users should be associated. But I didn't think I needed add associations using Single Table Inheritance.

答:
With Single Table Inheritance, one table must have all the attributes that any of the subclasses need (more information). So for your situation, you'd need to add the Trainer columns (first_name, last_name) to the users table as well, and then Users would leave that empty on the table and Trainers would fill them in.

If you want to keep the separate tables, what you are doing is no longer single table and would require some sort of joining between the 2.

Body:
I'm working on a issue with Single Table Inheritance. I have two different types of Users. User model and Trainer model, Trainer user should inherit attributes from the User model. I created a User in the rails console and everything worked. As soon as I attempted to create a Trainer I get the following error.
Rails 5.0.4

ActiveRecord::RecordInvalid: Validation failed: User must exist

Am I setting up my model associations incorrectly?

Here is my User Model

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

My Trainer Model

class Trainer < User

  has_many :appointments
  has_many :clients, through: :appointments
end

Schema for models

create_table "trainers", force: :cascade do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "type"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

As you can see from my User model, I added the required :type column

Here is the schema for my client and appointment

create_table "appointments", force: :cascade do |t|
    t.integer  "client_id"
    t.integer  "trainer_id"
    t.datetime "appointment_date"
    t.datetime "created_at",                   null: false
    t.datetime "updated_at",                   null: false
    t.datetime "start_time"
    t.datetime "end_time"
    t.integer  "status",           default: 0
  end

  create_table "clients", force: :cascade do |t|
    t.string   "name"
    t.string   "phone_number"
    t.integer  "price"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
  end

First I created a user in the console

User.create!(email:'ryan@test.com', password:'asdfasdf', password_confirmation:'asdfasdf')

Then I when on to create a Trainer

Trainer.create!(first_name:'Ryan', last_name:'Bent')

Trainers and Users should be associated. But I didn't think I needed add associations using Single Table Inheritance.


问:
Bukkit/Spigot) Getting configure section many times will occur an error
so recently I'm making some stuff with configure sections, this is my code

```<code>ConfigurationSection sec = getConfig().getConfigurationSection(p.getWorld().getName() + ".rewards");
        if (sec == null) {
            return;
        }
        int prizessize = sec.getKeys(false).size();
        int random = getRandomInt(0, prizessize);
</code>```

This is my config:

```<code>     world:
      rewards:
        '0':
          reward-name: '&etest'
          reward-chance: 10
          reward-rarity: '&6Legendary'
          item-type: customhead
          head-name: test
          custom-head-id: eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjNkNWU0M2RlNWQ0MTc3YzRiYWYyZjQ0MTYxNTU0NDczYTNiMGJlNTQzMDk5OGI1ZmNkODI2YWY5NDNhZmUzIn19fQ
          reward-item-id: 1
          reward-item-damage: 0
          firework:
            type: BALL
            flicker: true
            trail: false
            colors:
            - BLUE
            fade:
            - WHITE
          commands:
          - say %player% test reward
        '1':
.
.
.
</code>```

So it works fine while doing the reward event for several times but sometimes it spams an error in the console.

```<code>java.lang.StackOverflowError
    at org.bukkit.configuration.MemorySection.getConfigurationSection(MemorySection.java:679) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.get(MemorySection.java:219) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.getConfigurationSection(MemorySection.java:679) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.getDefaultSection(MemorySection.java:155) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.getKeys(MemorySection.java:76) ~[spigot.jar:git-Spigot-db6de12-18fbb24]

java.lang.StackOverflowError
    at org.bukkit.configuration.MemorySection.createPath(MemorySection.java:780) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.mapChildrenKeys(MemorySection.java:713) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.mapChildrenKeys(MemorySection.java:717) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.mapChildrenKeys(MemorySection.java:717) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.getKeys(MemorySection.java:83) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.getKeys(MemorySection.java:79) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
</code>```

答: i was getting a random chance and check if the reward chance is below my chance but there were no chances below my chance so it had endless loop</p>

Body:
so recently I'm making some stuff with configure sections, this is my code

ConfigurationSection sec = getConfig().getConfigurationSection(p.getWorld().getName() + ".rewards");
        if (sec == null) {
            return;
        }
        int prizessize = sec.getKeys(false).size();
        int random = getRandomInt(0, prizessize);

This is my config:

     world:
      rewards:
        '0':
          reward-name: '&etest'
          reward-chance: 10
          reward-rarity: '&6Legendary'
          item-type: customhead
          head-name: test
          custom-head-id: eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjNkNWU0M2RlNWQ0MTc3YzRiYWYyZjQ0MTYxNTU0NDczYTNiMGJlNTQzMDk5OGI1ZmNkODI2YWY5NDNhZmUzIn19fQ
          reward-item-id: 1
          reward-item-damage: 0
          firework:
            type: BALL
            flicker: true
            trail: false
            colors:
            - BLUE
            fade:
            - WHITE
          commands:
          - say %player% test reward
        '1':
.
.
.

So it works fine while doing the reward event for several times but sometimes it spams an error in the console.

java.lang.StackOverflowError
    at org.bukkit.configuration.MemorySection.getConfigurationSection(MemorySection.java:679) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.get(MemorySection.java:219) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.getConfigurationSection(MemorySection.java:679) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.getDefaultSection(MemorySection.java:155) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.getKeys(MemorySection.java:76) ~[spigot.jar:git-Spigot-db6de12-18fbb24]

java.lang.StackOverflowError
    at org.bukkit.configuration.MemorySection.createPath(MemorySection.java:780) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.mapChildrenKeys(MemorySection.java:713) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.mapChildrenKeys(MemorySection.java:717) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.mapChildrenKeys(MemorySection.java:717) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.getKeys(MemorySection.java:83) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.configuration.MemorySection.getKeys(MemorySection.java:79) ~[spigot.jar:git-Spigot-db6de12-18fbb24]


问:
Query the ids of every entry including a specified child key
Given a database scheme like the following:

```<code>{
   "lessons": {
      "subjectId1": {
           "lessonId2": { ... },
           "lessonId4": { ... },
           "lessonId6": { ... }
      },
      "subjectId2": {
           "lessonId1": { ... },
           "lessonId3": { ... },
           "lessonId5": { ... },
           "lessonId7": { ... }
      }
   }
}
</code>```

How do I retrieve the id(s) of any subject(s) that include a given lessonId?

I came up with a function like this:

```<code>    const refWithParent = database.ref("lessons");
    const snapshot = await refWithParent.orderByChild(lessonId).limitToLast(1).once("value");

    let firebaseId = null;
    if (snapshot.val() !== null) {
        snapshot.forEach(entry => {
            firebaseId = entry.key;
            return true;
        });
    }
    return firebaseId;
</code>```

This does work but I can't create an index in the database as the children are dynamically created.
Is there any easier way to retrieve the id?

答:
In Nosql like firebase you can denormalise or form your database as you want. I would advise that you make all your lesson names have a concatenation of it's subject when you creating them in order to avoid your querying of the database.
The codes below can help in getting a unique lesson id with a concatenation of the subject name before you create them.

```<code> let newId = database.ref("lessons").ref.push().key; //<-- get a new unique id
 let newlessonname = 'Subject2_' + newId;
</code>```

So your db would look like this

```<code>{
   "lessons": {
      "subjectId1": {
           "subjectId1_lessonId2": { ... },
           "subjectId1_lessonId4": { ... },
           "subjectId1_lessonId6": { ... }
      },
      "subjectId2": {
           "subjectId2_lessonId1": { ... },
           "subjectId2_lessonId3": { ... },
           "subjectId2_lessonId5": { ... },
           "subjectId2_lessonId7": { ... }
      }
   }
}
</code>```

Alternatively

You can include your Subjectid in the object of each lesson like this

```<code>{
   "lessons": {
      "subjectId1": {
           "lessonId2": {subjectid:"subjectId1" ... },
           "lessonId4": { ... },
           "lessonId6": { ... }
      },
      "subjectId2": {
           "lessonId1": { ... },
           "lessonId3": { ... },
           "lessonId5": { ... },
           "lessonId7": { ... }
      }
   }
}
</code>```

Body:
Given a database scheme like the following:

{
   "lessons": {
      "subjectId1": {
           "lessonId2": { ... },
           "lessonId4": { ... },
           "lessonId6": { ... }
      },
      "subjectId2": {
           "lessonId1": { ... },
           "lessonId3": { ... },
           "lessonId5": { ... },
           "lessonId7": { ... }
      }
   }
}

How do I retrieve the id(s) of any subject(s) that include a given lessonId?

I came up with a function like this:

    const refWithParent = database.ref("lessons");
    const snapshot = await refWithParent.orderByChild(lessonId).limitToLast(1).once("value");

    let firebaseId = null;
    if (snapshot.val() !== null) {
        snapshot.forEach(entry => {
            firebaseId = entry.key;
            return true;
        });
    }
    return firebaseId;

This does work but I can't create an index in the database as the children are dynamically created.
Is there any easier way to retrieve the id?

Body:
In Nosql like firebase you can denormalise or form your database as you want. I would advise that you make all your lesson names have a concatenation of it's subject when you creating them in order to avoid your querying of the database.
The codes below can help in getting a unique lesson id with a concatenation of the subject name before you create them.

 let newId = database.ref("lessons").ref.push().key; //<-- get a new unique id
 let newlessonname = 'Subject2_' + newId;

So your db would look like this

{
   "lessons": {
      "subjectId1": {
           "subjectId1_lessonId2": { ... },
           "subjectId1_lessonId4": { ... },
           "subjectId1_lessonId6": { ... }
      },
      "subjectId2": {
           "subjectId2_lessonId1": { ... },
           "subjectId2_lessonId3": { ... },
           "subjectId2_lessonId5": { ... },
           "subjectId2_lessonId7": { ... }
      }
   }
}

Alternatively

You can include your Subjectid in the object of each lesson like this

{
   "lessons": {
      "subjectId1": {
           "lessonId2": {subjectid:"subjectId1" ... },
           "lessonId4": { ... },
           "lessonId6": { ... }
      },
      "subjectId2": {
           "lessonId1": { ... },
           "lessonId3": { ... },
           "lessonId5": { ... },
           "lessonId7": { ... }
      }
   }
}


问:
Building typescript with Node vs. Visual Studio and an outDir
I have a typescript project that I can build with Visual Studio, and I can also build with node. But they both seem to behave slightly differently. My project looks like this (simplified):

```<code>.
+-- app
|   +-- app.component.ts
|   +-- app.module.ts
|   +-- main.ts
+-- dist
+-- system.config.js
+-- tsconfig.json
+-- packages.json
</code>```

Now when I build, I want to output all the files into the dist folder. Therefore my tsconfig.json is set up with an outDir as follows:

```<code>{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "dist"

  },
  "exclude": [
    "node_modules/*",
    "packages/*",
    "**/*-aot.ts"
  ]
}
</code>```

Now when I build with node, using npm run tsc the dist folder looks like this:

```<code>+-- dist
|   +-- app
|   |   +-- main.js
|   |   +-- app.module.js
|   |   +-- app.component.js
</code>```

And when building with visual studio:

```<code>+-- dist
|   +-- main.js
|   +-- app.module.js
|   +-- app.component.js
</code>```

As you can see, the Visual Studio build doesn't place all the files inside the app folder. But the node build does.

Why is this not the same for both, given they are using the same configuration?

答:
Visual Studio uses the MSBuild TypeScript tasks. It is likely not using the tsconfig file, or there is some conflict. Open up your csproj file and take a look at the TypeScript specific nodes. In Visual Studio, you can control most of the values of these nodes by right-clicking on the project, viewing properties, and selecting the TypeScript tab.

Visual Studio is said to have support for tsconfig files from 2015 onward (with TypeScript 1.8), but depending on your version of Visual Studio, that's debatable. It seems there are many that are still having issues.

One way to check would be to run msbuild from the command line, pointing to your csproj file, and check the output. It should contain the tsc output, which should show you if msbuild is using the tsconfig file by whether or not the call to tsc is using the -p or --project switch. If it is, then it is attempting to use your tsconfig.

At this point, you are compiling two different ways (with a third test possible):

npm run tsc

Visual Studio building

tsc -p .

Run it with tsc -p . to see if that matches Visual Studio, and maybe the npm task is causing an issue. Either way, you might want to take a look at the documentation for rootDir, which might help you resolve the differences.

Body:
I have a typescript project that I can build with Visual Studio, and I can also build with node. But they both seem to behave slightly differently. My project looks like this (simplified):

.
+-- app
|   +-- app.component.ts
|   +-- app.module.ts
|   +-- main.ts
+-- dist
+-- system.config.js
+-- tsconfig.json
+-- packages.json

Now when I build, I want to output all the files into the dist folder. Therefore my tsconfig.json is set up with an outDir as follows:

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "dist"

  },
  "exclude": [
    "node_modules/*",
    "packages/*",
    "**/*-aot.ts"
  ]
}

Now when I build with node, using npm run tsc the dist folder looks like this:

+-- dist
|   +-- app
|   |   +-- main.js
|   |   +-- app.module.js
|   |   +-- app.component.js

And when building with visual studio:

+-- dist
|   +-- main.js
|   +-- app.module.js
|   +-- app.component.js

As you can see, the Visual Studio build doesn't place all the files inside the app folder. But the node build does.

Why is this not the same for both, given they are using the same configuration?


问:
How can I insert some XAML snippet in to my window as child element?
I have some XAML (as string) like this:

```<code> <Grid>
        <TextBlock>some text</TextBlock>
</Grid>
</code>```

And I want to insert it into my window without generating it in code behind:

```<code> <Window  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="BookOnTheFly.MainWindow"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
 <insert xaml snippet here>
    </Grid>
</window>
</code>```

I mean something like jQuery append..

答:
What you want is a resource.  A resource is a snippet of XAML code that conforms to certain requirements that is put in a resource dictionary.  Resources can be defined at the application, window or on any framework element.  Once defined, it can be referenced in various ways.

See https://blogs.msdn.microsoft.com/wpfsldesigner/2010/06/03/creating-and-consuming-resource-dictionaries-in-wpf-and-silverlight/

Edit:

Put my desired XAML code in resource ditionary :

```<code> <DataTemplate x:Key="insertion">
        <!-- XAML here -->
    </DataTemplate>
</code>```

and use it as data in Content Control:

```<code><ContentControl ContentTemplate="{StaticResource insertion}"/>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have some XAML (as string) like this:

 <Grid>
        <TextBlock>some text</TextBlock>
</Grid>

And I want to insert it into my window without generating it in code behind:

 <Window  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="BookOnTheFly.MainWindow"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
 <insert xaml snippet here>
    </Grid>
</window>

I mean something like jQuery append..

Body:
What you want is a resource.  A resource is a snippet of XAML code that conforms to certain requirements that is put in a resource dictionary.  Resources can be defined at the application, window or on any framework element.  Once defined, it can be referenced in various ways.

See https://blogs.msdn.microsoft.com/wpfsldesigner/2010/06/03/creating-and-consuming-resource-dictionaries-in-wpf-and-silverlight/

Edit:

Put my desired XAML code in resource ditionary :

 <DataTemplate x:Key="insertion">
        <!-- XAML here -->
    </DataTemplate>

and use it as data in Content Control:

<ContentControl ContentTemplate="{StaticResource insertion}"/>


问:
css animation change from absolute to relative
i have found this wave animation "https://codepen.io/tedmcdo/pen/PqxKXg" and would like to use it over my headerimg on my page, but the problem is that the animation is written for absolute values, but i would need a relative position since the animation should stay on top of the page.

I have tried to change to position type to relative but however i do it i break the animation, if anyone could help me i would be happy^^

thank you all for your time.

here is the css:

```<code>html, body { height: 100%; }
body {
  background:radial-gradient(ellipse at center, rgba(255,254,234,1) 0%, rgba(255,254,234,1) 35%, rgba(254,208,149,1) 100%);
  overflow: hidden;
}

.ocean {
  height: 5%;
  width:100%;
  position:absolute;
  bottom:0;
  left:0;
  background: #015871;
}

.wave {
  background: url(http://tedmcdo.com/labs/wave.svg) repeat-x;
  position: absolute;
  top: -198px;
  width: 6400px;
  height: 198px;
  animation: wave 7s cubic-bezier( 0.36, 0.45, 0.63, 0.53) infinite;
  transform: translate3d(0, 0, 0);
}

.wave:nth-of-type(2) {
  top: -175px;
  animation: wave 7s cubic-bezier( 0.36, 0.45, 0.63, 0.53) -.125s infinite, swell 7s ease -1.25s infinite;
  opacity: 1;
}

@keyframes wave {
  0% {
    margin-left: 0;
  }
  100% {
    margin-left: -1600px;
  }
}

@keyframes swell {
  0%, 100% {
    transform: translate3d(0,-25px,0);
  }
  50% {
    transform: translate3d(0,5px,0);
  }
}
</code>```

答:
Not too sure what you mean by this:

```<code>...need a relative position since the animation should stay on top of the page.
</code>```

...but I digress.

Add a containing div with relative positioning

```<code><div class="oceanContainer">
    <div class="ocean">
        <div class="wave"></div>
        <div class="wave"></div>
    </div>
</div>
</code>```

with CSS

```<code>.oceanContainer {
    position: relative;
    height: 100% /* you can play around with this for your header */
}
</code>```

You may need to adjust some of the other CSS though

```<code>.ocean {
  height: 5%; /* as above, adjust to %, px, (r)em's to your liking */
  bottom: 0;
}

.wave {
  bottom: 0;    /* change top to bottom */
}

.wave:nth-of-type(2) {
  bottom: 0;    /* change top to bottom */
}
</code>```

Body:
i have found this wave animation "https://codepen.io/tedmcdo/pen/PqxKXg" and would like to use it over my headerimg on my page, but the problem is that the animation is written for absolute values, but i would need a relative position since the animation should stay on top of the page.

I have tried to change to position type to relative but however i do it i break the animation, if anyone could help me i would be happy^^

thank you all for your time.

here is the css:

html, body { height: 100%; }
body {
  background:radial-gradient(ellipse at center, rgba(255,254,234,1) 0%, rgba(255,254,234,1) 35%, rgba(254,208,149,1) 100%);
  overflow: hidden;
}

.ocean {
  height: 5%;
  width:100%;
  position:absolute;
  bottom:0;
  left:0;
  background: #015871;
}

.wave {
  background: url(http://tedmcdo.com/labs/wave.svg) repeat-x;
  position: absolute;
  top: -198px;
  width: 6400px;
  height: 198px;
  animation: wave 7s cubic-bezier( 0.36, 0.45, 0.63, 0.53) infinite;
  transform: translate3d(0, 0, 0);
}

.wave:nth-of-type(2) {
  top: -175px;
  animation: wave 7s cubic-bezier( 0.36, 0.45, 0.63, 0.53) -.125s infinite, swell 7s ease -1.25s infinite;
  opacity: 1;
}

@keyframes wave {
  0% {
    margin-left: 0;
  }
  100% {
    margin-left: -1600px;
  }
}

@keyframes swell {
  0%, 100% {
    transform: translate3d(0,-25px,0);
  }
  50% {
    transform: translate3d(0,5px,0);
  }
}

Body:
Not too sure what you mean by this:

...need a relative position since the animation should stay on top of the page.

...but I digress.

Add a containing div with relative positioning

<div class="oceanContainer">
    <div class="ocean">
        <div class="wave"></div>
        <div class="wave"></div>
    </div>
</div>

with CSS

.oceanContainer {
    position: relative;
    height: 100% /* you can play around with this for your header */
}

You may need to adjust some of the other CSS though

.ocean {
  height: 5%; /* as above, adjust to %, px, (r)em's to your liking */
  bottom: 0;
}

.wave {
  bottom: 0;    /* change top to bottom */
}

.wave:nth-of-type(2) {
  bottom: 0;    /* change top to bottom */
}


问:
How to model in UML when class has an attribute that realizes an interface
I have an interface (MyController). Two other classes implement that interface (ControllerTypeA and ControllerTypeB). Another class (MyFinal) has a field of MyController, so it can contain either ControllerTypeA or ControllerTypeB. How do I model the relationships between MyController, ControllerTypeA, ControllerTypeB, and MyFinal in UML? Here is a working C# program to show what I mean:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ScratchApp
{
    public interface MyController
    {
        void method1(String str);
        void method2(int num);
    }

    public class ControllerTypeA : MyController
    {
        public void method1(String str)
        {
            Console.WriteLine("This is controller type A and the string is: " + str);
        }

        public void method2(int num)
        {
            Console.WriteLine("This is controller type A and the number is: " + num);
        }
    }

    public class ControllerTypeB : MyController
    {
        public void method1(String str)
        {
            Console.WriteLine("This is controller type B and the string is: " + str);
        }

        public void method2(int num)
        {
            Console.WriteLine("This is controller type B and the number is: " + num);
        }
    }

    public class MyFinal
    {
        public MyController myController;

        public MyFinal(MyController mc)
        {
            myController = mc;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            MyFinal mf1 = new MyFinal(new ControllerTypeA());
            MyFinal mf2 = new MyFinal(new ControllerTypeB());

            mf1.myController.method1("From mf1");
            mf1.myController.method2(1);
            mf2.myController.method1("From mf2");
            mf2.myController.method2(2);
            Console.ReadKey();
        }
    }

}
</code>```

答:
Your attribute is of type MyController, so you have an association here. Both ControllerTypes realize this MyController. Graphically it looks like this:

As a side note: the attribute myController appears twice on the diagram. Mea culpa. It should rather be shown only once: either as role name at the end of the association or as attribute inside MyFinal (and then without role name). It's not really wrong this way. But as a matter of style the role name should be preferred here over the attribute in the compartment. This way it's more obvious that it's a distinguished typed attribute.

Body:
I have an interface (MyController). Two other classes implement that interface (ControllerTypeA and ControllerTypeB). Another class (MyFinal) has a field of MyController, so it can contain either ControllerTypeA or ControllerTypeB. How do I model the relationships between MyController, ControllerTypeA, ControllerTypeB, and MyFinal in UML? Here is a working C# program to show what I mean:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ScratchApp
{
    public interface MyController
    {
        void method1(String str);
        void method2(int num);
    }

    public class ControllerTypeA : MyController
    {
        public void method1(String str)
        {
            Console.WriteLine("This is controller type A and the string is: " + str);
        }

        public void method2(int num)
        {
            Console.WriteLine("This is controller type A and the number is: " + num);
        }
    }

    public class ControllerTypeB : MyController
    {
        public void method1(String str)
        {
            Console.WriteLine("This is controller type B and the string is: " + str);
        }

        public void method2(int num)
        {
            Console.WriteLine("This is controller type B and the number is: " + num);
        }
    }

    public class MyFinal
    {
        public MyController myController;

        public MyFinal(MyController mc)
        {
            myController = mc;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            MyFinal mf1 = new MyFinal(new ControllerTypeA());
            MyFinal mf2 = new MyFinal(new ControllerTypeB());

            mf1.myController.method1("From mf1");
            mf1.myController.method2(1);
            mf2.myController.method1("From mf2");
            mf2.myController.method2(2);
            Console.ReadKey();
        }
    }

}


问:
How to send a Status Code 500 in ASP.Net and still write to the response?
I have an ASP.Net single-file web service (a .ashx file containing an IHttpHandler implementation) which needs to be able to return errors as responses with 500 Internal Server Error status codes. This is a relatively straightforward thing to do in PHP:

```<code>header("HTTP/1.1 500 Internal Server Error");
header("Content-Type: text/plain");
echo "Unable to connect to database on $dbHost";
</code>```

The ASP.Net (C#) equivalent should be:

```<code>Context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
Context.Response.ContentType = "text/plain";
Context.Response.Write("Unable to connect to database on " + dbHost);
</code>```

Of course, this doesn't work as expected; instead, IIS intercepts the 500 status code, trashes whatever I've written to the Response object, and sends either debug info or a custom error page, depending on how the app is configured.

My question - how can I suppress this IIS behaviour and send error information directly from my IHttpHandler implementation?

This app is a port from PHP; the client-side is already written, so I'm essentially stuck with this spec. Sending errors with a 200 status code sadly doesn't fit the mould.

Ideally, I need to control the behaviour programmatically, because this is part of an SDK we want to distribute without any "edit this file" and "change this IIS setting" supplementary instructions.

Thanks!

Edit: Sorted. Context.Response.TrySkipIisCustomErrors = true was the ticket. Wow.

答:
You may wish to set a customErrors page (configurable via the web.config).  You can store your content across requests in Session (or via an alternative mechanism) then have asp.net configured to display the custom error page which in-turn displays your custom output.

A word of caution, though: If the 500 is being caused because of a fundamental problem with the application (i.e. StackOverflowException) and you try to display a page that depends on asp.net (i.e. MyCustomErrors.aspx), you may end up in a loop.

For more information, check out this page.

Body:
I have an ASP.Net single-file web service (a .ashx file containing an IHttpHandler implementation) which needs to be able to return errors as responses with 500 Internal Server Error status codes. This is a relatively straightforward thing to do in PHP:

header("HTTP/1.1 500 Internal Server Error");
header("Content-Type: text/plain");
echo "Unable to connect to database on $dbHost";

The ASP.Net (C#) equivalent should be:

Context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
Context.Response.ContentType = "text/plain";
Context.Response.Write("Unable to connect to database on " + dbHost);

Of course, this doesn't work as expected; instead, IIS intercepts the 500 status code, trashes whatever I've written to the Response object, and sends either debug info or a custom error page, depending on how the app is configured.

My question - how can I suppress this IIS behaviour and send error information directly from my IHttpHandler implementation?

This app is a port from PHP; the client-side is already written, so I'm essentially stuck with this spec. Sending errors with a 200 status code sadly doesn't fit the mould.

Ideally, I need to control the behaviour programmatically, because this is part of an SDK we want to distribute without any "edit this file" and "change this IIS setting" supplementary instructions.

Thanks!

Edit: Sorted. Context.Response.TrySkipIisCustomErrors = true was the ticket. Wow.


问:
SteamVR GameObject rigidbody released from grab with zero velocity
I have a trigger collider on my right Vive controller that detects when an "Enemy"-tagged gameobject is within grab range. To create a 'grab,' I add a FixedJoint component to the controller with the Enemy gameobject as the connectedBody. Upon release of the grip, I set connectedBody = null and Destroy(joint) (where joint is the FixedJoint). Whenever I release the selectedObj it falls to the ground with zero velocity. What gives?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Grab : MonoBehaviour {
    private GameObject selectedObj;
    private GameObject grabbableEnemy;
    public Transform gripTransform;
    private SteamVR_TrackedObject trackedObject;
    private SteamVR_Controller.Device _controllerDevice;
    private SteamVR_TrackedController _controller;

    private Vector3[] positions = new Vector3[2]; // positions[0] last frame, positions[1] this frame;
    private Vector3 releasedVelocity;

    void Awake()
    {
        trackedObject = GetComponent<SteamVR_TrackedObject>();
    }

    // Use this for initialization
    void Start () {
        _controllerDevice = SteamVR_Controller.Input((int)trackedObject.index);
        _controller = GetComponent<SteamVR_TrackedController>();
        positions[0] = Vector3.zero;
        positions[1] = Vector3.zero;
        releasedVelocity = new Vector3(-99,-99,-99);

        selectedObj = null;
        grabbableEnemy = null;
    }

    // Update is called once per frame
    void FixedUpdate () {
        if (selectedObj)
        {
            Debug.Log("Updating velocity");
            positions[0] = positions[1];
            positions[1] = selectedObj.transform.position;
            Debug.Log("Selected obj velocity: " + selectedObj.GetComponent<Rigidbody>().velocity);
        }
        if (_controllerDevice.GetPressDown(SteamVR_Controller.ButtonMask.Grip))
        {
            Debug.Log("Gripped");
            if (grabbableEnemy)
            {
                Debug.Log("Grab sequence begins");
                selectedObj = grabbableEnemy;
                Debug.Log(selectedObj.name);
                selectedObj.transform.position = gripTransform.position;
                var joint = gameObject.AddComponent<FixedJoint>();
                joint.connectedBody = selectedObj.GetComponent<Rigidbody>();
            }
        }
        if (_controllerDevice.GetPressUp(SteamVR_Controller.ButtonMask.Grip))
        {
            Debug.Log("Ungripped");
            if (gameObject.GetComponent<FixedJoint>() && selectedObj)
            {
                Debug.Log("Launch sequence begins");
                // currently unused velocity value
                releasedVelocity = (positions[1] - positions[0]) / Time.deltaTime;

                foreach (FixedJoint joint in gameObject.GetComponents<FixedJoint>()) {
                    joint.connectedBody = null;
                    Destroy(joint);
                }
                selectedObj.GetComponent<Rigidbody>().velocity = gameObject.GetComponent<Rigidbody>().velocity;
                selectedObj.GetComponent<Rigidbody>().angularVelocity = gameObject.GetComponent<Rigidbody>().angularVelocity;

                Debug.Log("Released @ release: " + selectedObj.GetComponent<Rigidbody>().velocity);

                // For garbage collection?
                selectedObj = null;
            }
        }
    }

    private void OnTriggerStay(Collider other)
    {
        Debug.Log("Triggered");
        if (other.gameObject.tag == "Enemy")
        {
            grabbableEnemy = other.gameObject;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        grabbableEnemy = null;
    }
}
```

答:
You're calculating releasedVelocity but never setting anything to use its value.

You have:

```<code>selectedObj.GetComponent<Rigidbody>().velocity = gameObject.GetComponent<Rigidbody>().velocity;
</code>```

but this will only set the velocity to the velocity of the GameObject your script is attached to.  I'm guessing you wanted to do:

```<code>selectedObj.GetComponent<Rigidbody>().velocity = releasedVelocity;
</code>```

Body:
You're calculating releasedVelocity but never setting anything to use its value.

You have:

selectedObj.GetComponent<Rigidbody>().velocity = gameObject.GetComponent<Rigidbody>().velocity;

but this will only set the velocity to the velocity of the GameObject your script is attached to.  I'm guessing you wanted to do:

selectedObj.GetComponent<Rigidbody>().velocity = releasedVelocity;


问:
preprocess angular2 upload file
I am building an import tool in angular2. The process is to allow the user to provide a csv file and then fill in how they want the data mapped to the system. So the steps would be
1. Select a local file (using file upload)
2. Instead of sending the file to the server it will be loaded into an array inside angular2 and then displayed on the screen.

Are there any examples of this.

答:
So I was able to prove I could get this to work by using this fiddle that someone posted.
http://jsfiddle.net/thzytf1w/2/

```<code>var fileInput = document.getElementById("csv"),

readFile = function () {
    var reader = new FileReader();
    reader.onload = function () {
        document.getElementById('out').innerHTML = reader.result;
    };
    // start reading the file. When it is done, calls the onload event defined above.
    reader.readAsBinaryString(fileInput.files[0]);
};

fileInput.addEventListener('change', readFile);
</code>```

I'm in the process of getting it to work with angular2

Title: preprocess angular2 upload file

Body:
So I was able to prove I could get this to work by using this fiddle that someone posted.
http://jsfiddle.net/thzytf1w/2/

var fileInput = document.getElementById("csv"),

readFile = function () {
    var reader = new FileReader();
    reader.onload = function () {
        document.getElementById('out').innerHTML = reader.result;
    };
    // start reading the file. When it is done, calls the onload event defined above.
    reader.readAsBinaryString(fileInput.files[0]);
};

fileInput.addEventListener('change', readFile);

I'm in the process of getting it to work with angular2


问:
How do I filter my api results to only show users that's either online or offline?
me again.  I've managed to almost finish this project without help (quite chuffed), but alas I need some aid now.  I'm trying to design a tabbed menu that filter the results of my API calls to: Show all users, Show users only online and show users only offline.  Please help.

Please see my code attached below:

```<code>    <body class="container-fluid">
  <div class="container-fluid center" id="title">
    <h1 class="text-center">My Twitch.TV Favorites List</h1>
    <div class="text-center" id="mainLink"></div>
  </div>
  <div class="container">Filter:
    <ul class="nav nav-tabs">
      <li class="active"><a href="#userDisplay">All</a></li>
      <li id="menuOnline"><a href="#userDisplay">Online</a></li>
      <li id="menuOffline"><a href="#userDisplay">Offline</a></li>
    </ul>
  </div>
  <div class="container-fluid center" id="userDisplay">
    <div class="container col-md-1" id="logo"></div>
    <div class="container col-md-2" id="name"></div>
    <div class="container col-md-8" id="activity"></div>
    <div class="container col-md-1" id="status"></div>
  </div>
</body>
</code>```

...and my JQuery:

```<code>$(document).ready(function() {
  var userArr = [
    "ESL_SC2",
    "OgamingSC2",
    "cretetion",
    "freecodecamp",
    "habathcx",
    "RobotCaleb",
    "noobs2ninjas",
    "Blackbat023",
    "thewildfirecommunity"
  ];

  for (var i = 0; i < userArr.length; i++) {
    var usersData ="https://wind-bow.gomix.me/twitch-api/users/" +userArr[i] +"?callback=?";
    var channelsData ="https://wind-bow.gomix.me/twitch-api/channels/" +userArr[i] +"?callback=?";
    var streamsData ="https://wind-bow.gomix.me/twitch-api/streams/" +userArr[i] +"?callback=?";

    $.getJSON(channelsData, function(users) {
      //console.log(users);
      $("#userDisplay").append(function(){
      $("#logo").append("<img src=" +users.logo +' class="img-resonsive img-thumbnail" alt="Logo" />');
      $("#name").append('<h4>' +users.name +"</h4> (" +users.updated_at +")<br><br>");
      $("#activity").append('Acitvity: <h4>'+users.status +"</h4><br>");
      });
    });

    $.getJSON(streamsData, function(streams) {
      //console.log(streams);
      var streamData = streams.stream;
      if (streamData === null) {
        $("#status").append('<img src="http://i.imgur.com/vz0GuT9.png" class="img-responsive img-thumbnail" alt="Offline" />'
        );
      } else {
        $("#status").append('<img src="http://i.imgur.com/4jbBgtn.png" class="img-responsive img-thumbnail" alt="Online" />'
        );
      }

      $(".active").onClick(function(){
        window.reload;
      });
      $("#menuOnline").onClick(function(){
        var statArr = $.grep(userArr, function(element, index){
          return(streamData != null);
        });
      });
      $("#menuOffline").onClick(function(){
        var statArr = $.grep(userArr, function(element, index){
          return(streamData == null);
        });
      });
    });
  }

  $.getJSON('https://wind-bow.gomix.me/twitch-api/streams/freecodecamp?callback=?', function(fccData){
    //console.log(fccData);
    if(fccData.stream === null){
      $("#mainLink").append('<h2><a href="https://www.twitch.tv/freecodecamp" target="blank">We are currently offline</a></h2>');
    } else {
      $("#mainLink").append('<h2><a href="https://www.twitch.tv/freecodecamp" target="blank">Please join us on Twitch.TV</a></h2>');
    }
  });

});
</code>```

答:
When you're creating the HTML for the users, give them a class that indicates whether they're online or offline.

```<code>  if (streamData === null) {
    $("#status").append('<img src="http://i.imgur.com/vz0GuT9.png" class="img-responsive img-thumbnail user-offline" alt="Offline" />'
    );
  } else {
    $("#status").append('<img src="http://i.imgur.com/4jbBgtn.png" class="img-responsive img-thumbnail user-online" alt="Online" />'
    );
  }
</code>```

Then you can use these classes to hide or show the appropriate users:

```<code>$("#menuOnline").click(function() {
    $("#status .user-online").show();
    $("#status .user-offline").hide();
});
$("#menuOffline").click(function() {
    $("#status .user-offline").show();
    $("#status .user-online").hide();
});
</code>```

These click handlers should be at the top level of your $(document).ready() function, not inside the for loop.

Body:
me again.  I've managed to almost finish this project without help (quite chuffed), but alas I need some aid now.  I'm trying to design a tabbed menu that filter the results of my API calls to: Show all users, Show users only online and show users only offline.  Please help.

Please see my code attached below:

My Twitch.TV Favorites List

Filter:

All

Online

Offline

...and my JQuery:

$(document).ready(function() {
  var userArr = [
    "ESL_SC2",
    "OgamingSC2",
    "cretetion",
    "freecodecamp",
    "habathcx",
    "RobotCaleb",
    "noobs2ninjas",
    "Blackbat023",
    "thewildfirecommunity"
  ];

  for (var i = 0; i < userArr.length; i++) {
    var usersData ="https://wind-bow.gomix.me/twitch-api/users/" +userArr[i] +"?callback=?";
    var channelsData ="https://wind-bow.gomix.me/twitch-api/channels/" +userArr[i] +"?callback=?";
    var streamsData ="https://wind-bow.gomix.me/twitch-api/streams/" +userArr[i] +"?callback=?";

    $.getJSON(channelsData, function(users) {
      //console.log(users);
      $("#userDisplay").append(function(){
      $("#logo").append("');
      $("#name").append('
' +users.name +"
 (" +users.updated_at +")

");
      $("#activity").append('Acitvity:
'+users.status +"

");
      });
    });

    $.getJSON(streamsData, function(streams) {
      //console.log(streams);
      var streamData = streams.stream;
      if (streamData === null) {
        $("#status").append(''
        );
      } else {
        $("#status").append(''
        );
      }

      $(".active").onClick(function(){
        window.reload;
      });
      $("#menuOnline").onClick(function(){
        var statArr = $.grep(userArr, function(element, index){
          return(streamData != null);
        });
      });
      $("#menuOffline").onClick(function(){
        var statArr = $.grep(userArr, function(element, index){
          return(streamData == null);
        });
      });
    });
  }

  $.getJSON('https://wind-bow.gomix.me/twitch-api/streams/freecodecamp?callback=?', function(fccData){
    //console.log(fccData);
    if(fccData.stream === null){
      $("#mainLink").append('
We are currently offline
');
    } else {
      $("#mainLink").append('
Please join us on Twitch.TV
');
    }
  });

});

Body:
When you're creating the HTML for the users, give them a class that indicates whether they're online or offline.

  if (streamData === null) {
    $("#status").append('<img src="http://i.imgur.com/vz0GuT9.png" class="img-responsive img-thumbnail user-offline" alt="Offline" />'
    );
  } else {
    $("#status").append('<img src="http://i.imgur.com/4jbBgtn.png" class="img-responsive img-thumbnail user-online" alt="Online" />'
    );
  }

Then you can use these classes to hide or show the appropriate users:

$("#menuOnline").click(function() {
    $("#status .user-online").show();
    $("#status .user-offline").hide();
});
$("#menuOffline").click(function() {
    $("#status .user-offline").show();
    $("#status .user-online").hide();
});

These click handlers should be at the top level of your $(document).ready() function, not inside the for loop.


问:
How to check if Vuex state object is empty
I have an initial empty object in Vuex state that gets updated from an API.

```<code>const state = {
  someObject: {}
}
</code>```

How do I check if the object is empty in my template?

```<code><template>
  <div v-if="someObject">
    This should not display when someObject is empty.
  </div>
</template>
</code>```

What is best practice for checking if a state object is set/empty or not?

Should i set someObject: null/undefined/false initially, even if it expects to be updated with a new object?

Does it make sense to do a check in getters?

```<code>export const someObject = state => Object.getOwnPropertyNames(state.someObject).length == 0 ? state.someObject : false
</code>```

答:
Depending  on particular use case I would ether set it to null/undefined or make if check by some required object property like v-if='someObject.id' </p>

<p>Anything else seams as unnecessary complication. </p>

Body:
I have an initial empty object in Vuex state that gets updated from an API.

const state = {
  someObject: {}
}

How do I check if the object is empty in my template?

<template>

    This should not display when someObject is empty.

</template>

What is best practice for checking if a state object is set/empty or not?

Should i set someObject: null/undefined/false initially, even if it expects to be updated with a new object?

Does it make sense to do a check in getters?

export const someObject = state => Object.getOwnPropertyNames(state.someObject).length == 0 ? state.someObject : false

Body:
Depending  on particular use case I would ether set it to null/undefined or make if check by some required object property like v-if='someObject.id'

Anything else seams as unnecessary complication.