问:
clear cache of clients browsers when making changes
When developing a website using HTML/CSS, during the development phase it makes sense to prevent caching as people viewing the website would otherwise see old versions. Ive seen threads on this before using meta tags ie:

```<code><meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />enter code here
</code>```

However this dosent seem to work with HTML5 and similarly I only want to clear clients cache to empty once Ive made an update.

For example if I have an image in index.html and update this image (same filename different content) then clients would see the previous image

Is there a way I can version html pages such that the clients browser would cache version 1 then on reloading If I change the html to version 2 the cache would be emptied and the new website with all changes would be loaded?

Seems this would need to be the case in most web developments otherwise clients would never see changes

答:
In my case, I change a lot an specific JS file and I need it to be in its last version in all browsers where is being used.

I do not have a specific version number for this file, so I simply hash the current date and time (hour and minute) and pass it as the version number:

```<code><script src="/js/panel/app.js?v={{ substr(md5(date("Y-m-d_Hi")),10,18) }}"></script>
</code>```

I need it to be loaded every minute, but you can decide when it should be reloaded.

Body:
When developing a website using HTML/CSS, during the development phase it makes sense to prevent caching as people viewing the website would otherwise see old versions. Ive seen threads on this before using meta tags ie:

<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />enter code here

However this dosent seem to work with HTML5 and similarly I only want to clear clients cache to empty once Ive made an update.

For example if I have an image in index.html and update this image (same filename different content) then clients would see the previous image

Is there a way I can version html pages such that the clients browser would cache version 1 then on reloading If I change the html to version 2 the cache would be emptied and the new website with all changes would be loaded?

Seems this would need to be the case in most web developments otherwise clients would never see changes

Body:
In my case, I change a lot an specific JS file and I need it to be in its last version in all browsers where is being used.

I do not have a specific version number for this file, so I simply hash the current date and time (hour and minute) and pass it as the version number:

<script src="/js/panel/app.js?v={{ substr(md5(date("Y-m-d_Hi")),10,18) }}"></script>

I need it to be loaded every minute, but you can decide when it should be reloaded.


来源: stackexchange

问:
Multiple primary key constraints?
I have a table like this:

```<code>CREATE TABLE BACAEN
(
CAEN_KEY INT PRIMARY NOT NULL,
CAET_KEY INT,
BUUN_KEY INT
)
</code>```

I've already defined primary key on CAEN_KEY column. What I also need is to have unique records for CAET_KEY and BUUN_KEY together. (So, combination with same CAET_KEY / BUUN_KEY is allowed only once). The easiest way would be to generate one more composite primary key, but this is not possible because sql server doesn't allow multiple primary key constraints. What are alternatives to this?

Please note: I can not drop primary key constraint on CAEN_KEY.

答:
Try a unique key Instead. Change the design as follows

```<code>CREATE TABLE BACAEN
(
CAEN_KEY INT PRIMARY KEY,
CAET_KEY INT  NOT NULL,
BUUN_KEY INT  NOT NULL,
CONSTRAINT uq_BACAEN UNIQUE(CAET_KEY , BUUN_KEY );
)
</code>```

Now, both the columns CAET_KEY and BUUN_KEY will be having a unique combination as well as they can't hold NULL values as I have specified them as NOT NULL

If want to allow NULL values to the CAET_KEY and BUUN_KEY, that's also fine but you can have only 1 record with NULL in both fields

ContentLicense: CC BY-SA 3.0

Title: Multiple primary key constraints?

Body:
I have a table like this:

CREATE TABLE BACAEN
(
CAEN_KEY INT PRIMARY NOT NULL,
CAET_KEY INT,
BUUN_KEY INT
)

I've already defined primary key on CAEN_KEY column. What I also need is to have unique records for CAET_KEY and BUUN_KEY together. (So, combination with same CAET_KEY / BUUN_KEY is allowed only once). The easiest way would be to generate one more composite primary key, but this is not possible because sql server doesn't allow multiple primary key constraints. What are alternatives to this?

Please note: I can not drop primary key constraint on CAEN_KEY.

Body:
Try a unique key Instead. Change the design as follows

CREATE TABLE BACAEN
(
CAEN_KEY INT PRIMARY KEY,
CAET_KEY INT  NOT NULL,
BUUN_KEY INT  NOT NULL,
CONSTRAINT uq_BACAEN UNIQUE(CAET_KEY , BUUN_KEY );
)

Now, both the columns CAET_KEY and BUUN_KEY will be having a unique combination as well as they can't hold NULL values as I have specified them as NOT NULL

If want to allow NULL values to the CAET_KEY and BUUN_KEY, that's also fine but you can have only 1 record with NULL in both fields


问:
If statement operator as a variable in ruby
I am trying to do something like this in ruby:

```<code>x = 0
y = 1
z = "!="

if x #{z} y
  puts "True"
end
#True
#=> nil

x = 1
if x #{z} y
  puts "True"
end
#True
#=> nil
</code>```

Using a operator as a variable is not evaluating the expression. Any way to do this.

答:
Try this one

```<code>x = 0
y = 1
z = "!="

x.public_send(z, y)
=> true
</code>```

The trick here is know that 3 >= 5 is syntactic sugar for 3.>=(5)

Body:
I am trying to do something like this in ruby:

x = 0
y = 1
z = "!="

if x #{z} y
  puts "True"
end
#True
#=> nil

x = 1
if x #{z} y
  puts "True"
end
#True
#=> nil

Using a operator as a variable is not evaluating the expression. Any way to do this.

Body:
Try this one

x = 0
y = 1
z = "!="

x.public_send(z, y)
=> true

The trick here is know that 3 >= 5 is syntactic sugar for 3.>=(5)


问:
Java-Swing: A problem using layout managers!
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

```<code>scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();
</code>```

答:
Why not give the "Genes" panel a 2x1 GridLayout? That should ensure that both sides have the same size.

But actually, it would make more sense to me to give the list all space not taken by the controls, since those require a fixed amount of space while the list may benefit from all additional space it can get, if there are wide entries.

To that end, I would give the "Genes" panel a BorderLayout, put the list in the CENTER slot and the controls in the EAST slot.

ContentLicense: CC BY-SA 2.5

Body:
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();


问:
How do I select a node within a template string in html?
Create an element and pass it an innerHTML string.

let mydiv = document.createElement('div');
mydiv.innerHTML = "

Intro

Hello Example

";
console.log(mydiv.getElementByID("greet"))```
</div>
</div>
</p>

<p>.. How do I get the element with id='greet'?</p>

```mydiv.getElementbyID('greet')   //doesn't work.
```

答:
With your code, you can use Element.querySelector instead

You do have a few issues

misspelling getElementByID - should be getElementById

you cannot use Element.getElementById - you can use document.getElementById after inserting the new div into the DOM

querySelector

let mydiv = document.createElement('div');
mydiv.innerHTML = "

Intro

Hello Example

";
console.log(mydiv.querySelector("#greet"))```
</div>
</div>
</p>

<p>Or jQuery: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let $myDiv =$('<div/>');
$myDiv.html("<div> <p>Intro</p> </div> <div id='greet'> <p>Hello Example</p> </div>");
console.log($myDiv.find("#greet"))</code>```

```

Body:
Create an element and pass it an innerHTML string.

let mydiv = document.createElement('div');
mydiv.innerHTML = "

Intro

Hello Example

";
console.log(mydiv.getElementByID("greet"))

.. How do I get the element with id='greet'?

mydiv.getElementbyID('greet')   //doesn't work.

Body:
With your code, you can use Element.querySelector instead

You do have a few issues

misspelling getElementByID - should be getElementById

you cannot use Element.getElementById - you can use document.getElementById after inserting the new div into the DOM

querySelector

let mydiv = document.createElement('div');
mydiv.innerHTML = "<div> <p>Intro</p> </div> <div id='greet'> <p>Hello Example</p> </div>";
console.log(mydiv.querySelector("#greet"))

Or jQuery:

let $myDiv =$('<div/>');
$myDiv.html("<div> <p>Intro</p> </div> <div id='greet'> <p>Hello Example</p> </div>");
console.log($myDiv.find("#greet"))

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>


问:
Android studio Installation error - JDK not detected
Please help me,I already installed java development kit and changed my os environment variables to JAVA_HOME. But still can not install android studio. OS is windows 10 pro. Android studio installation error_jdk could not detected
"System check
We could not detect a java Development kit (JDK) v 7 or newer on your system.Please browse to its path if know:
Or download the following compatible JDK: jdk.7u67-windows-x64.exe and press 'Next' after installation is complete."</p>

答:
Make sure you installed 64 bit jdk if your system is 64 bit first.
Secondly make sure your environment  variable is set right.

set path=C:\Program Files\Java\jdk1.8.0_121\bin:


问:
reference type of exception issue in multi-catch block
e is of type Exception but prints Exception1 in below code:

```<code>class Exception1 extends IOException {void info(){}}
class Exception2 extends Exception {}

class TestMultiCatch {
    public static void main(String args[]) {
        try {
            int a = 10;
            if (a <= 10)
                throw new Exception1();
            else
                throw new Exception2();
        } catch (Exception1 | Exception2 e) {
            e.info();  //line 1 error "The method info() is undefined for type Exception"
            System.out.println(e);   //prints Exception1 (after commenting line 1)
        }
    }
}
</code>```

From what I studied "e" should be of type Exception which is common base class of Exception1 and Exception2. Which it is, as evident from message in line 1.

But then why:

```<code>System.out.println(e); //prints Exception1 and not Exception
System.out.println(e instanceof IOException); //prints true and not false
System.out.println(e instanceof Exception1); //prints true and not false
System.out.println(e instanceof Exception2); //false
</code>```

?
Thanks.

答:
When you use a multi-catch clause (the Exception1 | Exception2 e form of catch), the compile-time type of e is the greatest type that the two types have in common, since of course the code has to handle either type of exception.From the spec:

An exception parameter may denote its type as either a single class type or a union of two or more class types (called alternatives). The alternatives of a union are syntactically separated by |.

A catch clause whose exception parameter is denoted as a single class type is called a uni-catch clause.

A catch clause whose exception parameter is denoted as a union of types is called a multi-catch clause.

...

The declared type of an exception parameter that denotes its type as a union with alternatives D1 | D2 | ... | Dn is lub(D1, D2, ..., Dn).

...where lub is Least Upper Bound as defined here.

If you want to use anything that's specific to Exception1 or Exception2, use separate catch blocks:

```<code>} catch (Exception1 e) {
    // Something using features of Exception1
} catch (Exception2 e) {
    // Something using features of Exception2
}
</code>```

If info exists on both Exception1 and Exception2, refactor them so that info exists on a common ancestor class of them:

```<code>class TheAncestorException extends Exception {
    public void info() { // Or possibly make it abstract
        // ...
    }
}
class Exception1 extends TheAncestorException {
    // Optionally override `info` here
}
class Exception2 extends TheAncestorException {
    // Optionally override `info` here
}
</code>```

...so the compiler can give e the type TheAncestorException and make info accessible.

Body:
e is of type Exception but prints Exception1 in below code:

class Exception1 extends IOException {void info(){}}
class Exception2 extends Exception {}

class TestMultiCatch {
    public static void main(String args[]) {
        try {
            int a = 10;
            if (a <= 10)
                throw new Exception1();
            else
                throw new Exception2();
        } catch (Exception1 | Exception2 e) {
            e.info();  //line 1 error "The method info() is undefined for type Exception"
            System.out.println(e);   //prints Exception1 (after commenting line 1)
        }
    }
}

From what I studied "e" should be of type Exception which is common base class of Exception1 and Exception2. Which it is, as evident from message in line 1.

But then why:

System.out.println(e); //prints Exception1 and not Exception
System.out.println(e instanceof IOException); //prints true and not false
System.out.println(e instanceof Exception1); //prints true and not false
System.out.println(e instanceof Exception2); //false

?
Thanks.

Body:
When you use a multi-catch clause (the Exception1 | Exception2 e form of catch), the compile-time type of e is the greatest type that the two types have in common, since of course the code has to handle either type of exception.From the spec:

An exception parameter may denote its type as either a single class type or a union of two or more class types (called alternatives). The alternatives of a union are syntactically separated by |.

A catch clause whose exception parameter is denoted as a single class type is called a uni-catch clause.

A catch clause whose exception parameter is denoted as a union of types is called a multi-catch clause.

...

The declared type of an exception parameter that denotes its type as a union with alternatives D1 | D2 | ... | Dn is lub(D1, D2, ..., Dn).

...where lub is Least Upper Bound as defined here.

If you want to use anything that's specific to Exception1 or Exception2, use separate catch blocks:

} catch (Exception1 e) {
    // Something using features of Exception1
} catch (Exception2 e) {
    // Something using features of Exception2
}

If info exists on both Exception1 and Exception2, refactor them so that info exists on a common ancestor class of them:

class TheAncestorException extends Exception {
    public void info() { // Or possibly make it abstract
        // ...
    }
}
class Exception1 extends TheAncestorException {
    // Optionally override `info` here
}
class Exception2 extends TheAncestorException {
    // Optionally override `info` here
}

...so the compiler can give e the type TheAncestorException and make info accessible.


问:
How to create a single color image using ImageView in android programmatically?
Is there any way to create an image using ImageView containing a solid single color programmatically?</p>

答:
You do not need ImageView for that. Any view (i.e. FrameLayout) will do as long as you set its background color to what you need using just setBackgroundColor() or XML android:background attribute, i.e.

```<code><FrameLayout
   android:layout_width="100dp"
   android:layout_height="100dp"
   android:background="#ff0000 />
</code>```

Body:
You do not need ImageView for that. Any view (i.e. FrameLayout) will do as long as you set its background color to what you need using just setBackgroundColor() or XML android:background attribute, i.e.

<FrameLayout
   android:layout_width="100dp"
   android:layout_height="100dp"
   android:background="#ff0000 />


问:
rails 3 paperclip imagemagick problem
I have been trying to get paperclip working for a few days now with no luck! From what I am aware this error below is related to imagemagick. I have tried to uninstall and install imagemagick both with macports and manually. Also, have Paperclip.options[:command_path] = "/usr/local/bin" set. It's starting to drive me nuts!

Photo /var/folders/A7/A7X8PAnOFsCTHkFpeODoO++++TI/-Tmp-/stream,65411,0.jpeg is not recognized by the 'identify' command.

I'm running snow leopard.

This appears when I run the rails server..
"/Users/michaelorcutt/shudder/vendor/plugins/paperclip/lib/paperclip.rb:50: warning: already initialized constant VERSION"

答:
Here is the list of things that needs to be checked for error "NotIdentifiedByImageMagickError":

Ensure that Imagemagick is installed on your system and its in the ENV path
try the command $ which identify Or $which convert.
For Ubuntu its usally in /usr/local/bin or /usr/bin.

Note the path of the above command and update the config/environments/development.rb (if
you are working in dev mode) with the following line.

   ```<code>Paperclip.options[:command_path]= '/usr/bin'</code>```

Incase, if you are still facing the issue check the installation of ImageMagick. If you installed from the source, the may be try packaged installation ( sudo apt-get install imagemagick)

~arunky

Title: rails 3 paperclip imagemagick problem

Body:
Here is the list of things that needs to be checked for error "NotIdentifiedByImageMagickError":

Ensure that Imagemagick is installed on your system and its in the ENV path
try the command $ which identify Or $which convert.
For Ubuntu its usally in /usr/local/bin or /usr/bin.

Note the path of the above command and update the config/environments/development.rb (if
you are working in dev mode) with the following line.

Paperclip.options[:command_path]= '/usr/bin'

Incase, if you are still facing the issue check the installation of ImageMagick. If you installed from the source, the may be try packaged installation ( sudo apt-get install imagemagick)

~arunky


问:
C# - Winforms - Global Variables
I want some variables to be global across the project and accessible in every form. How can I do this?</p>

答:
If you're using Visual C#, all you need to do is add a class in Program.cs inheriting Form and change all the inherited class from Form to your class in every Form*.cs.

```<code>//Program.cs
public class Forms : Form
{
    //Declare your global valuables here.
}

//Form1.cs
public partial class Form1 : Forms    //Change from Form to Forms
{
    //...
}
</code>```

Of course, there might be a way to extending the class Form without modifying it. If that's the case, all you need to do is extending it! Since all the forms are inheriting it by default, so all the valuables declared in it will become global automatically! Good luck!!!

Title: C# - Winforms - Global Variables

Body:
If you're using Visual C#, all you need to do is add a class in Program.cs inheriting Form and change all the inherited class from Form to your class in every Form*.cs.

//Program.cs
public class Forms : Form
{
    //Declare your global valuables here.
}

//Form1.cs
public partial class Form1 : Forms    //Change from Form to Forms
{
    //...
}

Of course, there might be a way to extending the class Form without modifying it. If that's the case, all you need to do is extending it! Since all the forms are inheriting it by default, so all the valuables declared in it will become global automatically! Good luck!!!


问:
< followed by space or not in regex
I have a multi-line textbox, if I enter below string:

```<code>index a<3

2<x
</code>```

By using regex I need to add space after character '<' if there is no space.
And if already have space after character '<' then keep as it is don't add additional space.

Expected result should be:

```<code>index a< 3

2< x
</code>```

I tried (?<=<)(?!$) and <[^\s]+  these but giving syntax error, when used inside Javascript.

I can use them in back end(C#) but I don't want to put server request for it, as it not a good option.

答: Use the following simple regex: <\b and replace it with < ('<' followed by a space)

Title: < followed by space or not in regex

Body:
I have a multi-line textbox, if I enter below string:

index a<3

2<x

By using regex I need to add space after character '<' if there is no space.
And if already have space after character '<' then keep as it is don't add additional space.

Expected result should be:

index a< 3

2< x

I tried (?<=<)(?!$) and <[^\s]+  these but giving syntax error, when used inside Javascript.

I can use them in back end(C#) but I don't want to put server request for it, as it not a good option.


问:
Index on JSON field with dynamic keys
I'm on PG 9.5 and I have a table Visitors(id, data::json)

Example:

```<code>Visitor(id: 1, data: {name: 'Jack', age: 33, is_user: true })
</code>```

I'd like to perform queries like

Give me all visitors named Jack and age > 25

Give me all visitors who are users, but where name is unspecified (key not in json)

The keys inside the data column user-specified and as such are dynamic.

Which index makes the most sense in this situation?

答:
You can look at additional extension JsQuery – is a language to query jsonb data type, it provides an additional functionality to jsonb (currently missing in PostgreSQL), such as a simple and effective way to search in nested objects and arrays, more comparison operators with indexes support. Read more here: https://github.com/postgrespro/jsquery.

In your cases, you can create jsonb_path_value_ops index:

```<code>CREATE INDEX idx_visitors ON visitors USING GIN (jsonb jsonb_path_value_ops);
</code>```

and use the next queries:

```<code>select * from visitors where jsonb @@ 'name = "Jack" and age > 25';
select * from visitors where jsonb @@ 'not name = * and is_user=true';
</code>```

Title: Index on JSON field with dynamic keys

Body:
I'm on PG 9.5 and I have a table Visitors(id, data::json)

Example:

Visitor(id: 1, data: {name: 'Jack', age: 33, is_user: true })

I'd like to perform queries like

Give me all visitors named Jack and age > 25

Give me all visitors who are users, but where name is unspecified (key not in json)

The keys inside the data column user-specified and as such are dynamic.

Which index makes the most sense in this situation?

Body:
You can look at additional extension JsQuery – is a language to query jsonb data type, it provides an additional functionality to jsonb (currently missing in PostgreSQL), such as a simple and effective way to search in nested objects and arrays, more comparison operators with indexes support. Read more here: https://github.com/postgrespro/jsquery.

In your cases, you can create jsonb_path_value_ops index:

CREATE INDEX idx_visitors ON visitors USING GIN (jsonb jsonb_path_value_ops);

and use the next queries:

select * from visitors where jsonb @@ 'name = "Jack" and age > 25';
select * from visitors where jsonb @@ 'not name = * and is_user=true';


问:
Wrong console read
Task: Converts Ohm's from 1 kOhm to 1000 Ohm etc. and find max and min values.

Example:

1 kOhm

2 Ohm

And after convert to

1000 Ohm

2 Ohm

But after input get only

1 kOhm

Ohm

Input must be with spaces. Program drops 1 char from every new line after first. I try using wscanf and other thinks but it isn't workig for me.

P.S. I must use wchar_t

```<code>#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>

int pow(int base, int exp) {
  if (exp < 0)
    return -1;

  int result = 1;
  while (exp) {
    if (exp & 1)
      result *= base;
    exp >>= 1;
    base *= base;
  }

  return result;
}
int transformSize(wchar_t name) {

  if (name == L'h') {
    return 2;
  } else if (name == L'k') {
    return 3;
  } else if (name == L'M') {
    return 6;
  } else if (name == L'G') {
    return 9;
  } else if (name == L'T') {
    return 12;
  } else if (name == L'P') {
    return 15;
  } else if (name == L'E') {
    return 18;
  } else if (name == L'Z') {
    return 21;
  } else if (name == L'Y') {
    return 24;
  }

  return 0;
}

int main() {

  unsigned int *numbers;
  unsigned int min = 0;
  unsigned int max = 0;
  int n = 0;
  wchar_t **array;
  setlocale(LC_ALL, "");

  wprintf(L"Enter n: ");
  wscanf(L"%d", &n);

  array = malloc(n * sizeof(wchar_t *));
  numbers = malloc(n * sizeof(unsigned int *));

  wprintf(L"Enter n-elements: \n");

  for (int i = 0; i < n; i++) {
    wchar_t temp;
    array[i] = malloc(256 * sizeof(wchar_t));
    wscanf(L"%c", &temp);
    fgetws(array[i], 2560, stdin);
  }

  wprintf(L"\n\nStart array: [");

  for (int i = 0; i < n; i++) {
    wprintf(L" ");
    wprintf(L"%ls", array[i]);
    wprintf(L" ");
  }

  wprintf(L"]\n\n");

  for (int i = 0; i < n; i++) {
    int spaceIndex = 0;
    for (int j = 0; j < wcslen(array[i]); j++) {
      if (array[i][j] != ' ') {
        spaceIndex++;
      } else {
        break;
      }
    }

    wchar_t *new = malloc(sizeof(wchar_t) * spaceIndex + 1);
    wcsncpy(new, array[i], spaceIndex);
    new[n] = '\0';
    numbers[i] = wcstol(new, (wchar_t **)NULL, 10) *
                 (pow(10.0, (double)transformSize(array[i][spaceIndex + 1])));

    if (i == 0) {
      min = numbers[i];
      max = numbers[i];
    }

    if (numbers[i] >= max) {
      max = numbers[i];
    }

    if (numbers[i] <= min) {
      min = numbers[i];
    }

    free(new);
  }

  wprintf(L"Converted array: [");

  for (int i = 0; i < n; i++) {
    wprintf(L" %ld Ohm ", numbers[i]);
  }

  wprintf(L"]\n\n");

  wprintf(L"Max element: %ld Ohm\n", max);
  wprintf(L"Min element: %ld Ohm\n", min);

  for (int i = 0; i < n; i++) {
    free(array[i]);
  }

  free(array);

  return 0;
}
</code>```

Example of current program input/output:

```<code>Enter n: 3
Enter n-elements:

12 kOhm
3 kOhm
1 Ohm

// Must be 12 kOhm, 3 kOhm, 1 Om
Start array: [ 12 kOhm
   kOhm
   Ohm
 ]
// Must be 12000 Ohm, 3000 Ohm, 1 Ohm
Converted array: [ 12000 Ohm  0 Ohm  0 Ohm ]

Max element: 12000 Ohm
Min element: 0 Ohm
</code>```

答:
Mixing fgetsw and wscanf is a bad idea.

The problem is here:

```<code>  ...
  for (int i = 0; i < n; i++) {
    wchar_t temp;
    array[i] = malloc(256 * sizeof(wchar_t));
    wscanf(L"%c", &temp);
    fgetws(array[i], 2560, stdin);
  }
  ...
</code>```

You are using wscanf(L"%c", &temp); to absorb the line feed that is left over from wscanf. You should do this only once after the wscanflike this:

```<code>  ...
  wchar_t temp;
  wscanf(L"%c", &temp);

  for (int i = 0; i < n; i++) {
    array[i] = malloc(256 * sizeof(wchar_t));
    fgetws(array[i], 2560, stdin);
  }
  ...
</code>```

But the best would be not to mix wscanf and fgetsw in first place.

I suppose you use Visual Studio. If yes, learn how to use the debugger, it's very easy to use and very powerful. If no, learn how to use your debugger anyway.

But further in your program there may be other problems unrelated to your question, I didn't check.

Title: Wrong console read

Body:
Task: Converts Ohm's from 1 kOhm to 1000 Ohm etc. and find max and min values.

Example:

1 kOhm

2 Ohm

And after convert to

1000 Ohm

2 Ohm

But after input get only

1 kOhm

Ohm

Input must be with spaces. Program drops 1 char from every new line after first. I try using wscanf and other thinks but it isn't workig for me.

P.S. I must use wchar_t

#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>

int pow(int base, int exp) {
  if (exp < 0)
    return -1;

  int result = 1;
  while (exp) {
    if (exp & 1)
      result *= base;
    exp >>= 1;
    base *= base;
  }

  return result;
}
int transformSize(wchar_t name) {

  if (name == L'h') {
    return 2;
  } else if (name == L'k') {
    return 3;
  } else if (name == L'M') {
    return 6;
  } else if (name == L'G') {
    return 9;
  } else if (name == L'T') {
    return 12;
  } else if (name == L'P') {
    return 15;
  } else if (name == L'E') {
    return 18;
  } else if (name == L'Z') {
    return 21;
  } else if (name == L'Y') {
    return 24;
  }

  return 0;
}

int main() {

  unsigned int *numbers;
  unsigned int min = 0;
  unsigned int max = 0;
  int n = 0;
  wchar_t **array;
  setlocale(LC_ALL, "");

  wprintf(L"Enter n: ");
  wscanf(L"%d", &n);

  array = malloc(n * sizeof(wchar_t *));
  numbers = malloc(n * sizeof(unsigned int *));

  wprintf(L"Enter n-elements: \n");

  for (int i = 0; i < n; i++) {
    wchar_t temp;
    array[i] = malloc(256 * sizeof(wchar_t));
    wscanf(L"%c", &temp);
    fgetws(array[i], 2560, stdin);
  }

  wprintf(L"\n\nStart array: [");

  for (int i = 0; i < n; i++) {
    wprintf(L" ");
    wprintf(L"%ls", array[i]);
    wprintf(L" ");
  }

  wprintf(L"]\n\n");

  for (int i = 0; i < n; i++) {
    int spaceIndex = 0;
    for (int j = 0; j < wcslen(array[i]); j++) {
      if (array[i][j] != ' ') {
        spaceIndex++;
      } else {
        break;
      }
    }

    wchar_t *new = malloc(sizeof(wchar_t) * spaceIndex + 1);
    wcsncpy(new, array[i], spaceIndex);
    new[n] = '\0';
    numbers[i] = wcstol(new, (wchar_t **)NULL, 10) *
                 (pow(10.0, (double)transformSize(array[i][spaceIndex + 1])));

    if (i == 0) {
      min = numbers[i];
      max = numbers[i];
    }

    if (numbers[i] >= max) {
      max = numbers[i];
    }

    if (numbers[i] <= min) {
      min = numbers[i];
    }

    free(new);
  }

  wprintf(L"Converted array: [");

  for (int i = 0; i < n; i++) {
    wprintf(L" %ld Ohm ", numbers[i]);
  }

  wprintf(L"]\n\n");

  wprintf(L"Max element: %ld Ohm\n", max);
  wprintf(L"Min element: %ld Ohm\n", min);

  for (int i = 0; i < n; i++) {
    free(array[i]);
  }

  free(array);

  return 0;
}

Example of current program input/output:

Enter n: 3
Enter n-elements:

12 kOhm
3 kOhm
1 Ohm

// Must be 12 kOhm, 3 kOhm, 1 Om
Start array: [ 12 kOhm
   kOhm
   Ohm
 ]
// Must be 12000 Ohm, 3000 Ohm, 1 Ohm
Converted array: [ 12000 Ohm  0 Ohm  0 Ohm ]

Max element: 12000 Ohm
Min element: 0 Ohm

Body:
Mixing fgetsw and wscanf is a bad idea.

The problem is here:

  ...
  for (int i = 0; i < n; i++) {
    wchar_t temp;
    array[i] = malloc(256 * sizeof(wchar_t));
    wscanf(L"%c", &temp);
    fgetws(array[i], 2560, stdin);
  }
  ...

You are using wscanf(L"%c", &temp); to absorb the line feed that is left over from wscanf. You should do this only once after the wscanflike this:

  ...
  wchar_t temp;
  wscanf(L"%c", &temp);

  for (int i = 0; i < n; i++) {
    array[i] = malloc(256 * sizeof(wchar_t));
    fgetws(array[i], 2560, stdin);
  }
  ...

But the best would be not to mix wscanf and fgetsw in first place.

I suppose you use Visual Studio. If yes, learn how to use the debugger, it's very easy to use and very powerful. If no, learn how to use your debugger anyway.

But further in your program there may be other problems unrelated to your question, I didn't check.


问:
static variables in c
Static variables when declared in a file cannot be accessed from outside the file.
But if we declare a static variable inside a file and a global pointer and then assign the address of the static variable to the pointer and then externing the pointer, it can be accessed.

So is it right saying that static variables can't be accessed directly but it can be accessed indirectly using global pointers and then externing?

答:
It is not correct to say that static variables "cannot be accessed" from outside. Being declared static has absolutely nothing to do with the possibility of the outside access.

When some entity is declared static it only means that this entity will not be associated with other entities of the same name in other translation units.

For example, when you declare two extern variables names a in different translation units, these variables are actually the same, single variable. When you declare two static variables named a in different translation units, these variables are two different independent variables. This is what static does in C. Nothing else.

Speaking in more everyday terms, it is not possible to link to static variables from outside, i.e. it is not possible to ask linker to let us access static variable by name from outside. However, it is always possible to access it in some other way, like through a pointer, assuming that you managed to obtain that pointer somehow.

OwnerDisplayName: maddy

Title: static variables in c


问:
Printing the exception message in an Ada Last_Chance_Handler
I'm in the process of learning Ada using the GNAT compiler using the AdaCore GPS (GPL) IDE, aimed at ARM "bare board" hardware (STM32F4 using a Ravenscar SFP runtime).

For my ARM based embedded work I've come from a C/C++ background.

Anyway, I've implemented a "last chance handler" that's defined as follows,

```<code>procedure Last_Chance_Handler (Msg : System.Address; Line : Integer);
pragma Export (C, Last_Chance_Handler, "__gnat_last_chance_handler");
</code>```

Here's the actual procedure (a snippet from the .adb file),

```<code>procedure Last_Chance_Handler (Msg : System.Address; Line : Integer) is
begin
   LEDs_All_On;
   -- Put_Line("Detail :" & Address_To_String(Msg));
   Put_Line("Line   :" & Line'Image);

   loop
      null;
   end loop;
end Last_Chance_Handler;
</code>```

The Msg argument is documented as follows,

The Msg parameter is a C null-terminated string representing the
  source location of the raise statement, as generated by the compiler,
  or a zero-length string if pragma Suppress_Exception_Locations is
  used.

I've been trying to figure out how to convert the null terminated Msg bytes to an Ada string so that I can display it using a Put_Line() call (when debugging I can access this type of output via the semihosting mechanism).

I've previously mapped Ada records (representing device registers etc.) to physical memory addresses by setting their 'Address attribute to a constant value. However, this is the first time I've tried access memory via a System.Address value held in a variable.

Can anyone suggest how I might go about implementing the Address_To_String() procedure?

I have experimented with Ada byte arrays and unchecked conversions between them and System.Address, also with Ada pointers, but so far I've not had any success.

Any help or suggestions would be greatly appreciated!

Many thanks,

...Max

答: The operation you are looking for is probably Interfaces.C.Strings.Value.  It takes an argument of the type Interfaces.C.Strings.chars_ptr (equivalent to char * in C) and returns a String.

Body:
I'm in the process of learning Ada using the GNAT compiler using the AdaCore GPS (GPL) IDE, aimed at ARM "bare board" hardware (STM32F4 using a Ravenscar SFP runtime).

For my ARM based embedded work I've come from a C/C++ background.

Anyway, I've implemented a "last chance handler" that's defined as follows,

procedure Last_Chance_Handler (Msg : System.Address; Line : Integer);
pragma Export (C, Last_Chance_Handler, "__gnat_last_chance_handler");

Here's the actual procedure (a snippet from the .adb file),

procedure Last_Chance_Handler (Msg : System.Address; Line : Integer) is
begin
   LEDs_All_On;
   -- Put_Line("Detail :" & Address_To_String(Msg));
   Put_Line("Line   :" & Line'Image);

   loop
      null;
   end loop;
end Last_Chance_Handler;

The Msg argument is documented as follows,

The Msg parameter is a C null-terminated string representing the
  source location of the raise statement, as generated by the compiler,
  or a zero-length string if pragma Suppress_Exception_Locations is
  used.

I've been trying to figure out how to convert the null terminated Msg bytes to an Ada string so that I can display it using a Put_Line() call (when debugging I can access this type of output via the semihosting mechanism).

I've previously mapped Ada records (representing device registers etc.) to physical memory addresses by setting their 'Address attribute to a constant value. However, this is the first time I've tried access memory via a System.Address value held in a variable.

Can anyone suggest how I might go about implementing the Address_To_String() procedure?

I have experimented with Ada byte arrays and unchecked conversions between them and System.Address, also with Ada pointers, but so far I've not had any success.

Any help or suggestions would be greatly appreciated!

Many thanks,

...Max


问:
okio.Base64.encode ArrayIndexOutOfBoundsException why is that even happening?
I noticed such exception in fabric, which is occurring rarely but with every build, 3-5 crashes every week on 2-3 users (from ~500 DAU)
I didn't found any information about such crashes, does anyone knows what causes them?

I've found only one question about such issue but it was deleted as "duplicate" https://stackoverflow.com/questions/45868217/arrayindexoutofboundsexception-trying-to-cache-certificate-list-in-okhttp3

```<code>Fatal Exception: java.lang.ArrayIndexOutOfBoundsException
length=1305; index=1953974520

okio.Base64.encode (Base64.java:137)
okio.Base64.encode (Base64.java:125)
okio.ByteString.base64 (ByteString.java:105)
okhttp3.Cache$Entry.writeCertList (Cache.java:686)
okhttp3.Cache$Entry.writeTo (Cache.java:645)
okhttp3.Cache.put (Cache.java:249)
okhttp3.Cache.access$000 (Cache.java:136)
okhttp3.Cache$1.put (Cache.java:148)
okhttp3.internal.cache.CacheInterceptor.maybeCache (CacheInterceptor.java:173)
okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.java:143)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)
okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:93)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:124)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)
</code>```

UPDATE:

https://github.com/square/okio/issues/325 Okio ticket for this issue
https://issuetracker.google.com/issues/69364976 Google ticket for this issue

UPDATE 2:
was fixed in Android Studio 3.1 Canary 6 Build

答: It’s a bug in either the VM or the infrastructure around the VM (the CPU?, the memory?). There’s no other way a value i, that loops between 0 and an array’s length, can go out of bounds like this.

Body:
I noticed such exception in fabric, which is occurring rarely but with every build, 3-5 crashes every week on 2-3 users (from ~500 DAU)
I didn't found any information about such crashes, does anyone knows what causes them?

I've found only one question about such issue but it was deleted as "duplicate" https://stackoverflow.com/questions/45868217/arrayindexoutofboundsexception-trying-to-cache-certificate-list-in-okhttp3

Fatal Exception: java.lang.ArrayIndexOutOfBoundsException
length=1305; index=1953974520

okio.Base64.encode (Base64.java:137)
okio.Base64.encode (Base64.java:125)
okio.ByteString.base64 (ByteString.java:105)
okhttp3.Cache$Entry.writeCertList (Cache.java:686)
okhttp3.Cache$Entry.writeTo (Cache.java:645)
okhttp3.Cache.put (Cache.java:249)
okhttp3.Cache.access$000 (Cache.java:136)
okhttp3.Cache$1.put (Cache.java:148)
okhttp3.internal.cache.CacheInterceptor.maybeCache (CacheInterceptor.java:173)
okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.java:143)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)
okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:93)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:124)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)

UPDATE:

https://github.com/square/okio/issues/325 Okio ticket for this issue
https://issuetracker.google.com/issues/69364976 Google ticket for this issue

UPDATE 2:
was fixed in Android Studio 3.1 Canary 6 Build


问:
On mobile phones have to click twice to click button
I have a question. I have some product blocks where a transparent overlay comes over the product block where the buttons to show information or place in cart are shown. I use a small JavaScript function on the href>, but the issue is, when the product block is clicked on mobile phones, the overlay comes up, but you have to click twice to reach the buttons, because somehow it first clicks the href>

this is the product block:

```<code><div class="block shadow1">
  <a href="" class="trigger"></a>
  <div class="overlay"></div>
  <div class="overlay-content smaller">
    <div class="align">
      <div class="vertical">
        <a href="'.$permalink.'" title="'.$title.'">
          <div class="button permalink">
            <div class="align">
              <div class="vertical">
                <img src="'.$imagesrc.'/images/info.svg">
              </div>
            </div>
          </div>
        </a>
        <div class="button transparent add-to-cart">
          <div class="align">
            <div class="vertical">
              <img src="'.$imagesrc.'/images/add-to-cart_1.svg">
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

And this is the JavaScript:

```<code>$('a.trigger').on('click', function() {
  $(this).toggle('static');
    return false;
});
</code>```

答:
```<code> $('a.trigger').unbind("click").click(function(){
      $(this).toggle('static');
        return false;
    });
</code>```

Body:
I have a question. I have some product blocks where a transparent overlay comes over the product block where the buttons to show information or place in cart are shown. I use a small JavaScript function on the , but the issue is, when the product block is clicked on mobile phones, the overlay comes up, but you have to click twice to reach the buttons, because somehow it first clicks the

this is the product block:

And this is the JavaScript:

$('a.trigger').on('click', function() {
  $(this).toggle('static');
    return false;
});


问:
How to read a full UTF-8 hexadecimal values into an int
What I am trying to do is get an int to take in an UTF-8-16-32 character, in doing so it should be able to tell whether it is UTF-8, UTF-16, or UTF-32.

I read binary values from a text file using fopen(fp, "rb"). I run into a problem where a single character is split into two bytes.

For instance, if I try to read a character CENT SIGN

The text file input.txt contains:

```<code>¢
</code>```

I get:

```<code>utf code:       LATIN CAPITAL LETTER A WITH CIRCUMFLEX
binary:         11000010
hexadecimal:    0xC2
decimal:        194
character:      �

utf code:       CENT SIGN
binary:         10100010
hexadecimal:    0xA2
decimal:        162
character:      �

utf code:       LINE FEED (LF)
binary:         00001010
hexadecimal:    0xA
decimal:        10
character:
</code>```

Code:

```<code>int ch;
while ((ch = fgetc(stream)) != EOF) {
    printf(“utf code:\t”);
    findCode(ch); // HERE

    write(1, “binary:         “, 16);
    printBits(ch);

    printf(“\nhexadecimal:\t%X”, ch);

    printf(“\ndecimal:\t%d”, ch);

    printf(“\ncharacter:\t%c\n\n”, ch);
}
</code>```

NOTE: On a UTF-8 database, the binary value for CENT SIGN is 0xC2A2 or 11000010:10100010

答:
You simply can't detect which UTF-what? encoding is used by your data as UTF-??? is an encoding for UTF characters.

Fortunately, tagging the encoding of data is something that can be used in your data, but it's not mandatory.  BOM has been issued almost (see note) for that purpose, but you'll find plenty of UTF documents (in whatever encoding you can have) that lack of following this approach.  The same bit pattern will mean different things in UTF-8, UTF-16 or UTF-32 encodings, so you'll have to search for encoding errors to discard (possibly them all) the invalid encodings to guess the correct one.

If the document has a BOM mark at the beginning, that sequence of bytes will allow you to detect which encoding is being made, as it's representation gets different patterns depending on the actual encoding.

```<code>0xef, 0xbb, 0xbf  => UTF-8 (no endianness)
0xfe, 0xff        => UTF-16-BE (big endian)
0xff, 0xfe        => UTF-16-LE (little endian)
0x00, 0x00, 0xfe, 0xff => UTF-32-BE (big endian)
0xff, 0xfe, 0x00, 0x00 => UTF-32-LE (little endian)
</code>```

But as you can see, UTF-32-LE begins the same as UTF-16-LE, and UTF-32-BE begins the same as UTF-16-BE, so this doesn't answer completely your question.  For example, a file with the sequence 0xff, 0xfe, 0x00, 0x00  is a perfectly valid file in UTF-32-LE with no data (only the BOM) or a perfectly valid file in UTF-16-LE with a Unicode Character 'NULL' U+0000 character.

The best approach is to pass the encoding as a parameter to the input routines, so they can decode the data appropiately.

Edit

In the example you use, the character CENT SIGN is passed (well, i'll suppose you mean you have the character code U+00A2 which is represented as the number, in binary (completed to the 21 bit representation of a UTF code) 00000000010100010.  If you encode this character as a UTF-8, you will get a two character encoding like: 0xe2, 0xa2, when you encode it as a UTF-16-LE you'll get: 0xa2, 0x00, if you encode it as UTF-16-BE, you'll get 0x00, 0xa2, if you encode it as UTF-32-LE, you'll get 0xa2, 0x00, 0x00, 0x00 and if you encode it as UTF-32-BE, you'll get 0x00, 0x00, 0x00, 0xa2.  The problem here is that you are using sequences of 4 bytes to represent all unicodes, when encoding UTF-32 (and different order, depending if you do it on big endian encoding or little endian) and as sequences of 2 bytes when you do it in UTF-16 (almost all unicodes fall below the limit U+10000, so almost all can be represented as single utf-16 codes, using the surrogate pairs, when they dont fit in 16 bits) and as sequences from 1 to 4 bytes, when using UTF-8 encoding.  So, the first thing you have to know, is that the unicode CODE POINT is different from the encoding used to represent it (and this already has the encoding stuck to it) and so, you cannot know which encoding has been use to encode a unicode char, by making tests to the code point (the numerical order of the character in the whole unicode table)

Note

BOM is an alternate use of the Not a character U+fffe character.  When it is put at the beginning of a document, it switches its meaning to represent de Byte Order Mark character, so this is unfortunate, as it forces you to include it twice in case you want to begin a document with it.  By the way, this character by definition is not a character so you will seldom see it as a normal document character.  It is normally used as a substitution character when some decoding occurs in a UTF document.

CREDITS

The BOM representation table has been drawn from the Wikipedia page

Body:
What I am trying to do is get an int to take in an UTF-8-16-32 character, in doing so it should be able to tell whether it is UTF-8, UTF-16, or UTF-32.

I read binary values from a text file using fopen(fp, "rb"). I run into a problem where a single character is split into two bytes.

For instance, if I try to read a character CENT SIGN

The text file input.txt contains:

¢

I get:

utf code:       LATIN CAPITAL LETTER A WITH CIRCUMFLEX
binary:         11000010
hexadecimal:    0xC2
decimal:        194
character:      �

utf code:       CENT SIGN
binary:         10100010
hexadecimal:    0xA2
decimal:        162
character:      �

utf code:       LINE FEED (LF)
binary:         00001010
hexadecimal:    0xA
decimal:        10
character:

Code:

int ch;
while ((ch = fgetc(stream)) != EOF) {
    printf(“utf code:\t”);
    findCode(ch); // HERE

    write(1, “binary:         “, 16);
    printBits(ch);

    printf(“\nhexadecimal:\t%X”, ch);

    printf(“\ndecimal:\t%d”, ch);

    printf(“\ncharacter:\t%c\n\n”, ch);
}

NOTE: On a UTF-8 database, the binary value for CENT SIGN is 0xC2A2 or 11000010:10100010

Body:
You simply can't detect which UTF-what? encoding is used by your data as UTF-??? is an encoding for UTF characters.

Fortunately, tagging the encoding of data is something that can be used in your data, but it's not mandatory.  BOM has been issued almost (see note) for that purpose, but you'll find plenty of UTF documents (in whatever encoding you can have) that lack of following this approach.  The same bit pattern will mean different things in UTF-8, UTF-16 or UTF-32 encodings, so you'll have to search for encoding errors to discard (possibly them all) the invalid encodings to guess the correct one.

If the document has a BOM mark at the beginning, that sequence of bytes will allow you to detect which encoding is being made, as it's representation gets different patterns depending on the actual encoding.

0xef, 0xbb, 0xbf  => UTF-8 (no endianness)
0xfe, 0xff        => UTF-16-BE (big endian)
0xff, 0xfe        => UTF-16-LE (little endian)
0x00, 0x00, 0xfe, 0xff => UTF-32-BE (big endian)
0xff, 0xfe, 0x00, 0x00 => UTF-32-LE (little endian)

But as you can see, UTF-32-LE begins the same as UTF-16-LE, and UTF-32-BE begins the same as UTF-16-BE, so this doesn't answer completely your question.  For example, a file with the sequence 0xff, 0xfe, 0x00, 0x00  is a perfectly valid file in UTF-32-LE with no data (only the BOM) or a perfectly valid file in UTF-16-LE with a Unicode Character 'NULL' U+0000 character.

The best approach is to pass the encoding as a parameter to the input routines, so they can decode the data appropiately.

Edit

In the example you use, the character CENT SIGN is passed (well, i'll suppose you mean you have the character code U+00A2 which is represented as the number, in binary (completed to the 21 bit representation of a UTF code) 00000000010100010.  If you encode this character as a UTF-8, you will get a two character encoding like: 0xe2, 0xa2, when you encode it as a UTF-16-LE you'll get: 0xa2, 0x00, if you encode it as UTF-16-BE, you'll get 0x00, 0xa2, if you encode it as UTF-32-LE, you'll get 0xa2, 0x00, 0x00, 0x00 and if you encode it as UTF-32-BE, you'll get 0x00, 0x00, 0x00, 0xa2.  The problem here is that you are using sequences of 4 bytes to represent all unicodes, when encoding UTF-32 (and different order, depending if you do it on big endian encoding or little endian) and as sequences of 2 bytes when you do it in UTF-16 (almost all unicodes fall below the limit U+10000, so almost all can be represented as single utf-16 codes, using the surrogate pairs, when they dont fit in 16 bits) and as sequences from 1 to 4 bytes, when using UTF-8 encoding.  So, the first thing you have to know, is that the unicode CODE POINT is different from the encoding used to represent it (and this already has the encoding stuck to it) and so, you cannot know which encoding has been use to encode a unicode char, by making tests to the code point (the numerical order of the character in the whole unicode table)

Note

BOM is an alternate use of the Not a character U+fffe character.  When it is put at the beginning of a document, it switches its meaning to represent de Byte Order Mark character, so this is unfortunate, as it forces you to include it twice in case you want to begin a document with it.  By the way, this character by definition is not a character so you will seldom see it as a normal document character.  It is normally used as a substitution character when some decoding occurs in a UTF document.

CREDITS

The BOM representation table has been drawn from the Wikipedia page


问:
Bitfield width in inspect
Currently working on a project where the data I am importing for my registers has very long bitfield names.  The current '13' width limit on inspect makes the registers completely unreadable as the first 13 characters are identical.

I have hacked at reg.rb to report inspect in nibbles instead of bytes just by replacing all the 8s with 4s.  If there are no better ideas, I was going to attempt to add something to do this automatically if the bit width is larger than 13.

Thoughts?

答:
Seems like a good idea, maybe also give the user the ability to override the 13 width limit via an environment variable or something?

Maybe a combination would be good:

Allow the user to increase the width past 13 if they want

At render time have a look to see if any truncation is happening for the current width/register combination and if so automatically drop down to the nibble view

Title: Bitfield width in inspect


问:
Multiple line content in cell fpdf
i am creating an invoice application and using fpdf and https://github.com/farjadtahir/pdf-invoicr pdf-invoicr class. Its working fine but now i have multi line content in database like address, when i am saving the textarea content from form it will save with br tag,

```<code>nl2br(htmlentities($address, ENT_QUOTES, 'UTF-8'));
</code>```

When it passes to fpdf cell attribute it displaying with br tag, the i use

```<code>str_ireplace('<br />', "\r\n", $address);
</code>```

Even after it not displaying in new line, just replacing br with space. Is there any way to print value in multi line inside cell

```<code>foreach($this->items as $item)
            {

                $cHeight = $cellHeight;
                $this->SetFont($this->font,'b',8);
                $this->SetTextColor(50,50,50);

                $cbgcolor = explode(",",$item['cbgcolor']);

                $this->SetFillColor($cbgcolor[0],$cbgcolor[1],$cbgcolor[2]);
                $this->Cell(1,$cHeight,'',0,0,'L',1);
                $x = $this->GetX();
                $this->Cell($this->firstColumnWidth,$cHeight,iconv("UTF-8", "ISO-8859-1",$item['item']),0,0,'L',1);

                $this->SetTextColor(50,50,50);
                $this->SetFont($this->font,'',8);
                $this->Cell($this->columnSpacing,$cHeight,'',0,0,'L',0);
                $this->Cell($this->secondColumnWidth,$cHeight,$item['quantity'],0,0,'L',1);

                $this->Cell($this->columnSpacing,$cHeight,'',0,0,'L',0);
                $this->Cell($this->priceColumnWidth,$cHeight,iconv('UTF-8', 'windows-1252', $this->currency.' '.number_format($item['price'],2,$this->referenceformat[0],$this->referenceformat[1])),0,0,'C',1);

                $this->Cell($this->columnSpacing,$cHeight,'',0,0,'L',0);
                $this->Cell($this->priceColumnWidth,$cHeight,iconv('UTF-8', 'windows-1252', $this->currency.' '.number_format($item['total'],2,$this->referenceformat[0],$this->referenceformat[1])),0,0,'C',1);
                $this->Ln();
                $this->Ln($this->columnSpacing);
            }
</code>```

This is my body..for $item['quantity'] have multi line content. where i am printing values as a table.so when i use multicell in one column the layout is changing and not look good.

答:
You can wrap your text in cell by using MultiCell

$pdf->MultiCell( 200, 40, $address, 1);

Title: Multiple line content in cell fpdf

Body:
i am creating an invoice application and using fpdf and https://github.com/farjadtahir/pdf-invoicr pdf-invoicr class. Its working fine but now i have multi line content in database like address, when i am saving the textarea content from form it will save with br tag,

nl2br(htmlentities($address, ENT_QUOTES, 'UTF-8'));

When it passes to fpdf cell attribute it displaying with br tag, the i use

str_ireplace('
', "\r\n", $address);

Even after it not displaying in new line, just replacing br with space. Is there any way to print value in multi line inside cell

foreach($this->items as $item)
            {

                $cHeight = $cellHeight;
                $this->SetFont($this->font,'b',8);
                $this->SetTextColor(50,50,50);

                $cbgcolor = explode(",",$item['cbgcolor']);

                $this->SetFillColor($cbgcolor[0],$cbgcolor[1],$cbgcolor[2]);
                $this->Cell(1,$cHeight,'',0,0,'L',1);
                $x = $this->GetX();
                $this->Cell($this->firstColumnWidth,$cHeight,iconv("UTF-8", "ISO-8859-1",$item['item']),0,0,'L',1);

                $this->SetTextColor(50,50,50);
                $this->SetFont($this->font,'',8);
                $this->Cell($this->columnSpacing,$cHeight,'',0,0,'L',0);
                $this->Cell($this->secondColumnWidth,$cHeight,$item['quantity'],0,0,'L',1);

                $this->Cell($this->columnSpacing,$cHeight,'',0,0,'L',0);
                $this->Cell($this->priceColumnWidth,$cHeight,iconv('UTF-8', 'windows-1252', $this->currency.' '.number_format($item['price'],2,$this->referenceformat[0],$this->referenceformat[1])),0,0,'C',1);

                $this->Cell($this->columnSpacing,$cHeight,'',0,0,'L',0);
                $this->Cell($this->priceColumnWidth,$cHeight,iconv('UTF-8', 'windows-1252', $this->currency.' '.number_format($item['total'],2,$this->referenceformat[0],$this->referenceformat[1])),0,0,'C',1);
                $this->Ln();
                $this->Ln($this->columnSpacing);
            }

This is my body..for $item['quantity'] have multi line content. where i am printing values as a table.so when i use multicell in one column the layout is changing and not look good.


问:
Django qs1.difference(qs2, qs3) not supported by backend
I need to check a table from a remote db and update another table in my db. The models have same fields but checking with difference method will return an error:

qs1 get the data from one postgresql db

qs2 get the data from one mysql db

```<code>qs1 = (Local.objects
            .values_list('ref')
)
qs2 = (Remote.objects
            .filter()
            .values_list('ref'))

>>> qs1.difference(qs1, qs2)
</code>```

DatabaseError: intersection not supported on this database backend.

答:
I'm not exactly sure what you think your code is doind.

qs1 looks for a model Local in your default Databasengine. And qs2 looks for a model Remote also in your default Databasengine.

What you might want to do is defining a second Database in your settings.py
naming it for Instance "remote" and then modify your q2 as follows :

```<code>qs2 = (Remote.objects.using("remote").filter().values_list('ref'))
</code>```

This tells django that it shall contact your remote Database not your Local one.

Lemme know wether this helps or not.

Body:
I need to check a table from a remote db and update another table in my db. The models have same fields but checking with difference method will return an error:

qs1 get the data from one postgresql db

qs2 get the data from one mysql db

qs1 = (Local.objects
            .values_list('ref')
)
qs2 = (Remote.objects
            .filter()
            .values_list('ref'))

>>> qs1.difference(qs1, qs2)

DatabaseError: intersection not supported on this database backend.

Body:
I'm not exactly sure what you think your code is doind.

qs1 looks for a model Local in your default Databasengine. And qs2 looks for a model Remote also in your default Databasengine.

What you might want to do is defining a second Database in your settings.py
naming it for Instance "remote" and then modify your q2 as follows :

qs2 = (Remote.objects.using("remote").filter().values_list('ref'))

This tells django that it shall contact your remote Database not your Local one.

Lemme know wether this helps or not.


答:
```<code>catch (Exception1 | Exception2 e) {....}
</code>```

Here e is reference variable of both Exception1 and Exception2. So at compile time e.info(); will throw exception since info() is not there for Exception2.

Better to use separate catch block for each since both classes don't have same method info().

```<code>} catch (Exception1 e) {
            e.info();
            System.out.println(e);
        } catch (Exception2 e) {
            System.out.println(e);
        }
</code>```

Title: reference type of exception issue in multi-catch block

Body:
e is of type Exception but prints Exception1 in below code:

class Exception1 extends IOException {void info(){}}
class Exception2 extends Exception {}

class TestMultiCatch {
    public static void main(String args[]) {
        try {
            int a = 10;
            if (a <= 10)
                throw new Exception1();
            else
                throw new Exception2();
        } catch (Exception1 | Exception2 e) {
            e.info();  //line 1 error "The method info() is undefined for type Exception"
            System.out.println(e);   //prints Exception1 (after commenting line 1)
        }
    }
}

From what I studied "e" should be of type Exception which is common base class of Exception1 and Exception2. Which it is, as evident from message in line 1.

But then why:

System.out.println(e); //prints Exception1 and not Exception
System.out.println(e instanceof IOException); //prints true and not false
System.out.println(e instanceof Exception1); //prints true and not false
System.out.println(e instanceof Exception2); //false

?
Thanks.

Body:
catch (Exception1 | Exception2 e) {....}

Here e is reference variable of both Exception1 and Exception2. So at compile time e.info(); will throw exception since info() is not there for Exception2.

Better to use separate catch block for each since both classes don't have same method info().

} catch (Exception1 e) {
            e.info();
            System.out.println(e);
        } catch (Exception2 e) {
            System.out.println(e);
        }


问:
Django Rest API, how to create post api for 2 model entries, and has foreign key associated to the model
I am trying to use DRF Django Rest Framework to create a post API to create entry for 2 models and associate foreign key relationship. How do I accomplish that ?

I have 2 models
- Employee model that OneToOne association with User, and has a ForeignKey Company
- Company model

I want to have a post to create employee model entry and also company model entry and associate the employee to the company. The employee also I want to enter in the User data (username, first_name, last_name, etc).

The following are the code excerpts:

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py

```<code>class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)

class Company(models.Model):
    name = models.CharField(max_length=50)
    tel = models.CharField(max_length=15, blank=True)
</code>```

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py

```<code>class EmployeeWithCompanyCreateView(generics.ListCreateAPIView):
    """This class defines the create behavior of our rest api."""
    queryset = Employee.objects.all()
    serializer_class = EmployeeWithCompanyCreateSerializer

    def perform_create(self, serializer):
        """Save the post data when creating a new bucketlist."""
        serializer.save()
</code>```

https://gitlab.com/firdausmah/railercom/blob/master/railercom/urls.py

```<code>urlpatterns = [
    url(r'^employee/$', EmployeeWithCompanyCreateView.as_view(), name="create"),
</code>```

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/serializers.py

```<code>class EmployeeWithCompanyCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = Employee
        fields = ("id","identity_number", "tel")
</code>```

答:
Your current solution has some thing wrong: the fields list of EmployeeWithCompanyCreateSerializer class is mismatch the fields of  Employee class.
In your question context ,I suggest you write the complicated view  by hand.</p>

Body:
I am trying to use DRF Django Rest Framework to create a post API to create entry for 2 models and associate foreign key relationship. How do I accomplish that ?

I have 2 models
- Employee model that OneToOne association with User, and has a ForeignKey Company
- Company model

I want to have a post to create employee model entry and also company model entry and associate the employee to the company. The employee also I want to enter in the User data (username, first_name, last_name, etc).

The following are the code excerpts:

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)

class Company(models.Model):
    name = models.CharField(max_length=50)
    tel = models.CharField(max_length=15, blank=True)

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py

class EmployeeWithCompanyCreateView(generics.ListCreateAPIView):
    """This class defines the create behavior of our rest api."""
    queryset = Employee.objects.all()
    serializer_class = EmployeeWithCompanyCreateSerializer

    def perform_create(self, serializer):
        """Save the post data when creating a new bucketlist."""
        serializer.save()

https://gitlab.com/firdausmah/railercom/blob/master/railercom/urls.py

urlpatterns = [
    url(r'^employee/$', EmployeeWithCompanyCreateView.as_view(), name="create"),

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/serializers.py

class EmployeeWithCompanyCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = Employee
        fields = ("id","identity_number", "tel")


问:
Setting default style of Ionic alert popup elements
I followed the answers found here: Ionic 2 Alert customization

But I can't find all the other classes or elements that have to be styled so alerts look like I want.

I edited my code so it looks like this:

app.scss:

```<code>.alertCustomCss {
  background-color: color($colors, dark, base);
  color: white;
  button {
      color: white !important;
  }
}
</code>```

ts:

```<code>const alert = this.alertCtrl.create({
    title: title,
    subTitle: msg,
    buttons: ['OK'],
    cssClass: 'alertCustomCss'
});
alert.present();
</code>```

But this makes all the text white, replaces the transparency of the modal page that holds the popup and sets it to set 'background-color' (so the page that called the popup is not visible anymore). The text of the button is set to white.

Please notice that the background around the popup is not transparent anymore.

The question is how to set the background color of the text placeholder and not the whole page? What css properties to use?

Broader question: What are the elements (css classes or directives) of the alert popup that can be styled? Title text color, content text font, etc..

答:
I edited all my AlertController.create methods to look like this:

```<code>const alert = this.alertCtrl.create({
    title: title,
    subTitle: msg,
    buttons: ['OK'],
    cssClass: 'alertCustomCss' // <- added this
});
</code>```

And I added this to app.scss:

```<code>.alertCustomCss {
    color: white; // text color for basic alerts
    button {
        color: white !important;
        background-color: color($colors, secondary, base) !important;
    }
    .alert-message {
        color: white; // text color for confirm alerts
    }
    .alert-wrapper {
        background-color: color($colors, dark, base);
    }
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I followed the answers found here: Ionic 2 Alert customization

But I can't find all the other classes or elements that have to be styled so alerts look like I want.

I edited my code so it looks like this:

app.scss:

.alertCustomCss {
  background-color: color($colors, dark, base);
  color: white;
  button {
      color: white !important;
  }
}

ts:

const alert = this.alertCtrl.create({
    title: title,
    subTitle: msg,
    buttons: ['OK'],
    cssClass: 'alertCustomCss'
});
alert.present();

But this makes all the text white, replaces the transparency of the modal page that holds the popup and sets it to set 'background-color' (so the page that called the popup is not visible anymore). The text of the button is set to white.

Please notice that the background around the popup is not transparent anymore.

The question is how to set the background color of the text placeholder and not the whole page? What css properties to use?

Broader question: What are the elements (css classes or directives) of the alert popup that can be styled? Title text color, content text font, etc..

Body:
I edited all my AlertController.create methods to look like this:

const alert = this.alertCtrl.create({
    title: title,
    subTitle: msg,
    buttons: ['OK'],
    cssClass: 'alertCustomCss' // <- added this
});

And I added this to app.scss:

.alertCustomCss {
    color: white; // text color for basic alerts
    button {
        color: white !important;
        background-color: color($colors, secondary, base) !important;
    }
    .alert-message {
        color: white; // text color for confirm alerts
    }
    .alert-wrapper {
        background-color: color($colors, dark, base);
    }
  }


问:
Does forkjoin return results in a particular order?
My app will make multiple parallel http call. Its based on a switch-fall though logic, so the number of query will vary (1, 2, or 3 calls). Is there a way for me to know which call gets returned first? I.e either assign a key or does it return in an ordered way based on the http request on the list?

Either way works for me. I just need to find a way to match the right result with the right call.

答: It is ordered based on the order of the requests. </p>


问:
ruby - rails - Dealing with a Boolean False- It outputs nothing
I have record in my db that is a boolean field (true/false).

The field is archived. When archived is true all these work great to output true:

```<code>  Rails.logger.info @commentable.archived
  Rails.logger.info @commentable.archived?
  Rails.logger.info !!@commentable.archived?
</code>```

BUT when the archived is false, it outputs nothing for either of the above. How can I get an output of false when the field is FALSE?

Thanks

答:
I prefer to use .inspect for doing output to logging.  I find its output more useful if you get a nil value.

```<code>ruby-1.8.7-p302 > nil.to_s
 => ""
ruby-1.8.7-p302 > nil.inspect
 => "nil"
ruby-1.8.7-p302 > false.to_s
 => "false"
ruby-1.8.7-p302 > false.inspect
 => "false"
ruby-1.8.7-p302 >
</code>```

Body:
I have record in my db that is a boolean field (true/false).

The field is archived. When archived is true all these work great to output true:

  Rails.logger.info @commentable.archived
  Rails.logger.info @commentable.archived?
  Rails.logger.info !!@commentable.archived?

BUT when the archived is false, it outputs nothing for either of the above. How can I get an output of false when the field is FALSE?

Thanks

Body:
I prefer to use .inspect for doing output to logging.  I find its output more useful if you get a nil value.

ruby-1.8.7-p302 > nil.to_s
 => ""
ruby-1.8.7-p302 > nil.inspect
 => "nil"
ruby-1.8.7-p302 > false.to_s
 => "false"
ruby-1.8.7-p302 > false.inspect
 => "false"
ruby-1.8.7-p302 >


问:
How can I make the navigation work in my project in UWP?
I have a split view (hamburger menu). The main page is divided into 2 columns. The first one is just split view and the second one contains a frame. I'd like to be able to change the contents of the frame depending on which button in the menu is clicked. Is it possible to do this way?</p>

答:
Actually you can do this by adding a frame element in your page, then load different page on that frame so, your main page split view will always there only frame will change through loading different pages.

e.g you have home button and another is settings button so when you click on any button your frame will load respective navigated page on frame you can follow this 33rd to 36th video of this series

you should add this element

```<code><Frame Name="MyFrame"></Frame>
</code>```

to load your page on it without fully navigating to other pages like this.

```<code>MyFrame.Navigate(typeof(YourPage));
</code>```

Body:
Actually you can do this by adding a frame element in your page, then load different page on that frame so, your main page split view will always there only frame will change through loading different pages.

e.g you have home button and another is settings button so when you click on any button your frame will load respective navigated page on frame you can follow this 33rd to 36th video of this series

you should add this element

<Frame Name="MyFrame"></Frame>

to load your page on it without fully navigating to other pages like this.

MyFrame.Navigate(typeof(YourPage));


问:
Javascript/Jquery won't change URL parameters in Safari but it will in Chrome
I have this JQuery/JS script that changes $_GET parameters of URL depending on which option from select element is selected. It works fine in Chrome but it won't change $_GET parameters or refresh in Safari 6.1.6.</p>

```<code> $("#promjena").change(function () {
    var v = $("#promjena").val();
    var href = window.location.href;

    if (v === "1") {
        if (href.includes("?akcija=kontrola")) {
            window.location.href = href.replace("?akcija=kontrola", "?akcija=default");
        } else if (href.includes("?akcija=signal")) {
            window.location.href = href.replace("?akcija=signal", "?akcija=default");
        } else {
            window.location.href = window.location.href + "?akcija=default";
        }
    }
    if (v === "2") {
        if (href.includes("?akcija=default")) {
            window.location.href = href.replace("?akcija=default", "?akcija=kontrola");
        } else if (href.includes("?akcija=signal")) {
            window.location.href = href.replace("?akcija=signal", "?akcija=kontrola");
        } else {
            window.location.href = window.location.href + "?akcija=kontrola";
        }
    }
    if (v === "3") {
        if (href.includes("?akcija=default")) {
            window.location.href = href.replace("?akcija=default", "?akcija=signal");
        } else if (href.includes("?akcija=kontrola")) {
            window.location.href = href.replace("?akcija=kontrola", "?akcija=signal");
        } else {
            window.location.href = window.location.href + "?akcija=signal";
        }
    }

});
</code>```

答:
One chance is that val() is returning a number and you are expecting a string in if(v === "1") if thats an issue you can do:

```<code> var v = $('#promjena').val() + ''; //to convert to string if not
</code>```

Another chance is the support for includes in Safari < 9

If that is the case you can use a polyfill for includes as mentioned in the above page, or rewrite your code like:

```<code>if(href.indexOf("?akcija=default") !== -1)
</code>```

Or use any other alternatives from this answer

Body:
I have this JQuery/JS script that changes $_GET parameters of URL depending on which option from select element is selected. It works fine in Chrome but it won't change $_GET parameters or refresh in Safari 6.1.6.

 $("#promjena").change(function () {
    var v = $("#promjena").val();
    var href = window.location.href;

    if (v === "1") {
        if (href.includes("?akcija=kontrola")) {
            window.location.href = href.replace("?akcija=kontrola", "?akcija=default");
        } else if (href.includes("?akcija=signal")) {
            window.location.href = href.replace("?akcija=signal", "?akcija=default");
        } else {
            window.location.href = window.location.href + "?akcija=default";
        }
    }
    if (v === "2") {
        if (href.includes("?akcija=default")) {
            window.location.href = href.replace("?akcija=default", "?akcija=kontrola");
        } else if (href.includes("?akcija=signal")) {
            window.location.href = href.replace("?akcija=signal", "?akcija=kontrola");
        } else {
            window.location.href = window.location.href + "?akcija=kontrola";
        }
    }
    if (v === "3") {
        if (href.includes("?akcija=default")) {
            window.location.href = href.replace("?akcija=default", "?akcija=signal");
        } else if (href.includes("?akcija=kontrola")) {
            window.location.href = href.replace("?akcija=kontrola", "?akcija=signal");
        } else {
            window.location.href = window.location.href + "?akcija=signal";
        }
    }

});

Body:
One chance is that val() is returning a number and you are expecting a string in if(v === "1") if thats an issue you can do:

 var v = $('#promjena').val() + ''; //to convert to string if not

Another chance is the support for includes in Safari < 9

If that is the case you can use a polyfill for includes as mentioned in the above page, or rewrite your code like:

if(href.indexOf("?akcija=default") !== -1)

Or use any other alternatives from this answer


问:
How to properly fetch data from API in vuex?
I'm working on my Vue.js application and having a trouble with fetching data via API with vuex-router-sync.

As I saw in every tutorial or sample, it is common thing to dispatch the store action on created component hook. In my case it doesn't seem to be an option and here's why:

I use the standard vue-router for my routing, and when I navigate between pages not only my content should change, but also my sidebar and header. Thus I implemented the named router-view concept, such as

```<code>    routes: [{
      path: '/',
      components: {
        page: Home,
        sidebar: GeneralSidebar,
        header: HomeHeader
      }
    }, {
      path: '/game/:id',
      name: 'game',
      components: {
        page: Game,
        sidebar: GameSidebar,
        header: GameHeader
      }
    }]
</code>```

But the Game, GameHeader and GameSidebar should share the same getter for the currently selected game. It's impossible to decide, which one of those components should be dispatching the action to fetch the data.

I tried to hook on the router itself, on beforeEnter, but faced the issue, that navigating between the same routes (in my case from /game/1 to /game/2) does not trigger the beforeEnter.

Is there any way that I can hook on any route navigation? Or maybe a better pattern for dispatching fetch-actions?

Thanks in advance!

答:
There are many ways to do this. For example You could fetch data inside some component which is loaded by route change and after set data to vuex by dispatching change. This does the job perfectly. Also keep in mind that there are few ways to fetch data inside any component - You can hook that in any of Vue lifecycle hooks. Take a look here https://router.vuejs.org/en/advanced/data-fetching.html

Also sometimes You need some data upfront of any route change and here You can use the same approach - make some request when Vue app is loaded.

Body:
I'm working on my Vue.js application and having a trouble with fetching data via API with vuex-router-sync.

As I saw in every tutorial or sample, it is common thing to dispatch the store action on created component hook. In my case it doesn't seem to be an option and here's why:

I use the standard vue-router for my routing, and when I navigate between pages not only my content should change, but also my sidebar and header. Thus I implemented the named router-view concept, such as

    routes: [{
      path: '/',
      components: {
        page: Home,
        sidebar: GeneralSidebar,
        header: HomeHeader
      }
    }, {
      path: '/game/:id',
      name: 'game',
      components: {
        page: Game,
        sidebar: GameSidebar,
        header: GameHeader
      }
    }]

But the Game, GameHeader and GameSidebar should share the same getter for the currently selected game. It's impossible to decide, which one of those components should be dispatching the action to fetch the data.

I tried to hook on the router itself, on beforeEnter, but faced the issue, that navigating between the same routes (in my case from /game/1 to /game/2) does not trigger the beforeEnter.

Is there any way that I can hook on any route navigation? Or maybe a better pattern for dispatching fetch-actions?

Thanks in advance!


问:
Multiple primary key constraints?
I have a table like this:

```<code>CREATE TABLE BACAEN
(
CAEN_KEY INT PRIMARY NOT NULL,
CAET_KEY INT,
BUUN_KEY INT
)
</code>```

I've already defined primary key on CAEN_KEY column. What I also need is to have unique records for CAET_KEY and BUUN_KEY together. (So, combination with same CAET_KEY / BUUN_KEY is allowed only once). The easiest way would be to generate one more composite primary key, but this is not possible because sql server doesn't allow multiple primary key constraints. What are alternatives to this?

Please note: I can not drop primary key constraint on CAEN_KEY.

答:
```<code>ALTER TABLE youtablename  ADD CONSTRAINT uq_yourtablename UNIQUE(CAET_KEY , BUUN_KEY );
</code>```

<p>ps. If your table is already populated, make sure to remove all those entries conflicting with this constraint. </p>

Title: Multiple primary key constraints?

Body:
I have a table like this:

CREATE TABLE BACAEN
(
CAEN_KEY INT PRIMARY NOT NULL,
CAET_KEY INT,
BUUN_KEY INT
)

I've already defined primary key on CAEN_KEY column. What I also need is to have unique records for CAET_KEY and BUUN_KEY together. (So, combination with same CAET_KEY / BUUN_KEY is allowed only once). The easiest way would be to generate one more composite primary key, but this is not possible because sql server doesn't allow multiple primary key constraints. What are alternatives to this?

Please note: I can not drop primary key constraint on CAEN_KEY.

Body:
ALTER TABLE youtablename  ADD CONSTRAINT uq_yourtablename UNIQUE(CAET_KEY , BUUN_KEY );

ps. If your table is already populated, make sure to remove all those entries conflicting with this constraint.


问:
reference type of exception issue in multi-catch block
e is of type Exception but prints Exception1 in below code:

```<code>class Exception1 extends IOException {void info(){}}
class Exception2 extends Exception {}

class TestMultiCatch {
    public static void main(String args[]) {
        try {
            int a = 10;
            if (a <= 10)
                throw new Exception1();
            else
                throw new Exception2();
        } catch (Exception1 | Exception2 e) {
            e.info();  //line 1 error "The method info() is undefined for type Exception"
            System.out.println(e);   //prints Exception1 (after commenting line 1)
        }
    }
}
</code>```

From what I studied "e" should be of type Exception which is common base class of Exception1 and Exception2. Which it is, as evident from message in line 1.

But then why:

```<code>System.out.println(e); //prints Exception1 and not Exception
System.out.println(e instanceof IOException); //prints true and not false
System.out.println(e instanceof Exception1); //prints true and not false
System.out.println(e instanceof Exception2); //false
</code>```

?
Thanks.

答: The multi-catch seems to be your problem. You (the compiler) can only access methods which are defined on the common ancestors. Of course, "e" will be an Exception1 during runtime, but the compiler just cannot assume that, cause it could as well be an Exception2. Better create a catch block for both Exception1 and Exception2.</p>


问:
scp with port number specified
I'm trying to scp a file from a remote server to my local machine. Only port 80 is accessible.

I tried:

```<code>scp -p 80 username@www.myserver.com:/root/file.txt .
</code>```

but got this error: cp: 80: No such file or directory

How do I specify the port number in a scp command?

答:
This can be achived by specifying port via the -P switch:

```<code>scp -i ~/keys/yourkey -P2222 file ubuntu@host:/directory/
</code>```

Title: scp with port number specified

Body:
I'm trying to scp a file from a remote server to my local machine. Only port 80 is accessible.

I tried:

scp -p 80 username@www.myserver.com:/root/file.txt .

but got this error: cp: 80: No such file or directory

How do I specify the port number in a scp command?

Body:
This can be achived by specifying port via the -P switch:

scp -i ~/keys/yourkey -P2222 file ubuntu@host:/directory/


问:
parse string object without using JSON
I need to parse an object from html element attribute (like angular does it) without using JSON.parse or something

For example I have a DIV like this

```<code><div some-attribute="{key1: 1 > 0, key2: true || false}"></div>
</code>```

And after parsing I need just string representation of all that I have in this object:

```<code>{'key1': '1 > 0', 'key2': 'true || false'}
</code>```

Is there any ability to parse it this way without inventing a new parser?

答:
Do you want to get the [Object] finally? You can search for , and : in the [String] value and then split it like this:

//retrieve this from attribute with DOM methods
var a = "{key1: 1 > 0, key2: true || false}";

console.log(parse(a));

function parse(data) {
  if (data[0] !== '{' || data[data.length - 1] !== '}') return null; //remove it if useless
  var props = data.slice(1, data.length - 1).split(/\s*,\s*/);
  var newObj = {};
  props.forEach((a) => {
    var pair = a.split(/\s*:\s*/);
    newObj[pair[0]] = pair[1];
  });
  return newObj;
}```

The RegExp removes spaces between , and :

Title: parse string object without using JSON

Body:
I need to parse an object from html element attribute (like angular does it) without using JSON.parse or something

For example I have a DIV like this

 0, key2: true || false}">

And after parsing I need just string representation of all that I have in this object:

{'key1': '1 > 0', 'key2': 'true || false'}

Is there any ability to parse it this way without inventing a new parser?

Body:
Do you want to get the [Object] finally? You can search for , and : in the [String] value and then split it like this:

//retrieve this from attribute with DOM methods
var a = "{key1: 1 > 0, key2: true || false}";

console.log(parse(a));

function parse(data) {
  if (data[0] !== '{' || data[data.length - 1] !== '}') return null; //remove it if useless
  var props = data.slice(1, data.length - 1).split(/\s*,\s*/);
  var newObj = {};
  props.forEach((a) => {
    var pair = a.split(/\s*:\s*/);
    newObj[pair[0]] = pair[1];
  });
  return newObj;
}

The RegExp removes spaces between , and :


问:
Assigning a class to the
 parent of an image
ETA - Solution found. Nice work Stack Overflow beauties!! What would I do without you ;) ;)

I'm building a carousel, some items have images, others don't. I need to be able to target the items without images for styling, so I'm trying to add a class to the div that wraps the image if that makes sense?

What I have is this :
For items with images:

      Day 1

```
</div>
</div>
</p>

<p><strong>For items without images :</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="carousel-item" style="width: 157.4px; margin-right: 2px;">
  <li>

      <span>Day 1</span>

  </li>
</div></code>```

And what I'm trying to do using jquery is add the class 'noImg' to the div 'carousel-item' what I've tried is many variations of this sort of thing :

$("div.carousel-item").addClass("noImg");
if ($(this).hasClass('.img-responsive')) {
  ("div.carousel-item").removeClass("noImg")
};
```

I've tried variations of .children .parent I've tried doing it the other way around and doing .find on image-responsive and adding classes that way.

Any suggestions of the 'you dope, you're missing this obvious thing' would very much be appreciated, Thanks very much in advance.

答:
Working example, see console.output:

$('.carousel-item').each(function (idx) {
  if ($(this).find('img').length)
    $(this).removeClass('noImg')
  else
    $(this).addClass('noImg')
  console.log('Div ' + idx + ' hasClass noImg: ' + $(this).hasClass('noImg'))
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="carousel-item active" style="width: 157.4px; margin-right: 2px;">
  <li>

      <span>Day 1</span>
      <img src="*example image*" class="img-responsive" alt="words here" width="380" height="226" title="words here">

  </li>
</div>

<div class="carousel-item" style="width: 157.4px; margin-right: 2px;">
  <li>

      <span>Day 1</span>

  </li>
</div>

<script src="https://unpkg.com/jquery"></script></code>```

Title: Assigning a class to the <div> parent of an image

Body:
ETA - Solution found. Nice work Stack Overflow beauties!! What would I do without you ;) ;)

I'm building a carousel, some items have images, others don't. I need to be able to target the items without images for styling, so I'm trying to add a class to the div that wraps the image if that makes sense?

What I have is this :
For items with images:

      Day 1

For items without images :

      Day 1

And what I'm trying to do using jquery is add the class 'noImg' to the div 'carousel-item' what I've tried is many variations of this sort of thing :

$("div.carousel-item").addClass("noImg");
if ($(this).hasClass('.img-responsive')) {
  ("div.carousel-item").removeClass("noImg")
};

I've tried variations of .children .parent I've tried doing it the other way around and doing .find on image-responsive and adding classes that way.

Any suggestions of the 'you dope, you're missing this obvious thing' would very much be appreciated, Thanks very much in advance.

Body:
Working example, see console.output:

$('.carousel-item').each(function (idx) {
  if ($(this).find('img').length)
    $(this).removeClass('noImg')
  else
    $(this).addClass('noImg')
  console.log('Div ' + idx + ' hasClass noImg: ' + $(this).hasClass('noImg'))
})

<div class="carousel-item active" style="width: 157.4px; margin-right: 2px;">
  <li>
    <a href="#" class="innerTabLink" rel="XYZ">
      <span>Day 1</span>
      <img src="*example image*" class="img-responsive" alt="words here" width="380" height="226" title="words here">
    </a>
  </li>
</div>

<div class="carousel-item" style="width: 157.4px; margin-right: 2px;">
  <li>
    <a href="#" class="innerTabLink" rel="XYZ">
      <span>Day 1</span>
    </a>
  </li>
</div>

<script src="https://unpkg.com/jquery"></script>