text:
Q: Can I use multiprocessing.Pool in a method of a class? I am tring to use multiprocessing in my code for better performance.
However, I got an error as follows:
Traceback (most recent call last):
  File "D:\EpubBuilder\TinyEpub.py", line 49, in <module>
    e.epub2txt()
  File "D:\EpubBuilder\TinyEpub.py", line 43, in epub2txt
    tempread = self.get_text()
  File "D:\EpubBuilder\TinyEpub.py", line 29, in get_text
    txtlist = pool.map(self.char2text,charlist)
  File "C:\Python34\lib\multiprocessing\pool.py", line 260, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "C:\Python34\lib\multiprocessing\pool.py", line 599, in get
    raise self._value
  File "C:\Python34\lib\multiprocessing\pool.py", line 383, in _handle_tasks
    put(task)
  File "C:\Python34\lib\multiprocessing\connection.py", line 206, in send
    self._send_bytes(ForkingPickler.dumps(obj))
  File "C:\Python34\lib\multiprocessing\reduction.py", line 50, in dumps
    cls(buf, protocol).dump(obj)
TypeError: cannot serialize '_io.BufferedReader' object

I have tried it an other way and got this error:
TypeError: cannot serialize '_io.TextIOWrapper' object

My code looks like this:
from multiprocessing import Pool
class Book(object):
    def __init__(self, arg):
        self.namelist = arg
    def format_char(self,char):
        char = char + "a"
        return char
    def format_book(self):
        self.tempread = ""
        charlist = [f.read() for f in self.namelist] #list of char
        with Pool() as pool:
            txtlist = pool.map(self.format_char,charlist)
        self.tempread = "".join(txtlist)
        return self.tempread

if __name__ == '__main__':
    import os
    b = Book([open(f) for f in os.listdir()])
    t = b.format_book()
    print(t)

I think that the error is raised because of not using the Pool in the main function.
Is my conjecture right? And how can I modify my code to fix the error?

A: The issue is that you've got an unpicklable instance variable (namelist) in the Book instance. Because you're calling pool.map on an instance method, and you're running on Windows, the entire instance needs to be picklable in order for it to be passed to the child process. Book.namelist is a open file object (_io.BufferedReader), which can't be pickled. You can fix this a couple of ways. Based on the example code, it looks like you could just make format_char a top-level function:
def format_char(char):
    char = char + "a"
    return char

class Book(object):
    def __init__(self, arg):
        self.namelist = arg

    def format_book(self):
        self.tempread = ""
        charlist = [f.read() for f in self.namelist] #list of char
        with Pool() as pool:
            txtlist = pool.map(format_char,charlist)
        self.tempread = "".join(txtlist)
        return self.tempread

However, if in reality, you need format_char to be an instance method, you can use __getstate__/__setstate__ to make Book picklable, by removing the namelist argument from the instance before pickling it:
class Book(object):
    def __init__(self, arg):
        self.namelist = arg

    def __getstate__(self):
        """ This is called before pickling. """
        state = self.__dict__.copy()
        del state['namelist']
        return state

    def __setstate__(self, state):
        """ This is called while unpickling. """
        self.__dict__.update(state)

    def format_char(self,char):
        char = char + "a"

    def format_book(self):
        self.tempread = ""
        charlist = [f.read() for f in self.namelist] #list of char
        with Pool() as pool:
            txtlist = pool.map(self.format_char,charlist)
        self.tempread = "".join(txtlist)
        return self.tempread

This would be ok as long as you don't need to access namelist in the child process.


text:
Q: How to detect where I was clicked before click on submit button I have been facing a problem in my project.
Here in my project I want the position where mouse was clicked after I clicked on facebook upload button.
For example

Here In the image say I was clicked Hello text I want the position of Hello Text after I click on the facebook upload button and add image after the text. Similarly as the Hello Test case. This is where I have been trying
<!doctype html>
getLocale() }}">

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

Medium Editor

            <form action="{{ route('editor') }}" method="post">
                {{ csrf_field() }}

                    <textarea class="form-control textarea" name="description_en" id="description_en" ></textarea>

                <input type="submit" value="submit">
            </form>
            <button id="facebookUpload">Facebook Upload</button>

But this is not working. It is added image at the bottom in all case.
Here is the Example

I didnot find a solution for this. Plz help me. Thank You.

A: Next time, please mention all relevant details about your question. Using a plugin which replaces a <textarea> by a
 is quite important.
There was 2 problems with your attempt:

*

*You can't add an image in a <textarea>. But in a
, yes.

*You won't be able to append anything based on x/y click coordinates. You need to target an element to append something before, after or inside.

So here is a solution, using the event target, to store the clicked element.
You have to check if that target is a
. Because if it's a
, it may be the editor's div... And that would be annoying to append an image after it.
So if it's not the case, keep that element in memory using a variable.
Then on the FB button click, you can append the image.

var editor = new MediumEditor('.editable textarea');

var clickedElement;

$(".medium-editor-element").on("click",function(e){

  // Making sure the click did not occured on the editor itself.
  if(e.target.tagName == "DIV" && $(e.target).hasClass("medium-editor-element")){
    return;
  }

  // Keep that clicked element in memory...
  clickedElement = $(e.target);

});

$("#facebookUpload").on("click",function(){
  if(typeof(clickedElement) != "undefined"){
    // Append an image after the last clicked element, if any.
    clickedElement.after("");
  }
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/medium-editor/5.23.3/css/medium-editor.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/medium-editor/5.23.3/css/themes/beagle.css" rel="stylesheet"/>

Medium Editor

  <form action="" method="post">

      <textarea class="form-control textarea" name="description_en" id="description_en" ></textarea>

    <input type="submit" value="submit">
  </form>
  <button id="facebookUpload">Facebook Upload</button>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to send decimal as a argument in the c# method I have a simple class which has a constructor in this manner:
public Components(int sNo, string componentName, string fileType, **decimal size**, int totalDownloads, string filePath, **decimal price**, string description)

i'm trying to send the arguments by calling this statement:
new DatabaseObjects.Components(1, "CC Cleaner", "exe", **2,84**, 0, @"C:\Users\admin\Desktop\Software_Components\CCCleaner.exe", **5,00**, "To clean up junk files and invalid Registry entries")

But as you can see when i try to send the arguments in this way it is not taking 2,84 as one value it is taking 2 as one argument and 84 as one argument.
and when i try to replace ,with . i mean 2,84 as 2.84
it is saying cannot convert double to decimal.
How can i solve this problem ?
Please help me

A: Use the decimal literal 2.84m.
Plain 2.84 is parsed as a double, which cannot be implicitly converted to a decimal.


text:
Q: Fail to instantiate the chaincode in first network of fabric-samples The official hyperledger fabric v1.0.0 gives a simple demo by using docker.
What i am doing is to avoid docker and directly run them on the machine. Thanks to the answer from my previous question, I have successfully launched 1 solo orderer, two peers (each from one org), created and joined the channels from peers, installed the chaincode on two peers.
The client side's command to install chaincode is
peer chaincode install -n myC1 -v 1.0 -p github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02

Both peers return the following message and I think it should be correct.
2017-09-11 16:34:26.361 SGT [chaincodeCmd] checkChaincodeCmdParams -> INFO 001 Using default escc
2017-09-11 16:34:26.361 SGT [chaincodeCmd] checkChaincodeCmdParams -> INFO 002 Using default vscc
2017-09-11 16:34:26.556 SGT [main] main -> INFO 003 Exiting.....

However, when i try to instantiate the chaincode as follows
peer chaincode instantiate -o orderer.example.com:7040 --tls $CORE_PEER_TLS_ENABLED --cafile $ORDERER_CA -C $CHANNEL_NAME -n myC1 -v 1.0 -c '{"Args":["init","a","100","b","200"]}' -P "OR  ('Org1MSP.member','Org2MSP.member')

Client console returns the error message
2017-09-11 17:00:18.181 SGT [chaincodeCmd] checkChaincodeCmdParams -> INFO 001 Using default escc
2017-09-11 17:00:18.181 SGT [chaincodeCmd] checkChaincodeCmdParams -> INFO 002 Using default vscc
Error: Error endorsing chaincode: rpc error: code = Unknown desc = Failed to init chaincode(handler not found for chaincode myC1:1.0)

The console of Peer0.org2 gives NO error message. But Peer0.org1's console gives the following:
2017-09-11 17:00:18.183 SGT [chaincode] Launch -> ERRO 032 sending init failed(handler not found for chaincode myC1:1.0)
2017-09-11 17:00:18.184 SGT [endorser] simulateProposal -> ERRO 033 failed to invoke chaincode name:"lscc"  on transaction a665c5305c5e3f158d272e4a39b04611e5335406e2a7c7057f11d32d8e07670e, error: Failed to init chaincode(handler not found for chaincode myC1:1.0)

Can any one help me to solve this problem and give me a simple explanation??


text:
Q: How make jQuery UI Dialog be draggable outside of viewpoint too? For now, it's only draggable within viewpoint.

A: You can't do this, it's part of the page/frame it's in.  If this were allowed, you'd see advertisements outside the frame as well :)
If you want to drag it outside of the scrolled view in the page, that's the default behavior, you can test it here.

A: Nick Craver, I think you did not understand me. If you set up a simple div element to be draggable, you could drag it beyond the viewpoint. But that just doesn't work you use the dialog. What ads are you talking about?


text:
Q: File Upload Handling with Pynecone I want to create a file sharing website in with pynecone. Is there a go-to way to upload files and save them on the server?
The documentation says to use React components if there aren't any Pynecone specific components, but I wanted to know if Pynecone can handle files uploads on its own.

A: This is not available yet, but is a high priority feature to add. There is an open ticket here. It should be available soon.


text:
Q: I am getting the following error.Uncaught TypeError: Cannot read property 'files' of undefined $(document).ready(function() {
      const ipfs = window.IpfsApi({
        host: 'ipfs.infura.io',
        port: 5001,
        protocol: 'https'
      });
      const Buffer = window.IpfsApi().Buffer;
      const ContractAddress = "0xf21ac1844861a76754d7c3db29067cb0970fb8b5";
      if (typeof web3 === "undefined") {
        return showError("Please install MetaMask.");
      }
      const contract = web3.eth.contract(Config.getContractABI()).at(ContractAddress);

      function uploadCertificate() {
        //TODO: Write the Logic behind Uploading a Certificate to IPFS and adding the information to the Blockchain
        let filesDiv = $("#certificateForUpload");
        if (filesDiv[0].files.length === 0) {
          return showError("Please select a file.");
        }

        let fileReader = new FileReader();
        fileReader.onload = function() {
          let fileBuffer = Buffer.from(fileReader.result);
          ipfs.files.add(fileBuffer, (err, result) => {
            if (err) {
              return showError(err);
            }

            if (result) {
              let ipfsHash = result[0].hash;
              contract.addCertificate(ipfsHash, function(err, result) {
                if (err) {
                  return showError("There was error with smart contract: $(err)")
                }
                showInfo("Certificate $(ipfsHash) was <b> successfully added.</b> to the Registry.")
              })
            }

          });
        };
        fileReader.readAsArrayBuffer(filesDiv[0].files[0]);

      }


text:
Q: Telebot API Python3 When i start this script in telegram. Script run correct but
            if message2.text.lower() == 'what do you do?':
                bot.send_message(message2.chat.id, 'im learning mode?  ' + message2.chat.first_name +

In this place script cant send message after question 'what do you do?'. Why? whats problem in code?
import telebot

bot = telebot.TeleBot('API')

@bot.message_handler(commands=['tarot'])
def start_message(message):
    bot.send_message(message.chat.id, 'Hello!')

@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text.lower() == 'hi tarot':
        bot.send_message(message.chat.id, 'Hi!  ' + message.chat.first_name + '!')
        @bot.message_handler(content_types=['text'])
        def send2_text(message2):
            if message2.text.lower() == 'what do you do?':
                bot.send_message(message2.chat.id, 'im learning mode?  ' + message2.chat.first_name + '!')

    elif message.text.lower() == 'By':
        bot.send_message(message.chat.id, 'BY!  ' + message.chat.first_name + '!')

bot.polling()

A: I think you want, to allow asking what do you do only if user send hi to bot at any time
import telebot

bot = telebot.TeleBot('API')
hi_ids = []

@bot.message_handler(commands=['tarot'])
def start_message(message):
    bot.send_message(message.chat.id, 'Hello!')

# content_types=['text'] is not required as it default type
@bot.message_handler(func=lambda message: message.text.lower() == 'hi tarot')
def send_hi(message):
    bot.send_message(message.chat.id, f'Hi! {message.chat.first_name}!')
    if message.chat.id not in hi_ids:
        hi_ids.append(message.chat.id)

@bot.message_handler(func=lambda message: message.text.lower() == 'what do you do?' and message.chat.id in hi_ids)
def send2_text(message):
    bot.send_message(message.chat.id, f'I\'m learning mode? {message.chat.first_name}!')

@bot.message_handler(func=lambda message: message.text.lower() == 'by')
def good_buy(message):
    bot.send_message(message.chat.id, f'BY! {message.chat.first_name}!')

bot.infinity_polling(3600, True)  # One hour and ignore net errors

But if you want to allow user to ask what bot is doing right after hi use this code
import telebot

bot = telebot.TeleBot('API')

def second_question(message):
    if message.text is None:
        bot.send_message(message.chat.id, "Nice none text message")
    elif message.text.lower() == 'what do you do?':
        bot.send_message(message.chat.id, f'I\'m learning mode? {message.chat.first_name}!')
    elif message.text.lower() == 'do you like cats?':
        bot.send_message(message.chat.id, 'Sure')

@bot.message_handler(commands=['tarot'])
def start_message(message):
    bot.send_message(message.chat.id, 'Hello!')

# content_types=['text'] is not required as it default type
@bot.message_handler(func=lambda message: message.text.lower() == 'hi tarot')
def send_hi(message):
    bot.register_next_step_handler(bot.send_message(message.chat.id, f'Hi! {message.chat.first_name}!'),
                                   second_question)

@bot.message_handler(func=lambda message: message.text.lower() == 'by')
def good_buy(message):
    bot.send_message(message.chat.id, f'BY! {message.chat.first_name}!')

bot.infinity_polling(3600, True)  # One hour and ignore net errors


text:
Q: R: Scraping the hover text title of every cell in a table using rvest I'm using rvest to scrape data from some javascript tables such as the one here. https://tipping.portadelaidefc.com.au/comp/the-alberton-crowd
As you can see, in this table each cell has a value and also when you hover your mouse over, has another attached value.
I have no problem scraping the table using rvest like so:
tips <- read_html("https://tipping.portadelaidefc.com.au/comp/the-alberton-crowd") %>%
   html_table(header=TRUE)

But I'm not sure how to scrape the hover values. Can I do that with rvest?

A: You could extend/modify the rvest:::html_table.xml_node method as follows:
see R comments
my_html_table <- function(x, header = NA, trim = TRUE, fill = FALSE, dec = ".", attr_name = ""){
  rows <- html_nodes(x, "tr")
  n <- length(rows)
  cells <- lapply(rows, "html_nodes", xpath = ".//td|.//th")
  ncols <- lapply(cells, html_attr, "colspan", default = "1")
  ncols <- lapply(ncols, as.integer)
  p <- unique(vapply(ncols, sum, integer(1)))
  if (length(p) > 1) {
    if (!fill) {
      stop("Table has inconsistent number of columns. ",
           "Do you want fill = TRUE?", call. = FALSE)
    }
    else {
      p <- max(p)
    }
  }
#############################
## The following line is the only one that was changed
#############################
  values <- lapply(cells, html_attr, attr_name)
# insted of
# values <- lapply(cells, html_text, trim = trim)
  out <- matrix(NA_character_, nrow = n, ncol = p)
  for (i in seq_len(n)) {
    row <- values[[i]]
    ncol <- ncols[[i]]
    col <- 1
    for (j in seq_len(p)) {
      if (j > length(row))
        next
      out[i, col] <- row[[j]]
      col <- col + ncol[j]
    }
  }
  if (is.na(header)) {
    header <- all(html_name(cells[[1]]) == "th")
  }
  if (header) {
    col_names <- out[1, , drop = FALSE]
    out <- out[-1, , drop = FALSE]
  } else {
    col_names <- paste0("X", seq_len(ncol(out)))
  }
  df <- lapply(seq_len(p), function(i) {
    utils::type.convert(out[, i], as.is = TRUE, dec = dec)
  })
  names(df) <- col_names
  class(df) <- "data.frame"
  attr(df, "row.names") <- .set_row_names(length(df[[1]]))
  df
}

now you can do something like this to "merge" the original data with the tooltip data
require(rvest)
doc <- read_html("https://tipping.portadelaidefc.com.au/comp/the-alberton-crowd")
x <- doc %>% html_node("table")
tips <- x %>% my_html_table(attr_name = "title")
dat <- doc %>% html_table() %>% `[[`(1)

tips[,c(1,2,28,29)] <- dat[,c(1,2,28,29)]
tips[1:2,] <- dat[1:2,]

which gives you
> head(tips)

                         X1          X2 X3      X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14 X15 X16 X17 X18 X19 X20 X21
1 Leaderboard Select Round:        <NA> NA Overall  1  2  3  4  5   6   7   8   9  10  11  12  13  14  15  16  17
2                      Rank        Name NA         NA NA NA NA NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
3                         1   Gilly2311 NA    <NA> 11 53 42 72 51  41   5  45  20  75  39   3  41  18  13   7  58
4                         2       Harts NA    <NA> 27 50 56 57 53  28  15  32   8  63  51   1  26  23  21   6  87
5                         3 mygypsyrose NA    <NA>  3 49 64 62 35  61   1  37  20  47  53   9  23   0   7  15  38
6                         4 Scraggie_93 NA    <NA> 19 58 81 32 39  31  12  54  35  44  44  17  25  15   7  16  38
  X22 X23 X24 X25 X26 X27    X28   X29
1  18  19  20  21  22  23
2  NA  NA  NA  NA  NA  NA Margin Score
3  74  52  11  62  80  15    888   146
4  46  63  18  51  79   4    865   145
5  48  56  19  12  78  11    748   142
6  48  53   7  21  75  11    782   142

have a look at tips and dat to see their results

A: Or do it with a bit less effort:
library(rvest)
library(dplyr)

pg <- read_html("https://tipping.portadelaidefc.com.au/comp/the-alberton-crowd")
tips <- html_table(pg, header=TRUE)[[1]]

bind_rows(lapply(html_nodes(pg, "tbody > tr"), function(x) {
  cbind.data.frame(t(c(html_text(html_nodes(x, "td"))[2],
                       html_attr(html_nodes(x, "td.tooltip"), "title"))))
}))

##                 1     2     3     4     5     6     7     8     9    10    11    12
##             (chr) (chr) (chr) (chr) (chr) (chr) (chr) (chr) (chr) (chr) (chr) (chr)
## 1       Gilly2311    11    53    42    72    51    41     5    45    20    75    39
## 2           Harts    27    50    56    57    53    28    15    32     8    63    51
## 3     mygypsyrose     3    49    64    62    35    61     1    37    20    47    53
## 4     Scraggie_93    19    58    81    32    39    31    12    54    35    44    44
## 5         Deb1967     4    33    54    60    35    72    21    53    20   118    66
## 6        svolaris     6    52    45    76    50    24    19    45    19    64    58
## 7     dazza power    14    56    61    45    62    54     2    64    60    40    36
## 8  Flamingoflames    28    33    35    83    34    76     1    17     9    83    46
## 9    FEARTHEBEARD    27    34    47    59    50    59     6    50     5    54    38
## 10        Jules23    11    35    57    47    42    65    34    38     4    61    37
## ..            ...   ...   ...   ...   ...   ...   ...   ...   ...   ...   ...   ...
## Variables not shown: 13 (chr), 14 (chr), 15 (chr), 16 (chr), 17 (chr), 18 (chr), 19
##   (chr), 20 (chr), 21 (chr), 22 (chr), 23 (chr), 24 (chr)

renaming the columns, changing column type and cbinding it to the main table is also really straightforward.


text:
Q: Zabbix external checks runs from bash but not from map in admin web console I have a python script which I have placed in /usr/lib/zabbix/externalscripts/ and am able to execute this from bash. I am on a RHEL 7 machine and am on Zabbix 3.x.
When I try to run the script from Monitoring > Maps > Local Network > Click on local zabbix server icon > Select my script name, I get an error stating :

*

*Connection timeout of 60 seconds exceeded when connecting to the zabbix server on "localhost".

*Cannot execute script

I have tried setting a different Timeout value in the zabbix_server.conf but that hasn't fixed this error.
I have attached a screenshot of this error.
Can you help me in troubleshooting this error ?
TIA

A: Bad https proxy setting in python code. Once that was fixed this error got corrected.


text:
Q: Apart from being maxima, minima or inflection point, can a critical point be anything else? Question:
Let $f(x)=\begin{cases} 6, & x\le1\\7-x, & x\gt1\end{cases}$ then for $f(x), x=1$ is
A) a point of local maxima
B) a point of local minima
C) neither a point of local maxima nor minima
D) a stationary point
My Attempt:
The graph of $f(x)$ has a sharp edge at $x=1$. So, it's not a stationary point but a critical point.
Also, $f(1+h)\lt f(1)$, so, $x=1$ is not a point of minima.
And $f(1-h)$ is not less than $f(1)$, so, $x=1$ is not a maxima either. Or is it?
I am confused between A) and C).
If it is indeed C) then what will we call $x=1?$
If a critical point is neither maxima nor minima nor inflection then what is it?

A: Your function $f$ isn't differentiable at $x = 1$. A point $a$ in the domain of the function $f$ is a critical point iff $f'(a) = 0$ (Some people do define a critical point to be a point where either the derivative is zero or the function is not differentiable). In this case:
$$\lim_{x \to 1^-} \frac{f(x)-f(1)}{x-1} = \lim_{x \to 1^-} 0 = 0$$
$$\lim_{x \to 1^+} \frac{f(x)-f(1)}{x-1} = \lim_{x \to 1^-} \frac{1-x}{x-1} = -1$$
Since these two derivatives don't coincide, the function isn't differentiable there. Now, observe that when $x > 1$, we have that $-x < -1$. So, $7-x < 6$. In other words, at $x = 1$, $f$ has a local maximum.
This will depend a little bit on your definition of local maximum. Let $f: I \to \mathbb{R}$ be a function defined on an open interval $I$ and let $a \in I$. Usually, we say that $a$ is a local maximum of $I$ iff there is a $\delta > 0$ such that $(a-\delta,a+\delta) \subseteq I$ and:
$$\forall x \in (a-\delta,a+\delta): f(x) \leq f(a)$$
If you demand that the inequality be strict, then $x = 1$ is not a local maximum and certainly, it isn't a local minimum. You'll have to check your definitions to determine what's the answer in this case.


text:
Q: PHP/Codeigniter processing a list with javascript I have a list of items that the user can select. I want it to be more user friendly than standard checkboxes so I have seperate div's each with a unique id.
When user clicks an item, I use javascript to display a tick on top of that item and change the style to show that it is highlighted.
Im trying to work out how I can pass the list of id's when the form is submitted. Remember, if the user unticks an item, it should be removed from the list, I was thinking of using comma seperated values in a hidden text field but couldnt work out how to remove items from the start of the list if they were deselected

A: Make your style toggling function aslo toggle values in hidden fields.

A: You could store your list of selected items in a javascript array and, like Babiker said, when you toggle your style, also add or remove the element to/from the array. Then when you submit the form write a piece of javascript that plugs the array data into a hidden field.
Also if you're speaking in terms of straight up user friendliness, just a bit of advice I've learned over the years is that people are actually quite used to checkboxes and they provide the highest level of comprehension to the user. It's tried and true. So unless you're shooting for a specific design need I would stick with checkboxes.

A: As already stated, use a javascript array to store toggled list options. Then bind to the submit from event a function that converts the array into a comma separated string (you can use the javascript join() method) and assigns the string to a hidden form field
reference: http://www.w3schools.com/jsref/jsref_join.asp


text:
Q: 12.04 - cannot access wireless at work but can access it at home I'm new to ubuntu, and haven't used UNIX since my college days in the 90s. I just installed 12.04 and, after the update, it attached to my home wireless network just fine.
Unfortunately, at work no such luck.  I tried everything I could think of, and scoured way too many possible answers here and elsewhere.  Still no luck.
When I do a iwconfig at work vs. home and do a diff, here is what I get:
$diff iwconfig_office iwconfig_home
5,6c5,6
< eth1      IEEE 802.11abg  ESSID:off/any
<           Mode:Managed  Access Point: Not-Associated
---
> eth1      IEEE 802.11abg  ESSID:"Evergreen"
>           Mode:Managed  Frequency:2.437 GHz  Access Point: 00:1C:10:8E:D5:89
8c8
<           Power Management:off
---
>           Power Management:on

lspci at home and office are identical.
At the office I have a Motorola 3347 router; at home a Linksys WRT54GS.
At the office I tried 128 bit WEP as well as personal WPA/WPA2.  Neither would connect.
iwlist -scan (note that wyolution2 is the connection I'm trying to use):

eth0      Interface doesn't support scanning.

eth1      Scan completed :
          Cell 01 - Address: 02:21:1E:4B:29:A1
                    Channel:1
                    Frequency:2.412 GHz (Channel 1)
                    Quality=70/70  Signal level=-23 dBm
                    Encryption key:on
                    ESSID:"wyolution2"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                    Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s
                              36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 2660ms ago
                    IE: Unknown: 000A77796F6C7574696F6E32
                    IE: Unknown: 010582848B960C
                    IE: Unknown: 030101
                    IE: Unknown: 2A0107
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : TKIP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK
                    IE: Unknown: 32080C1218243048606C
                    IE: WPA Version 1
                        Group Cipher : TKIP
                        Pairwise Ciphers (1) : TKIP
                        Authentication Suites (1) : PSK
          Cell 02 - Address: 48:F8:B3:55:E0:F6
                    Channel:1
                    Frequency:2.412 GHz (Channel 1)
                    Quality=19/70  Signal level=-91 dBm
                    Encryption key:on
                    ESSID:"County 10"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s
                              24 Mb/s; 36 Mb/s; 54 Mb/s
                    Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 48 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 2660ms ago
                    IE: Unknown: 0009436F756E7479203130
                    IE: Unknown: 010882848B962430486C
                    IE: Unknown: 030101
                    IE: Unknown: 050400010000
                    IE: Unknown: 2A0102
                    IE: Unknown: 2F0102
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : TKIP
                        Pairwise Ciphers (2) : CCMP TKIP
                        Authentication Suites (1) : PSK
                    IE: Unknown: 32040C121860
                    IE: Unknown: 2D1A7C181BFFFF000000000000000000000000000000000000000000
                    IE: Unknown: 3D1601001700000000000000000000000000000000000000
                    IE: Unknown: DD180050F204104A00011010440001021049000600372A000120
                    IE: Unknown: DD090010180201F02C0000
                    IE: WPA Version 1
                        Group Cipher : TKIP
                        Pairwise Ciphers (2) : CCMP TKIP
                        Authentication Suites (1) : PSK
                    IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00
          Cell 03 - Address: 24:DE:C6:AF:8E:C0
                    Channel:1
                    Frequency:2.412 GHz (Channel 1)
                    Quality=40/70  Signal level=-70 dBm
                    Encryption key:on
                    ESSID:"Hotspot_194A"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                              9 Mb/s; 12 Mb/s; 18 Mb/s
                    Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 2660ms ago
                    IE: Unknown: 000C486F7473706F745F31393441
                    IE: Unknown: 010882840B160C121824
                    IE: Unknown: 030101
                    IE: Unknown: 050400010000
                    IE: Unknown: 2A0102
                    IE: Unknown: 32043048606C
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK
                    IE: Unknown: 2D1ACC111BFFFF000000000000000000000000000000000000000000
                    IE: Unknown: 3D16010019000000FF000000000000000000000000000000
                    IE: Unknown: DD1E00904C33CC111BFFFF000000000000000000000000000000000000000000
                    IE: Unknown: DD1A00904C34010019000000FF000000000000000000000000000000
                    IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00
                    IE: Unknown: DD0A00037F04010000000000
          Cell 04 - Address: 24:DE:C6:AF:8E:C1
                    Channel:1
                    Frequency:2.412 GHz (Channel 1)
                    Quality=40/70  Signal level=-70 dBm
                    Encryption key:on
                    ESSID:""
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                              9 Mb/s; 12 Mb/s; 18 Mb/s
                    Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 2660ms ago
                    IE: Unknown: 0000
                    IE: Unknown: 010882840B160C121824
                    IE: Unknown: 030101
                    IE: Unknown: 050400010000
                    IE: Unknown: 2A0102
                    IE: Unknown: 32043048606C
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : 802.1x
                    IE: Unknown: 2D1ACC111BFFFF000000000000000000000000000000000000000000
                    IE: Unknown: 3D16010019000000FF000000000000000000000000000000
                    IE: Unknown: DD1E00904C33CC111BFFFF000000000000000000000000000000000000000000
                    IE: Unknown: DD1A00904C34010019000000FF000000000000000000000000000000
                    IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00
                    IE: Unknown: DD0A00037F04010000000000
          Cell 05 - Address: 00:21:1E:4B:29:A0
                    Channel:1
                    Frequency:2.412 GHz (Channel 1)
                    Quality=70/70  Signal level=-38 dBm
                    Encryption key:on
                    ESSID:"wyolution"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                    Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s
                              36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 2660ms ago
                    IE: Unknown: 000977796F6C7574696F6E
                    IE: Unknown: 010582848B960C
                    IE: Unknown: 030101
                    IE: Unknown: 050C000200000000000000000000
                    IE: Unknown: 2A0107
                    IE: Unknown: 32080C1218243048606C
          Cell 06 - Address: FE:F5:28:44:3C:D8
                    Channel:3
                    Frequency:2.422 GHz (Channel 3)
                    Quality=36/70  Signal level=-74 dBm
                    Encryption key:on
                    ESSID:"Julie"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 9 Mb/s
                              18 Mb/s; 36 Mb/s; 54 Mb/s
                    Bit Rates:6 Mb/s; 12 Mb/s; 24 Mb/s; 48 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 2660ms ago
                    IE: Unknown: 00054A756C6965
                    IE: Unknown: 010882848B961224486C
                    IE: Unknown: 030103
                    IE: Unknown: 32040C183060
                    IE: Unknown: 0706555320010B14
                    IE: Unknown: 33082001020304050607
                    IE: Unknown: 33082105060708090A0B
                    IE: Unknown: DD310050F204104A000110104400010210470010BC329E001DD811B28601FEF528443CD8103C0001011049000600372A000120
                    IE: Unknown: 050400010038
                    IE: Unknown: DD310050F204104A000110104400010210470010BC329E001DD811B28601FEF528443CD8103C0001011049000600372A000120
                    IE: Unknown: 2A0104
                    IE: Unknown: 2D1AEE1117FFFF000001000000000000000000000000000000000000
                    IE: Unknown: 3D1603050000000000000000000000000000000000000000
                    IE: Unknown: 4A0E14000A002C01C800140005001900
                    IE: Unknown: 7F0101
                    IE: WPA Version 1
                        Group Cipher : TKIP
                        Pairwise Ciphers (2) : TKIP CCMP
                        Authentication Suites (1) : PSK
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : TKIP
                        Pairwise Ciphers (2) : TKIP CCMP
                        Authentication Suites (1) : PSK
                    IE: Unknown: DD180050F2020101000003A4000027A4000042435E0062322F00
                    IE: Unknown: 0B0500001B127A
                    IE: Unknown: DD07000C4300000000
          Cell 07 - Address: 00:0F:B3:8A:29:D7
                    Channel:6
                    Frequency:2.437 GHz (Channel 6)
                    Quality=33/70  Signal level=-77 dBm
                    Encryption key:on
                    ESSID:"LightHawk!"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 22 Mb/s
                    Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s
                              36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 2660ms ago
                    IE: Unknown: 000A4C696768744861776B21
                    IE: Unknown: 010582848B962C
                    IE: Unknown: 030106
                    IE: Unknown: 050400020000
                    IE: Unknown: 2A0103
                    IE: Unknown: 32080C1218243048606C
                    IE: WPA Version 1
                        Group Cipher : TKIP
                        Pairwise Ciphers (1) : TKIP
                        Authentication Suites (1) : PSK
          Cell 08 - Address: 9C:D3:6D:C1:AD:35
                    Channel:8
                    Frequency:2.447 GHz (Channel 8)
                    Quality=44/70  Signal level=-66 dBm
                    Encryption key:on
                    ESSID:"NETGEAR14"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s
                              24 Mb/s; 36 Mb/s; 54 Mb/s
                    Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 48 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 2660ms ago
                    IE: Unknown: 00094E4554474541523134
                    IE: Unknown: 010882840B162430486C
                    IE: Unknown: 030108
                    IE: Unknown: 050400020000
                    IE: Unknown: 2A0100
                    IE: Unknown: 2F0100
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK
                    IE: Unknown: 32040C121860
                    IE: Unknown: 2D1AFC181FFFFF000000000000000000000000000000000000000000
                    IE: Unknown: 3D1608001300000000000000000000000000000000000000
                    IE: Unknown: 4A0E14000A002C01C800140005001900
                    IE: Unknown: 7F0101
                    IE: Unknown: DD310050F204104A00011010440001021047001012AEBDACF164EA95D226FB0349BBA2C4103C0001031049000600372A000120
                    IE: Unknown: DD090010180200F0040000
                    IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00
          Cell 09 - Address: 00:1C:10:A6:BB:0A
                    Channel:6
                    Frequency:2.437 GHz (Channel 6)
                    Quality=28/70  Signal level=-82 dBm
                    Encryption key:on
                    ESSID:"LNDRWY0304 Do Not Use"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s
                              24 Mb/s; 36 Mb/s; 54 Mb/s
                    Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 48 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 2660ms ago
                    IE: Unknown: 00154C4E445257593033303420446F204E6F7420557365
                    IE: Unknown: 010882848B962430486C
                    IE: Unknown: 030106
                    IE: Unknown: 050400010002
                    IE: Unknown: 2A0100
                    IE: Unknown: 2F0100
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : TKIP
                        Pairwise Ciphers (2) : CCMP TKIP
                        Authentication Suites (1) : PSK
                    IE: Unknown: 32040C121860
                    IE: Unknown: DD06001018020304
                    IE: WPA Version 1
                        Group Cipher : TKIP
                        Pairwise Ciphers (2) : CCMP TKIP
                        Authentication Suites (1) : PSK
          Cell 10 - Address: 50:3D:E5:30:63:A1
                    Channel:6
                    Frequency:2.437 GHz (Channel 6)
                    Quality=27/70  Signal level=-83 dBm
                    Encryption key:on
                    ESSID:"aissd"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                              9 Mb/s; 12 Mb/s; 18 Mb/s
                    Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 2660ms ago
                    IE: Unknown: 00056169737364
                    IE: Unknown: 010882848B960C121824
                    IE: Unknown: 030106
                    IE: Unknown: 050400010000
                    IE: Unknown: 2A0100
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK
                       Preauthentication Supported
                    IE: Unknown: 32043048606C
                    IE: Unknown: DD180050F2020101840003A4000027A4000042435E0062322F00
                    IE: Unknown: DD1E00904C334C101BFFFF000000000000000000000000000000000000000000
                    IE: Unknown: 2D1A4C101BFFFF000000000000000000000000000000000000000000
                    IE: Unknown: DD1A00904C3406080800000000000000000000000000000000000000
                    IE: Unknown: 3D1606080800000000000000000000000000000000000000
                    IE: Unknown: DD0900037F01010000FF7F
                    IE: Unknown: DD0A00037F04010000000000
          Cell 11 - Address: 00:12:CF:B5:5E:20
                    Channel:11
                    Frequency:2.462 GHz (Channel 11)
                    Quality=39/70  Signal level=-71 dBm
                    Encryption key:on
                    ESSID:"\x00\x00\x00\x00\x00\x00"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                              12 Mb/s; 24 Mb/s; 36 Mb/s
                    Bit Rates:9 Mb/s; 18 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 2660ms ago
                    IE: Unknown: 0006000000000000
                    IE: Unknown: 010882848B960C183048
                    IE: Unknown: 03010B
                    IE: Unknown: 050400010000
                    IE: Unknown: 2A0100
                    IE: Unknown: 32041224606C
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK
                       Preauthentication Supported
                    IE: Unknown: DD180050F2020101000003A4000027A4000042435E0062322F00
          Cell 12 - Address: 00:1F:C4:8D:B1:80
                    Channel:1
                    Frequency:2.412 GHz (Channel 1)
                    Quality=22/70  Signal level=-88 dBm
                    Encryplo        Interface doesn't support scanning.

tion key:on
                    ESSID:"qwest6528"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                    Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s
                              36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 2660ms ago
                    IE: Unknown: 0009717765737436353238
                    IE: Unknown: 010582848B960C
                    IE: Unknown: 030101
                    IE: Unknown: 050C010200000000000000000000
                    IE: Unknown: 2A0107
                    IE: Unknown: 32080C1218243048606C
          Cell 13 - Address: 24:DE:C6:AF:8E:E0
                    Channel:11
                    Frequency:2.462 GHz (Channel 11)
                    Quality=37/70  Signal level=-73 dBm
                    Encryption key:on
                    ESSID:"Hotspot_194A"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                              9 Mb/s; 12 Mb/s; 18 Mb/s
                    Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 2660ms ago
                    IE: Unknown: 000C486F7473706F745F31393441
                    IE: Unknown: 010882840B160C121824
                    IE: Unknown: 03010B
                    IE: Unknown: 050400010000
                    IE: Unknown: 2A0100
                    IE: Unknown: 32043048606C
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK
                    IE: Unknown: 2D1ACC111BFFFF000000000000000000000000000000000000000000
                    IE: Unknown: 3D160B0019000000FF000000000000000000000000000000
                    IE: Unknown: DD1E00904C33CC111BFFFF000000000000000000000000000000000000000000
                    IE: Unknown: DD1A00904C340B0019000000FF000000000000000000000000000000
                    IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00
                    IE: Unknown: DD0A00037F04010000000000

Note:  I have half a dozen devices connected to this wireless access point already, including Android devices, W7 and W8.  In addition, this specific machine had connected to it in the past before being re-purposed as a Ubuntu box.
Any advice would be much appreciated!

A: In case anyone is reading this thread, I wanted to update with a resolution.  I moved my system to 3.10 and wireless WPA/TKIP is working fine.


text:
Q: Images randomly positioned on page I am trying to get lots of .gifs to appear in random positions on the page. I have managed to get the first one to execute this action but for some reason all the ones that come after remain static despite having the same id. The .gifs also have a draggable function.
Can anyone tell me where I've gone wrong?

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" media="all" href="css/style.css">
  <link rel="stylesheet" type="text/css" media="all" href="css/smoothness/jquery-ui-1.10.3.custom.min.css">
  <link rel="stylesheet" type="text/css" media="all" href="http://fonts.googleapis.com/css?family=Cherry+Swash:400,700">

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title></title>

A: You should only use id tags once. Use classes instead, for example:

and
image_Element = document.getElementsByClassName("image");

You'll need to make other changes as well but this should give you the general idea.

A: Since you're using JQuery, you could do something like..
window.onload = Prep();
var window_Height, window_Width;
var changeInterval = 3000;

function Prep(){
  window_Height = $(window).height();
  window_Width = $(window).width();
}

function moveImage(imgEl,space_V,space_H){
  var randNum_V = Math.round(Math.random() * space_V);
  var randNum_H = Math.round(Math.random() * space_H);

  imgEl.style.top = randNum_V + "px";
  imgEl.style.left = randNum_H + "px";
}

$('img').each(function(){
  var img = $(this);
  var image_Height = img.height();
  var image_Width = img.width();
  var availSpace_V = window_Height - image_Height;
  var availSpace_H = window_Width - image_Width;

  setInterval(moveImage(img,availSpace_V,availspace_H),changeInterval);
});

I've shortened your Prep function to just get the window dimensions and changed your moveImage function to have the necessary variables passed as arguments. This way, you can use the function for each image individually.
The JQuery .each targets each img element on the page and executes the moveImage function accordingly. If you want get more specific rather than targeting all image elements, you could just select the ones in the div with id w by doing something like..
$('#w').find('img').each(function(){...

Hope this helps!


text:
Q: Subsonic + Paging question I am trying to do server-side paging with Subsonic. Using the .Paged function works well (the link to the webcast seems to be broken btw). However, how do I go the total number of records from my query (without the .Paged function) i.e. do I need to run a recordcount on the query which returns the full result first? If yes, then it kinda defeits the purpose of server-side paging?
e.g.
SQLQuery q = Select.Allfromcolumns .Paged(1,10), will return 10 records only. However, I need to know the total number of records from Products first to determine my Page links?
For a simple table, there is no need for server-side paging, but my query is very complicated one and I need to use the Paging functionality for performance mainly.
thanks

A: The following will return a count of the total number of records that would be returned so you can build your query, then call GetRecordCount() on it to find how many records will be returned and then call Paged(1, 10) to return the first page:
SqlQuery query = Select.AllColumnsFrom<Product>();
int numberOfRecords = query.GetRecordCount();
List<Product> products = query.Paged(1, 10).ExecuteTypedList<Product>();

A: I would like to point out that typically when someone does "serverside" paging they run a query that returns all rows.  They take a count of the rows (record count) and then they grab the rows they need for displaying to the user and display the subset (Good amount of overhead and processing).  Using the query posted by Adam you will save yourself a lot of that overhead if on the first request you cache the "numberofRecords" and then on each of the subsequent requests you only perform a Paged query which only brings back the wanted rows from the database.

A: SqlQuery query = Select.AllColumnsFrom<Product>();
if(IsfirstCall){//Set firstCall = false on all subsequent calls to the method
int numberOfRecords = query.GetRecordCount(); }
List<Product> products = query.Paged(1, 10).ExecuteTypedList<Product>();


text:
Q: How to pause and resume timer in Google sheets handling time tracker using onEdit function I'm creating a simple time tracker for time and motion study purposes in Google sheets. The current code that I'm using only records start time and end time as shown on the screenshot below.
[Time tracker]
What I would like to do is for it to have the ability to pause the timer and then have the ability to resume anytime.
Below is the current script/code I'm using (Credits to @Cooper who provided me this code in Automatically record start time, end time and total handling time in Google sheets:
function onEdit(e) {
  const sh = e.range.getSheet();
  if (sh.getName() == "Sheet1" && e.range.columnStart == 2 && e.value) {
    e.range.offset(0, 7).setValue(new Date())
  }
  if (sh.getName() == "Sheet1" && e.range.columnStart == 8 && e.value) {
    e.range.offset(0, 2).setValue(new Date());
    let Start = new Date(sh.getRange(e.range.rowStart,8).getValue());
    let End = new Date(sh.getRange(e.range.rowStart,9).getValue());
    sh.getRange(e.range.rowStart,10).setValue(timeDiff1(Start,End));
  }

}

function timeDiff1(Start, End) {
  if (Start && End) {
    var second = 1000;
    var minute = 60 * second;
    var t1 = new Date(Start).valueOf();
    var t2 = new Date(End).valueOf();
    var d = t2 - t1;
    var minutes = Math.floor(d % day % hour / minute);
    var seconds = Math.floor(d % day % hour % minute / second);
    return 'mm:ss\n' + minutes + ':' + seconds;
  }
  else {
    return 'Invalid Inputs';
  }
}

Is this doable or is there an alternative code I can use?


text:
Q: Pandas KeyError: 'occurred at index 0' Let's say I have a Pandas dataframe df:
start_time   Event
0            0
1            0
2            0
3            0
4            0
5            0
6            0
7            0
8            0
9            0

I want to set the value of the Event column to -1 when the corresponding start_time lies between two values, so I define this function:
def test(time):
    if (time['start_time'] >= 5) and (time['start_time'] <= 8):
        return -1
    else:
        return time

To apply this to the event column, I do the following:
df[['Event']] = df[['Event']].apply(test,axis=1)

which yields this error: KeyError: ('start_time', 'occurred at index 0')
Why is this happening? Should be a simple fix.

A: Simply do:
df['Event'] = df.apply(test, axis=1)['Event']

A: The function that you are passing to .apply() uses the start_time field of the input argument (in the conditional checks if (time['start_time'] >= 5) and (time['start_time'] <= 8)). So it should be applied to a DataFrame or Series that has a start_time column.
However, before you call apply you are first calling df[['Event']], which returns a Series. So df[['Event']].apply() will apply a function to the resulting Series. But when the function reaches the expression time['start_time'], it is looking for a column called start_time in the Series, can't find it (because only 'Event' column was kept), and raises a KeyError.
The solution is to pass a DataFrame or a Series that has a start_time column in it. In your case you want to apply the function to the entire DataFrame so replace df[['Event']] with the whole DataFrame df.
df = df.apply(test, axis=1)

and change your function to modify the Event column instead of returning a value. Replace return -1 with time['Event'] = -1 and eliminate the else return time part (i.e., don't change anything if the conditions aren't met).


text:
Q: Cannot add the specified assembly "Microsoft.Practices.ServiceLocation.dll" For a while now, me and my team having been having an issue where when we try and deploy a project we very frequently end up with the error

Error occurred in deployment step 'Add Solution': Error: Cannot add
  the specified assembly to the global assembly cache:
  Microsoft.Practices.ServiceLocation.dll.

We get around this by restarting IIS and once we do the project will deploy fine. But now our project is getting big and deployment take a long time and it is becoming incredibly annoying having to deploy twice.
So, we have decided to tackle this issue and clearly failed. Thus, I have turned to the internet and I'm hoping someone out there might know why this happening and how we can prevent it in the future.

A: I can think of a few things, but try these for starters :

*

*Verify that your development environment and your other SharePoint
servers have the exact same version of the Enterprise Library
installed

*Check each WSP that your team is creating to make sure that it is not bundling an older version of the DLL in your WSPs
Library as well.  You may need to manually inspect each WSP by renaming them to .CAB and then browsing the content in Windows Explorer

*Make sure that you do not have an older copy of that DLL anywhere on your dev machines or on your sharepoint servers.  People are notorious for manually copying troublesome DLLs to the /bin/ or /_app_bin/ of the web application

*If you have other older WSPs that are deployed to that farm make sure that they do not reference and include the older version of the library

*If you have a build server that checks and builds your WSPs then do all of the above on that server as well

*If you are building your Enterprise Library from source, be sure that you have key for it and it is strong-named.

A: I'd recommend that you put:

*

*the Microsoft.Practices dlls into a seperate WSP (MSP.WSP)

*set your WSP to depend on MSP.WSP

*Deploy the MSP.WSP

Now you don't have to retract/deploy these standard dlls every time you deploy you package. And maybe also split you package into smaller WSPs depending on when you need to upgrade them.


text:
Q: python function default parameter is evaluated only once? I am a python beginner, reading 'python tutorial', it says if we have a function:
def f(a, L=[]):
     L.append(a)
     return L
print f(1)
print f(2)
print f(3)

This will print
[1]
[1, 2]
[1, 2, 3]

Because the default value is evaluated only once and list is a mutable object. I can understand it.
And it says continue, if we don't want the default to be shared between subsquent calls, we can:
def f(a, L=None):
   if L is None:           #line  2
       L = []
   L.append(a)
   return L
print f(1)
print f(2)
print f(3)

and this will output:
[1]
[2]
[3]

But why? How to explain this. We know default value is evaluated only once, and when we call f(2), L is not None and that if(in line 2) can not be true, so L.append(a) == [1, 2]. Could I guess the default value is evaluated again for some reason , but what is 'some reason', just because the python interpreter see if L is None: L = []

A: Python passes parameters to functions by value; So for objects, the value passed is a reference to the object, not a new copy of the object.
That, along with the following part of the official docs is what helped me understand it better (emphasis mine):

Default parameter values are evaluated [...] when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same "pre-computed" value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. [...] A way around this is to use None as the default, and explicitly test for it in the body of the function [...]

Putting it all together:
If you define the default for a parameter to be a mutable object (such as []) then the "pre-computed" value is the reference to that object, so each call to the function will always reference the same object, which can then be mutated across multiple invocations of the function.
However, since None is an immutable built-in type, the "pre-computed" value for a default of None is simply that. So the parameter will be None each time you call the function.
Hopefully that helps! I do think that the tutorial could have had better wording, because I was also confused by that at first.

A: In your second example you have a variable L. At first L refers to None. You repoint it to a new empty list on each invocation, then mutate that new list. Remember L = [] is the same as L = list()
In your first example, however, L is set to the new list once at function declaration. L isn't reset to [] on each invocation of the function. So you are always mutating the same list.

A: What happens is as follows:
When a python function is called, it is evaluated in the environment in which it was defined and not the environment in which it was called although the second part is secondary ( no pun intended) for the purpose of answering your question.
The default arguments are evaluated only once at the time of function definition. This creates a closure. Think of closure as function code + environment in which the function was been defined.
So in this case when the function was defined, L was assigned to [] and now every subsequent call to the function will use this value of L.
The tutorial also mentions:
The default values are evaluated at the point of function definition in the defining scope (and the defining scope is part of the closure along with function code)
http://docs.python.org/2/tutorial/controlflow.html#default-argument-values

A: I think this is happening because a list is a mutable object while the value None is immutable.
For the first function, variable L is outside the function environment (in the function definition), and it refers to an empty list. Then you make changes to this list in the function environment, but since a list is mutable, the variable L that is outside the function environment refers to this now mutated list, and the change propagates each time you call the function.
For the second function, variable L is also outside the function environment (in the function definition), but this time it refers to None, which is immutable. Now, every change you make in the function environment will not affect what L refers to outside the function environment. The variable L inside the function environment refers to something different as you change it. First, it refers to an empty list, and then a list that gets a value appended to it. You then return this list. The next time you call the function, you call it with the variable L that is outside the function environment, which has not changed and still refers to None.
Hope this makes sense.

A: "The default value is only evaluated once" does not mean that a parameter with a default retains its value between invocations of the function. It means that the expression which you specify (the None part of def f(a, L=None)) is evaluated once, and the object it results in is stored in a hidden location and re-used if no value for that parameter is given at call. Parameters are still reset to the value (default or not) at every invocation.


text:
Q: Howto Pass A String as Parameter in AWK within Bash Script I have a text file which I want to filter
using awk. The text file looks like this:
foo 1
bar 2
bar 0.3
bar 100
qux 1033

I want to filter those files with awk inside a bash script.
#!/bin/bash

#input file
input=myfile.txt

# I need to pass this as parameter
# cos later I want to make it more general like
# coltype=$1
col1type="foo"

#Filters
awk '$2>0 && $1==$col1type' $input

But somehow it failed. What's the right way to do it?

A: "double quote single quote"

awk '{print "'$1'"}'

example:

$./a.sh arg1
arg1

$cat a.sh
echo "test" | awk '{print "'$1'"}'

linux tested

A: You need double quotes to allow variable interpolation, which means you then need to escape the other dollar signs with backslashes so $1 and $2 are not interpolated. Also you need double quotes around "$col1type".
awk "\$2>0 && \$1==\"$col1type\""

A: Single quotes inhibit variable expansion in bash:
awk '$2>0 && $1=='"$col1type"

A: pass it in using -v option of awk. that way, you separate out awk variables and shell variables. Its neater also without extra quoting.
#!/bin/bash

#input file
input=myfile.txt

# I need to pass this as parameter
# cos later I want to make it more general like
# coltype=$1
col1type="foo"

#Filters
awk -vcoltype="$col1type" '$2>0 && $1==col1type' $input


text:
Q: How to access meta OpenGraph with cheerio? i'm trying to do some html scraping with cheerio (can't use jsdon i have a problem with dependency: the bug with contextify ecc.) but i can't get the meta "og:type" , "og:title"...
request(Url, function(error, response, body) {
var $ = cheerio.load(body);
    $('meta').each(function() {
        console.log(  $('meta').attr('content'));
    });
});

i get only the first metatext/html; charset=UTF-8". do you know how to access to og??

A: Expanding on Herman's answer:
I found the combination of node-crawler + cheerio to be a bit more manageable. The code below makes it a bit easier to track which tag attributes you're searching for, and can easily be tweaked to include other tags.  Here's how I did it:
  var crawler = require('crawler'),
  url = require('url');

  var c = new crawler({
    maxConnections:10,
    callback:function(error,response,$) {
      var data = {
        'og:type':null,
        'og:title':null,
        'og:description':null,
        'og:image':null,
        'twitter:title':null,
        'twitter:image':null,
        'twitter:description':null,
        'twitter:site':null,
        'twitter:creator':null,
      }
      var meta = $('meta');
      var keys = Object.keys(meta);
      for (var s in data) {
        keys.forEach(function(key) {
          if ( meta[key].attribs
            && meta[key].attribs.property
            && meta[key].attribs.property === s) {
              data[s] = meta[key].attribs.content;
          }
        })
      }
      console.log(data);
    }
  })
  c.queue( [ YOUR URL HERE ] )

A: You'll have to play a bit with the keys of the object $('meta) and checking whether the required keys exist or not, to obtain your result.
Try this code:
var cheerio = require('cheerio')
var request = require('request')

request(Url, function(error, response, body) {
  var $ = cheerio.load(body);

  var meta = $('meta')
  var keys = Object.keys(meta)

  var ogType;
  var ogTitle;

  keys.forEach(function(key){
    if (  meta[key].attribs
       && meta[key].attribs.property
       && meta[key].attribs.property === 'og:type') {
      ogType = meta[key].attribs.content;
    }
  });

  keys.forEach(function(key){
    if (  meta[key].attribs
       && meta[key].attribs.property
       && meta[key].attribs.property === 'og:title') {
      ogTitle = meta[key].attribs.content;
    }
  });

  console.log(ogType);
  console.log(ogTitle);
});

A: An simpler solution would be, if you know which property you want to get:
var $ = cheerio.load(html);
var result = $('meta[property="og:title"]').attr('content');

(assuming you want to get the title.)


text:
Q: Cannot set %PATH% in windows from boost::process I have a program which works great on Linux, but fails to preserve some of %PATH% on Windows.  Here's an example:
parent.cpp
#include <boost/process.hpp>

int main()
{
    auto this_env = boost::this_process::environment();
    boost::process::environment env = this_env; // make a copy to avoid changing the orig

    env["TESTVAR"]  = "Test12";   // Confirm we can set a variable
    env["TESTVAR"] += "Test34";   // Confirm we can append
    env["PATH"]    += "C:\\Users\\"; // Confirm we can append to PATH

    boost::process::child c(
        boost::process::exe = "./child.exe",
        boost::process::env = env
    );
    c.wait();
}

child.cpp
#include <boost/process.hpp>
#include <iostream>

int main()
{
    auto env = boost::this_process::environment();

    std::cout << "TESTVAR = " << env["TESTVAR"].to_string() << std::endl
              << "PATH = " << env["PATH"].to_string() << std::endl;
}

Output on Linux (good):
$ g++ parent.cpp -o parent.exe
$ g++ child.cpp  -o child.exe
$ echo PATH = $PATH
PATH = /usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
$ ./parent.exe
TESTVAR = Test12:Test34
PATH = /usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:C:\Users\
                                          PATH is augmented! ~~~~~^

Output on Windows (bad):
$ x86_64-w64-mingw32.static.posix-g++ parent.cpp -o parent.exe -lwsock32 -lboost_filesystem-mt-x64
$ x86_64-w64-mingw32.static.posix-g++ child.cpp  -o child.exe  -lwsock32
$ scp parent.exe child.exe user@windows:
$ ssh user@windows
> echo %PATH%
C:\Windows\system32;C:\Windows;...

> parent.exe
TESTVAR = Test12:Test34
PATH = C:\Users\
        ^~~~ Path is replaced!

Is this a bug in boost::process, a feature of Windows, or is there something wrong with my code?

A: There appears some case-sensitivity in windows environment variables.  By changing child.cpp to this, we can see all environment variables:
#include <boost/process.hpp>
#include <iostream>

int main()
{
    auto env = boost::this_process::environment();

    for (auto it : env )
        std::cout << it.get_name() << " = " << it.to_string() << std::endl;
}

The output contains:
Path = C:\Windows\system32;C:\Windows;...
TESTVAR = Test12;Test34
PATH = C:\Users\

If we change parent.cpp from :
env["PATH"] += "C:\\Users\\";

to
env["Path"] += "C:\\Users\\";

we get the correct output on Windows:
Path = C:\Windows\system32;C:\Windows;...;C:\Users\
TESTVAR = Test12;Test34

While cmd.exe can set/get path insensitively (SET PATH=%PATH%;C:\\Users\\), the API used by boost is case-sensitive.  Strange!


text:
Q: Filter data inside array and returns object filtered with group I have an object like this and I need to filter the rules within each group item, however I need to also return the group name next to the filtered rule
{
  "id": "rulesCompany",
  "group": [
    {
      "name": "Cadastral",
      "rule": [
        {
          "title": "Receita Federal",
          "description": "Fonte atualizada mensalmente.",
          "homonym": false,
          "criticality": "high"
        },
        {
          "title": "CNAE Primário - Alteração",
          "description": "Fonte atualizada mensalmente.",
          "homonym": false,
          "criticality": "high"
        },
      ]
    },
    {
      "name": "Dados modelados",
      "rule": [
        {
          "title": "Nível de Atividade - Alteração",
          "description": "Fonte atualizada mensalmente.",
          "homonym": false,
          "criticality": "high"
        },
        {
          "title": "Faturamento Presumido",
          "description": "Fonte atualizada mensalmente.",
          "homonym": false,
          "criticality": "medium"
        }
      ]
    },
  ]
}

For example, I need to return the group "Cadastral/Receita Federal" if I search for "Rece" in search field, but I don't know how to filter data inside data.
What I've done so far:
Module.vue
<template>

    <slide-out :visible.sync="isVisible" :title="text.header">

          <button class="neo-bt-icon--big slideout__close--button" @click="isVisible=false">
            <svg><use xlink:href="/red/neo-assets/images/simple-line-icons.svg#arrow-2-left"></use></svg>
          </button>

            {{ text.header }}

            <input type="text" class="neo-form-field" placeholder="Buscar" v-model="searchQuery">
            <input class="neo-form-toggle__field" :id="selectAllRules" @click="selectAllRules($event)" type="checkbox"/>
            selecionar tudo

            <input class="neo-form-toggle__field" :id="policyRule.name" @click="selectGroupRules(policyRule.rule, policyRule.name, $event)" type="checkbox" v-model="policyRules.name" />
            selecionar grupo

              <input class="neo-form-toggle__field" :id="rule.title" :value="rule" name="rule" type="checkbox" v-model="checkedRules"/>
              {{ rule.title }}

{{ rule.description }}

        {{ checkedRules  }}

    </slide-out>

</template>

Object expected result using "Rec" in search field:
{
  "name": "Cadastral",
  "rule": [
    {
      "title": "Receita Federal",
      "description": "Fonte atualizada mensalmente.",
      "homonym": false,
      "criticality": "high"
    },
  ]
},

A: Try this computed prop.
filteredPolicyRules() {
  if (this.searchQuery) {
    return this.policyRules.group.reduce((groups, { name, rule }) => {
      const rules = [];

      rule.forEach(r => {
        if (r.title.startsWith(this.searchQuery)) {
          rules.push(r);
        }
      });

      if (rules.length > 0) {
        groups.push({
          name,
          rules
        });
      }

      return groups;
    }, []);
  }

  return this.policyRules;
}

I'd suggest calling them groups and rules (plural) respectively, to avoid future confusion -- after all they are arrays.
Full demo:

const policyRules = {
  "id": "rulesCompany",
  "group": [{
    "name": "Cadastral",
    "rule": [{
      "title": "Receita Federal",
      "description": "Fonte atualizada mensalmente.",
      "homonym": false,
      "criticality": "high"
    },
    {
      "title": "CNAE Primário - Alteração",
      "description": "Fonte atualizada mensalmente.",
      "homonym": false,
      "criticality": "high"
    },
    ]
  },
  {
    "name": "Dados modelados",
    "rule": [{
      "title": "Nível de Atividade - Alteração",
      "description": "Fonte atualizada mensalmente.",
      "homonym": false,
      "criticality": "high"
    },
    {
      "title": "Faturamento Presumido",
      "description": "Fonte atualizada mensalmente.",
      "homonym": false,
      "criticality": "medium"
    }
    ]
  }]
};

new Vue({
  el: '#app',

  data() {
    return {
      searchQuery: '',
      policyRules
    }
  },

  computed: {
    filteredPolicyRules() {
      if (this.searchQuery) {
        return this.policyRules.group.reduce((groups, { name, rule }) => {
          const rules = rule.filter(this.matchFilter);

          if (rules.length > 0) {
            groups.push({
              name,
              rules
            });
          }

          return groups;
        }, []);
      }

      return this.policyRules;
    }
  },

  methods: {
    matchFilter(item) {
      const
        search = this.searchQuery.toLowerCase(),
        term = (item.title || '').toLowerCase();

      return term.includes(search);
    }
  }
});

  <input v-model="searchQuery" placeholder="Search..." />

{{ filteredPolicyRules }}

A: So first I've put your list into a map variable. Then I'm filtering that by checking if any of the wanted properties contain the search term. The array.filter Method returns a new array based on what entries returned true and what false.
I'm checking inside name, title and description. Also I made everything lower case so case doesn't matter.
Array.prototype.filter Reference

const term = 'CNE';

console.log(map.filter(e => {
  const { name } = e;
  if(contains(name, term)) return true;

  for(const _r of e.rule) {
    const { title, description } = _r;
    if(contains(title, term)) return true;
    if(contains(description, term)) return true;
  }
  return false;
}));

function contains(str, term) {
  return str.toLowerCase().includes(term.toLowerCase());
}

And I would also suggest like Yom in his answer that you use groups and rules so you can name them better. So that then would be groups.filter(group => {[..]}) and for(const rule of group.rules)


text:
Q: Replace range text then insert a symbol I am attempting to insert text into the footer, I am running into problems with inserting a symbol after my inserted text so that I can easily replace that text on future calls of the code.
In the following code Word will crash after calling the sub, I suspect it is failing at the oRng.Collapse wdCollapseEnd and oRng.InsertSymbol lines, perhaps it is failing to exit the loop?
Public Sub UpdateFooter()

    Dim objRange As Range
    Dim strCurrentView As String
    Dim objSection As Section
    Dim objHeaderFooter As HeaderFooter
    Dim rng As Word.Range

    ' Turn off screen updating
    Application.ScreenUpdating = False

    ' Loop through sections
    For Each objSection In ActiveDocument.Sections

        Set rng = objSection.Footers(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range

        Dim oRng As Word.Range

        Set oRng = rng

        oRng.Collapse wdCollapseStart

        ' Find existing U+61472 symbol, which means footer text has already been inserted
        With oRng.Find
            .ClearFormatting
            .Text = ChrW(61472)
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindStop
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
            Do While (.Execute = True) = True
                If .Found = True Then
                    ' Found, select first word through to and including the symbol
                    oRng.MoveStart wdWord, -1
                    oRng.MoveEnd wdCharacter, 1
                Else
                    ' Not found
                    oRng.MoveEnd wdStory, 1
                End If

                ' Insert new text
                oRng.Font.Name = "Arial"
                oRng.Font.Size = 8
                oRng.Text = "TEST_TEXT"

                ' Insert symbol after the new text so that we can replace in future
                'oRng.Collapse wdCollapseEnd
                'oRng.InsertSymbol Font:="Wingdings", CharacterNumber:=-4064, Unicode:=True
            Loop
        End With
    Next

    ' Set view back to Print View and enabled screen updating
    ActiveDocument.PrintPreview
    ActiveDocument.ClosePrintPreview
    Application.ScreenUpdating = True

End Sub

This code will perform a find for the symbol U+61472, if found the text from the start of the line to the symbol will be selected and the text replaced, if the symbol isn't found then the text will be inserted.
If I remove the
oRng.Collapse wdCollapseEnd
oRng.InsertSymbol Font:="Wingdings", CharacterNumber:=-4064, Unicode:=True

The footer text is inserted but without the symbol any future saves will have the text re-inserted as duplicates instead of being replaced.
How would I go about inserting text in the selected range, and then adding a symbol after the inserted text?

A: I ended up resolving this by doing the insert symbol outside the while loop.
Public Sub UpdateFooter()
Dim objRange As Range
Dim strCurrentView As String
Dim objSection As Section
Dim objHeaderFooter As HeaderFooter
Dim rng As Word.Range

' Turn off screen updating
Application.ScreenUpdating = False

' Loop through sections
For Each objSection In ActiveDocument.Sections

    Set rng = objSection.Footers(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range

    Dim oRng As Word.Range

    Set oRng = rng

    oRng.Collapse wdCollapseStart

    ' Find existing U+61472 symbol, which means footer text has already been inserted
    With oRng.Find
        .ClearFormatting
        .Text = ChrW(61472)
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        Do While (.Execute = True) = True
            If .Found = True Then
                ' Found, select first word through to and including the symbol
                oRng.MoveStart wdWord, -1
                oRng.MoveEnd wdCharacter, 1
            Else
                ' Not found
                oRng.MoveEnd wdStory, 1
            End If

            ' Insert new text
            oRng.Font.Name = "Arial"
            oRng.Font.Size = 8
            oRng.Text = "TEST_TEXT"

        Loop
    End With
 Insert symbol after the new text so that we can replace in future
 oRng.Collapse wdCollapseEnd
 oRng.InsertSymbol Font:="Wingdings", CharacterNumber:=-4064, Unicode:=True

Next

' Set view back to Print View and enabled screen updating
ActiveDocument.PrintPreview
ActiveDocument.ClosePrintPreview
Application.ScreenUpdating = True

End Sub


text:
Q: Restoring corrupted UTF-8 files After my PC broke down I managed to make a backup of the relevant files before reinstalling Windows.
Now that I'm restoring those files and setting the system up I noticed that some of the files got corrupted in the backup and I was wondering if you have any idea on how to restore their original content.
For example, the image below shows a piece of a corrupted file (opened in notepad). I do know (partially) what the content is: the first line is <?php.

Do you think there is a way to recover these files?
I have some experience at programming so if I need to write a script I'm happy to do it but I guess I'd need a conversion map.

A: You won't recover your files.
Corruption is not a defined operation that can be reversed with a script.
Strictly technically UTF-8 is not a file format. It is a way of representing so-called code points.
The simplest tool to analyse a files is a hex editor that shows you binary data and ASCII and maybe UTF symbols. I guess that PHP code is largely represented as ASCII. Notepad does not necessarily show all information, for instance no symbols for bytes with a value below 32. Therefore your image of Notepad does not help at all - possible information is hidden.
Your broken computer leads to the question why it broke down. Is the file system dammaged? How did you backup your files?
What file type are you talking about?
Your description of your incident is insufficient to get an idea what might have happened.

A: This won't actually RECOVER missing data (I mean.. where would it get it from?), but it WILL give you back all of your text that could be recovered in an easy way.
The "secret"?  ... ... "[dramatic-pause]"... ...
MICROSOFT WORD. .. wait.. WHAT? .. WORD? ??
I used to use it to rip command line options from EXE files and all sorts of other stupid nerd tricks.  This feature has been in there since the early Word95 days.

*

*First, open word (the cool kids pull up the Run dialog and type "winword").

*Click Open on the left.  Then find the Browse button.

*Use the file type drop down and change it to "Recover Text from Any File (.)" and find your file.  Ignore the errors.. (of COURSE there are errors!)

For this sample, I opened notepad.exe.

This text can now be dropped into notepad.exe or even a not-lame text editor.
I hope this helps.


text:
Q: Grunt to export specific files from svn I'm looking for a npm grunt module that will help me export specific files (not directories) from svn repository.
Thanks

A: You can not export files. You can only svn cat FILE > filename


text:
Q: UDP Application in omnet++ In a network simulation with omnet++5.4 inet 3.6, how can I set a UDP Application in .ini file to send packets from array A[sizeofA] to array B[sizeofB]?
A and B are two sets of nodes with different sizes and there should be send to the nearest node.
and if there is another set of nodes that called C[sizeofC], how can I set UDP traffic form B to C? I mean B acts as a router here.
appreciate for your help, in advance.


text:
Q: Set min-width equal to height? It's easy enough to set an element's height depending on its width using tricks such as setting margin-top: AR%, with AR being the aspect ratio of the element.
However, I'd like to do something the other way around.
Namely, I'd like to set the element's min-width to be equal to the element's height, which may be dynamic based on content.
If this isn't possible, that's okay - it's only needed for user-generated content, since the cases where I use it have a static and known height! It's fairly minor, but if it can be done then that'd be great.
Anyone got any ideas?


text:
Q: how to know and add Python path which is in vm to editor in host I'm using vagrant and virtualbox which has ubuntu LTS 12.04 . Now I'm trying to use Aptana Studio for development and when I created a project it asks to specify Python interpreter path. I also have python installed in my host os i.e. win 7.
So how do I know which path to add to, to the aptana studio ?

A: You can find the PYTHONPATH with Python or with UNIX console:
Python:
import os
os.environ['PYTHONPATH']

or
os.getenv('PYTHONPATH')

or
import sys
sys.path

Console:
which python

or
whereis python

Commonly this is on /usr/bin/python


text:
Q: How to store elements of a string array into a struct in C? So I have a string: a = 2.b 1.d; milk cheese
I separate it by removing all the special characters (the equal sign, the period, the semicolon) and this is done using the strtok function in C. I take each element and store it into an array of strings, like this:
arr[0]="a"
arr[1]="2"
arr[2]="b"
arr[3]="1"
arr[4]="d"
arr[5]="milk"
arr[6]="cheese"

Now, I want to take those values and put them into a struct. Here is my struct:
struct stopPoints {
    int  weights[10];
    char connectingPoints[10];
    char *items;
    int startBool;
};

I've declared the struct and called it myPoint. Now, I want to store each of the separated elements up top into my struct. For example, i want to store the "2" and "1" into myPoint.weights[0] and myPoint.weights[1]. I want to store the "a" and "b" into myPoint.connectingPoints[0] and myPoint.connectingPoints[1].
I approached this by trying to distinguish between letters and numbers. I loop through the "arr" array and check if each index has either a letter or number. This is done by using the ASCII values (I know there's a better method to doing this according to the answers on my previous post). But when I try printing out the first weight element in my struct, I get a random value. How can I fix this? My code is below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct stopPoints {
    int  weights[10];
    char connectingPoints[10];
    char *items;
    int startBool;
};

int main ()
{
    struct stopPoints myPoint;
  char *arr[30];
  char str[] ="a = 2.b 1.d; milk cheese";
  char * pch;
  pch = strtok (str," ;=,.-");
  arr[0] = pch;
  int i=0;
  while (pch != NULL)
  {
    //printf ("%s\n",pch);
    pch = strtok (NULL, " ;=,.-");
    arr[i+1] = pch;
    printf("%s\n", arr[i]);
    i++;
  }
    int sizeofstring = sizeof(str)/sizeof(str[0]);

    int x,y=0;
     for (x=0; x<sizeofstring; x++){
          if (arr[y+1] >= 97 && arr[y+1] <= 122){
                myPoint.connectingPoints[x] = arr[y+1];
                y++;
          }
          else if (arr[y+1] >= 48 && arr[y+1] <= 57){
                myPoint.weights[x] = arr[y+1];
                y++;
          }
     }

    printf("%d\n", myPoint.weights[1]);

  return 0;
}

A: First, very good job on the detail, the minimum complete and verifiable example, and the formatting of your question. Next, it is apparent you are quite lost...
It is hard to imagine a more awkward approach to doing what you are attempting to do, but for the sake of learning, there is quite a bit of learning that can be had in doing it in an awkward fashion.
To begin, do not use magic numbers in your code. This is for readability and maintainability as your code grows. 10, 30, 97, 122, 48 and 57 are all magic numbers.
#define CPWT 10     /* if you need a constant, #define one (or more) */
#define NPTR 30     /*   (do not use "magic numbers" in your code)   */

Do not use magic numbers for characters. While you should use the macros provided in ctype.h for islower() and isdigit(), if you are going to use characters, then use characters, e.g. if (foo >= 'a' && foo <= 'z') not 97 and 122. Just single quote the character.
Next, you are overwriting every pointer in arr every time you assign arr[i+1] = pch; Why?
    char *arr[NPTR];                /* array of 30 UNINITIALIZED pointers */

While strtok does return a pointer, when you assign arr[i+1] = pch;, you are assigning the same pointer to each pointer in arr. When you are done, every element in arr will hold the last value returned by strtok (and since you assign after the last call to strtok returns NULL -- you most likely SegFault)
Further, before you "store" anything at the address of arr[0] to arr[NPTR-1], you must allocate storage based on the length of the string you are storing. (and yes, even though you are only storing a single-character in many elements, you are storing strings -- and every string requires a nul-terminating character).
You cannot assign strings in C (except for the assignment of string literals or during initialization of an array). Otherwise, you must copy strings in C.
So since you begin with uninitialized, unallocated pointers in arr, you must allocate and then copy to store information at each pointer address. You have two ways of doing so, (1) either malloc (length + 1) characters, validate the allocation, and then strcpy (or more efficiently memcpy since you have already scanned to find the nul-character with strlen()), or (2) if you have strdup() it will both allocate and copy as you did in (1) in a single function call. (note: since strdup allocates, you still must validate the allocation succeeded)
Example (1)
    if ((pch = strtok (str," ;=,.-")) != NULL) {    /* validate each call */
        size_t len = strlen (pch);                  /* get length */
        if ((arr[0] = malloc (len + 1)) == NULL) {  /* allocate/validate */
            perror ("arr[0]-malloc");
            exit (EXIT_FAILURE);
        }
        memcpy (arr[0], pch, len+1);    /* copy! string to arr[0] */
        i++;
    }

Example 2 (using strdup to allocate/copy)
    /* only loop if good return from strtok */
    while ((pch  = strtok (NULL, " ;=,.-")) != NULL)
    {
        /* allocate/copy all at once with strdup (if you have it) */
        if ((arr[i] = strdup (pch)) == NULL) {
            perror ("arr[n]-strdup");
            exit (EXIT_FAILURE);
        }
        i++;
    }

Since you have just filled i elements of arr, there is no need for:
    int sizeofstring = sizeof(str)/sizeof(str[0]);

You know you have i strings in arr -- use i not sizeofstring and step through each string you stored in arr, not each character in str. That defeats the entire purpose of having tokenized str. Further, you only want to consider single character or single digit strings in arr (not "milk" and "cheese") when setting connectingPoints and weights, so check whether the 2nd character is the nul-character, otherwise skip the element of arr.
You can't use y for both connectingPoints and weights, you have a, b, d connectingPoints (3 of them) and only 2 weights. You would be attempting to access outside the valid data in weights if you iterated from j = 0; j < y; ...
Again, you cannot assign a pointer as a character, so the easiest way to assign the 1st character in a string as a character, is simply to dereference the pointer, e.g. *arr[x] (which is equivalent to the character arr[x][0]). That in mind, you could do:
    /* i contains the number of strings in arr - use it */
    for (x = 0; x < i; x++) {
        if (arr[x][1] == 0) {   /* only consider single char strings in arr */
            if (cpts < CPWT && islower(*arr[x])) { /* check bound/lowercase */
                myPoint.connectingPoints[cpts] = *arr[x];  /* assign char */
                cpts++;
            }
            else if (weights < CPWT && isdigit(*arr[x])) { /* same w/digits */
                myPoint.weights[weights] = *arr[x];
                weights++;
            }
        }
    }

(note: the separate use of the counters cpts and weights instead of a single y)
Putting all the pieces together, you could do the awkward approach with something like the following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define CPWT 10     /* if you need a constant, #define one (or more) */
#define NPTR 30     /*   (do not use "magic numbers" in your code)   */

struct stopPoints {
    int  weights[CPWT];
    char connectingPoints[CPWT];
    char *items;
    int startBool;
};

int main (void)
{
    struct stopPoints myPoint = { .weights = {0} };
    char *arr[NPTR];                /* array of 30 UNINITIALIZED pointers */
    char str[] ="a = 2.b 1.d; milk cheese";
    char *pch;
    int i = 0, x, cpts = 0, weights = 0;

    if ((pch = strtok (str," ;=,.-")) != NULL) {    /* validate each call */
        size_t len = strlen (pch);                  /* get length */
        if ((arr[0] = malloc (len + 1)) == NULL) {  /* allocate/validate */
            perror ("arr[0]-malloc");
            exit (EXIT_FAILURE);
        }
        memcpy (arr[0], pch, len+1);    /* copy! string to arr[0] */
        i++;
    }

    /* only loop if good return from strtok */
    while ((pch  = strtok (NULL, " ;=,.-")) != NULL)
    {
        /* allocate/copy all at once with strdup (if you have it) */
        if ((arr[i] = strdup (pch)) == NULL) {
            perror ("arr[n]-strdup");
            exit (EXIT_FAILURE);
        }
        i++;
    }

    /* i contains the number of strings in arr - use it */
    for (x = 0; x < i; x++) {
        if (arr[x][1] == 0) {   /* only consider single char strings in arr */
            if (cpts < CPWT && islower(*arr[x])) { /* check bound/lowercase */
                myPoint.connectingPoints[cpts] = *arr[x];  /* assign char */
                cpts++;
            }
            else if (weights < CPWT && isdigit(*arr[x])) { /* same w/digits */
                myPoint.weights[weights] = *arr[x];
                weights++;
            }
        }
    }

    puts ("arr contents:");
    for (x = 0; x < i; x++)
        printf (" arr[%2d]: %s\n", x, arr[x]);

    puts ("\nconnectingPoints:");
    for (x = 0; x < cpts; x++)
        printf (" myPoint.connectionPoints[%2d]: %c\n",
                x, myPoint.connectingPoints[x]);

    puts ("\nweights:");
    for (x = 0; x < weights; x++)
        printf (" myPoint.weights[%2d]: %c\n",
                x, myPoint.weights[x]);

    return 0;
}

(note: the use of islower() and isdigit() from ctype.h)
Example Use/Output
$ ./bin/strtokarrptrs
arr contents:
 arr[ 0]: a
 arr[ 1]: 2
 arr[ 2]: b
 arr[ 3]: 1
 arr[ 4]: d
 arr[ 5]: milk
 arr[ 6]: cheese

connectingPoints:
 myPoint.connectionPoints[ 0]: a
 myPoint.connectionPoints[ 1]: b
 myPoint.connectionPoints[ 2]: d

weights:
 myPoint.weights[ 0]: 2
 myPoint.weights[ 1]: 1

Look things over and let me know if you have further questions.

A: I am not really understanding what you are trying to do, but arr is an array of pointers, myPoint.connectingPoints is an array of char and myPoint.weights is an array of int. So myPoint.connectingPoints[x] = arr[y+1] and myPoint.weights[x] = arr[y+1] will do pointer to char or int conversion, which is generally a bad idea.
Maybe you wanted to do
myPoint.connectingPoints[x] = arr[y+1][0];

and
myPoint.weights[x] = arr[y+1][0];

The same goes for the comparisons with arr[y+1]. 97, 122, 48 and 57 are not hardcoded memory addresses, are they?
This is totally ignoring the fact that you have a buffer overflow in myPoint.connectingPoints and myPoint.weights. Hint: sizeofstring is larger than 10.
Please, always compile with -Wall. The flag exists for a reason

A: You do not initialize your struct at any point and you alternate by assigning values
to myPoint.connectionPoints[x] and myPoint.weights[x] but then skip a spot in the other
array so that is the reason you get random values
      if (arr[y+1] >= 97 && arr[y+1] <= 122){
            myPoint.connectingPoints[x] = arr[y+1];  // myPoint.weights[x] left unassigned
            y++;
      }
      else if (arr[y+1] >= 48 && arr[y+1] <= 57){
            myPoint.weights[x] = arr[y+1]; // myPoint.connectingPoints[x] left unassigned
            y++;
      }

I would suggest you convert your values to the struct already when you get the
return value from strtok to avoid allocating for things you do not later
need.
E.g.
    int index = 0;
    for (char* pch = strtok(str, " ;=,.-"); pch != NULL; pch = strtok(NULL, " ;=,.-")
    {
      switch (index++)
      {
      case 0:
      case 1:
      case 2:
      ...
      default:
        break;
      }
    }

EDIT: in fact I am not sure you need the switch at all, just have a counter for each array and increment when you assign to it.
In the case of the return value of strtok() you must take care to allocate memory for the return value in order to store the value between each iteration since it uses a static buffer of the original string when it returns tokens, but if you directly convert the token you don't need to.
When you check the value of the character use one of the standard c runtime
functions for that purpose isdigit() isalpha()/islower() instead of checking ASCII
value directly.


text:
Q: Shockley-Queisser limit calculations I am working through the paper, Detailed Balance Limit of Efficiency of p-n Junction Solar Cells by Shockley & Queisser, for my own research with perovskite solar cells.
I am able to follow their logic but am having trouble with one of their calculations.
Given their equations (2.2) and $x_g\equiv \frac{h\nu_g}{k_B T_s}$,
$$Q_s \equiv Q(\nu_g,T_s)=\frac{2\pi}{c^2}\int^{\infty}_{\nu_g}\left[\exp{\left(\frac{h\nu}{k_B T_s}\right)}-1\right]^{-1}\nu^2d\nu \\ =\frac{2\pi}{c^2}\left(\frac{k_B T_s}{h}\right)^3 \int^{\infty}_{x_g}\frac{x^2}{e^x-1}dx$$
I can see that this is a straightforward change of variables from $\nu_g \rightarrow x_g$.
I am running into difficulty deriving a similar expression for $Q_c=Q(\nu_g,T_c)$ using another definition $x_c \equiv \frac{T_c}{T_s}$.
It's clear that $\frac{h\nu}{k_B T_c} = \frac{x_g}{x_c}$, but when I try to compute the value of the integral for $Q_c$
$$Q_c = \frac{2\pi}{c^2}\left(\frac{k_B T_c}{h}\right)^3 \int^{\infty}_{x_g/x_c}\frac{x^2}{e^x-1}dx$$
I don't get the answer that they get in their article. For an energy gap of $E_g=1.09 eV$ and $T_c=300\;K$ they get a value of $1700 \;cm^{-2}s^{-1}$ whereas I get $10.8 \;cm^{-2}s^{-1}$.
Is there some calculus step I am missing during the change of variables, I mean $\frac{T_c}{T_s}$ is just a constant, why would that affect anything? They never explicitly write out their equation for $Q_c$ so I'm wondering if anybody has encountered this before.


text:
Q: Get Lowest Value While Comparing a Different Column I'm trying compare the data in a table and output the lowest value of each type. I know there's a MIN() function in SQL, but it will only get the lowest value overall, which is not exactly I want.
I want to get the data of the whole row, whose value in Column1 is the smallest foreach type.
This is how the table looks like:
Type        Column1         Column2
-------     --------        ---------
A           1               !!!
A           2               @@@
B           3               ###
B           4               $$$
C           5               %%%
C           6               ^^^

When I use the SELECT MIN(Value), the result I got looks like this:
Type        Column1         Column2
-------     --------        ---------
A           1               !!!

I used the GROUP BY method suggest by Linger, but the result still didn't quite match what I want:
Type        Column1         Column2
-------     --------        ---------
A           1               @@@
B           3               $$$
C           5               ^^^

However, the desire result is suppose to be:
Type        Column1         Column2
-------     --------        ---------
A           1               !!!
B           3               ###
C           5               %%%

How would I write my SQL query to do the job? Thanks in advance.

A: That is a simple query to perform simply by using the GROUP BY clause:
SELECT MTM.* FROM
(
    SELECT MTS.Type, MIN(MTS.Values) AS SmallestValue
    FROM  MyTable AS MTS
    GROUP BY MTS.Type
) AS MainQ
INNER JOIN MyTable AS MTM
ON MTM.UniqueID = MainQ.UniqueID

In the above example I am performing the MIN() GROUP BY query and then joining the results to the same table to pull the remaining fields I am in need of.  You should have a field that uniquely identifies a record.  Use that field instead of UniqueID above.