问:
Calling 7z from PHP archives wrong items
I've been fiddling with this for an hour, haven't figured out why it won't work. I have a project which outputs 3 xlsx and docx files in a temp folder (/temp). I want to zip them for download.

The problem is everytime I exec the 7z command, it zips the whole project folder instead (../temp), not even just the temp folder. I can't figure out why. If I echo $command and run it in cmd from PHP's working directory (which shouldn't matter anyway since I use absolute paths for everything), works just fine. It also doesn't work if I use relative paths.

The filename variables $HSModuleFileName etc are generated elsewhere, ending in either '.docx' or '.xlsx'

```<code>$project_dir = str_replace('\\', '/', preg_replace('/\\|\/$/', '', dirname(dirname(__DIR__)))) . '/';

$FileName = 'output_' . substr($ImportGUID, -8) . '.zip';

$command = '"C:/Program Files/7-Zip/7z.exe" a -tzip "' . $project_dir . 'temp/' . $FileName . '"
    "' . $project_dir . 'temp/' . $HSModuleFileName . '" "' . $project_dir . 'temp/' . $SummaryFileName . '" "' . $project_dir . 'temp/' . $NoInvoiceFileName . '"';

exec($command);
</code>```

Echo of $command:

```<code>"C:/Program Files/7-Zip/7z.exe" a -tzip "D:/Projects/JFC/temp/output_38416fc5.zip" "D:/Projects/JFC/temp/HS_Module_38416fc5.xlsx" "D:/Projects/JFC/temp/Summary_38416fc5.xlsx" "D:/Projects/JFC/temp/NoInvoice_38416fc5.docx"
</code>```

So the resulting output_38416fc5.zip file actually contains the whole "D:/Projects/JFC" folder

答:
Found it! Thanks to @n0rd for pointing me in the right direction. Using sysinternals Process Monitor I saw that on the Process Start event of 7z, the command line parameter was

```<code>"C:/Program Files/7-Zip/7z.exe" a -tzip "D:/Projects/JFC/temp/output_de75eb91.zip"
</code>```

without the list of files.
Then I suddenly realized I separated the command with a newline in the PHP code, just before the list of files, which meant it was also processed as a newline by exec.

Body:
I've been fiddling with this for an hour, haven't figured out why it won't work. I have a project which outputs 3 xlsx and docx files in a temp folder (/temp). I want to zip them for download.

The problem is everytime I exec the 7z command, it zips the whole project folder instead (../temp), not even just the temp folder. I can't figure out why. If I echo $command and run it in cmd from PHP's working directory (which shouldn't matter anyway since I use absolute paths for everything), works just fine. It also doesn't work if I use relative paths.

The filename variables $HSModuleFileName etc are generated elsewhere, ending in either '.docx' or '.xlsx'

$project_dir = str_replace('\\', '/', preg_replace('/\\|\/$/', '', dirname(dirname(__DIR__)))) . '/';

$FileName = 'output_' . substr($ImportGUID, -8) . '.zip';

$command = '"C:/Program Files/7-Zip/7z.exe" a -tzip "' . $project_dir . 'temp/' . $FileName . '"
    "' . $project_dir . 'temp/' . $HSModuleFileName . '" "' . $project_dir . 'temp/' . $SummaryFileName . '" "' . $project_dir . 'temp/' . $NoInvoiceFileName . '"';

exec($command);

Echo of $command:

"C:/Program Files/7-Zip/7z.exe" a -tzip "D:/Projects/JFC/temp/output_38416fc5.zip" "D:/Projects/JFC/temp/HS_Module_38416fc5.xlsx" "D:/Projects/JFC/temp/Summary_38416fc5.xlsx" "D:/Projects/JFC/temp/NoInvoice_38416fc5.docx"

So the resulting output_38416fc5.zip file actually contains the whole "D:/Projects/JFC" folder

Body:
Found it! Thanks to @n0rd for pointing me in the right direction. Using sysinternals Process Monitor I saw that on the Process Start event of 7z, the command line parameter was

"C:/Program Files/7-Zip/7z.exe" a -tzip "D:/Projects/JFC/temp/output_de75eb91.zip"

without the list of files.
Then I suddenly realized I separated the command with a newline in the PHP code, just before the list of files, which meant it was also processed as a newline by exec.


来源: stackexchange

问:
Background image load slowly in react native
I use an image for background like this

```<code><Image
  source={Images.workingBg}
  style={styles.container}
>
  {this.renderHeader(navigation)}
  {this.renderContent(navigation)}
</Image>
</code>```

But image display slowly, text show before and image show after that even though that image is loaded.

答:
Because images in RN are decoded natively in a separate thread.

Image decoding can take more than a frame-worth of time. This is one of the major sources of frame drops on the web because decoding is done in the main thread.

So RN displaying the placeholder for a few more frames while it is decoding the images used in components, then show them at different times after each individual image has loaded (instead of waiting then show the whole component at once when it's ready).

See: Off-thread Decoding

Note

Images are loaded differently in development/debugging and "real" production. During local debugging the images will be served over HTTP from the packager server, whereas in production they will be bundled with the app.

Solution

Try doing a production build (full release build) on device to see if it's actually a problem or just a development mode side effect.

Or try the workaround from this issue

```<code>componentWillMount() {
    this.image = (<Image source={require('./background.png')} />);
}
</code>```

and in your render() function:

```<code>render() {
    return(
        <View>
            {this.image}
        </View>
    );
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use an image for background like this

<Image
  source={Images.workingBg}
  style={styles.container}
>
  {this.renderHeader(navigation)}
  {this.renderContent(navigation)}
</Image>

But image display slowly, text show before and image show after that even though that image is loaded.

Body:
Because images in RN are decoded natively in a separate thread.

Image decoding can take more than a frame-worth of time. This is one of the major sources of frame drops on the web because decoding is done in the main thread.

So RN displaying the placeholder for a few more frames while it is decoding the images used in components, then show them at different times after each individual image has loaded (instead of waiting then show the whole component at once when it's ready).

See: Off-thread Decoding

Note

Images are loaded differently in development/debugging and "real" production. During local debugging the images will be served over HTTP from the packager server, whereas in production they will be bundled with the app.

Solution

Try doing a production build (full release build) on device to see if it's actually a problem or just a development mode side effect.

Or try the workaround from this issue

componentWillMount() {
    this.image = (<Image source={require('./background.png')} />);
}

and in your render() function:

render() {
    return(
        <View>
            {this.image}
        </View>
    );
}

ContentLicense: CC BY-SA 4.0


问:
PHP Why is !empty not working?
!empty works in this code:

```<code>if (!empty($p1_firstname))
mysql_query ("INSERT INTO cases VALUES ('','$case','$date_booked','$p1_firstname','$p1_lastname','$city')");

if (!empty($p2_firstname))
$register_case = mysql_query ("INSERT INTO cases VALUES ('','$case','$date_booked','$p2_firstname','$p2_lastname','$city')");
</code>```

but not this code:

```<code>if (!empty($p1_firstname))
$passenger1 = 1;
mysql_query ("INSERT INTO cases VALUES ('','$case','$passenger1','$date_booked','$p1_firstname','$p1_lastname','$city')");

if (!empty($p2_firstname))
$passenger2 = 2;
$register_case = mysql_query ("INSERT INTO cases VALUES ('','$case','$passenger2','$date_booked','$p2_firstname','$p2_lastname','$city')");
</code>```

It still does the query even if the field is empty. What can be done to fix this?

答:
Because you're missing curly braces

```<code>if (!empty($p1_firstname)) {
    $passenger1 = 1;
    mysql_query ("INSERT INTO cases VALUES ('','$case','$passenger1','$date_booked','$p1_firstname','$p1_lastname','$city')");
}

if (!empty($p2_firstname)) {
    $passenger2 = 2;
    $register_case = mysql_query ("INSERT INTO cases VALUES ('','$case','$passenger2','$date_booked','$p2_firstname','$p2_lastname','$city')");
}
</code>```

The missing curly braces mean only the statement immediately following the ifs get executed if their conditions are satisfied. The mysql_query() calls are not part of the if blocks at all, and will execute regardless of whether your variables are empty() or not.

By both omitting the braces and not indenting your code correctly, this kind of error becomes even harder to spot. Not that you can't do that, but it's much safer, and results in less time wasted, to adopt a habit of good indentation and using curly braces to clearly indicate control flow blocks.

ContentLicense: CC BY-SA 2.5

Title: PHP Why is !empty not working?

Body:
!empty works in this code:

if (!empty($p1_firstname))
mysql_query ("INSERT INTO cases VALUES ('','$case','$date_booked','$p1_firstname','$p1_lastname','$city')");

if (!empty($p2_firstname))
$register_case = mysql_query ("INSERT INTO cases VALUES ('','$case','$date_booked','$p2_firstname','$p2_lastname','$city')");

but not this code:

if (!empty($p1_firstname))
$passenger1 = 1;
mysql_query ("INSERT INTO cases VALUES ('','$case','$passenger1','$date_booked','$p1_firstname','$p1_lastname','$city')");

if (!empty($p2_firstname))
$passenger2 = 2;
$register_case = mysql_query ("INSERT INTO cases VALUES ('','$case','$passenger2','$date_booked','$p2_firstname','$p2_lastname','$city')");

It still does the query even if the field is empty. What can be done to fix this?

Body:
Because you're missing curly braces

if (!empty($p1_firstname)) {
    $passenger1 = 1;
    mysql_query ("INSERT INTO cases VALUES ('','$case','$passenger1','$date_booked','$p1_firstname','$p1_lastname','$city')");
}

if (!empty($p2_firstname)) {
    $passenger2 = 2;
    $register_case = mysql_query ("INSERT INTO cases VALUES ('','$case','$passenger2','$date_booked','$p2_firstname','$p2_lastname','$city')");
}

The missing curly braces mean only the statement immediately following the ifs get executed if their conditions are satisfied. The mysql_query() calls are not part of the if blocks at all, and will execute regardless of whether your variables are empty() or not.

By both omitting the braces and not indenting your code correctly, this kind of error becomes even harder to spot. Not that you can't do that, but it's much safer, and results in less time wasted, to adopt a habit of good indentation and using curly braces to clearly indicate control flow blocks.


问:
How to randomly select values for a list?
I'm using Python 2.7

To be clear, I don't want to randomize the items in the list. I want to make it so it's possible for certain strings not to show up at all. For example:

```<code>    r = "red"
    b = "blue"
    y = "yellow"
    rc = random colour
    myColours = [rc,rc,rc]
    print myColours
</code>```

Obviously the code above wouldn't work, but I'm not sure how to proceed. It would also help if I could change how likely a certain string would be selected, like 50% odds of red, 30% odds of blue, and 20% odds of yellow.

答:
You can use numpy.random.choice.  The p parameter allows you to specify the probabilities associated with each entry.

```<code>import numpy as np

r, b, y = 'red', 'blue', 'yellow'
my_colours = np.random.choice(a=[r, b, y], size=3, p=[.5, .3, .2])
print(my_colours) . # my_colours.tolist() if you want list output
# ['yellow' 'red' 'red']
</code>```

To confirm this is working, use a result of size 30,000 rather than 3 and let the law of large numbers do its thing.

```<code>from collections import Counter

test = np.random.choice(a=[r, b, y], size=30000, p=[.5, .3, .2])
counts = Counter(test)

# Relative occurences:
dict(zip(counts.keys(), [count/30000 for count in counts.values()]))
{'blue': 0.30483333333333335,
 'red': 0.5000333333333333,
 'yellow': 0.19513333333333333}
</code>```

Body:
I'm using Python 2.7

To be clear, I don't want to randomize the items in the list. I want to make it so it's possible for certain strings not to show up at all. For example:

    r = "red"
    b = "blue"
    y = "yellow"
    rc = random colour
    myColours = [rc,rc,rc]
    print myColours

Obviously the code above wouldn't work, but I'm not sure how to proceed. It would also help if I could change how likely a certain string would be selected, like 50% odds of red, 30% odds of blue, and 20% odds of yellow.

Body:
You can use numpy.random.choice.  The p parameter allows you to specify the probabilities associated with each entry.

import numpy as np

r, b, y = 'red', 'blue', 'yellow'
my_colours = np.random.choice(a=[r, b, y], size=3, p=[.5, .3, .2])
print(my_colours) . # my_colours.tolist() if you want list output
# ['yellow' 'red' 'red']

To confirm this is working, use a result of size 30,000 rather than 3 and let the law of large numbers do its thing.

from collections import Counter

test = np.random.choice(a=[r, b, y], size=30000, p=[.5, .3, .2])
counts = Counter(test)

# Relative occurences:
dict(zip(counts.keys(), [count/30000 for count in counts.values()]))
{'blue': 0.30483333333333335,
 'red': 0.5000333333333333,
 'yellow': 0.19513333333333333}


问:
VS Code Key Binding for quick switch between terminal screens?
I'm trying to figure out if there is a way to set up a key binding to allow a quick switch between the terminal windows I have open in the built in terminal rather than having to click on the drop down selector each time. Does anyone know the command for this when making a personal key binding or where I can see a list of all the possible commands for VSC? Thank you in advance!</p>

答:
Here's the solution I built that works well for me on OSX.

It mimics the same shortcuts used in the editor to open new files (cmd+n) and switch between tabs (cmd+left|right) and the same shortcuts work for terminals when that view is in focus.

Hit cmd+shift+p and type keyboard to find Preferences: Open Keyboard Shortcuts File

Add the following to the keybindings.json file and save it.

```<code>{
    "key": "cmd+alt+right",
    "command": "workbench.action.terminal.focusNext",
    "when": "terminalFocus"
},
{
    "key": "cmd+alt+left",
    "command": "workbench.action.terminal.focusPrevious",
    "when": "terminalFocus"
},
{
    "key": "cmd+n",
    "command": "workbench.action.terminal.new",
    "when": "terminalFocus"
},
{
    "key": "cmd+w",
    "command": "workbench.action.terminal.kill",
    "when": "terminalFocus"
}
</code>```

It also does the same for closing terminals (cmd+w)

Body:
Here's the solution I built that works well for me on OSX.

It mimics the same shortcuts used in the editor to open new files (cmd+n) and switch between tabs (cmd+left|right) and the same shortcuts work for terminals when that view is in focus.

Hit cmd+shift+p and type keyboard to find Preferences: Open Keyboard Shortcuts File

Add the following to the keybindings.json file and save it.

{
    "key": "cmd+alt+right",
    "command": "workbench.action.terminal.focusNext",
    "when": "terminalFocus"
},
{
    "key": "cmd+alt+left",
    "command": "workbench.action.terminal.focusPrevious",
    "when": "terminalFocus"
},
{
    "key": "cmd+n",
    "command": "workbench.action.terminal.new",
    "when": "terminalFocus"
},
{
    "key": "cmd+w",
    "command": "workbench.action.terminal.kill",
    "when": "terminalFocus"
}

It also does the same for closing terminals (cmd+w)


问:
how to make this text array change color when it is called a bone when clicking
enter image description hereenter image description here----------

//Escriba el código JQuery, señalando el número de caso
$(document).ready(function(){
//caso 01
$("#banner").css({"width":"100%","height":"400px"});
//caso 02
$("#marco section").css("width","100%");
//caso 03
$("section article").css({"width":"100%","text-align":"center","float":"left","margin-bot":"10px"});
//caso 04
$("section article img").css({"width":"80px","height":"50px","cursor":"pointer","border":"3px outset red"});
//caso 05
$("section article").find("label").css({"color":"blue","font-size":"10pt","font-weight":"bold"});
//caso 06
$("section article").find("input").css({"border":"3px double skyblue","font-size":"10pt","font-weight":"bold"});
//caso 07
var imagen = $("section article img");
imagen.mouseover(function(){
   $(this).fadeTo(1000,0.6).css({"border-radius":"10px","border":"3px solid gold"});
  });
//caso 08
imagen.mouseout(function(){
   $(this).fadeTo(1000,1).css({"border-radius":"0px","border":"3px outset red"});
  });
//caso 09

var arrlugares = ["Macchu-Picchu(Cuzco-Perú)","Coliseo(Roma-Italia)",
      "Chichen-Itza(Yucatán-México)","Cristo Redentor(Río de Janeiro-Brasil)","Taj-Mahal(Uttar Pradesh-India)","Muralla-China(Huairo-China)","Petra(Jordania)"];

var n = Math.floor(Math.random()*7);

 //calling  array and make  change  the img  when its  click
imagen.each(function(x,imagenes){
   $(imagenes).click(function(){
    $("header h2").text(arrlugares[x]);
    $("header h2").css("color",colores[n]);
    $("#banner").attr("src", $(this).attr("src"));
   });
 });

$(function(){
  var colors = ['#ff6','#6ff','#f6f','#f66','#66f','#6f6'];
  $('input').click(function(){
      var randomcolor=Math.floor(Math.random()*colors.length);
      //alert(randomcolor);
      $('section').css('color',colors[randomcolor]);
  });
});

 ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { background:#76A5CC; font-family: arial; }

#marco { width:80%; height:auto; float:left;
      margin-left:10%; background-color:white; border: 2px solid white;
    }

#banner { width:80px; height:20px; float:left; }

header, nav { width:100%; height:auto; float:left; margin-bottom:5px; }

aside { width:30%; height:auto; float:left; }

section { width:70%; height:auto; float:left; }

nav { text-align:center; background-color:#76A5CC; }

footer { width:100%; height:auto; float:left; background-color:#76A5CC; text-align:center; font-size:10pt; font-weight:bold; color:#FFFFFF; }

header>h2 { text-align:center; color:#FFF; }

section>article h2 { color:#76A5CC; }

a:link {
 color: blue;
}
.redsocial { width:10px; height:10px; cursor:pointer; }</code>```

<!doctype html>

  <meta charset="utf-8">
  <title>Características JQuery</title>
  <link rel="stylesheet" type="text/css" href="../css/estilo.css" />

Las maravillas del mundo

       //those are imgs

Datos del contacto

     <form>
      Nombre:<input type="text" />

      Apellido:<input type="text" />

      Dirección:<input type="text" />
     </form>

Redes sociales

```

`href="https://i.stack.imgur.com/k5bnI.png" rel="nofollow noreferrer">enter image description here

By clicking on each image (img) within the section article block, perform:
to. Show the description of the image in h2 of the header block.
second. Apply a font color randomly.
do. Get the path of the image and assign it to the banner.

var arrlugares = ["Macchu-Picchu(Cuzco-Perú)","Coliseo(Roma-Italia)",
                  "Chichen-Itza(Yucatán-México)","Cristo Redentor(Río de Janeiro-Brasil)","Taj-Mahal(Uttar Pradesh-India)","Muralla-China(Huairo-China)","Petra(Jordania)"];

答:
Line 29 in your code produces a floating point number. Arrays do not accept floating point numbers. Cast it to an integer. Use something like Math.floor or Math.ceil.

Actually I see you doing it in a few places in your code.

Try using your debugger to trace your code. What what it is doing.

I'm still not sure what you're asking but here's a Plunker of clicking an image and changing color, from your code.

```<code>  $(document).ready(function() {
      var colors = ['#ff6', '#6ff', '#f6f', '#f66', '#66f', '#6f6'];
      var arrlugares = ["Macchu-Picchu(Cuzco-Perú)", "Coliseo(Roma-Italia)", "Chichen-Itza(Yucatán-México)", "Cristo Redentor(Río de Janeiro-Brasil)", "Taj-Mahal(Uttar Pradesh-India)", "Muralla-China(Huairo-China)", "Petra(Jordania)"];

      $('img').click(function(evnt) {
        var randomcolor = Math.floor(Math.random() * colors.length),
          randomText = Math.floor(Math.random() * arrlugares.length);

        $('#marco header h2')
          .css('color', colors[randomcolor])
          .text(arrlugares[randomText]);

        $('#banner').attr('src', $(evnt.currentTarget).attr('src'));
      });
    })
</code>```

Body:
enter image description hereenter image description here----------

//Escriba el código JQuery, señalando el número de caso
$(document).ready(function(){
//caso 01
$("#banner").css({"width":"100%","height":"400px"});
//caso 02
$("#marco section").css("width","100%");
//caso 03
$("section article").css({"width":"100%","text-align":"center","float":"left","margin-bot":"10px"});
//caso 04
$("section article img").css({"width":"80px","height":"50px","cursor":"pointer","border":"3px outset red"});
//caso 05
$("section article").find("label").css({"color":"blue","font-size":"10pt","font-weight":"bold"});
//caso 06
$("section article").find("input").css({"border":"3px double skyblue","font-size":"10pt","font-weight":"bold"});
//caso 07
var imagen = $("section article img");
imagen.mouseover(function(){
   $(this).fadeTo(1000,0.6).css({"border-radius":"10px","border":"3px solid gold"});
  });
//caso 08
imagen.mouseout(function(){
   $(this).fadeTo(1000,1).css({"border-radius":"0px","border":"3px outset red"});
  });
//caso 09

var arrlugares = ["Macchu-Picchu(Cuzco-Perú)","Coliseo(Roma-Italia)",
      "Chichen-Itza(Yucatán-México)","Cristo Redentor(Río de Janeiro-Brasil)","Taj-Mahal(Uttar Pradesh-India)","Muralla-China(Huairo-China)","Petra(Jordania)"];

var n = Math.floor(Math.random()*7);

 //calling  array and make  change  the img  when its  click
imagen.each(function(x,imagenes){
   $(imagenes).click(function(){
    $("header h2").text(arrlugares[x]);
    $("header h2").css("color",colores[n]);
    $("#banner").attr("src", $(this).attr("src"));
   });
 });

$(function(){
  var colors = ['#ff6','#6ff','#f6f','#f66','#66f','#6f6'];
  $('input').click(function(){
      var randomcolor=Math.floor(Math.random()*colors.length);
      //alert(randomcolor);
      $('section').css('color',colors[randomcolor]);
  });
});

body { background:#76A5CC; font-family: arial; }

#marco { width:80%; height:auto; float:left;
      margin-left:10%; background-color:white; border: 2px solid white;
    }

#banner { width:80px; height:20px; float:left; }

header, nav { width:100%; height:auto; float:left; margin-bottom:5px; }

aside { width:30%; height:auto; float:left; }

section { width:70%; height:auto; float:left; }

nav { text-align:center; background-color:#76A5CC; }

footer { width:100%; height:auto; float:left; background-color:#76A5CC; text-align:center; font-size:10pt; font-weight:bold; color:#FFFFFF; }

header>h2 { text-align:center; color:#FFF; }

section>article h2 { color:#76A5CC; }

a:link {
 color: blue;
}
.redsocial { width:10px; height:10px; cursor:pointer; }

<!doctype html>

  <meta charset="utf-8">
  <title>Características JQuery</title>
  <link rel="stylesheet" type="text/css" href="../css/estilo.css" />

Las maravillas del mundo

       //those are imgs

Datos del contacto

     <form>
      Nombre:<input type="text" />

      Apellido:<input type="text" />

      Dirección:<input type="text" />
     </form>

Redes sociales

`enter image description here

By clicking on each image (img) within the section article block, perform:
to. Show the description of the image in h2 of the header block.
second. Apply a font color randomly.
do. Get the path of the image and assign it to the banner.

var arrlugares = ["Macchu-Picchu(Cuzco-Perú)","Coliseo(Roma-Italia)",
                  "Chichen-Itza(Yucatán-México)","Cristo Redentor(Río de Janeiro-Brasil)","Taj-Mahal(Uttar Pradesh-India)","Muralla-China(Huairo-China)","Petra(Jordania)"];

Body:
Line 29 in your code produces a floating point number. Arrays do not accept floating point numbers. Cast it to an integer. Use something like Math.floor or Math.ceil.

Actually I see you doing it in a few places in your code.

Try using your debugger to trace your code. What what it is doing.

I'm still not sure what you're asking but here's a Plunker of clicking an image and changing color, from your code.

  $(document).ready(function() {
      var colors = ['#ff6', '#6ff', '#f6f', '#f66', '#66f', '#6f6'];
      var arrlugares = ["Macchu-Picchu(Cuzco-Perú)", "Coliseo(Roma-Italia)", "Chichen-Itza(Yucatán-México)", "Cristo Redentor(Río de Janeiro-Brasil)", "Taj-Mahal(Uttar Pradesh-India)", "Muralla-China(Huairo-China)", "Petra(Jordania)"];

      $('img').click(function(evnt) {
        var randomcolor = Math.floor(Math.random() * colors.length),
          randomText = Math.floor(Math.random() * arrlugares.length);

        $('#marco header h2')
          .css('color', colors[randomcolor])
          .text(arrlugares[randomText]);

        $('#banner').attr('src', $(evnt.currentTarget).attr('src'));
      });
    })


问:
Format table issue converting markdown to pdf with jupyter notebook
I have the markdown code below for a table in a jupyter notebook.  If I render the notebook to html the formatting comes out fine.  If I try to render it to pdf, the formatting comes out terrible, jumbled up no borders.  I'm working on a mac, any tips on how to solve this.  My end goal is to get a pdf version.

Code:

```<code>| user_id |  business_id |
| :------------: | :-----------------: |
| CxDOIDnH8gp9KXzpBHJYXw |  650 |
| bLbSNkLggFnqwNNzzq-Ijw |  233 |
| ELcQDlf69kb-ihJfxZyL0A |  176 |
| d_TBs6J3twMy9GChqUEXkg |  166 |
| Wu0yySWcHQ5tZ_59HNiamg |  163 |
</code>```

答: Got one solution, open the html in safari and then export to pdf.</p>

Body:
I have the markdown code below for a table in a jupyter notebook.  If I render the notebook to html the formatting comes out fine.  If I try to render it to pdf, the formatting comes out terrible, jumbled up no borders.  I'm working on a mac, any tips on how to solve this.  My end goal is to get a pdf version.

Code:

| user_id |  business_id |
| :------------: | :-----------------: |
| CxDOIDnH8gp9KXzpBHJYXw |  650 |
| bLbSNkLggFnqwNNzzq-Ijw |  233 |
| ELcQDlf69kb-ihJfxZyL0A |  176 |
| d_TBs6J3twMy9GChqUEXkg |  166 |
| Wu0yySWcHQ5tZ_59HNiamg |  163 |


问:
Hide 'div' after specific amount of time
I have a div, which is generally used for showing some status messsage like "you have selected some xyz thing"

Now, I need to hide it at interval of specific amount of time (say, 60 secs) after page loads.

Code:

```<code> <div id="msg">You have selected 'Time and Money' magazine</div>
</code>```

How can I perform the above mentioned thing?

Thanks

答:
To hide msg after 60 seconds, do this</p>

```<code>$("#msg").fadeOut(60000);
</code>```

Body:
I have a div, which is generally used for showing some status messsage like "you have selected some xyz thing"

Now, I need to hide it at interval of specific amount of time (say, 60 secs) after page loads.

Code:

You have selected 'Time and Money' magazine

How can I perform the above mentioned thing?

Thanks

Body:
To hide msg after 60 seconds, do this

$("#msg").fadeOut(60000);


问:
how could I solve this equation, any idea?
I have the code for imacros
I would like to receive the result.

```<code>TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:firstNumber&&VALUE:8
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:secondNumber&&VALUE:9

SET !EXTRACT_TEST_POPUP NO
SET !EXTRACT NULL
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:firstNumber&&VALUE:8 EXTRACT=TXT
SET !VAR1 {{!EXTRACT}}
SET !EXTRACT_TEST_POPUP NO
SET !EXTRACT NULL
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:secondNumber&&VALUE:9 EXTRACT=TXT
SET !VAR2 {{!EXTRACT}}
SET !VAR3 EVAL("var a=\"{{!VAR1}}\"; var b=\"{{!VAR2}}\"; var z = (((a + b))); z")
PROMPT {{!VAR3}}
</code>```

I already tried this code, and even result
click to see the result of imcros

any idea how I can solve.

答:
All what you need is to parse the variable to int before plus action.

```<code>var a = parseInt( "{{!VAR1}}" );
var b = parseInt( "{{!VAR2}}" );
var z = a + b;
z;
</code>```

So for your source code you just need to do:

```<code>TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:firstNumber&&VALUE:8
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:secondNumber&&VALUE:9

SET !EXTRACT_TEST_POPUP NO
SET !EXTRACT NULL
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:firstNumber&&VALUE:8 EXTRACT=TXT
SET !VAR1 {{!EXTRACT}}
SET !EXTRACT_TEST_POPUP NO
SET !EXTRACT NULL
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:secondNumber&&VALUE:9 EXTRACT=TXT
SET !VAR2 {{!EXTRACT}}
SET !VAR3 EVAL("var a = parseInt( "{{!VAR1}}" );var b = parseInt( "{{!VAR2}}" );var z = a + b;z")
PROMPT {{!VAR3}}
</code>```

Body:
I have the code for imacros
I would like to receive the result.

TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:firstNumber&&VALUE:8
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:secondNumber&&VALUE:9

SET !EXTRACT_TEST_POPUP NO
SET !EXTRACT NULL
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:firstNumber&&VALUE:8 EXTRACT=TXT
SET !VAR1 {{!EXTRACT}}
SET !EXTRACT_TEST_POPUP NO
SET !EXTRACT NULL
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:secondNumber&&VALUE:9 EXTRACT=TXT
SET !VAR2 {{!EXTRACT}}
SET !VAR3 EVAL("var a=\"{{!VAR1}}\"; var b=\"{{!VAR2}}\"; var z = (((a + b))); z")
PROMPT {{!VAR3}}

I already tried this code, and even result
click to see the result of imcros

any idea how I can solve.

Body:
All what you need is to parse the variable to int before plus action.

var a = parseInt( "{{!VAR1}}" );
var b = parseInt( "{{!VAR2}}" );
var z = a + b;
z;

So for your source code you just need to do:

TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:firstNumber&&VALUE:8
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:secondNumber&&VALUE:9

SET !EXTRACT_TEST_POPUP NO
SET !EXTRACT NULL
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:firstNumber&&VALUE:8 EXTRACT=TXT
SET !VAR1 {{!EXTRACT}}
SET !EXTRACT_TEST_POPUP NO
SET !EXTRACT NULL
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=TYPE:text&&NAME:secondNumber&&VALUE:9 EXTRACT=TXT
SET !VAR2 {{!EXTRACT}}
SET !VAR3 EVAL("var a = parseInt( "{{!VAR1}}" );var b = parseInt( "{{!VAR2}}" );var z = a + b;z")
PROMPT {{!VAR3}}


问:
Yellow exclamation mark top-right corner component. What does it mean?
There is this annoying symbol that appears on the top right corner of a component while i was using swing and i have no idea what it means. Once it appears it becomes impossible to align the component properly which makes it infuriating.

Top-right. Yellow symbol with the exclamation in the middle:

This time (not the first time this happen) it appeared after i moved a panel to the wrong place (it was a just a order reshuffling but ended up with a new tab somehow) and after moving it back (Dragging it back using the navigator) it showed this symbol.

It isnt clickable, there is no tooltip. It is just standing there and somehow messing up with the component alignment. It probably causes more than that but i am not sure.

I got rid of it by pressing CTRL+Z but i wanna know what that means, why that even appears and how to get rid of it properly. This appeared multiple times these days and IIRC i had to delete a whole component because of it.

答:
I am making a wild guess here. But it looks to me as if using the design view messed up your Java code. Did you check for methods that set layouts and Bounds(setLayout, setBounds) in your code? Your panel might be overlapping other components or wrongly set. There are various anomalies here. Can you upload the code?

or just check for

```<code>setBounds(int,int); //It places components according to given coordinates
setLayout()  // It might be a wrong layout?
</code>```

Body:
I am making a wild guess here. But it looks to me as if using the design view messed up your Java code. Did you check for methods that set layouts and Bounds(setLayout, setBounds) in your code? Your panel might be overlapping other components or wrongly set. There are various anomalies here. Can you upload the code?

or just check for

setBounds(int,int); //It places components according to given coordinates
setLayout()  // It might be a wrong layout?


问:
Pygame, do command exactly 1 time when pressed a key then wait for another click
```<code>if key("LEFT"):
    if select_x != 100:
        select_x-=64
    else:
        print("BORDER REACHED")
</code>```

If you run the Program and press the LEFT key, pygame will do the command written below forever until you stop pressing the key, I want pygame just to do the command 1 time and then waits for another click.

答:
Do the event handling in the event loop for event in pygame.event.get()::

```<code>import pygame as pg

pg.init()
screen = pg.display.set_mode((320, 240))
clock = pg.time.Clock()
select_x = 164
done = False

while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_LEFT:
                if select_x != 100:
                    select_x -= 64
                else:
                    print("BORDER REACHED")

    screen.fill((30, 30, 30))
    pg.display.flip()
    clock.tick(30)

pg.quit()
</code>```

Body:
if key("LEFT"):
    if select_x != 100:
        select_x-=64
    else:
        print("BORDER REACHED")

If you run the Program and press the LEFT key, pygame will do the command written below forever until you stop pressing the key, I want pygame just to do the command 1 time and then waits for another click.

Body:
Do the event handling in the event loop for event in pygame.event.get()::

import pygame as pg

pg.init()
screen = pg.display.set_mode((320, 240))
clock = pg.time.Clock()
select_x = 164
done = False

while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_LEFT:
                if select_x != 100:
                    select_x -= 64
                else:
                    print("BORDER REACHED")

    screen.fill((30, 30, 30))
    pg.display.flip()
    clock.tick(30)

pg.quit()


问:
select button ng model value undefined inside ng if
i have a problem,i cant get value from ng-model inside ng-if. if i alert the model the result is undefined. here is my html file

```<code><div class="col-sm-2">
            <select class="form-control" ng-model="yayaya">
                <option value="1">yeyeyeye</option>

            </select>
        </div>
        <div class="col-sm-2" ng-if="yayaya ==='1'">
            <select class="form-control" ng-model="yoyoyo">
                <option value="bla">blabla</option>
                        </select>
        </div>
</code>```

this is the result when i alert the ng-model

答:
You need ng-change to get the model value, you can pass it as follows,

DEMO

var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope){
    $scope.show = function(yo) {
      alert(yo);
    }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp" ng-controller="testCtrl">
<div class="col-sm-2">
            <select class="form-control" ng-model="yayaya">
                <option value="1">yeyeyeye</option>

            </select>
        </div>
        <div class="col-sm-2" ng-if="yayaya ==='1'">
            <select ng-change="show(yoyoyo)" class="form-control" ng-model="yoyoyo">
                <option value="bla">blabla</option>
            </select>
 </div>
 </body>

        </code>```

Body:
i have a problem,i cant get value from ng-model inside ng-if. if i alert the model the result is undefined. here is my html file

            <select class="form-control" ng-model="yayaya">
                <option value="1">yeyeyeye</option>

            </select>

            <select class="form-control" ng-model="yoyoyo">
                <option value="bla">blabla</option>
                        </select>

this is the result when i alert the ng-model

Body:
You need ng-change to get the model value, you can pass it as follows,

DEMO

var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope){
    $scope.show = function(yo) {
      alert(yo);
    }

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp" ng-controller="testCtrl">
<div class="col-sm-2">
            <select class="form-control" ng-model="yayaya">
                <option value="1">yeyeyeye</option>

            </select>
        </div>
        <div class="col-sm-2" ng-if="yayaya ==='1'">
            <select ng-change="show(yoyoyo)" class="form-control" ng-model="yoyoyo">
                <option value="bla">blabla</option>
            </select>
 </div>
 </body>


问:
iPad css3 animation flickers after keyboard use
I'm developing an app for the iPad using HTML5/CSS3. I'm not using any framework and am just using whatever is natively supported on the device. I have created some css3 animations to emulate the typical iOS sliding left or sliding right when navigating between screens. Here's an example of the slide left animation which is taking advantage of the iPad's CSS3 hardware acceleration: (the ipad is running 4.2).

```<code>/*************************************************
Slide Left
*************************************************/
.screen.slideleft{
 -webkit-animation-duration: 0.5s;
 -webkit-animation-timing-function: ease-in-out;
}
.screen.slideleft.outgoing{
 z-index: 50 !important;
 -webkit-animation-name: slideleft-outgoing;

}
.screen.slideleft.incoming{
 z-index: 100 !important;
 -webkit-animation-name: slideleft-incoming;
}
@-webkit-keyframes slideleft-outgoing{
 from { -webkit-transform: translate3d(0%,0,0); }
 to { -webkit-transform: translate3d(-100%,0,0); }
}
@-webkit-keyframes slideleft-incoming{
 from { -webkit-transform: translate3d(100%,0,0); }
 to { -webkit-transform: translate3d(0%,0,0); }
}</code>```

I also have this CSS which I've attempted to use to fix the flicker:
```
.incoming,
.outgoing{
 display: block !important;
 -webkit-backface-visibility: hidden;
}
```

This works great until the iPad keyboard is used. After which point all the animations flicker severely.

I've been looking for examples of an iPad HTML5 app that uses the keyboard and doesn't have flickers afterwards, but haven't turned up much. The jqTouch demos exhibit the same behavior on the iPad (although I know they were designed for the iPhone).

I've turned up a few posts/questions of similar questions but have never found a good answer.  I've been through http://css3animator.com/2010/12/fight-the-flicker-making-your-css3-animation-bomb-proof/ and the articles linked there but haven't had any success.

Any other suggestions?

Update 1/13 @ 9am

I've added this css and it helped a lot:
```
.incoming *,
.outgoing *{
 -webkit-backface-visibility: hidden;
 -webkit-transform: translate3d(0,0,0); /* This helps with the flicker a lot. */
}
</code>```

The foreground elements don't seem to flicker anymore, but the backgrounds still do. Still looking for some help or helpful resources on Mobile Safari's memory handling tactics.

Update 1/16 @ 11pm

Increasing the z-index as suggested by anonymous. Didn't seem to make a difference.

Update 1/17 @ 8:30am

I've posted a demo of the problem here.

The transitions between screens work great...until you tap/click inside one of the form fields. After the keyboard slides up and returns, all the transitions flicker. Go to the URL inside the iOS simulator or on an actual iPad to see what I'm talking about.

答:
I had the same issue, but i was able to reduce the flicker to almost unnoticeable by applying the fix described here and here:

http://code.google.com/p/jqtouch/issues/detail?id=301

https://github.com/senchalabs/jQTouch/issues/issue/130

Basically set the z-index of the page you a are moving out to -1 and after the transistion back to 1

Body:
I'm developing an app for the iPad using HTML5/CSS3. I'm not using any framework and am just using whatever is natively supported on the device. I have created some css3 animations to emulate the typical iOS sliding left or sliding right when navigating between screens. Here's an example of the slide left animation which is taking advantage of the iPad's CSS3 hardware acceleration: (the ipad is running 4.2).

/*************************************************
Slide Left
*************************************************/
.screen.slideleft{
 -webkit-animation-duration: 0.5s;
 -webkit-animation-timing-function: ease-in-out;
}
.screen.slideleft.outgoing{
 z-index: 50 !important;
 -webkit-animation-name: slideleft-outgoing;

}
.screen.slideleft.incoming{
 z-index: 100 !important;
 -webkit-animation-name: slideleft-incoming;
}
@-webkit-keyframes slideleft-outgoing{
 from { -webkit-transform: translate3d(0%,0,0); }
 to { -webkit-transform: translate3d(-100%,0,0); }
}
@-webkit-keyframes slideleft-incoming{
 from { -webkit-transform: translate3d(100%,0,0); }
 to { -webkit-transform: translate3d(0%,0,0); }
}

I also have this CSS which I've attempted to use to fix the flicker:

.incoming,
.outgoing{
 display: block !important;
 -webkit-backface-visibility: hidden;
}

This works great until the iPad keyboard is used. After which point all the animations flicker severely.

I've been looking for examples of an iPad HTML5 app that uses the keyboard and doesn't have flickers afterwards, but haven't turned up much. The jqTouch demos exhibit the same behavior on the iPad (although I know they were designed for the iPhone).

I've turned up a few posts/questions of similar questions but have never found a good answer.  I've been through http://css3animator.com/2010/12/fight-the-flicker-making-your-css3-animation-bomb-proof/ and the articles linked there but haven't had any success.

Any other suggestions?

Update 1/13 @ 9am

I've added this css and it helped a lot:

.incoming *,
.outgoing *{
 -webkit-backface-visibility: hidden;
 -webkit-transform: translate3d(0,0,0); /* This helps with the flicker a lot. */
}

The foreground elements don't seem to flicker anymore, but the backgrounds still do. Still looking for some help or helpful resources on Mobile Safari's memory handling tactics.

Update 1/16 @ 11pm

Increasing the z-index as suggested by anonymous. Didn't seem to make a difference.

Update 1/17 @ 8:30am

I've posted a demo of the problem here.

The transitions between screens work great...until you tap/click inside one of the form fields. After the keyboard slides up and returns, all the transitions flicker. Go to the URL inside the iOS simulator or on an actual iPad to see what I'm talking about.


问:
Status bar visibility is not unified on iOS
I am migrating an iOS app to XCode9 from 8. I'm not sure what's causing but it seems like either Swift 3.2/Xcode 9 is behaving badly.

So this app I'm developing has Status bar on all the view controllers and so has it been, but after migrating this started showing only the home view. Changing view by tab button it becomes blank like the following screenshots.

View controller-based status bar appearance is NO and Hide Status Bar is OFF

I added setNeedsStatusBarAppearanceUpdate() and its parameters but still not working.

Here's code of ViewController of "Another View"

```<code>import UIKit

class InfoViewController: UITableViewController {

private var threads: [Info] = []
private var loading: Bool = false
private var hasNext: Bool = true

private var selectedThread: Info?
private var noInfoView: UIView?

internal var shouldRefresh: Bool = true
private var pagingIndicatorView: UIActivityIndicatorView!

private var timer: Timer?
private var poolingInterval: TimeInterval = 60 * 3

private var shouldClearThread: Bool = false
private var nextViewController: InfoDetailViewController?

let RequireCheckStatusForMessagesNotificationKey = "RequireCheckStatusForMessagesNotificationKey"

deinit {
    NotificationCenter.default.removeObserver(self)
    stopPooling()
}

override func viewDidLoad() {
    super.viewDidLoad()
    setNeedsStatusBarAppearanceUpdate()
    tableView.contentInset.bottom = 40

    pagingIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    pagingIndicatorView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50)
    pagingIndicatorView.hidesWhenStopped = true

    NotificationCenter.default.addObserver(self, selector: #selector(InfoViewController.requireCheckInfosForMessagesNotificationHandler(notif:)), name: NSNotification.Name(rawValue: RequireCheckStatusForMessagesNotificationKey), object: nil)
}

var statusBarStyle : UIStatusBarStyle = .lightContent

override var preferredStatusBarStyle: UIStatusBarStyle {
    get {
        return statusBarStyle
    }
}

var statusBarStatus : Bool = false

override var prefersStatusBarHidden: Bool {
    get {
        return statusBarStatus
    }
}
</code>```

答:
It's easier to have View controller-based status bar appearance set to YES and to play with the following parameters of UIViewController:

```<code>override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
    get {
        return .slide
    }
}

var statusBarStyle : UIStatusBarStyle = .default

override var preferredStatusBarStyle: UIStatusBarStyle {
    get {
        return statusBarStyle
    }
}

var statusBarStatus : Bool = false

override var prefersStatusBarHidden: Bool {
    get {
        return statusBarStatus
    }
}
</code>```

as you can see here, i refer to custom stored parameters for the value i actually want, thus changing the status bar's update is a matter of changing those custom parameters and to call statusBarNeedsUpdate.

Try this approach, if it does not fix your issue, provide code for your controller.

Body:
I am migrating an iOS app to XCode9 from 8. I'm not sure what's causing but it seems like either Swift 3.2/Xcode 9 is behaving badly.

So this app I'm developing has Status bar on all the view controllers and so has it been, but after migrating this started showing only the home view. Changing view by tab button it becomes blank like the following screenshots.

View controller-based status bar appearance is NO and Hide Status Bar is OFF

I added setNeedsStatusBarAppearanceUpdate() and its parameters but still not working.

Here's code of ViewController of "Another View"

import UIKit

class InfoViewController: UITableViewController {

private var threads: [Info] = []
private var loading: Bool = false
private var hasNext: Bool = true

private var selectedThread: Info?
private var noInfoView: UIView?

internal var shouldRefresh: Bool = true
private var pagingIndicatorView: UIActivityIndicatorView!

private var timer: Timer?
private var poolingInterval: TimeInterval = 60 * 3

private var shouldClearThread: Bool = false
private var nextViewController: InfoDetailViewController?

let RequireCheckStatusForMessagesNotificationKey = "RequireCheckStatusForMessagesNotificationKey"

deinit {
    NotificationCenter.default.removeObserver(self)
    stopPooling()
}

override func viewDidLoad() {
    super.viewDidLoad()
    setNeedsStatusBarAppearanceUpdate()
    tableView.contentInset.bottom = 40

    pagingIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    pagingIndicatorView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50)
    pagingIndicatorView.hidesWhenStopped = true

    NotificationCenter.default.addObserver(self, selector: #selector(InfoViewController.requireCheckInfosForMessagesNotificationHandler(notif:)), name: NSNotification.Name(rawValue: RequireCheckStatusForMessagesNotificationKey), object: nil)
}

var statusBarStyle : UIStatusBarStyle = .lightContent

override var preferredStatusBarStyle: UIStatusBarStyle {
    get {
        return statusBarStyle
    }
}

var statusBarStatus : Bool = false

override var prefersStatusBarHidden: Bool {
    get {
        return statusBarStatus
    }
}

Body:
It's easier to have View controller-based status bar appearance set to YES and to play with the following parameters of UIViewController:

override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
    get {
        return .slide
    }
}

var statusBarStyle : UIStatusBarStyle = .default

override var preferredStatusBarStyle: UIStatusBarStyle {
    get {
        return statusBarStyle
    }
}

var statusBarStatus : Bool = false

override var prefersStatusBarHidden: Bool {
    get {
        return statusBarStatus
    }
}

as you can see here, i refer to custom stored parameters for the value i actually want, thus changing the status bar's update is a matter of changing those custom parameters and to call statusBarNeedsUpdate.

Try this approach, if it does not fix your issue, provide code for your controller.


问:
How to call a method that requires "self" in Python?
I am very new to python and am trying to figure out what needs to be passed to this method. I'm sure this is such a noob question, but how do I create an object to pass to self?</p>

```<code>class Bittrex(object):

    def get_markets(self):

        return self._api_query(path_dict={
            API_V1_1: '/public/getmarkets',
            API_V2_0: '/pub/Markets/GetMarkets'
        }, protection=PROTECTION_PUB)

    get_markets(self) //My attempt to call
</code>```

答:
Create an object of class Bittrex and then call method using .

```<code>b = Bittrex()
res = b.get_markets()
</code>```

Body:
I am very new to python and am trying to figure out what needs to be passed to this method. I'm sure this is such a noob question, but how do I create an object to pass to self?

class Bittrex(object):

    def get_markets(self):

        return self._api_query(path_dict={
            API_V1_1: '/public/getmarkets',
            API_V2_0: '/pub/Markets/GetMarkets'
        }, protection=PROTECTION_PUB)

    get_markets(self) //My attempt to call

Body:
Create an object of class Bittrex and then call method using .

b = Bittrex()
res = b.get_markets()


问:
How to mass change the link in WordPress?
the thing is, In my WordPress website i have posted some links to some post. and the domain name of the links have been changed and they are so much in an amount in total of 549 posts.the link is like this yourdomain.com/free-access/ and they are in a button. so any suggestions how can i change the domain name. </p>

<p>thanks </p>

答: The best way to change the domain names in posts is to export and download the database backup. Search and replace the domain name occurrences and save the sql file. Then import the sql file.</p>

Body:
the thing is, In my WordPress website i have posted some links to some post. and the domain name of the links have been changed and they are so much in an amount in total of 549 posts.the link is like this yourdomain.com/free-access/ and they are in a button. so any suggestions how can i change the domain name.

thanks


问:
pthread_mutex_trylock() use to wait , until other lock has not released
In my code I am using pthread_mutx_trylock() to check thread 1 has completed his
job and release the mutexlock or not ?Please let me know either its a valid way or not ?

In Thread 1:

```<code>     pthread_mutex_lock(&sync_wait);
     // Waiting for return type.
     pthread_mutex_unlock(&sync_wait);
</code>```

In Thread 2:

```<code>    while (pthread_mutex_trylock(&sync_wait) == 0) {
          }; // Wait until other thread has lock

    // Waiting till thread 1 sync wait lock has not released.
    pthread_mutex_unlock(&sync_wait);
</code>```

答:
From manual Page

The pthread_mutex_trylock() function shall return zero if a lock on
  the mutex object referenced by mutex is acquired. Otherwise, an error
  number is returned to indicate the error.

```<code>// so this will loop forever once you aquire lock
    while (pthread_mutex_trylock(&sync_wait) == 0) {
              }; // Wait until other thread has lock
</code>```

Edit:

This section of code should handle your scenario

```<code>while ( int ret = pthread_mutex_trylock( &sync_wait) )
{
  // Unable to get Mutex probably some other thread aquired it
  // sleep for some time usleep or even better use pthread_mutex_timedlock
  // Ideally possible ret values should have been handled but for now
  // this will do
}
</code>```

and yes pthread_mutex_unlock( );once done with work

here is the manpage
also there is a question on so about difference between pthread_mutex_lock and pthread_mutex_trylock here
this is another example of handling multiple return values from pthread_try_lock()

Body:
In my code I am using pthread_mutx_trylock() to check thread 1 has completed his
job and release the mutexlock or not ?Please let me know either its a valid way or not ?

In Thread 1:

     pthread_mutex_lock(&sync_wait);
     // Waiting for return type.
     pthread_mutex_unlock(&sync_wait);

In Thread 2:

    while (pthread_mutex_trylock(&sync_wait) == 0) {
          }; // Wait until other thread has lock

    // Waiting till thread 1 sync wait lock has not released.
    pthread_mutex_unlock(&sync_wait);

Body:
From manual Page

The pthread_mutex_trylock() function shall return zero if a lock on
  the mutex object referenced by mutex is acquired. Otherwise, an error
  number is returned to indicate the error.

// so this will loop forever once you aquire lock
    while (pthread_mutex_trylock(&sync_wait) == 0) {
              }; // Wait until other thread has lock

Edit:

This section of code should handle your scenario

while ( int ret = pthread_mutex_trylock( &sync_wait) )
{
  // Unable to get Mutex probably some other thread aquired it
  // sleep for some time usleep or even better use pthread_mutex_timedlock
  // Ideally possible ret values should have been handled but for now
  // this will do
}

and yes pthread_mutex_unlock( );once done with work

here is the manpage
also there is a question on so about difference between pthread_mutex_lock and pthread_mutex_trylock here
this is another example of handling multiple return values from pthread_try_lock()


问:
Force redraw of img element
My Elm app lets the user rotate pictures: when a picture on the screen is clicked, elm makes an API call to rotate the picture file on the server. Following that I'd like the rotated image to show in the browser.

But the virtual DOM hasn't changed at all since the img node has the same src URL. Is there a way I can force the img to be recreated anyway?

Sure, I could use a Keyed node or modify some attribute on my img to force the redraw, but that would mean adding something to my model that is modified on rotate. It's possible but not very elegant.

答: You want something to be modified on rotate: namely, the image. So you're going to have a change in your model at the point when you want the rotation to occur. I'd have the response from the API increment a counter in the model (or use the current time via Time.now), and then update the image URL with a cache busting query parameter based on that value. More details on cache busting query parameters are here: Cache busting via params

Title: Force redraw of img element


问:
Browse file in AngularJS + TypeScript on button click
I have user.component.html and user.component.ts
All examples I found were in html this way <input type="file" />
I don't want to use this style. I have in my html file:

```<code><button type="button" class="btn" (click)="openPicture()" Browse </button>
</code>```

Below is the function on ts file:

```<code>  public openPicture() {
    //for testing
    console.log('button clicked to open picture');

    var picture = browse.the.picture.and.assing.to.this.variable;

    //another test, see on console if picture is read
    console.log('%c       ', 'font-size: 100px; background: {{picture}} no-repeat;');
    // Later display picture variable on html and save to database or do anything desired.
}
</code>```

I have found an example on stackoverflow with angular/material but I dont have this module. Is there any other alternative way, without installing any extra package to solve this?

答:
you can implement like this

```<code><input type="file" style="display: none" #file (change)="fileChange($event)"/>
<button type="button" class="btn" (click)="file.click()"> Browse </button>
</code>```

.ts

```<code>export class AppComponent {
  file: File;

  constructor() {

  }

  fileChange(file) {
    this.file = file.target.files[0];
    console.log(this.file.name);
  }
}
</code>```

Body:
I have user.component.html and user.component.ts
All examples I found were in html this way <input type="file" />
I don't want to use this style. I have in my html file:

<button type="button" class="btn" (click)="openPicture()" Browse </button>

Below is the function on ts file:

  public openPicture() {
    //for testing
    console.log('button clicked to open picture');

    var picture = browse.the.picture.and.assing.to.this.variable;

    //another test, see on console if picture is read
    console.log('%c       ', 'font-size: 100px; background: {{picture}} no-repeat;');
    // Later display picture variable on html and save to database or do anything desired.
}

I have found an example on stackoverflow with angular/material but I dont have this module. Is there any other alternative way, without installing any extra package to solve this?

Body:
you can implement like this

<input type="file" style="display: none" #file (change)="fileChange($event)"/>
<button type="button" class="btn" (click)="file.click()"> Browse </button>

.ts

export class AppComponent {
  file: File;

  constructor() {

  }

  fileChange(file) {
    this.file = file.target.files[0];
    console.log(this.file.name);
  }
}


问:
Hash table print and insert function
I am writing a hash table function and the data it has is from a text file. The text file has a four digit student ID and a name with embedded spaces. The problem is the insert function doesn't get the first line from the file. I run the program and when I test it, the first student from the file doesn't come up. I check the rest of the students name by inputting their ID's and they output their names. Also, it doesn't output the full name it gets from the file, just the first. If I look up chris campos from the file, I would type in its four digit ID, but only chris will be output not chris campos.

If you want to see the full code, I will edit the post, but I believe the error should be in the code I posted. I think the code is right, but I want to see if others can see the error or how I can improve it.

Also, I am curious, I am using chaining to handle collisions. How can I make the program output all the names in the bucket that have the same four digit ID. If two names have the same ID, how can I make the program output the two names when the user inputs the ID.

2301 Robb Arredondo
5401 Chris Campos
6305 Yogi Bear
9108 Yoshi Man
0310 John Du
1812 Maria Yu
4318 Power Ranger
7122 Bob Chan
8225 Will Boo
5324 Ghost Lee
0134 Mary Su
2150 Jane Mary
1100 Gary Campos
2305 Alan Kong
3420 Bill Nye
5608 Alex Garcia
9112 Goku Nani
6750 Paul Avalos
1220 Jason Noni
9005 Oscar Roger
6550 Geo Qwerty
1112 Mini Me
2315 Garfield Beria
4201 Just Saying
```

<p>Here is how my program gets the data from the file:</p>

```HashTable hashtable;
std::ifstream file("students.txt");
int option;
std::string studentID;
std::string studentName;
std::string line;

if (!file.is_open())
{
    std::cout << "Error in opening file\n";
}
else
{
    while (std::getline(file, line))
    {
        file >> studentID >> studentName;
        hashtable.Insert(studentID, studentName);
    }

    file.close();
}
```

<p>Here is my insert function..</p>

```void HashTable::Insert(std::string ID, std::string name)
{
    int location = Hash(ID, tableSize);

    if (listofStudents[location]->m_idNum == "empty")
    {
        listofStudents[location]->m_idNum = ID;
        listofStudents[location]->m_Name = name;
    }
    else
    {

        Student* ptr = listofStudents[location];
        Student* newStudent = new Student;
        newStudent->m_Name = name;
        newStudent->m_idNum = ID;
        newStudent->next = NULL;

        while (ptr->next != NULL)
        {
            ptr = ptr->next;
        }
        ptr->next = newStudent;
    }

}
```

<p>Here is my retrieve function...</p>

```void HashTable::Retrieve(std::string ID)
{
int location = Hash(ID, tableSize);
Student* ptr;

for (ptr = listofStudents[location]; ptr; ptr = ptr->next)
{
    if (ptr->m_idNum == ID)
    {
        std::cout << "--------------------\n";
        std::cout << "Name of Student: " << ptr->m_Name << std::endl;
        std::cout << "---------------------\n";
    }
    else
        std::cout << "No Student Found\n";
}
}
```

<p>Here is my hash function if you want to see how the hashing technique is working.It converts a string to an int. The reason I am using a string is because I need to use a string for the assignment.</p>

```int HashTable::Hash(const std::string& key, int tablesize)
{
    int hashVal = 0;
    for (int i = 0; i < key.length(); i++)
    {
        hashVal =  37 * hashVal + key[i];
    }
    hashVal %= tablesize;

    if (hashVal < 0)
        hashVal += tablesize;

    return hashVal;
}
```

答:
Your problem here:

```<code>while (std::getline(file, line))
{
    file >> studentID >> studentName; // This only read the id and the first name
    hashtable.Insert(studentID, studentName);
}
</code>```

You should try:

```<code>file >> studentID >> firstname >> lastname;
file.ignore(); // this will pass the EOL character
</code>```

Title: Hash table print and insert function

Body:
I am writing a hash table function and the data it has is from a text file. The text file has a four digit student ID and a name with embedded spaces. The problem is the insert function doesn't get the first line from the file. I run the program and when I test it, the first student from the file doesn't come up. I check the rest of the students name by inputting their ID's and they output their names. Also, it doesn't output the full name it gets from the file, just the first. If I look up chris campos from the file, I would type in its four digit ID, but only chris will be output not chris campos.

If you want to see the full code, I will edit the post, but I believe the error should be in the code I posted. I think the code is right, but I want to see if others can see the error or how I can improve it.

Also, I am curious, I am using chaining to handle collisions. How can I make the program output all the names in the bucket that have the same four digit ID. If two names have the same ID, how can I make the program output the two names when the user inputs the ID.

2301 Robb Arredondo
5401 Chris Campos
6305 Yogi Bear
9108 Yoshi Man
0310 John Du
1812 Maria Yu
4318 Power Ranger
7122 Bob Chan
8225 Will Boo
5324 Ghost Lee
0134 Mary Su
2150 Jane Mary
1100 Gary Campos
2305 Alan Kong
3420 Bill Nye
5608 Alex Garcia
9112 Goku Nani
6750 Paul Avalos
1220 Jason Noni
9005 Oscar Roger
6550 Geo Qwerty
1112 Mini Me
2315 Garfield Beria
4201 Just Saying

Here is how my program gets the data from the file:

HashTable hashtable;
std::ifstream file("students.txt");
int option;
std::string studentID;
std::string studentName;
std::string line;

if (!file.is_open())
{
    std::cout << "Error in opening file\n";
}
else
{
    while (std::getline(file, line))
    {
        file >> studentID >> studentName;
        hashtable.Insert(studentID, studentName);
    }

    file.close();
}

Here is my insert function..

void HashTable::Insert(std::string ID, std::string name)
{
    int location = Hash(ID, tableSize);

    if (listofStudents[location]->m_idNum == "empty")
    {
        listofStudents[location]->m_idNum = ID;
        listofStudents[location]->m_Name = name;
    }
    else
    {

        Student* ptr = listofStudents[location];
        Student* newStudent = new Student;
        newStudent->m_Name = name;
        newStudent->m_idNum = ID;
        newStudent->next = NULL;

        while (ptr->next != NULL)
        {
            ptr = ptr->next;
        }
        ptr->next = newStudent;
    }

}

Here is my retrieve function...

void HashTable::Retrieve(std::string ID)
{
int location = Hash(ID, tableSize);
Student* ptr;

for (ptr = listofStudents[location]; ptr; ptr = ptr->next)
{
    if (ptr->m_idNum == ID)
    {
        std::cout << "--------------------\n";
        std::cout << "Name of Student: " << ptr->m_Name << std::endl;
        std::cout << "---------------------\n";
    }
    else
        std::cout << "No Student Found\n";
}
}

Here is my hash function if you want to see how the hashing technique is working.It converts a string to an int. The reason I am using a string is because I need to use a string for the assignment.

int HashTable::Hash(const std::string& key, int tablesize)
{
    int hashVal = 0;
    for (int i = 0; i < key.length(); i++)
    {
        hashVal =  37 * hashVal + key[i];
    }
    hashVal %= tablesize;

    if (hashVal < 0)
        hashVal += tablesize;

    return hashVal;
}

Body:
Your problem here:

while (std::getline(file, line))
{
    file >> studentID >> studentName; // This only read the id and the first name
    hashtable.Insert(studentID, studentName);
}

You should try:

file >> studentID >> firstname >> lastname;
file.ignore(); // this will pass the EOL character


问:
How to set img size as percentage of parent element within sizes attribute
Is there a way to set the size of an image as a percentage of its parent element within the srcset/sizes attributes? I have only seen ways to set the size as an absolute or as a percentage of the view port.

If the above is not possible, and we are using relative img widths in say, a grid, is there a way (in CSS and/or HTML) to tell the browser to download different img resolutions depending on the device size?

Thanks.

答:
If you make the image width a percentage it will shrink the image to the width of the parent element I think.

```<code>height: auto;
width: 40%;
</code>```

If you want to use different resolutions you can use the @ media rule. Set up an empty div where the image should go. Then use the @ media rule to change the background image at different screen widths in CSS.

In your html where the image should go:

```<code><div class="yourclass"></div>
</code>```

In your  css document:

```<code>  @media screen and (min-width: 630px) {
     .yourclass {
     background-image: url("yourpciture.png");
    }
    }
</code>```

If you create one of these for each resolution change you want the image will change when someone drags their window or when you change devices. Just remember it's min width so call them smallest screen size to largest or your changes will be overridden.

Body:
If you make the image width a percentage it will shrink the image to the width of the parent element I think.

height: auto;
width: 40%;

If you want to use different resolutions you can use the @ media rule. Set up an empty div where the image should go. Then use the @ media rule to change the background image at different screen widths in CSS.

In your html where the image should go:

<div class="yourclass"></div>

In your  css document:

  @media screen and (min-width: 630px) {
     .yourclass {
     background-image: url("yourpciture.png");
    }
    }

If you create one of these for each resolution change you want the image will change when someone drags their window or when you change devices. Just remember it's min width so call them smallest screen size to largest or your changes will be overridden.


问:
Maintain object references through Serialize/Deserialize
When serializing, I would like to serialize an object only once, then any references to that object should be serialized as a reference to the object. This is because, when I later deserialize the objects, I would like to maintain those references. To illustrate my goal, the code below should output "After Serialization: true".</p>

```<code>class Program
{
    static void Main(string[] args)
    {
        MyObject obj = new MyObject() { Name = "obj" };
        MyObject[] myObjs = new MyObject[]
        {
            obj, obj
        };

        Console.WriteLine("Object Refs Equal?");
        Console.WriteLine(string.Format("Before Serialization: {0}",
            object.ReferenceEquals(myObjs[0], myObjs[1])));

        XmlSerializer toXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream toFile = File.Create(@"C:\foo.xml"))
        {
            toXml.Serialize(toFile, myObjs);
        }

        XmlSerializer fromXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream fromFile = File.OpenRead(@"C:\foo.xml"))
        {
            MyObject[] deserialized = (MyObject[])fromXml.Deserialize(fromFile);

            Console.WriteLine(string.Format("After Serialization: {0}",
            object.ReferenceEquals(deserialized[0], deserialized[1])));
        }

        Console.ReadLine();
    }
}

[Serializable]
public class MyObject
{
    public string Name { get; set; }
}
</code>```

答:
Not sure if this is what you would like to hear... But lets just think about what you are trying to do.

You only have the need to serialize an object when:
 a) You want to store it somewhere an latter on retrieve the information.
 b) You want to send the object to another application.

A reference is nothing more than a pointer to where the object is. So in either case you simply cannot access the memory because in a) it is reserved for your application and in b) it is another machine and it doesn't even exists.

http://en.csharp-online.net/Glossary:Definition_-_Reference_type

OwnerDisplayName: CodeChef

Body:
When serializing, I would like to serialize an object only once, then any references to that object should be serialized as a reference to the object. This is because, when I later deserialize the objects, I would like to maintain those references. To illustrate my goal, the code below should output "After Serialization: true".

class Program
{
    static void Main(string[] args)
    {
        MyObject obj = new MyObject() { Name = "obj" };
        MyObject[] myObjs = new MyObject[]
        {
            obj, obj
        };

        Console.WriteLine("Object Refs Equal?");
        Console.WriteLine(string.Format("Before Serialization: {0}",
            object.ReferenceEquals(myObjs[0], myObjs[1])));

        XmlSerializer toXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream toFile = File.Create(@"C:\foo.xml"))
        {
            toXml.Serialize(toFile, myObjs);
        }

        XmlSerializer fromXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream fromFile = File.OpenRead(@"C:\foo.xml"))
        {
            MyObject[] deserialized = (MyObject[])fromXml.Deserialize(fromFile);

            Console.WriteLine(string.Format("After Serialization: {0}",
            object.ReferenceEquals(deserialized[0], deserialized[1])));
        }

        Console.ReadLine();
    }
}

[Serializable]
public class MyObject
{
    public string Name { get; set; }
}

OwnerDisplayName: Sergio


问:
I've been coding with notepad++ and now I'm getting into Eclipse IDE and I'm having trouble with my older projects
So,
I have been coding Java last semester (college) and we've always done it in Notepad++ , compile and execute by CMD (very simple programs though) and now I want to start codding in Eclipse, since I heard that it saves you a lot of time in syntax and gives you a heads up on typos and errors (Also I'm tired of compiling and executing by console). But the thing is that I usually have my code into two folders (model and interface) and use the

```<code>package modelo;
package interfaz;
</code>```

And now I execute eclipse and open these files, but it doesn't seem to work, I mean the code shows up and I can edit, but it wont show help or even let me execute the code. I know it must be a very noobie question but I can't seem to make it work.

Update:
This is what i get when i import my "project"
This is the error

答: You need to create a project in Eclipse first, then add packages and classes in that project, make sure that the JDK in classpath is configured correctly </p>

Body:
So,
I have been coding Java last semester (college) and we've always done it in Notepad++ , compile and execute by CMD (very simple programs though) and now I want to start codding in Eclipse, since I heard that it saves you a lot of time in syntax and gives you a heads up on typos and errors (Also I'm tired of compiling and executing by console). But the thing is that I usually have my code into two folders (model and interface) and use the

package modelo;
package interfaz;

And now I execute eclipse and open these files, but it doesn't seem to work, I mean the code shows up and I can edit, but it wont show help or even let me execute the code. I know it must be a very noobie question but I can't seem to make it work.

Update:
This is what i get when i import my "project"
This is the error


问:
New to tkinter buttons not displaying?
Sorry if the title does not elucidate on the question - blame the way submissions work, I guess.

I'm new to tkinter, and I was given this code by a teacher to display how the module works.  The module is installed on my machine, I checked 'help modules' to make sure.

```<code>import tkinter

class Application(tkinter.Frame):
   def _init_(self, master=None):
      tkinter.Frame._init_(self, master)
      self.pack()

      self.increase_button = tkinter.RADIOBUTTON(self)
      self.increase_button["text"] - "Increase"
      self.increase_button["command"] = self.increase_value
      self.increase_button.pack(side="right")

      self.increase_button - tkinter.RADIOBUTTON(self)
      self.increase_button["text"] = "Decrease"
      self.increase_button["command"] = self.decrease_value
      self.increase_button.pack(side="left")

   def increase_value(self):
      global mainval
      mainval *= 2
      print (mainval)
   def decrease_value(self):
      global mainval
      mainval /= 2
      print (mainval)

mainval = 1.0

root = tkinter.Tk()
app = Application(master=root)
app.mainloop()
</code>```

So, it's supposed to display buttons that are made to increase and decrease a number that also displays on the screen.

When I test however, I just get a blank window, with no errors detected.

答:
In Python the constructor for a class is named __init__ with two underscores on either side. You have one underscore on each side. Add the proper number of underscores to def _init_( and to tkinter.Frame._init_(

In tkinter the Radiobutton class only has one capital letter. Replace the tkinter.RADIOBUTTON( with tkinter.Radiobutton(
The code should look something like this:

```<code>def __init__(self, master=None):
    tkinter.Frame.__init__(self, master)
    self.pack()

    self.increase_button = tkinter.Radiobutton(self)
</code>```

Title: New to tkinter buttons not displaying?

Body:
Sorry if the title does not elucidate on the question - blame the way submissions work, I guess.

I'm new to tkinter, and I was given this code by a teacher to display how the module works.  The module is installed on my machine, I checked 'help modules' to make sure.

import tkinter

class Application(tkinter.Frame):
   def _init_(self, master=None):
      tkinter.Frame._init_(self, master)
      self.pack()

      self.increase_button = tkinter.RADIOBUTTON(self)
      self.increase_button["text"] - "Increase"
      self.increase_button["command"] = self.increase_value
      self.increase_button.pack(side="right")

      self.increase_button - tkinter.RADIOBUTTON(self)
      self.increase_button["text"] = "Decrease"
      self.increase_button["command"] = self.decrease_value
      self.increase_button.pack(side="left")

   def increase_value(self):
      global mainval
      mainval *= 2
      print (mainval)
   def decrease_value(self):
      global mainval
      mainval /= 2
      print (mainval)

mainval = 1.0

root = tkinter.Tk()
app = Application(master=root)
app.mainloop()

So, it's supposed to display buttons that are made to increase and decrease a number that also displays on the screen.

When I test however, I just get a blank window, with no errors detected.

Body:
In Python the constructor for a class is named __init__ with two underscores on either side. You have one underscore on each side. Add the proper number of underscores to def _init_( and to tkinter.Frame._init_(

In tkinter the Radiobutton class only has one capital letter. Replace the tkinter.RADIOBUTTON( with tkinter.Radiobutton(
The code should look something like this:

def __init__(self, master=None):
    tkinter.Frame.__init__(self, master)
    self.pack()

    self.increase_button = tkinter.Radiobutton(self)


问:
Dynamic allocation array difference in C++
Today I came across a new type of allocation in cpp which I never heard of any I tried to search google but didn't find any related answer.

```<code>long int *a=new long int[N+1]();
</code>```

I know long int *a = new long int[N+1];

But what is the difference between the two above?

答: long int *a=new long int[N+1](); is the value initialization of int so each element of a is automatically initialized to 0, whereas in the second instance it just creates an array of size N+1 which may contain anything. In that case, you must assign a value to that variable before using it or invoke undefined behavior.

Body:
Today I came across a new type of allocation in cpp which I never heard of any I tried to search google but didn't find any related answer.

long int *a=new long int[N+1]();

I know long int *a = new long int[N+1];

But what is the difference between the two above?


问:
C# Console Loop Proceed On KeyUp
I need to make it to where my code will only exit the loop when the key that is pressed, is released. I am doing this is console and will need to stay in console.

Here is an example of the code.

```<code>ConsoleKeyInfo = ki;

while (true)
{
    ki = Console.ReadKey();

    if (ki.Key == ConsoleKey.A)
    {
        Console.Write("A");
    }
}
</code>```

As you can see above, when the A key is pressed, it will write A in the console. If you hold down the A key, it will continuously write A.

What I'm wanting is for the console to write A ONCE until the A key is released. Then, if you press A again, it will print again.

I've thought about using "KeyUp" but I'm not able to use it on a console application. But something that would accomplish the following...

```<code>ConsoleKeyInfo = ki;

while (true)
{
    ki = Console.ReadKey();

    if (ki.Key == ConsoleKey.A)
    {
        //I know the following isn't actually code, but it's explaining what I want to happen.
        do (onKeyRelease)
        {
            Console.Write("A");
        }
    }
}
</code>```

Basically, I'm wanting only one thing to happen when the loop when a key is pressed until the key is released. When the key is released, the loop will start again.

Please note that I am using this idea for a Text-Based RPG game. So waiting until another key is pressed (including adding another Console.ReadKey() to the end) would not be ideal.

答: Store last pressed key and print character only when it is different from the last pressed key.</p>

Title: C# Console Loop Proceed On KeyUp

Body:
I need to make it to where my code will only exit the loop when the key that is pressed, is released. I am doing this is console and will need to stay in console.

Here is an example of the code.

ConsoleKeyInfo = ki;

while (true)
{
    ki = Console.ReadKey();

    if (ki.Key == ConsoleKey.A)
    {
        Console.Write("A");
    }
}

As you can see above, when the A key is pressed, it will write A in the console. If you hold down the A key, it will continuously write A.

What I'm wanting is for the console to write A ONCE until the A key is released. Then, if you press A again, it will print again.

I've thought about using "KeyUp" but I'm not able to use it on a console application. But something that would accomplish the following...

ConsoleKeyInfo = ki;

while (true)
{
    ki = Console.ReadKey();

    if (ki.Key == ConsoleKey.A)
    {
        //I know the following isn't actually code, but it's explaining what I want to happen.
        do (onKeyRelease)
        {
            Console.Write("A");
        }
    }
}

Basically, I'm wanting only one thing to happen when the loop when a key is pressed until the key is released. When the key is released, the loop will start again.

Please note that I am using this idea for a Text-Based RPG game. So waiting until another key is pressed (including adding another Console.ReadKey() to the end) would not be ideal.


问:
Don't know why valgrind gives me Conditional jump or move depends on uninitialised value(s) error?
My code below successfully converts a Binary search tree to a linked list however valgrind has been giving me "Conditional jump or move depends on uninitialised value(s)" errors. Yet after looking at my code, I don't see where I have that?

```<code>ListNodePtr convertBSTtoLinkedList(TreeNodePtr root)
{
    ListNodePtr list,head;
    list = malloc(sizeof(struct ListNode));
    list->key = root->key;
    if (root->right != NULL)
    {
        list->next = convertBSTtoLinkedList(root->right);    //line 80
    }
    if (root->left != NULL)
    {
    ListNodePtr tail;
    head = convertBSTtoLinkedList(root->left);   //line 85
    tail = head;
    while (tail->next != NULL) {        //Line 87
        tail = tail->next;
    }
    tail->next = list;
    return head;
    }
    return list;
}
</code>```

This is my valgrind error, it repeats itself a few times.

```<code>==3076== Conditional jump or move depends on uninitialised value(s)
==3076==    at 0x108AF2: convertBSTtoLinkedList (bst.c:87)
==3076==    by 0x108AC8: convertBSTtoLinkedList (bst.c:80)
==3076==    by 0x108ADD: convertBSTtoLinkedList (bst.c:85)
==3076==    by 0x108ADD: convertBSTtoLinkedList (bst.c:85)
==3076==    by 0x108ADD: convertBSTtoLinkedList (bst.c:85)
==3076==    by 0x108AC8: convertBSTtoLinkedList (bst.c:80)
==3076==    by 0x108AC8: convertBSTtoLinkedList (bst.c:80)
==3076==    by 0x108754: main (main_bst.c:28)
</code>```

答:
malloc gives you a pointer to uninitialized memory. So unless you set each member of your ListNode struct, trying to access that member later is a bad idea.

When your convertBSTtoLinkedList function processes any node of the BST which does not have a right child, it fails to set next on the created list node.  So the next time after that a higher level in the recursion attempts to find the end of the returned sublist, it walks to the end of the sublist, checks that uninitialized next pointer, and valgrind complains.

Body:
My code below successfully converts a Binary search tree to a linked list however valgrind has been giving me "Conditional jump or move depends on uninitialised value(s)" errors. Yet after looking at my code, I don't see where I have that?

ListNodePtr convertBSTtoLinkedList(TreeNodePtr root)
{
    ListNodePtr list,head;
    list = malloc(sizeof(struct ListNode));
    list->key = root->key;
    if (root->right != NULL)
    {
        list->next = convertBSTtoLinkedList(root->right);    //line 80
    }
    if (root->left != NULL)
    {
    ListNodePtr tail;
    head = convertBSTtoLinkedList(root->left);   //line 85
    tail = head;
    while (tail->next != NULL) {        //Line 87
        tail = tail->next;
    }
    tail->next = list;
    return head;
    }
    return list;
}

This is my valgrind error, it repeats itself a few times.

==3076== Conditional jump or move depends on uninitialised value(s)
==3076==    at 0x108AF2: convertBSTtoLinkedList (bst.c:87)
==3076==    by 0x108AC8: convertBSTtoLinkedList (bst.c:80)
==3076==    by 0x108ADD: convertBSTtoLinkedList (bst.c:85)
==3076==    by 0x108ADD: convertBSTtoLinkedList (bst.c:85)
==3076==    by 0x108ADD: convertBSTtoLinkedList (bst.c:85)
==3076==    by 0x108AC8: convertBSTtoLinkedList (bst.c:80)
==3076==    by 0x108AC8: convertBSTtoLinkedList (bst.c:80)
==3076==    by 0x108754: main (main_bst.c:28)


问:
How to unpivot columns and GROUP BY based on values in SQL Server?
I want to calculate distinct PID and VID counts per year.

Condition:

```<code>1. Separate count for column A or B or C or D  having value 1  ( A_to_D)
2. Separate count for column E  having value 1  (E)
3. Separate count for column F  having value 1   (F)
4. Separate count for ALL A to F column are NULL  (ALL_NULL)
</code>```

In the output I want a separate new column Alpha with the following values:

```<code>A_to_D, E, F and ALL_Null
</code>```

Current output of table:

```<code>PID VID Flag    Date        A       B       C       D       E       F
1   A1  0       10/17/2013  NULL    NULL    NULL    NULL    NULL    NULL
2   A2  1       5/27/2014   1       NULL    NULL    1       NULL    NULL
3   A3  NULL    2/23/2015   NULL    NULL    NULL    NULL    1       NULL
4   A4  NULL    12/6/2013   NULL    0       NULL    NULL    NULL    NULL
5   A5  NULL    7/14/2016   NULL    NULL    NULL    NULL    NULL    1
6   A6  NULL    4/29/2015   NULL    1       1       NULL    NULL    NULL
7   A7  1       9/30/2016   1       NULL    NULL    NULL    NULL    NULL
8   A8  NULL    6/28/2016   NULL    NULL    NULL    NULL    NULL    NULL
9   A9  1       11/20/2013  NULL    NULL    NULL    NULL    NULL    NULL
10  A10 2       10/8/2015   NULL    1       NULL    NULL    NULL    NULL
</code>```

Here:

```<code>select datepart(Year,date) ,Count(distinct PID) ,Count( distinct VID)
from table
where A is not null or B is Not NUll or C is not null
   or D is not null or E is not Null or F is not null
group by datepart(Year,date)
</code>```

Expected output:

```<code>Year        Count_PID       Count_VID       Alpha
2013                                        A_to_D
2013                                        E
2013                                        F
2013            2               2           ALL_NULL
2014            1               1           A_to_D
2014                                        E
2014                                        F
2014                                        ALL_NULL
2015            2               2           A_to_D
2015            1               1           E
2015                                        F
2015                                        ALL_NULL
2016            2               2           A_to_D
2016                                        E
2016            1                           F
2016            1                           ALL_NULL
</code>```

答:
I am using your sample data.Your output is wrong in few case.
Try my script using various sample data.

```<code>create table #tbl(PID int,VID varchar(30),Flag int,Dates Date
,A int,B int,C int,D int,E int,F int,Years as year(dates))

insert into #tbl VALUES
(1   ,'A1',  0       ,'10/17/2013',  NULL  ,NULL ,NULL, NULL,NULL,NULL)
,(2   ,'A2',  1       ,'5/27/2014',  1     ,NULL ,NULL, 1   ,NULL,NULL)
,(3   ,'A3',  NULL    ,'2/23/2015',  NULL  ,NULL ,NULL, NULL,1   ,NULL)
,(4   ,'A4',  NULL    ,'12/6/2013',  NULL  ,0    ,NULL, NULL,NULL,NULL)
,(5   ,'A5',  NULL    ,'7/14/2016',  NULL  ,NULL ,NULL, NULL,NULL,1   )
,(6   ,'A6',  NULL    ,'4/29/2015',  NULL  ,1    ,1   , NULL,NULL,NULL)
,(7   ,'A7',  1       ,'9/30/2016',  1     ,NULL ,NULL, NULL,NULL,NULL)
,(8   ,'A8',  NULL    ,'6/28/2016',  NULL  ,NULL ,NULL, NULL,NULL,NULL)
,(9   ,'A9',  1       ,'11/20/2013',  NULL  ,NULL ,NULL, NULL,NULL,NULL)
,(10  ,'A10', 2       ,'10/8/2015',  NULL  ,1    ,NULL, NULL,NULL,NULL)

-- This is hard coded
create table #temp (Alpha varchar(50))
insert into #temp VALUES ('A_to_D'),('E'),('F'),('ALL_NULL')

-- you can decide the value of @StartYear and @Maxyear according to some logic
-- don't consider it hard coded .It is no big deal
declare @StartYear int=2013
declare @Maxyear int =4

create table #year (Years int)
insert into #year
select TOP(@Maxyear) @StartYear+(ROW_NUMBER()OVER(ORDER BY number)-1)
from master..spt_values
--select * from #year

;

WITH CTE
AS (
    SELECT *
    FROM #year
        ,#temp
    )
    ,CTE1
AS (
    SELECT  t.Years
        ,sum(CASE
                WHEN A = 1
                    OR B = 1
                    OR c = 1
                    OR d = 1
                    THEN 1
                END) PA_to_D
        ,sum(CASE
                WHEN (flag IS NOT NULL)
                    AND (
                        A = 1
                        OR B = 1
                        OR c = 1
                        OR d = 1
                        )
                    THEN 1
                END) VA_to_D
        ,sum(CASE
                WHEN E = 1
                    THEN 1
                END) P_E
        ,sum(CASE
                WHEN (flag IS NOT NULL)
                    AND (E = 1)
                    THEN 1
                END) V_E
        ,sum(CASE
                WHEN F = 1
                    THEN 1
                END) P_F
        ,sum(CASE
                WHEN (flag IS NOT NULL)
                    AND (F = 1)
                    THEN 1
                END) V_F
        ,sum(CASE
                WHEN COALESCE([A], [B], [C], [D], [E], [F]) IS NULL
                    THEN 1
                END) P_ALL_NULL
        ,sum(CASE
                WHEN (flag IS NOT NULL)
                    AND COALESCE([A], [B], [C], [D], [E], [F]) IS NULL
                    THEN 1
                END) V_ALL_NULL
    FROM #tbl t
    where exists(select years from #year Y where Y.years=t.years)
    GROUP BY t.Years
    )

SELECT c.years
    ,c.alpha
    ,ca.Count_PID
    ,ca.Count_VID
FROM cte c
CROSS APPLY (
    SELECT CASE
            WHEN c.years = t.years
                AND alpha = 'A_to_D'
                THEN PA_to_D
            WHEN c.years = t.years
                AND alpha = 'E'
                THEN P_E
            WHEN c.years = t.years
                AND alpha = 'F'
                THEN P_F
            WHEN c.years = t.years
                AND alpha = 'ALL_NULL'
                THEN P_ALL_NULL
            ELSE NULL
            END Count_PID
        ,CASE
            WHEN c.years = t.years
                AND alpha = 'A_to_D'
                THEN VA_to_D
            WHEN c.years = t.years
                AND alpha = 'E'
                THEN V_E
            WHEN c.years = t.years
                AND alpha = 'F'
                THEN V_F
            WHEN c.years = t.years
                AND alpha = 'ALL_NULL'
                THEN V_ALL_NULL
            ELSE NULL
            END Count_VID
    FROM CTE1 t
    WHERE years = c.years
    ) ca
ORDER BY c.Years

drop table #tbl
drop table #year
drop table #temp
</code>```

Explanation

: I have use Years as year(dates) as computed column (or may be permanent column) to take advantage of index in future.It is just and idea.

If you use Year(Dates) instead of Years then also output will be OK

Body:
I want to calculate distinct PID and VID counts per year.

Condition:

1. Separate count for column A or B or C or D  having value 1  ( A_to_D)
2. Separate count for column E  having value 1  (E)
3. Separate count for column F  having value 1   (F)
4. Separate count for ALL A to F column are NULL  (ALL_NULL)

In the output I want a separate new column Alpha with the following values:

A_to_D, E, F and ALL_Null

Current output of table:

PID VID Flag    Date        A       B       C       D       E       F
1   A1  0       10/17/2013  NULL    NULL    NULL    NULL    NULL    NULL
2   A2  1       5/27/2014   1       NULL    NULL    1       NULL    NULL
3   A3  NULL    2/23/2015   NULL    NULL    NULL    NULL    1       NULL
4   A4  NULL    12/6/2013   NULL    0       NULL    NULL    NULL    NULL
5   A5  NULL    7/14/2016   NULL    NULL    NULL    NULL    NULL    1
6   A6  NULL    4/29/2015   NULL    1       1       NULL    NULL    NULL
7   A7  1       9/30/2016   1       NULL    NULL    NULL    NULL    NULL
8   A8  NULL    6/28/2016   NULL    NULL    NULL    NULL    NULL    NULL
9   A9  1       11/20/2013  NULL    NULL    NULL    NULL    NULL    NULL
10  A10 2       10/8/2015   NULL    1       NULL    NULL    NULL    NULL

Here:

select datepart(Year,date) ,Count(distinct PID) ,Count( distinct VID)
from table
where A is not null or B is Not NUll or C is not null
   or D is not null or E is not Null or F is not null
group by datepart(Year,date)

Expected output:

Year        Count_PID       Count_VID       Alpha
2013                                        A_to_D
2013                                        E
2013                                        F
2013            2               2           ALL_NULL
2014            1               1           A_to_D
2014                                        E
2014                                        F
2014                                        ALL_NULL
2015            2               2           A_to_D
2015            1               1           E
2015                                        F
2015                                        ALL_NULL
2016            2               2           A_to_D
2016                                        E
2016            1                           F
2016            1                           ALL_NULL

Body:
I am using your sample data.Your output is wrong in few case.
Try my script using various sample data.

create table #tbl(PID int,VID varchar(30),Flag int,Dates Date
,A int,B int,C int,D int,E int,F int,Years as year(dates))

insert into #tbl VALUES
(1   ,'A1',  0       ,'10/17/2013',  NULL  ,NULL ,NULL, NULL,NULL,NULL)
,(2   ,'A2',  1       ,'5/27/2014',  1     ,NULL ,NULL, 1   ,NULL,NULL)
,(3   ,'A3',  NULL    ,'2/23/2015',  NULL  ,NULL ,NULL, NULL,1   ,NULL)
,(4   ,'A4',  NULL    ,'12/6/2013',  NULL  ,0    ,NULL, NULL,NULL,NULL)
,(5   ,'A5',  NULL    ,'7/14/2016',  NULL  ,NULL ,NULL, NULL,NULL,1   )
,(6   ,'A6',  NULL    ,'4/29/2015',  NULL  ,1    ,1   , NULL,NULL,NULL)
,(7   ,'A7',  1       ,'9/30/2016',  1     ,NULL ,NULL, NULL,NULL,NULL)
,(8   ,'A8',  NULL    ,'6/28/2016',  NULL  ,NULL ,NULL, NULL,NULL,NULL)
,(9   ,'A9',  1       ,'11/20/2013',  NULL  ,NULL ,NULL, NULL,NULL,NULL)
,(10  ,'A10', 2       ,'10/8/2015',  NULL  ,1    ,NULL, NULL,NULL,NULL)

-- This is hard coded
create table #temp (Alpha varchar(50))
insert into #temp VALUES ('A_to_D'),('E'),('F'),('ALL_NULL')

-- you can decide the value of @StartYear and @Maxyear according to some logic
-- don't consider it hard coded .It is no big deal
declare @StartYear int=2013
declare @Maxyear int =4

create table #year (Years int)
insert into #year
select TOP(@Maxyear) @StartYear+(ROW_NUMBER()OVER(ORDER BY number)-1)
from master..spt_values
--select * from #year

;

WITH CTE
AS (
    SELECT *
    FROM #year
        ,#temp
    )
    ,CTE1
AS (
    SELECT  t.Years
        ,sum(CASE
                WHEN A = 1
                    OR B = 1
                    OR c = 1
                    OR d = 1
                    THEN 1
                END) PA_to_D
        ,sum(CASE
                WHEN (flag IS NOT NULL)
                    AND (
                        A = 1
                        OR B = 1
                        OR c = 1
                        OR d = 1
                        )
                    THEN 1
                END) VA_to_D
        ,sum(CASE
                WHEN E = 1
                    THEN 1
                END) P_E
        ,sum(CASE
                WHEN (flag IS NOT NULL)
                    AND (E = 1)
                    THEN 1
                END) V_E
        ,sum(CASE
                WHEN F = 1
                    THEN 1
                END) P_F
        ,sum(CASE
                WHEN (flag IS NOT NULL)
                    AND (F = 1)
                    THEN 1
                END) V_F
        ,sum(CASE
                WHEN COALESCE([A], [B], [C], [D], [E], [F]) IS NULL
                    THEN 1
                END) P_ALL_NULL
        ,sum(CASE
                WHEN (flag IS NOT NULL)
                    AND COALESCE([A], [B], [C], [D], [E], [F]) IS NULL
                    THEN 1
                END) V_ALL_NULL
    FROM #tbl t
    where exists(select years from #year Y where Y.years=t.years)
    GROUP BY t.Years
    )

SELECT c.years
    ,c.alpha
    ,ca.Count_PID
    ,ca.Count_VID
FROM cte c
CROSS APPLY (
    SELECT CASE
            WHEN c.years = t.years
                AND alpha = 'A_to_D'
                THEN PA_to_D
            WHEN c.years = t.years
                AND alpha = 'E'
                THEN P_E
            WHEN c.years = t.years
                AND alpha = 'F'
                THEN P_F
            WHEN c.years = t.years
                AND alpha = 'ALL_NULL'
                THEN P_ALL_NULL
            ELSE NULL
            END Count_PID
        ,CASE
            WHEN c.years = t.years
                AND alpha = 'A_to_D'
                THEN VA_to_D
            WHEN c.years = t.years
                AND alpha = 'E'
                THEN V_E
            WHEN c.years = t.years
                AND alpha = 'F'
                THEN V_F
            WHEN c.years = t.years
                AND alpha = 'ALL_NULL'
                THEN V_ALL_NULL
            ELSE NULL
            END Count_VID
    FROM CTE1 t
    WHERE years = c.years
    ) ca
ORDER BY c.Years

drop table #tbl
drop table #year
drop table #temp

Explanation

: I have use Years as year(dates) as computed column (or may be permanent column) to take advantage of index in future.It is just and idea.

If you use Year(Dates) instead of Years then also output will be OK