text:
Q: How to define a PL/SQL function and call it from another language I am trying to write a PL/SQL function that returns a number. I must use the number in SQL where clause. The function is in the following:
CREATE OR REPLACE FUNCTION func_id(str_id IN STRING,num_group IN NUMBER)
  RETURN NUMBER
IS
  result NUMBER;
declare
  temp STRING;
BEGIN
  temp := substr(str_id, -least(length(str_id), 2));
  result := TO_NUMBER(temp) % num_group;
  RETURN result;
END;

select * from table where func_id("id",2)=1

2 and 1 are just an example. I want to call the function in my Scala Program that variables are replaced in place of 2 and 1.
When I run the code in SQL Developer I receive this error:
 Function FUNC_ID compiled

 LINE/COL  ERROR
 --------- -------------------------------------------------------------
 5/1       PLS-00103: Encountered the symbol "DECLARE" when expecting one of the following:     begin function pragma procedure subtype type <an identifier>    <a double-quoted delimited-identifier> current cursor delete    exists prior The symbol "begin" was substituted for "DECLARE" to continue.
 13/54     PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:     . , @ ; for <an identifier>    <a double-quoted delimited-identifier> group having intersect    minus order partition start subpartition union where connect    sample

Would you please guide me how to write a PL/SQL function and call it in another query or any where else?
Any help is really appreciated.

A: *

*DECLARE is syntactically invalid in that position;

*STRING is not a valid data type, you want VARCHAR2;

*% is not a valid operator, you want the MOD function; and

*The intermediate variables are not required.

CREATE OR REPLACE FUNCTION func_id(
  str_id    IN VARCHAR2,
  num_group IN NUMBER
) RETURN NUMBER
IS
BEGIN
  RETURN MOD(TO_NUMBER(substr(str_id, -LEAST(2, LENGTH(str_id)))), num_group);
END;
/

Then, if you have the table:
CREATE TABLE table_name ( id ) AS
SELECT '1' FROM DUAL UNION ALL
SELECT '24' FROM DUAL UNION ALL
SELECT '10-05' FROM DUAL;

You can call the function using:
select id,
       func_id(id, 23)
from   table_name

Which outputs:

ID
FUNC_ID(ID,23)

1
1

24
1

10-05
5

db<>fiddle here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Plot subset of column using base R I have a vector:
a <- c(1:100)

If I'd like to plot a subset of this data, I do this:
hist(a[a<40])

However, if the vector a is a column of a data frame, this code does not work, i. e.:
b <- c(101:200)
c <- rep("A", 100)
df <- data.frame(a, b, c)

Then this
hist(df$a[df$a<40])

gives me this error message:
$ operator is invalid for atomic vectors

I have googled for a while but cannot figure out the problem. I would like to solve this using base R. Thanks for your help.

A: Assuming that you are using a data.frame, you could use the following code:
a <- c(1:100)
b <- c(101:200)
c <- rep("A", 100)
df <- data.frame(a, b, c)
with(df[df$a < 40,], hist(a))

Output:


text:
Q: I am unable to include "code" into this system as part of a question. Anything I put into the "Body" For example, I only have one "body" but have a description like:
I can understand that a non-BLE device will not respond to the BLE Client device (Android) using StartDiscovery but should respond to a Scan request. I believe that the AdaFruit is responding to a discovery event because I am getting discovery responses to devices within range with the Android device app in the Settings/Connections/Bluetooth display. This includes the Adafruit BLE device. Again, I believe this means that the problem is on the Android side. I have searched everything I can find but most of the information I get is years old. I have focused in on something called LeScanCallback and/or LeDeviceListAdapter as the potential problem. I can't even tell is my callback is being triggered. Any help would be GREATLY appreciated!
but when I try to insert a code block this system won't let me post the question. I have seen many other questions where the poster actually has different input blocks for the manifest, xms, and main Java script, but I don't see anything like that.

A: I didn't realize I had the formatting wrong. I needed to manually insert 4 spaces in front of every line, and use the "Code here". That will teach me for reading the instructions too fast! Thanks for the comment from Morrison Chang that put me in the right direction.


text:
Q: Combining multiple Bluebird promises into a single promise object I'm using the BluebirdJS promise library.
I have a method called getOrder which returns back an orders details based on a PO number in a form of a promise.
var poNumber = '12345';
return getOrder(poNumber).then(function (order) {
   console.log(order.poNumber, order.items[0].sku);
   return order;
});

However I now need to call this method in a loop and combine the details about the order into a single object.
What I have ATM is this:
var poNumbers = ['12345', '67890'];
return Promise.each(poNumbers, function (poNumber) {
   return Promise.try(function () {
      return getOrder(poNumber).then(function (order) {
          console.log(order.poNumber, order.items[0].sku);
          return order;
      });
   });
}).then(function (combinedOrder) {
   console.log(combinedOrder);
});

But I'm unsure how to combine the details of each order into a single object and return that object as a promise instead?
The project also uses lodash and I tried using _.difference to maybe grab the difference and make up a combined order object but I was again unsure how to get it working.
What's the best way to achieve the above?

A: You need Promise.all instead of Promise.each:
Quoting from the docs:

Given an Iterable(arrays are Iterable), or a promise of an Iterable,
  which produces promises (or a mix of promises and values), iterate
  over all the values in the Iterable into an array and return a promise
  that is fulfilled when all the items in the array are fulfilled. The
  promise's fulfillment value is an array with fulfillment values at
  respective positions to the original array. If any promise in the
  array rejects, the returned promise is rejected with the rejection
  reason.


text:
Q: Comparing the properties of two lists I have a List with a Content object ( List<Content>). Inside the Content object, I have 4 fields.
ContentID
ModifiedDate
Description
HtmlMarkup

I have two List<Content> which I need to compare by ContentID (two different databases) and see if any of the fields have different values, and then I need get which fields are different.
So lets say I have object A
ContentID    - 1
ModifiedDate - 1/1/2013
Description  - "This is my first content class"
HtmlMarkup   - "First Content

And object B
ContentID    - 1  -- these are from two different databases, so contentID will match
ModifiedDate - 1/1/2013
Description  - "This is a description"
HtmlMarkup   - "Test

I should be comparing them by ContentID. And with this example I will return that the Description and HtmlMarkup are different for ContentID 1.  If there is not match for ContentID (meaning it has been deleted or its not in the second database) I would like to grab that as well. How do I do that?

A: Not the most elegant solution but something like this should work. Could just modify the select to return whatever data you need.
var result = from contentA in contentObjectA
             join contentB in contentObjectB on contentA.Id equals contentB.Id into contentBB
             from contentB in contentBB.DefaultIfEmpty(null)
             select new {
                ContentAId = contentA.Id
                //Check if Id exists
                ExistsInB = contentB == null ? false : true,
                ModifiedDateDiff = contentB.ModifiedDate == null ? true : contentA.ModifiedDate == contentB.ModifiedDate,
                DescriptionDiff = contentB.Description == null ? true : contentA.Description == contentB.Description,
                HtmlMarkupDiff = contentB.HtmlMarkup == null ? true : contentA.HtmlMarkup == contentB.HtmlMarkup
             };


text:
Q: Sending email in iPhone In my application I have to send feedback to the client's email.
Here is my code,
-(void) send:(id) sender {
    [self sendEmailTo:[txtTo text] withSubject:[txtSubject text] withBody:[txtBody text]];
}

-(void) sendEmailTo:(NSString *)to withSubject:(NSString *) subject withBody:(NSString*)body {
    NSString *mailString = [NSString stringWithFormat:@"mailto:?to=%@&subject=%@body=%@",
    [to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
    [subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
    [body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailString]];
}

But this does not work. Is it require any type of SMTP setting or something else?
I tried apple's MailComposer sample but it also does not work.
Please help me.

A: I have posted this here, but for the sake of not clicking again here it is:

You need to include the MessageUI.framework into your project, and inside your header file you need to set the delegate:
#import <MessageUI/MessageUI.h>
@interface RootViewController : UIViewController <MFMailComposeViewControllerDelegate> {
    MFMailComposeViewController *email;
}

@property (nonatomic, retain) MFMailComposeViewController *email;

Once you do that, you have a few delegate methods inside your implementation file you need to include (You should check to see the result, but I am trying to keep as little code as needed):
@synthesize email;

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    [email dismissModalViewControllerAnimated:YES];
}

Wherever you want to use this, you need to initialize and set it up like this:
email = [[MFMailComposeViewController alloc] init];
email.mailComposeDelegate = self;

// Subject
[email setSubject:@"Testing"];

// Optional Attachments
NSData *artwork = UIImagePNGRepresentation([UIImage imageNamed:@"albumart.png"]);
[email addAttachmentData:artwork mimeType:@"image/png" fileName:@"albumart.png"];

// Body
[email setMessageBody:@"This is the body"];

// Present it
[self presentModalViewController:email animated:YES];

A: Try to use different format:
NSString *mailString = [NSString stringWithFormat:@"mailto:%@?subject=%@&body=%@",
     [to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
     [subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
     [body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];


text:
Q: How to separate long strings with variable number of spaces in between, in individual strings I am trying to split strings, which are separated by a variable number of spaces.
something like this:
abcde          123456

I know how to trim a string, but I am having hard time here, because the 2 strings has a variable amount of spaces. If a string is long, it will have less spaces in between, so I can't find a way to delimit them clearly, so I can save each of them in a different string.
How do you actually do so?

A: Use .split():
input = 'abcde          123456'
output = input.split()
print(output)

['abcde', '123456']

A: Python string's have a method called split() just for this case.  When called on a string with no arguments, it will split on space and strip out any number of leading and trailing spaces:
data = 'abcde          123456'
letters, numbers = data.split()

A: Its the best way to remove the spaces before splitting:
import re
my_string = "abcde          123456"
regex = re.compile(r'( [ ]+)')
shortend_string = regex.sub(' ', a)
elements = shortend_string.split(' ')


text:
Q: Accessing .sqlite file in Android 2.1 I have a .sqlite file with one table in it. i want to access this data. Please tell me, where to copy this .sqlite file (in eclipse project) and how to access the data from this .sqlite file.
please suggest some code or liniks.. [i am using Android 2.1, dont know the database version..]
Thank you..

A: Here are a few articles that explain exactly that ;)
http://www.helloandroid.com/tutorials/how-have-default-database
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
Include a database file with Android application via Eclipse


text:
Q: Undefined reference aiImportfile (assimp) using QT I have bee trying to get assimp running in QT 5.2 in order to import some 3D objects, but Im having a problem with (I believe) the linker.
I installed it via cmake, first downloading the source files from here http://sourceforge.net/projects/assimp/files/assimp-3.0/, then using cmake to compile and install.
Then, I have tried to run the example they provide in the documentation
#include <assimp/cimport.h>        // Plain-C interface
#include <assimp/scene.h>          // Output data structure
#include <assimp/postprocess.h>    // Post processing flags

bool DoTheImportThing( const char* pFile)
{
  // Start the import on the given file with some example postprocessing
  // Usually - if speed is not the most important aspect for you - you'll t
  // probably to request more postprocessing than we do in this example.
  const aiScene* scene = aiImportFile( pFile,
                                      aiProcess_CalcTangentSpace       |
                                      aiProcess_Triangulate            |
                                      aiProcess_JoinIdenticalVertices  |
                                      aiProcess_SortByPType);
  // If the import failed, report it
  if( !scene)
  {
   // DoTheErrorLogging( aiGetErrorString());
    return false;
  }

  return true;
}

But when trying to compile this piece of code, I get the error
 error: undefined reference to `aiImportFile'
 error: collect2: error: ld returned 1 exit status

I am using a 32 bit linux mint. Does anybody have any idea why is it not linking? Should I have compiled with cmake using a specific flag? i havent been able to found any special flags in any posts around.
Thanks!

A: I finally solved it! Apparently, QT has a tool for importing external libraries. I just had to right click on the project, click add library, and add the file located at /user/local/libassimp.a
This added the following lines to my .pro file:
win32:CONFIG(release, debug|release): LIBS += -L$$PWD/../../../../../usr/local/lib/release/ -lassimp
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/../../../../../usr/local/lib/debug/ -lassimp
else:unix: LIBS += -L$$PWD/../../../../../usr/local/lib/ -lassimp

INCLUDEPATH += $$PWD/../../../../../usr/local/include
DEPENDPATH += $$PWD/../../../../../usr/local/include

win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$PWD/../../../../../usr/local/lib/release/libassimp.a
else:win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$PWD/../../../../../usr/local/lib/debug/libassimp.a
else:win32:!win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$PWD/../../../../../usr/local/lib/release/assimp.lib
else:win32:!win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$PWD/../../../../../usr/local/lib/debug/assimp.lib
else:unix: PRE_TARGETDEPS += $$PWD/../../../../../usr/local/lib/libassimp.a

Theres possibly a more elegant way of coding that, but at least it worked.


text:
Q: How to display the page range of marked locations in a passage in ConTeXt? I have a macro placed throughout my document marking key places within a long passage. These have no relation to the chapter or section titles.
 _____________ _____________
|             |             |
| .....a..... | ........... |
| .........b. | ..d........ |
| ........... | ........... |
| ........... | ........... |
| ........... | ........... |
| ....c...... | .......e... |
| ........... | ........... |
|______1______|______2______|

 _____________ _____________
|             |             |
| ....f...... | ........... |
| .......g... | ........... |
| ...h....... | .....j..... |
| ........... | ........... |
| ........... | Section.... |
| .......i... | ..........k |
| ........... | ........... |
|______3______|______4______|

I need to place information in the headers, to tell readers the current page range of the markings of the portion of text they are currently reading, e.g.:
 _____________ _____________
| c: 1-2      | e: 2-3      |
| .....a..... | ........... |
| .........b. | ..d........ |
| ........... | ........... |
| ........... | ........... |
| ........... | ........... |
| ....c...... | .......e... |
| ........... | ........... |
|______1______|______2______|

 _____________ _____________
| e: 2-3      | j: 4-4      |
| ........... | ........... |
| ........... | ........... |
| ........... | .....j..... |
| ........... | ........... |
| ........... | Section.... |
| ........... | ........... |
| ........... | ..........k |
|______3______|______4______|

*

*As some pages, have multiple ranges, the last range appearing on the page can be displays.

How can I place information in the headers of my document to tell readers the page range of the current portion of the text they are reading?

A: Make a \rangestart{rangename} and \rangestop{rangename} macro, make them store the page numbers across runs, and make a function to select and print any ranges that are active on a given page number.
I stole the job.datasets.setdata / job.datasets.getdata syntax from phg's construction for a different multi-pass question. Hope this helps!
\startluacode
    userdata = userdata or {}
    local ranges_start_tmp = {}

    -- record range name and start in temp. array, to be
    -- flushed to the .tuc file when we also know the stop.
    function userdata.rangestart(rangename, page)
        ranges_start_tmp[rangename] = page
    end

    -- flush range name, start, and stop to the .tuc file.
    function userdata.rangestop(rangename, page)
        job.datasets.setdata({
            name = "ranges",
            data = {
                ["name"]  = rangename,
                ["start"] = ranges_start_tmp[rangename],
                ["stop"]  = page,
            }
        })
        ranges_start_tmp[rangename] = nil
    end

    -- Takes 3 arguments: the page whose active ranges to describe,
    -- a template{name, start, stop} for formatting a single range,
    -- and a separator to print between multiple ranges
    function userdata.printranges(page, template, sep)
        local ranges = {}

        local i = 1
        local range = job.datasets.getdata("ranges", i) -- default: nil
        while range do
            if range.start <= page and page <= range.stop then
                ranges[#ranges + 1] = string.formatters[template](
                    range.name, range.start, range.stop
                )
            end
            i = i + 1
            range = job.datasets.getdata("ranges", i)
        end

        context(table.concat(ranges, sep))
    end
\stopluacode

% The TeX side of the mechanism
\define[1]\rangestart{\ctxlua{userdata.rangestart([[#1]], \userpage)}}
\define[1]\rangestop{\ctxlua{userdata.rangestop([[#1]], \userpage)}}
\define[3]\printranges{\ctxlua{userdata.printranges(#1, #2, #3)}}

% -------------------------
% Let's try it out

% Templates contain percent signs -- better to write them in a lua
% block.
\startluacode
    userdata.mytemplate = "%s, from %i to %i"
\stopluacode
\setupheadertexts[\printranges{\userpage}{userdata.mytemplate}{"; "}]
\setupfootertexts[\userpage]

\setuppapersize[A6, landscape]

\starttext
    \section{A}
        \input knuth
        \input knuth
    \section{B}
        \rangestart{a}
        \input knuth
        \rangestop{a}
        \rangestart{b}
    \section{C}
        \input knuth
        \rangestop{b}
\stoptext


text:
Q: Agregar tarjeta de Bootstrap luego de pulsar un botón en modal Lo que quiero es que mediante un modal que tengo, al hacer click en aceptar me agregue a la página una tarjeta de bootstrap5 con los datos que yo ponga en los inputs. ¿Se podrá hacer eso?
He intentado un par de cosas, pero no le hallo solución.

                      <input type="file" id="archivo">

 Agregar

                        Título
                        <input type="text" id="titulo">

                        Descripción
                        <input type="text" id="descripcion">

                        Ubicación
                        <input type="text" id="ubicacion">

                        Precio
                        <input type="text" id="precio">

                    <button href="" id="button" class="btn" onclick="cargarCard()">Aceptar</button>

function cargarCard(){
    let archivo = document.querySelector(#archivo).value;
    let titulo = document.querySelector(#titulo).value;
    let descripcion = document.querySelector(#descripcion).value;
    let ubicacion = document.querySelector(#ubicacion).value;
    let precio = document.querySelector(#precio).value;
}


text:
Q: Handle PHP Array in Ajax Response I send an AJAX request to a PHP file with this code:
$.post({
    url: "manage.php",
    dataType: "JSON"
}, {
    firtname: John,
    lastname: edwin
}, function(data){
    $("#persons").html(data[0])
});

My PHP file returns data in an array such as this:
$a = 0;
while ($a < 5)
{
    $data[$a] = "person".$a;
    $a2++;
}
echo json_encode($data);

I want to return data something like $data[0] = "person 1";. How can I handle this in AJAX? As you can see above currently I am trying data[0] but no success. How can I do this? Thanks

A: $.post{'manage.php',{firstname:'John',lastname:'edwin'},function(data){
    $('#persons').html(data.0);
},'json');

A: i solved the problem. Sorry guys, there was a syntax error in my variable thats why i was not getting data in my ajax response. so the following code is correct & working
$.post({
url: "manage.php",
dataType: "JSON"
}, {
firtname: John,
lastname: edwin
}, function(data){
$("#persons").html(data[0])
});

in my php file my Array variable was wrong thats why i was not getting data. sorry and thanks :)


text:
Q: Sum of json-formatted value I have a column that its value is JSON formatted:
Row 1: {"id":"1","name":"shoe","price":"1000"}
Row 2: {"id":"2","name":"bag","price":"2000"}
etc....

I want the sum of all prices in this JSON-formatted column. How can I achieve this? Note that I can use PHP to parse the JSON value, but the problem is that I should Group Concat all these rows (I want a single row). For example:
{"id":"1","name":"shoe","price":"1000"}||{"id":"2","name":"bag","price":"2000"}||...

|| is the separator for example. My concern is that, suppose that we have 10,000 rows! Does MySQL support too long strings or is it even efficient to do so?
Is there any alternative ways to do this?

A: Try this:
$json = '[{"id":"1","name":"shoe","price":"1000"} ,{"id":"2","name":"bag","price":"2000"}]'; // Assign Json to var

$jsonObj = json_decode($json); // Decode the JSON to OBJ

// Now loop and find the SUM
$total = 0;
foreach ($jsonObj as $item){
    $total =+ $item->price;
}

// Print the SUM
echo "Sum : $total";


text:
Q: An effective way to knock down GSM on demand I am building a test rig for a device that has a GSM module to communicate and I want to test how the FW behaves when there is a comms loss and recovery. The GSM module of the device has an antenna connector where I can potentially tap into.
Just disconnecting the antenna doesn't work, because PCB traces some times are enough!
My thought was to have like a T connector and inject noise when I want to simulate loss of signal and then stop injecting to simulate a recovery.
What would be the easiest and most effective way to do this?
Note some devices use GPRS, others 2G, 3G or even 4G.
Edit just a note here, covering the device in some kind of Faraday cage is not possible. I am looking for an automated way of doing this.

A: Buy a 10 bucks GSM/3G/4G radio jammer.
Cheap jammers have a range of 5 meters.
You should switch it on just for the time of your tests.
That's the fastest and cheapest way.
I did it in the past and it works.
To monitor if the comm port works, if the modem is alive and connected, just issue an AT+CSQ? every 12 hours.


text:
Q: mssql ConnectionPool request() exception NOT A FUNCTION I followed this question here using mssql 5.0.4
How can I use a single mssql connection pool across several routes in an Express 4 web application?
and I always get the
pool.request() is not a function

exception. What did I do wrong.
Exactly same 'db.js'
const sql = require('mssql')
const config = {/*...*/}

const poolPromise = new sql.ConnectionPool(config)
  .connect()
  .then(pool => {
    console.log('Connected to MSSQL')
    return pool
  })
  .catch(err => console.log('Database Connection Failed! Bad Config: ', err))

module.exports = {
  sql, poolPromise
}

and the call at:
const { poolPromise } = require('./db')

module.exports = {
  get: async (req, res) => {
    try {
      const pool = await poolPromise
      // RUNTIME ERROR EXCEPTION at the following line
      const result = await pool.request()
          .query('select * from cars')

      res.json(result.recordset)
    } catch (err) {
      res.status(500)
      res.send(err.message)
    }
  })
}


text:
Q: Git revert merge VIM editor I merged a branch into another but now I want to revert the merge I just pushed to the repo so I did the following:
git revert -m 1 <log hash>
but this opens the VIM commit message editor which is giving me issues. When the VIM editor opens, it tells me to place my commit message, so what I did was

*

*Press i key to insert

*Wrote my commit message like this --> RM000: Reverting merge

*Exited out by :x
However, when I push my changes, I get a commit message regex error as we have a a convention of how commit messages should be so when I entered i in step one and wrote my commit message in step two, it didn't take my commit message correctly.

My question is, how can I do the commit message without having the VIM pop up? i.e after I use git revert -m 1 <log hash> I want to do git commit -m "RM:000 Reverted" but once I use the git revert it automatically opens the VIM editor.

A: Well... comment conversation may have presented the user with a solution, but the question wasn't answered and the conversation raises more questions, so here are some things:

First of all, if you want to enter the commit message for a revert on the command line, you can say
git revert -n -m 1 <hash>
git commit -m "RM:000 Reverted"

Adding the -n option tells revert not to automatically commit.  It also means that if you revert multiple commits at once, the undo changes are combined into the index, so when you do manually commit they will all be squashed together.  Maybe that's what you want, maybe not; in this case, it's just one commit, so it doesn't matter.

That said, you might want to either familiarize yourself more with the vi editor, or change your git config to use an editor with which you're more comfortable.  You can set the core.editor config value or the environment variable GIT_EDITOR to specify a command for git to run when it needs to show you an editor.

Lastly, as pointed out in the comments, undoing a merge that has been pushed is a very difficult thing; every solution has negative consequences.
You can revert the commit, as you are trying to do.  This is good in many ways, but it leaves git thinking that the branch has been merged and accounted for, even though its changes have been undone.  So if you want it later, you have to do one of two things:
1) You can "revert the revert"
2) You can do a rebase -f on the branch before merging; this causes the branch to be rebuilt from new commits that git won't think are "already accounted for".
You can read more about these techniques in numerous articles and SO answers.
The other option is to use git reset to remove the merge from the branch history.  This has all of the consequences of rebasing a branch after sharing it, so see the git rebase documentation under "recovering from upstream rebase" (or search for questions about force pushing, as many of them will spell this out).


text:
Q: How to set up a Google Drive Client ID for access without a local server? I'm wondering if it's possible to, say, open up a jsfiddle on a random computer and log in and authenticate and use the drive API, without having to have a local server running all the time? And how exactly does one go about setting this up? I'm sorry if this is a simple question but I'm just sorta lost because the instructions that I've found so far are unclear.
Edit:
So far I have, following from here and here:

*

*Created a project via the Google Developers Console.

*Opened up that project there, navigated to APIs under APIs & auth, and ensured that Drive API was enabled

*Went into credentials, and clicked on "Create a new Client ID"

*

*Selected "Web Application"

*Set authorized javascript origins to http://localhost:4567

*Deleted any contents in Redirect URI's and left it blank, then pressed "Create Client ID."

*Took a sample like this, this, or this, and stored it in a local file named named index.html.

*

*This wouldn't run by simply opening in a brower, so I had to host a local server

*I navigated into that directory in the command line and then typed "python -m SimpleHTTPServer 4567" (without the quotes) and this hosted a local server

*Opened http://localhost:4567 in my web brower, and all of these samples work fine, after copying the newly created client ID into these files where they ask for it.

I also have made a python application, to use pydrive I:

*

*Clicked on "Create a new Client ID", then "Installed Application" and "Other", then "Create Client ID."

*Next I went to the Old Google APIs Console, clicked on API Access, found that client ID, and clicked Download JSON.

*I placed this client_secrets.json next to my python application, and this allowed pydrive to authenticate successfully and I could access and modify my google drive files anywhere using that client ID. Though of course I deleted this client_secrets.json before giving the application to another person, and showed them how to do this process as well.

However, beyond this, I'm a little unsure about, specifically:

*

*How one can use the drive api in web applications without having to set up a local server, say simply by running code in jsfiddle and having requests sent through my project via using a Client ID, and

*If a local server is set up that can be accessed by anyone on the web, how one can modify the above steps to allow any client to open that server's webpage to use the google drive API?

I know that I most likely need to set up a Public API access in the developers console, but am not entirely sure what Referers I should use as well. So is there a simple way to do any of this?
I also know that gspread can open google excell spreadsheets only using the client's username and password, so I'm suspecting that what I'm looking for is possible, but I'm not sure.

A: Okay, so I found a solution that works pretty well:

*

*Make an OAuth.io account (It's free).

*Once you're logged in, go to your oauth.io dashboard.

*You should be looking at a Default App, or you can make another one it doesn't really matter.

*Under "Domains & URLs whitelist", you'll see a little box that says "localhost." Type in "
http://fiddle.jshell.net/" (without the quotes) and press enter. This allows any jsfiddle to authenticate with your application

*Next, we need to enable Google Drive support

*

*Go to the Google Developers Console

*Like before, navigate to Credentials under APIs and Auth.

*Click "Create new Client ID"

*Select Web Application

*Under "Redirect URIs" put "https://oauth.io/auth" and "http://oauth.io/auth" (without quotes, on separate lines)

*Under "Javascript Origins" put "https://oauth.io" and "http://oauth.io"

*Press "Create Client ID"

*Now go to your Oauth.io key manager. Click on Google Drive in the list to the left. Press next, and enter your client_id and client_secret that you created in the previous step (via the Google Developers Console)

*Select online (at least online is preferred since offline should be for server side only)

*Click on the Scope text book, and select "https://www.googleapis.com/auth/drive (View and manage the files in your google Drive)."

*Press finish. Now click on the Try Auth button, and hopefully you should get some output like

{
  "access_token": "ya29.AwH-1N_gnstLBuZfOR4W9CCcggKrQpMyKYV4QVEtCiIzHozNU5AfUJoYQzukALfjdiw2iOCUve7JbQ",
  "token_type": "Bearer",
  "expires_in": 3600,
  "provider": "google_drive"
}

To use this, you can do something like:
// This only works because we're set to "No wrap - in <head>"
function ShowDriveFileList() {
    var accessToken;
    // Initialize OAuth with our key
    OAuth.initialize('lmGlb8BaftfF4Y5en_c8XYOSq2A');

   // Connect to google drive, and print out file list
    OAuth.popup('google_drive').done(function (result) {
    var xmlHttp = null;
        xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", "https://www.googleapis.com/drive/v2/files", false);
        xmlHttp.setRequestHeader("Authorization", "Bearer " + result.access_token);
        xmlHttp.send(null);
        alert(xmlHttp.responseText);
    }).fail(function (err) {
        alert(err);
    });;
}

Which you can find at http://jsfiddle.net/JMTVz/41/. This uses my oauth.io client id, but you can replace it with yours and it should work as well.

A: You can do the same thing using the OAuth Playground.
See How do I authorise an app (web or installed) without user intervention? (canonical ?)
Step 11 will be different. Instead of pasting the refresh token into your server app (which you don't have), you'll paste the access token into your JS in the same way as you are doing in your answer.


text:
Q: How can I exhaust /dev/urandom for testing? I recently had a bug where I didn't properly handle when the entropy on my linux server got too low and a read of /dev/urandom returned less than the number of bytes expected.
How can I recreate this with a test?  Is there a way to lower the entropy on a system or to reliably empty /dev/urandom?
I'd like to be able to have a regression test that will verify my fix.  I'm using Ubuntu 12.04.

A: According to random(4) man page,
read from the /dev/urandom device will not block

You should read  a lot of bytes from /dev/random (without any u) if you want it to block. (How many is hardware and system dependent).
So you cannot "exaust" /dev/urandom, since

 A read from the /dev/urandom device will not block waiting for
 more entropy. As a result, if there is not sufficient entropy in
 the entropy pool, the returned values are theoretically vulnerable
 to a cryptographic attack on the algorithms used by the driver.

I believe you should use /dev/random which indeed can be exhausted, by blocking.
But you should not read more than about 256 bits from it.


text:
Q: Is use of Commons FileUpload to handle multipart/form-data not deprecated? I just start learning Java EE and now I try to implement to my learning project uploading files from HTML forms.
Many tutorials use to handle file uploads in Servlets by use of Commons FileUpload API. But Java 6 introduced the multipart configuration option into Servlet 3.0.  Is it mean that use of Commons FileUpload is deprecated and all  those tutorials are out of date?
EDIT:
@Vishal answered FileUpload API is different way to handle same task.
My question now is, what advantages has one API over another?

A: No its not Deprecated, Else you can say a different way to upload and send MIME.
Commons FileUpload API is provided by Apache foundation and Multipart is feature provided from Java 6, so there is no way to link this two things and deprecating FileUpload API. I hope this clears at least few of your doubts.
For more details refer this links FileUpload
and Multipart Utility


text:
Q: Не повторяющийся рандом в сдвоенном массиве Можете помочь? Есть двумерный массив из 0 размером 10 на 10 рандомоно выбираем х и у. Допустим, х=1 и у=1 . Эту клетку мы из 0 делаем 1. Проблема в том что таких точек ( 1 ) у меня должно быть 3 штуки. Как сделать так чтобы при рандоме у меня не выпала та же самая клетка что и при первом рандоме? Допустим при первом рандоме мне выпало х=5 и у=7 и при втором рандоме выпало х=5 и у=7. Как сделать так чтобы точки не повторялись? Код на c++ консоль.

A: #include <iostream>
#include <ctime>
using namespace std;

int main()
{
    srand(time(NULL));
    int arr[10][10] = { 0 };
    const int quantity = 3;

    int row = rand() % 10;
    int column = rand() % 10;
    for (int i = 0; i < quantity; )
    {
        if (arr[row][column] == 1) // без повторений
        {
            row = rand() % 10;
            column = rand() % 10;
            continue;
        }
        ++i;
        arr[row][column] = 1; // mina esti
    }

    system("pause");
    return 0;
}


text: Q: The proportions of those arrangements of the numerals 1,2,...,9 in which all the multiples of 3 appears consecutively is The multiples of 3 appears in 3! Ways consecutively in 7 different places while the remaining numbers appears in 6! Ways therefore we have 7*3!*6! Ways of arranging the numbers. Now the proportion of the arrangement = (7*3!*6!)/9!=1/12


text:
Q: What does \1 (backslash 1) do in Ruby strings? ActiveSupport::Inflector::Inflections#human uses a \1 in the example:
human /_cnt$/i, '\1_count'

As far as I can tell, that's actually adding a \u0001 character to the string, and it seems to still work if I just use '_count'. Can anyone tell me what the \1 is actually supposed to be doing?

A: It may be that under the hood, they are passing that string to gsub or something similar. In a gsub replacement string, '\1' has a special meaning -- it refers to whatever the first capturing group in the regex argument matched.
For example, try:
 "a short sentence".gsub(/([aeiou])/, '\1\1')

If you use "\1", now that is a completely different thing. That is a \u001 character. (Escapes work differently in single-quoted and double-quoted Ruby strings.)
Probably the reason why omitting the \1 doesn't seem to change anything in the example you gave, is because there is no capturing group in the regex.


text:
Q: Energy Density with a Linear Dielectric Inconsistency The energy density of an electromagnetic field with a linear dielectric is often expressed as $0.5 E \cdot D$. It is also known that energy can be found by $ 0.5\int_{V} \rho V dV $. Using the latter, the energy density is found to be $0.5 E^2 \varepsilon_0$, as is well known. If you integrate the latter only over free charge and ignore bound charge, you write $\epsilon \nabla \cdot E=     \rho$, use integration by parts, and obtain the first result. Does the first result neglect the energy from bound charge? If not, why does $0.5 E^2 \varepsilon_0$ break down (I.e. why can't one find the energy with a dielectric by treating the bound charge as its own independent charge arrangement and using formulae for a vacuum?)
Here is a concrete example:
Consider again a parallel plate capacitor with charge $Q$, area $A$, separation $d$, and ignore edge effects. Fill it with dielectric of constant $k$. Now, we know that there will be a surface charge density of $-\frac{(k-1)Q}{kA}$ on the side of the dielectric next to the positively charged plate, and the opposite density on the side of the dielectric next to the negatively charged plate. This reduces the electric field by a factor of $k$, as is well known. If you consider this charge arrangement in a vacuum, it has energy $\frac{AdE^2 \varepsilon_0}{2k^2}$. But with a dielectric, apparently you must replace $ \varepsilon_0 $ with $ \varepsilon $, and the energy is now suddenly $\frac{AdE^2 \varepsilon_0}{2k} $ for the same charge distribution!

A: Yes. The first result neglects the energy from bound charge.
Given you consider that the E is net E(=E due to free charge +E due to bound charge) .
In the example of a capacitor with a dielectric between its plates the first result represents the energy that is retrievable from the capacitor(by discharging the capacitor). The first result , neglects the energy in dielectric , but, it keeps track of the effect of dielectric on the energy retrievable from capacitor. If you write $Q*V$ for all charges(those on capacitor plates and those in dielectric) in this example. You will find that the total energy in the system(capacitor plates + dielectric) is $EQd/2$ + some other term. (Here E is net E in dielectric , d is distance between the plates and Q is the charge on capacitor plates) . This $EQd/2$ is equal to  $0.5E.D$ .
$V$ is potential in above discussion

A: Griffith's gives a good exposition. Essentially the vacuum formula does not take into account "spring energy" in dipoles (which could be electric in nature, but is still neglected because we use an averaged, macroscopic E field).


text:
Q: MySQL indexes best performance I'm optimizing a mysql table for my high traffic website and I've got a question about mysql indexes. First some info:
The table has 273382 rows.
The query is:
SELECT table1.field1, table1.field2, table2.field2
FROM table1
LEFT JOIN table2 ON table1.idfield = table2.idfield
WHERE table1.field = 1 AND table1.field2 = 'yes'
ORDER BY table1.id DESC
LIMIT 0,25

I've got the following indexes:
index for table1.id - primary unique index
index for table1.idfield - index
index for table2.idfield - index
index for (table1.field,table1.field2) - index

With the above indexes query takes 1.5 to 2.5s to complete
EXPLAIN EXTENDED says it is using the primary key (table1.id), I've tried unique/index (table1.field,table1.field2,table1.id) with similar results (even though it is using this index).
During the index altering process (which takes around 1 min) the query becomes much much faster 0.009. Once the altering process is complete the query goes back to being slow at 1.5-2.5s (mostly under 2).
My question is: which index would work the best for this query and why the query is so much faster while altering the index.

A: If more than about 20% of the table has table1.field = 1 AND table1.field2 = 'yes', then the Optimizer decides that it is cheaper to scan the table rather than bounce back and forth between even the optimal index (field, field2, id) and the data.
Please provide SHOW CREATE TABLE, SHOW TABLE STATUS, EXPLAIN SELECT ..., the size of RAM, and the value of innodb_buffer_pool_size if you want to discuss this further.
It smells like caching and I/O issues; the above info will help drill into that.


text:
Q: Dataframes join returns empty results in Spark Scala I have four data frames in Spark Scala (Spark version: 2.3 and Spark-sql: 2.11 and Scala version: 2.11.0) such as:
ratingsDf
+-------+---+
|ratings| id|
+-------+---+
|      0|  1|
|      1|  2|
|      1|  3|
|      0|  4|
|      0|  5|
|      1|  6|
|      1|  7|
|      1|  8|
|      0|  9|
|      1| 10|
+-------+---+

GpredictionsDf
+-----------+---+
|gprediction| id|
+-----------+---+
|          0|  1|
|          1|  2|
|          1|  3|
|          1|  4|
|          1|  5|
|          1|  6|
|          1|  7|
|          1|  8|
|          0|  9|
|          1| 10|
+-----------+---+

RpredictionsDf
+-----------+---+
|rprediction| id|
+-----------+---+
|          0|  1|
|          1|  2|
|          1|  3|
|          1|  4|
|          1|  5|
|          1|  6|
|          1|  7|
|          1|  8|
|          1|  9|
|          1| 10|
+-----------+---+

LpredictionsDf
+-----------+---+
|lprediction| id|
+-----------+---+
|          0|  1|
|          1|  2|
|          1|  3|
|          0|  4|
|          1|  5|
|          1|  6|
|          1|  7|
|          1|  8|
|          0|  9|
|          1| 10|
+-----------+---+

I need to create a DataFrame by joining all four tables on "id" column. I tried below two ways to do this:
**Method 1: **
val ensembleDf = GpredictionsDf.join(rpredjoin, gpredjoin("id") === RpredictionsDf("id"))
                               .join(LpredictionsDf, LpredictionsDf("id") === RpredictionsDf("id"))
                               .join(ratingsDf, ratingsDf("id") === RpredictionsDf("id"))
                               .select("gprediction", "rprediction", "lprediction", "ratings")

**Method 2: **
ratingsDf.createOrReplaceTempView("ratingjoin");
GpredictionsDf.createOrReplaceTempView("gpredjoin")
RpredictionsDf.createOrReplaceTempView("rpredjoin")
LpredictionsDf.createOrReplaceTempView("lpredjoin")

val ensembleDf = sqlContext.sql("SELECT gprediction, rprediction, lprediction, ratings FROM gpredjoin, rpredjoin, lpredjoin, ratingjoin WHERE " +
  "gpredjoin.id = rpredjoin.id AND rpredjoin.id = lpredjoin.id AND lpredjoin.id = ratingjoin.id");

However, in both cases my join failes and returns empty
ensembleDf.show();

+-----------+-----------+-----------+-------+
|gprediction|rprediction|lprediction|ratings|
+-----------+-----------+-----------+-------+
+-----------+-----------+-----------+-------+

Any idea why this could be happening? What code changes do I need to do to get this fixed?

A: scala> val ratingsDf = Seq((0,1),(1,2),(1,3),(0,4),(0,5),(1,6),(1,7),(1,8),(0,9),(1,10)).toDF("ratings","id")

scala> val GpredictionsDf = Seq((0,1),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(1,8),(0,9),(1,10)).toDF("gprediction", "id")

scala> val RpredictionsDf = Seq((0,1),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(1,8),(1,9),(1,10)).toDF("rprediction", "id")

scala> val LpredictionsDf = Seq((0,1),(1,2),(1,3),(0,4),(1,5),(1,6),(1,7),(1,8),(0,9),(1,10)).toDF("lprediction", "id")

scala> val ensembleDf = GpredictionsDf.join(RpredictionsDf, GpredictionsDf("id") === RpredictionsDf("id") ).join(LpredictionsDf, LpredictionsDf("id") === RpredictionsDf("id")).join(ratingsDf, ratingsDf("id") === RpredictionsDf("id")).select("gprediction", "rprediction", "lprediction", "ratings")

scala> ensembleDf.show
    +-----------+-----------+-----------+-------+
    |gprediction|rprediction|lprediction|ratings|
    +-----------+-----------+-----------+-------+
    |          0|          0|          0|      0|
    |          1|          1|          1|      1|
    |          1|          1|          1|      1|
    |          1|          1|          0|      0|
    |          1|          1|          1|      0|
    |          1|          1|          1|      1|
    |          1|          1|          1|      1|
    |          1|          1|          1|      1|
    |          0|          1|          0|      0|
    |          1|          1|          1|      1|
    +-----------+-----------+-----------+-------+

This is what I tried and it is giving the correct values. I would recommend you to check the DFs you are using for joining.


text:
Q: Contact Us form is not displaying I am new to magento. I have override the Contact form, but in home page not displaying the Contacts link.
my code is:
etc\module\Easylife_Contacts.xml
     <?xml version="1.0"?>
<config>
    <modules>
        <Easylife_Contacts>
            <active>true</active>
            <codePool>local</codePool>
        </Easylife_Contacts>
    </modules>
</config>

magento\app\code\local\Easylife\Contacts\controllers\IndexController.php
<?php
include_once('Mage/Contacts/controllers/IndexController.php');

class Easylife_Contacts_IndexController extends Mage_Contacts_IndexController
{

    const XML_PATH_EMAIL_RECIPIENT  = 'contacts/email/recipient_email';
    const XML_PATH_EMAIL_SENDER     = 'contacts/email/sender_email_identity';
    const XML_PATH_EMAIL_TEMPLATE   = 'contacts/email/email_template';
    const XML_PATH_ENABLED          = 'contacts/contacts/enabled';

    public function preDispatch()
    {
        parent::preDispatch();

        if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
            $this->norouteAction();
        }
    }

    public function indexAction()
    {
        $this->loadLayout();
        $this->getLayout()->getBlock('contactForm')
            ->setFormAction( Mage::getUrl('*/*/post') );

        $this->_initLayoutMessages('customer/session');
        $this->_initLayoutMessages('catalog/session');
        $this->renderLayout();
    }

    public function postAction()
    {
        ....
    }

}

magento\app\code\local\Easylife\Contacts\etc\config.xml
<?xml version="1.0" encoding="utf-8"?>

<config>
    <modules>
        <Easylife_Contacts>
            <version>0.1.0</version>
        </Easylife_Contacts>
    </modules>
    <frontend>
        <routers>
            <contacts>
                <args>
                    <modules>
                        <Easylife_Contacts before="Mage_Contacts">Easylife_Contacts</Easylife_Contacts>
                    </modules>
                </args>
            </contacts>
        </routers>
    </frontend>
     <layout>
        <updates>
            <contacts>
                <file>contacts.xml</file>
            </contacts>
        </updates>
    </layout>
</config>

magento\app\design\frontend\easylife\default\layout\contacts.xml
<?xml version="1.0"?>

<layout version="0.1.0">

    <contacts_index_index translate="label">

        <reference name="content">
            <block type="core/template" name="contactForms" template="contacts/form.phtml"/>
        </reference>

        <update handle="contactForm"></update>
    </contacts_index_index>
</layout>

magento\app\design\frontend\easylife\default\template\contacts\form.phtml

<?php echo $this->getMessagesBlock()->getGroupedHtml() ?>

<?php echo Mage::helper('contacts')->__('Contact Us') ?>

<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post">
  ....
</form>

Can anyone tell me where I went wrong?
thanks.

A: <default>
        <reference name="footer_links">
            <action method="addLink" translate="label title" module="contacts">Contact Us<url>contacts</url><title>Contact Us</title></action>
        </reference>
    </default>

Add this code in your layout file.


text:
Q: Basic JS Animation Does't Work Correctly In Safari So here is my animation function:
    function animation(el, isHorizontal, from, to, callback) {
        var start = true === isHorizontal ? from.x : from.y,
            stop = true === isHorizontal ? to.x : to.y,
            intervalId, diff;

        intervalId = setInterval(function () {
            diff = Math.abs(stop - start);
            if (stop < start) {
                if (diff < 4) {
                    start -= diff;
                } else {
                    start -= 4;
                }
            } else {
                if (diff < 4) {
                    start += diff;
                } else {
                    start += 4;
                }
            }
            if (true === isHorizontal) {
                el.style.left = start + 'px';
            } else {
                el.style.top = start + 'px';
            }
            if (start === stop) {
                clearInterval(intervalId);
                callback();
            }
        }, 1);
    }

It works perfectly in Chrome, although in Safari, the animated elements seem to stop few pixels before they are supposed to.
Let's say I am going to move from left: 8 to left: 116. In Safari, the element ends at around left: 108, when I open the Inspector to see the console and check that the left offset is correct on the element, the element repositions itself correctly.
All I need to do is open the developer console and the element jumps to correct position.
So strange.
Here's some of my CSS that might be relevant:
.box {
    position: relative;
     }
    .item {
        position: absolute;
        background-position: left top;
        background-repeat: no-repeat;
        background-size: 100% auto;
        -webkit-transform: transform;
    }

A: It looks like there's nothing wrong with your code, but that Safari doesn't perform a repaint when it should (since the problem goes away when you open the developer console).
Do you still get the problem if you increase the 1ms interval to say 50ms?
One hack that usually works is to force the browser to repaint the whole page by toggling a dummy class on the body at the end of the animation:
if (start === stop) {
    jQuery("body").toggleClass("forceRepaint");

    clearInterval(intervalId);
    callback();
}

You could do this without jQuery of course, but it's going to be less concise.
Also, you would most likely avoid this problem if you used requestAnimationFrame() instead of setInterval() for animations like this (as well as better performance). There's several polyfills that fall back to setInterval/setTimeout in old browsers.

A: So it seems in Safari I have to trigger hardware acceleration otherwise Safari can't keep up and repaint images fast enough:
    -webkit-transform-style: preserve-3d;
    .item {
        position: absolute;
        background-position: left top;
        background-repeat: no-repeat;
        background-size: 100% auto;
        -webkit-transform-style: preserve-3d;
    }


text:
Q: C error expected identifier I was trying to test my code so far, and when compiling a test run I'm getting an error.
Here is my code:
mips_op.h file
#ifndef MIPS_OP_H
#define MIPS_OP_H

typedef enum {
    R, I, J
} op_type;

typedef struct op_instr {
    op_type op_t; // instruction type {R, I, J}
    int opcode : 6; // instruction opcode - 6-bit integer

    // if the instruction type is J
    #if op_t == J

    int address : 26; // address to jump to - 26-bit integer

    #else // if the instruction type is R or I

    int rs : 5; // the output - 5-bit integer
    int rt : 5; // the first operand - 5-bit integer

        #if op_t == R // if instruction type is R

        int rd : 5; // the second operand - 5-bit integer
        int shamt : 5; // the shift amount field - 5-bit integer
        int funct : 6; // the function field

        #endif

        #if op_t == I // if instruction type is R

        int immediate : 16; // the immediate field - 16-bit integer

        #endif

    #endif
};

#endif

and here is main.c file
#include <stdio.h>
#include "mips_op.h"

int main (void) {
    printf("Before instr\n");

    op_instr add;

    printf("After instr\n");

    return 0;
}

and here is the error I'm getting
In file included from main.c:2:0:
mips_op.h:9:10: error: expected ')' before 'op_t'
main.c: In function 'main':
main.c:7:2: error: unknown type name 'op_instr'

What is wrong with my code? Why am I getting this error?
Thanks
EDIT: Fixed the brackets to curly brackets

A: I think you use ( instead of { aound your struct. or am i wrong ?

A: Replace the "(" in the struct definition to "{"
typedef struct op_instr
**{**
   ...
**}**

EDIT: You may are having this problem
"Basically, there's a complex interaction between ordinary C preprocessor directives, ordinary C language elements, and the inscrutable innards of the Arduino IDE & compiler chain.
As nearly as I can tell, you can wrap #if whatever around simple declarations and most executable code with impunity, but putting anything more elaborate than that, like a simple typedef struct, inside the conditionals causes bizarre problems.
In fact, just typedef can cause problems, particularly if you attempt to use the ensuing tag in a function declaration. Don't even think about anything along these lines:"

A: Your immidiate problem is that you are using () instead of {} for your struct scope.
As Paul R says you appear to have some other issues as well.


text:
Q: UIGraphicsGetImageFromCurrentImageContext() - Memory Leak I am opening the camera with UIImagePickerControllerSourceTypeCamera and a custom cameraOverlayView so I can take multiple photos without the "Use Photo" step.
This is working great, but there is a memory leak in the save photo function.  Through a lot of debugging and research I have narrowed it down to the UIGraphicsGetImageFromCurrentImageContext function.
Here is a snippet of code where it happens:
UIGraphicsBeginImageContextWithOptions(timestampedImage.frame.size, timestampedImage.opaque, [[UIScreen mainScreen] scale]);
[[timestampedImage layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *finalTimestampImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

I have scoured the internet and it seems that the UIGraphicsGetImageFromCurrentImageContext() function (quoted from this SO question) "returns a new autoreleased UIImage and points the finalTimestampImage ivar to it. The previously allocated UIImage is never actually released, the variable to it is just repointed to somewhere else."
I've tried so many solutions that have apparently worked for others:

*

*Adding timestampedImage.layer.contents = nil; after UIGraphicsEndImageContext

*Adding CGContextRef context = UIGraphicsGetCurrentContext(); and CGContextRelease(context); after UIGraphicsEndImageContext

*Wrapping the above snippet in an NSAutoreleasePool

*Wrapping the entire saveThisPhoto function in an NSAutoreleasePool

*Creating an NSAutoreleasePool when the camera pops up and calling the [pool release] when didReceiveMemoryWarning is called

*Closing the camera popup when didReceiveMemoryWarning is called, hoping it will clear the pool

*Every possibly combination of the above
Yet everything I try, when I take photos I can see the Memory Utilized rising and not falling when I'm repeatedly taking photos on the device.
Does anyone know how I can release the autorelease object created by UIGraphicsGetImageFromCurrentImageContext?
Alternatively, is there an alternative way to make a UIImage out of an UIImageView?
Edit:
Here are the full functions as requested.  There's a lot of extra releasing added in there just to try make sure everything is cleaned up.  I have gone through and tested for the memory leak with each code block in saveThisPhoto systematically, and it only occurs when the UIGraphicsGetImageFromCurrentImageContext block (snippet above) is run.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    NSLog(@"SAVING PHOTO");

    [self saveThisPhoto:info];

    picker = nil;
    [picker release];

    info = nil;
    [info release];

}

- (void)saveThisPhoto:(NSDictionary *)info {

    // Get photo count for filename so we're not overriding photos

    int photoCount = 0;

    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"photocount"]) {
        photoCount= [[[NSUserDefaults standardUserDefaults] objectForKey:@"photocount"] intValue];
        photoCount++;
    }

    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%d", photoCount] forKey:@"photocount"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    // Obtaining saving path

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName = [NSString stringWithFormat:@"ri_%d.jpg", photoCount];
    NSString *fileNameThumb = [NSString stringWithFormat:@"ri_%d_thumb.jpg", photoCount];
    NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    NSString *imagePathThumb = [documentsDirectory stringByAppendingPathComponent:fileNameThumb];

    // Extracting image from the picker and saving it

    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];

    // SAVE TO IPAD AND DB

    if ([mediaType isEqualToString:@"public.image"]){

        // Get Image

        UIImage *editedImage = [info objectForKey:UIImagePickerControllerOriginalImage];

        // Figure out image orientation

        CGSize resizedSize;
        CGSize thumbSize;

        if (editedImage.size.height > editedImage.size.width) {
            resizedSize = CGSizeMake(480, 640);
            thumbSize = CGSizeMake(150, 200);
        } else {
            resizedSize = CGSizeMake(640, 480);
            thumbSize = CGSizeMake(150, 113);
        }

        // MAKE NORMAL SIZE IMAGE

        UIImage *editedImageResized = [editedImage resizedImage:resizedSize interpolationQuality:0.8];

        // clean up the one we won't use any more

        editedImage = nil;
        [editedImage release];

        // ADD TIMESTAMP TO IMAGE

        // make the view

        UIImageView *timestampedImage = [[UIImageView alloc] initWithImage:editedImageResized];
        CGRect thisRect = CGRectMake(editedImageResized.size.width - 510, editedImageResized.size.height - 30, 500, 20);

        // clean up

        editedImageResized = nil;
        [editedImageResized release];

        // make the label

        UILabel *timeLabel = [[UILabel alloc] initWithFrame:thisRect];
        timeLabel.textAlignment =  UITextAlignmentRight;
        timeLabel.textColor = [UIColor yellowColor];
        timeLabel.backgroundColor = [UIColor clearColor];
        timeLabel.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:(25.0)];
        timeLabel.text = [self getTodaysDateDatabaseFormat];
        [timestampedImage addSubview:timeLabel];

        // clean up what we won't use any more

        timeLabel = nil;
        [timeLabel release];

        // make UIIMage out of the imageview -- MEMORY LEAK LOOKS LIKE IT IS IN THIS BLOCK

        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

        UIGraphicsBeginImageContextWithOptions(timestampedImage.frame.size, timestampedImage.opaque, [[UIScreen mainScreen] scale]);
        [[timestampedImage layer] renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *finalTimestampImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        timestampedImage.layer.contents = nil;
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextRelease(context);

        // clean up the one we won't use any more

        timestampedImage = nil;
        [timestampedImage release];

        // SAVE NORMAL SIZE IMAGE TO DOCUMENTS FOLDER

        NSData *webDataResized = UIImageJPEGRepresentation(finalTimestampImage, 1.0); // JPG

        [webDataResized writeToFile:imagePath atomically:YES];

        // clean up the one we won't use any more

        finalTimestampImage = nil;
        [finalTimestampImage release];

        [pool release]; // to get rid of the context image that is stored

        // SAVE TO DATABASE

        [sqlite executeNonQuery:@"INSERT INTO inspection_images (agentid,groupid,inspectionid,areaid,filename,filenamethumb,filepath,orderid,type) VALUES (?, ?, ?, ?, ?, ?, ?, ?,?) ",
         [NSNumber numberWithInt:loggedIn],
         [NSNumber numberWithInt:loggedInGroup],
         myInspectionID,
         [[tableData objectAtIndex:alertDoMe] objectForKey:@"areaid"],
         fileName,
         fileNameThumb,
         documentsDirectory,
         [NSNumber numberWithInt:photoCount],
         [NSNumber numberWithInt:isPCR]
         ];

        // Clean up

        webDataResized = nil;
        [webDataResized release];

    } else {

        NSLog(@">>> IMAGE ***NOT*** SAVED");

    }

    NSLog(@"IMAGE SAVED - COMPLETE");

    info = nil;
    [info release];

}

A: You're setting your variables to nil before releasing them, and some are already auto released.
Normally when using release you should release and them set to nil.
[var release]
var = nil;

But in some of these you should not be calling release.
The following one is your main culprit.
    // clean up the one we won't use any more

    timestampedImage = nil;
    [timestampedImage release];

    // SAVE NORMAL SIZE IMAGE TO DOCUMENTS FOLDER


text:
Q: Domain of composite functions Given $f(x)= 1- x^2$  and $g(x) = \sqrt x$
What is the domain of $f$ and $g$? My answer is that the domain of $f$ is all real $x$, and the domain of $g$ is all $x \ge 0$.
However, I am not sure if this is correct. The question does not specify that we are in the real vector space. Does this mean the domain includes even the complex numbers.
Also, my formula for the composition $f \circ g$ is $1-x$. I got this by putting $\sqrt x$ in $1- x^2$. Domain of this would be $x \ge 0$.
and $g \circ f$ is  $\sqrt {1-x^2}$. Domain of this is $x \ge 1$.
Have I got this right or are they backwards?

A: If $f$ and $g$ are real-valued functions of a real variable, then all your answers are correct except for the domain of $g \circ f$.  Observe that if $x > 1$, then $1 - x^2 < 0$, so $\sqrt{1 - x^2}$ is not real-valued.  Since $g \circ f = \sqrt{1 - x^2}$ and the domain of $f$ is the set of all real numbers, the only restriction is that $1 - x^2 \geq 0 \iff 1 \geq x^2 \iff 1 \geq |x|$.  Thus, the domain of $g \circ f$ is $D_{g \circ f} = [-1, 1]$.


text:
Q: What Facebook App settings determine whether data is released? I'm trying to retrieve a list of pages that an authorized Facebook user has access to update through a Facebook App using the PHP SDK.
require_once('facebook.php');

$config = array(
  'appId'  => APPID,
  'secret' => SECRET,
  'cookie' => true,
);

$facebook = new Facebook($config);

$params = array(
    'method' => 'fql.query',
    'query' => "select page_id, name from page where page_id in (select page_id from page_admin where uid = me())",
);

$result = $facebook->api($params);

print_r($result);

When we put this FQL into the Graph Explorer in Facebook for testing purposes, it gives us the following (correct) data.
{
  "data": [
    {
      "page_id": 1234567689,
      "name": "A page we have access to"
    },
    {
      "page_id": 987654321,
      "name": "Another page we have access to"
    }
  ]
}

When we use the PHP SDK it returns an array with no values. I have verified we have the manage_pages permission in our Application settings. Furthermore, if I simplify the FQL parameters to:
    $params = array(
        'method' => 'fql.query',
        'query' => "SELECT name from user where uid = me()",
    );

This works in both the Graph Explorer AND the Facebook PHP SDK. This leads me to believe that the problem is some hidden setting in the Application area that is affecting the first FQL query. By the way, when using the Graph Explorer the only permission we needed to successfully return the data was manage_pages and so I don't think it's a permission problem.
Has anyone run into this before or has anyone successfully returned a list of pages that a Facebook user is an administer to? Any ideas on how I could start debugging this? Is there an alternate way to retrieve the information we want in case this is some kind of bug?

A: $loginUrl = $facebook->getLoginUrl(
        array(
            'scope'        => 'manage_pages,read_stream',
            'redirect_uri' => RETURN_ADDRESS,
        )
);

It turns out when you generate the login request you have the option to set the scope for the application. In our scope we did not have manage_pages set even though the Application did.
Hope this helps -- it cost the better part of the day to realize that what you request and what is offered are managed separately.


text:
Q: Strange behaviour of a System.Threading.Timer I am trying to get some insight into how Timer will use thread pool. I wrote following simple snippet.
class Program
    {
        static private readonly Action Action = () => {
                                                     Thread.SpinWait(100 * 10000);
                                                     Interlocked.Increment(ref _data);
        };

        private static volatile int _data;

        static private Timer _threadCountChecker = new Timer(
            (obj) =>
                {
                    var t = Process.GetCurrentProcess().Threads;
                    Console.WriteLine("Using {0} threads.", t.Count);
                    Console.WriteLine(Program._data);
                }, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));

        static void Main(string[] args)
        {
            var l = new List<Timer>();

            for (int i = 0; i < 10; i++)
            {
                l.Add(new Timer((obj) => Action(), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)));
            }

            var exitEvent = new ManualResetEvent(false);
            exitEvent.WaitOne();
        }
    }

Surprisingly this is the output I get:

Using 14 threads. 10 Using 14 threads. 18 Using 14 threads. 28 Using
  14 threads. 39 Using 14 threads. 48 Using 15 threads. 58 Using 15
  threads. 69 Using 15 threads. 80 Using 15 threads. 80 Using 15
  threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15
  threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15
  threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15
  threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15
  threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15
  threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15
  threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15
  threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15
  threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15
  threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15
  threads. 80 Using 15 threads. 80

The data variable stays at 80 no matter for how long I keep running the process.
Does anyone have an idea why the variable gets updated for the first 8 iteration and just stops being incremented?

A: The timers got garbage collected.  Add this statement after the eventWait.WaitOne() call to fix that:
  GC.KeepAlive(l);

The way the GC treats local variables in the Release build is explained in detail in this answer.


text:
Q: render jsf commandLink on basis of bean value Hi as per my requirement I have a datatable and last column is activate/deactivate.
I have to create a commandLink for deactivate the row, once it get deactivated, activate commandLink should appear.To acheive this I have created two commandLink one for activate and other for deactivate.but problem is that both are appearing same time.How to restrict appearing one at a time. also I have to show these on the basis of statusId(1-active,2-deactive)
<h:commandLink id="a" rendered=#{status=1} action="#{bean.activate}"  value="Activate" />
<h:commandLink id="b" rendered=#{status=2} action="#{bean.deactivate}"  value="Deactivate" />

A: http://docs.oracle.com/javaee/6/tutorial/doc/bnaik.html
The correct expression would be
 <h:commandLink id="a" rendered="#{status == 1}" action="#{bean.activate}"  value="Activate" />

eq is also a valid operator. Notice also the quotes.
It would have been nicer if it was a boolean property deactivated or (activated), but that is more a matter of opinion.


text:
Q: Extracting tag value from a JSON string field in Oracle I have an Oracle column that stores a JSON string. This is an example value
{
    "data": {
        "employer": {
            "status": "active",
            "name1": {
                "content": "My favorite company"
            }
        }
    }
}

I am interested in getting the value of the content tag that is contained in the first occurrence of name1 tag. So in this example, what I want is to get "My favorite company" (without the quotes)
How do I do this in Oracle SQL query?

A: If you are using Oracle 12.2 or higher, You may use  below query -
SELECT JSON_VALUE(YOUR_COLUMN, $.content)
FROM YOUR_TABLE;

A: Here's one option; should be OK if JSON data is simple, but - that's what your example suggests:
SQL> select * from test;

JSON
--------------------------------------------------------------------------------
{
    "data": {
        "employer": {
            "status": "active",
            "name1": {
                "content": "My favorite company"
            }
        }
    }
}

Query:

*

*temp CTE finds "content" string and returns everything that follows

*the final query extracts what's between  3rd and 4th double quotes character

SQL> with temp as
  2    (select substr(json,
  3                   instr(json, '"content"')
  4                  ) content
  5     from test
  6    )
  7  select substr(content,
  8                instr(content, '"', 1, 3) + 1,
  9                instr(content, '"', 1, 4) - instr(content, '"', 1, 3) - 1
 10               ) result
 11  from temp;

RESULT
--------------------------------------------------------------------------------
My favorite company

SQL>


text:
Q: Managing Timers Passed as Variables I am trying to perform what I thought was a simple task. I have a handful of repeating timers that need to be started and stopped.
I created methods for starting and stopping the timers, and attempt to pass the timers to the methods as parameters.
The problem is that the timers never seem to be stopped. Any ideas why this might not be working properly? Thank you!
Top of File:
#import "ViewController.h"

NSTimer *launchTimer;
NSTimer *transactionTimer;

Starting Method:
-(void) startingMethod {

    NSString *urlString = @"http://google.com";

    [[AsynchRequestService sharedInstance]
    performAsynchronousURLRequest:urlString completion:^(BOOL success,
    NSString *responseBody, NSString *responseStatus) {

        if (success) {
            [self stopResponseTimer:launchTimer];
        }

        else {
            [self startResponseTimer:launchTimer
            method:@selector(startingMethod)
            interval:10];
        }
    }];
}

Method to Start the Timer:
-(void)startResponseTimer:(NSTimer *) timer method:(SEL) method
interval:(int) interval {

[timer invalidate];
timer = nil;
timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self
selector:method userInfo:nil repeats:YES];
}

Method to Stop the Timer:
-(void)stopResponseTimer:(NSTimer *) timer {

NSLog(@"STOP TIMER");

[timer invalidate];
timer = nil;
}

A: Make startResponseTimer and `stopResponseTimer' take the pointer to the object pointer intead.
-(void)startResponseTimer:(NSTimer **) timer method:(SEL) method
interval:(int) interval {

[*timer invalidate];
*timer = nil;
*timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self
selector:method userInfo:nil repeats:YES];
}

-(void)stopResponseTimer:(NSTimer **) timer {

NSLog(@"STOP TIMER");

[*timer invalidate];
*timer = nil;
}

then invoke it like
[self startResponseTimer:&launchTimer];
[self stopResponseTimer:&launchTimer];

This should make sure that you retain the right NSTimer object.
NOTE:It is always a good idea to check a pointer to a pointer to an object for NULL in a public method


text:
Q: Angular - cookies usage I need some help in understanding how cookies are managed in Angular. I am using ngx-cookie-service to generate a cookie for my web app. What isn't clear to me is that since angular run in my browser, actually the browser should set the cookie when I use cookieService.setCookie(...). But if it's the case, where is that cookie sent? To which server?
I would say the cookie should be sent to the web server, for example http://localhost:4200, but if the cookie is created from my browser, how can the server be aware of it?
I'm speaking about Angular, but I can formulate the same question more generally to every web applications.

A: Cookies are stored by the user's browser, regardless of whether the cookie is set via a header received from a http(s) call, or via a setCookie() api call in the client JavaScript.
Cookies are segregated by the domain that has set them, and can be further segregated by the "page" that set them (less meaningful in an SPA app).
In a simple, static web page, the browser will send further http(s) requests with the cookies are "in scope" for the current domain, page, etc.
However, the Angular HttpClient does not, by default, send cookies when you make an Http(s) call. You have to enable this explicitly.
For more info, see Angular HttpClient does not send domain cookie


text:
Q: Synology NAS DSM: SSH client to backup/rsync a REMOTE server locally Scenario:

*

*a remote Linux webserver (Ubuntu 22.04)

*a local Synology DS220+ with DSM 7.1

I would like to use the Synology to access the remote server via SSH to rsync the server data locally. The Synology would then create a local copy of the remote server data. Please note: the Synology would be the SSH CLIENT here, not the other way around.
The procedure needs to be scheduled, to run it automatically.
I haven't tried anything yet because I don't even know where to start. How should I proceed?

A: I contacted Synology Support about this. They pointed me to "Active Backup for Business", which works exactly as I needed

A: I don't believe that it is set up to allow that to happen.  The Synology reference for how to do rsync backups is here.
There is no suggestion of any possibility of doing the backup in the reverse direction, even though rsync allows that mode.
However, if you can log in as root on the Synology device with a proper bash shell (verify whether the embedded OS used by the device is linux), and if the device allows "at" jobs or "cron" jobs to be scheduled, then you can write a script to perform that.
If, however, you are looking for a script that does backups using rsync (in general), then let me know and I can add 2 very different scripts, from which you can distill any functions/processes you would prefer to use.


text:
Q: Parent Directory is not Writable Error Android Emulator Getting "Parent directory of file is not writable" when trying to create a temp file. I am using Eclipse and the emulator.  I am using the permission in my Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Here is the code:
@SuppressWarnings("static-access")
public void sendEmail() {
    Calendar today = new GregorianCalendar();
    Log.d(TAG, "Path:" + Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + "/GPSTracking/" + MakeTextDate(today) + ".csv");
    File tempFile = null;
    try {

        tempFile.createTempFile(MakeTextDate(today), ".csv");
        FileWriter out = FormatEmail(tempFile);
    }
    catch (IOException e) {
        // error
        Log.d(TAG, "create temp file:" + e.toString());
    }

    try {
        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                "Trip report");
        emailIntent
                .putExtra(Intent.EXTRA_TEXT, "Here is your Trips Report");

        emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
        emailIntent.setType("plain/text");
        startActivity(Intent.createChooser(emailIntent, "Send email..."));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

A: You're trying to create file in root directory of storage, not sd-card
tempFile.createTempFile(MakeTextDate(today), ".csv");

Create file as you writing log with full path to external storage.


text:
Q: Git: Says master is up to date, but when deleting branch it says it isnt' I created a new branch for my 1.0.2 fixes. Once I was finished I wanted to merge them back into my master, so I used:
git merge 'v1.0.2'

But, it tells me that it is 'Already up-to-date`, which is strange. I say, ok, that is fine, so I try to delete the branch:
git branch -d 'v1.0.2'

But now it tells me error: The branch 'v1.0.2' is not fully merged..
Why are my changes not being merged in the first place? Do I need to somehow force them to be merged?
EDIT:
Output of git log --all --oneline --graph --decorate
* a783018 (HEAD, origin/master, master) Updated with 1.0.2 changes
* c208285 Updates
| * 655b0ea (v1.0.2) Submitted 1.0.2 to apple for review
| * 0d4f33d Updates
|/
| * 02f7155 (origin/v1.1, v1.1) Additional fixes
| * 5a68697 Renaming classes and .m .h files with three letter prefixes to comply with Apple requirements
| * c90a76d Added pin pad as an option
| * 3dc6ceb Adding new security methods to lock app if the user chooses
| * 3bf1c88 Updates
|/
* 71af916 Bug fixes
* 523672f (tag: v1.0.2) Final fixes before release
* 0269dab Bug fixes and added new methods to specifically layout details screens
* e1e7c08 Bug fixes
* 071c9cc (tag: v1.0.1) Last changes before 1.0.1 submission
* 8d56576 Bug fixes
* 9e86414 Major file restructure for easier git viewing and structure
* 4f14c9e Updated a few methods to no longer use the Utility object
* 1be42ea Moved some properties to the ZSSingleton rather than the Squiz Matrix singleton
* 1450e7d Updated a few code snippets
* 27c3ebb Updated methods for Metadata
* baf8a6c (tag: v1.0) Final fixes, submitted to apple
* d5ffb6c Addtional fixes
* aa7d123 Removed unused files
* a472a1d Removal of old Matrix library. Removal of ASIHTTPRequest!
* b533ac3 Added new attribute types
* 76c29ef Adding UIDatePicker for creating of Calendar assets
* 1fb09dc Added some fixes for ipad
* 0f93c82 Cleaning up of code, adding comments
* 27c7984 Cleaning up of code, adding comments
* d0d29bb Added ignore file
* 7911483 A file was deleted
* fdba63c First add of all files

A: You need to be on the other branch to merge them. so
git checkout master
git merge v1.0.2
git branch -d v1.0.2

It seems your merge failed. It is not fine that it tells you it's already up to date. Try adding --allow-empty to the merge just to test this out. Make sure you are on master when you issue the merge command.

A: Try this:
git checkout master
git merge refs/heads/v1.0.2

You apparently have both a branch and a tag with the name v1.0.2, and it seems that git merge v1.0.2 prefers to guess that you want to merge with the tag, not the branch. The above syntax makes it explicit that you want to merge the branch instead.


text:
Q: ISO 8859-1 Characters I am working on an application in which we do translations for English/Spanish/French using a JSON file. I am a bit confused on if I need to use ISO 8859-1 Characters (their entity number) for the extra symbols on Spanish and French words. Everything is rendering properly (ex: é í ñ ¿)  but am I not sure if I am doing it incorrectly.
Ex. W/ ISO 8859-1 Characters  (these are using entity names, I heard using entity numbers are better?):
  "resultsperpage":"Resultados / Página",

  "customer":"Cliente",

  "corp":"Corporación",

  "displaycorp":"MostrarCorporación",

Ex. Without:
  "resultsperpage":"Resultados / Página",

  "customer":"Cliente",

  "corp":"Corporación",

  "displaycorp":"Mostrar Corporación",

A: Use the second approch.
Make absolutely sure you always use the same encoding when programmatically reading or writing to file, or when doing http.
Never rely on the default encoding of your system(s). Always specify your chosen encoding.
Make absolutely sure you always edit these files in the correct encoding.
The encoding itself does not matter. I recommed utf-8 over ISO 8859-1 or others.


text:
Q: Square brackets in CSS What does it mean when something between square brackets in CSS? E.g.
input[type="radio"]

A: This is an attribute selector. It selects elements that have the specified attribute. You can find out more about them here: https://developer.mozilla.org/en-US/docs/CSS/Attribute_selectors
In your example: input[type="radio"]
This would match an element that looked like this:
<input type='radio'>

The selector you've given in the question means it would need all three words: The element name 'input', the attribute 'type' and the value for that attribute being 'radio'.
Browser compatibilty: This is a standard selector that is available in all browsers in common use. The only browser you may need to worry about that doesn't support it is IE6. See here for compatibility charts for this and other CSS selectors.
Hope that helps.

A: It's an attribute selector in CSS

E[foo="warning"]    Matches any E element whose "foo" attribute value is exactly equal to "warning".

more on http://www.w3.org/TR/CSS2/selector.html

A: Square brackets are attribute selector syntax.
Your (complete) example means "Select elements of type input which have a type attribute with the value radio" e.g. <input type="radio">

A: This is a CSS attribute selector that will only select inputs with the type set to radio, that is, it will select all of the radio buttons.
Here's an article explaining it a bit more.


text:
Q: How to run multiple screens each with a command programmatically? I'm new to linux screen utility, and now I have to create a lot of screens, passing each some command. How to achieve that programmatically instead of creating each screen with (Ctrl+a c) and typing the command there?

A: Use tmux instead, tmux has a more modern API and is easy to use in most cases. To achieve you purpose with tmux, you need:
$ tmux new-session -s foo -d                # create a new session called foo
$ tmux new-window -t foo                    # create a new window
$ tmux send-keys -t foo.0 ./your_script.sh  # window number starts with 0
$ tmux new-window -t foo                    # another new window
$ tmux send-keys -t foo.1 ./another_command # another of your script
...
$ tmux attach -t foo                        # attach to your session, escape key is ^b