问:
How to stop a large query if it has too many rows in PostgreSQL using Jdbc?
We run user submitted queries which can potentially return a large result set.

In order to avoid memory issues, we would like to detect these cases and cancel the query. The user then is expected to modify the query.

We already use PreparedStatement#setFetchSize() to scroll the result set and process a large result set incrementally.
However, when the result set is too large, we would like to avoid bringing even the first results over the network or any other unnecessary work as much as possible on the client side and on the database side.

Doing a SELECT COUNT(*)... beforehand just degrades the performance of the expected case where the queries behave nicely in general.

Is there a way for postgres to tell the expected result set size?

答:
Take a look here.

They are doing an estimate with a database procedure:

```<code>CREATE FUNCTION count_estimate(query text) RETURNS INTEGER AS
$func$
DECLARE
    rec   record;
    ROWS  INTEGER;
BEGIN
    FOR rec IN EXECUTE 'EXPLAIN ' || query LOOP
        ROWS := SUBSTRING(rec."QUERY PLAN" FROM ' rows=([[:digit:]]+)');
        EXIT WHEN ROWS IS NOT NULL;
    END LOOP;

    RETURN ROWS;
END
$func$ LANGUAGE plpgsql;
</code>```

It uses the EXPLAIN command of PGSQL to estimate the returned rowcount.

Body:
Take a look here.

They are doing an estimate with a database procedure:

CREATE FUNCTION count_estimate(query text) RETURNS INTEGER AS
$func$
DECLARE
    rec   record;
    ROWS  INTEGER;
BEGIN
    FOR rec IN EXECUTE 'EXPLAIN ' || query LOOP
        ROWS := SUBSTRING(rec."QUERY PLAN" FROM ' rows=([[:digit:]]+)');
        EXIT WHEN ROWS IS NOT NULL;
    END LOOP;

    RETURN ROWS;
END
$func$ LANGUAGE plpgsql;

It uses the EXPLAIN command of PGSQL to estimate the returned rowcount.


来源: stackexchange

问:
Open image in modal (link in one div img in another)
I have a dot-front that when hovered over it flips and shows a dot-back with a link. If I click the link it should open a modal with a preview image.
I think that the problem is in the jquery where I wrote closest and find, but I don't know how to fix it.

$(function() {
  $('.pop').on('click', function() {
    console.log("pop");
    $('#imagepreview').attr('src', $('#modal-icon01').closest(".div-img").find('.front img').attr('src'));
    $('#imagemodal').modal('show');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.div-img {
  display: inline-block;
  height: 200px;
  width: 200px;
  cursor: pointer;
}

.div-img img {
  object-fit: cover;
  width: 240px;
  margin-left: -20px;
}

.div-img span {
  display: table-cell;
  vertical-align: middle;
  height: 200px;
}

.div-img > .front {
  position: absolute;
  transform: perspective( 600px) rotateY( 0deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img > .back {
  position: absolute;
  transform: perspective( 600px) rotateY( 180deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img:hover > .front {
  transform: perspective( 600px) rotateY( -180deg);
}

.div-img:hover > .back {
  transform: perspective( 600px) rotateY( 0deg);
}</code>```

    Pizza Hut Delivery
(De ce Pizza Hut)

        <button type="button" class="close" data-dismiss="modal">×Close</button>

```

答:
I Dont see the id called modal-icon01 but base on your html file you can access the img through this:

```<code>$('.pop').on('click', function() {
        console.log("pop");
        var image = $(".div-img").find('.front').find('img').attr('src');
        $('#imagepreview').attr('src', image);
        $('#imagemodal').modal('show');
    });
</code>```

Then dont forget to check if your jquery.js is attact before your script.

Hope it will help.

ContentLicense: CC BY-SA 3.0

Body:
I have a dot-front that when hovered over it flips and shows a dot-back with a link. If I click the link it should open a modal with a preview image.
I think that the problem is in the jquery where I wrote closest and find, but I don't know how to fix it.

$(function() {
  $('.pop').on('click', function() {
    console.log("pop");
    $('#imagepreview').attr('src', $('#modal-icon01').closest(".div-img").find('.front img').attr('src'));
    $('#imagemodal').modal('show');
  });
});

.div-img {
  display: inline-block;
  height: 200px;
  width: 200px;
  cursor: pointer;
}

.div-img img {
  object-fit: cover;
  width: 240px;
  margin-left: -20px;
}

.div-img span {
  display: table-cell;
  vertical-align: middle;
  height: 200px;
}

.div-img > .front {
  position: absolute;
  transform: perspective( 600px) rotateY( 0deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img > .back {
  position: absolute;
  transform: perspective( 600px) rotateY( 180deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img:hover > .front {
  transform: perspective( 600px) rotateY( -180deg);
}

.div-img:hover > .back {
  transform: perspective( 600px) rotateY( 0deg);
}

    Pizza Hut Delivery
(De ce Pizza Hut)

        <button type="button" class="close" data-dismiss="modal">×Close</button>

Body:
I Dont see the id called modal-icon01 but base on your html file you can access the img through this:

$('.pop').on('click', function() {
        console.log("pop");
        var image = $(".div-img").find('.front').find('img').attr('src');
        $('#imagepreview').attr('src', image);
        $('#imagemodal').modal('show');
    });

Then dont forget to check if your jquery.js is attact before your script.

Hope it will help.


问:
Java Program to display sport played by player on user input and player name on user input sport
```<code>Player 1 -- chess , hockey , carom
Player 2 -- cricket , badminton , carom
Player 3 -- ludo , badminton , pool
Player 4 -- Table tennis , badminton , snooker
</code>```

Need to display sport played on user input player name

Need to display on user input player name , sport played by him

User can add player name and also can add more sport to individual player

Asked in interview
Got stuck .. Please help with core java
Thanks in advance

答:
here is your solution :</p>

```<code>package com.sujit;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Sport {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter player name : ");
        String playerName = sc.next();
        List<String> list = getSportByPlayerName(playerName);
        for (String string : list) {
            System.out.println(string);
        }
    }

    private static List<String> getSportByPlayerName(String playerName) {
        List<String> listOfSports = new ArrayList<>();
        if(playerName.equalsIgnoreCase("player1")) {
            listOfSports.add("chess");
            listOfSports.add("hockey");
            listOfSports.add("carrom");
            return listOfSports;
        }
        else if(playerName.equalsIgnoreCase("player2")) {
            listOfSports.add("cricket");
            listOfSports.add("badminton");
            listOfSports.add("carrom");
            return listOfSports;
                }
        else if(playerName.equalsIgnoreCase("player3")) {
            listOfSports.add("ludo");
            listOfSports.add("badminton");
            listOfSports.add("pool");
            return listOfSports;
        }
        else if(playerName.equalsIgnoreCase("player4")) {
            listOfSports.add("table tennis");
            listOfSports.add("snooker");
            listOfSports.add("badminton");
            return listOfSports;
        }
        else
            return null;
    }
}
</code>```

Body:
Player 1 -- chess , hockey , carom
Player 2 -- cricket , badminton , carom
Player 3 -- ludo , badminton , pool
Player 4 -- Table tennis , badminton , snooker

Need to display sport played on user input player name

Need to display on user input player name , sport played by him

User can add player name and also can add more sport to individual player

Asked in interview
Got stuck .. Please help with core java
Thanks in advance

Body:
here is your solution :

package com.sujit;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Sport {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter player name : ");
        String playerName = sc.next();
        List<String> list = getSportByPlayerName(playerName);
        for (String string : list) {
            System.out.println(string);
        }
    }

    private static List<String> getSportByPlayerName(String playerName) {
        List<String> listOfSports = new ArrayList<>();
        if(playerName.equalsIgnoreCase("player1")) {
            listOfSports.add("chess");
            listOfSports.add("hockey");
            listOfSports.add("carrom");
            return listOfSports;
        }
        else if(playerName.equalsIgnoreCase("player2")) {
            listOfSports.add("cricket");
            listOfSports.add("badminton");
            listOfSports.add("carrom");
            return listOfSports;
                }
        else if(playerName.equalsIgnoreCase("player3")) {
            listOfSports.add("ludo");
            listOfSports.add("badminton");
            listOfSports.add("pool");
            return listOfSports;
        }
        else if(playerName.equalsIgnoreCase("player4")) {
            listOfSports.add("table tennis");
            listOfSports.add("snooker");
            listOfSports.add("badminton");
            return listOfSports;
        }
        else
            return null;
    }
}


问:
Best way to pass the value in Some to a function with a default parameter value?
I have a function from a third party library as below :

```<code>def myfunction(input:String = "some constant value")
</code>```

I have a

```<code>myinput:Option[String]
</code>```

with me and I need to pass the function. Right now I am doing this:

```<code>myfunction(myinput.getOrElse("some constant value"))
</code>```

But I dont want to look into the third party library for its default value.
What is the ideal way to do this?

答:
I don't know if it is the best way, but you can do something like this:

```<code>if (myinput.isDefined){
  myfunction(myinput.get)
}
else{
  myfunction()
}
</code>```

So if your myinput contains a value, use it, otherwise use the default-value.

Clearly, if you do this very often, you should outsource it to a function to just have one line at each call.

Body:
I have a function from a third party library as below :

def myfunction(input:String = "some constant value")

I have a

myinput:Option[String]

with me and I need to pass the function. Right now I am doing this:

myfunction(myinput.getOrElse("some constant value"))

But I dont want to look into the third party library for its default value.
What is the ideal way to do this?

Body:
I don't know if it is the best way, but you can do something like this:

if (myinput.isDefined){
  myfunction(myinput.get)
}
else{
  myfunction()
}

So if your myinput contains a value, use it, otherwise use the default-value.

Clearly, if you do this very often, you should outsource it to a function to just have one line at each call.


问:
Click Button in ExtendedSelenium2Library selects button very slow
I am using 'Click Button' from ExtendedSelenium2Library to select Login button on my login page.

But is takes more than 12 seconds to select the Button. With Selenium2library it works immediately.
I prefer using Extendedselenium2 instead of selenium2. How to make it click faster?

答:
TL;DR

Click Button    ${button}    True

Seems you already figured this out, but I had the same problem and it took some time to figure it out. So this is for future reference.

ExtendedSelenium2Library waits for AngularJs to be ready to process the next request. As can be seen here ExtendedSelenium2Library (and like you already said). So by using these commands that wait for Angular to be ready, when you are not using AngularJS, it is necessary for the timeout to kick in which is about the 12-14 seconds you experienced. To still be able to use the extended library and have "fast clicking" you need to set the argument "skip ready" to "True".

Example:

Click Element    xpath=//a[@href="#/motor"]

Becomes

Click Element    xpath=//a[@href="#/motor"]    True


问:
Converting Æ to "Ae" In PHP With Str_replace?
For reasons justified by business logic, I need to convert the character "Æ" to "Ae" in a string.  However, despite the fact that mb_detect_encoding() tells me the string is UTF-8, I can't figure out how to do this.  (And for other reasons of business logic, it would be an issue to htmlentities() the string before replacing it, as other Google searches have suggested.)

What I tried first was this, using the test string "Æther":

```<code>return str_replace("Æ", 'Ae', $string);
</code>```

Unfortunately, that doesn't actually find the Æ in the text, returning "Æther".

```<code>return str_replace(chr(195), 'Ae', $string);
</code>```

That finds the Æ and replaces it, but adds an unknown character afterwards, changing it to the not-usable "Ae�ther."  So I tried this:

```<code>$ae_character = mb_convert_encoding('&#' . intval(195) . ';', 'UTF-8', 'HTML-ENTITIES');
return str_replace($ae_character, 'Ae', $string);
</code>```

Which again failed to find the Æ character in the string.  I know it's a UTF-8 issue of some sort, but I'm honestly stumped as to how to search for and replace this without adding the extra character afterwards.  Any ideas?

答:
```<code><?php
$x = 'Æmystr';
print str_replace('Æ', 'AE', $x); // prints: AEmystr
?>
</code>```

That code works just fine, what I believe you're missing is changing the encoding of your file. Your .php file should be encoded in UTF-8 or UNICODE. This can be done in some (text) editors or IDEs, i.e Eclipse, EditPlus, Notepad++ etc... Even Notepad on windows 7.

When saving bring up the Save/Save As dialog, and normally near the Save button there is an Encoding dropdown/radio buttons, that lets you choose between ANSI and UTF-8 (and others).

On *nix I believe most editors have it, just not sure of the locations. If after you do it and get it working, then edit/save with an editor that just does ANSI it'll overwrite it with an unknown char etc...

As to why the below code didn't work.

```<code>return str_replace(chr(195), 'Ae', $string);
</code>```

It's because a unicode char is normally 2 chars put together. So what you have above is just the start of the unicode char. try this:

```<code>print str_replace(chr(195).chr(134), 'AE', $x);
</code>```

That should replace it as well and might even be preferred as you (might|do) not have to change the file encoding.

ContentLicense: CC BY-SA 2.5

Body:
For reasons justified by business logic, I need to convert the character "Æ" to "Ae" in a string.  However, despite the fact that mb_detect_encoding() tells me the string is UTF-8, I can't figure out how to do this.  (And for other reasons of business logic, it would be an issue to htmlentities() the string before replacing it, as other Google searches have suggested.)

What I tried first was this, using the test string "Æther":

return str_replace("Æ", 'Ae', $string);

Unfortunately, that doesn't actually find the Æ in the text, returning "Æther".

return str_replace(chr(195), 'Ae', $string);

That finds the Æ and replaces it, but adds an unknown character afterwards, changing it to the not-usable "Ae�ther."  So I tried this:

$ae_character = mb_convert_encoding('&#' . intval(195) . ';', 'UTF-8', 'HTML-ENTITIES');
return str_replace($ae_character, 'Ae', $string);

Which again failed to find the Æ character in the string.  I know it's a UTF-8 issue of some sort, but I'm honestly stumped as to how to search for and replace this without adding the extra character afterwards.  Any ideas?

Body:
<?php
$x = 'Æmystr';
print str_replace('Æ', 'AE', $x); // prints: AEmystr
?>

That code works just fine, what I believe you're missing is changing the encoding of your file. Your .php file should be encoded in UTF-8 or UNICODE. This can be done in some (text) editors or IDEs, i.e Eclipse, EditPlus, Notepad++ etc... Even Notepad on windows 7.

When saving bring up the Save/Save As dialog, and normally near the Save button there is an Encoding dropdown/radio buttons, that lets you choose between ANSI and UTF-8 (and others).

On *nix I believe most editors have it, just not sure of the locations. If after you do it and get it working, then edit/save with an editor that just does ANSI it'll overwrite it with an unknown char etc...

As to why the below code didn't work.

return str_replace(chr(195), 'Ae', $string);

It's because a unicode char is normally 2 chars put together. So what you have above is just the start of the unicode char. try this:

print str_replace(chr(195).chr(134), 'AE', $x);

That should replace it as well and might even be preferred as you (might|do) not have to change the file encoding.


问:
"Save as" from Google chrome Developer Tools Network tab missing
If I right click an entry in the network tab in google chromes developer tools network tab, I get theese alternatives:

Copy (open a sub menu with Copy Link Address, Copy Request headers, Copy Response headers, Copy response, Copy as cURL (cmd), Copy as cURL (bash), Copy all as cURL (cmd), Copy all as cURL (bash), Copy all as HAR)

Save as HAR with content

Clear browser cache

Clear browser cookies

Block request URL

Block request Domain

Open in Sources panel

Open in new tab

Questions

Where is "Save as"?

Can I customize this menu to remove unneeded entries?

Is the pluginability letting me do those things?

答:
You can save the whole list of requests/responses by using 'Save as HAR with content', but you can't save an individual one.

As for customising the context menu on the Network panel, or any other built-in panel, this isn't possible. I answered a similar question on the Elements panel last year, and found, after looking at the source code, that there were no hooks available. See https://stackoverflow.com/a/38050351

You can create context menus on custom panels, via chrome.contextMenus. The Network panel has an API that exposes the requests data (getHar). You could perhaps build your own DevTools panel based on this data.


问:
Pass variable to included layout via xml
I want to include a simple layout and pass a static variable to it (string resource here). I followed multiple examples with no luck.

main_layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data></data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <include android:id="@+id/first_included" layout="@layout/included" app:theValue="@string/firstValue" />
        <include android:id="@+id/first_included" layout="@layout/included" app:theValue="@string/secondValue" />
    </LinearLayout>
</layout>
</code>```

included.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable name="theValue" type="String" />
    </data>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{theValue}"/>
</layout>
</code>```

This gives me the compile error

Error: No resource identifier found for attribute 'theValue' in
  package 'com.just.example'

I do use databinding in the rest of the project and everything works fine. I could set the value programmatically but this one is static, I want to be able to set it in the layout file.

答:
In general you have to assign a data binding statement to the attribute you want to use it with. If the attribute itself is well supported with the default XML definitions, it won't fail. But when there's no definition for the attribute (other than the explicit and implicit ones with data binding), the attribute can't be handled and you'll find the error you got.

So whenever you use data binding specific attributes like with the variables of an included layout, you need to define it as

```<code>app:myAttr="@{...}"
</code>```

The Expression Language itself has some nice shortcuts for resources defined. So in you case you can just @string/firstValue inside your expression. This will be resolved to a String which is in turn assigned to the variable theValue in your sublayout.

Body:
I want to include a simple layout and pass a static variable to it (string resource here). I followed multiple examples with no luck.

main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data></data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <include android:id="@+id/first_included" layout="@layout/included" app:theValue="@string/firstValue" />
        <include android:id="@+id/first_included" layout="@layout/included" app:theValue="@string/secondValue" />
    </LinearLayout>
</layout>

included.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable name="theValue" type="String" />
    </data>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{theValue}"/>
</layout>

This gives me the compile error

Error: No resource identifier found for attribute 'theValue' in
  package 'com.just.example'

I do use databinding in the rest of the project and everything works fine. I could set the value programmatically but this one is static, I want to be able to set it in the layout file.

Body:
In general you have to assign a data binding statement to the attribute you want to use it with. If the attribute itself is well supported with the default XML definitions, it won't fail. But when there's no definition for the attribute (other than the explicit and implicit ones with data binding), the attribute can't be handled and you'll find the error you got.

So whenever you use data binding specific attributes like with the variables of an included layout, you need to define it as

app:myAttr="@{...}"

The Expression Language itself has some nice shortcuts for resources defined. So in you case you can just @string/firstValue inside your expression. This will be resolved to a String which is in turn assigned to the variable theValue in your sublayout.


问:
How to know in BroadcastReceiver if App is running on foreground?
I am working in application that needs make a synchronization every night. I use Alarm Manager that calls a BroadcastReceiver at the hour that I want. The problem is that I cant make a synchronization if the application is running in foreground to avoid losing data. So I need to know in Broadcast Receiver if the app is running in foreground to cancel this synchronization.

I tried solutions that I found in StackOverflow:
Checking if an Android application is running in the background
But this parameter is always false in BroadcastReceiver, but true in activites.

Can anyone tell me which is the problem? What am I doing bad?

Really thanks!

答:
in case you don't want to do anything if app in foreground you could simply turn off the receiver on your activity onStart method:

```<code>ComponentName receiver = new ComponentName(context, MyReceiver.class);
context.getPackageManager().setComponentEnabledSetting(receiver,
        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
        PackageManager.DONT_KILL_APP);
</code>```

and you could turn it on onStop method:

```<code>ComponentName receiver = new ComponentName(context, MyReceiver.class);
context.getPackageManager().setComponentEnabledSetting(receiver,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP);
</code>```

and if receiver is turned off, no alarms will come to it, and your code will not be executed

Body:
in case you don't want to do anything if app in foreground you could simply turn off the receiver on your activity onStart method:

ComponentName receiver = new ComponentName(context, MyReceiver.class);
context.getPackageManager().setComponentEnabledSetting(receiver,
        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
        PackageManager.DONT_KILL_APP);

and you could turn it on onStop method:

ComponentName receiver = new ComponentName(context, MyReceiver.class);
context.getPackageManager().setComponentEnabledSetting(receiver,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP);

and if receiver is turned off, no alarms will come to it, and your code will not be executed


问:
React – the right way to pass form element state to sibling/parent elements?

Suppose I have a React class P, which renders two child classes, C1 and C2.

C1 contains an input field. I'll refer to this input field as Foo.

My goal is to let C2 react to changes in Foo.

I've come up with two solutions, but neither of them feels quite right.

First solution:

Assign P a state, state.input.

Create an onChange function in P, which takes in an event and sets state.input.

Pass this onChange to C1 as a props, and let C1 bind this.props.onChange to the onChange of Foo.

This works. Whenever the value of Foo changes, it triggers a setState in P, so P will have the input to pass to C2.

But it doesn't feel quite right for the same reason: I'm setting the state of a parent element from a child element. This seems to betray the design principle of React: single-direction data flow.

Is this how I'm supposed to do it, or is there a more React-natural solution?

Second solution:

Just put Foo in P.

But is this a design principle I should follow when I structure my app—putting all form elements in the render of the highest-level class?

Like in my example, if I have a large rendering of C1, I really don't want to put the whole render of C1 to render of P just because C1 has a form element.

How should I do it?

答: You should learn Redux and ReactRedux library.It will structure your states and props in one store and you can access them later in your components .</p>


问:
Change (local) in SQL Management Studio 2008
During the installation of SQL Management Studio 2008, I set up the default server to be (local).

Now, I want to either change this to (local)/mySubdirectoryName, or create a new one that is located at (local)/mySubdirectoryName, but I cannot see where this can be done.

Is there a way that I can do this?

Thanks.

答:
In order to change the name of a SQL Server instance, you need to reinstall it. There's no other way to do this.

So in your case, your best bet would be to probably just install a new instance of SQL Server under a new specific instance name.


问:
Swift setting object's properties to nil
I am new to Swift and I'm facing a problem.

My problem is quite simple:

I have a simple class with some object in it (declared in their own file) :

```<code>class Outcome : NSObject {
   var foo : SomeClass?
   var doo : OtherClass?
   var roo: AnotherClass?

}
</code>```

What I want to do is when an object of the class is set, set all the other object to nil, so I used the didSet feature and add a resetData method that is supposed to set all the object to nil, except the one I just set.

The class looks like this :

```<code>    class Outcome : NSObject {
       var foo : SomeClass? {
    didSet { self.resetData(exeption: foo!) }
       var doo : OtherClass? {
           didSet { self.resetData(exeption: doo!) }
      }
       var roo: AnotherClass? {
            didSet { self.resetData(exeption: roo!) }
       }

    func resetData (exeption: AnyObject) {

    var allObjects = NSArray(array: [self.foo ?? NSNull(), self.doo ?? NSNull(), self.roo ?? NSNull()])

    for var anObject in (allObjects as NSArray as! [NSObject?]) {
        if exeption.isEqual(anObject) == false  {
            anObject = nil
        }
    }
   }
 }
</code>```

The idea of the resetData method is to set all the objects to nil except the exception (which is the object I just set in my view controller)

The code is working and the instruction anObject = nil is executed, but the problem is that when I set a set a beakpoint I can clearly see that the object is not nil, so this does not do what I want.

I think it is a question of reference, I do not really get it, is it possible to set an object to nil ? Is there a better way to do this ?

答:
As mentioned in the comments, your loop does not modify the class
properties at all, only the anObject loop variable.

If the intention is to define a type which holds either an instance
of SomeClass or an instance of OtherClass or an instance
of AnotherClass then an enum would be a better choice:

```<code>enum Outcome {
    case foo(SomeClass)
    case doo(OtherClass)
    case roo(AnotherClass)
}
</code>```

Usage example:

```<code>var outCome = Outcome.foo(SomeClass())
print(outCome) // foo(<SomeClass: 0x1009000b0>)
// ...

outCome = .doo(OtherClass())
print(outCome) // doo(<OtherClass: 0x100d00540>)
</code>```

Body:
I am new to Swift and I'm facing a problem.

My problem is quite simple:

I have a simple class with some object in it (declared in their own file) :

class Outcome : NSObject {
   var foo : SomeClass?
   var doo : OtherClass?
   var roo: AnotherClass?

}

What I want to do is when an object of the class is set, set all the other object to nil, so I used the didSet feature and add a resetData method that is supposed to set all the object to nil, except the one I just set.

The class looks like this :

    class Outcome : NSObject {
       var foo : SomeClass? {
    didSet { self.resetData(exeption: foo!) }
       var doo : OtherClass? {
           didSet { self.resetData(exeption: doo!) }
      }
       var roo: AnotherClass? {
            didSet { self.resetData(exeption: roo!) }
       }

    func resetData (exeption: AnyObject) {

    var allObjects = NSArray(array: [self.foo ?? NSNull(), self.doo ?? NSNull(), self.roo ?? NSNull()])

    for var anObject in (allObjects as NSArray as! [NSObject?]) {
        if exeption.isEqual(anObject) == false  {
            anObject = nil
        }
    }
   }
 }

The idea of the resetData method is to set all the objects to nil except the exception (which is the object I just set in my view controller)

The code is working and the instruction anObject = nil is executed, but the problem is that when I set a set a beakpoint I can clearly see that the object is not nil, so this does not do what I want.

I think it is a question of reference, I do not really get it, is it possible to set an object to nil ? Is there a better way to do this ?

Body:
As mentioned in the comments, your loop does not modify the class
properties at all, only the anObject loop variable.

If the intention is to define a type which holds either an instance
of SomeClass or an instance of OtherClass or an instance
of AnotherClass then an enum would be a better choice:

enum Outcome {
    case foo(SomeClass)
    case doo(OtherClass)
    case roo(AnotherClass)
}

Usage example:

var outCome = Outcome.foo(SomeClass())
print(outCome) // foo(<SomeClass: 0x1009000b0>)
// ...

outCome = .doo(OtherClass())
print(outCome) // doo(<OtherClass: 0x100d00540>)


问:
Draw Points / Lines using MITK
I need some help with MITK. I am trying to draw points and lines (actually my goal is display a virtual colonoscopy centerline), under MITK. I created a vtkPolyData which contains the data of the centerline. This is wrapped into a mitk::Surface structure in order to add in a mitk::StandaloneDataStorage:

```<code>mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New();
mitk::DataNode::Pointer dn = mitk::DataNode::New();
mitk::Surface::Pointer aSurface = mitk::Surface::New();
aSurface->Initialize();
aSurface->SetVtkPolyData(polydata); //polydata is a vtkPolyData which contains data
dn->SetData(aSurface);
ds->Add(dn);
renderWindow.GetRenderer()->SetDataStorage(ds); //renderWindow is a QmitkRenderWindow
</code>```

Now, nothing is shown. I assume that something is missing (e.g. indicate the type of rendering).
The camera and its orientation are placed correctly due that I am drawing something else in the same location.
Thanks!

答:
I solved!
The trick is put the function mitk::RenderingManager::GetInstance()->RequestUpdateAll(); every time that you want to render something :-) or when an event/callback is invoked

Title: Draw Points / Lines using MITK

Body:
I need some help with MITK. I am trying to draw points and lines (actually my goal is display a virtual colonoscopy centerline), under MITK. I created a vtkPolyData which contains the data of the centerline. This is wrapped into a mitk::Surface structure in order to add in a mitk::StandaloneDataStorage:

mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New();
mitk::DataNode::Pointer dn = mitk::DataNode::New();
mitk::Surface::Pointer aSurface = mitk::Surface::New();
aSurface->Initialize();
aSurface->SetVtkPolyData(polydata); //polydata is a vtkPolyData which contains data
dn->SetData(aSurface);
ds->Add(dn);
renderWindow.GetRenderer()->SetDataStorage(ds); //renderWindow is a QmitkRenderWindow

Now, nothing is shown. I assume that something is missing (e.g. indicate the type of rendering).
The camera and its orientation are placed correctly due that I am drawing something else in the same location.
Thanks!


问:
nginx passenger standalone prevent proxy_pass on subdirectory
i'm running nginx as reverse proxy for passenger standalone rails server.
I need to set up root / location on passenger standalone port (5000) but few other subdirectories must be served by "pure" nginx.
I'm trying configurations like

```<code>server {
    listen 443;

    root /path/to/rails/public;

    server_name example.com;

    ssl on;
    # ... some ssl config

    # this is used for passenger standalone on port 5000
    location / {
            proxy_pass https://127.0.0.1:5000;
            proxy_http_version 1.1;
            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_buffering off;
    }

    # this is not passenger standalone!
    location /subdir {
            proxy_pass https://127.0.0.1;
            auth_basic "Restricted access area authorization needed.";
            auth_basic_user_file /path/to/.htpasswd;
    }
</code>```

}

but https://example.com/subdir/ return always 404 error.
Any tips to fix it?

答:
Move the location directive for /subdir above the root location's direction.
The request paths are matched in the order defined in the configuration.

```<code>server {
    listen 443;

    root /path/to/rails/public;

    server_name example.com;

    ssl on;
    # ... some ssl config

    # this is not passenger standalone!
    location /subdir {
            proxy_pass https://127.0.0.1;
            auth_basic "Restricted access area authorization needed.";
            auth_basic_user_file /path/to/.htpasswd;
    }
    # this is used for passenger standalone on port 5000
    location / {
            proxy_pass https://127.0.0.1:5000;
            proxy_http_version 1.1;
            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_buffering off;
    }
}
</code>```

Body:
i'm running nginx as reverse proxy for passenger standalone rails server.
I need to set up root / location on passenger standalone port (5000) but few other subdirectories must be served by "pure" nginx.
I'm trying configurations like

server {
    listen 443;

    root /path/to/rails/public;

    server_name example.com;

    ssl on;
    # ... some ssl config

    # this is used for passenger standalone on port 5000
    location / {
            proxy_pass https://127.0.0.1:5000;
            proxy_http_version 1.1;
            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_buffering off;
    }

    # this is not passenger standalone!
    location /subdir {
            proxy_pass https://127.0.0.1;
            auth_basic "Restricted access area authorization needed.";
            auth_basic_user_file /path/to/.htpasswd;
    }

}

but https://example.com/subdir/ return always 404 error.
Any tips to fix it?

Body:
Move the location directive for /subdir above the root location's direction.
The request paths are matched in the order defined in the configuration.

server {
    listen 443;

    root /path/to/rails/public;

    server_name example.com;

    ssl on;
    # ... some ssl config

    # this is not passenger standalone!
    location /subdir {
            proxy_pass https://127.0.0.1;
            auth_basic "Restricted access area authorization needed.";
            auth_basic_user_file /path/to/.htpasswd;
    }
    # this is used for passenger standalone on port 5000
    location / {
            proxy_pass https://127.0.0.1:5000;
            proxy_http_version 1.1;
            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_buffering off;
    }
}


问:
mp3 encoding at different bitrates using ffmpy into python
I am trying to convert a .flac audio file into an .mp3 at different bitrates. The simple code is the following:

```<code>import ffmpy
ff = ffmpy.FFmpeg(inputs={'in.flac': None},outputs={'out.mp3': None})
ff.run()
</code>```

Now, since I want my out.mp3, let's say, at 320k, I modify the second line of the code as follows:

```<code>ff = ffmpy.FFmpeg(inputs={'in.flac': None},outputs={'out.mp3': '-ab 320k'})
</code>```

The problem is that I am not sure I am using the right command in the right position, by inserting

```<code>'-ab 320k'
</code>```

or

```<code>'-ab 320000'
</code>```

The script seems to run correctly and Python does the conversion into mp3 but the bitrate is always 128 (I am checking it by using eyed3).
How can I modify my code to get 320kbps?

答:
try this:</p>

```<code>ff = ffmpy.FFmpeg(
 inputs={'16 Bit Lolitas - Beat Organ (Original Mix).mp4': None},
 outputs={'16 Bit Lolitas - Beat Organ (Original Mix).mp3': ['-ab', '320k']}
)
</code>```

Body:
I am trying to convert a .flac audio file into an .mp3 at different bitrates. The simple code is the following:

import ffmpy
ff = ffmpy.FFmpeg(inputs={'in.flac': None},outputs={'out.mp3': None})
ff.run()

Now, since I want my out.mp3, let's say, at 320k, I modify the second line of the code as follows:

ff = ffmpy.FFmpeg(inputs={'in.flac': None},outputs={'out.mp3': '-ab 320k'})

The problem is that I am not sure I am using the right command in the right position, by inserting

'-ab 320k'

or

'-ab 320000'

The script seems to run correctly and Python does the conversion into mp3 but the bitrate is always 128 (I am checking it by using eyed3).
How can I modify my code to get 320kbps?

Body:
try this:

ff = ffmpy.FFmpeg(
 inputs={'16 Bit Lolitas - Beat Organ (Original Mix).mp4': None},
 outputs={'16 Bit Lolitas - Beat Organ (Original Mix).mp3': ['-ab', '320k']}
)


问:
not getting correct data format in json while using ajax call
i have written a get api and i want to show some records in data table, while im getting records in json im getting date values like this "/Date(1498849454000)/".
How to get date value in "2017-04-11 02:09" in this format.
data is stored correctly "2017-04-11 02:09:17.000".
data type - datetime

sample data

```<code>{"data":[{"updtd_date":"\/Date(1498849454000)\/","usecase":"watertank","id":1026,"sms":"Alert: Tank is Full  at 01/07/2017 12:33:51 AM ]"},
</code>```

code

```<code>     <script>
            $(document).ready(function () {
                $('#myTable').DataTable({
                    "ajax": {
                        "url": "url",
                        "type": "GET",
                        "datatype": "json"
                    },
                    "columns" : [
                        { "data": "updtd_date", "autoWidth": true },
                        { "data": "usecase", "autoWidth": true },
                        { "data": "id", "autoWidth": true },
                        { "data": "sms", "autoWidth": true }
                        ]
                });
            });
        </script>

        <table id="myTable">
                <thead>
                    <tr>
                        <th>Time</th>
                        <th>Use Case</th>
                        <th>Sl no</th>
                        <th>SMS</th>
                    </tr>
                </thead>
            </table>
</code>```

controller

```<code>   public ActionResult getSMS()
        {
            using (smartpondEntities dc = new smartpondEntities())
            {
                var data = dc.sms.OrderByDescending(a => a.id).ToList();
                return Json(new { data = data }, JsonRequestBehavior.AllowGet);
            }

        }
</code>```

答:
You can create a date object by passing your time in milliseconds as the parameter to the Date constructor var date = Date(1498849454000);

Then you can get the date by using date.toDateString()

Body:
i have written a get api and i want to show some records in data table, while im getting records in json im getting date values like this "/Date(1498849454000)/".
How to get date value in "2017-04-11 02:09" in this format.
data is stored correctly "2017-04-11 02:09:17.000".
data type - datetime

sample data

{"data":[{"updtd_date":"\/Date(1498849454000)\/","usecase":"watertank","id":1026,"sms":"Alert: Tank is Full  at 01/07/2017 12:33:51 AM ]"},

code

                        Time
                        Use Case
                        Sl no
                        SMS

controller

   public ActionResult getSMS()
        {
            using (smartpondEntities dc = new smartpondEntities())
            {
                var data = dc.sms.OrderByDescending(a => a.id).ToList();
                return Json(new { data = data }, JsonRequestBehavior.AllowGet);
            }

        }


问:
SonarQube Critical Violation asks for filter on rest api web.xml file
The SonarQube hint (rule "Web applications should use validation filters") suggests this compliant solution:

```<code>public class ValidatingHttpRequest extends HttpServletRequestWrapper {
  // ...
}

public class ValidationFilter implements javax.servlet.Filter {
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
    chain.doFilter(new ValidatingHttpRequest( (HttpServletRequest)request ), response);
  }
}
</code>```

and in web.xml:

```<code><filter>
    <filter-name>ValidationFilter</filter-name>
    <filter-class>com.myco.servlet.ValidationFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>ValidationFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

But I have no clue of what validations are expected here. My code is a rest api (resteasy implementation) and all services are under "/rest/* path. Is this a false positive case?

答:
According to the OWASP, injection flaws are one of the top application security risks (link). The basic prevention idea includes automatic validation of all input values using the whitelist approach. In order to implement it in Java EE, OWASP suggests using a custom filter, you can find more details with some restrictive patterns here.

tl;dr: Sonar requires you to filter out some potentially unsafe input characters.

In my opinion, this rule is too general and does not apply to all of the possible applications - it is possible to prevent code injection in many ways.

Body:
The SonarQube hint (rule "Web applications should use validation filters") suggests this compliant solution:

public class ValidatingHttpRequest extends HttpServletRequestWrapper {
  // ...
}

public class ValidationFilter implements javax.servlet.Filter {
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
    chain.doFilter(new ValidatingHttpRequest( (HttpServletRequest)request ), response);
  }
}

and in web.xml:

<filter>
    <filter-name>ValidationFilter</filter-name>
    <filter-class>com.myco.servlet.ValidationFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>ValidationFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

But I have no clue of what validations are expected here. My code is a rest api (resteasy implementation) and all services are under "/rest/* path. Is this a false positive case?


问:
Angular 4 Headers not passing
I have a REST-API to contact, it works on swagger.
Now I try to call it with my Angular 4 app.
I get the error:

```<code>  XMLHttpRequest cannot load
  "baseURL"/company/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access
</code>```

When I look at the call, I see that it doesn't pass any headers (also not the token), but I actually added them to my request in my Angular 4 code:

```<code>getCompanies(): Observable<Company[]> {
   let tokenobject =JSON.parse(sessionStorage.getItem('current_user'));
   let token = tokenobject.token;
   let headers = new Headers({ 'Access-Control-Allow-Origin' : 'http://localhost:4200','Authorization': token });
   let options = new RequestOptions({ headers: headers });
   return this.http.get(this.url + this.path, options)
          .map(this.extractData)
          .catch(this.handleError);
}
</code>```

Is there something I forgot or did wrong?

答:
For CORS, others have already pointed out you need to enable it on server.

For Headers, use Headers.append:

```<code>let headers = new Headers();
headers.append('Authorization', token );
let options = new RequestOptions({ headers: headers });
</code>```

btw, for authorization header you might want to consider overriding angulars Http class in order to append Authorization header (if token exists, of course) to all requests so you don't have to add it manually to get, post, delete...

Title: Angular 4 Headers not passing

Body:
I have a REST-API to contact, it works on swagger.
Now I try to call it with my Angular 4 app.
I get the error:

  XMLHttpRequest cannot load
  "baseURL"/company/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access

When I look at the call, I see that it doesn't pass any headers (also not the token), but I actually added them to my request in my Angular 4 code:

getCompanies(): Observable<Company[]> {
   let tokenobject =JSON.parse(sessionStorage.getItem('current_user'));
   let token = tokenobject.token;
   let headers = new Headers({ 'Access-Control-Allow-Origin' : 'http://localhost:4200','Authorization': token });
   let options = new RequestOptions({ headers: headers });
   return this.http.get(this.url + this.path, options)
          .map(this.extractData)
          .catch(this.handleError);
}

Is there something I forgot or did wrong?

Body:
For CORS, others have already pointed out you need to enable it on server.

For Headers, use Headers.append:

let headers = new Headers();
headers.append('Authorization', token );
let options = new RequestOptions({ headers: headers });

btw, for authorization header you might want to consider overriding angulars Http class in order to append Authorization header (if token exists, of course) to all requests so you don't have to add it manually to get, post, delete...


问:
Firebird lock "table" to prevent inserts
Is possible to lock a table to prevent inserts/updates/deletes ?

I need to lock a table, delete some records and "reset" a generator.

```<code>>> lock table logs to prevent inserts/updates/deletes;
delete from logs where id <= :lastIdProcessed;
if ((select count(1) from logs) = 0) {
    alter sequence logSequence restart with 0;
}
>> commit and release table
</code>```

Another question is, I'll get in throwble if there is an insert into logs (gen_id(logSequence,1)) waiting for the lock release, the insert will run with the logSequence incremented using its value before it restart?

答:
Depending on your needs you can start a snapshot table stability transaction with table reservation using

```<code>SET TRANSACTION
    READ WRITE
    ISOLATION LEVEL SNAPSHOT TABLE STABILITY
    WAIT
    RESERVING <tablename>, <tablename> FOR PROTECTED WRITE
</code>```

SNAPSHOT TABLE STABILITY Isolation Level

The SNAPSHOT TABLE STABILITY isolation level is the most
restrictive. As in SNAPSHOT, a transaction in
SNAPSHOT TABLE STABILITY isolation sees only those changes that were committed
before the current transaction was started. After a
SNAPSHOT TABLE STABILITY is started, no other transactions can make any changes to
any table in the database that has changes pending. Other transactions
are able to read other data, but any attempt at inserting, updating or
deleting by a parallel process will cause conflict exceptions.

The RESERVING clause can be used to allow other transactions to
change data in some tables.

If any other transaction has an uncommitted change of data pending in
any database table before a transaction with the
SNAPSHOT TABLE STABILITY isolation level is started, trying to start a
SNAPSHOT TABLE STABILITY transaction will result in an exception.

[..]

RESERVING

The RESERVING clause in the SET TRANSACTION statement reserves
tables specified in the table list. Reserving a table prevents other
transactions from making changes in them or even, with the inclusion
of certain parameters, from reading data from them while this
transaction is running.

A RESERVING clause can also be used to specify a list of tables that
can be changed by other transactions, even if the transaction is
started with the SNAPSHOT TABLE STABILITY isolation level.

One RESERVING clause is used to specify as many reserved tables as
required.

See Transaction Statements for more information; you might also want to consult the old Interbase 6.0 documentation (especially Embedded SQL Guide and Developer's guide, see https://www.firebirdsql.org/en/reference-manuals/ at end) for information.

I have no experience using this feature, so I can't advise you on its potential pitfalls.

Body:
Is possible to lock a table to prevent inserts/updates/deletes ?

I need to lock a table, delete some records and "reset" a generator.

>> lock table logs to prevent inserts/updates/deletes;
delete from logs where id <= :lastIdProcessed;
if ((select count(1) from logs) = 0) {
    alter sequence logSequence restart with 0;
}
>> commit and release table

Another question is, I'll get in throwble if there is an insert into logs (gen_id(logSequence,1)) waiting for the lock release, the insert will run with the logSequence incremented using its value before it restart?

Body:
Depending on your needs you can start a snapshot table stability transaction with table reservation using

SET TRANSACTION
    READ WRITE
    ISOLATION LEVEL SNAPSHOT TABLE STABILITY
    WAIT
    RESERVING <tablename>, <tablename> FOR PROTECTED WRITE

SNAPSHOT TABLE STABILITY Isolation Level

The SNAPSHOT TABLE STABILITY isolation level is the most
restrictive. As in SNAPSHOT, a transaction in
SNAPSHOT TABLE STABILITY isolation sees only those changes that were committed
before the current transaction was started. After a
SNAPSHOT TABLE STABILITY is started, no other transactions can make any changes to
any table in the database that has changes pending. Other transactions
are able to read other data, but any attempt at inserting, updating or
deleting by a parallel process will cause conflict exceptions.

The RESERVING clause can be used to allow other transactions to
change data in some tables.

If any other transaction has an uncommitted change of data pending in
any database table before a transaction with the
SNAPSHOT TABLE STABILITY isolation level is started, trying to start a
SNAPSHOT TABLE STABILITY transaction will result in an exception.

[..]

RESERVING

The RESERVING clause in the SET TRANSACTION statement reserves
tables specified in the table list. Reserving a table prevents other
transactions from making changes in them or even, with the inclusion
of certain parameters, from reading data from them while this
transaction is running.

A RESERVING clause can also be used to specify a list of tables that
can be changed by other transactions, even if the transaction is
started with the SNAPSHOT TABLE STABILITY isolation level.

One RESERVING clause is used to specify as many reserved tables as
required.

See Transaction Statements for more information; you might also want to consult the old Interbase 6.0 documentation (especially Embedded SQL Guide and Developer's guide, see https://www.firebirdsql.org/en/reference-manuals/ at end) for information.

I have no experience using this feature, so I can't advise you on its potential pitfalls.

ContentLicense: CC BY-SA 4.0


问:
Normalize PostgreSQL Table with more than 700 columns
I have a source (and I have no control on it) with a table like:

```<code>CREATE TABLE temp.badtable(
    Id       INTEGER
   ,Meta     TEXT
   ,Field001 FLOAT
   ,Field002 FLOAT
   ,...
   ,Field720 FLOAT
);
</code>```

Where fields names are predictable and types are homogeneous. I would like to normalize this table before processing its data. I would like to have a well-shaped table instead, it should look like:

```<code>CREATE TABLE temp.goodtable(
    Id         INTEGER
   --,Meta       TEXT -- For normalization sake
   ,FieldName  TEXT
   ,FieldValue FLOAT
);
</code>```

Is there a proper way to do so with PostgreSQL?

Update

I get a beggining of solution using JSON. This is not performent, but it achieves what I need:

```<code>WITH

A AS (
SELECT
    Id
   ,row_to_json(M) AS Data
FROM
    temp.badtable
),

B AS (
SELECT
    Id
   ,row_to_json(json_each(Data)) AS Pair
FROM
    A
)

SELECT
    Id
   ,Pair->>'key' AS FieldKey
   ,Pair->>'value' AS FieldValue
FROM B;
</code>```

答: Consider using a JSON[] in PostgreSQL.</p>

Body:
I have a source (and I have no control on it) with a table like:

CREATE TABLE temp.badtable(
    Id       INTEGER
   ,Meta     TEXT
   ,Field001 FLOAT
   ,Field002 FLOAT
   ,...
   ,Field720 FLOAT
);

Where fields names are predictable and types are homogeneous. I would like to normalize this table before processing its data. I would like to have a well-shaped table instead, it should look like:

CREATE TABLE temp.goodtable(
    Id         INTEGER
   --,Meta       TEXT -- For normalization sake
   ,FieldName  TEXT
   ,FieldValue FLOAT
);

Is there a proper way to do so with PostgreSQL?

Update

I get a beggining of solution using JSON. This is not performent, but it achieves what I need:

WITH

A AS (
SELECT
    Id
   ,row_to_json(M) AS Data
FROM
    temp.badtable
),

B AS (
SELECT
    Id
   ,row_to_json(json_each(Data)) AS Pair
FROM
    A
)

SELECT
    Id
   ,Pair->>'key' AS FieldKey
   ,Pair->>'value' AS FieldValue
FROM B;

Body: Consider using a JSON[] in PostgreSQL.


问:
CSS hidden and visible properties change all the time
I have following website:

window.onload = function() {
  var executed = false;
  if (!executed) {
    document.getElementById("at").style.visibility = "visible";
    setInterval(function() {
      document.getElementById("t-ground").style.visibility = "visible";
      document.getElementById("ground").style.opacity = "0.3";
      setInterval(function() {
        document.getElementById("right-top").style.visibility = "visible";
        document.getElementById("t-ground").style.visibility = "hidden";
        document.getElementById("ground").style.opacity = "1.0";
        document.getElementById("t-plant").style.visibility = "visible";
        document.getElementById("hand").style.opacity = "0.3";
        setInterval(function() {
          document.getElementById("right-bot").style.visibility = "visible";
          document.getElementById("hand").style.opacity = "1.0";
          document.getElementById("t-plant").style.visibility = "hidden";
          document.getElementById("ab").style.visibility = "visible";
          document.getElementById("t-animal").style.visibility = "visible";
          document.getElementById("animal").style.opacity = "0.3";
          setInterval(function() {
            document.getElementById("left-bot").style.visibility = "visible";
            document.getElementById("animal").style.opacity = "1.0";
            document.getElementById("t-animal").style.visibility = "hidden";
            document.getElementById("t-human").style.visibility = "visible";
            document.getElementById("human").style.opacity = "0.3";
            setInterval(function() {
              document.getElementById("left-top").style.visibility = "visible";
              document.getElementById("t-human").style.visibility = "hidden";
              document.getElementById("human").style.opacity = "1.0";
              document.getElementById("logo-mid").style.display = "none";
              setInterval(function() {
                document.getElementById("about-text").style.display = "inline";
                document.getElementById("text-div").style.overflowY = "scroll";
                document.getElementById("at").style.visibility = "hidden";
                document.getElementById("ab").style.visibility = "hidden";
                document.getElementById("right-top").style.visibility = "hidden";
                document.getElementById("right-bot").style.visibility = "hidden";
                document.getElementById("left-bot").style.visibility = "hidden";
                document.getElementById("left-top").style.visibility = "hidden";
                executed = true;
              }, 1725);
            }, 2125);
          }, 2125);
        }, 2125);
      }, 2125);
    }, 2125);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  font-family: "Verdana", Geneva, sans-serif;
  font-size: 14px;
}

body {
  padding-top: 10px;
  margin: auto;
  background-color: #FFFFFF;
  width: 1100px;
}

hr {
  border-top: 1px dotted #747737;
}

.title {
  text-align: center;
  padding-bottom: 20px;
}

.wrapper {
  margin: auto;
}

#text-div {
  height: 496px;
  width: 450px;
  border-top: 1px solid #747737;
  border-bottom: 1px solid #747737;
  box-shadow: inset 0px 0px 20px 0px rgba(0, 0, 0, 1);
  margin-top: -4px;
}

.about-text {
  margin-left: 25px;
  margin-right: 25px;
  width: 350px;
  height: 472px;
  display: none;
}

#title-fading-in {
  visibility: hidden;
  height: 100px;
}

.image-text {
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 300px;
  height: 230px;
  margin-top: -230px;
  text-align: center;
  vertical-align: middle;
  line-height: 200px;
  font-size: 20px;
  visibility: hidden;
}

.arrow-in-image {
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 150px;
  height: 250px;
  margin-top: -230px;
}

.left {
  float: left;
}

.relative {
  position: relative;
}

.image {
  height: 250px;
  width: 300px;
  transition: 1s ease;
  margin-top: -4px;
}

.arrow-right-left {
  height: 500px;
  width: 150px;
  margin-top: -4px;
  visibility: hidden;
  transition: 1s ease;
  opacity: 0.9;
}

.arrow-top-bottom-wrapper {
  width: 1050px;
  height: 150px;
  margin-left: 125px;
}

.arrow-top-bottom {
  visibility: hidden;
  margin-top: -4px;
}

#left-top {
  position: absolute;
  top: -4px;
  left: 125px;
  z-index: 3;
  visibility: hidden;
}

#left-bot {
  position: absolute;
  top: 246px;
  left: 125px;
  z-index: 3;
  visibility: hidden;
}

#right-top {
  position: absolute;
  top: -4px;
  left: 25px;
  z-index: 3;
  visibility: hidden;
}

#right-bot {
  position: absolute;
  top: 246px;
  left: 25px;
  z-index: 3;
  visibility: hidden;
}</code>```

      Sit

      Dolor

          Some Text

      Lorem

      Ipsum

```

For some reason after loading the site, the hidden and visible properties change all the time. Why is that the case?

答:
setInterval will execute the function repeatedly every x ms. So Your functions are all repeated triggering between visible and hidden all the time.

Since you want to do it once you need to use setTimeout which will only trigger once after x ms.

Body:
I have following website:

window.onload = function() {
  var executed = false;
  if (!executed) {
    document.getElementById("at").style.visibility = "visible";
    setInterval(function() {
      document.getElementById("t-ground").style.visibility = "visible";
      document.getElementById("ground").style.opacity = "0.3";
      setInterval(function() {
        document.getElementById("right-top").style.visibility = "visible";
        document.getElementById("t-ground").style.visibility = "hidden";
        document.getElementById("ground").style.opacity = "1.0";
        document.getElementById("t-plant").style.visibility = "visible";
        document.getElementById("hand").style.opacity = "0.3";
        setInterval(function() {
          document.getElementById("right-bot").style.visibility = "visible";
          document.getElementById("hand").style.opacity = "1.0";
          document.getElementById("t-plant").style.visibility = "hidden";
          document.getElementById("ab").style.visibility = "visible";
          document.getElementById("t-animal").style.visibility = "visible";
          document.getElementById("animal").style.opacity = "0.3";
          setInterval(function() {
            document.getElementById("left-bot").style.visibility = "visible";
            document.getElementById("animal").style.opacity = "1.0";
            document.getElementById("t-animal").style.visibility = "hidden";
            document.getElementById("t-human").style.visibility = "visible";
            document.getElementById("human").style.opacity = "0.3";
            setInterval(function() {
              document.getElementById("left-top").style.visibility = "visible";
              document.getElementById("t-human").style.visibility = "hidden";
              document.getElementById("human").style.opacity = "1.0";
              document.getElementById("logo-mid").style.display = "none";
              setInterval(function() {
                document.getElementById("about-text").style.display = "inline";
                document.getElementById("text-div").style.overflowY = "scroll";
                document.getElementById("at").style.visibility = "hidden";
                document.getElementById("ab").style.visibility = "hidden";
                document.getElementById("right-top").style.visibility = "hidden";
                document.getElementById("right-bot").style.visibility = "hidden";
                document.getElementById("left-bot").style.visibility = "hidden";
                document.getElementById("left-top").style.visibility = "hidden";
                executed = true;
              }, 1725);
            }, 2125);
          }, 2125);
        }, 2125);
      }, 2125);
    }, 2125);
  }
}

html {
  font-family: "Verdana", Geneva, sans-serif;
  font-size: 14px;
}

body {
  padding-top: 10px;
  margin: auto;
  background-color: #FFFFFF;
  width: 1100px;
}

hr {
  border-top: 1px dotted #747737;
}

.title {
  text-align: center;
  padding-bottom: 20px;
}

.wrapper {
  margin: auto;
}

#text-div {
  height: 496px;
  width: 450px;
  border-top: 1px solid #747737;
  border-bottom: 1px solid #747737;
  box-shadow: inset 0px 0px 20px 0px rgba(0, 0, 0, 1);
  margin-top: -4px;
}

.about-text {
  margin-left: 25px;
  margin-right: 25px;
  width: 350px;
  height: 472px;
  display: none;
}

#title-fading-in {
  visibility: hidden;
  height: 100px;
}

.image-text {
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 300px;
  height: 230px;
  margin-top: -230px;
  text-align: center;
  vertical-align: middle;
  line-height: 200px;
  font-size: 20px;
  visibility: hidden;
}

.arrow-in-image {
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 150px;
  height: 250px;
  margin-top: -230px;
}

.left {
  float: left;
}

.relative {
  position: relative;
}

.image {
  height: 250px;
  width: 300px;
  transition: 1s ease;
  margin-top: -4px;
}

.arrow-right-left {
  height: 500px;
  width: 150px;
  margin-top: -4px;
  visibility: hidden;
  transition: 1s ease;
  opacity: 0.9;
}

.arrow-top-bottom-wrapper {
  width: 1050px;
  height: 150px;
  margin-left: 125px;
}

.arrow-top-bottom {
  visibility: hidden;
  margin-top: -4px;
}

#left-top {
  position: absolute;
  top: -4px;
  left: 125px;
  z-index: 3;
  visibility: hidden;
}

#left-bot {
  position: absolute;
  top: 246px;
  left: 125px;
  z-index: 3;
  visibility: hidden;
}

#right-top {
  position: absolute;
  top: -4px;
  left: 25px;
  z-index: 3;
  visibility: hidden;
}

#right-bot {
  position: absolute;
  top: 246px;
  left: 25px;
  z-index: 3;
  visibility: hidden;
}

      Sit

      Dolor

          Some Text

      Lorem

      Ipsum

For some reason after loading the site, the hidden and visible properties change all the time. Why is that the case?


问:
Load local HTML content dynamically
I have to code a little HTML page for a knowledgebase and I need some help. The concept I got is to have very much little files with a headline, the purpose, some keywords and a frame where the content linked in the keywords should load dynamically.

My problem is the dynamic content because I can’t use the iframe tag recursively and jQuery doesn’t work on local files.

答: You need to be working on a server. local file path or url provided won't work for you.</p>

Title: Load local HTML content dynamically


问:
Open image in modal (link in one div img in another)
I have a dot-front that when hovered over it flips and shows a dot-back with a link. If I click the link it should open a modal with a preview image.
I think that the problem is in the jquery where I wrote closest and find, but I don't know how to fix it.

$(function() {
  $('.pop').on('click', function() {
    console.log("pop");
    $('#imagepreview').attr('src', $('#modal-icon01').closest(".div-img").find('.front img').attr('src'));
    $('#imagemodal').modal('show');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.div-img {
  display: inline-block;
  height: 200px;
  width: 200px;
  cursor: pointer;
}

.div-img img {
  object-fit: cover;
  width: 240px;
  margin-left: -20px;
}

.div-img span {
  display: table-cell;
  vertical-align: middle;
  height: 200px;
}

.div-img > .front {
  position: absolute;
  transform: perspective( 600px) rotateY( 0deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img > .back {
  position: absolute;
  transform: perspective( 600px) rotateY( 180deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img:hover > .front {
  transform: perspective( 600px) rotateY( -180deg);
}

.div-img:hover > .back {
  transform: perspective( 600px) rotateY( 0deg);
}</code>```

    Pizza Hut Delivery
(De ce Pizza Hut)

        <button type="button" class="close" data-dismiss="modal">×Close</button>

```

答:
First of all, you have to add Jquery library then you have to declare what does .modal means ?
you can take the shortcut and just add bootstrap library with jquery and it will work fine, check this working fiddle

Updated with image attached

Body:
I have a dot-front that when hovered over it flips and shows a dot-back with a link. If I click the link it should open a modal with a preview image.
I think that the problem is in the jquery where I wrote closest and find, but I don't know how to fix it.

$(function() {
  $('.pop').on('click', function() {
    console.log("pop");
    $('#imagepreview').attr('src', $('#modal-icon01').closest(".div-img").find('.front img').attr('src'));
    $('#imagemodal').modal('show');
  });
});

.div-img {
  display: inline-block;
  height: 200px;
  width: 200px;
  cursor: pointer;
}

.div-img img {
  object-fit: cover;
  width: 240px;
  margin-left: -20px;
}

.div-img span {
  display: table-cell;
  vertical-align: middle;
  height: 200px;
}

.div-img > .front {
  position: absolute;
  transform: perspective( 600px) rotateY( 0deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img > .back {
  position: absolute;
  transform: perspective( 600px) rotateY( 180deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img:hover > .front {
  transform: perspective( 600px) rotateY( -180deg);
}

.div-img:hover > .back {
  transform: perspective( 600px) rotateY( 0deg);
}

    Pizza Hut Delivery
(De ce Pizza Hut)

        <button type="button" class="close" data-dismiss="modal">×Close</button>


问:
Use fade-in and delay with ng-repeat to display list items
I am trying to display list items one by one with some delay. For that I managed to do something like this:

```<code>  $("#dropDownMenu li").each(function(i) {
    $(this).delay(1000 * i).fadeIn(100);
});
</code>```

It works good when list is something like

```<code>    <li>one</li>
    <li>two</li>
    <li>three</li>
</code>```

JSFiddle

But it does't work when I use ng-repeat in a list, something like this

```<code><li ng-repeat="time in msg.time">{{time}}<li>
</code>```

How can I make it work with ng-repeat?

答:
The recommended way of animations in angular is by using the ngAnimate module and use the ng-enter classes:

```<code>var myApp = angular.module('myApp',['ngAnimate']);
</code>```

Html:

```<code><ul>
    <li class="item" ng-repeat="time in msg.time">{{time}}<li>
</ul>
</code>```

In your css:

```<code>.item.ng-enter {
    -webkit-transition: 1s;
    transition: 1s;
    opacity:0;
}
.item.ng-enter-active {
    opacity: 1;
}
</code>```

For having the timeout of each item to appear, you should take a look at @Slava Utesinov answer.

Body:
I am trying to display list items one by one with some delay. For that I managed to do something like this:

  $("#dropDownMenu li").each(function(i) {
    $(this).delay(1000 * i).fadeIn(100);
});

It works good when list is something like

one

two

three

JSFiddle

But it does't work when I use ng-repeat in a list, something like this

{{time}}

How can I make it work with ng-repeat?

Body:
The recommended way of animations in angular is by using the ngAnimate module and use the ng-enter classes:

var myApp = angular.module('myApp',['ngAnimate']);

Html:

<ul>
    <li class="item" ng-repeat="time in msg.time">{{time}}<li>
</ul>

In your css:

.item.ng-enter {
    -webkit-transition: 1s;
    transition: 1s;
    opacity:0;
}
.item.ng-enter-active {
    opacity: 1;
}

For having the timeout of each item to appear, you should take a look at @Slava Utesinov answer.


问:
Linebreaks in middle of URL in HTML
I have this strange issue, where I get random linebreaks in my HTML when I copy & paste links from mails I get.

The problem is, linebreaks look exactly like any other whitespace and on long lines I have problems seeing if there is any linebreaks.

Normally this wouldn't be a problem, but we are also using emailing system that doesn't like breaklines in middle of an element.

Is there a way to see these without manually scanning all the lines, which is impossible due to amount of mails we are sending.

Regex maybe?
I'm using Notepad++ as an editor.

答: In Notepad++, you can use "Extended" mode in the FIND Option. Use "\r\n" to scan all the new lines in the file. Use "\r" to find all carriage returns in the file.</p>

Title: Linebreaks in middle of URL in HTML


问:
this.each is not a function in jqm widget
I have some trouble with my jqm widget.
When I do that $("div[id=leftSideList]").leftlist('refresh'), its work fine. But, if I wrap code below on constraction like this

```<code>function _list (key) {
            switch (key) {
                case 'leftlist':
                    return $("div[id=leftSideList]").leftlist;
                case 'rightlist':
                    return $("div[id=leftSideList]").rightlist;
            }
        }
</code>```

and use it _list('leftlist')('refresh').
Its return me error Uncaught TypeError: this.each is not a function

答:
The issue is because the returned function (leftlist or rightlist) has lost its scope; this within the function no longer refers to the div[id="leftSideList"] element, hence the error.

You can fix this by using $.proxy, however it is incredibly ugly and not really a workable solution for a production setting:

```<code>function _list(key) {
  switch (key) {
    case 'leftlist':
      return $.proxy($("div[id=leftSideList]").leftlist, $("div[id=leftSideList]"));
    case 'rightlist':
      return $.proxy($("div[id=leftSideList]").rightlist, $("div[id=leftSideList]"));
  }
}
</code>```

Working example - note this uses built in jQuery methods as you did not provide the source of leftlist() and rightlist().

A much better solution would be to avoid this completely unnecessary abstraction entirely. It is offering you no benefit whatsoever, other than keeping the selected element consistent.

```<code>function _list(key, action) {
  return $("div[id=leftSideList]")[key](action);
}

_list('leftlist', 'refresh')
</code>```

Finally note that using div[id=leftSideList] is redundant and slow. You can just use #leftSideList instead. The only reason you would use the attribute selector is if you have multiple elements with the same id attribute - which is invalid and an issue you should fix as soon as possible.

Body:
I have some trouble with my jqm widget.
When I do that $("div[id=leftSideList]").leftlist('refresh'), its work fine. But, if I wrap code below on constraction like this

function _list (key) {
            switch (key) {
                case 'leftlist':
                    return $("div[id=leftSideList]").leftlist;
                case 'rightlist':
                    return $("div[id=leftSideList]").rightlist;
            }
        }

and use it _list('leftlist')('refresh').
Its return me error Uncaught TypeError: this.each is not a function

Body:
The issue is because the returned function (leftlist or rightlist) has lost its scope; this within the function no longer refers to the div[id="leftSideList"] element, hence the error.

You can fix this by using $.proxy, however it is incredibly ugly and not really a workable solution for a production setting:

function _list(key) {
  switch (key) {
    case 'leftlist':
      return $.proxy($("div[id=leftSideList]").leftlist, $("div[id=leftSideList]"));
    case 'rightlist':
      return $.proxy($("div[id=leftSideList]").rightlist, $("div[id=leftSideList]"));
  }
}

Working example - note this uses built in jQuery methods as you did not provide the source of leftlist() and rightlist().

A much better solution would be to avoid this completely unnecessary abstraction entirely. It is offering you no benefit whatsoever, other than keeping the selected element consistent.

function _list(key, action) {
  return $("div[id=leftSideList]")[key](action);
}

_list('leftlist', 'refresh')

Finally note that using div[id=leftSideList] is redundant and slow. You can just use #leftSideList instead. The only reason you would use the attribute selector is if you have multiple elements with the same id attribute - which is invalid and an issue you should fix as soon as possible.


问:
How can I find out more about my classic ASP environment?
I'm trying to make some modifications to some old ASP pages running VBScript on a server that I don't have a lot of information about. The people who would have that information are off in another department/hard to track down/probably wouldn't be able to provide complete information anyway.

I would like to run an ASP script that would get the server to tell me about itself. Information I would like to know is stuff like:

the version number of the server

version of Windows it is running on

the version of VBScript am I using

what dll's and COM objects are available for me to use

Bearing in mind that I know very little about ASP, what is some code that I could put into an ASP file I could run on the server so that it would provide me this information?

Based on the ServerVariables clue provided in the comment by JB King, below, I wrote this code and put it in an ASP:

```<code><%
    dim x
    for each x in Request.ServerVariables
      response.write("<p>" & x & ": " & Request.ServerVariables(x) &"</p>")
    next
%>
</code>```

This provided a lot of the information I needed - such as telling me that I'm actually running under something called Chili!Soft on a Solaris server, not Windows, which probably explains why the stuff I want to use from the Microsoft library doesn't work.

I still would like a good way of figuring out what COM objects are available in this environment...

答:
Server Variables would be a starting point though I'm not sure how well that would work as if you could remote onto the server that may be a better option.  You may also want to look into COM objects as those were used with ASP that involve some DLLs.

You may want to look into what version of IIS is being used and what ISAPI filters are on server for a couple of other points along with what logging is there on the server.

Body:
I'm trying to make some modifications to some old ASP pages running VBScript on a server that I don't have a lot of information about. The people who would have that information are off in another department/hard to track down/probably wouldn't be able to provide complete information anyway.

I would like to run an ASP script that would get the server to tell me about itself. Information I would like to know is stuff like:

the version number of the server

version of Windows it is running on

the version of VBScript am I using

what dll's and COM objects are available for me to use

Bearing in mind that I know very little about ASP, what is some code that I could put into an ASP file I could run on the server so that it would provide me this information?

Based on the ServerVariables clue provided in the comment by JB King, below, I wrote this code and put it in an ASP:

<%
    dim x
    for each x in Request.ServerVariables
      response.write("
" & x & ": " & Request.ServerVariables(x) &"
")
    next
%>

This provided a lot of the information I needed - such as telling me that I'm actually running under something called Chili!Soft on a Solaris server, not Windows, which probably explains why the stuff I want to use from the Microsoft library doesn't work.

I still would like a good way of figuring out what COM objects are available in this environment...


问:
Python round() too slow, faster way to reduce precision?
I am doing the following:

```<code>TOLERANCE = 13
some_float = ...
round(some_float, TOLERANCE)
</code>```

This is run many times, so performance is important. I have to round some_float due to floating point representation error. I don't actually need to "round" the number in that sense, just remove digits after 13 trailing digits.

Is there a faster way to do this?

答:
Using int, multiply and divide is faster. You can use timeit with ipython in order to quickly benchmark Python code.

```<code>In [7]: %timeit int(1.12345678901234*(10**13))/(10.**13)
1000000 loops, best of 3: 380 ns per loop

In [8]: %timeit round(1.12345678901234, 13)
1000000 loops, best of 3: 1.32 µs per loop
</code>```

Body:
I am doing the following:

TOLERANCE = 13
some_float = ...
round(some_float, TOLERANCE)

This is run many times, so performance is important. I have to round some_float due to floating point representation error. I don't actually need to "round" the number in that sense, just remove digits after 13 trailing digits.

Is there a faster way to do this?

Body:
Using int, multiply and divide is faster. You can use timeit with ipython in order to quickly benchmark Python code.

In [7]: %timeit int(1.12345678901234*(10**13))/(10.**13)
1000000 loops, best of 3: 380 ns per loop

In [8]: %timeit round(1.12345678901234, 13)
1000000 loops, best of 3: 1.32 µs per loop


问:
How to update Fragment view from onActivityResult() in parent Activity
In my Activity, I do implement onActivityResult:

```<code>@Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            //do something

        }
</code>```

I tried to implement onActivityResult in that Fragment:

```<code>@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10020) {
            Log.e(TAG, "requestCode == 10020");
            tv1.setText(Html.fromHtml("You are currently on a <b>GOLD</b> plan. You can:"));
        }
        Log.e(TAG, "line 401");

    }
</code>```

and BroadcastReceive, which will be called when reach onActivityResult in parent Activity but both of them is not work. How can I do that? Help me!

答:
In your fragment declare a public method that takes in all the required information to update the view (some text?).  When you're creating your fragment in the activity, keep a reference to it so you can call that method.

Activity

```<code>MyFragment fragment;

oncreateView() {
    if(savedInstance == null) {
        fragment = // create fragment
        // getSupportFragmentManager() and add it to the activity
    }
}

onActivityResult() {
    fragment.updateText(String text);
}
</code>```

Fragment

```<code>public class MyFragment {
    ...
    ...
    public void updateText(String text) {
        // update the textview with the new text
    }
}
</code>```

Body:
In my Activity, I do implement onActivityResult:

@Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            //do something

        }

I tried to implement onActivityResult in that Fragment:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10020) {
            Log.e(TAG, "requestCode == 10020");
            tv1.setText(Html.fromHtml("You are currently on a GOLD plan. You can:"));
        }
        Log.e(TAG, "line 401");

    }

and BroadcastReceive, which will be called when reach onActivityResult in parent Activity but both of them is not work. How can I do that? Help me!

Body:
In your fragment declare a public method that takes in all the required information to update the view (some text?).  When you're creating your fragment in the activity, keep a reference to it so you can call that method.

Activity

MyFragment fragment;

oncreateView() {
    if(savedInstance == null) {
        fragment = // create fragment
        // getSupportFragmentManager() and add it to the activity
    }
}

onActivityResult() {
    fragment.updateText(String text);
}

Fragment

public class MyFragment {
    ...
    ...
    public void updateText(String text) {
        // update the textview with the new text
    }
}


问:
How to handle NSTextView preferences (spelling and grammar, substitutions,...)
The NSTextView class allows the user to dis-/enable features like "spelling while typing" with the context menu (right click). But when I use a NSTextView in my own app, those preferences are not saved automatically by the text view itself, which means that I have to save them separately - right?

Now I also want to allow the user to change those settings in my app preferences (like in TextEdit). What I do is to save the text view preferences in the user defaults, which means that every time the user changes the setting in the app preferences, I apply those settings and save them. It's pretty easy to accomplish that except the one case where the user changes the text view setting with the context menu and not through the app preferences.

My question now: How can I get notified when the settings of a NSTextView is changed, so I can save them?

答:
You could also use NSTextViews method
 toggleAutomaticSpellingCorrection:

This method is only called, when the user changes the setting via menu/contextMenu and not if the programmer changes the setting programatically (e.g. temporarily disabling when inserting text).


问:
How to get the version history of a list using Client Object Model Sharepoint 2010
I want to access the list item history details since I have some multiline fields which are all enabled with append data mode. Also, I want to see if any date is modified after creation of that item and etc. How can I do it through Sharepoint 2010 Client Object Model?</p>

答:
This is demonstrated here:

http://www.learningsharepoint.com/2010/07/16/programmatically-get-document-version-history-using-client-object-model-sharepoint-2010/


问:
Second unit does not find TImage
so I have some work to do using lazarus and one of my procedures is written in a second unit but also used in the first.
The problem is, I want to give the procedure a TImage from the Form connected to unit 1, but unit 2 can't find an identifier "TImage".</p>

```<code>interface
procedure Bewegen(Spieler:TImage);

..

procedure Bewegen(Spieler:TImage);
var Lefti,Topi:integer;

function wurf(AnzahlWurfel:integer):integer;
begin
  randomize;
  case AnzahlWurfel of 1 : result:=1+Random(6);        //AZ von 1 bis 6 oder 12. Je nach Anzahl der Würfel.
                       2 : result:=1+Random(12);
  end;
end;

procedure gehen(Wurf:integer;out Left, Top:integer);
var i:integer;
begin
  for i:=1 to Wurf do if (Left<908) AND (Top=56) then Left:=Left+90//oben links nach oben rechts
                  else if (Left=908) AND (Top<956) then Top :=Top+90 //oben rechts nach unten rechts
                    else if (Left>8) AND (Top=956) then Left:=Left-90//unten rechts nach unten links
                     else if (Left=8) AND (Top>56) then Top :=Top-90;//unten links nach oben links
end;

begin
  FMono.Edit1.Text:=IntToStr(wurf(AnzahlWurfel));
   Lefti:=Spieler.Left;
   Topi:=Spieler.Top;
  gehen(wurf(AnzahlWurfel),Lefti,Topi);
   Spieler.Left:=Lefti;
   Spieler.Top:=Topi;
end;
</code>```

答:
Solution is typing the uses before the procedure and in the interface.</p>

```<code>interface

uses
 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ActnList, ExtCtrls, u_settings, u_grafik;

procedure Bewegen(Spieler:TImage);
</code>```

Title: Second unit does not find TImage

Body:
so I have some work to do using lazarus and one of my procedures is written in a second unit but also used in the first.
The problem is, I want to give the procedure a TImage from the Form connected to unit 1, but unit 2 can't find an identifier "TImage".

interface
procedure Bewegen(Spieler:TImage);

..

procedure Bewegen(Spieler:TImage);
var Lefti,Topi:integer;

function wurf(AnzahlWurfel:integer):integer;
begin
  randomize;
  case AnzahlWurfel of 1 : result:=1+Random(6);        //AZ von 1 bis 6 oder 12. Je nach Anzahl der Würfel.
                       2 : result:=1+Random(12);
  end;
end;

procedure gehen(Wurf:integer;out Left, Top:integer);
var i:integer;
begin
  for i:=1 to Wurf do if (Left<908) AND (Top=56) then Left:=Left+90//oben links nach oben rechts
                  else if (Left=908) AND (Top<956) then Top :=Top+90 //oben rechts nach unten rechts
                    else if (Left>8) AND (Top=956) then Left:=Left-90//unten rechts nach unten links
                     else if (Left=8) AND (Top>56) then Top :=Top-90;//unten links nach oben links
end;

begin
  FMono.Edit1.Text:=IntToStr(wurf(AnzahlWurfel));
   Lefti:=Spieler.Left;
   Topi:=Spieler.Top;
  gehen(wurf(AnzahlWurfel),Lefti,Topi);
   Spieler.Left:=Lefti;
   Spieler.Top:=Topi;
end;

Body:
Solution is typing the uses before the procedure and in the interface.

interface

uses
 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ActnList, ExtCtrls, u_settings, u_grafik;

procedure Bewegen(Spieler:TImage);


问:
How can I match coordinates from three arrays that are not exactly equal?
I have six arrays with coordinates of detected sources in an astronomical image. Each array has the right ascension or declination of the sources in a specific filter of the observation (r,i,z). The positions will not be 100% equal (float numbers).
I found out that one can find matching pairs for integer numbers where it is possible to check for equality (How can I find identical x,y coordinates in two arrays of corrdinates?).
But how do I find the matching pairs for float numbers? My idea was to check if the distance between two positions is smaller than a distance dist=0.5 / 3600 (so 0.5 arcsec). Then I consider the two sources to be the same object. Once the matching pairs in three filters are found I want to append some information on that source (the magnitudes) to a list.
Here is the code that I tried:

```<code># open the relevant catalogs
cat_r = pyfits.open("%s/%s_R_for_calib.cat" %(cluster,cluster))[2].data
cat_i = pyfits.open("%s/%s_I_for_calib.cat" %(cluster,cluster))[2].data
cat_z = pyfits.open("%s/%s_Z_for_calib.cat" %(cluster,cluster))[2].data

mask_r = cat_r['FLAGS'] == 0
mask_i = cat_i['FLAGS'] == 0
mask_z = cat_z['FLAGS'] == 0

# get the information needed for the analysis
cat_r_MAG               = cat_r.field("MAG_AUTO")[mask_r]
cat_i_MAG               = cat_i.field("MAG_AUTO")[mask_i]
cat_z_MAG               = cat_z.field("MAG_AUTO")[mask_z]
cat_r_MAG_ERR           = cat_r.field("MAGERR_AUTO")[mask_r]
cat_i_MAG_ERR           = cat_i.field("MAGERR_AUTO")[mask_i]
cat_z_MAG_ERR           = cat_z.field("MAGERR_AUTO")[mask_z]
cat_r_ra = cat_r.field("ALPHA_J2000")[mask_r]
cat_r_dec = cat_r.field("DELTA_J2000")[mask_r]
cat_i_ra = cat_i.field("ALPHA_J2000")[mask_i]
cat_i_dec = cat_i.field("DELTA_J2000")[mask_i]
cat_z_ra = cat_z.field("ALPHA_J2000")[mask_z]
cat_z_dec = cat_z.field("DELTA_J2000")[mask_z]

dist = 0.5 / 3600
matches = []

for a in range(0,len(cat_r_ra)):
    for b in range(0,len(cat_i_ra)):
        for c in range(0,len(cat_z_ra)):
            if np.sqrt((cat_r_ra[a] - cat_i_ra[b])**2 + (cat_r_dec[a] - cat_i_dec[b])**2) < dist and np.sqrt((cat_r_ra[a] - cat_z_ra[c])**2 + (cat_r_dec[a] - cat_z_dec[c])**2 < dist):
                match = [cat_r_ra[a], cat_r_dec[a], cat_r_MAG[a], cat_r_MAG_ERR[a], cat_i_MAG[b], cat_i_MAG_ERR[b], cat_z_MAG[c], cat_z_MAG_ERR[c]]
                matches.append(match)
matches = np.array(matches)
</code>```

The problem is, that it takes really long to run. I think the combination of for loops and if statements slows it down. But I am still fairly new to programming in python so I do not know a more efficient way. Is there an efficient way in python to find the matching sources up to some accuracy (in this case 0.5 / 3600)?

Thank you for your help!

答:
You could try rounding your arrays beforehand. Using the method suggested in the thread you linked, this would give you:

```<code>import numpy as np
A = np.array([[ 2.31,  1, 4.33],
              [ 4.46,  3, 10.75]])

B = np.array([[ 2.34,  3,  4.34],
              [ 4.47, 11, 10.78]])

roundedA = np.around(A, decimals=1)
roundedB = np.around(B, decimals=1)

print('%s\n%s\n' % (roundedA, roundedB))
print(set(zip(*roundedA)) & set(zip(*roundedB)))
</code>```

Output:

```<code>[[  2.3   1.    4.3]
 [  4.5   3.   10.8]]
[[  2.3   3.    4.3]
 [  4.5  11.   10.8]]

{(4.2999999999999998, 10.800000000000001), (2.2999999999999998, 4.5)}
</code>```

Beware of the floating point errors.

Body:
I have six arrays with coordinates of detected sources in an astronomical image. Each array has the right ascension or declination of the sources in a specific filter of the observation (r,i,z). The positions will not be 100% equal (float numbers).
I found out that one can find matching pairs for integer numbers where it is possible to check for equality (How can I find identical x,y coordinates in two arrays of corrdinates?).
But how do I find the matching pairs for float numbers? My idea was to check if the distance between two positions is smaller than a distance dist=0.5 / 3600 (so 0.5 arcsec). Then I consider the two sources to be the same object. Once the matching pairs in three filters are found I want to append some information on that source (the magnitudes) to a list.
Here is the code that I tried:

# open the relevant catalogs
cat_r = pyfits.open("%s/%s_R_for_calib.cat" %(cluster,cluster))[2].data
cat_i = pyfits.open("%s/%s_I_for_calib.cat" %(cluster,cluster))[2].data
cat_z = pyfits.open("%s/%s_Z_for_calib.cat" %(cluster,cluster))[2].data

mask_r = cat_r['FLAGS'] == 0
mask_i = cat_i['FLAGS'] == 0
mask_z = cat_z['FLAGS'] == 0

# get the information needed for the analysis
cat_r_MAG               = cat_r.field("MAG_AUTO")[mask_r]
cat_i_MAG               = cat_i.field("MAG_AUTO")[mask_i]
cat_z_MAG               = cat_z.field("MAG_AUTO")[mask_z]
cat_r_MAG_ERR           = cat_r.field("MAGERR_AUTO")[mask_r]
cat_i_MAG_ERR           = cat_i.field("MAGERR_AUTO")[mask_i]
cat_z_MAG_ERR           = cat_z.field("MAGERR_AUTO")[mask_z]
cat_r_ra = cat_r.field("ALPHA_J2000")[mask_r]
cat_r_dec = cat_r.field("DELTA_J2000")[mask_r]
cat_i_ra = cat_i.field("ALPHA_J2000")[mask_i]
cat_i_dec = cat_i.field("DELTA_J2000")[mask_i]
cat_z_ra = cat_z.field("ALPHA_J2000")[mask_z]
cat_z_dec = cat_z.field("DELTA_J2000")[mask_z]

dist = 0.5 / 3600
matches = []

for a in range(0,len(cat_r_ra)):
    for b in range(0,len(cat_i_ra)):
        for c in range(0,len(cat_z_ra)):
            if np.sqrt((cat_r_ra[a] - cat_i_ra[b])**2 + (cat_r_dec[a] - cat_i_dec[b])**2) < dist and np.sqrt((cat_r_ra[a] - cat_z_ra[c])**2 + (cat_r_dec[a] - cat_z_dec[c])**2 < dist):
                match = [cat_r_ra[a], cat_r_dec[a], cat_r_MAG[a], cat_r_MAG_ERR[a], cat_i_MAG[b], cat_i_MAG_ERR[b], cat_z_MAG[c], cat_z_MAG_ERR[c]]
                matches.append(match)
matches = np.array(matches)

The problem is, that it takes really long to run. I think the combination of for loops and if statements slows it down. But I am still fairly new to programming in python so I do not know a more efficient way. Is there an efficient way in python to find the matching sources up to some accuracy (in this case 0.5 / 3600)?

Thank you for your help!

Body:
You could try rounding your arrays beforehand. Using the method suggested in the thread you linked, this would give you:

import numpy as np
A = np.array([[ 2.31,  1, 4.33],
              [ 4.46,  3, 10.75]])

B = np.array([[ 2.34,  3,  4.34],
              [ 4.47, 11, 10.78]])

roundedA = np.around(A, decimals=1)
roundedB = np.around(B, decimals=1)

print('%s\n%s\n' % (roundedA, roundedB))
print(set(zip(*roundedA)) & set(zip(*roundedB)))

Output:

[[  2.3   1.    4.3]
 [  4.5   3.   10.8]]
[[  2.3   3.    4.3]
 [  4.5  11.   10.8]]

{(4.2999999999999998, 10.800000000000001), (2.2999999999999998, 4.5)}

Beware of the floating point errors.