问:
Excel VBA - loop over files in folder, copy range, paste in this workbook
I have 500 excel files with data. I would merge all this data into one file.

Task list to achieve this:

I want to loop over all the files in a folder

open the file,

copy this range "B3:I102"

paste it into the 1st sheet of the active workbook

repeat but paste new data underneath

I've done task 1-4 but i need help with task 5, last bit - pasting the data under the existing data and making it dynamic. I've highlighted this bit with '#### in my code.

Here is my code which I've put together from other people's question :)

Any suggestions on how to do this?

```<code>Sub LoopThroughFiles()
Dim MyObj As Object,
MySource As Object,
file As Variant
Dim wbThis                  As Workbook     'workbook where the data is to be pasted, aka Master file
Dim wbTarget                As Workbook     'workbook from where the data is to be copied from, aka Overnights file
Dim LastRow As Long
Dim sht1 As Worksheet
Dim sht2 As Worksheet

'set to the current active workbook (the source book, the Master!)
Set wbThis = ActiveWorkbook
Set sht1 = wbThis.Sheets("Sheet1")

Folder = "\\dne\ldc\research-dept\3 CEEMEA\15. EMB\Turkey\TLC Overnight & Weekly Reports\weekly (majeed)\"
Fname = Dir(Folder)

While (Fname <> "")

  Set wbTarget = Workbooks.Open(Filename:=Folder & Fname)
  wbTarget.Activate
  Range("b3:i102").Copy

  wbThis.Activate

  '################################
  'NEED HELP HERE. I GET A ERROR HERE. NEEDS TO BE MORE DYNAMIC.
  sht1.Range("b1:i100").PasteSpecial

 Fname = Dir

 'close the overnight's file
  wbTarget.Close
 Wend

End Sub
</code>```

答:
I think using variant is useful than copy method.</p>

```<code>Sub LoopThroughFiles()

Dim MyObj As Object, MySource As Object

file As Variant
Dim wbThis                  As Workbook     'workbook where the data is to be pasted, aka Master file
Dim wbTarget                As Workbook     'workbook from where the data is to be copied from, aka Overnights file
Dim LastRow As Long
Dim sht1 As Worksheet
Dim sht2 As Worksheet

Dim vDB As Variant

'set to the current active workbook (the source book, the Master!)
Set wbThis = ActiveWorkbook
Set sht1 = wbThis.Sheets("Sheet1")

Folder = "\\dne\ldc\research-dept\3 CEEMEA\15. EMB\Turkey\TLC Overnight & Weekly Reports\weekly (majeed)\"
Fname = Dir(Folder)

While (Fname <> "")

  Set wbTarget = Workbooks.Open(Filename:=Folder & Fname)

  vDB = wbTarget.Sheets(1).Range("b3:i102")

  '################################
  'NEED HELP HERE. I GET A ERROR HERE. NEEDS TO BE MORE DYNAMIC.

        sht1.Range("b" & Rows.Count).End(xlUp)(2).Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB

 Fname = Dir

 'close the overnight's file
  wbTarget.Close
 Wend

End Sub
</code>```

Body:
I have 500 excel files with data. I would merge all this data into one file.

Task list to achieve this:

I want to loop over all the files in a folder

open the file,

copy this range "B3:I102"

paste it into the 1st sheet of the active workbook

repeat but paste new data underneath

I've done task 1-4 but i need help with task 5, last bit - pasting the data under the existing data and making it dynamic. I've highlighted this bit with '#### in my code.

Here is my code which I've put together from other people's question :)

Any suggestions on how to do this?

Sub LoopThroughFiles()
Dim MyObj As Object,
MySource As Object,
file As Variant
Dim wbThis                  As Workbook     'workbook where the data is to be pasted, aka Master file
Dim wbTarget                As Workbook     'workbook from where the data is to be copied from, aka Overnights file
Dim LastRow As Long
Dim sht1 As Worksheet
Dim sht2 As Worksheet

'set to the current active workbook (the source book, the Master!)
Set wbThis = ActiveWorkbook
Set sht1 = wbThis.Sheets("Sheet1")

Folder = "\\dne\ldc\research-dept\3 CEEMEA\15. EMB\Turkey\TLC Overnight & Weekly Reports\weekly (majeed)\"
Fname = Dir(Folder)

While (Fname <> "")

  Set wbTarget = Workbooks.Open(Filename:=Folder & Fname)
  wbTarget.Activate
  Range("b3:i102").Copy

  wbThis.Activate

  '################################
  'NEED HELP HERE. I GET A ERROR HERE. NEEDS TO BE MORE DYNAMIC.
  sht1.Range("b1:i100").PasteSpecial

 Fname = Dir

 'close the overnight's file
  wbTarget.Close
 Wend

End Sub

Body:
I think using variant is useful than copy method.

Sub LoopThroughFiles()

Dim MyObj As Object, MySource As Object

file As Variant
Dim wbThis                  As Workbook     'workbook where the data is to be pasted, aka Master file
Dim wbTarget                As Workbook     'workbook from where the data is to be copied from, aka Overnights file
Dim LastRow As Long
Dim sht1 As Worksheet
Dim sht2 As Worksheet

Dim vDB As Variant

'set to the current active workbook (the source book, the Master!)
Set wbThis = ActiveWorkbook
Set sht1 = wbThis.Sheets("Sheet1")

Folder = "\\dne\ldc\research-dept\3 CEEMEA\15. EMB\Turkey\TLC Overnight & Weekly Reports\weekly (majeed)\"
Fname = Dir(Folder)

While (Fname <> "")

  Set wbTarget = Workbooks.Open(Filename:=Folder & Fname)

  vDB = wbTarget.Sheets(1).Range("b3:i102")

  '################################
  'NEED HELP HERE. I GET A ERROR HERE. NEEDS TO BE MORE DYNAMIC.

        sht1.Range("b" & Rows.Count).End(xlUp)(2).Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB

 Fname = Dir

 'close the overnight's file
  wbTarget.Close
 Wend

End Sub


来源: stackexchange

问:
Killing a PID which is using a port
I am using below code to kill a process which is using a port number

```<code>port = sudo lsof -n -i4TCP:3030 | grep LISTEN | awk '{print $2;}'
if [ ! -z "$port" -a "$port" != " " ]; then
   sudo kill "$port"
fi
</code>```

But it is saying port: command not found. What is causing the issue and how can I fix it.

答:
With just one line!</p>

```<code>sudo kill `sudo lsof -t -i:3030`
</code>```

ContentLicense: CC BY-SA 3.0

Title: Killing a PID which is using a port

Body:
I am using below code to kill a process which is using a port number

port = sudo lsof -n -i4TCP:3030 | grep LISTEN | awk '{print $2;}'
if [ ! -z "$port" -a "$port" != " " ]; then
   sudo kill "$port"
fi

But it is saying port: command not found. What is causing the issue and how can I fix it.

Body:
With just one line!

sudo kill `sudo lsof -t -i:3030`


问:
Looping through a list and generating knockout components
So I want to dynamically generate knockout components from an array of objects with properties.

Here is the html that will generate the components (apologies in advance for the terrible component name):

```<code> <div data-bind="foreach: graphs">
               <y1vsy2graphs params=" graphTitle: $data.y1Title + ' vs ' +
                                      $data.y2Title,
                                      y1Title: $data.y1Title,
                                      y2Title: $data.y2Title,
                                      tickInterval: $parent.tickInterval(),
                                      y1suffix: '',
                                      y2suffix: '',
                                      graphID: 'red',
                                      filter: $parent.filter(),
                                      selectedOption:
                                      $parent.selectedOption(),
                                      url:
                      Urls.get_ppc_dashboard_values(PageMeta.AccountToken)">
                </y1vsy2graphs>
</div>
</code>```

And here is the array it is looping through in the parent viewModel:

```<code>self.graphs = ko.observableArray([
{'y1Title': 'Cost', 'y1Data': self.datas()['Cost'],'y2Title':'ROI', 'y2Data': self.datas()['ROI']},
{'y1Title': 'Clicks','y1Data': self.datas()['Clicks'], 'y2Title': 'CPC', 'y2Data': self.datas()['CPC']},
{'y1Title': 'IMP','y1Data': self.datas()['IMP'], 'y2Title': 'CTR','y2Data':self.datas()['CTR']},
{'y1Title': 'Conv','y1Data': self.datas()['Conv'], 'y2Title': 'CPA', 'y2Data':self.datas()['CPA']},
{'y1Title': 'Conv','y1Data': self.datas()['Conv'],'y2Title': 'RPS', 'y2Data': self.datas()['RPS']}
]);
</code>```

Currently my code does create the elements as shown in the developer tools:

Developer-Tools:Elements

However I am not receiving any error messages from my y1vsy2graphs component. For that reason i'm having diffuculty identifying my problem.

答:
Try this:

```<code><div data-bind="foreach: graphs">
  <div data-bind="component: { name: 'y1vsy2graphs',
                               params: {
                                  graphTitle: $data.y1Title + ' vs ' + $data.y2Title,
                                  y1Title: $data.y1Title,
                                  y2Title: $data.y2Title,
                                  tickInterval: $parent.tickInterval(),
                                  y1suffix: '',
                                  y2suffix: '',
                                  graphID: 'red',
                                  filter: $parent.filter(),
                                  selectedOption: $parent.selectedOption(),
                                  url: Urls.get_ppc_dashboard_values(PageMeta.AccountToken)
                                }
                              }">
  </div>
</div>
</code>```

Basicly the same thing, but I guess custom elements might present problems in a foreach?

Body:
So I want to dynamically generate knockout components from an array of objects with properties.

Here is the html that will generate the components (apologies in advance for the terrible component name):

               <y1vsy2graphs params=" graphTitle: $data.y1Title + ' vs ' +
                                      $data.y2Title,
                                      y1Title: $data.y1Title,
                                      y2Title: $data.y2Title,
                                      tickInterval: $parent.tickInterval(),
                                      y1suffix: '',
                                      y2suffix: '',
                                      graphID: 'red',
                                      filter: $parent.filter(),
                                      selectedOption:
                                      $parent.selectedOption(),
                                      url:
                      Urls.get_ppc_dashboard_values(PageMeta.AccountToken)">
                </y1vsy2graphs>

And here is the array it is looping through in the parent viewModel:

self.graphs = ko.observableArray([
{'y1Title': 'Cost', 'y1Data': self.datas()['Cost'],'y2Title':'ROI', 'y2Data': self.datas()['ROI']},
{'y1Title': 'Clicks','y1Data': self.datas()['Clicks'], 'y2Title': 'CPC', 'y2Data': self.datas()['CPC']},
{'y1Title': 'IMP','y1Data': self.datas()['IMP'], 'y2Title': 'CTR','y2Data':self.datas()['CTR']},
{'y1Title': 'Conv','y1Data': self.datas()['Conv'], 'y2Title': 'CPA', 'y2Data':self.datas()['CPA']},
{'y1Title': 'Conv','y1Data': self.datas()['Conv'],'y2Title': 'RPS', 'y2Data': self.datas()['RPS']}
]);

Currently my code does create the elements as shown in the developer tools:

Developer-Tools:Elements

However I am not receiving any error messages from my y1vsy2graphs component. For that reason i'm having diffuculty identifying my problem.

Body:
Try this:

<div data-bind="foreach: graphs">
  <div data-bind="component: { name: 'y1vsy2graphs',
                               params: {
                                  graphTitle: $data.y1Title + ' vs ' + $data.y2Title,
                                  y1Title: $data.y1Title,
                                  y2Title: $data.y2Title,
                                  tickInterval: $parent.tickInterval(),
                                  y1suffix: '',
                                  y2suffix: '',
                                  graphID: 'red',
                                  filter: $parent.filter(),
                                  selectedOption: $parent.selectedOption(),
                                  url: Urls.get_ppc_dashboard_values(PageMeta.AccountToken)
                                }
                              }">
  </div>
</div>

Basicly the same thing, but I guess custom elements might present problems in a foreach?


问:
Is now the time to start designing for 1280px wide screens instead of 1024px?
Need opinions on this, what do you guys think? A good idea or not so good idea.

I could do a seperate css style but not sure whether to drop 1024 for sure.

答:
I wouldn't drop it just yet. A lot of people still run 1024. I have two monitors at work, both set to 1024. It is a great source of annoyance when websites are too wide for the screen, and if it's really bad, I just don't go back (especially if it's a non-essential site).

As others have said it depends on your target audience. Here in this corporate world I'm in, your 1280 site would be very unpopular with most of the users here. Until there's a mass-upgrade which pushes most of us up to 1280. If there's a way to keep it flexible and work at multiple widths, that is usually best, but I know that can also make things rather difficult.

ContentLicense: CC BY-SA 2.5


问:
SQL query to get value based on some values in fields
I have a MySQL database with a table named generations the structure of the table is as follows

I want to get value 10 as output when ten_generation have value 1 otherwise it will not return any value, 20 as output if twenty_generation have value 1 otherwise it will not return any value, 30 as output if thirty_generation have value 1 otherwise it will not return any value. If all the three fields has a value 1 output will be 10,20,30 also the task_id will provided as the input.

答:
Its unclear what you intend the output to be when multiple generation columns are 1 but one solution is to use a CASE statement:

```<code>SELECT CASE
         WHEN ten_generation    = 1 THEN 10
         WHEN twenty_generation = 1 THEN 20
         WHEN thirty_generation = 1 THEN 30
                                    ELSE NULL
       END AS value
FROM   generations
WHERE  id = :your_id
</code>```

If you want it as multiple columns then:

```<code>SELECT CASE
         WHEN ten_generation = 1
         THEN 10
         ELSE NULL
       END AS ten_value,
       CASE
         WHEN twenty_generation = 1
         THEN 20
         ELSE NULL
       END AS twenty_value,
       CASE
         WHEN thirty_generation = 1
         THEN 30
         ELSE NULL
       END AS thirty_value
FROM   generations
WHERE  id = :your_id
</code>```

if only twenty_generation contain value 1 the output is 20 and if twenty_generation and ten_generation contain value 1 output is 10,20

Oracle Query:

```<code>SELECT TRIM(
         LEADING ',' FROM
         CASE WHEN ten_generation = 1 THEN '10' END
          || CASE WHEN twenty_generation = 1 THEN ',20' END
          || CASE WHEN thirty_generation = 1 THEN ',30' END
       ) AS value
FROM   generations
WHERE  id = :your_id
</code>```

Body:
Its unclear what you intend the output to be when multiple generation columns are 1 but one solution is to use a CASE statement:

SELECT CASE
         WHEN ten_generation    = 1 THEN 10
         WHEN twenty_generation = 1 THEN 20
         WHEN thirty_generation = 1 THEN 30
                                    ELSE NULL
       END AS value
FROM   generations
WHERE  id = :your_id

If you want it as multiple columns then:

SELECT CASE
         WHEN ten_generation = 1
         THEN 10
         ELSE NULL
       END AS ten_value,
       CASE
         WHEN twenty_generation = 1
         THEN 20
         ELSE NULL
       END AS twenty_value,
       CASE
         WHEN thirty_generation = 1
         THEN 30
         ELSE NULL
       END AS thirty_value
FROM   generations
WHERE  id = :your_id

if only twenty_generation contain value 1 the output is 20 and if twenty_generation and ten_generation contain value 1 output is 10,20

Oracle Query:

SELECT TRIM(
         LEADING ',' FROM
         CASE WHEN ten_generation = 1 THEN '10' END
          || CASE WHEN twenty_generation = 1 THEN ',20' END
          || CASE WHEN thirty_generation = 1 THEN ',30' END
       ) AS value
FROM   generations
WHERE  id = :your_id


问:
Export LDAP entries from 389 Directory Server?
Can someone tell me the best way to export entries (user information, their groups and roles, etc) from 389 Directory Server so it can be best imported into a different LDAP server?  Do these files follow some standard format?  Is there a general best practice to doing this?

Thanks!

答:
With the command line below you can export to LDIF format, that you can then import into another server:</p>

```<code>db2ldif -s 'dc=example,dc=com' -a /tmp/ldifdump.ldif  -m -E -q
</code>```

Body:
With the command line below you can export to LDIF format, that you can then import into another server:

db2ldif -s 'dc=example,dc=com' -a /tmp/ldifdump.ldif  -m -E -q


问:
How do I execute a sed command from a Bash variable?
I have a sed command that works when executed directly.

```<code>echo foo > /home/user/bar
sed -i 's/foo/zoo/' /home/user/bar
</code>```

It also works when directly embedded in $(...) or `...`.

However, if I try to execute it from a Bash variable, I get an error:

```<code>CMD="sed -i 's/foo/zoo/' /home/user/bar"
$CMD
</code>```

Error:

sed: -e expression #1, char 1: unknown command: `''

It also works if I echo it out and source the file:

```<code>echo $CMD > file
source file
</code>```

What's going on here, and how do I get the sed command to run from a Bash variable?

答:
use eval : I am not sure why you want to do it. Note that using eval is a fragil solution and can cause your script to broke.

```<code>eval $CMD
</code>```

Body:
I have a sed command that works when executed directly.

echo foo > /home/user/bar
sed -i 's/foo/zoo/' /home/user/bar

It also works when directly embedded in $(...) or `...`.

However, if I try to execute it from a Bash variable, I get an error:

CMD="sed -i 's/foo/zoo/' /home/user/bar"
$CMD

Error:

sed: -e expression #1, char 1: unknown command: `''

It also works if I echo it out and source the file:

echo $CMD > file
source file

What's going on here, and how do I get the sed command to run from a Bash variable?

Body:
use eval : I am not sure why you want to do it. Note that using eval is a fragil solution and can cause your script to broke.

eval $CMD


问:
Can you install an Ad-Hoc iPad distribution on an iPad emulator?
Can you install an Ad-Hoc iPad distribution on an iPad emulator?

Update: Please see: iOS Question. Can I distribute the Xcode simulator versions of my app?

答:
This answer basically gives the ability to distribute an emulator version of the application (tackles the main requirement of my question.):

iOS Question. Can I distribute the Xcode simulator versions of my app?


问:
Detecting if iOS app is run in debugger
I set up my application to either send debugging output to console or a log file. Now, I'd like to decide with in the code whether

it is run in the debugger (or simulator) and have thus a console window where I would like to read the output directly or if

there is no console window and thus, the output should be redirected to a file.

Is there a way to determine if the app runs in the debugger?

答:
The simplest solution actually is

```<code>_isDebugging = isatty(STDERR_FILENO);
</code>```

It isn't exactly the same as telling whether the app is running under debugger, but good enough (even better?) to determine whether the log should be written to disk.

Title: Detecting if iOS app is run in debugger

Body:
The simplest solution actually is

_isDebugging = isatty(STDERR_FILENO);

It isn't exactly the same as telling whether the app is running under debugger, but good enough (even better?) to determine whether the log should be written to disk.


问:
Stop alloy build from a build config task (alloy.jmk)
Let's say I have the following task modifying my Alloy compile process (alloy.jmk build configuration file)

```<code>task("pre:compile", function (e, log) {

    // execute something that may throw an error
    try {
        // ...
    }
    catch(err) {
        // do some custom error handling
        // ...
        // !!! need to stop the build here !!!
    }

    log.info("My task completed!");
});
</code>```

How can I stop the build in the catch-clause? Of course I could just remove the try-catch but then my custom error handling won't be executed...

答:
Well, answering my own question here... It seems it was too easy ... Simply throw a custom error inside the catch-statement like so</p>

```<code>task("pre:compile", function (e, log) {

    // execute something that may throw an error
    try {
        // ...
    }
    catch(err) {
        // do some custom error handling
        // ...
        throw('throwing some error to stop the build');
    }

    log.info("My task completed!");
});
</code>```

Body:
Let's say I have the following task modifying my Alloy compile process (alloy.jmk build configuration file)

task("pre:compile", function (e, log) {

    // execute something that may throw an error
    try {
        // ...
    }
    catch(err) {
        // do some custom error handling
        // ...
        // !!! need to stop the build here !!!
    }

    log.info("My task completed!");
});

How can I stop the build in the catch-clause? Of course I could just remove the try-catch but then my custom error handling won't be executed...

Body:
Well, answering my own question here... It seems it was too easy ... Simply throw a custom error inside the catch-statement like so

task("pre:compile", function (e, log) {

    // execute something that may throw an error
    try {
        // ...
    }
    catch(err) {
        // do some custom error handling
        // ...
        throw('throwing some error to stop the build');
    }

    log.info("My task completed!");
});


问:
get data as pfiles within kernel module code in solaris
When I execute on solaris 11.0:

```<code>pfiles /proc/PROCESSID
</code>```

The result is process information, a small chunk of output is what interest me:

```<code> 4: S_IFSOCK mode:0666 dev:543,0 ino:46228 uid:0 gid:0 size:0
  O_RDWR|O_NONBLOCK
    SOCK_STREAM
    SO_REUSEADDR,SO_KEEPALIVE,SO_SNDBUF(49152),SO_RCVBUF(128480)
    sockname: AF_INET6 ::ffff:10.10.50.28  port: 22
    peername: AF_INET6 ::ffff:10.16.6.150  port: 55504
</code>```

The process I pfiles /proc/PROCESSID is the sshd session itself.

My question is given a process id, how can i get this (pfiles) information from within a kernel code ?

When looking in struct proc i could not find something that give me this data.

Is there a pointer to struct that hold all open files occupied by the process on the proccess' proc?

I also executed truss pfiles /proc/PROCESSID but could not find the exact call

答:
If you look in /usr/include/sys/user.h you'll see the open file information can be found in the p_user.u_finfo structure of the current process.

Walking that structure is not trivial.  Just look at what the proc filesystem code has to do to look up the attributes of just one open file descriptor.  There's lots of locking needed - you can't simply walk the data structures while things are running.

And, the following is beyond the scope of the question, but it's important...

For what it's worth, what you're doing can't work.  It's fundamentally flawed - technically and legally.

What you're trying to do - track users who share a user account - is worthless anyway.  You will never be able to prove that just because a certain login session executed some code that the code was executed because the user logged into that session purposely ran that code.  Because any of the users with access to that account can modify the environment of the shared account such that malware is run by someone else.  And they can make it look just like a typed-in command.

Shared credentials and accounts violate nonrepudiation.  That's your insurmountable legal flaw in using any data your custom kernel tracking may produce - even if you manage to produce a system that's foolproof, which isn't likely.

If I'm logged into a shared account, you can never prove that the code I ran was run intentionally.

Well, that's not entirely true - if you have perfect auditing where you can trace every thing a user does down to the bytes modified on disk, you can.  And "perfect" in this case means those users have no access whatsoever to change any part of the auditing system.

But if you already have perfect auditing in place, you don't need to write kernel modules to try and implement it.

Of course, it's impossible to prove you have perfect auditing in place because you can't prove that you don't have holes in it.

See the problem?

We're right back to "You CAN'T prove I did it intentionally."

You'd be much better off just using the OS-provided auditing services.  Whatever you come up with isn't going to be useful in proving "who did it" for any intelligent bad actor - like someone who figures out a way to insert malicious code into another user's session.  And the OS auditing will be sufficient to catch anyone who has no clue in how to cover their tracks.

But you won't be able to provably catch any bad actor who knows what he's doing when shared accounts are involved.  And if you can't prove it, you might not even be able to do anything at all to someone you suspect.  Because someone who really knows what they're doing will be able to pin the apparent blame on someone who's innocent - if they can't hide or destroy the evidence of the bad act[s] in the first place.

What are you going to do if you find the shared .profile file has a line in it that after a certain date emails sensitive data to a throwaway email account, but only when the login comes from a certain IP address?

Any one of the users who share that one account could have put it in there.

No auditing system in the world can solve that problem unless it's perfect and tracks every file change.

If the data you're trying to protect is important, whoever is tasking you to solve the problem by writing custom kernel modules needs to grow a brain and solve the real problem - shared user accounts.  Get rid of them.

There's a reason why every security guide says not to use shared accounts, and every security audit I've ever seen will fail anyone using shared accounts.

Body:
When I execute on solaris 11.0:

pfiles /proc/PROCESSID

The result is process information, a small chunk of output is what interest me:

 4: S_IFSOCK mode:0666 dev:543,0 ino:46228 uid:0 gid:0 size:0
  O_RDWR|O_NONBLOCK
    SOCK_STREAM
    SO_REUSEADDR,SO_KEEPALIVE,SO_SNDBUF(49152),SO_RCVBUF(128480)
    sockname: AF_INET6 ::ffff:10.10.50.28  port: 22
    peername: AF_INET6 ::ffff:10.16.6.150  port: 55504

The process I pfiles /proc/PROCESSID is the sshd session itself.

My question is given a process id, how can i get this (pfiles) information from within a kernel code ?

When looking in struct proc i could not find something that give me this data.

Is there a pointer to struct that hold all open files occupied by the process on the proccess' proc?

I also executed truss pfiles /proc/PROCESSID but could not find the exact call


问:
docker stack deploy from private repo
Does anyone know how to specify username / password for pulling images from a private registry during a docker stack deploy? I want to be able to do this in one command:

```<code>docker stack deploy --compose-file docker-compose.yml --username <user> --password <pass> mystack
</code>```

Without this, I first have to do a

```<code>docker login -u <user> -p <pass> <registry-url>
</code>```

Can this be done in one command?

答:
This worked for me, I had a private repo on dockerhub

```<code>docker login -u <<UserName>> -p <<Password>>
registry.hub.docker.com/<<Repo_Name>>
&& docker stack deploy -c docker-swarm.yml mystack --with-registry-auth
</code>```

The key is to pass Username Password along with registry name and then followed it up with this flag --with-registry-auth

Here is the  link  which provides step by step information.

Title: docker stack deploy from private repo

Body:
Does anyone know how to specify username / password for pulling images from a private registry during a docker stack deploy? I want to be able to do this in one command:

docker stack deploy --compose-file docker-compose.yml --username <user> --password <pass> mystack

Without this, I first have to do a

docker login -u <user> -p <pass> <registry-url>

Can this be done in one command?

Body:
This worked for me, I had a private repo on dockerhub

docker login -u <<UserName>> -p <<Password>>
registry.hub.docker.com/<<Repo_Name>>
&& docker stack deploy -c docker-swarm.yml mystack --with-registry-auth

The key is to pass Username Password along with registry name and then followed it up with this flag --with-registry-auth

Here is the  link  which provides step by step information.


答:
I see where you're coming from, and I think we're getting close.  But I wouldn't do a blanket drop on 1024 just yet.  It depends on your audience, really.  A lot of conference room projectors still max at 1024, a lot of older web surfers still keep it at 1024 because it's easier to read, a lot of smaller devices with "full web browsers" still run at 1024 (or something close to it).

It's really a weighted decision, for any individual project, between the target audience and the effect in user experience of a horizontal scroll (or unexpected wrapping).

Title: Is now the time to start designing for 1280px wide screens instead of 1024px?

Body:
Need opinions on this, what do you guys think? A good idea or not so good idea.

I could do a seperate css style but not sure whether to drop 1024 for sure.


问:
WPF: User Control access Style via Dependency Property
I have created a Style for a Button with an Image:

```<code>    <Style x:Key="StyleButtonBase" TargetType="Button">
    <Style.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="../Sizes/Sizes.xaml" />
                <ResourceDictionary Source="../Colors/Brushes.xaml" />
                <ResourceDictionary Source="../Fonts/Fonts.xaml" />
                <ResourceDictionary Source="../Images/Images.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Style.Resources>
    <Setter Property="Background" Value="{StaticResource BrushButtonActive}" />
    <Setter Property="Foreground" Value="{StaticResource BrushForegroundLight}" />
    <Setter Property="FontFamily" Value="{StaticResource FontFamilyDefault}" />
    <Setter Property="FontSize" Value="{StaticResource DoubleFontSizeStandard}" />
    <Setter Property="Cursor" Value="Hand" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border
                    Background="{TemplateBinding Background}"
                    BorderBrush="{StaticResource BrushBorder}"
                    BorderThickness="{StaticResource ThicknessBorder}"
                    CornerRadius="{StaticResource CornerRadius}">
                    <Image Source="{StaticResource IconIcon}" Stretch="None" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="Background" Value="{StaticResource BrushButtonPressed}" />
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

Now I Want to create a User-Control which only consists of a Button with this style and a Dependency Property to set the Button Image. The XAML part of my user control looks like this:

```<code><UserControl
x:Class="HH.HMI.ToolSuite.ResourceLib.Controls.ButtonSmall">

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="../Styles/Buttons.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

<Button Style="{StaticResource StyleButtonBase}" Width="{StaticResource DoubleWidthButtonSmall}" Height="{StaticResource DoubleHeightControls}">
</Button></UserControl>
</code>```

The code behind of my user-control looks like this:

```<code>public partial class ButtonSmall : UserControl, INotifyPropertyChanged
{
    public ButtonSmall()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty ButtonImageProperty
        = DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(TextOutput), new PropertyMetadata(null, OnButtonImagePropertyChanged));

    private static void OnButtonImagePropertyChanged(DependencyObject dependencyObject,
           DependencyPropertyChangedEventArgs e)
    {
        ButtonSmall temp = dependencyObject as ButtonSmall;
        temp.OnPropertyChanged("ButtonImage");
        temp.OnButtonImagePropertyChanged(e);
    }

    private void OnButtonImagePropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        ButtonSmallImage.Source = ButtonImageSource;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public ImageSource ButtonImageSource
    {
        get { return (ImageSource)GetValue(ButtonImageProperty); }
        set { SetValue(ButtonImageProperty, value); }
    }
}
</code>```

In my other user-controls i usually access an element in the user control itself like:

```<code>xamlname.text = text
</code>```

Now i haven't a named element in my xaml code of the user-control. Instead i have the named element in the style, which i reference in the user control. How can access this throug my code behind?

答:
If I were you I'd subclass Button and create a new class (just a .cs file) like so:

```<code>using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace MyProject
{
    public class IconButton : Button
    {
        public static readonly DependencyProperty ButtonImageProperty = DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(IconButton),
                  new FrameworkPropertyMetadata(new BitmapImage(), FrameworkPropertyMetadataOptions.AffectsRender));

        public ImageSource ButtonImage
        {
            get { return (ImageSource)GetValue(ButtonImageProperty); }
            set { SetValue(ButtonImageProperty, value); }
        }
    }
}
</code>```

This means you can now reference the property. Otherwise, because your button is just a regular button (with only a regular button's properties; no image), your style doesn't know about your new image property which it expects a Button to have. Don't forget to update your style's TargetType's to point to IconButton.

If you place your style in the resources section of your User Control, you can set the button style like so:

```<code><UserControl x:Class="MyProject.MyControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myclass="clr-namespace:MyProject">
   <UserControl.Resources>
      <!-- your style here -->
   </UserControl.Resources>
   <myclass:IconButton Style="{StaticResource StyleButtonBase}/>
</UserControl>
</code>```

(The xmlns 'myclass' must be replaced to refer to the namespace your custom button is in!)

Also, if you remove the x:Key property from the style, it will apply to all buttons in scope, meaning you can omit setting it explicitly. This may be handy if you locate it in a shared ResourceDictionary (if you're building a library of custom controls for example) (if you do this, you will need to combine this resource dictionary in your App.xaml.cs file). If you end up doing that and you discover your UserControl doesn't have any especial functionality beyond wrapping an IconButton, you can of course omit it entirely and just use IconButtons directly in other controls. Your style declares how your IconButton looks, and your IconButton class ensures that the resources (your image) your style expects are there when it looks for them at runtime, so as long as your style is in scope, you're good to go.

Body:
I have created a Style for a Button with an Image:

    <Setter Property="Background" Value="{StaticResource BrushButtonActive}" />
    <Setter Property="Foreground" Value="{StaticResource BrushForegroundLight}" />
    <Setter Property="FontFamily" Value="{StaticResource FontFamilyDefault}" />
    <Setter Property="FontSize" Value="{StaticResource DoubleFontSizeStandard}" />
    <Setter Property="Cursor" Value="Hand" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border
                    Background="{TemplateBinding Background}"
                    BorderBrush="{StaticResource BrushBorder}"
                    BorderThickness="{StaticResource ThicknessBorder}"
                    CornerRadius="{StaticResource CornerRadius}">
                    <Image Source="{StaticResource IconIcon}" Stretch="None" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

</Style>

Now I Want to create a User-Control which only consists of a Button with this style and a Dependency Property to set the Button Image. The XAML part of my user control looks like this:

<UserControl
x:Class="HH.HMI.ToolSuite.ResourceLib.Controls.ButtonSmall">

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="../Styles/Buttons.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

<Button Style="{StaticResource StyleButtonBase}" Width="{StaticResource DoubleWidthButtonSmall}" Height="{StaticResource DoubleHeightControls}">
</Button></UserControl>

The code behind of my user-control looks like this:

public partial class ButtonSmall : UserControl, INotifyPropertyChanged
{
    public ButtonSmall()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty ButtonImageProperty
        = DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(TextOutput), new PropertyMetadata(null, OnButtonImagePropertyChanged));

    private static void OnButtonImagePropertyChanged(DependencyObject dependencyObject,
           DependencyPropertyChangedEventArgs e)
    {
        ButtonSmall temp = dependencyObject as ButtonSmall;
        temp.OnPropertyChanged("ButtonImage");
        temp.OnButtonImagePropertyChanged(e);
    }

    private void OnButtonImagePropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        ButtonSmallImage.Source = ButtonImageSource;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public ImageSource ButtonImageSource
    {
        get { return (ImageSource)GetValue(ButtonImageProperty); }
        set { SetValue(ButtonImageProperty, value); }
    }
}

In my other user-controls i usually access an element in the user control itself like:

xamlname.text = text

Now i haven't a named element in my xaml code of the user-control. Instead i have the named element in the style, which i reference in the user control. How can access this throug my code behind?

Body:
If I were you I'd subclass Button and create a new class (just a .cs file) like so:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace MyProject
{
    public class IconButton : Button
    {
        public static readonly DependencyProperty ButtonImageProperty = DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(IconButton),
                  new FrameworkPropertyMetadata(new BitmapImage(), FrameworkPropertyMetadataOptions.AffectsRender));

        public ImageSource ButtonImage
        {
            get { return (ImageSource)GetValue(ButtonImageProperty); }
            set { SetValue(ButtonImageProperty, value); }
        }
    }
}

This means you can now reference the property. Otherwise, because your button is just a regular button (with only a regular button's properties; no image), your style doesn't know about your new image property which it expects a Button to have. Don't forget to update your style's TargetType's to point to IconButton.

If you place your style in the resources section of your User Control, you can set the button style like so:

<UserControl x:Class="MyProject.MyControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myclass="clr-namespace:MyProject">
   <UserControl.Resources>
      <!-- your style here -->
   </UserControl.Resources>
   <myclass:IconButton Style="{StaticResource StyleButtonBase}/>
</UserControl>

(The xmlns 'myclass' must be replaced to refer to the namespace your custom button is in!)

Also, if you remove the x:Key property from the style, it will apply to all buttons in scope, meaning you can omit setting it explicitly. This may be handy if you locate it in a shared ResourceDictionary (if you're building a library of custom controls for example) (if you do this, you will need to combine this resource dictionary in your App.xaml.cs file). If you end up doing that and you discover your UserControl doesn't have any especial functionality beyond wrapping an IconButton, you can of course omit it entirely and just use IconButtons directly in other controls. Your style declares how your IconButton looks, and your IconButton class ensures that the resources (your image) your style expects are there when it looks for them at runtime, so as long as your style is in scope, you're good to go.


问:
Spacing between columns in a table
I have a big problem with the spacing of columns in a table.
Here's what I'd like to get, spacing only between :

Not working with margin, padding  or border:

td {
  padding-left: 7.5px;
  padding-right: 7.5px;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td></td>
<td></td>
<td></td>
<td></td></code>```

Not working with border-spacing:

And if use first-child and last-child, same problem as previous image.

Solution I found, but really dirty:

.spacer {
  width: 15px;
  height: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td></td>
<div id="spacer"></div>
<td></td>
<div id="spacer"></div>
<td></td>
<div id="spacer"></div>
<td></td></code>```

答:
Use border-spacing: 15px 0px to generate only horizontal spacing;

To not display only left and right spacing, you can wrap the table in a div, and set margin: 0px -15px to table. Then, set overflow: hidden; to div how hide extra left and right spacing.

td {
  padding-left: 7.5px;
  padding-right: 7.5px;
  background-color: red;
  height: 40px;
  border: 1px solid green;
  width: 25%;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}

table {
  width: calc(100% + 30px);
  table-layout: fixed;
  border-spacing: 15px 0px;
  background: green;
  margin: 0px -15px;
}

.table-container {
  overflow: hidden;
  width: 400px;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="table-container">
  <table>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </table>
</div></code>```

Title: Spacing between columns in a table

Body:
I have a big problem with the spacing of columns in a table.
Here's what I'd like to get, spacing only between :

Not working with margin, padding  or border:

td {
  padding-left: 7.5px;
  padding-right: 7.5px;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}

Not working with border-spacing:

And if use first-child and last-child, same problem as previous image.

Solution I found, but really dirty:

.spacer {
  width: 15px;
  height: 15px;
}

Body:
Use border-spacing: 15px 0px to generate only horizontal spacing;

To not display only left and right spacing, you can wrap the table in a div, and set margin: 0px -15px to table. Then, set overflow: hidden; to div how hide extra left and right spacing.

td {
  padding-left: 7.5px;
  padding-right: 7.5px;
  background-color: red;
  height: 40px;
  border: 1px solid green;
  width: 25%;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}

table {
  width: calc(100% + 30px);
  table-layout: fixed;
  border-spacing: 15px 0px;
  background: green;
  margin: 0px -15px;
}

.table-container {
  overflow: hidden;
  width: 400px;
  margin: 0 auto;
}

<div class="table-container">
  <table>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </table>
</div>


问:
Error-timeout after 30000ms in Selenium IDE
I want to open a pop up (panel) using ADD button but I am getting time out even with setting- settimeout-30000/600000/1200000 and also using waitforpagetoload function with the same time as I mentioned for settimeout.
Anyone help ?

答: Slow down the speed of your test to run. Probably Selenium doesn't have enough time to catch the element</p>


问:
Input a list of arrays of numbers in h5py
I was trying to input a list of numeric arrays into an HDF5 file using h5py. Consider for example:

```<code>f = h5py.File('tester.hdf5','w')
b = [[1,2][1,2,3]]
</code>```

This throws an error.

```<code>TypeError: Object dtype dtype('O') has no native HDF5 equivalent
</code>```

So I am assuming HDF5 doesn't support this.

Like you can store a list of strings by using a special datatype, is there a way for list of numeric array as well.

H5py store list of list of strings

If not, what are the other suitable ways to store a list like this which I can access later from memory.

Thanks for the help in advance

答:
You could split your list of lists in seperate datasets and store them seperately:

```<code>import h5py
my_list = [[1,2],[1,2,3]]
f = h5py.File('tester.hdf5','w')
grp=f.create_group('list_of_lists')
for i,list in enumerate(my_list):
    grp.create_dataset(str(i),data=list)
</code>```

After doing so, you can slice trough your datasets like before with a little variation:

```<code>In[1]: grp[str(0)][:].tolist()
Out[1]: [1, 2]
In[2]: grp[str(1)][:].tolist()
Out[2]: [1, 2, 3]
</code>```

Body:
I was trying to input a list of numeric arrays into an HDF5 file using h5py. Consider for example:

f = h5py.File('tester.hdf5','w')
b = [[1,2][1,2,3]]

This throws an error.

TypeError: Object dtype dtype('O') has no native HDF5 equivalent

So I am assuming HDF5 doesn't support this.

Like you can store a list of strings by using a special datatype, is there a way for list of numeric array as well.

H5py store list of list of strings

If not, what are the other suitable ways to store a list like this which I can access later from memory.

Thanks for the help in advance

Body:
You could split your list of lists in seperate datasets and store them seperately:

import h5py
my_list = [[1,2],[1,2,3]]
f = h5py.File('tester.hdf5','w')
grp=f.create_group('list_of_lists')
for i,list in enumerate(my_list):
    grp.create_dataset(str(i),data=list)

After doing so, you can slice trough your datasets like before with a little variation:

In[1]: grp[str(0)][:].tolist()
Out[1]: [1, 2]
In[2]: grp[str(1)][:].tolist()
Out[2]: [1, 2, 3]


问:
CMS projects to learn from?
There have been quite a few questions about CMS systems but I wonder if there are any good open-source versions available that support ASP.NET MVC (preferably 2.0) and work well with SQL Server?
I'm not looking for a CMS system to use, although that will probably happen too. I'm looking for a CMS system to learn from! So basically, it should follow the KISS principle.
Yeah, I know about DotNetNuke. It looks okay but it feels like overkill to me. There should be alternatives, right?

And no, I'm not a beginner! My web development skills go back to the time when Internet Explorer was still displaying static pages on a Windows 3.11 system when RAM was still measured in kilobytes and with CompuServe as provider over a 33k6 model phone line. But it never hurts to learn from existing code.

答: There are very few CMS systems based on MVC, as the technology is so new.  The only open source one I am aware of is MyTrip.MVC.  It's pretty basic, so doesn't have all the bells and whistles, but seems well put together.</p>

Title: CMS projects to learn from?


问:
IOS create UIAlertViewController programmatically
I'm working on a ViewController with code (no storyboard). I'm trying to add and AlertController

I have declare propery in .m

```<code>@property (nonatomic, strong) UIAlertController *alertController;
</code>```

And init in loadview method

```<code>//alertviewController
    _alertController = [[UIAlertController alloc]initWithNibName:nil bundle:nil];
</code>```

And call the alertview in viewDidLoad:

```<code>_alertController = [UIAlertController alertControllerWithTitle:@"Error display content" message:@"Error connecting to server, no local database" preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                LandingPageViewController *viewController = [[LandingPageViewController alloc] initWithNibName:nil bundle:nil];
    //            viewController.showNavBarBackButton = YES;
                [[AppDelegate sharedAppDelegate].rootViewController cPushViewController:viewController];
}];
[_alertController addAction:ok];
[self presentViewController:_alertController animated:YES completion:nil];
</code>```

I dont' know why the alert is not showing up. Some thing wrong with my code. How to set up and call alertViewController programmatically?

答:
Create global Alert controller that is accessible in all view controllers using extension.

Create an extension of UIViewController with your function to display alert with required parameter arguments.

```<code>extension UIViewController {

      func displayalert(title:String, message:String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

            alert.dismiss(animated: true, completion: nil)

        })))

        self.present(alert, animated: true, completion: nil)

      }
}
</code>```

Now call this function from your view controller:

```<code>class TestViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.displayalert(title: <String>, message: <String>)
    }
}
</code>```

Body:
I'm working on a ViewController with code (no storyboard). I'm trying to add and AlertController

I have declare propery in .m

@property (nonatomic, strong) UIAlertController *alertController;

And init in loadview method

//alertviewController
    _alertController = [[UIAlertController alloc]initWithNibName:nil bundle:nil];

And call the alertview in viewDidLoad:

_alertController = [UIAlertController alertControllerWithTitle:@"Error display content" message:@"Error connecting to server, no local database" preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                LandingPageViewController *viewController = [[LandingPageViewController alloc] initWithNibName:nil bundle:nil];
    //            viewController.showNavBarBackButton = YES;
                [[AppDelegate sharedAppDelegate].rootViewController cPushViewController:viewController];
}];
[_alertController addAction:ok];
[self presentViewController:_alertController animated:YES completion:nil];

I dont' know why the alert is not showing up. Some thing wrong with my code. How to set up and call alertViewController programmatically?

Body:
Create global Alert controller that is accessible in all view controllers using extension.

Create an extension of UIViewController with your function to display alert with required parameter arguments.

extension UIViewController {

      func displayalert(title:String, message:String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

            alert.dismiss(animated: true, completion: nil)

        })))

        self.present(alert, animated: true, completion: nil)

      }
}

Now call this function from your view controller:

class TestViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.displayalert(title: <String>, message: <String>)
    }
}


问:
jQuery code to get text of children
I am trying to use jQuery to get the text of child elements.

I must be doing something wrong, been working on this for 2 days now.

If someone has a moment to take a look, I would be very grateful!

CODE:

```<code>function generateRemoveSectionDropDown() {
    var dropDown = document.getElementById('RemoveSectionId');
    var agendaDiv = $("[name='agenda-nestable']");
    var agendaSections = $(agendaDiv).find("ol#agenda-root>li");
    for (var i = 0; i < agendaSections.length; i++) {
        var optValue = null;
        var optText = null;
        var section = agendaSections[i];
        var sectionChildren = $(agendaSections[i]).children();
        for (var j = 0; j < sectionChildren.length; j++) {
            alert('The text from child is: ' + sectionChildren[j].text);
            optValue = j;
            optText = sectionChildren[j].text;
        }

        var opt = document.createElement('option');
        opt.value = optValue;
        opt.innerText = optText;
        dropDown.appendChild(opt);
    }
}
</code>```

PLUNK: http://plnkr.co/edit/jLi9epblNAtMbzezcRSY?p=preview (if you click the "Run Method", my code will run)

Note: Updated code.I had been hacking around with it, putting it back in a good state.

答:
use foreach(each) function,

try this below code

```<code> function generateRemoveSectionDropDown() {
        var dropDown = document.getElementById('RemoveSectionId');
        var agendaDiv = $("[name='agenda-nestable']");
        var agendaSections = $(agendaDiv).find("ol#agenda-root>li>div");
         //console.log(agendaSections);

        agendaSections.each(function(  ) {
          console.log( $(this).html() );

              // add your set of code

        });
 }
</code>```

Title: jQuery code to get text of children

Body:
I am trying to use jQuery to get the text of child elements.

I must be doing something wrong, been working on this for 2 days now.

If someone has a moment to take a look, I would be very grateful!

CODE:

function generateRemoveSectionDropDown() {
    var dropDown = document.getElementById('RemoveSectionId');
    var agendaDiv = $("[name='agenda-nestable']");
    var agendaSections = $(agendaDiv).find("ol#agenda-root>li");
    for (var i = 0; i < agendaSections.length; i++) {
        var optValue = null;
        var optText = null;
        var section = agendaSections[i];
        var sectionChildren = $(agendaSections[i]).children();
        for (var j = 0; j < sectionChildren.length; j++) {
            alert('The text from child is: ' + sectionChildren[j].text);
            optValue = j;
            optText = sectionChildren[j].text;
        }

        var opt = document.createElement('option');
        opt.value = optValue;
        opt.innerText = optText;
        dropDown.appendChild(opt);
    }
}

PLUNK: http://plnkr.co/edit/jLi9epblNAtMbzezcRSY?p=preview (if you click the "Run Method", my code will run)

Note: Updated code.I had been hacking around with it, putting it back in a good state.

Body:
use foreach(each) function,

try this below code

 function generateRemoveSectionDropDown() {
        var dropDown = document.getElementById('RemoveSectionId');
        var agendaDiv = $("[name='agenda-nestable']");
        var agendaSections = $(agendaDiv).find("ol#agenda-root>li>div");
         //console.log(agendaSections);

        agendaSections.each(function(  ) {
          console.log( $(this).html() );

              // add your set of code

        });
 }


问:
Laravel display image from path which is in database
So use is uploading a logo and it's path is stored in a database like this:

C:\xampp\htdocs\laravel\public\logo\1496912432.jpg

I am displaying the image like this:

```<code><img class="images" id="image" src="{{$business->image}}" />
</code>```

However I get this error:

```<code>Not allowed to load local resource: file:///C:/xampp/htdocs/laravel/public/logo/1496912432.jpg
</code>```

How can this problem be solved?

//edit

Controller:

```<code>public function image(Request $request) {
    if($request->hasFile('img'))
    {
        $image = Input::file('img');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $path = public_path('logo/' . $filename);
        Image::make($image->getRealPath())->fit(303, 200)->save($path);
        $file = $request->file('img');
        $session = session()->get('key');
        $update_image = Business::find($session);
        $update_image->image = $path;
        $update_image->save();
        return ['url' => url('logo/' . $filename)];
    }
</code>```

答: You want to store all files inside the web root. Because of cross-domain security, you cannot access the file:// domain/protocol from a http protcol. By using Laravel to store and retrieve, it will come from the same host.</p>

Body:
So use is uploading a logo and it's path is stored in a database like this:

C:\xampp\htdocs\laravel\public\logo\1496912432.jpg

I am displaying the image like this:

image}}" />

However I get this error:

Not allowed to load local resource: file:///C:/xampp/htdocs/laravel/public/logo/1496912432.jpg

How can this problem be solved?

//edit

Controller:

public function image(Request $request) {
    if($request->hasFile('img'))
    {
        $image = Input::file('img');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $path = public_path('logo/' . $filename);
        Image::make($image->getRealPath())->fit(303, 200)->save($path);
        $file = $request->file('img');
        $session = session()->get('key');
        $update_image = Business::find($session);
        $update_image->image = $path;
        $update_image->save();
        return ['url' => url('logo/' . $filename)];
    }


问:
Determining if a user input field is empty
I've looked at some of the answers here but for some reason, I can't get this to work. I want the user to grade something and if they input nothing in the required field and press "Grade", I want for it to alert something.

function Script() {
  var G = document.getElementById("gradevalue").value
  if (G == null || G == undefined) {
    window.alert("Please input a grade");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
    <input id="gradevalue" type="text"; size="2"; maxlength="2">
    </label>
<input type="button" value="GRADE!" id="nota" onclick="Script()"></code>```

I'm very new at this, so please don't be too harsh.

答:
I think, you can simply check it like:

```<code>if (!Number(G)) {
   window.alert("Please input a grade");
}
</code>```

this is going to be true if G is null, undefined, '', 0, false and NaN and any strings that are not converted to numbers.

function CheckGrade () {
  var G = document.getElementById("gradevalue").value;
  if(!Number(G)) {
    window.alert("Please input a grade");
  } else {
    //your code here, maybe some othe validation logic
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
<input id="gradevalue" type="number" min="1" max="10"/>
</label>
<input type="button" value="GRADE!" id="nota" onclick="CheckGrade()"></code>```

UPDATE Added a code sample and minor mistakes.

Body:
I've looked at some of the answers here but for some reason, I can't get this to work. I want the user to grade something and if they input nothing in the required field and press "Grade", I want for it to alert something.

function Script() {
  var G = document.getElementById("gradevalue").value
  if (G == null || G == undefined) {
    window.alert("Please input a grade");
  }
}

|Please grade on a scale from 1 to 10 (10 is the best!)
    <input id="gradevalue" type="text"; size="2"; maxlength="2">

<input type="button" value="GRADE!" id="nota" onclick="Script()">

I'm very new at this, so please don't be too harsh.

Body:
I think, you can simply check it like:

if (!Number(G)) {
   window.alert("Please input a grade");
}

this is going to be true if G is null, undefined, '', 0, false and NaN and any strings that are not converted to numbers.

function CheckGrade () {
  var G = document.getElementById("gradevalue").value;
  if(!Number(G)) {
    window.alert("Please input a grade");
  } else {
    //your code here, maybe some othe validation logic
  }
}

<label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
<input id="gradevalue" type="number" min="1" max="10"/>
</label>
<input type="button" value="GRADE!" id="nota" onclick="CheckGrade()">

UPDATE Added a code sample and minor mistakes.


问:
Tinymce custom plugin
A client asked me to make a plugin to insert phone links, I know this can be done through the link plugin but he wants one specifically designed to do this. I already have the plugin with the popup window where you can insert the data you need, here is the code, what I want is to add the same functionality that has the link plugin so when the user clicks over the linked text the content can be edited inside the window manager of my plugin.

This is the code i have so far:

```<code>tinymce.PluginManager.add('phonelink', function(editor, url) {
// Add a button that opens a window
  tinymce.DOM.loadCSS(url + '/css/phonelink.css');
  editor.addButton('phonelink', {
    text: false,
    icon: 'phonelink',
    onclick: function() {
      // Open window
      editor.windowManager.open({
        title: 'Enlace teléfono',
        body: [
          {type: 'textbox', name: 'phone', label: 'Teléfono'},
          {type: 'textbox', name: 'showtext', label: 'Texto a mostrar'},
          {type: 'textbox', name: 'title', label: 'Título'}
        ],
        onsubmit: function(e) {
          // Insert content when the window form is submitted
          editor.insertContent('<a title="' + e.data.title + '" href="tel:+34' + e.data.phone + '">' + e.data.showtext + '</a>');
        }
      });
    }
  });

  // Adds a menu item to the tools menu
  editor.addMenuItem('phonelink', {
    text: 'Teléfono',
    context: 'tools',
    onclick: function() {
      // Open window with a specific url
      editor.windowManager.open({
          title: 'Enlace teléfono',
          body: [
            {type: 'textbox', name: 'phone', label: 'Teléfono'},
            {type: 'textbox', name: 'showtext', label: 'Texto a mostrar'},
            {type: 'textbox', name: 'title', label: 'Título'}
          ],
          onsubmit: function(e) {
            // Insert content when the window form is submitted
            editor.insertContent('<a title="' + e.data.title + '" href="tel:+34' + e.data.phone + '">' + e.data.showtext + '</a>');
          }
      });
    }
  });
});
</code>```

答:
Maybe this will help https://www.tinymce.com/docs-3x/api/dom/class_tinymce.dom.Selection.html/

Add some class, for example, .phonelink for your element. Then with editor.selection.getNode(); you can get the contents of selected element, and if it has desired class, paste its contents into your popup form. Same changes in the submit function.

For better UI experience, you can add an onclick tooltip to your button

```<code>editor.addContextToolbar(
  '.phonelink',
  'phonelink'
);
</code>```

Hope it'll help you.

Title: Tinymce custom plugin

Body:
A client asked me to make a plugin to insert phone links, I know this can be done through the link plugin but he wants one specifically designed to do this. I already have the plugin with the popup window where you can insert the data you need, here is the code, what I want is to add the same functionality that has the link plugin so when the user clicks over the linked text the content can be edited inside the window manager of my plugin.

This is the code i have so far:

tinymce.PluginManager.add('phonelink', function(editor, url) {
// Add a button that opens a window
  tinymce.DOM.loadCSS(url + '/css/phonelink.css');
  editor.addButton('phonelink', {
    text: false,
    icon: 'phonelink',
    onclick: function() {
      // Open window
      editor.windowManager.open({
        title: 'Enlace teléfono',
        body: [
          {type: 'textbox', name: 'phone', label: 'Teléfono'},
          {type: 'textbox', name: 'showtext', label: 'Texto a mostrar'},
          {type: 'textbox', name: 'title', label: 'Título'}
        ],
        onsubmit: function(e) {
          // Insert content when the window form is submitted
          editor.insertContent('' + e.data.showtext + '');
        }
      });
    }
  });

  // Adds a menu item to the tools menu
  editor.addMenuItem('phonelink', {
    text: 'Teléfono',
    context: 'tools',
    onclick: function() {
      // Open window with a specific url
      editor.windowManager.open({
          title: 'Enlace teléfono',
          body: [
            {type: 'textbox', name: 'phone', label: 'Teléfono'},
            {type: 'textbox', name: 'showtext', label: 'Texto a mostrar'},
            {type: 'textbox', name: 'title', label: 'Título'}
          ],
          onsubmit: function(e) {
            // Insert content when the window form is submitted
            editor.insertContent('' + e.data.showtext + '');
          }
      });
    }
  });
});

Body:
Maybe this will help https://www.tinymce.com/docs-3x/api/dom/class_tinymce.dom.Selection.html/

Add some class, for example, .phonelink for your element. Then with editor.selection.getNode(); you can get the contents of selected element, and if it has desired class, paste its contents into your popup form. Same changes in the submit function.

For better UI experience, you can add an onclick tooltip to your button

editor.addContextToolbar(
  '.phonelink',
  'phonelink'
);

Hope it'll help you.


问:
How to prevent Sql-Injection on User-Generated Sql Queries
I have a project (private, ASP.net website, password protected with https) where one of the requirements is that the user be able to enter Sql queries that will directly query the database. I need to be able to allow these queries, while preventing them from doing damage to the database itself, and from accessing or updating data that they shouldn't be able to access/update.

I have come up with the following rules for implementation:

Use a db user that only has permission for Select Table/View and Update Table (thus any other commands like drop/alter/truncate/insert/delete will just not run).

Verify that the statement begins with the words "Select" or "Update"

Verify (using Regex) that there are no instances of semi-colons in the statement that are not surrounded by single-quotes, white space and letters. (The thought here is that the only way that they could include a second query would be to end the first with a semi-colon that is not part of an input string).

Verify (using Regex) that the user has permission to access the tables being queried/updated, included in joins, etc. This includes any subqueries. (Part of the way that this will be accomplished is that the user will be using a set of table names that do not actually exist in the database, part of the query parsing will be to substitute in the correct corresponding table names into the query).

Am I missing anything?

The goal is that the users be able to query/update tables to which they have access in any way that they see fit, and to prevent any accidental or malicious attempts to damage the db. (And since a requirement is that the user generate the sql, I have no way to parametrize the query or sanitize it using any built-in tools that I know of).

答:
You can do a huge amount of damage with an update statement.

I had a project similar to this, and our solution was to walk the user through a very annoying wizard allowing them to make the choices, but the query itself is constructed behind the scenes by the application code. Very laborious to create, but at least we were in control of the code that finally executed.

OwnerDisplayName: Yaakov Ellis

LastEditorDisplayName: Yaakov Ellis

OwnerDisplayName: BradC


问:
Android layout centering in RelativeLayout for custom ListView
I'm really pulling my hair out over this one. Some background. I have a list of items that all have checkboxes next to them. When you deselect a checkbox, a button appears that allows you to delete the item from the list. This seems backwards at first but we only want "selected" items to be eligible for further processing, etc. This is my layout:

```<code><RelativeLayout android:id="@+id/rlBlahBlah"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:minHeight="?android:attr/listPreferredItemHeight"
                xmlns:android="http://schemas.android.com/apk/res/android">
  <CheckBox android:text=""
            android:id="@+id/cbDeleteItem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:focusable="false"
            />
  <TextView android:text=""
            android:id="@+id/tvItemText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="14dip"
            android:paddingLeft="3dip"
            android:paddingRight="3dip"
            android:paddingTop="13dip"
            android:gravity="fill_vertical"
            android:layout_toRightOf="@id/cbDeleteItem"
            />
  <Button android:layout_height="wrap_content"
          android:id="@+id/btnDelete"
          android:text="Delete"
          android:layout_width="wrap_content"
          android:layout_alignParentRight="true"
          android:gravity="center_vertical"
          android:focusable="false"
          />
</RelativeLayout>
</code>```

I cannot get the 3 items to center vertically in my row to save my life. layout_gravity, gravity, layout_centerVertical, none of it works. I'm sure my issue is some tiny setting to flip somewhere, but I'm really at wits end on this.

edit: I know the textview is "fill_vertical", that's some random stuff I was trying.

答:
Using RelativeLayout, I had no luck with gravity nor layout_gravity.

But android:layout_centerVertical="true" worked for me positioned in the child of my RelativeLayout, so you can keep it if you need.

Body:
I'm really pulling my hair out over this one. Some background. I have a list of items that all have checkboxes next to them. When you deselect a checkbox, a button appears that allows you to delete the item from the list. This seems backwards at first but we only want "selected" items to be eligible for further processing, etc. This is my layout:

<RelativeLayout android:id="@+id/rlBlahBlah"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:minHeight="?android:attr/listPreferredItemHeight"
                xmlns:android="http://schemas.android.com/apk/res/android">
  <CheckBox android:text=""
            android:id="@+id/cbDeleteItem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:focusable="false"
            />
  <TextView android:text=""
            android:id="@+id/tvItemText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="14dip"
            android:paddingLeft="3dip"
            android:paddingRight="3dip"
            android:paddingTop="13dip"
            android:gravity="fill_vertical"
            android:layout_toRightOf="@id/cbDeleteItem"
            />
  <Button android:layout_height="wrap_content"
          android:id="@+id/btnDelete"
          android:text="Delete"
          android:layout_width="wrap_content"
          android:layout_alignParentRight="true"
          android:gravity="center_vertical"
          android:focusable="false"
          />
</RelativeLayout>

I cannot get the 3 items to center vertically in my row to save my life. layout_gravity, gravity, layout_centerVertical, none of it works. I'm sure my issue is some tiny setting to flip somewhere, but I'm really at wits end on this.

edit: I know the textview is "fill_vertical", that's some random stuff I was trying.


问:
Error: Undefined is not a function - React Native
I created a simple activity where in if you press inside the circular area, the text in it should change accordingly. The app runs well but when I press inside the circular area, I get an error saying "undefined is not a function ( evaluating 'this.setState( {pressing: true});' )     ".
Also, the text inside the circular area should be initially set but it is empty.
You can see the activity here. The code is also provided below:

```<code>import React, { Component } from "react";
import {
  StyleSheet,
  View,
  AppRegistry,
  Text,
  TouchableHighlight
} from "react-native";

class dhrumil extends Component {
  constructor(props) {
    super(props);
    this.state = { pressing: false };
  }
  _inPress() {
    this.setState({ pressing: true });
  }
  _outPress() {
    this.setState({ pressing: false });
  }
  render() {
    return (
      <View style={styles.mainContainer}>
        <TouchableHighlight
          onPressIn={this._inPress}
          onPressOut={this._outPress}
          style={styles.toucher}
        >
          <View style={styles.smallContainer}>
            <Text style={styles.texter}>
              {this.state.pressing ? "EEK" : "PUSH ME"}
            </Text>
          </View>
        </TouchableHighlight>
      </View>
    );
  }
}
var styles = StyleSheet.create({
  mainContainer: {
    flex: 1,
    backgroundColor: "white",
    justifyContent: "center",
    margin: 10,
    alignItems: "center"
  },
  toucher: {
    borderRadius: 100
  },
  smallContainer: {
    backgroundColor: "#ff0000",
    width: 200,
    height: 200,
    borderRadius: 100
  },
  texter: {
    color: "white",
    fontSize: 10,
    fontWeight: "bold"
  }
});

AppRegistry.registerComponent("dhrumil", () => dhrumil);
</code>```

How can I solve this?

答:
The issue is here:

```<code><TouchableHighlight onPressIn={this._inPress}
onPressOut={this._outPress}  style={styles.toucher}>
</code>```

You are setting handlers without fixing the context as the current this.
So when the functions are called setState is not found as this will be different. Use bind.

```<code><TouchableHighlight onPressIn={this._inPress.bind(this)}
   onPressOut={this._outPress.bind(this)}  style={styles.toucher}>
</code>```

Or you can also use arrow function:

```<code> <TouchableHighlight onPressIn={() => this._inPress()}
       onPressOut={() => this._outPress()}  style={styles.toucher}>
</code>```

Body:
I created a simple activity where in if you press inside the circular area, the text in it should change accordingly. The app runs well but when I press inside the circular area, I get an error saying "undefined is not a function ( evaluating 'this.setState( {pressing: true});' )     ".
Also, the text inside the circular area should be initially set but it is empty.
You can see the activity here. The code is also provided below:

import React, { Component } from "react";
import {
  StyleSheet,
  View,
  AppRegistry,
  Text,
  TouchableHighlight
} from "react-native";

class dhrumil extends Component {
  constructor(props) {
    super(props);
    this.state = { pressing: false };
  }
  _inPress() {
    this.setState({ pressing: true });
  }
  _outPress() {
    this.setState({ pressing: false });
  }
  render() {
    return (
      <View style={styles.mainContainer}>
        <TouchableHighlight
          onPressIn={this._inPress}
          onPressOut={this._outPress}
          style={styles.toucher}
        >
          <View style={styles.smallContainer}>
            <Text style={styles.texter}>
              {this.state.pressing ? "EEK" : "PUSH ME"}
            </Text>
          </View>
        </TouchableHighlight>
      </View>
    );
  }
}
var styles = StyleSheet.create({
  mainContainer: {
    flex: 1,
    backgroundColor: "white",
    justifyContent: "center",
    margin: 10,
    alignItems: "center"
  },
  toucher: {
    borderRadius: 100
  },
  smallContainer: {
    backgroundColor: "#ff0000",
    width: 200,
    height: 200,
    borderRadius: 100
  },
  texter: {
    color: "white",
    fontSize: 10,
    fontWeight: "bold"
  }
});

AppRegistry.registerComponent("dhrumil", () => dhrumil);

How can I solve this?

Body:
The issue is here:

<TouchableHighlight onPressIn={this._inPress}
onPressOut={this._outPress}  style={styles.toucher}>

You are setting handlers without fixing the context as the current this.
So when the functions are called setState is not found as this will be different. Use bind.

<TouchableHighlight onPressIn={this._inPress.bind(this)}
   onPressOut={this._outPress.bind(this)}  style={styles.toucher}>

Or you can also use arrow function:

 <TouchableHighlight onPressIn={() => this._inPress()}
       onPressOut={() => this._outPress()}  style={styles.toucher}>


问:
boost library error while using message_queue and shared_memory
I'm using shared_memory and message_queue from the boost library.

A image processing application provides parameter and 3D points in a shared_memory and a gui-application grabs the data out of the memory. The synchronisation works with message_queue's.
It works well in a short run but after a longer perdiod fatal errors occurs and also a restart does not help.
After that it's not possible to create a new shared_memory section or a message_queue. Creating a new message_queue fails with 'BOOST_ASSERT (ptr != 0)'.
A part of the init part looks like the code below (is also not working anymore):

```<code>//initializing default values - VoxelGrid_X
message_queue::remove("param_VX");
message_queue mq_VX(create_only, "param_VX", 1, sizeof(double));
mq_VX.try_send(&parameter_VX, sizeof(parameter_VX), 0);
ui->lineEdit_VX->setPlaceholderText(QString::number(convert_m_mm(parameter_VX)));
</code>```

A part of reading out the parameter in the image-processing app looks like the code below:

```<code>//VoxelGrid: X
                            try {
                                unsigned int priority_VX = NULL;
                                message_queue::size_type recv_size_VX = NULL;
                                message_queue mq_VX(open_only, "param_VX");
                                mq_VX.try_receive(&leafSizeX, sizeof(leafSizeX), recv_size_VX, priority_VX);
                            }
                            catch (interprocess_exception &ex) {

                            }
</code>```

What could be the problem? Does anybody have similar experiences? I would be happy to get hints about possible solutions.

Best regards,
T

答:
I got it ... it's a weird problem, but it in that case is necessary to define the place, where the shared_memory has to be stored.
In my case:

#define BOOST_INTERPROCESS_SHARED_DIR_PATH "C:/Shared_Memory"

Body:
I'm using shared_memory and message_queue from the boost library.

A image processing application provides parameter and 3D points in a shared_memory and a gui-application grabs the data out of the memory. The synchronisation works with message_queue's.
It works well in a short run but after a longer perdiod fatal errors occurs and also a restart does not help.
After that it's not possible to create a new shared_memory section or a message_queue. Creating a new message_queue fails with 'BOOST_ASSERT (ptr != 0)'.
A part of the init part looks like the code below (is also not working anymore):

//initializing default values - VoxelGrid_X
message_queue::remove("param_VX");
message_queue mq_VX(create_only, "param_VX", 1, sizeof(double));
mq_VX.try_send(&parameter_VX, sizeof(parameter_VX), 0);
ui->lineEdit_VX->setPlaceholderText(QString::number(convert_m_mm(parameter_VX)));

A part of reading out the parameter in the image-processing app looks like the code below:

//VoxelGrid: X
                            try {
                                unsigned int priority_VX = NULL;
                                message_queue::size_type recv_size_VX = NULL;
                                message_queue mq_VX(open_only, "param_VX");
                                mq_VX.try_receive(&leafSizeX, sizeof(leafSizeX), recv_size_VX, priority_VX);
                            }
                            catch (interprocess_exception &ex) {

                            }

What could be the problem? Does anybody have similar experiences? I would be happy to get hints about possible solutions.

Best regards,
T


问:
HTML and CSS - banner and background positioning
I am building a simple landing page where the visitor would see a banner, a background image below it and a couple of buttons located vertically beneath each other.

The problem I am experiencing is that, at the moment, both the banner and the background image are starting from the same position (the top left corner of the web page), thus part of the background is hidden by the banner.

The code I currently have is:

```<code><style>
  body {
    background: url("http://url.to/background") no-repeat center center fixed;
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
    padding: 0px;
    margin: 0px;
  }

  #Wrap {
    position: absolute;
  }
</style>

<body>
  <div id="Wrap">
    <img src="http://url.to/banner" />
  </div>
</body>
</code>```

The expected result is to have the banner image take the beginning of the page while fitting into the screen without causing any extra scroll to appear. What is more important is to have the background start after the banner.

A fiddle could be found at the following URL:

https://jsfiddle.net/morL1zka/

Any help or ideas would be appreciated.

答:
You can easyli solve this using JavaScript. The Backgroundposition will be automatically set under the banner, without knowing the height of it.

var body = document.getElementById('body-margin');
var banner = document.getElementById('banner');

body.style.backgroundPositionY = banner.offsetHeight + 'px';```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: url("http://simonakoleva.me/wp-content/themes/hitchcock/images/bg.jpg") no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  margin: 0px;
  padding: 0px;
}

#Wrap {
  background-color: #345370;
  text-align:center;
}</code>```

```

Here is also your updated fiddle: https://jsfiddle.net/morL1zka/2/

Body:
I am building a simple landing page where the visitor would see a banner, a background image below it and a couple of buttons located vertically beneath each other.

The problem I am experiencing is that, at the moment, both the banner and the background image are starting from the same position (the top left corner of the web page), thus part of the background is hidden by the banner.

The code I currently have is:

The expected result is to have the banner image take the beginning of the page while fitting into the screen without causing any extra scroll to appear. What is more important is to have the background start after the banner.

A fiddle could be found at the following URL:

https://jsfiddle.net/morL1zka/

Any help or ideas would be appreciated.

Body:
You can easyli solve this using JavaScript. The Backgroundposition will be automatically set under the banner, without knowing the height of it.

var body = document.getElementById('body-margin');
var banner = document.getElementById('banner');

body.style.backgroundPositionY = banner.offsetHeight + 'px';

body {
  background: url("http://simonakoleva.me/wp-content/themes/hitchcock/images/bg.jpg") no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  margin: 0px;
  padding: 0px;
}

#Wrap {
  background-color: #345370;
  text-align:center;
}

<body id="body-margin">
  <div id="Wrap">
    <img id="banner" src="http://simonakoleva.me/wp-content/uploads/2017/05/mybanner.jpg" />
  </div>
</body>

Here is also your updated fiddle: https://jsfiddle.net/morL1zka/2/


问:
How can I make my html td elements fit to changing window sizes?
```<code>**THIS IS MY HTML**

<div class="table">
<table>
<tr>
<td><a href="otherpage.html">Home</a></td>
<td><a href="otherpage.html">About us</a></td>
<td><a href="otherpage.html">Testimonials</a></td>
<td><a href="otherpage.html">Contact us</a></td>
<tr>
</table>
</div>
</code>```

THIS IS MY CSS

```<code>html,body{
margin:0;
height:100%;
background: linear-gradient(red,pink);
}
.table{
background-color:black;
margin:0;
}
td,a{
padding:25px;
margin:80px;
}
</code>```

When I make the window size smaller, some of the text in td goes to the next line. How to I make that stop?

This is normal:

This is after I reduce window size:

答:
add to ur body width:100% or watever then in ur table specify width and height in percentages
so let say your table need to match the body width and height then you need to add width:100% and height:100% in your css table or whatever percentages you like</p>

Body:
**THIS IS MY HTML**

Home
About us
Testimonials
Contact us

THIS IS MY CSS

html,body{
margin:0;
height:100%;
background: linear-gradient(red,pink);
}
.table{
background-color:black;
margin:0;
}
td,a{
padding:25px;
margin:80px;
}

When I make the window size smaller, some of the text in td goes to the next line. How to I make that stop?

This is normal:

This is after I reduce window size:


问:
Is Jstl tags caches the content
Is jstl tags caches the content, tags like  caches content the between them.

I am using large jsp file, which caches the content between the jstl tags causing a big memory leak.

答:
No, it doesn't. Only the c:set can store stuff in session or application scope, but you have the control fully in your hands.

Did you actually profile the memory leak? You might just have misinterpreted the profiler results.

Title: Is Jstl tags caches the content


问:
Clipboard.Clear - Exception not caught by Try/Catch
I would like to clear the clipboard, however sometimes this is during a loop and a file might still be in the process of copying to the clipboard so calling Clipboard.Clear() raises an exception.

I made the following function to handle this:

```<code>Private Shared Sub ClearClipboard()
    Dim b As Boolean = False
    While b = False
        Try
            Clipboard.Clear()
            b = True
        Catch ex As Exception
        End Try
    End While
End Sub
</code>```

This works fine on my machine running from Visual Studio, however on the client's machine the unhandled exception message pops up.
Why is it not being caught silently there?

Alternatively, if this is not the best way of going about it, how can I check if something is currently being copied to the clipboard and wait until it is finished?
In other words is it possible to check if the clipboard is "busy"?

答:
Thank you Neal!

Looked through that and in the end I can remove the whole loop and Clipboard.SetDataObject("", False, 20, 300) works fine instead of Clipboard.Clear()

Body:
I would like to clear the clipboard, however sometimes this is during a loop and a file might still be in the process of copying to the clipboard so calling Clipboard.Clear() raises an exception.

I made the following function to handle this:

Private Shared Sub ClearClipboard()
    Dim b As Boolean = False
    While b = False
        Try
            Clipboard.Clear()
            b = True
        Catch ex As Exception
        End Try
    End While
End Sub

This works fine on my machine running from Visual Studio, however on the client's machine the unhandled exception message pops up.
Why is it not being caught silently there?

Alternatively, if this is not the best way of going about it, how can I check if something is currently being copied to the clipboard and wait until it is finished?
In other words is it possible to check if the clipboard is "busy"?


问:
How to handle both a promise or variable return from a function
Here is a simplified version of what I have:

```<code>function test(thisBool){
   var response;
   if(thisBool){
      response = makeAPIrequest().then(function(){
      }, function(err){
         console.log(err)
      })
   } else {
      response = "doesntmatter"
   }
}
</code>```

So if the parameter is true, make the api request. If it's false, return the 'doesntmatter' string.

When I call this, I wish to use the response in either instance.

```<code>var testResponseTrue = test(true);
var testResponseFalse = test(false);
</code>```

Is there a way to do this? Or will I have to do some callback functions somehow? I'm not sure of the best way to do this, any advice would help :)

答:
Return a promise for each condition. You already have a promise being returned from your api request method so you can use Promise.resolve() for the default

function makeApiRequest(){
   // fake request ... use your normal method that already returns a prmise
   return new Promise(resolve=>{
     setTimeout(function(){
        resolve('Value from request')
     },500)
   });

}

function test(thisBool){
 return thisBool ? makeApiRequest() : Promise.resolve("Default value")
}

test(false).then(r => {console.log('False value:', r)});
test(true).then(r => {console.log('True value:', r)})```

ContentLicense: CC BY-SA 4.0

Body:
Here is a simplified version of what I have:

function test(thisBool){
   var response;
   if(thisBool){
      response = makeAPIrequest().then(function(){
      }, function(err){
         console.log(err)
      })
   } else {
      response = "doesntmatter"
   }
}

So if the parameter is true, make the api request. If it's false, return the 'doesntmatter' string.

When I call this, I wish to use the response in either instance.

var testResponseTrue = test(true);
var testResponseFalse = test(false);

Is there a way to do this? Or will I have to do some callback functions somehow? I'm not sure of the best way to do this, any advice would help :)


问:
How do I apply border bottom to more than one line of text?
I'm using border-bottom for all the CATs on my website. Great when it a word or two. On trying to apply it to a CTA that's more than a sentence, the words break on mobile and the border-bottom only affects the last line of the sentence. How do I make the border-bottom affect the lines of text? I don't want to use underline for the sake of transition on hover, and the fact that underlines does not give my the 1px border I want.

See images for desktop, mobile and tab here

答:
Try this!

div
{
display:inline;
border-bottom: solid 1px #000
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an
</div></code>```

Body:
Try this!

div
{
display:inline;
border-bottom: solid 1px #000
}

<div>

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an
</div>


问:
YII2 Custom validation is not working with custom function model rule
I am trying to implement with custom function in model its not working i am not getting what's wrong in my code. i am trying to call with basic later i will put my condition.

Here is model code

```<code>public function rules()
    {
        return [
            ['mobile_number', 'required'],
            ['mobile_number', 'myfunction'],

        ];
    }

public function myfunction($attribute,$params)
    {
             $this->addError($attribute, 'You have already submitted');

    }
</code>```

Here is controller code

```<code>public function actionCreate()
    {
        $model = new Createuser();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
</code>```

its not assiging the error to a form-field.

```<code>Thanks in advance.
</code>```

答: Code is fine. it was error with Dynamic Form validation.</p>

Body:
I am trying to implement with custom function in model its not working i am not getting what's wrong in my code. i am trying to call with basic later i will put my condition.

Here is model code

public function rules()
    {
        return [
            ['mobile_number', 'required'],
            ['mobile_number', 'myfunction'],

        ];
    }

public function myfunction($attribute,$params)
    {
             $this->addError($attribute, 'You have already submitted');

    }

Here is controller code

public function actionCreate()
    {
        $model = new Createuser();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

its not assiging the error to a form-field.

Thanks in advance.


问:
October CMS: Error Log in frontend
when I'm updating my backend on the server, an error could occur. If so, an error log will be displayed. Is there a way to hide all the details for the whole world and just display something like: "Error occurred." for the admins?

Thanks for your help.

答:
At the time of writing, October installs with debug mode switched off. You should enable it when in production. Open the PHP file config/app.php and update the debug value to false.

```<code>/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
| You can create a CMS page with route "/error" to set the contents
| of this page. Otherwise a default error page is shown.
|
*/

'debug' => true,
</code>```

This will convert errors to be generic and is recommended by the documentation.

http://octobercms.com/docs/setup/configuration#debug-mode

Important: Always set the app.debug setting to false for production environments.

Title: October CMS: Error Log in frontend

Body:
At the time of writing, October installs with debug mode switched off. You should enable it when in production. Open the PHP file config/app.php and update the debug value to false.

/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
| You can create a CMS page with route "/error" to set the contents
| of this page. Otherwise a default error page is shown.
|
*/

'debug' => true,

This will convert errors to be generic and is recommended by the documentation.

http://octobercms.com/docs/setup/configuration#debug-mode

Important: Always set the app.debug setting to false for production environments.