text:
Q: variable value in arrray is returned as an integer but needed string in codeigniter Hello everyone I am completely stuck with this problem.
I want add the name of a file I changed using the string "rename" function in codeigniter to an array and then send that array to a model where I can extract it and add to it my database.
However when I do this the value added in my database for the file name always comes as '1'.
Here is my code, in it I am uploaded and file.
This is part of the controller class with the file name changing and adding to the array
        $data = array('upload_data' => $this->upload->data()); // Get the file from the form userfile information
        $file = $data['upload_data']['file_name'];

        //hacky name generator
        $randomstring = random_string('alnum', 4);
        $filenew = rename($dir . $file, $dir . $id . '_' . $randomstring . '.jpg'); //basic php rename call, rename my upload now that upload finished

        // this array is all the other values from my form fields
        $data = array($this->input->post('comment'), $filenew);

        $configB['image_library'] = 'gd2'; // this code begins the thumbnail making process, from user guide
        $configB['source_image'] = $filenew;//$dir . $id.'.jpg'; // I am using $id for image name, which is my users id, comes from the session
        $configB['create_thumb'] = FALSE;
        $configB['maintain_ratio'] = TRUE;
        $configB['width'] = 300;
        $configB['height'] = 300;
        $this->image_lib->initialize($configB);
        $this->image_lib->resize();

        $this->load->model('membership_model');
        // run my model which saves all this to the database, image name also ($filenew)
        if($query = $this->membership_model->create_post($id,$data))
        {
            $data = array('upload_data' => $this->upload->data());
            $data['filename'] = $filenew;
            $this->load->view('post_success_view', $data);

        }

Here is the model
function create_post($id, $data)
{
    //get data from array
            $content = $data[0];
    $filename = $data[1];

    // update database to track a new post.
    $new_post_insert_data = array(
        'content' => $content,
        'beer_down' => 0,
        'beer_up' => 0,
        'user_name' => $this->session->userdata('username'),
        'account_id' => $this->session->userdata('userid'),
        'file_name' => $filename
        );

    $insert_post = $this->db->insert('post', $new_post_insert_data);
    return $insert_post;
}

Thank you in advanced if you can help me out been stuck here for hours.

A: rename() changes the name of a system resource, and returns a Bool for success. When you cast that boolean true to a string, you get "1". If you want to store the name in the DB, you should set a variable ie:
$new_name = $dir . $id . '_' . $randomstring . '.jpg';

then call rename:
rename($dir . $file, $new_name);

and use the $new_name to insert in the database.


text:
Q: Android REST webservices I have a code which works perfectly on the java project but when i use the same on the android project it throws error here is the code .(Note i cannot share link and parameters, problem is NOT there . link is right . the code is working i am getting result in java project in eclipse but same in android project fails  )
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
try{
        Client client=Client.create();
        WebResource webResource2 = client.resource("some...link");

        WSDetPojo wsdetpojo = new WSDetPojo(); // some class
        wsdetpojo.parameter1("parameter1");
        wsdetpojo.parameter2("parameter2");
        wsdetpojo.parameter3("parameter3");
        wsdetpojo.parameter4("parameter4");

        ObjectMapper om=new ObjectMapper();

        ClientResponse response2 = webResource2.type("application/json")
        .post(ClientResponse.class,om.writeValueAsString(wsdetpojo)); // here is the problem <==

        System.out.println("response of sms ==> "+response2);
        if (response2.getStatus() != 201)
        {
            throw new RuntimeException("Failed : HTTP error code : "+ response2.getStatus());

        }

        String output2 = response2.getEntity(String.class);
        System.out.println("output :\n" +output2);

    }catch(Exception ex){
        ex.printStackTrace();
    }

Now here is the error which i get when i run it on android
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object javax.ws.rs.ext.RuntimeDelegate$HeaderDelegate.fromString(java.lang.String)' on a null object reference
    at javax.ws.rs.core.MediaType.valueOf(MediaType.java:119)
    at com.sun.jersey.api.client.PartialRequestBuilder.type(PartialRequestBuilder.java:92)
    at com.sun.jersey.api.client.WebResource.type(WebResource.java:347)
    at co.example.punerto.classes.NicClient.sendData(NicClient.java:43)
    at com.example.punerto.Activity.ActivityLearnLicAppointment_Tab6$uploadFrom.doInBackground(ActivityLearnLicAppointment_Tab6.java:303)
    at com.example.punerto.Activity.ActivityLearnLicAppointment_Tab6$uploadFrom.doInBackground(ActivityLearnLicAppointment_Tab6.java:1)
    at android.os.AsyncTask$2.call(AsyncTask.java:288)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)

Please help !! Stuck on this spent 8 hours already . I also tried alternative did not worked !! If you have some alternative for this please do let me know.

A: Did you set the required android permissions ?
 <uses-permission android:name="android.permission.INTERNET" />

A: Actually it is too complicated to understand what is the problem when you are showing only your objects for storing your result and makeing the post request.
This is deprecated but still works fine for me in Android and might be useful for you to find your error.
    try {
        //Create an HTTP client
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet("https://www...."); //your url as String
        //use HttpPost instead HttpGet if you need the post method
        //Perform the request and check the status code
        HttpResponse response = client.execute(get);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();

            try {
                //Read the server response
                Reader reader = new InputStreamReader(content);

                //get your data from the reader

                content.close();
            } catch (Exception ex) {
                Log.e(TAG, "Failed with: " + ex);
            }
        } else {
            Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
        }
    } catch (Exception ex) {
        Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Match phototransistor to LED source Phototransistors are a new tool for me, and I'm wondering how to select one that will match a specified source (LED worklight, color temp 5000K, wavelength unspecified). My prototype works but apparently does not match the light source. Of course the data sheet for the transistor (ROHM RPM075PTT86) specifies its spectral response. I can't find out how to correlate a color temp of 5000K to a wavelength. There must be a better way than trial and error. For reference the app is a conveyor package detector, light is overhead strip about 2' above the surface, sensors are in a strip across the conveyor. Any suggestions appreciated!
Harry
Datasheet HERE

A: Your photo transistor is optimally responding to 600 nm.

White leds of 5000k tend to have their heighest peak in the blue range of 450 nm and a lower hump over 525 to 550 nm.

The setup is not ideal, but should still have some reasonable response, as long as you properly aim them at the light source. Both the transistor and the light source spectrum peaks are curves, and should work even if not directly matched, as long as the output is in the curve. Without knowing your specific lights spectral range, we cannot give you better guidance.

A: 5000K corresponds to green/yellow (if it is black body radiation). So your phototransistor should have a response curve in the visible part of the spectrum, between (approx) 700nm to 400nm

A: This answer addresses part of your question only.

*Figure 1. Typical RGB LED module color gamut and white colour temperatures. Source: AGI.
The human eye has three sets of rods sensitive to short, medium and long wavelengths which roughly correspond to blue, green and red respectively. The brain converts the relative stimulus strength received by each rod to a 'colour'. With an RGB source with wavelengths identified by the black dots on the chart of Figure 1 you can simulate any colour inside the triangle. Note that you are not generating that wavelength - just fooling the eye with the relative strengths of each component.
Some white LEDs use a blue light with yellow phosphors. By controlling (in the design and manufacture) the mix of blue and yellow the colour temperature can be controlled roughly along a straigh line - an extended line from 25000 K through 6000 K over towards yellow.
Note that in both cases described above that the light sources will not be truly monochromatic but will have a spectral spread.

I can't find out how to correlate a color temp of 5000K to a wavelength. There must be a better way than trial and error.

If you have enough time and interest you could make a spectrometer for your phone. See PublicLab smartphone-spectrometer.

For reference the app is a conveyor package detector, light is overhead strip about 2' above the surface, sensors are in a strip across the conveyor.

You haven't linked a datasheet for your sensors but it's much more likely that ambient light is swamping the measurements. Edit your question to show your circuit - there's a simple schematic button on the editor toolbar - and readings obtained with target present and absent.

A: Thanks to all for the good info. My original question betrays my ignorance of photo-electronics. In retrospect, I have found that the source @5000K resembles white light ("early sunlight", per mfr), and as such would hardly have a discrete wavelength. One of the comments is quite correct in that the 600um detector is well matched to the light from the source.  I should have realized this because the source is used to light the existing detector strip (which I am replacing, and which is a very specific design) without any problems.
I'm embarrassed to say that the issue is more related to the bias of the photo-transistor. I believe it is true that the higher the value of the pullup resistor the more 'sensitive' it is. I found this to be true when I changed from 4.7K to 21K pullups. (not sure how to import drawings, but in this circuit the emitters of the detectors are grounded, pullup resistor to 5V, also to the gate of a mosfet, the open drains of which are wire ored to the processor pin). This increased the sensitivity dramatically. Should have been obvious- if the pt is a current modulator, then the IR drop will be greater for a greater resistor value, within reason.


text:
Q: Comparing values (pd) Edit: typos
so I have to look at a kindergarden to see if someone went home happy.
There is a happy column:
If they went home happy there's a 1
If they went home unhappy there's a 0
I have to compare that to age groups:
There is a age_group column:
"20 to 40"
"40 to 60"
"60 to 80"
Now I want to compare if they went home happy and the age group.
Can someone help me please? :-)

A: Try if this works:
happy_group1 = 0
for row in df.iterrows():
    if row[1]["happy"] == "1" and row[1]["age_group"] == "20-40":
        happy_group1+=1
    else:
        pass
print(happy_group1)

A: Can you try this?
happy_group1 = 0
for n in df["happy"]:
    for k in df["age_group"]:
        if n == 1 and k == "20-40":
            happy_group1 += 1
        else:
            pass
print(happy_group1)


text:
Q: Lua: has the behaviour of garbage collector changed with Lua 5.3.2? I'm facing a problem of memory leak in Lua. To understand how the gc works I have written a small script and the results are surprising (for me):
local mt = { __gc = function() end }

local function new()
    local o = { s = string.rep(os.date("%c"), 500) }
    setmetatable(o, mt)
end

local before = math.floor(collectgarbage("count"))
for i = 1, 100000 do new() end
local after = math.floor(collectgarbage("count"))
print(before, after)

I'm creating 100000 objects, each objet has a metatable having a __gc function.
As result I get :

*

*with Lua 5.2.4 : 25      130 (25 kb of memory at start, 130 kb at the
end of the script)

*with Lua 5.3.5 : 25      17470

Lua 5.3.5 does not garbage the objects as Lua 5.2.4 did.
I used the same script on different Lua versions (5.3.0, 5.3.1, 5.3.2, 5.3.3, 5.3.5) and this behaviour appears starting with Lua 5.3.2.
More surprising is that, if I remove the __gc function, the results are quite the same for all Lua versions.
Do you think that I'm missing something or is it a bug introduced in Lua 5.3.2 ?
Edit : this script behaves with Lua 5.4.0 as with Lua 5.3.1. So the bug is solved.


text:
Q: php is_function() to determine if a variable is a function I was pretty excited to read about anonymous functions in php, which let you declare a variable that is function easier than you could do with create_function. Now I am wondering if I have a function that is passed a variable, how can I check it to determine if it is a function? There is no is_function() function yet, and when I do a var_dump of a variable that is a function::
$func = function(){
    echo 'asdf';
};
var_dump($func);

I get this:
object(Closure)#8 (0) { }

Any thoughts on how to check if this is a function?

A: You can use function_exists to check there is a function with the given name. And to combine that with anonymous functions, try this:
function is_function($f) {
    return (is_string($f) && function_exists($f)) || (is_object($f) && ($f instanceof Closure));
}

A: If you only want to check whether a variable is an anonymous function, and not a callable string or array, use instanceof.
$func = function()
{
    echo 'asdf';
};

if($func instanceof Closure)
{
    // Will be true.
}

Anonymous functions (of the kind that were added in PHP 5.3) are always instances of the Closure class, and every instance of the Closure class is an anonymous function.
There's another type of thing in PHP that could arguably be considered a function, and that's objects that implement the __invoke magic method.  If you want to include those (while still excluding strings and arrays), use method_exists($func, '__invoke').  This will still include closures, since closures implement __invoke for consistency.

A: function is_function($f) {
    return is_callable($f) && !is_string($f);
}

A: Use is_callable to determine whether a given variable is a function. For example:
$func = function()
{
    echo 'asdf';
};

if( is_callable( $func ) )
{
    // Will be true.
}

A: In php valid callables can be functions, name of functions (strings) and arrays of the forms ['className', 'staticMethod'] or [$object, 'method'], so to detect only functions need to exclude strings and arrays:
function isFunction($callable) {
    return $callable && !is_string($callable) && !is_array($callable) && is_callable($callable);
}


text:
Q: Invisible Stack Overflow users? Why isn't the content of field Display Name displayed for Stack Overflow user erikkallen?
The screenshot below is from Opera, but I see the same in Firefox (or rather I don't).

alt text http://www.pil.sdu.dk/1/until2039-12-31/SO/empty_erikkallen_16c.png

A: You do not have to set a display name (i.e. you keep your profile completely empty). The username of your OpenID URL is taken as SO username then.


text:
Q: RStudio Desktop 0.98.1006 for Windows unable to access mapped network drives Recently I updated my RStudio Desktop for Windows to the latest version 0.98.953. When running a previously working script accessing data stored on a mapped network drive (university personal file store), error occurred saying the specified path did not exist, which was not true - the directories and files were all accessible from Windows Explorer.
Further investigations showed that there were crosses on the concerned drive icons in RStudio's File - Open File... dialogue box.  However, using dir() to display these files in the native R GUI was OK, suggesting that it was a problem of RStudio's.  I have uninstalled, reinstalled RStudio and updated to the latest Version 0.98.1006 but the problem persisted.
I searched the RStudio community forums but only found one similar case reported (https://support.rstudio.com/hc/communities/public/questions/200655286-RStudio-can-t-see-my-network-directory?locale=en-us) and no practical reply. Could anyone with similar experience help me with this?
Many thanks in advance!

A: I faced a similar problem with Version 0.98.1074 and also with eclipse:
http://www.eclipse.org/forums/index.php/t/612569/
My (increasingly annoying) workaround is to manually open the mapped network drive, which works for both eclipse and RStudio. After initialization accessing files from the mapped network drive works perfectly.
Best regards


text:
Q: Adding nearline SAS disks to a controller with SAS disks I have a Dell Poweredge 840 server that currently has a pair of hot swappable 146Gb SAS disks attached to a SAS 5IR controller, configured as RAID 1.
I have two spare slots to add two add more storage, and have a need to add a relatively large amount of storage as cheaply as possible. The data on the new disks will mostly be temporary file storage.
I've explored adding SATA storage to the on board SATA interface, which is limited to 1TB per SATA disk, and am now looking at alternatives. I'm wondering about adding nearline SAS drives to the existing controller to give me lots of storage at near SATA pricing.
I'm a little nervous about mixing SAS and nearline SAS disks on the same controller even though no volumes will ever span the two disks types. I'm looking for advise on whether this would be a good idea or not?
I'm considering adding either 1 or 2 disks with a capacity of 2TB each. If I add two disks, I'll likely configure them as RAID 0 as capacity is more important than fault tolerance.

A: SAS uses higher signalling voltages than SATA so mixing those on the same backplane isn't the best of ideas, although you can get SATA interposer cards to allow SATA to be used on the same backplane.
Near line SAS however uses a proper SAS interface so there should be no issue with your intended setup even if you put them all on the SAS 5iR.
I would suggest using the SAS 5iR rather than the onboard SATA for a few reasons - the 5iR will be connected to your hotswap backplane and the onboard SATA won't. Also from my experience the onboard SATA on most poweredge's is just a basic SATA controller that doesn't support RAID in any way shape or form.

A: You can add the nearline disks to the same controller without any issues. I'd still hesitate on using RAID0 unless loss of data is no big deal.


text:
Q: Magento2 Category Attribute I have created Attribute on category level
now I want to fetch the value of this attribute. I have tried below code
 $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $object_manager =
 $_objectManager->create('Magento\Catalog\Model\Category')->load($cat_id);
 echo "<pre>"; print_r($object_manager->getData('google_taxonomy'));

but not result coming.

A: Try the below solution,
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category'); //Get Current Category
    $PCategory = $objectManager->get('Magento\Catalog\Model\CategoryFactory')->create()->load($category->getId());

    echo $PCategory->getGoogleTaxonomy();


text:
Q: How to print printable characters and characters like '\n', '\t', etc I'm trying to display an HTTP frame. The problem is that some characters are not recognized. I use the isprint function.
Here is the function I created:
void printAscii(const int dataLength, const char *data){
  if (dataLength <= 0) {
    printf("No data (data length <= 0)\n");
  } else {
    printf("Warning: Unsupported characters are not displayed.\n\n");
    size_t i;
    printf("|- ");
    for (i = 0; i < dataLength; i++) {
      if (isprint(data[i])) {
        printf("%c", data[i]);
      }
      if (data[i] == '\n') {
        printf("|- ");
      }
    }
  }
}

The problem is that characters like "\ n" and "\ t" are not displayed either.
I thought of adding additional conditions in my function
  if (isprint(data[i]) || data[i] == '\n' || data[i] == '\t')

But I was wondering if there was not a more "clean" way?
I started the C there is not too long so do not hesitate if I made mistakes in my function.
EDIT
I may not have been clear enough in my question.
My project is a frame analyzer (pcap), and I get to the HTTP part. The frame contains only ASCII, so it is relatively easy to display this type of frame. The problem is that some characters are not displayed directly (encoding for images for example) so I decided to ignore these characters. The problem is with isprint () characters like '\ n', '\ t', etc ... are not displayed either and so my display is less "beautiful".
For example, this HTTP trame :

Foo

Bar

become :

Foo

Bar

which is less understandable.
Edit 2
I found. This code works as desired.
  if (isprint(data[i]) || isspace(data[i]))

Thanks anyway.

A: I found. This code works as desired.
  if (isprint(data[i]) || isspace(data[i]))

– Eraseth

A: Since these characters ASCII values are white space you will not see them with the "%c" format specifier.  What you need to do is use the hexadecimal string format specifier in printf as follows:
printf("%x", data[i]);
Note: The "%x"(lowercase) and "%X"(uppercase) means to display the hexadecimal value of the character instead of the actual ASCII value.
I should also note, that formatting the string in this fashion will give you the raw data.  This is what it would look like in memory or what it would look like if it were transmitted on the wire. So, a \n would be a 0x0A and a \t would be a 0x09
See the following link for a great reference on what all the specifiers mean.
http://www.cplusplus.com/reference/cstdio/printf/
Also, here is another link to an ASCII Table.
https://www.techonthenet.com/ascii/chart.php
Hope this helps!


text:
Q: git log --follow, show all commits including merges I would like to git log --follow file.ext but showing all commits, including merges.
Tried no-max-parents, but not helping.

A:
The -m will do the trick for you, log -m is for get into the merges.

git log -m --oneline --full-history --follow file.ext
This should follow the file  in the Merges [-m].
And i assume you was aiming to use --min-parents=2 instead of no-max-parents. The --min-parents=2 is the same as --merged since it will return the commit with more then one parent.
You can always add some extra flags to display the results in a more friendly way:
git log -m --name-only --oneline --follow file.ext. It will display the results with the SHA-1 of the commits as well with the message


text:
Q: Java exception: "Can't get a Writer while an OutputStream is already in use" when running xAgent I am trying to implement Paul Calhoun's Apache FOP solution for creating PDF's from Xpages (from Notes In 9 #102).  I am getting the following java exception when trying to run the xAgent that does the processing --> Can't get a Writer while an OutputStream is already in use
The only changes that I have done from Paul's code was to change the package name.  I have isolated when the exception happens to the SSJS line:  var jce: DominoXMLFO2PDF = new DominoXMLFO2PDF();  All that line does is instantiate the class, there is no custom constructor.  I don't believe it is the code itself, but some configuration issue.  The SSJS code is in the beforeRenderResponse event where it should be, I haven't changed anything on the xAgent.
I have copied the jar files from Paul's sample database to mine, I have verified that the build paths are the same between the two databases.  Everything compiles fine (after I did all this.)  This exception appears to be an xpages only exception.

A: Here's what's really going on with this error:
XPages are essentially servlets... everything that happens in an XPage is just layers on top of a servlet engine. There are basically two types of data that a servlet can send back to whatever is initiating the connection (e.g. a browser): text and binary.
An ordinary XPage sends text -- specifically, HTML. Some xAgents also send text, such as JSON or XML. In any of these scenarios, however, Domino uses a Java Writer to send the response content, because Writers are optimized for sending Character data.
When we need to send binary content, we use an OutputStream instead, because streams are optimized for sending generic byte data. So if we're sending PDF, DOC/XLS/PPT, images, etc., we need to use a stream, because we're sending binary data, not text.
The catch (as you'll soon see, that's a pun) is that we can only use one per response.
Once any HTTP client is told what the content type of a response is, it makes assumptions about how to process that content. So if you tell it to expect application/pdf, it's expecting to only receive binary data. Conversely, if you tell it to expect application/json, it's expecting to only receive character data. If the response includes any data that doesn't match the promised content type, that nearly always invalidates the entire response.
So Domino in its infinite wisdom protects us from making this mistake by only allowing us to send one or the other in a single request, and throws an exception if we disobey that rule.
Unfortunately... if there's any exception in our code when we're trying to send binary content, Domino wants to report that to the consumer... which tries to invoke the output writer to send HTML reporting that something went wrong. Except we already got a handle on the output stream, so Domino isn't allowed to get a handle on the output writer, because that would violate its own rule against only using one per response. This, in turn, throws the exception you reported, masking the exception that actually caused the problem (in your case, probably a ClassNotFoundException).
So how do we make sure that we see the real problem, and not this misdirection? We try:
try {
  /*
   * Move all your existing code here...
   */
} catch (e) {
  print("Error generating dynamic PDF: " + e.toString());
} finally {
  facesContext.responseComplete();
}

There are two reasons this is a preferred approach:

*

*If something goes wrong with our code, we don't let Domino throw an exception about it. Instead, we log it (instead of using print to send it to the console and log, you could also toss it to OpenLog, or whatever your preferred logging mechanism happens to be). This means that Domino doesn't try to report the error to the user, because we've promised that we already reported it to ourselves.

*By moving the crucial facesContext.responseComplete() call (which is what ultimately tells Domino not to send any content of its own) to the finally block, this ensures it will get executed. If we left it inside the try block, it would get skipped if an exception occurs, because we'd skip straight to the catch... so even though Domino isn't reporting our exception because we caught it, it still tries to invoke the response writer because we didn't tell it not to.

If you follow the above pattern, and something's wrong with your code, then the browser will receive an incomplete or corrupt file, but the log will tell you what went wrong, rather than reporting an error that has nothing to do with the root cause of the problem.

A: I almost deleted this question, but decided to answer it myself since there is very little out on google when you search for the exception.
The issue was in the xAgent, there is a line importPackage that was incorrect.  Fixing this made everything work.  The exception verbage:  "Can't get a Writer while an OutputStream is already in use"  is quite misleading.   I don't know what else triggers this exception, but an alternative description would be "Java class ??yourClass?? not found"
If you found this question, then you likely have the same issue. I would ignore what the exception actually says, and check your package statements throughout your application.  The java code will error on its own, but your SSJS that references the java will not error until runtime, focus on that code.

A: Update the response header after the body can solve this kind of problem, example :
HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();

response.getWriter().write("...");

response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");


text:
Q: How to use Google Docs as you would Dropbox (or any other online backup site) What I would like to do is have files sync in the background with my Google Docs account, both up, and down.
Is there any way to do this? I use Mint 11, if it helps. Thanks!

A: Check out https://www.insynchq.com which support multiple Google Drive accounts and offline Google docs editing. It is available in multiple platforms (mac, windows, linux and mobile platforms).
Hope it helps!


text:
Q: Explorerer and Discoverer I'm trying to figure out whether exploration can imply discovery and discovery imply exploration. I think these two terms are linked.

*

*An explorer can discover when he explores.

*A discoverer may need to explorer in order to discover.

Imaging a person who is sent into a cave to explore it and he discovers ancient glyphs and objects. Or imaging a person who is working on discovering a new energy source. He explores different sources and places.
Am I on the right track?

A: Certainly an explorer is someone who sets out with the intention to discover something.  The explorer might fail to discover anything, in which case we could  say:

He discovered nothing but destitution, dejection, and death

but while this sounds nice it's not the same as making a significant discovery.
A discoverer is someone who has discovered something, ordinarily through some kind of exploration, but possibly by accident.  For example, there used to be this commercial for Reese's Peanut Butter cups, in which two people accidentally discover that chocolate and peanut butter taste good together.
(Actually Reese was a real person who spent many years exploring different confections before he discovered this particular, very successful, combination.)
So the terms are related but not synonymous.  An explorer might be a discoverer, and a discoverer an explorer, but neither requires the other.


text:
Q: What is the sports hall in schools called in English? What is the sports hall in schools called in English?
I've translated from my language and the translation is "sport venue", but the according to the picture on Wikipedia I suspect that it is not what I'm looking for.
I'm looking for the name of the sports hall in schools, such as in the following picture:

A: That would be an (indoor) "gym" or "gymnasium".
From Wikipedia:

A gym, short for gymnasium, is an open air or covered location for gymnastics, athletics, and gymnastic services. The word is derived from the ancient Greek gymnasium. They are commonly found in athletic and fitness centers, and as activity and learning spaces in educational institutions. "Gym" is also slang for "fitness center", which is often an indoor facility.

A: In British School, that would be more likely to be called a 'Sports Hall' than a 'Gym'. In Britain, one tends to think of a 'Gym' as a room with weights, and machines, rather than a large hall.

A: In the US, we definitely call the pictured facility a 'gym,' or 'gymnasium.' We also very often refer to the room with weights and such as 'the gym,' though never 'gymnasium,' which would refer to the 'sports hall.' The room with weights and such is often referred to as 'the weight room' in schools. However, when referring to a fitness club, we also call that 'the gym,' colloquially.
I'd never heard the term 'sports hall' before reading this post, though it makes sense.

A: I'm nearly 42 and British. Sports hall is the term I would use for an indoor space for sport in a school with floor markings. We also used to call it the gym and that was because it also had equipment in it like crash mats and ropes and bars.
My school had another structure that was vast and used for sport with a sloped roof and was called the dutch barn, but that was so school specific I think anyone who went to my school is now going 'she went to my school' in their heads.
so sports hall or gym are both fine

A: We called the room pictured "sports hall", we had several of these in different buildings of the school but we'd differentiate between them by saying "the sports hall in D-block, F-block" etc. we also had a building devoted to one large sports hall which was THE sports hall, part of the same building was a room with running machines and weights etc and that's what we called the gym (I went to a sports specialist school in case you couldn't tell lmao).
The hall where assemblies were held was called the main hall (I've never heard "auditorium" outside of American media), which was also next to the canteen (cafeteria for Americans) so that's where the long tables were during lunch. We sometimes had dance lessons in there tho and dance/music/drama shows on the stage but that one was never used for sports as far as i remember. However almost all of them doubled as exam rooms during exam season lmao. I attended school in South east England 2000s-2010s if that helps anyone.

A: There are several terms that might be used. It can be called a gymnasium (gym for short) or an indoor court. Such structures are also often used to hold assemblies, and are therefore auditoriums. And since they can be used both as a sports venue and an auditorium, often they are called a "multipurpose room" (often a multipurpose room also has a stage so that it can be used to put on plays).

A: A Grammar School (Selective secondary school age 11-18) in Yorkshire 1971 to 1978 it was called the "Sports Hall"

A: Another British English term not mentioned here (perhaps more commonly used in Scotland) would be "Games Hall".
A quick Google search confirms that this is used by Glasgow Clyde College and in Shetland among other places, as well as images of the same kind of room.


text:
Q: How can duplicate processing of messages be avoided if two instances of same app subscribes to a topic? I have two instances of same application running and they both subscribe to same topic. Messages are  going to to published to both servers and both servers are going to process that same message. How can duplicate processing of messages be avoided if two instances of same app subscribes to a (same)topic using a stateless approach?

A: If the servers are just a replication of each other, they should not have separate sources of data that they will listen to. The whole point of creating multi-instance architecture is to parallelize, and so speed up, processing of things. You should have a single source of data so that the once a message is taken in hand by one server it is not anymore available for the other, which can focus on following messages.

A: Topic has exactly opposite purpose from what you try to achieve.
Queue stands for it.
If you still want to use topic you must have only one subscriber/listener on top of your application instances.
Then you have to force on your own any load balance algorithm between your application instances (e.g. round-robin or something more complex).


text:
Q: Converting a text file into a .tex file using C++ I have a text file which contains data like this:
word: 'Swine';      conf: 92.03;pointsize:'48':,font_name:'Verdana_Bold',X1:'152', X2:'283', Y1: '166', Y2: '202
word: 'flu';    conf: 93.43;pointsize:'48':,font_name:'Verdana_Bold',X1:'299', X2:'354', Y1: '164', Y2: '202
word: 'tightens';   conf: 90.12;pointsize:'48':,font_name:'Verdana_Bold',X1:'370', X2:'551', Y1: '164', Y2: '211
word: 'its';    conf: 96.04;pointsize:'48':,font_name:'Verdana_Bold',X1:'568', X2:'617', Y1: '166', Y2: '202
word: 'grip';   conf: 90.41;pointsize:'48':,font_name:'Verdana_Bold',X1:'632', X2:'716', Y1: '166', Y2: '211
word: 'over';   conf: 94.29;pointsize:'48':,font_name:'Verdana_Bold',X1:'732', X2:'831', Y1: '175', Y2: '202
word: 'India';      conf: 94.00;pointsize:'48':,font_name:'Verdana_Bold',X1:'848', X2:'953', Y1: '164', Y2: '202

With the following meanings:
Word: Actual word to be printed
Pointsize : Font size
Font name: Name of font used
X1,X2,Y1,Y2: Coordinates of location of word in the document

I want to take all this data, and put it as it is in a latex document. Now, I know I have to make a C++ code for this, by first opening a .tex file and start writing down the data by reading from the text file. The problem I am facing is, how to set the exact fonts and size of the text as mentioned in the file? Thanks!
Edit: Finally, I want to make a pdf file from the generated .tex file using the terminal commands.
Also, I referred the link: https://priyankacool10.wordpress.com/2012/05/10/creating-tex-file-using-c-program/ and I just need to know, what all do I have to write as part of my C++ code in order to make the .tex file.
I am not asking for the entire C++ code, just the exact syntax and package details for the same.
Sample Output:

Edit2: I will need a C++ code for reading the input words from the text file and writing it into a tex file. Is their any other way of doing it?
Edit3: (Error)
* Redefining document command \oldstylenums with arg. spec. 'm' on line 128.
*************************************************
) (/usr/share/texlive/texmf-dist/tex/latex/fontspec/fontspec-luatex.sty
(/usr/share/texlive/texmf-dist/tex/latex/base/fontenc.sty

! Package fontenc Error: Encoding file `eu2enc.def' not found.
(fontenc)                You might have misspelt the name of the encoding.

See the fontenc package documentation for explanation.
Type  H <return>  for immediate help.
 ...

l.99 \ProcessOptions*

A: It seems that TeX can read the file directly, I don't think you need C++

If your input text is text1.txt then the above is made by the following tex, processed by xelatex.
\documentclass{article}
\usepackage{fontspec}

\newread\dfile
\openin\dfile=text1.txt

\def\printword#1: '#2'#3pointsize:'#4'#5font_name:'#6'#7\relax{%
\fontsize{#4}{\numexpr#4+6\relax}\selectfont\dofont{#6}#2 }

\def\dofont#1{\csname do #1\endcsname}
\expandafter\def\csname do Verdana_Bold\endcsname{\bfseries\fontspec{Verdana}}

\def\partest{\par}
\begin{document}

\raggedright
\loop
\ifeof\dfile\else
\read\dfile to \tmp
\ifx\tmp\partest
\par
\else
\expandafter\printword\tmp\relax
\fi
\repeat

\end{document}

With the new question and new data file you want to use picture mode

This does what asked although the coordinates seem rather close for 48pt text?
The font could be scaled to a proportion (say half) of the specified size.
\documentclass{article}
\usepackage{fontspec}
\textwidth60cm
\pdfpagewidth80cm

\makeatletter
\newread\dfile
\openin\dfile=text2.txt

\def\printword#1: '#2'#3pointsize:'#4'#5font_name:'#6'#7\relax{%
\edef\tmp{\zap@space#7 \@empty}%
\expandafter\getcoords\tmp\relax
{\fontsize{#4}{\numexpr#4+6\relax}\selectfont\dofont{#6}#2}}

\def\dofont#1{\csname do #1\endcsname}
\expandafter\def\csname do Verdana_Bold\endcsname{\bfseries\fontspec{Verdana}}

\def\getcoords#1X1:'#2'#3Y1:'#4'#5\relax{%
\typeout{#2/#4}%
\put(#2,4)}
\def\partest{\par}
\begin{document}

\hspace*{-10cm}\begin{picture}(200,200)
\loop
\ifeof\dfile\else
\read\dfile to \tmp
\ifx\tmp\partest
\par
\else
\expandafter\printword\tmp\relax
\fi
\repeat
\end{picture}

\end{document}

A: I know, Python is not C++, but I wanted some exercise in this language.
The specified font size and the area locations do not fit too well, even
if the font size would be scaled down by around 75%. Therefore I have used \resizebox to force the text to the size of the specified area location.
The word is placed via \put of the picture environment. There are more
powerful environments for drawings like TikZ or pstricks. But advanced features are not needed here and picture is much more efficient and faster.
The coordinates are transformed, since the vertical axis has the opposite
direction of the y values need for the picture environment. The program
calculates the minimum and maximum values and sets the lower left corner
as new origin.
Before the word is set, the program sets some lines to show the specified
rectangle.
The Python program can be called with the text file name as argument. Without argument, the text data are taken from the standard input. Output is standard output, which can be redirected to a TeX file.
The font and size settings are optimized, thus that the font is only defined
once. Also the font is only set for a word, if the font has changed.
The generated file is processed with LuaLaTeX or XeLaTeX because of package fontspec. Then it is easier to use arbitrary font names, as long as LuaTeX or XeTeX know, where to find them.
Some characters need special treatment in TeX, see the program code for an example, how to deal with these characters.
A little more elegant would be to put the TeX preamble into a new LaTeX class
file. Then the generated TeX file would just contain \documentclass{...} as whole preamble.
#!/usr/bin/env python

import fileinput;
import re;

line_pattern = re.compile(
        r"word:\s*'(?P<word>[^']+)';\s*"
        r"conf:\s*[0-9\.]+;\s*"
        r"pointsize:\s*'(?P<pointsize>\d+)':,"
        r"font_name:\s*'(?P<font_name>[^']+)',\s*"
        r"X1:\s*'(?P<X1>\d+)',\s*"
        r"X2:\s*'(?P<X2>\d+)',\s*"
        r"Y1:\s*'(?P<Y1>\d+)',\s*"
        r"Y2:\s*'(?P<Y2>\d+)'\s*")

# Mapping from character to TeX representation
tex_char_map = {}
for c in "%#$&":
    tex_char_map[c] = "\\" + c
for c in "_^~\\{}":
    tex_char_map[c] = r"\symbol{" + str(ord(c)) + "}"

fonts = set()
words = []
x_min = None
x_max = None
y_min = None
y_max = None

for line in fileinput.input():
    match = line_pattern.match(line)
    if match:
        word = match.group("word")
        pointsize = match.group("pointsize")
        font_name = match.group("font_name")
        X1 = int(match.group("X1"))
        X2 = int(match.group("X2"))
        Y1 = int(match.group("Y1"))
        Y2 = int(match.group("Y2"))
        fonts.add(font_name)
        data = (word, pointsize, font_name, X1, X2, Y1, Y2)
        words.append(data)
        # assuming X1 <= X2 and Y1 <= Y2
        if x_min is None or X1 < x_min:
            x_min = X1
        if x_max is None or X2 > x_max:
            x_max = X2
        if y_min is None or Y1 < y_min:
            y_min = Y1
        if y_max is None or Y2 > y_max:
            y_max = Y2

tex_preamble = r"""\NeedsTeXFormat{LaTeX2e}
\documentclass[border=10pt]{standalone}
\usepackage{fontspec}
\newcommand*{\NewFont}[1]{%
  \expandafter\newfontfamily\csname#1\endcsname{#1}%
}
\newcommand*{\SetFont}[1]{%
  \csname#1\endcsname
  \ignorespaces
}
\newdimen\FontSize
\newdimen\FontUnitLength
\setlength{\FontUnitLength}{.75bp}
\newcommand*{\SetSize}[1]{%
  \setlength{\FontSize}{#1\FontUnitLength}%
  \fontsize{\FontSize}{1.2\FontSize}\selectfont
  \ignorespaces
}
%\usepackage{graphicx}
\newcommand*{\Put}{}
\def\Put(#1,#2)(#3,#4)#5{%
  \put(#1,#2){\line(1,0){#3}\line(0,1){#4}}%
  \put(#1,#2){\line(0,1){#4}}%
  \put(#1,#2){\put(0,#4){\line(1,0){#3}}}%
  %\put(#1,#2){\makebox(#3,#4)[lb]{\resizebox{#3\unitlength}{!}{#5}}}%
  \put(#1,#2){%
    \makebox(#3,#4)[lb]{%
      \resizebox{#3\unitlength}{#4\unitlength}{%
        \raisebox{\depth}{#5}%
      }%
    }%
  }%
  %\put(#1,#2){\makebox(#3,#4)[lb]{#5}}%
}
\setlength{\unitlength}{1bp}"""
print(tex_preamble)

for font in fonts:
    print(r"\NewFont{" + font + "}")

print(r"\begin{document}")

picture_width = x_max - x_min
picture_height = y_max - y_min
print(r"\begin{picture}(%d,%d)" % (picture_width, picture_height))

current_font = ""
current_pointsize = ""
for word, pointsize, font_name, X1, X2, Y1, Y2 in words:
    if font != current_font:
        print(r"\SetFont{" + font + "}")
        current_font = font

    if pointsize != current_pointsize:
        print(r"\SetSize{" + pointsize + "}")
        current_pointsize = pointsize

    w = ""
    for c in word:
        if c in tex_char_map:
            w += tex_char_map[c]
        else:
            w += c
    width = X2 - X1
    height = Y2 - Y1
    x = X1 - x_min
    y = picture_height - (Y2 - y_min)
    print(r"\Put(%d,%d)(%d,%d){%s}" % (x, y, width, height, w))

print(r"\end{picture}")

print(r"\end{document}")

The input data (with closing single quote added for the value of Y2):
word: 'Swine';      conf: 92.03;pointsize:'48':,font_name:'Verdana_Bold',X1:'152', X2:'283', Y1: '166', Y2: '202'
word: 'flu';    conf: 93.43;pointsize:'48':,font_name:'Verdana_Bold',X1:'299', X2:'354', Y1: '164', Y2: '202'
word: 'tightens';   conf: 90.12;pointsize:'48':,font_name:'Verdana_Bold',X1:'370', X2:'551', Y1: '164', Y2: '211'
word: 'its';    conf: 96.04;pointsize:'48':,font_name:'Verdana_Bold',X1:'568', X2:'617', Y1: '166', Y2: '202'
word: 'grip';   conf: 90.41;pointsize:'48':,font_name:'Verdana_Bold',X1:'632', X2:'716', Y1: '166', Y2: '211'
word: 'over';   conf: 94.29;pointsize:'48':,font_name:'Verdana_Bold',X1:'732', X2:'831', Y1: '175', Y2: '202'
word: 'India';      conf: 94.00;pointsize:'48':,font_name:'Verdana_Bold',X1:'848', X2:'953', Y1: '164', Y2: '202'

The generated LaTeX file:
\NeedsTeXFormat{LaTeX2e}
\documentclass[border=10pt]{standalone}
\usepackage{fontspec}
\newcommand*{\NewFont}[1]{%
  \expandafter\newfontfamily\csname#1\endcsname{#1}%
}
\newcommand*{\SetFont}[1]{%
  \csname#1\endcsname
  \ignorespaces
}
\newdimen\FontSize
\newdimen\FontUnitLength
\setlength{\FontUnitLength}{.75bp}
\newcommand*{\SetSize}[1]{%
  \setlength{\FontSize}{#1\FontUnitLength}%
  \fontsize{\FontSize}{1.2\FontSize}\selectfont
  \ignorespaces
}
%\usepackage{graphicx}
\newcommand*{\Put}{}
\def\Put(#1,#2)(#3,#4)#5{%
  \put(#1,#2){\line(1,0){#3}\line(0,1){#4}}%
  \put(#1,#2){\line(0,1){#4}}%
  \put(#1,#2){\put(0,#4){\line(1,0){#3}}}%
  %\put(#1,#2){\makebox(#3,#4)[lb]{\resizebox{#3\unitlength}{!}{#5}}}%
  \put(#1,#2){%
    \makebox(#3,#4)[lb]{%
      \resizebox{#3\unitlength}{#4\unitlength}{%
        \raisebox{\depth}{#5}%
      }%
    }%
  }%
  %\put(#1,#2){\makebox(#3,#4)[lb]{#5}}%
}
\setlength{\unitlength}{1bp}
\NewFont{Verdana_Bold}
\begin{document}
\begin{picture}(801,47)
\SetFont{Verdana_Bold}
\SetSize{48}
\Put(0,9)(131,36){Swine}
\Put(147,9)(55,38){flu}
\Put(218,0)(181,47){tightens}
\Put(416,9)(49,36){its}
\Put(480,0)(84,45){grip}
\Put(580,9)(99,27){over}
\Put(696,9)(105,38){India}
\end{picture}
\end{document}


text:
Q: Как считать слово из файла в Паскале? Не могу сообразить, нужна Ваша подсказка.
Можно использовать только packed array. Переменные типа string использовать нельзя. Т.е. использовать стандарт Паскаля, а не тубро и т.п.
Как мне считать слово и присвоить его переменной? Длина слова неизвестна.
Не могу сообразить механизм присваивания.

A: считывайте посимвольно до первого пробела или знака препинания


text:
Q: Assigning the output of 'ps -a -u user -F` to a SHELL variable I 'm trying to capture VNC sessions running. So I use as below
    STAT = `ps -a -u user -F | grep "Xvnc :" | grep -v grep`

If VNC session is running, the output of command "ps -a -u user -F" is multiple lines. Then STAT is assigned all the lines. I 'm just interested just ONLY ONE line, as all I wanted all the SESSION NUMBER s of VNC running for the "user" . I tried the command below, to use "@" as my delimiter (insteard of "\n" to parse STAT). It doesn't seem to work
    STAT = `ps -a -u user -F | grep "Xvnc :" | grep -v grep | tr -s "\n" "@"

All I need is to grab the VNC session number(s). Any suggestions appreciated.

A: If your version of ps supports it, you would be better off reformatting its output to make it easier to parse. On my system I can do this:
$ ps -o command= -C Xvnc
Xvnc :1

$ ps_output="$(ps -o command= -C Xvnc)"

$ vnc_display="${ps_output#Xvnc :}"

$ echo $vnc_display
1

Of course this method has a number of limitations. It does not select a particular user, and will not work if you used other command-line options to Xnc, or if you have multiple sessions running. So instead, you might want to do something like this:
$ grep -z "^:" "/proc/$(pgrep -u user Xvnc)/cmdline"
:1

Set to a parameter with command substitution, and then potentially remove the colon if that's what you want. This still won't work if a single user is running multiple VNC sessions. You'll have to iterate over the results of $(pgrep -u user Xvnc) instead. If you don't care about nicely parsed output since a human is dealing with the results anyway, you could always just do this:
$ ps $(pgrep -u user Xvnc)
  PID TTY      STAT   TIME COMMAND
 3600 pts/2    S      0:00 Xvnc :2
 3606 pts/2    S      0:00 Xvnc :3

The way this works is by running the pgrep command, which will search for processes that meet specified criteria (in this case, running under user user and with the command name Xvnc). Here's what its output would look like:
$ pgrep -u user Xvnc
3600
3606

Encosing this in $( and ) engages the shell's command substitution facility. This takes the output of a command and substitutes it in as part of your command line. (Run info "(bash)Command Substitution") for more information). When you run ps $(pgrep -u user Xvnc), it causes the shell to interpret it as this:
$ ps 3600 3606

which will produce the same output. You can see exactly what Bash is doing if you use the set -x debug option:
$ set -x
$ ps $(pgrep -u user Xvnc)
++ pgrep -u user Xvnc
+ ps 3600 3606
  PID TTY      STAT   TIME COMMAND
 3600 pts/2    S      0:00 Xvnc :2
 3606 pts/2    S      0:00 Xvnc :3

A: To process a list of session numbers:
$ for snumber in $(ps -a -u USERNAME -F | grep -o -P '[X]vnc :\d+' | awk -F':' '{ print $2 }'); do echo Session ${snumber}; done
Session 2
Session 1
$

To have a list of session numbers in one variable:
LIST=$(ps -a -u USERNAME -F | grep -o -P '[X]vnc :\d+' | awk -F':' '{ print $2 }' | tr '\n' ' ' | sed 's; $;;')

A: If you just want X display numbers (e.g. :1, :2), you could try:
  STAT=`ps -a -u ${USER} -F | \
     perl -ne '$\=" ";if (/^.{64,}Xvnc.*?:([0-9]+)/){print $1}'

This might be a little safer under esoteric conditions, because it skips the first 64 columns of ps output before looking for Xvnc, and the regexp is complex enough that it can't match itself. This will load $STAT with a space-delimited list of X display ID's, e.g. "2 4 6" or similar, suitable for use in for n in $STAT; do echo "$USER is on :$n"; done
(broken-out:
   $\=" ";       # print a space after every print command
   if (/^        # start of line (matches the input line
        .{64,}   # at least 64 characters
        Xvnc     # the bit you wanted
        .*?      # any other spaces or parameters that might be around
        :        # find a colon
        (\d+)    # find, and keep, at least one digit
        /x)      # (the /x only so I can put comments into the regex here)
   { print $1 }  # print the digits that we found in () group 1

and perl -ne puts an automatic while(<>){} loop in place to read the input)


text:
Q: Etag's are not being taken out of css,js, and images? I'm attempting to reduce the loading speed of my site by using mod_deflate and mod_headers, which compresses the content and sets expire dates but also deletes the ETag's for my content. It is not however deleting the ETags from my images (png's), css, and js according to Yslow.
My .htaccess code:
<IfModule mod_deflate.c>
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$            HAVE_Accept-Encoding
            RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
        </IfModule>
    </IfModule>
    <IfModule filter_module>
        FilterDeclare   COMPRESS
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/html
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/css
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/plain
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/xml
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/x-component
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/javascript
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/json
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xml
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xhtml+xml
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/rss+xml
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/atom+xml
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/vnd.ms-fontobject
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/svg+xml
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/x-font-ttf
        FilterProvider  COMPRESS  DEFLATE resp=Content-Type $font/opentype
        FilterChain     COMPRESS
        FilterProtocol  COMPRESS  DEFLATE change=yes;byteranges=no
    </IfModule>
    <IfModule !mod_filter.c>
        # Legacy versions of Apache
        AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
        AddOutputFilterByType DEFLATE application/javascript
        AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
        AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
        AddOutputFilterByType DEFLATE image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype
    </IfModule>
</IfModule>
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault                          "access plus 1 month"
    ExpiresByType text/cache-manifest       "access plus 0 seconds"
    ExpiresByType text/html                 "access plus 0 seconds"
    ExpiresByType text/xml                  "access plus 0 seconds"
    ExpiresByType application/xml           "access plus 0 seconds"
    ExpiresByType application/json          "access plus 0 seconds"
    ExpiresByType application/rss+xml       "access plus 1 hour"
    ExpiresByType image/x-icon              "access plus 1 month"
    ExpiresByType image/gif                 "access plus 1 month"
    ExpiresByType image/png                 "access plus 1 month"
    ExpiresByType image/jpg                 "access plus 1 month"
    ExpiresByType image/jpeg                "access plus 1 month"
    ExpiresByType video/ogg                 "access plus 1 month"
    ExpiresByType audio/ogg                 "access plus 1 month"
    ExpiresByType video/mp4                 "access plus 1 month"
    ExpiresByType video/webm                "access plus 1 month"
    ExpiresByType text/x-component          "access plus 1 month"
    ExpiresByType font/truetype             "access plus 1 month"
    ExpiresByType font/opentype             "access plus 1 month"
    ExpiresByType application/x-font-woff   "access plus 1 month"
    ExpiresByType image/svg+xml             "access plus 1 month"
    ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
    ExpiresByType text/css                  "access plus 1 year"
    ExpiresByType application/javascript    "access plus 1 year"
    ExpiresByType text/javascript           "access plus 1 year"
    <IfModule mod_headers.c>
        Header append Cache-Control "public"
    </IfModule>
</IfModule>
<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None

Taken from: http://html5boilerplate.com/

A: I think I figured it out..
YSlow was caching the results. Changing browsers (from Safari to Firefox) seemed to show that the ETags were in fact deleted.


text:
Q: SQL to remove duplicated rows I've written a sql statement to only keep one instance (minimum id) where there are duplicated product_codes. The issue is that the statement is very inefficient and takes absolutely ages to run, so I'm hoping there is a more efficient way to write it
The dataset is structured as:
id  product_code  cat_desc      product_desc
1   2352345       423           COCA COLA
2   8967896       457           FANTA
3   6456466       435           SPARKLING WATER
4   3562314       457           STILL WATER

The statement is:
DELETE
FROM raw_products_inter
WHERE id IN (SELECT id
             FROM raw_products_inter outer_table
             WHERE product_code IN (SELECT product_code
                                    FROM raw_products_inter
                                    GROUP BY 1
                                    HAVING COUNT(id) > 1)
             AND   id NOT IN (SELECT MIN(id)
                              FROM raw_products_inter inner_table
                              WHERE inner_table.product_code = outer_table.product_code))

A: You should be able to boost the performance using an EXISTS condition:
DELETE
  FROM raw_products_inter P
 WHERE EXISTS (
          SELECT *
            FROM raw_products_inter OP
           WHERE OP.product_code = P.product_code
             AND OP.id < P.id
       )


text:
Q: Parse files in FileList object I am using FormData to upload multiple files in my grails project.The files needs to be uploaded via Ajax. I have used following code for ajax upload. But in controller, I get the params as [object FileList]. How do I get files from this object. Is there any way to change this object to multipart?

jQuery('#file-save').click(function() {
  if (jQuery('#form input[type="file"]')) {
    var form = jQuery("#form").find('input[type="file"]');

    var picData = new FormData();
    picData.append('userFiles', form.get(0).files);
    picData.append('userId', '$usrId');

    jQuery.ajax({
      url: '/file/upload',
      type: 'post',
      dataType:'json',
      data: picData,
      enctype: "multipart/form-data",
      contentType: false,
      processData: false,
      success: function(data) {
        console.log("success");
      }
    });
  }
});

The controller code is:

def upload(){
    def userId = params.userId
    def inputFile = params.userFiles
    println(inputFile)
    inputFile.each{i,j->
        println(i)
        println(j)
    }
}

When I debug, I get params.userFiles : "[object FileList]". Any insights would be appreciated.

A: You most likely need to loop through the files client side, adding the same key for each one
var picData = new FormData();
// loop through form.get(0).files
picData.append('userFiles', file);
// end loop
picData.append('userId', '$usrId');


text:
Q: How to change font family of incoming HTML email in Outlook 2007 After our company switched to Microsoft Windows 7 and Microsoft Office 2007 I noticed that most incoming email is hard to read since the default Microsoft Office font was used when the message was composed and this font looks pretty fuzzy. I know how I could change the format of incoming email from HTML to plain text but I would loose all the formatting in this case.
So what I'm looking for is a way to define a font for incoming HTML email, e.g. Arial, so that only the font family is changed but everything else is untouched (bold, italic, colour etc). I looked through all options and searched the web for a solution but couldn't find anything yet.
Anybody knows a solution for this?

A: See here  http://www.slipstick.com/outlook/email/to-change-the-font-on-incoming-messages
"... you cannot easily control the font used to read HTML messages, since most people who send HTML mail specify the font they want their messages to appear in. If you're bothered by that, you can follow these steps to set a default font and make an HTML message use that font.
To set the default HTML font:

*

*In Internet Explorer, choose Tools | Internet Options.

*Click the Fonts button.

*On the Web page font list, select the font you want to use as your default.

*Click OK to return to Internet Explorer. Note that this change affects web pages, not just HTML mail messages.

To make a message use your default HTML font:

*

*Choose Edit | Edit Message.

*Choose Format | Plain Text, and respond Yes when you're asked whether you really want to change the format.

*Choose Edit | Edit Message.

*Choose Format | HTML."

A: If the received mail has the font hardcoded,  then I don´t think there´s alot you can do. You can try changing the default font in IE. Maybe you want to read this.


text:
Q: Custom Translator Pricing The Translator Text API cost description is not clear to me on the page here:
Training a custom system is 1 character per character of training material in source text.

*

*Is that a typo? 1 character per character of training material does not make sense to me. How should it be calculated if I opt for the  price tier S1 (pay as you go)?

Hosting a deployed system is 1M characters per month per deployed system.

*

*Does that mean if I am in the S1 tier, the monthly cost for hosting 4 deployed systems for the first 1M characters is $10x4=$40?

Many Thanks!

A: Training is charged per character in your source training material, with a minimum charge of 250K characters per training. For instance, if you had 500K characters in the source training material, you would be charged for 500K characters at the price for your tier. At the S1 level, that would be $5. The minimum charge for training is 250K characters ($2.50 at S1) if the source material has fewer than 250K characters.
Deployment is a flat charge of 1M characters per deployed system per month regardless of the number of characters in the training material. Yes, if you had 4 deployed systems at the S1 level, it would be $10 per system, so $10x4=$40 total per month for the 4 systems.


text:
Q: How to enable CORS allow-origin header in express server with swagger-ui My API server doesn't change or overwrite the Access-Control-Allow-Origin header.
I have an Angular 2+ application with an Express/Swagger-UI API.
The Access-Control-Allow-Origin header in the API cannot be '*' because I use 'withCredentials' in my requests and it's trigger an error on the browser.
I've used 'cors' for setting the CORS headers. Like this:
'use strict';

var configuration = require('./configuration');
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
var mongoose = require('mongoose');
var bluebird = require('bluebird');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var compression = require('compression');
var cors = require('cors');

app.use(bodyParser.json({ limit: '50mb' }));
app.use(compression());

SwaggerExpress.create(config, function(err, swaggerExpress) {
  if (err) { throw err; }

  swaggerExpress.register(app);
  var port = process.env.PORT || 10010;
  mongoose.Promise = bluebird;
  mongoose.connect(appConfig.dbConection());
  mongoose.connection.on('error', console.error.bind(console, 'connection error: '));
  mongoose.set('debug', true);
  mongoose.connection.once('open', function() {
    app.listen(port);
  })
});
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./api/swagger/swagger.yaml');

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
var allowedOrigins = ['http://localhost:4200', 'http://127.0.0.1:10010'];
app.use(cors({
    origin: (origin, callback) => {
        if (!origin) return callback(null, true);
        if (allowedOrigins.indexOf(origin) === -1) {
            return callback(new Error('The CORS policy for this site does not allow the specified Origin'), false);
        }
        return callback(null, true);
    },
    exposedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'api_key', 'x-api-key'],
    credentials: true
}));

The Access-Control-Allow-Origin should match the array of allowed hosts.
When I call the API from the browser, it first make an OPTIONS request, that look correct, like this:
Request URL: http://localhost:10010/v1/loginApp
Request Method: OPTIONS
Status Code: 204 No Content
Remote Address: [::1]:10010
Referrer Policy: no-referrer-when-downgrade

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: x-api-key
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Origin: http://localhost:4200
Access-Control-Expose-Headers: Origin,X-Requested-With,Content-Type,Accept,Authorization,api_key,x-api-key
Connection: keep-alive
Content-Length: 0
Date: Thu, 04 Apr 2019 08:25:53 GMT
Vary: Origin, Access-Control-Request-Headers
X-Powered-By: Express

But then it makes the GET/POST request, and then it has the default headers again:
Request URL: http://localhost:10010/v1/loginApp
Request Method: GET
Status Code: 200 OK
Remote Address: [::1]:10010
Referrer Policy: no-referrer-when-downgrade

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Origin,X-Requested-With,Content-Type,Accept,Authorization,api_key,x-api-key
Content-Length: 770
Content-Type: application/json; charset=utf-8
Date: Thu, 04 Apr 2019 08:25:53 GMT
ETag: W/"302-BwX5DjK/lUY+ueP6UZ9TgWOTw/s"
Vary: Origin
X-Powered-By: Express

I think something (probably swagger-UI) is overwriting my headers configuration, but I can't figure it out.

A: You need to register your CORS middleware before the Swagger GET/POST handlers.
The OPTIONS request is succeeding because Swagger doesn't register an OPTIONS handler, so the request reaches the middleware.
The GET/POST requests are failing before the Swagger handlers accept the request before it reaches the CORS middleware.
Move app.use(cors({... so it is before app.use('/api-docs', swaggerUi....

A: It seems as if swagger-express-mw comes with CORS support built-in, see swagger_controllers in your config/default.yaml. I had the same issue and fixed it by removing cors from there.

Like you, I suspect it's overwriting the Access-Control-Allow-Origin header but didn't have time to check it properly.


text:
Q: Replace a running python script with os.execl I may not be looking hard enough but I am trying to replace a running python script with another python script. Based on the research that I have done, using the os.execl function may be what I am looking for. I am a little bit confused about the arguments that should be used with the function. Can anyone please help explain to me how to just replace the currently running python script with another.

A: exec*() familiy replaces the whole process, keeping the process number (PID). If this is what you want...
One example inside Python interpreter. I replace the interpreter by echo. The first item in 'args' becomes the argv[0] which is the process name that is seen in ps or top.
>>> import os
>>> args=['process_name', 'bla', 'ble']
>>> os.execlp("/bin/echo", *args)
bla ble
/Users/epx $


text:
Q: Do i have to delete the event listener manually in websockets? Does the following code create duplicate on.message listeners ?
when i execute on.message once, the payloads array takes it's initial value each time
export default function ProjectChat() {

    const { id: projectId } = useParams()

    const [payloads, setPayloads] = useState([])
    const [messageBody, setMessageBody] = useState('')
    const [webSocket, setWebSocket] = useState(null)

    // Create the connection
    useEffect(() => {
        const url = `ws://localhost:3000/ws/${projectId}`;
        const ws = new WebSocket(url);
        setWebSocket(ws)

        return () => ws.close()
    }, [])

    useEffect(() => {
        if (webSocket !== null) {
            webSocket.onmessage = e => {
                const payload = JSON.parse(e.data);
                const allMessages = [...payloads, payload]
                setPayloads(allMessages)
            }
        }
    }, [webSocket, payloads])

    return
jsx

}

A: You can't create duplicate listeners with on.message. Every time you define on.message, you're over-writing the previous listener.
The addListener is the method which can lead to multiple listeners. In that case, you would want to run removeEventListener() on the listener you created inside your component's unmount phase return () => removeEvenListener(...).


text:
Q: How does Eclipse debug code in an application server? What communication is going on between Eclipse and my application server (JBoss) when I run the server from within Eclipse in debugging mode?  How does this work?

A: I think it is called JDWP (Java Debugging Wire Protocol) - read more here

A: When you start the server in debug mode, it listens on a specified TCP port. Eclipse connects to that port, and they talk using the Java Debug Wire Protocol (JDWP). Read the details here:
http://java.sun.com/j2se/1.5.0/docs/guide/jpda/

A: Eclipse debugging starts with what is referred to as Agents.
The JVM, which runs the complied .class sources has a feature that allows externally libraries (written in either Java or C++) to be injected into the JVM, just about runtime. These external libraries are referred to as Agents and they have the ability to modify the content of the .class files been run. These Agents have access to functionality of the JVM that is not accessible from within a regular Java code running inside the JVM and they can be used to do interesting stuff like injecting and modify the running source code, profiling etc. Tools like JRebel makes use of this piece of functionality to achieve their magic.
And to pass an Agent Lib to a JVM, you do so via start up arguments, using the
 agentlib:libname[=options] format.

We were actually passing an Agent Lib named jdwp to the JVM running Tomcat. The jdwp is a JVM specific, optional implementation of the JDWP (Java Debug Wire Protocol) that is used for defining communication between a debugger and a running JVM. It's implementation, if present is supplied as a native library of the JVM as either jdwp.so or jdwp.dll
So what does it do?
In simple terms, the jdwp agent we pass is basically serving the function of being a link between the JVM instance running an application and a Debugger (which can be located either remote or local). Since it is an Agent Library, It does have the ability to intercept the running code, create a bridge between the JVM and a debugger, and have the functionality of a debugger applied on the JVM.
Since in the JVM architecture, the debugging functionality is not found within the JVM itself but is abstracted away into external tools (that are aptly referred to as debuggers), these tools can either reside on the local machine running the JVM being debugged or be run from am external machine. It is this de-coupled, modular architecture that allows us to have a JVM running on a remote machine and using the JDWP, have a remote debugger be able to communicate with it.
That is how Eclipse debugger works in short.


text:
Q: What is the parallel version of dplyr::mutate? Given that I have a very large dataframe, please advise if there is a function in R to make dplyr::mutate to run in parallel multicored?
Like furrr package where you can set the plan and run multicored.


text:
Q: Deliberately slow down file access speed I am trying to deliberately slow down access to files on my Windows machine to test load times on an application I am making.
I've tried virtual machines and giving it limited CPU/RAM resources, but that doesn't quite do what I require.
Is there a way to slow down access to the virtual hard drive or to a folder etc?
VirtualBox/VMWare are both good.

A: For VirtualBox,

Starting from version 4.0 we are able to limit Virtual Box bandwith
  for acess to disk images (see Virtual Box Manual for details)
We need to create a bandwith group first (in the example below named
  "Limit" for 20 MB/s):
VBoxManage bandwidthctl "VM name" --name Limit --add disk --limit 20
VBoxManage storageattach "VM name" --storagectl "SATA" --port 0 --device 0 --type hdd
                                   --medium disk1.vdi --bandwidthgroup Limit
VBoxManage storageattach "VM name" --storagectl "SATA" --port 1 --device 0 --type hdd
                                   --medium disk2.vdi --bandwidthgroup Limit

Note: From versions >= 4.2 these commands changed to:
VBoxManage bandwidthctl "VM name" add Limit --type disk --limit 20M
VBoxManage storageattach "VM name" --controller "SATA" --port 0 --device 0 --type hdd
                                   --medium disk1.vdi --bandwidthgroup Limit
VBoxManage storageattach "VM name" --controller "SATA" --port 1 --device 0 --type hdd
                                   --medium disk2.vdi --bandwidthgroup Limit

We need to give the details of our personal setup above.
To further limit disk access to 10 MB/s we can then issue
VBoxManage bandwidthctl "VM name" --name Limit --limit 10 # version 4.0
VBoxManage bandwidthctl "VM name" set Limit --limit 10M   # >= 4.2

This can even be done during runtime.

Please note that all credit is due to the original author on Ask Ubuntu.


text:
Q: How to tell the version of jetty that apt-get will install? Is it possible to see what version of jetty will be installed on the various versions of Ubuntu?
Is it online somewhere?
Also, is it possible to see the package so I can tweak it if required?

A: To see what version(s) of Jetty are available for installation on your system:
apt-cache policy jetty

This lists the installed version (if any) and all the versions available for installation, and indicates which one would be installed by default.
If you want to know about other Ubuntu release, look on packages.ubuntu.com.
If you want to see the package before installation, download it but don't install it yet:
apt-get -d install jetty

The package is in /var/lib/apt/cache/jetty*.deb.

A: packages.ubuntu.com can be searched to see which version are included with each release.  Some packages from future releases are fairly easy to install on an older Ubuntu release.  Jetty is likely one of them.
You can download the source packages from the above site.  However, I would recommend against tweaking the package.  It is relatively easy to do, but you won't get important security patches.
A note about package versions.  These are the original versions.  Security patches are backported to this release, and the available package is updated.  These patches are applied when you update the package.  If you use one of the automatic update packages, they may be applied automatically depending on your settings.
Debian/Ubuntu makes it quite easy to adapt the configuration to your needs.  For packages that support conf.d configuration, I would recommend using it rather than modifying the original configuration.  This will make version updates much simpler.

A: There are a couple of ways to do this, here is the way that I usually use. Depending on the version of ubuntu you're currently running, you might need to install aptitude. You can do that by opening a terminal and typing the following:
sudo apt-get install aptitude

Once aptitude is installed then you would type the following to determine the version that would be installed or is installed depending.
sudo aptitude show jetty

Hope this helps!
Chris

A: Instead of installing aptitude, it is faster to use apt-cache :

apt-cache showpkg jetty

This command will show full informations about the packet, even if it is not installed.

A: if you do not want to use aptitude, you can use apt instead :
apt search jetty | grep jetty

the result is
libjetty8-extra-java/xenial,xenial,now 8.1.19-1 all  [installé, automatique]
libjetty8-java/xenial,xenial,now 8.1.19-1 all  [installé, automatique]
libjetty8-java-doc/xenial,xenial 8.1.19-1 all
libjetty9-extra-java/xenial,xenial 9.2.14-1 all
libjetty9-java/xenial,xenial 9.2.14-1 all

consequently you have the choice betweel jetty8 and jetty9


text:
Q: How do right read file via stdio? C++ I want to read file via stdio for RapidXML. I used following:
#include <iostream>
#include <rapidxml.hpp>
#include <stdio.h>
#include <Windows.h>

using namespace rapidxml;

int main(int argc, char** argv)
{
    FILE *pFile;
    pFile = fopen("D:\\ColladaFiles\\sample1.dae", "rb");
    long lSize;
    char *buffer;
    size_t result;

    //if error
    if (pFile == NULL) { fputs("File error", stderr); exit(1); }

    // obtain file size:
    fseek(pFile, 0, SEEK_END);
    lSize = ftell(pFile);
    rewind(pFile);

    // allocate memory to contain the whole file:
    buffer = (char*)malloc(sizeof(char)*lSize);
    if (buffer == NULL) { fputs("Memory error", stderr); exit(2); }

    // copy the file into the buffer:
    result = fread(buffer, 1, lSize, pFile);
    if (result != lSize) { fputs("Reading error", stderr); exit(3); }

    /* the whole file is now loaded in the memory buffer. */

    xml_document<> xdoc;
    xdoc.parse<0>(buffer);

    system("pause");
    return 0;
}

RapidXML generated an error. Because If I write buffer following:
std::cout << buffer << std::endl;

Last line is contains a following:

How do fast read a file for RapidXML?

A: You missed two things:

*

*on malloc:
buffer = (char*)malloc(sizeof(char)*lSize + 1); //place for '\0';

*after fread:
buffer[lsize]='\0'; //terminate string
You can also use fgets() or std::ifsteam method getline

A: The following line expects char array with null termination character('\0') at the end of the array.
xdoc.parse<0>(buffer);

So add following lin after reading file, and also allocate space for that '\0'.
buffer[lSize]='\0

A: For C++ you shouldn't be reading the file that way. See this question. Read whole ASCII file into C++ std::string
Basically, Try this instead.
std::ifstream t("D:\\ColladaFiles\\sample1.dae");
std::stringstream buffer;

buffer << t.rdbuf(); //read file into stringstream

xdoc.parse<0>(buffer.str().c_str()); // parse it


text:
Q: Aggregate hash function? Just like we have aggregate functions of sum and count, is there any way to do aggregate hashes on field?  For example, assume you have the following recordset:
Name     ID
Bob      1
Bob      2
Bob      3
Bob      4

Conceptually, I'd like to do this:
select name, hash(id) from mydb.mytable
group by 1

...which would return this:
Name     ID
Bob      D8-F0-00-91

If I delete the record with ID = 3, the aggregate would then return this:
Name     ID
Bob      A8-EB-6D-1D

FYI, I used select hashrow(1,2,3,4) and select hashrow(1,2,4) to get the above hash values.
Update for dnoeth:  It's probably helpful to mention that I need the resulting aggregate to be unique.  Here's an example of the data model I am using:
table office (Id integer)
table employee (Id integer, OfficeId integer)

Each office has employees, so it's a one-to-many from office to employee with the employee table having OfficeId as a FK to the office table.
locking row for access
select n, count(n) from
(
    select
        officeid,
        sum(cast(from_bytes('00'xb || hashrow(id), 'base10') as bigint)) n
    from mydb.employee
    group by 1
) x
group by 1

Here's a great example of how a collision occurs.  Again, though, I didn't mention that I needed the result to be unique.
select
    cast(from_bytes('00'xb || hashrow(2300015), 'base10') as bigint) +
    cast(from_bytes('00'xb || hashrow(14100028), 'base10') as bigint) hash1,

    cast(from_bytes('00'xb || hashrow(1000004), 'base10') as bigint) +
    cast(from_bytes('00'xb || hashrow(3100014), 'base10') as bigint) +
    cast(from_bytes('00'xb || hashrow(12300025), 'base10') as bigint) hash2

A: You need to cast the result of the HASHROW to a numeric value, then you can easily sum it.
-- HASHROW to unsigned integer, TD14
SUM(CAST(FROM_BYTES('00'xb||HASHROW(ColumnName), 'base10') AS BIGINT)
   ) AS SumHash

-- HASHROW to unsigned integer, pre-TD14
SUM(  HASHBUCKET(       HASHROW(ColumnName)      (BYTE(4)))  / ((HASHBUCKET()+1)/65536) * CAST(65536 AS BIGINT)
    + HASHBUCKET(SUBSTR(HASHROW(ColumnName),3,2) (BYTE(4)))  / ((HASHBUCKET()+1)/65536)
   ) AS SumHash

Edit:
There's no way to get a guaranteed unique result when hashing, there's just a increasing probability based on the length of the calculated hash. And HASHROW returns a 4 byte value and you simply add them :-(
You could install an existing hashing UDF returning way more than 4 bytes like
https://downloads.teradata.com/download/extensibility/sha-1-message-digest-udf
https://downloads.teradata.com/download/extensibility/md5-message-digest-udf
https://github.com/akuroda/teradata-udf-sha2
and then implement an Aggregate XOR UDF.
There was a blog on Teradata's DevEx about comparing tables:
http://developer.teradata.com/blog/ulrich/2013/05/calculation-of-table-hash-values-to-compare-table-content


text:
Q: Prove that for any circle in R^2, if two ordered pairs on the circle are separated by 180 degrees, then the connecting line passes through the center I want to prove that for any circle $C$ with $r \gt 0$ and center $(x_0,y_0)$ in the Euclidean Plane $\mathbb R \times \mathbb R$, if $(x_1,y_1), (x_2,y_2) \in C$ and are separated by $180\deg$, then the line $L$ that connects $(x_1,y_1)$ to $(x_2,y_2)$ must pass through $(x_0,y_0)$. In particular, then, this line must contain the diameter of $C$.
If there is a more straightforward non-geometric approach, I would love to see it.

Firstly, what does it mean for $(x_1,y_1)$ to be separated by $(x_2,y_2)$ by $180 \deg$? Consider the Euclidean distance $d$ between $(x_1,y_1)$ and the center of the circle. Next, consider the angle $\theta_1$ between the positive $x$ axis and the radial line connecting $(x_0,y_0)$ to $(x_1,y_1)$. Let $\theta_2=\theta_1+\pi$ and let this correspond to the angle between the positive $x$ axis and the radial line connecting $(x_0,y_0)$ to $(x_2,y_2)$. Because $(x_2,y_2) \in C$, we can rewrite $(x_2,y_2)$ by making the following observations: \begin{align}&(1) \quad x_2=x_0+\cos(\theta_2)d \implies x_2=x_0+\cos(\theta_1+\pi) \implies x_2=x_0-\cos(\theta_1)\\&(2) \quad y_2=y_0+\sin(\theta_2)d \implies y_2=y_0+\sin(\theta_1+\pi) \implies y_2=y_0-\sin(\theta_1)\end{align}
By definition of $C$, $\sin(\theta_1)=y_1-y_0$ and $\cos(\theta_1)=x_1-x_0$.
Therefore, $(1)$ and $(2)$ can be rewritten as:
\begin{align} &(3) \quad x_2=x_0-(x_1-x_0) \implies x_2=2x_0-x_1 \\&(4) \quad y_1=y_0-(y_1-y_0) \implies y_2=2y_0-y_1\end{align}
As such, $(x_2,y_2)=(2x_0-x_1,2y_0-y_1)$.
Next, consider a line represented by the following equation: $L(x)=\frac{y_2-y_1}{x_2-x_1}(x-x_1)+y_1$. Plugging in our values for $x_2$ and $y_2$, we have:
$$L(x)=\frac{2y_0-y_1-y_1}{2x_0-x_1-x_1}(x-x_1)+y_1 \implies L(x)=\frac{y_0-y_1}{x_0-x_1}(x-x_1)+y_1$$
Now, solving for when $x=x_0$, we have that $L(x_0)=y_0$, which means that $(x_0,y_0) \in L$.
This argument worked for any arbitrary ordered pairs meeting our initial criteria, as well as for any circle in the Euclidean plane.

A: Whether there is a more straightforward approach depends on how you define "circle" and "separation by 180 degrees".
I can define a circle $S(a,r)\subset\mathbb{C}$ to be the loci of points $z$ such that $|z-a|=r$ for $a\in\mathbb{C}$ and $r\in\mathbb{R}^+$.
I can then define $z,z'\in S(a,r)$ to be separated by 180 degrees whenever $z-a=e^{\pi i}(z'-a)$, since 180 degrees is equal to $\pi$ radians. But $e^{\pi i}=-1$, so the condition amounts to $z-a=a-z'$.
The separation of $z$ and $z'$ by 180 degrees implies that $z\neq z'$. How? Suppose for contradiction that $z=z'$. Then $2z=2a$, which is not allowed by $|z-a|=r>0$.
The line passing through $z$ and $z'$ is defined as the set of points $z+(z'-z)t$, where $t$ ranges over $\mathbb{R}$.
Observe that $z+\dfrac{1}{2}(z'-z)=\dfrac{1}{2}(z+z')=\dfrac{1}{2}\cdot2a=a$.

A: This is a proof (outline, left for the reader to fill in the details) by reducing to a special case (and is not the most simplified case, but it is sufficient). I prefer this proof to the nicely presented proof by Chris Sanders using complex numbers because it generalizes to higher dimensions more easily (i.e., we can replace $\mathbb{R}^2$ with $\mathbb{R}^n$ and nothing changes). Before we get into the proof, some definitions:
Definition 1 (Anti-parallel):

Two vectors $x,y\in\mathbb{R}^2$ are said to be anti-parallel or separated by $180^{\circ}$ provided that $\langle x,y\rangle =-\lVert x\rVert\cdot\lVert y\rVert$.

Definition 2 (Circle in the plane):

For $r\in(0,\infty)$ and $z_0\in\mathbb{R}^2$, define $S_r(z_0)=\{z\in\mathbb{R}^2:\lVert z - z_0\rVert = r\}$ to be the circle of radius $r$ centered at $z_0$.

Proof (of main result):
It suffices to show that the result holds for the circle $S_r(0)$ and any two points $x,y\in S_r(0)$ that are anti-parallel. I encourage you to try and show that the line connecting them, parametrized by the function $\ell:\mathbb{R}\to\mathbb{R}^2$
$$\ell(t)=x+t(y-x)$$
passes through the origin (this relies on the fact that $\lVert x\rVert = \lVert y\rVert = r$).
The reason why this case is enough is because for arbitrary $z_0$, we can consider the image of $S_r(z_0)$ under the translation $T:\mathbb{R}^2\to\mathbb{R}^2$ given by $T(z) = z-z_0$ along with considering its inverse, $T^{-1}(z) = z + z_0$.
You should show that if $x,y\in S_r(z_0)$ and are separated by $180^{\circ}$ then $T(x),T(y)\in S_r(0)$ and $T(x),T(y)$ are still separated by $180^{\circ}$. Then use the result for $S_r(0)$ along with $T^{-1}$ to show that the line adjoining $x$ and $y$ passes through $z_0$.


text:
Q: A verifiable and teachable Gibbs example I am attempting to construct a teachable example of Gibbs sampling that I can also relate to how it might be used on an actual dataset and yet could also be verified analytically by students with minimal probability education. Do you know of an example with these qualities?
One that I have been considering is the example of doing Gibbs sampling to calculate agreement between two biased coins. Consider if $X$ and $Y$ are coins with $X_{heads}=1/3$ and $Y_{heads}=3/4$. We then know analytically that agreement between the coins, $A_{true}=5/12$.
However suppose we didn't know how to solve this analytically then we would sample as follows:

*

*Set $X$ arbitrarily, say $heads$.

*Sample $A_{true} = P(Y_{heads}|X_{heads})$ which is $3/4$. By 'sampling' we could be flipping this $Y$ coin, or choosing $U$ from a continuous uniform distribution and tallying if $U \leq 3/4$, or we could sample from a dataset of these coin flips, a $Y_{heads}$ value from a randomly selected row where we know that $x=heads$.

*If for instance we got $Y_{heads}$ then sample $A_{true} = P(X_{heads}|Y_{heads}) = 1/3$ using the same approach as in step 2.

*Repeating thousands of times should produce a tally of $A_{true}=5/12$.

Are there other examples out there that are similarly rewarding to intuition?


text:
Q: class added to element in directive, but not reflecting on page Following is the code inside my directive.
template: '<button class="btn"><i class="fa fa-thumbs-o-up fa-2x"></i></button>'
link: function(scope, elem, attrs) {
    elem.bind('click', function() {
        elem.find('button').addClass('btn-success');
    });
}

In the console it shows that the class has been added to the element.
But does not reflect on page.

A: AngularJS does not react to added classes at runtime. You need to compile the element with the new class for it to work, try this:
app.directive('MyButton', function($compile)
    return {
        template: ...
        link: function(scope, elem, attrs) {
            elem.bind('click', function() {
                elem.find('button').addClass('btn-success');
                $compile(elem)(scope);
            });
        },
    };
});


text:
Q: TextView not setText on onActivityResult Fragment This is my code to scan barcode and set content to TextView:
public class scanCodeFragment extends android.support.v4.app.Fragment implements View.OnClickListener{

  Button btnScan;
  TextView contentTxt;
  String substrCode, scanContent;
  View v;

  public scanCodeFragment(){
  }

  @Override
  public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    v = inflater.inflate(R.layout.fragment_scan_code, container, false);
    btnScan = (Button) v.findViewById(R.id.btnScan);
    contentTxt = (TextView) v.findViewById(R.id.scan_content);

    btnScan.setOnClickListener(this);

    return v;
  }

  public void onClick(View v){
    if (v.getId() == R.id.btnScan){
        IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
        scanIntegrator.initiateScan();
    }
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    if (scanningResult != null) {
        scanContent = scanningResult.getContents();
        substrCode = scanContent.substring(2, 10);
        contentTxt.setText("NIS: " + substrCode);
    }
    else {
        Toast toast = Toast.makeText(getActivity(), "Kode barcode salah", Toast.LENGTH_SHORT);
        toast.show();
    }
  }
}

In onActivityResult method , I can't get the result after scan the barcode code. Before this code fragment, I can get the result from onActivityResult.

A: Try to change this line IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity()); to this IntentIntegrator scanIntegrator = new IntentIntegrator(this);.
The reason is that if you pass an Activity as parameter inside IntentIntegrator then on initiateScan will be called activity.startActivityForResult(intent, code) - so result won't be passed to fragment (try to check onActivityResult for parent Activity, it will be called). But if you pass Fragment as parameter inside IntentIntegrator - will be called fragment.startActivityForResult(intent, code), so Android framework will be able to call onActivityResult inside your fragment for result.

A: i don't know what your initiateScan() so keep it if you need it
final int requestCode = 100;

public void onClick(View v){
    if (v.getId() == R.id.btnScan){
      IntentIntegrator intent = new IntentIntegrator(getContext(), MainActivity.class);
            intent.putExtra(RECIPE_EXTRA, extraObject);
            startActivityForResult(intent, requestCode);
    }
}

A: From the code snippet you have provided, I suggest you to create a separate Activity for scanning, instead of a Class file, in your case which is IntentIntegrator, and start it when your Scan Button is clicked.
So, create IntentIntegratorActivity and start it like this.
public void onClick(View v){
    if (v.getId() == R.id.btnScan){
        IntentIntegratorActivity intent = new Intent(getActivity(), IntentIntegratorActivity.class);
        startActivityForResult(intent, SCAN_INTENT_CODE);//Remember this code, which is an Integer value
    }
}

Then, in OnCreate method of IntentIntegratorActivity, do the scanning and return the scan data via an Intent.
Intent returnIntent = new Intent();
returnIntent.putExtra("SCAN_DATA_KEY", scanData);//Send scan data from here and remember the key SCAN_DATA_KEY
setResult(RESULT_OK, returnIntent);
finish();

Then this data should be caught inside onActivityResult method in the Fragment Class.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case ConstList.SCAN_INTENT_CODE:
        String scanData = data.getStringExtra("SCAN_DATA_KEY");//Use this key to get the data.
        //I have assumed that the data is String
        contentTxt.setText("NIS: " + scanData);//Set data to the Text field
        break;
    }
}

A: OnActivityResult() called only if you call
startActivityForResult()
I call the startActivityForResult() in Fragment and implement the onActivityResult in Fragment, the onActivityResult() will be called correctly.
you can not call startActivityForResult() in activity, otherwise the onActivityResult() in Fragment will not be called