问:
Should I use $_GET to dynamically load html?
I am working on a social networking site using PHP, MySQL(PDO), JQuery, and HTML(CSS). I'm working on the profile page right now and I want to determine if the user is on their own page or another's to determine what inputs they'll have. I would like to keep a framework for the profile page and load the respective options rather than having 2 different pages (my profile vs other profile).

I'm learning JQuery and PHP as I go, so right now I am thinking, in JQuery, I can get the $_GET (?username= ) and compare it to the user id of who's logged in, then load the components I need based on that.

Or I determine the user in PHP then run a certain scrip to load the components.

Would on of these ways work, or is there a different/better way to do this?

答:
I don't think you can use $_GET in JavaScript.

Instead, there is a URLSearchParams

```<code>const url = new URL('http://domain/path?username=someone');
const username = new URLSearchParams(url.search).get('username)'; // someone
</code>```

Body:
I don't think you can use $_GET in JavaScript.

Instead, there is a URLSearchParams

const url = new URL('http://domain/path?username=someone');
const username = new URLSearchParams(url.search).get('username)'; // someone


来源: stackexchange

问:
Programatically add a page to a known parent
I would like to create programatically a sub page for a known parent. How can I do that? The page creation will takes place in a signal receiver: the page is created on publication of another page.</p>

答:
Add a revision as well.

```<code>from wagtail.wagtailcore.models import Page
from models import MyPage

home = Page.objects.get(id=3) # or better Page query
my_page = MyPage(title="test", body="<h1>the body</h1>")
home.add_child(instance=my_page)

# later when a cms user updates the page manually
# there will be no first revision to compare against unless
# you add a page revision also programmatically.

my_page.save_revision().publish()
</code>```

You can see how wagtail does this in the wagtailadmin pages create view (line 156).
https://github.com/wagtail/wagtail/blob/stable/1.13.x/wagtail/wagtailadmin/views/pages.py

Update 2018-09-18:
I built a 700 page site including 200 generated pages. I never added an initial Revision anywhere and no editors complained. After the first manual edit there will be a Revision. Go ahead and add an initial Revision if you think it is needed for traceability.

ContentLicense: CC BY-SA 3.0

Body:
Add a revision as well.

from wagtail.wagtailcore.models import Page
from models import MyPage

home = Page.objects.get(id=3) # or better Page query
my_page = MyPage(title="test", body="<h1>the body</h1>")
home.add_child(instance=my_page)

# later when a cms user updates the page manually
# there will be no first revision to compare against unless
# you add a page revision also programmatically.

my_page.save_revision().publish()

You can see how wagtail does this in the wagtailadmin pages create view (line 156).
https://github.com/wagtail/wagtail/blob/stable/1.13.x/wagtail/wagtailadmin/views/pages.py

Update 2018-09-18:
I built a 700 page site including 200 generated pages. I never added an initial Revision anywhere and no editors complained. After the first manual edit there will be a Revision. Go ahead and add an initial Revision if you think it is needed for traceability.

ContentLicense: CC BY-SA 4.0


问:
keras ignoring values in $HOME/.keras/keras.json file
I know the default backend for Keras has switched from Theano to TensorFlow, but with the dev version of Theano I can train on the GPU with OpenCL (I have an AMD card).

However, when I import Keras, it only uses the TensorFlow backend even after I changed the values in the Keras configuration file:

```<code>~ $ cat $HOME/.keras/keras.json
{"epsilon": 1e-07, "floatx": "float32", "backend": "theano"}

~ $ python -c 'import keras'
Using TensorFlow backend.

~ $ KERAS_BACKEND=theano python -c 'import keras'
Using Theano backend.
Mapped name None to device opencl0:2: AMD Radeon R9 M370X Compute Engine
</code>```

In addition, I know that Keras is reading the configuration file after import because if I fill some non-valid value for "backend" I get an error:

```<code>~ $ cat $HOME/.keras/keras.json
{"epsilon": 1e-07, "floatx": "float32", "backend": "foobar"}

~ $ python -c 'import keras'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/antalek/anaconda/envs/ENVPy3/lib/python3.5/site-packages/keras/__init__.py", line 3, in <module>
    from . import activations
  File "/Users/antalek/anaconda/envs/ENVPy3/lib/python3.5/site-packages/keras/activations.py", line 3, in <module>
    from . import backend as K
  File "/Users/antalek/anaconda/envs/ENVPy3/lib/python3.5/site-packages/keras/backend/__init__.py", line 34, in <module>
    assert _backend in {'theano', 'tensorflow'}
AssertionError
</code>```

System details:

Mac OSX 10.11.6

Anaconda Python v 3.5

Keras v 2.0.2

I would like to have Keras use Theano as the default backend. Anyone know how to set it as such?

EDIT:

To answer @Marcin Możejko 's question:

```<code>~ $ which python
/Users/<my name>/anaconda/envs/ENVPy3/bin/python
</code>```

Which is the conda virtual environment that Keras is installed in as well.

答:
Same issue here, system setup:

Ubuntu 16.04

Anaconda + Python 3.6

Keras 2.0.2

The only way to change backend is to use KERAS_BACKEND environment variable. Json field is ignored.

EDIT:
The issue is Anaconda, open anaconda3/envs/ENV-NAME/etc/conda/activate.d/keras_activate.sh

```<code>#!/bin/bash
if [ "$(uname)" == "Darwin" ]
then
    # for Mac OSX
    export KERAS_BACKEND=tensorflow
elif [ "$(uname)" == "Linux" ]
then
    # for Linux
    export KERAS_BACKEND=theano
fi
</code>```

You'll see that  tensorflow is forced for MAC, and Theano for Linux.

I have no idea who creates this file, keras or anaconda, and the reasoning behind this forcing. I'm just ignoring it and doing my own way:)

Body:
I know the default backend for Keras has switched from Theano to TensorFlow, but with the dev version of Theano I can train on the GPU with OpenCL (I have an AMD card).

However, when I import Keras, it only uses the TensorFlow backend even after I changed the values in the Keras configuration file:

~ $ cat $HOME/.keras/keras.json
{"epsilon": 1e-07, "floatx": "float32", "backend": "theano"}

~ $ python -c 'import keras'
Using TensorFlow backend.

~ $ KERAS_BACKEND=theano python -c 'import keras'
Using Theano backend.
Mapped name None to device opencl0:2: AMD Radeon R9 M370X Compute Engine

In addition, I know that Keras is reading the configuration file after import because if I fill some non-valid value for "backend" I get an error:

~ $ cat $HOME/.keras/keras.json
{"epsilon": 1e-07, "floatx": "float32", "backend": "foobar"}

~ $ python -c 'import keras'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/antalek/anaconda/envs/ENVPy3/lib/python3.5/site-packages/keras/__init__.py", line 3, in <module>
    from . import activations
  File "/Users/antalek/anaconda/envs/ENVPy3/lib/python3.5/site-packages/keras/activations.py", line 3, in <module>
    from . import backend as K
  File "/Users/antalek/anaconda/envs/ENVPy3/lib/python3.5/site-packages/keras/backend/__init__.py", line 34, in <module>
    assert _backend in {'theano', 'tensorflow'}
AssertionError

System details:

Mac OSX 10.11.6

Anaconda Python v 3.5

Keras v 2.0.2

I would like to have Keras use Theano as the default backend. Anyone know how to set it as such?

EDIT:

To answer @Marcin Możejko 's question:

~ $ which python
/Users/<my name>/anaconda/envs/ENVPy3/bin/python

Which is the conda virtual environment that Keras is installed in as well.

Body:
Same issue here, system setup:

Ubuntu 16.04

Anaconda + Python 3.6

Keras 2.0.2

The only way to change backend is to use KERAS_BACKEND environment variable. Json field is ignored.

EDIT:
The issue is Anaconda, open anaconda3/envs/ENV-NAME/etc/conda/activate.d/keras_activate.sh

#!/bin/bash
if [ "$(uname)" == "Darwin" ]
then
    # for Mac OSX
    export KERAS_BACKEND=tensorflow
elif [ "$(uname)" == "Linux" ]
then
    # for Linux
    export KERAS_BACKEND=theano
fi

You'll see that  tensorflow is forced for MAC, and Theano for Linux.

I have no idea who creates this file, keras or anaconda, and the reasoning behind this forcing. I'm just ignoring it and doing my own way:)


问:
Where is the chink in Google Chrome's armor?
While browsing with Chrome, I noticed that it responds extremely fast (in comparison with IE and Firefox on my laptop) in terms of rendering pages, including JavaScript heavy sites like gmail.

This is what googlebook on Chrome has to say

tabs are hosted in process rather than thread.

compile javascript using V8 engine as opposed to interpreting.

Introduce new virtual machine to support javascript heavy apps

introduce "hidden class transitions" and apply dynamic optimization to speed up things.

Replace inefficient "Conservative garbage colllection" scheme with more precise garbage  collection scheme.

Introduce their own task scheduler and memory manager to manage the browser environment.

All this sounds so familiar, and Microsoft has been doing such things for long time.. Windows os, C++, C# etc compilers, CLR, and so on.

So why isn't Microsoft or any other browser vendor taking Chrome's approach? Is there a flaw in Chrome's approach? If not, is the rest of browser vendor community caught unaware  with Google's approach?

答:
@pix0r but they added a little thing in the bottom right corner so you can expand the text box any direction you want, which I love because I use a wide display and prefer to type in a wider screen.

Thats actually a WebKit feature, Chrome just inherited it.

OwnerDisplayName: kudlur

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Greg Hurlman

OwnerDisplayName: Jonathan Holland


问:
Spring and Hibernate, Lazy initiation problem
Hey I am developing an desktop application using Spring and Hibernate, and I have a problem with lazy initiation. I looked in the web and every solution is related to the open session in view pattern, but I can't use this pattern. I've also tried to get the sessionfactory from the HibernateTemplate, but it returns to me a disconnected session.

Does anyone know other solution?

答:
One option is to call Hibernate.initialize() on the entities or collections to force initialize them. You'd want to do this before you return the data back to your view. I would consider this carefully, since it's going to generate a lot of SQL statements back to the database.

You may want to look into using "fetch" in your HQL queries or configuration the fetch mode to "eager" in your mappings (I believe it's FetchMode.EAGER in JPA or lazy="false" in hbm.xml).

@Jose: Don't manage the Session in your own ThreadLocal.  Use SessionFactory.getCurrentSession() and configure Hibernate to use the "thread" SessionContext.

OwnerDisplayName: Thiago Diniz

LastEditorDisplayName: sblundy


问:
How can i convert linux "date +%s" output to a more readable format in bash script
Here is the script:

```<code>
#!/bin/bash

i="0"
startTime=`date -u +%s`
startTime=$[$startTime+$1+5]
echo ""
echo "##################"
echo "LAUNCHING REQUESTS"
echo "  COUNT:  $1 "
echo "  DELAY:  1 "
echo "  EXECUTION:  $startTime "
echo "##################"
echo ""

while [ $1 -gt "$i" ]
do
  i=$[$i+1]
  php avtestTimed.php $1 $2 $startTime &
  echo "QUEUEING REQUEST $i"
  sleep 1
done

</code>
```

so i want to convert $startTime into a UTC format

答:
You can use -d to pass $startTime back into date for processing, just prefix it with @ so it is recognized as seconds since the epoch.

```<code>$ date -d @$startTime
</code>```

Once you have that down you can change the output format. I would suggest looking at the man page or the info documentation of date for that. For UTC output you would use

```<code>$ date -d @$startTime -u
</code>```

Body:
Here is the script:

#!/bin/bash

i="0"
startTime=`date -u +%s`
startTime=$[$startTime+$1+5]
echo ""
echo "##################"
echo "LAUNCHING REQUESTS"
echo "  COUNT:  $1 "
echo "  DELAY:  1 "
echo "  EXECUTION:  $startTime "
echo "##################"
echo ""

while [ $1 -gt "$i" ]
do
  i=$[$i+1]
  php avtestTimed.php $1 $2 $startTime &
  echo "QUEUEING REQUEST $i"
  sleep 1
done

so i want to convert $startTime into a UTC format

Body:
You can use -d to pass $startTime back into date for processing, just prefix it with @ so it is recognized as seconds since the epoch.

$ date -d @$startTime

Once you have that down you can change the output format. I would suggest looking at the man page or the info documentation of date for that. For UTC output you would use

$ date -d @$startTime -u


问:
VBA Call Function not working
```<code>Sub CommandButton1_Click()

Call Worksheets("Chart").Range("B1").Value

End Sub
</code>```

Error: Object doesn't support this property or method (438)

What is wrong? I have also tried using a variable i.e. x to no avail.

Thanks

答:
why are you using call?
get the value into a variable and continue from there
dim a as variant
a = workbook. worksheet("aaa")..... </p>

Title: VBA Call Function not working

Body:
Sub CommandButton1_Click()

Call Worksheets("Chart").Range("B1").Value

End Sub

Error: Object doesn't support this property or method (438)

What is wrong? I have also tried using a variable i.e. x to no avail.

Thanks


问:
How to export an Excel sheet range to a picture, from within R
We are trying to automate the creation of some picture files within an R Script.

We have the Excel files looking the way that we want them to, but now need to make a JPG or PNG picture-copy of those excel tables for easier web posting.

We've been using the library(xlsx) package for most of our interactions between R and Excel, and it looks like we should be able to send specific java commands through something like ?.jmethods but it's unclear how we would pass as many lines as we need to.

In an R session, here's a minimal reproducible example...

Here's an example Excel file with a range to print

```<code>library(xlsx)
file <- system.file("tests", "test_import.xlsx", package = "xlsx")
file
</code>```

And here's the Excel macro that exports the Excel range to a picture file

```<code>Sub Tester()

    Worksheets("deletedFields").Range("A8:J36").CopyPicture xlScreen, xlBitmap

    Application.DisplayAlerts = False
    Set oCht = Charts.Add
    With oCht
        .Paste
        .Export Filename:="C:\temp\SavedRange.jpg", Filtername:="JPG"
        .Delete
    End With

End Sub
</code>```

Any help automating this would be much appreciated!

答:
Hmm, not sure about posting, maybe it got redundant through Ian´s post. Its a bit more generic, but I can also remove it.

```<code>library(xlsx)

OutputPicFileName <- "Chart.jpg"
ScriptFileName <- "Chart.vbs"
xclFileName <- "test_import.xlsx"
xclRng <- "A8:J36"
file <- system.file("tests", xclFileName, package = "xlsx")
fileDirec <- unlist(strsplit(file, xclFileName))

CreateChart <- function(fileDirec, OutputPicFileName, ScriptFileName, xclRng){
  setwd(fileDirec)
  filePath <- file(paste0(fileDirec, ScriptFileName))
  writeLines(
    c(
      "Dim App, WBook, Sht, Rng, FileName, ChartObj, Chart",
       paste0("FileName = \"", gsub("/", "\\\\", fileDirec), xclFileName ,"\""),
       "Set App = CreateObject(\"Excel.Application\")",
       "Set WBook = App.WorkBooks.Open(FileName)",
       "Set Sht = App.Worksheets(1)",
       paste0("Set Rng = Sht.Range(\"", xclRng,"\")"),
       "Rng.CopyPicture",
       "Set ChartObj = App.Charts",
       "Set Chart = ChartObj.Add() ",
       "Chart.paste",
       paste0("Chart.Export \"", gsub("/", "\\\\", fileDirec) , OutputPicFileName ,"\", \"JPG\"")
    ),
    filePath
  )
  close(filePath)
  shell.exec(ScriptFileName)
}

CreateChart(fileDirec, OutputPicFileName, ScriptFileName, xclRng)

# Result in: fileDirec
</code>```

Body:
We are trying to automate the creation of some picture files within an R Script.

We have the Excel files looking the way that we want them to, but now need to make a JPG or PNG picture-copy of those excel tables for easier web posting.

We've been using the library(xlsx) package for most of our interactions between R and Excel, and it looks like we should be able to send specific java commands through something like ?.jmethods but it's unclear how we would pass as many lines as we need to.

In an R session, here's a minimal reproducible example...

Here's an example Excel file with a range to print

library(xlsx)
file <- system.file("tests", "test_import.xlsx", package = "xlsx")
file

And here's the Excel macro that exports the Excel range to a picture file

Sub Tester()

    Worksheets("deletedFields").Range("A8:J36").CopyPicture xlScreen, xlBitmap

    Application.DisplayAlerts = False
    Set oCht = Charts.Add
    With oCht
        .Paste
        .Export Filename:="C:\temp\SavedRange.jpg", Filtername:="JPG"
        .Delete
    End With

End Sub

Any help automating this would be much appreciated!

Body:
Hmm, not sure about posting, maybe it got redundant through Ian´s post. Its a bit more generic, but I can also remove it.

library(xlsx)

OutputPicFileName <- "Chart.jpg"
ScriptFileName <- "Chart.vbs"
xclFileName <- "test_import.xlsx"
xclRng <- "A8:J36"
file <- system.file("tests", xclFileName, package = "xlsx")
fileDirec <- unlist(strsplit(file, xclFileName))

CreateChart <- function(fileDirec, OutputPicFileName, ScriptFileName, xclRng){
  setwd(fileDirec)
  filePath <- file(paste0(fileDirec, ScriptFileName))
  writeLines(
    c(
      "Dim App, WBook, Sht, Rng, FileName, ChartObj, Chart",
       paste0("FileName = \"", gsub("/", "\\\\", fileDirec), xclFileName ,"\""),
       "Set App = CreateObject(\"Excel.Application\")",
       "Set WBook = App.WorkBooks.Open(FileName)",
       "Set Sht = App.Worksheets(1)",
       paste0("Set Rng = Sht.Range(\"", xclRng,"\")"),
       "Rng.CopyPicture",
       "Set ChartObj = App.Charts",
       "Set Chart = ChartObj.Add() ",
       "Chart.paste",
       paste0("Chart.Export \"", gsub("/", "\\\\", fileDirec) , OutputPicFileName ,"\", \"JPG\"")
    ),
    filePath
  )
  close(filePath)
  shell.exec(ScriptFileName)
}

CreateChart(fileDirec, OutputPicFileName, ScriptFileName, xclRng)

# Result in: fileDirec


问:
SQL query summary issue
I'm new to SQL and trying to create a total summary of a working SQL query. It's listing the total results from one month of data.
Now I need the total values of the outcome of the query.
So I created a 'query in a query' piece of SQL, but it ain't working because my lack of SQL knowledge. I guess it's an easy fix for you pro's :-)

The working SQL query with the daily outcome of one month:

```<code>SELECT
          DATE_FORMAT(date, '%d/%m/%y') AS Datum,
          COUNT(*) AS Berichten,
          SUM(CASE WHEN virusinfected>0 THEN 1 ELSE 0 END) AS Virus,
          SUM(CASE WHEN (virusinfected=0 OR virusinfected IS NULL) AND isspam>0 THEN 1 ELSE 0 END) AS Ongewenst,
          SUM(CASE WHEN (virusinfected=0 OR virusinfected IS NULL) AND (isspam=1) AND isrblspam>0 THEN 1 ELSE 0 END) AS RBL,
          SUM(size) AS Grootte
         FROM
          maillog
         WHERE
          1=1
        AND (1=1)
        AND
         date < '2017-04-01'
        AND
         date >= '2017-03-01'
        AND
         to_domain = 'domain1.nl'
        OR
        date < '2017-04-01'
        AND
         date >= '2017-03-01'
        AND
         to_domain = 'domain2.nl'

         GROUP BY
          Datum
         ORDER BY
          date
</code>```

The incorrect query trying to create the monthly totals:

```<code>SELECT  Datum,
    SUM(Berichten) AS Berichten,
    SUM(Virus) AS Virus,
    SUM(Ongewenst) AS Ongewenst,
    SUM(RBL) AS RBL,
    SUM(Grootte) AS Grootte,
    FROM    (   SELECT
                  DATE_FORMAT(date, '%d/%m/%y') AS Datum,
                  COUNT(*) AS Berichten,
                  SUM(CASE WHEN virusinfected>0 THEN 1 ELSE 0 END) AS Virus,
                  SUM(CASE WHEN (virusinfected=0 OR virusinfected IS NULL) AND isspam>0 THEN 1 ELSE 0 END) AS Ongewenst,
                  SUM(CASE WHEN (virusinfected=0 OR virusinfected IS NULL) AND (isspam=1) AND isrblspam>0 THEN 1 ELSE 0 END) AS RBL,
                  SUM(size) AS Grootte
                 FROM
                  maillog
                 WHERE
                  1=1
                AND (1=1)
                AND
                 date < '2017-04-01'
                AND
                 date >= '2017-03-01'
                AND
                 to_domain = 'domain1.nl'
                OR
                date < '2017-04-01'
                AND
                 date >= '2017-03-01'
                AND
                 to_domain = 'domain2.nl'

                 GROUP BY
                  Datum
                 ORDER BY
                  date
            ) t
    GROUP BY Datum;
</code>```

Thanks in advance.

答:
What you want can be done with just a little addition to your first SQL statement: add with rollup after the group by clause:

```<code>GROUP BY Datum WITH ROLLUP
</code>```

It will run more efficiently than the version with sub-query, although it could work that way, but you should then remove the outer group by clause and not select Datum there, since you don't want the totals per date any more, but overall.

Still, you will lose the details and only get the overall totals then. You would have to use a union with your original query to get both levels of totals. You can imagine that the with rollup modifier will do the job more efficiently.

Title: SQL query summary issue

Body:
I'm new to SQL and trying to create a total summary of a working SQL query. It's listing the total results from one month of data.
Now I need the total values of the outcome of the query.
So I created a 'query in a query' piece of SQL, but it ain't working because my lack of SQL knowledge. I guess it's an easy fix for you pro's :-)

The working SQL query with the daily outcome of one month:

SELECT
          DATE_FORMAT(date, '%d/%m/%y') AS Datum,
          COUNT(*) AS Berichten,
          SUM(CASE WHEN virusinfected>0 THEN 1 ELSE 0 END) AS Virus,
          SUM(CASE WHEN (virusinfected=0 OR virusinfected IS NULL) AND isspam>0 THEN 1 ELSE 0 END) AS Ongewenst,
          SUM(CASE WHEN (virusinfected=0 OR virusinfected IS NULL) AND (isspam=1) AND isrblspam>0 THEN 1 ELSE 0 END) AS RBL,
          SUM(size) AS Grootte
         FROM
          maillog
         WHERE
          1=1
        AND (1=1)
        AND
         date < '2017-04-01'
        AND
         date >= '2017-03-01'
        AND
         to_domain = 'domain1.nl'
        OR
        date < '2017-04-01'
        AND
         date >= '2017-03-01'
        AND
         to_domain = 'domain2.nl'

         GROUP BY
          Datum
         ORDER BY
          date

The incorrect query trying to create the monthly totals:

SELECT  Datum,
    SUM(Berichten) AS Berichten,
    SUM(Virus) AS Virus,
    SUM(Ongewenst) AS Ongewenst,
    SUM(RBL) AS RBL,
    SUM(Grootte) AS Grootte,
    FROM    (   SELECT
                  DATE_FORMAT(date, '%d/%m/%y') AS Datum,
                  COUNT(*) AS Berichten,
                  SUM(CASE WHEN virusinfected>0 THEN 1 ELSE 0 END) AS Virus,
                  SUM(CASE WHEN (virusinfected=0 OR virusinfected IS NULL) AND isspam>0 THEN 1 ELSE 0 END) AS Ongewenst,
                  SUM(CASE WHEN (virusinfected=0 OR virusinfected IS NULL) AND (isspam=1) AND isrblspam>0 THEN 1 ELSE 0 END) AS RBL,
                  SUM(size) AS Grootte
                 FROM
                  maillog
                 WHERE
                  1=1
                AND (1=1)
                AND
                 date < '2017-04-01'
                AND
                 date >= '2017-03-01'
                AND
                 to_domain = 'domain1.nl'
                OR
                date < '2017-04-01'
                AND
                 date >= '2017-03-01'
                AND
                 to_domain = 'domain2.nl'

                 GROUP BY
                  Datum
                 ORDER BY
                  date
            ) t
    GROUP BY Datum;

Thanks in advance.

Body:
What you want can be done with just a little addition to your first SQL statement: add with rollup after the group by clause:

GROUP BY Datum WITH ROLLUP

It will run more efficiently than the version with sub-query, although it could work that way, but you should then remove the outer group by clause and not select Datum there, since you don't want the totals per date any more, but overall.

Still, you will lose the details and only get the overall totals then. You would have to use a union with your original query to get both levels of totals. You can imagine that the with rollup modifier will do the job more efficiently.


问:
CSS padding-bottom does not seem to work
I need to put space between the fixed footer and the bottom of the page. I've tried setting a padding for #main-content, but it's not working. Is there a problem here that I failed to see?

CSS

```<code>#main-content {
    position: relative;
    width: 100%;
    padding-left:20px;
    padding-right:20px;
    height: 300px;

    box-sizing:border-box;
    padding-top: 50px;
    padding-bottom: 200px;
}

footer {
    background-color: #00496b;
    width: 100%;
    bottom: 0;
    position: fixed;
}
</code>```

Instead of getting the desired result, the main contents disappear behind the footer, instead. I want the #main-content to go a little further up. Hope I have explained the problem enough.

答:
Footer has bottom zero and keep footer to bottom. When you type one more div between you see that padding-bottom work properly. Try padding-bottom: 500px;  and change to padding-bottom: 20px; that you see changes because #main-content is very height, 300px. I type border and now you can see that padding-bottom works normal:</p>

```<code>    <style>
#main-content {
    position: relative;
    width: 100%;
    padding-left:20px;
    padding-right:20px;
    height: 100px;

    box-sizing:border-box;
    padding-top: 50px;
    padding-bottom: 200px;
    border: 1px solid blue;

}
footer {
            background-color: #00496b;
            width: 100%;
            bottom: 0;
            position: fixed;
        }
</style>
<div id="main-content">
lkdjad d,a dma dm dmad mad ad,ma dma dma dmad a
</div>
<div>
midle midle
</div>
<footer>
footer footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footer
</footer>
</code>```

Body:
I need to put space between the fixed footer and the bottom of the page. I've tried setting a padding for #main-content, but it's not working. Is there a problem here that I failed to see?

CSS

#main-content {
    position: relative;
    width: 100%;
    padding-left:20px;
    padding-right:20px;
    height: 300px;

    box-sizing:border-box;
    padding-top: 50px;
    padding-bottom: 200px;
}

footer {
    background-color: #00496b;
    width: 100%;
    bottom: 0;
    position: fixed;
}

Instead of getting the desired result, the main contents disappear behind the footer, instead. I want the #main-content to go a little further up. Hope I have explained the problem enough.

Body:
Footer has bottom zero and keep footer to bottom. When you type one more div between you see that padding-bottom work properly. Try padding-bottom: 500px;  and change to padding-bottom: 20px; that you see changes because #main-content is very height, 300px. I type border and now you can see that padding-bottom works normal:

    <style>
#main-content {
    position: relative;
    width: 100%;
    padding-left:20px;
    padding-right:20px;
    height: 100px;

    box-sizing:border-box;
    padding-top: 50px;
    padding-bottom: 200px;
    border: 1px solid blue;

}
footer {
            background-color: #00496b;
            width: 100%;
            bottom: 0;
            position: fixed;
        }
</style>
<div id="main-content">
lkdjad d,a dma dm dmad mad ad,ma dma dma dmad a
</div>
<div>
midle midle
</div>
<footer>
footer footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footerfooter footer footer
</footer>


答: in jquery you can use $.get() with datatype html</p>

Title: Should I use $_GET to dynamically load html?

Body:
I am working on a social networking site using PHP, MySQL(PDO), JQuery, and HTML(CSS). I'm working on the profile page right now and I want to determine if the user is on their own page or another's to determine what inputs they'll have. I would like to keep a framework for the profile page and load the respective options rather than having 2 different pages (my profile vs other profile).

I'm learning JQuery and PHP as I go, so right now I am thinking, in JQuery, I can get the $_GET (?username= ) and compare it to the user id of who's logged in, then load the components I need based on that.

Or I determine the user in PHP then run a certain scrip to load the components.

Would on of these ways work, or is there a different/better way to do this?


问:
Qt - How to make QTextBrowser resize to contents (vertical layout)
I have a QTextBrowser object in my dialog which will have HTML written to it. It is in a vertical layout with several other objects. I have the vertical size policy currently set to MinimumExpanding for this QTextbrowser. The problem is if the HTML written to the browser ends up taller than the QTextBrowser's minimum set height, its height stays the same and it instead makes me scroll down through the browser to see all the data, where I would like it instead to show all the data at once. I have tried changing around the size policies for the QTextBrowser and the layout it is in, but nothing I have tried has worked. Is there a way to do this that I am overlooking?</p>

答:
```<code>QTextBrowser  *m_text=new QTextBrowser;
m_text->setFixedHeight(m_text->document()->size().height());
</code>```

wish to help you.

Body:
QTextBrowser  *m_text=new QTextBrowser;
m_text->setFixedHeight(m_text->document()->size().height());

wish to help you.


问:
__stdcall with JNR
I'm using JNR and trying to call to __stdcall function. I've already tried to load library with stdcall() convention:

```<code>mTemplateApi = LibraryLoader.create(FPTemplateAPI.class).stdcall().load("FPTemplateAPI");
</code>```

And tried to annotate method with @StdCall.

```<code>public interface FPTemplateAP
{
    @StdCall
    Pointer CreateTemplateImage(@In ByteBuffer aTemplate,
                                @Out IntByReference aWidth,
                                @Out IntByReference aHeight,
                                @In boolean aColor);

}
</code>```

As result I get the following error when I try to call to method:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: The operation completed successfully.

at jnr.ffi.provider.jffi.AsmRuntime.newUnsatisifiedLinkError(AsmRuntime.java:40)
</code>```

答: For now I created another dll that delegates to __stdcall dll, but uses __cdecl, and it perfectly works for me.

Title: __stdcall with JNR

Body:
I'm using JNR and trying to call to __stdcall function. I've already tried to load library with stdcall() convention:

mTemplateApi = LibraryLoader.create(FPTemplateAPI.class).stdcall().load("FPTemplateAPI");

And tried to annotate method with @StdCall.

public interface FPTemplateAP
{
    @StdCall
    Pointer CreateTemplateImage(@In ByteBuffer aTemplate,
                                @Out IntByReference aWidth,
                                @Out IntByReference aHeight,
                                @In boolean aColor);

}

As result I get the following error when I try to call to method:

Exception in thread "main" java.lang.UnsatisfiedLinkError: The operation completed successfully.

at jnr.ffi.provider.jffi.AsmRuntime.newUnsatisifiedLinkError(AsmRuntime.java:40)


问:
MVVM Pattern tutorial for UWP but it wont bind Commands why?
Ok. I'm following a tutorial to master MVVM Pattern to my app.

I've followed the tutorial quite well, I got to the part of commandings and when I try to apply command to a button it doesnt seem to work at all, my button never disables.
I've seen other MVVM sources and my code seems to be fine besides I found this tutorial on internet it was meant for WPF, but it also apply for UWP Windows 10 Apps.

So I'll paste my classes and Xaml views.

this is my Model:

```<code>using System.ComponentModel;

namespace MVVMDemo.Model
{
public class Student : INotifyPropertyChanged
{
    private string firstName;
    private string lastName;

    public string FirstName
    {
        get
        {
            return firstName;
        }

        set
        {
            if (firstName != value)
            {
                firstName = value;
                RaisePropertyChanged("FirstName");
                RaisePropertyChanged("FullName");
            }
        }
    }

    public string LastName
    {
        get { return lastName; }

        set
        {
            if (lastName != value)
            {
                lastName = value;
                RaisePropertyChanged("LastName");
                RaisePropertyChanged("FullName");
            }
        }
    }

    public string FullName
    {
        get
        {
            return firstName + " " + lastName;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private void RaisePropertyChanged(string property)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }
}
}
</code>```

The model code I believe has no errors on it.
this is my ViewModel:

```<code>using MVVMDemo.Model;
using System.Collections.ObjectModel;

namespace MVVMDemo.ViewModel
{
public class StudentViewModel
{
    /*Let’s add a property of MyICommand type in StudentView Model class.
     * Now we need to construct an instance in the StudentViewModel. We will
     * use the overloaded constructor of MyICommand that takes two parameters.*/
    public MyICommand DeleteCommand { get; set; }

    /*Now add the implementation of OnDelete and CanDelete methods.*/
    public StudentViewModel()
    {
        LoadStudents();
        DeleteCommand = new MyICommand(OnDelete, CanDelete);
    }

    private bool CanDelete()
    {
        //if (SelectedStudent != null)
        //    return true;
        //return false;
        return SelectedStudent != null;
    }

    private void OnDelete()
    {
        Students.Remove(SelectedStudent);
    }

    /*We also need to add a new SelectedStudent so that the user
     * can delete the Selected Item from ListBox.*/
    private Student _selectedStudent;

    public Student SelectedStudent
    {
        get
        {
            return _selectedStudent;
        }
        set
        {
            _selectedStudent = value;
            DeleteCommand.RaiseCanExecuteChanged();
        }
    }
    public ObservableCollection<Student> Students
    {
        get;
        set;
    }

    public void LoadStudents()
    {
        ObservableCollection<Student> students = new ObservableCollection<Student>();

        students.Add(new Student { FirstName = "Mark", LastName = "Allain" });
        students.Add(new Student { FirstName = "Allen", LastName = "Brown" });
        students.Add(new Student { FirstName = "Linda", LastName = "Hamerski" });

        Students = students;
    }
}
}
</code>```

This is my ViewModelLocator:

```<code>using MVVMDemo.ViewModel;

namespace MVVMDemo.VML
{
public class ViewModelLocator
{
private static StudentViewModel studentViewModel = new StudentViewModel();

    public static StudentViewModel StudentViewModel
    {
        get { return studentViewModel; }
    }
}
}
</code>```

and at Last this is my View my UserControl StudentView

```<code><UserControl
    x:Class="MVVMDemo.Views.StudentView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MVVMDemo.Views"
    xmlns:vml="using:MVVMDemo.VML"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    DataContext="{Binding Source={StaticResource mainViewModelLocator}, Path=StudentViewModel}"
    d:DesignHeight="300"
    d:DesignWidth="400">

<!--We will apply MVVM Using ItemTemplates-->
<UserControl.Resources>
    <DataTemplate x:Key = "studentsTemplate">

        <StackPanel Orientation = "Horizontal">
            <TextBox Text = "{Binding Path = FirstName, Mode = TwoWay}"
        Width = "100" Margin = "3 5 3 5"/>

            <TextBox Text = "{Binding Path = LastName, Mode = TwoWay}"
        Width = "100" Margin = "0 5 3 5"/>

            <TextBlock Text = "{Binding Path = FullName, Mode = OneWay}"
        Margin = "0 5 3 5"/>
        </StackPanel>

    </DataTemplate>
</UserControl.Resources>

<Grid>
    <StackPanel Orientation="Horizontal">
        <!--In StudentView.xaml, we need to add SelectedItem property in a ListBox
        which will bind to the SelectStudent property.-->
        <ListView ItemsSource="{Binding Students}"
                  ItemTemplate="{StaticResource studentsTemplate}"
                  SelectedItem="{Binding SelectedStudent}"/>

        <Button Content = "Delete"
                Command="{Binding DeleteCommand}"
                HorizontalAlignment = "Left"
                VerticalAlignment = "Top"
                Width = "75"/>
    </StackPanel>
</Grid>
</UserControl>
</code>```

I'm applying the viewmodellocator on the app.xaml file at application level:

```<code><Application.Resources>
    <vml:ViewModelLocator x:Key="mainViewModelLocator"/>
</Application.Resources>
</code>```

and I call my view on the main page like this:

can somebody help me, I've run this code on VS2015 and VS2017 and the Delete button never gets enabled and it also doesnt delete the rows from the listview or listbox i've tried changing them and nothing seems to be different.

I've even had a commanding implemetation without using the relaycommand pattern as it is used here.
I would appreciate your help.

Thanks!!!

答:
You're missing a line in the setter to raise the property changed notification

```<code>public Student SelectedStudent
{
    get
    {
        return _selectedStudent;
    }
    set
    {
        _selectedStudent = value;
        RaisePropertyChanged("SelectedStudent"); // your version of this notifier
        DeleteCommand.RaiseCanExecuteChanged();
    }
}
</code>```

The above is enough to fix the issue, but, aside from that, you can simply check the private backing field in CanDelete:

```<code>return _selectedStudent != null;
</code>```

Body:
Ok. I'm following a tutorial to master MVVM Pattern to my app.

I've followed the tutorial quite well, I got to the part of commandings and when I try to apply command to a button it doesnt seem to work at all, my button never disables.
I've seen other MVVM sources and my code seems to be fine besides I found this tutorial on internet it was meant for WPF, but it also apply for UWP Windows 10 Apps.

So I'll paste my classes and Xaml views.

this is my Model:

using System.ComponentModel;

namespace MVVMDemo.Model
{
public class Student : INotifyPropertyChanged
{
    private string firstName;
    private string lastName;

    public string FirstName
    {
        get
        {
            return firstName;
        }

        set
        {
            if (firstName != value)
            {
                firstName = value;
                RaisePropertyChanged("FirstName");
                RaisePropertyChanged("FullName");
            }
        }
    }

    public string LastName
    {
        get { return lastName; }

        set
        {
            if (lastName != value)
            {
                lastName = value;
                RaisePropertyChanged("LastName");
                RaisePropertyChanged("FullName");
            }
        }
    }

    public string FullName
    {
        get
        {
            return firstName + " " + lastName;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private void RaisePropertyChanged(string property)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }
}
}

The model code I believe has no errors on it.
this is my ViewModel:

using MVVMDemo.Model;
using System.Collections.ObjectModel;

namespace MVVMDemo.ViewModel
{
public class StudentViewModel
{
    /*Let’s add a property of MyICommand type in StudentView Model class.
     * Now we need to construct an instance in the StudentViewModel. We will
     * use the overloaded constructor of MyICommand that takes two parameters.*/
    public MyICommand DeleteCommand { get; set; }

    /*Now add the implementation of OnDelete and CanDelete methods.*/
    public StudentViewModel()
    {
        LoadStudents();
        DeleteCommand = new MyICommand(OnDelete, CanDelete);
    }

    private bool CanDelete()
    {
        //if (SelectedStudent != null)
        //    return true;
        //return false;
        return SelectedStudent != null;
    }

    private void OnDelete()
    {
        Students.Remove(SelectedStudent);
    }

    /*We also need to add a new SelectedStudent so that the user
     * can delete the Selected Item from ListBox.*/
    private Student _selectedStudent;

    public Student SelectedStudent
    {
        get
        {
            return _selectedStudent;
        }
        set
        {
            _selectedStudent = value;
            DeleteCommand.RaiseCanExecuteChanged();
        }
    }
    public ObservableCollection<Student> Students
    {
        get;
        set;
    }

    public void LoadStudents()
    {
        ObservableCollection<Student> students = new ObservableCollection<Student>();

        students.Add(new Student { FirstName = "Mark", LastName = "Allain" });
        students.Add(new Student { FirstName = "Allen", LastName = "Brown" });
        students.Add(new Student { FirstName = "Linda", LastName = "Hamerski" });

        Students = students;
    }
}
}

This is my ViewModelLocator:

using MVVMDemo.ViewModel;

namespace MVVMDemo.VML
{
public class ViewModelLocator
{
private static StudentViewModel studentViewModel = new StudentViewModel();

    public static StudentViewModel StudentViewModel
    {
        get { return studentViewModel; }
    }
}
}

and at Last this is my View my UserControl StudentView

<UserControl
    x:Class="MVVMDemo.Views.StudentView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MVVMDemo.Views"
    xmlns:vml="using:MVVMDemo.VML"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    DataContext="{Binding Source={StaticResource mainViewModelLocator}, Path=StudentViewModel}"
    d:DesignHeight="300"
    d:DesignWidth="400">

<UserControl.Resources>
    <DataTemplate x:Key = "studentsTemplate">

        <StackPanel Orientation = "Horizontal">
            <TextBox Text = "{Binding Path = FirstName, Mode = TwoWay}"
        Width = "100" Margin = "3 5 3 5"/>

            <TextBox Text = "{Binding Path = LastName, Mode = TwoWay}"
        Width = "100" Margin = "0 5 3 5"/>

            <TextBlock Text = "{Binding Path = FullName, Mode = OneWay}"
        Margin = "0 5 3 5"/>
        </StackPanel>

    </DataTemplate>
</UserControl.Resources>

<Grid>
    <StackPanel Orientation="Horizontal">

        <ListView ItemsSource="{Binding Students}"
                  ItemTemplate="{StaticResource studentsTemplate}"
                  SelectedItem="{Binding SelectedStudent}"/>

        <Button Content = "Delete"
                Command="{Binding DeleteCommand}"
                HorizontalAlignment = "Left"
                VerticalAlignment = "Top"
                Width = "75"/>
    </StackPanel>
</Grid>
</UserControl>

I'm applying the viewmodellocator on the app.xaml file at application level:

<Application.Resources>
    <vml:ViewModelLocator x:Key="mainViewModelLocator"/>
</Application.Resources>

and I call my view on the main page like this:

can somebody help me, I've run this code on VS2015 and VS2017 and the Delete button never gets enabled and it also doesnt delete the rows from the listview or listbox i've tried changing them and nothing seems to be different.

I've even had a commanding implemetation without using the relaycommand pattern as it is used here.
I would appreciate your help.

Thanks!!!

Body:
You're missing a line in the setter to raise the property changed notification

public Student SelectedStudent
{
    get
    {
        return _selectedStudent;
    }
    set
    {
        _selectedStudent = value;
        RaisePropertyChanged("SelectedStudent"); // your version of this notifier
        DeleteCommand.RaiseCanExecuteChanged();
    }
}

The above is enough to fix the issue, but, aside from that, you can simply check the private backing field in CanDelete:

return _selectedStudent != null;


问:
How to change the size of the textbox, make it long in asp.net core defalut template
I am trying to make a form in which the required input is lager. And that default <input ="text"> size is not enough. I tried size="" and also width="" but it is not giving any change. I am using asp.net core default website templates. Is there any size limit? If there is, how can I change it? Please help me to change the size of the textbox.

答:
```<code><input asp-for="Title" class="form-control" style="min-width:100%"/>
</code>```

I added style ="min-width:100%" as shown above and it worked.

Body:
<input asp-for="Title" class="form-control" style="min-width:100%"/>

I added style ="min-width:100%" as shown above and it worked.


问:
Direct Incoming Emails to CPanel email server?
I've configured several email addresses using the built-in CPanel email utility, and they're all able to successfully send outgoing mail. Incoming mail however is bounced back, with one of the following two errors:

```<code>Address not found:
The response from the remote server was:
550 5.1.1 <email@domain.com> Recipient not found.

Message not delivered:
The response from the remote server was:
550 5.4.1 [nathan@fortunesfavored.com]: Recipient address rejected: Access denied
</code>```

I believe that these error codes (550 5.4.1 and 550 5.1.1) are Exchange server errors, meaning that incoming mail is being directed to the wrong server. (I'm hosting on a GoDaddy service). Is that correct? If so, is this an issue that I would solve in my DNS settings under the MX entry? Here's what I have now:

```<code>Priority  Host   Points to                    TTL
10        @      mailstore1.secureserver.net  1 Hour
0         @      smtp.secureserver.net        1 Hour
</code>```

答:
yes you have to edit your MX entries.

Login to you cpanel account.
under emails click on MX entries.

if there is no MX entry then add a MX entry.

mail.yourdomainname.com and set priority 10

Body:
I've configured several email addresses using the built-in CPanel email utility, and they're all able to successfully send outgoing mail. Incoming mail however is bounced back, with one of the following two errors:

Address not found:
The response from the remote server was:
550 5.1.1 <email@domain.com> Recipient not found.

Message not delivered:
The response from the remote server was:
550 5.4.1 [nathan@fortunesfavored.com]: Recipient address rejected: Access denied

I believe that these error codes (550 5.4.1 and 550 5.1.1) are Exchange server errors, meaning that incoming mail is being directed to the wrong server. (I'm hosting on a GoDaddy service). Is that correct? If so, is this an issue that I would solve in my DNS settings under the MX entry? Here's what I have now:

Priority  Host   Points to                    TTL
10        @      mailstore1.secureserver.net  1 Hour
0         @      smtp.secureserver.net        1 Hour


问:
App Engine, How to check if all values in a list are in a string list in the datastore
If you have a string list in the datastore that has the values:

a,b,c

How can you compare it against a list so that it only returns true if every value in the string list is present in the list?

['a', 'b'] would return false

['a', 'b', 'c'] would return true

['a', 'b', 'c', 'd', 'e'] would return true

Is this possible with GQL alone or would I need to pull put out the string list and loop over it?

答:
You can serialize your list in a sorted fashion as a single StringProperty.  Depending on the content of your StringListProperty this may be as trivial as comma separated values.

Optionally you can use something like an md5 checksums to reduce the length of the string being stored and filtered against.


问:
Select arrow style change
I'm trying to replace the arrow of a select with a picture of my own. I'm including the select in a div with the same size, I set the background of the select as transparent and I'm including a picture(with the same size as the arrow) in the right top corner of the div as background.

It only works in Chrome.

How can I make it work in Firefox and IE9 where I'm getting this:

.styled-select {
  width: 100px;
  height: 17px;
  overflow: hidden;
  overflow: -moz-hidden-unscrollable;
  background: url(images/downarrow_blue.png) no-repeat right white;
  border: 2px double red;
  display: inline-block;
  position: relative;
}

.styled-select select {
  background: transparent;
  -webkit-appearance: none;
  width: 100px;
  font-size: 11px;
  border: 0;
  height: 17px;
  position: absolute;
  left: 0;
  top: 0;
}

body {
  background-color: #333333;
  color: #FFFFFF;
}

.block label {
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><HTML>

<HEAD>
</HEAD>

<BODY>
  <p/>
  <form action="/prepareUpdateCategoryList.do?forwardto=search">

    <fieldset class="block" id="searchBlock">
      <p>
        <label style="width:80px">Class</label>
        <div class="styled-select">
          <select property="voucherCategoryClass">
      <option value="0">Select </option>
      <option value="7382">steam </option>
     </select>
        </div>

      </p>
    </fieldset>
  </form>
</BODY>

</HTML></code>```

答:
This would work well especially for those using Bootstrap, tested in latest browser versions:

select {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  /* Some browsers will not display the caret when using calc, so we put the fallback first */
  background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat 98.5% !important; /* !important used for overriding all other customisations */
  background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat calc(100% - 10px) !important; /* Better placement regardless of input width */
}
/*For IE*/
select::-ms-expand { display: none; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>

<div class="container">
  <div class="row">
    <div class="col-xs-6">
      <select class="form-control">
       <option>Option 1</option>
       <option>Option 2</option>
       <option>Option 3</option>
      </select>
    </div>
  </div>
</div></code>```

Title: Select arrow style change

Body:
I'm trying to replace the arrow of a select with a picture of my own. I'm including the select in a div with the same size, I set the background of the select as transparent and I'm including a picture(with the same size as the arrow) in the right top corner of the div as background.

It only works in Chrome.

How can I make it work in Firefox and IE9 where I'm getting this:

.styled-select {
  width: 100px;
  height: 17px;
  overflow: hidden;
  overflow: -moz-hidden-unscrollable;
  background: url(images/downarrow_blue.png) no-repeat right white;
  border: 2px double red;
  display: inline-block;
  position: relative;
}

.styled-select select {
  background: transparent;
  -webkit-appearance: none;
  width: 100px;
  font-size: 11px;
  border: 0;
  height: 17px;
  position: absolute;
  left: 0;
  top: 0;
}

body {
  background-color: #333333;
  color: #FFFFFF;
}

.block label {
  color: white;
}

  <form action="/prepareUpdateCategoryList.do?forwardto=search">

    <fieldset class="block" id="searchBlock">

        Class

          <select property="voucherCategoryClass">
      <option value="0">Select </option>
      <option value="7382">steam </option>
     </select>

    </fieldset>
  </form>

Body:
This would work well especially for those using Bootstrap, tested in latest browser versions:

select {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  /* Some browsers will not display the caret when using calc, so we put the fallback first */
  background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat 98.5% !important; /* !important used for overriding all other customisations */
  background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat calc(100% - 10px) !important; /* Better placement regardless of input width */
}
/*For IE*/
select::-ms-expand { display: none; }

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>

<div class="container">
  <div class="row">
    <div class="col-xs-6">
      <select class="form-control">
       <option>Option 1</option>
       <option>Option 2</option>
       <option>Option 3</option>
      </select>
    </div>
  </div>
</div>


问:
htaccess query string redirect to path
I have a url like about.php?lang=en and I want to change it to about.php/en
I have tried

```<code>```
RewriteCond %{THE_REQUEST} ^GET\ /\?(([^&\s]*&)*)lang=([^&\s]+)&?([^\s]*)
RewriteRule ^(.*)$ /lang/%3?%1%4 [L,R=301]
```
</code>```

In htaccess but it doen't work.

答:
You can use this :

```<code>RewriteEngine on
#redirect /about.php?lang=lang to /about.php/lang
RewriteCond %{THE_REQUEST} /about\.php\?lang=([^\s&]+) [NC]
RewriteRule ^ /about.php/%1? [L,R]
#internally forward /about.php/lang to /about.php?lang=lang
RewriteRule ^about\.php/([^/]+)/?$ /about.php?lang=$1 [L]
</code>```

Dont remove the final ? otherwise mod-rewrite will append old querystring to the destination url.

Title: htaccess query string redirect to path

Body:
I have a url like about.php?lang=en and I want to change it to about.php/en
I have tried

RewriteCond %{THE_REQUEST} ^GET\ /\?(([^&\s]*&)*)lang=([^&\s]+)&?([^\s]*)
RewriteRule ^(.*)$ /lang/%3?%1%4 [L,R=301]

In htaccess but it doen't work.

Body:
You can use this :

RewriteEngine on
#redirect /about.php?lang=lang to /about.php/lang
RewriteCond %{THE_REQUEST} /about\.php\?lang=([^\s&]+) [NC]
RewriteRule ^ /about.php/%1? [L,R]
#internally forward /about.php/lang to /about.php?lang=lang
RewriteRule ^about\.php/([^/]+)/?$ /about.php?lang=$1 [L]

Dont remove the final ? otherwise mod-rewrite will append old querystring to the destination url.


问:
How to divide multiple columns with each other in Pandas
I have a dataframe with 52 columns with sales data (weekly) and 52 columns with the sold quantity. I want to create another 52 colums with the price per soldunit.

The division does not work for some reason. I get

ValueError: Wrong number of items passed 2, placement implies 1

Also, can this be achieved in a more elegant (pandas way) by removing the for loop?

This is what I have...

```<code>#calculate cost per unit
for i in range(0,52):
    cw = i + 1
    i = i + 5
    print cw
    data['Cost' + str(cw)] = data.iloc[:,i:i+1] / sap_data.iloc[:,i+52:i+1+52]
</code>```

答:
Do you mean just

```<code>data['sales']/data['quantity']
</code>```

Edit: It might be a notation matter. Can you try:

```<code>data.iloc[:,i] / sap_data.iloc[:,i+52]
</code>```

which I believe is what you have in mind

Body:
I have a dataframe with 52 columns with sales data (weekly) and 52 columns with the sold quantity. I want to create another 52 colums with the price per soldunit.

The division does not work for some reason. I get

ValueError: Wrong number of items passed 2, placement implies 1

Also, can this be achieved in a more elegant (pandas way) by removing the for loop?

This is what I have...

#calculate cost per unit
for i in range(0,52):
    cw = i + 1
    i = i + 5
    print cw
    data['Cost' + str(cw)] = data.iloc[:,i:i+1] / sap_data.iloc[:,i+52:i+1+52]

Body:
Do you mean just

data['sales']/data['quantity']

Edit: It might be a notation matter. Can you try:

data.iloc[:,i] / sap_data.iloc[:,i+52]

which I believe is what you have in mind


问:
serilog convert scalarvalue into a dictionary inside a sink
Can i convert this scalarvalue into two separate properties inside a sink?

The sink will store the logevent as a json object inside Postgresql using Marten.

```<code>var sensorInput = new { Latitude = 25, Longitude = 134 };
Log.Information("Test {sensorInput}", sensorInput);
</code>```

In my json object i want store this as two seperate properties
so i can filter on one of the properties

The JsonFormatter is also not converting this object into two separate properties. I want to store the separate property so i can query on those properties

see https://github.com/mdissel/serilog-sinks-marten/blob/master/src/Serilog.Sinks.Marten/LogMessage.cs

答: Confirmed! Use the @ in the message to convert the properties into a Dictionary.</p>

Body:
Can i convert this scalarvalue into two separate properties inside a sink?

The sink will store the logevent as a json object inside Postgresql using Marten.

var sensorInput = new { Latitude = 25, Longitude = 134 };
Log.Information("Test {sensorInput}", sensorInput);

In my json object i want store this as two seperate properties
so i can filter on one of the properties

The JsonFormatter is also not converting this object into two separate properties. I want to store the separate property so i can query on those properties

see https://github.com/mdissel/serilog-sinks-marten/blob/master/src/Serilog.Sinks.Marten/LogMessage.cs


问:
How to preview what a XAML control with bound values looks like
I'm writing an app in XAML, and I'm using binding for getting values to the UI layer.  I'd like to see what my control will look like while making changes to the XAML, but because the data values are bound, many areas show up as blank (which, in turn, messes up the relative layout).

Is there any way to give XAML values to use for rendering the control review without replacing the Binding directives?

答: You can also use design time data to see how your xaml works. You just need to add new class that will be treated as design time view model. Its more elegant way to test xaml at design time. </p>


问:
HTML5 Canvas Rotate Image
```<code>jQuery('#carregar').click(function() {
  var canvas    = document.getElementById('canvas');
  var image   = document.getElementById('image');
  var element = canvas.getContext("2d");
  element.clearRect(0, 0, canvas.width, canvas.height);
  element.drawImage(image, 0, 0, 300, 300);
});
</code>```

jsfiddle.net/braziel/nWyDE/

I have a problem to rotate an image 90 ° to the right or to the left.

I use an image on the canvas, the same screen will have several canvas equal to that of the example, but I left it as close as possible to the project.

I ask, how do I rotate the image 90 ° to the left or right when I click "Rotate Left" and "Rotate Right"?

I tried several codes on the internet but none worked.

答:
Quickest 2D context image rotation method

A general purpose image rotation, position, and scale.

```<code>// no need to use save and restore between calls as it sets the transform rather
// than multiply it like ctx.rotate ctx.translate ctx.scale and ctx.transform
// Also combining the scale and origin into the one call makes it quicker
// x,y position of image center
// scale scale of image
// rotation in radians.
function drawImage(image, x, y, scale, rotation){
    ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin
    ctx.rotate(rotation);
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
}
</code>```

If you wish to control the rotation point use the next function

```<code>// same as above but cx and cy are the location of the point of rotation
// in image pixel coordinates
function drawImageCenter(image, x, y, cx, cy, scale, rotation){
    ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin
    ctx.rotate(rotation);
    ctx.drawImage(image, -cx, -cy);
}
</code>```

To reset the 2D context transform

```<code>ctx.setTransform(1,0,0,1,0,0); // which is much quicker than save and restore
</code>```

Thus to rotate image to the left (anti clockwise) 90 deg

```<code>drawImage(image, canvas.width / 2, canvas.height / 2, 1, - Math.PI / 2);
</code>```

Thus to rotate image to the right (clockwise) 90 deg

```<code>drawImage(image, canvas.width / 2, canvas.height / 2, 1, Math.PI / 2);
</code>```

Example draw 500 images translated rotated scaled

var image = new Image;
image.src = "https://i.stack.imgur.com/C7qq2.png?s=328&g=1";
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.style.position = "absolute";
canvas.style.top = "0px";
canvas.style.left = "0px";
document.body.appendChild(canvas);
var w,h;
function resize(){ w = canvas.width = innerWidth; h = canvas.height = innerHeight;}
resize();
window.addEventListener("resize",resize);
function rand(min,max){return Math.random() * (max ?(max-min) : min) + (max ? min : 0) }
function DO(count,callback){ while (count--) { callback(count) } }
const sprites = [];
DO(500,()=>{
    sprites.push({
       x : rand(w), y : rand(h),
       xr : 0, yr : 0, // actual position of sprite
       r : rand(Math.PI * 2),
       scale : rand(0.1,0.25),
       dx : rand(-2,2), dy : rand(-2,2),
       dr : rand(-0.2,0.2),
    });
});
function drawImage(image, spr){
    ctx.setTransform(spr.scale, 0, 0, spr.scale, spr.xr, spr.yr); // sets scales and origin
    ctx.rotate(spr.r);
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
}
function update(){
    var ihM,iwM;
    ctx.setTransform(1,0,0,1,0,0);
    ctx.clearRect(0,0,w,h);
    if(image.complete){
      var iw = image.width;
      var ih = image.height;
      for(var i = 0; i < sprites.length; i ++){
          var spr = sprites[i];
          spr.x += spr.dx;
          spr.y += spr.dy;
          spr.r += spr.dr;
          iwM = iw * spr.scale * 2 + w;
          ihM = ih * spr.scale * 2 + h;
          spr.xr = ((spr.x % iwM) + iwM) % iwM - iw * spr.scale;
          spr.yr = ((spr.y % ihM) + ihM) % ihM - ih * spr.scale;
          drawImage(image,spr);
      }
    }
    requestAnimationFrame(update);
}
requestAnimationFrame(update);```

Title: HTML5 Canvas Rotate Image

Body:
jQuery('#carregar').click(function() {
  var canvas    = document.getElementById('canvas');
  var image   = document.getElementById('image');
  var element = canvas.getContext("2d");
  element.clearRect(0, 0, canvas.width, canvas.height);
  element.drawImage(image, 0, 0, 300, 300);
});

jsfiddle.net/braziel/nWyDE/

I have a problem to rotate an image 90 ° to the right or to the left.

I use an image on the canvas, the same screen will have several canvas equal to that of the example, but I left it as close as possible to the project.

I ask, how do I rotate the image 90 ° to the left or right when I click "Rotate Left" and "Rotate Right"?

I tried several codes on the internet but none worked.

Body:
Quickest 2D context image rotation method

A general purpose image rotation, position, and scale.

// no need to use save and restore between calls as it sets the transform rather
// than multiply it like ctx.rotate ctx.translate ctx.scale and ctx.transform
// Also combining the scale and origin into the one call makes it quicker
// x,y position of image center
// scale scale of image
// rotation in radians.
function drawImage(image, x, y, scale, rotation){
    ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin
    ctx.rotate(rotation);
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
}

If you wish to control the rotation point use the next function

// same as above but cx and cy are the location of the point of rotation
// in image pixel coordinates
function drawImageCenter(image, x, y, cx, cy, scale, rotation){
    ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin
    ctx.rotate(rotation);
    ctx.drawImage(image, -cx, -cy);
}

To reset the 2D context transform

ctx.setTransform(1,0,0,1,0,0); // which is much quicker than save and restore

Thus to rotate image to the left (anti clockwise) 90 deg

drawImage(image, canvas.width / 2, canvas.height / 2, 1, - Math.PI / 2);

Thus to rotate image to the right (clockwise) 90 deg

drawImage(image, canvas.width / 2, canvas.height / 2, 1, Math.PI / 2);

Example draw 500 images translated rotated scaled

var image = new Image;
image.src = "https://i.stack.imgur.com/C7qq2.png?s=328&g=1";
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.style.position = "absolute";
canvas.style.top = "0px";
canvas.style.left = "0px";
document.body.appendChild(canvas);
var w,h;
function resize(){ w = canvas.width = innerWidth; h = canvas.height = innerHeight;}
resize();
window.addEventListener("resize",resize);
function rand(min,max){return Math.random() * (max ?(max-min) : min) + (max ? min : 0) }
function DO(count,callback){ while (count--) { callback(count) } }
const sprites = [];
DO(500,()=>{
    sprites.push({
       x : rand(w), y : rand(h),
       xr : 0, yr : 0, // actual position of sprite
       r : rand(Math.PI * 2),
       scale : rand(0.1,0.25),
       dx : rand(-2,2), dy : rand(-2,2),
       dr : rand(-0.2,0.2),
    });
});
function drawImage(image, spr){
    ctx.setTransform(spr.scale, 0, 0, spr.scale, spr.xr, spr.yr); // sets scales and origin
    ctx.rotate(spr.r);
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
}
function update(){
    var ihM,iwM;
    ctx.setTransform(1,0,0,1,0,0);
    ctx.clearRect(0,0,w,h);
    if(image.complete){
      var iw = image.width;
      var ih = image.height;
      for(var i = 0; i < sprites.length; i ++){
          var spr = sprites[i];
          spr.x += spr.dx;
          spr.y += spr.dy;
          spr.r += spr.dr;
          iwM = iw * spr.scale * 2 + w;
          ihM = ih * spr.scale * 2 + h;
          spr.xr = ((spr.x % iwM) + iwM) % iwM - iw * spr.scale;
          spr.yr = ((spr.y % ihM) + ihM) % ihM - ih * spr.scale;
          drawImage(image,spr);
      }
    }
    requestAnimationFrame(update);
}
requestAnimationFrame(update);


问:
Should I use $_GET to dynamically load html?
I am working on a social networking site using PHP, MySQL(PDO), JQuery, and HTML(CSS). I'm working on the profile page right now and I want to determine if the user is on their own page or another's to determine what inputs they'll have. I would like to keep a framework for the profile page and load the respective options rather than having 2 different pages (my profile vs other profile).

I'm learning JQuery and PHP as I go, so right now I am thinking, in JQuery, I can get the $_GET (?username= ) and compare it to the user id of who's logged in, then load the components I need based on that.

Or I determine the user in PHP then run a certain scrip to load the components.

Would on of these ways work, or is there a different/better way to do this?

答:
You can echo the PHP's GET value in JavaScript. But make sure, without makeItSafe (which you have to define yourself) this code can be exploited to perform cross site scripting attacks:

```<code><script>
var myGlobalUserID = "<?php echo makeItSafe($_GET['userID']); ?>";
</script>
</code>```

Body:
You can echo the PHP's GET value in JavaScript. But make sure, without makeItSafe (which you have to define yourself) this code can be exploited to perform cross site scripting attacks:

<script>
var myGlobalUserID = "<?php echo makeItSafe($_GET['userID']); ?>";
</script>


问:
How to set a value to display for bound properties in WPF design mode?
My bound contents are showed as empty string in the UI design-mode. I want to display some faked value for those contents but I don't know how to.

Please share if you know how to. Thank you!

答:
You could use the DesignMode property to find out if you are at design time ( http://msdn.microsoft.com/en-us/library/c58hb4bw(vs.71).aspx )

There are further thoughts but no real conclusions on ways to do it at this question: What approaches are available to dummy design-time data in WPF?


问:
My subscribe method is called even before my greenrobot bus posts an event
I'm trying to post an event from within a subscriber

```<code>@Subscribe
public void onFirstEvent(FirstEvent event) {
    ...
    bus.post(new SecondEvent(...));
}
</code>```

And in my other class, where I handle SecondEvent, I use a subscribe method in the same way. The problem is, the method that subscribes to SecondEventis called even before onFirstEvent() is called.

What am I doing wrong?

答:
```<code>public void onFirstEvent(Event event) {
    if (event instanceof FirstEvent) {
        ...
        bus.post(new SecondEvent(...));
    } else if (event instanceof SecondEvent) {
        // process
    }

}
</code>```

you can test like this

Body:
I'm trying to post an event from within a subscriber

@Subscribe
public void onFirstEvent(FirstEvent event) {
    ...
    bus.post(new SecondEvent(...));
}

And in my other class, where I handle SecondEvent, I use a subscribe method in the same way. The problem is, the method that subscribes to SecondEventis called even before onFirstEvent() is called.

What am I doing wrong?

Body:
public void onFirstEvent(Event event) {
    if (event instanceof FirstEvent) {
        ...
        bus.post(new SecondEvent(...));
    } else if (event instanceof SecondEvent) {
        // process
    }

}

you can test like this


问:
datepicker, jquery
I have a datepicker (jquery)

$("#datepicker").datepicker({

});

I want to colorize(highlight)  some days in this datepicker.  And these days i'd like to get from some array !!!!

I dont know, something like this:

$("#datepicker").datepicker({

  highlight:['09/16/2009', 09/12/2009,
  08/16/2009 ....]  });

Help me please

Thanks a lot !!!

答:
Here is the simple one, may be useful for someone</p>

```<code><link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("#datepicker").datepicker();
  });
  </script>

<form>
    <input id="datepicker" />
</form>
</code>```

Title: datepicker, jquery

Body:
Here is the simple one, may be useful for someone

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("#datepicker").datepicker();
  });
  </script>

<form>
    <input id="datepicker" />
</form>


问:
Javascript repeating if statements better solution?
I have 3 inputs and the code checks if they are empty and if they are then the variable values are added to the inputs.

So I have 3 variables with values:

```<code>var input1text = "something here";
var input2text = "something else here";
var input3text = "something else 2 here";
</code>```

So when the page loads, I check if the inputs are empty and if they are I add the variable values to the inputs.

Like this:

```<code>if($('#input1').val() == '') {

    //Add input1text text to it

}

if($('#input2').val() == '') {

    //Add input2text text to it

}

if($('#input3').val() == '') {

    //Add input3text text to it

}
</code>```

My question is, it having multiple ifs the most elegant way to do this? Is there a better way?

答:
We can extract an abstraction over the operation of checking the fields and putting the default value.</p>

```<code>var fields = [{
    selector: "#input1",
    defaultVal: "default1"
}, {
    selector: "#input2",
    defaultVal: "default2"
}, {
    selector: "#input3",
    defaultVal: "default3"
}
];

var setDefault = function (selector, default) {
    if($(selector).val() == '') {
        $(selector).val(default);
    }
}

for (var i = 1; i < fields.length; i++) {
    var field = fields[i];
    setDefault(field.selector, field.defaultVal);
}
</code>```

Body:
I have 3 inputs and the code checks if they are empty and if they are then the variable values are added to the inputs.

So I have 3 variables with values:

var input1text = "something here";
var input2text = "something else here";
var input3text = "something else 2 here";

So when the page loads, I check if the inputs are empty and if they are I add the variable values to the inputs.

Like this:

if($('#input1').val() == '') {

    //Add input1text text to it

}

if($('#input2').val() == '') {

    //Add input2text text to it

}

if($('#input3').val() == '') {

    //Add input3text text to it

}

My question is, it having multiple ifs the most elegant way to do this? Is there a better way?

Body:
We can extract an abstraction over the operation of checking the fields and putting the default value.

var fields = [{
    selector: "#input1",
    defaultVal: "default1"
}, {
    selector: "#input2",
    defaultVal: "default2"
}, {
    selector: "#input3",
    defaultVal: "default3"
}
];

var setDefault = function (selector, default) {
    if($(selector).val() == '') {
        $(selector).val(default);
    }
}

for (var i = 1; i < fields.length; i++) {
    var field = fields[i];
    setDefault(field.selector, field.defaultVal);
}


答:
You could use .each() to check every input and if it's empty - assign corresponding value from an array holding the values.

var inputs = ['something here', 'something else here', 'something else 2 here'];

    $('input').each(function(i){
      $(this).val() == '' ? $(this).val(inputs[i]) : null;
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='input1' value='x'>
<input id='input2'>
<input id='input3'></code>```

var inputs = {input1:'something here', input2:'something else here', input3: 'something else 2 here'};

    $('input').each(function(i){
      $(this).val() == '' ? $(this).val(inputs[$(this).attr('id')]) : null;
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='input1' value='x'>
<input id='input2'>
<input id='input3'></code>```

Title: Javascript repeating if statements better solution?

Body:
You could use .each() to check every input and if it's empty - assign corresponding value from an array holding the values.

var inputs = ['something here', 'something else here', 'something else 2 here'];

    $('input').each(function(i){
      $(this).val() == '' ? $(this).val(inputs[i]) : null;
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='input1' value='x'>
<input id='input2'>
<input id='input3'>

var inputs = {input1:'something here', input2:'something else here', input3: 'something else 2 here'};

    $('input').each(function(i){
      $(this).val() == '' ? $(this).val(inputs[$(this).attr('id')]) : null;
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='input1' value='x'>
<input id='input2'>
<input id='input3'>


答:
You could create an object with keys the ids of your html elements and values their default values:

```<code>var inputDefaultValues = {
    "input1": "something here",
    "input2": "something else here",
    "input3":  "something else 2 here"
};
</code>```

Then you could loop through the keys of this object, check if the value of the corresponding element is empty and if it is empty to aplly the default value:

```<code>Object.keys(inputDefaultValues)
      .forEach(function(key){
          var inputElement = document.getElementById(key);
          if(inputElement.value === ''){
              inputElement.value = inputDefaultValues[key];
          }
      });
</code>```

var inputDefaultValues = {
    "input1": "something here",
    "input2": "something else here",
    "input3":  "something else 2 here"
};

Object.keys(inputDefaultValues)
      .forEach(function(key){
          var inputElement = document.getElementById(key);
          if(inputElement.value === ''){
              inputElement.value = inputDefaultValues[key];
          }
      });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="input1"/>
<input type="text" id="input2"/>
<input type="text" id="input3"/></code>```

Body:
You could create an object with keys the ids of your html elements and values their default values:

var inputDefaultValues = {
    "input1": "something here",
    "input2": "something else here",
    "input3":  "something else 2 here"
};

Then you could loop through the keys of this object, check if the value of the corresponding element is empty and if it is empty to aplly the default value:

Object.keys(inputDefaultValues)
      .forEach(function(key){
          var inputElement = document.getElementById(key);
          if(inputElement.value === ''){
              inputElement.value = inputDefaultValues[key];
          }
      });

var inputDefaultValues = {
    "input1": "something here",
    "input2": "something else here",
    "input3":  "something else 2 here"
};

Object.keys(inputDefaultValues)
      .forEach(function(key){
          var inputElement = document.getElementById(key);
          if(inputElement.value === ''){
              inputElement.value = inputDefaultValues[key];
          }
      });

<input type="text" id="input1"/>
<input type="text" id="input2"/>
<input type="text" id="input3"/>


问:
convert an encoded string to jpg and display it
I need to convert a base64 encoded string from a server (being sent via amf) to an image. on the server the raw image data (gif / jpeg / png) is being encoded to base64 (which already works fine), and I need to decode this string and display the image in my flash movie. How can this be done?</p>

答:
convert it to ByteArray

if you need saving: as3corelib package com.adobe.images.*


问:
Array of arrays and variable name based on object property
I call ajax service and I got back collection of objects. Object (A) properties are Group, order, salary. Let's say [Employee, 1, 1500],[Management, 2, 2000], [Employee, 3, salary] are my objects.

I need to to create an array for every group that can hold different objects (B), these objects could have format [OrderNo, String] and will be also retrieved by ajax call. If an array for a group was already created I do not want to call ajax for it again.

Problem is number of objects (A) or (B) isn't known in advance and I have to be able to reference the (A) object arrays and list thru them.

Result in pseudo code

```<code>var groups = [
    Employee: [[1372, "Free meals"],[947, "Lower salary"],[21, "Overtimes"],[74667,"Great Xmass party"]],
    Management: [[11, "Responsibility"],[485,"Extra meetings"]]
]
</code>```

I don't know how to correctly write

```<code>for(var index in "Object A"){
if(groups.AlreadyContains("Object A[index]")){
     do nothing;
}
else {
     var "Object A[index]" = MyAjaxCall("Object A[index]");
     groups.AddAnArray("Object A[index]");
    }
}

function MyAjaxCall(par){ call ajax and return collection of B objects;}

foreach(var i in groups.Management)
{Console.log(Management[i].PropertyName);}
</code>```

Console output: Responsibility, Extra meetings

答:
You need to get both objects of type A and objects of type B ready and then start computation over them.

This is a common pattern in async functionality.

If you are using ES6

```<code>Promise.all(fetchObjectA, fetchObjectsB).then((objectsA, objectsB) =>
  // Do things over both objectsA and B
)
</code>```

If you are using jQuery

```<code>$.when(fetchObjectA, fetchObjectsB).done((objectsA, objectsB) =>
   // Do same as above
)
</code>```

Body:
I call ajax service and I got back collection of objects. Object (A) properties are Group, order, salary. Let's say [Employee, 1, 1500],[Management, 2, 2000], [Employee, 3, salary] are my objects.

I need to to create an array for every group that can hold different objects (B), these objects could have format [OrderNo, String] and will be also retrieved by ajax call. If an array for a group was already created I do not want to call ajax for it again.

Problem is number of objects (A) or (B) isn't known in advance and I have to be able to reference the (A) object arrays and list thru them.

Result in pseudo code

var groups = [
    Employee: [[1372, "Free meals"],[947, "Lower salary"],[21, "Overtimes"],[74667,"Great Xmass party"]],
    Management: [[11, "Responsibility"],[485,"Extra meetings"]]
]

I don't know how to correctly write

for(var index in "Object A"){
if(groups.AlreadyContains("Object A[index]")){
     do nothing;
}
else {
     var "Object A[index]" = MyAjaxCall("Object A[index]");
     groups.AddAnArray("Object A[index]");
    }
}

function MyAjaxCall(par){ call ajax and return collection of B objects;}

foreach(var i in groups.Management)
{Console.log(Management[i].PropertyName);}

Console output: Responsibility, Extra meetings

Body:
You need to get both objects of type A and objects of type B ready and then start computation over them.

This is a common pattern in async functionality.

If you are using ES6

Promise.all(fetchObjectA, fetchObjectsB).then((objectsA, objectsB) =>
  // Do things over both objectsA and B
)

If you are using jQuery

$.when(fetchObjectA, fetchObjectsB).done((objectsA, objectsB) =>
   // Do same as above
)