Q:

Is Tor traffic using the TAP handshake vulnerable to retroactive decryption?

Assume an attacker with a record of Tor traffic between a client and guard has precomputed the 1024-bit Oakley group for Diffie-Hellman used in the TAP protocol. This would allow them to rapidly decrypt any recorded DH key exchange done over that group after an expensive but feasible (millions of dollars of equipment and a year of time) one-time computation. If I recall, the legacy TAP protocol used 1024-bit DH. Combined with the suspicion that the "breakthrough cryptanalytic capabilities" mentioned in the Snowden leaks refer to precomputation attacks against 1024-bit Diffie-Hellman parameters as pointed out in the WeakDH paper, would an adversary with these capabilities be able to decrypt old Tor traffic?

A:

To answer my own question after rereading the spec, it is not. There are two things that make it difficult to attack broken DH groups in the old TAP protocol: the RSA hybrid handshake, and link encryption.
RSA hybrid handshake
The protocol uses the 1024-bit safe prime from RFC 2409 section 6.2 with the hex representation:
FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08
8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B
302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9
A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6
49286651ECE65381FFFFFFFFFFFFFFFF

While this is small enough for a powerful adversary to attack, TAP uses a hybrid handshake where the DH data is encrypted using static RSA. In particular, RSA with OAEP-MGF1 padding is used to encrypt a 128-bit symmetric key as well as the first part of the DH data (specifically gx, where g is the generator and x is the DH private key). The symmetric key is then used to encrypt the second part of the DH data which is too large to encrypt using RSA. The Tor specification defines this as follows:

The payload for a CREATE cell is an 'onion skin', which consists of
the first step of the DH handshake data (also known as g^x).  This
value is encrypted using the "legacy hybrid encryption" algorithm
(see 0.4 above) to the server's onion key, giving a client handshake:

    PK-encrypted:
      Padding                       [PK_PAD_LEN bytes]
      Symmetric key                 [KEY_LEN bytes]
      First part of g^x             [PK_ENC_LEN-PK_PAD_LEN-KEY_LEN bytes]
    Symmetrically encrypted:
      Second part of g^x            [DH_LEN-(PK_ENC_LEN-PK_PAD_LEN-KEY_LEN)
                                        bytes]

Breaking the Diffie-Hellman handshake now requires breaking the RSA key. While the RSA key is only 1024 bits and RSA is generally slightly easier to break than a DH key of equivalent size, precomputation attacks are not useful against it. While breaking pure DH (for any given group) requires a one-time expensive precomputation, breaking RSA requires performing an expensive computation each time. While the TAP protocol does use static RSA keys, they are regenerated periodically (once every 1 to 90 days, but 28 days by default, according to dir-spec.txt).
It would absolutely be possible to decrypt an entire circuit by first breaking the 1024-bit RSA and then breaking the DH exchange underneath it, but this would have to be done for each relay in a circuit, and the end result would be only around 10 minutes of plaintext (or however long that individual circuit lived). Millions of dollars and a year of computation to break a single circuit is very unlikely to be worth it.
Link encryption
In addition to the above RSA hybrid handshake, another obstacle exists which makes mass decryption difficult even if the DH handshake can be broken. Tor not only uses layered encryption for each relay using its native protocol, it also encapsulates each link to another relay using standard TLS. That is, before any circuits are created or extended, two relays or a client and relay that wish to communicate first establish a connection using TLS. Breaking the inner circuit encryption thus requires also breaking the outer TLS layer. The parameters used by this TLS session depend on the version of OpenSSL that the Tor binary is linked with. Forward secrecy and sufficiently large keys are mandatory.
The only way to attack the inner onion circuit is if this TLS can be broken, or if the adversary is in control of the relay (since TLS is naturally not end-to-end, but only protecting data between each individual relay). This means that a malicious ISP or datacenter which passively logs the traffic of a Tor relay cannot strip this TLS unless it also controls the relay itself. While it is absolutely possible to run malicious relays, the traffic visibility would be much lower than it would be if their ISP could passively break the TLS.


Q:

Select if comma separated string contains a value

I have table
raw TABLE
=========
id             class_ids
------------------------
1              1234,12334,12341,1228
2              12281,12341,12283
3              1234,34221,31233,43434,1123

How to define regex to select raws if class_ids contains special id.
If we select raws with '1234' in class_ids result list should not contain raws with  '12341' in class_ids.
IDs   in column class_ids separated with ,
SELECT FROM raw re WHERE re.class_ids LIKE (regex)

A:

You shouldn't be storing comma separated values in a single column.

However, this is better done using string_to_array() in Postgres instead of a regex:
SELECT *
FROM raw
WHERE '1234'= any(string_to_array(class_ids, ','));

If you really want to de-normalize your data, it's better to store those numbers in a proper integer array, instead of comma separated list of strings

A:

If you really want to do this with regular expressions, you can use the ~ operator:
SELECT FROM raw re WHERE re.class_ids ~ '^(^|,)1234(,|$)$';

But I prefer a_horse_with_no_name's answer that uses arrays.


Q:

Use data from one .dbf as search string for another one

Sorry, I don't even know the right words to use to ask this question. Please note that I am not official tech support, nor did I write any of the programs in question. I'm the guy that tries to fix things while waiting for the official tech support company to get through all the "Have you turned it off and on again" tickets before they get to ours.
Our store's main program stores all it's patient data in a big pile of .DBFs. I want to delete a value called an IHI (Ihino) for all patients that have no recorded Date Of Birth (pbirthdate).
Unfortunately, the patient.dbf that stores most of the patient data (including pbirthdate) is not the same one that stores the IHI value (Ihino in HIPatientExt.dbf). There is one common value between them. The patient.dbf has a value called pnumber, which corresponds with the ihipatno value in HIPatientExt.dbf (i.e. these numbers refer to the same patient).
I have access to the database commands input. So using that, is there a way to clear/replace a value in one dbf from a search using data from another. I know that is probably worded poorly. To put it another way, let's say they were in the same .dbf, the command I'd run would be
repl Ihino with "" for empty(pbirthdate)
I figured that it may involve outputting a list of the involved pnumbers. I have gotten as far as using copy to to make a big .txt file that contains the pnumbers of all the patients that have an empty pbirthdate. But I have no idea how to use this massive list as part of the repl command. If that's even possible.
Sorry for the airy nature of the question. I've just picked up VFP9 commands along the way that I've needed as I've needed them. And as most VFP tutorials are probably written on stone tablets, I'm hoping there is someone on here with some idea how to accomplish what I'm trying to do.
Regards
Lobsta

A:

VFP supports SQL commands for querying, updating, adding, and deleting data. Based on the table and column names you supplied in question, I think something like this should work.
UPDATE ;
    HIPatientExt ;  && Table to Update
SET ;
    HIPatientExt.Ihino = '' ;  && Column(s) to Update
FROM ;
    Patient, ;  && List of Tables
    HIPatientExt ;
WHERE ;
    HIPatientExt.ihipatno = Patient.pnumber ;  && How to Relate Tables
    AND EMPTY(Patient.pbirthdate)  && Filter


Q:

Show that $f(x)=0$ if there is zero arbitrarily close to $0$ for $f(x)=\sum_{n=0}^{\infty}a_nx^n$

Suppose that,
$$f(x)=\sum_{n=0}^{\infty}a_nx^n$$
converges on $(-R,R)$ for some $R>0$. If we let $(x_n)$ be a sequence in $(-R,R)$ with $x_n\ne 0$ but $\lim x_n=0$. If $f(x_n)=0$ for all $n\in N$, I need to show that $f(x)=0$ for all $x\in (-R,R)$.
My thinking is that I could use Rolle's Theorem. This theorem states that if we let $f$ be continuous on a closed interval $[a,b]$ and differentiable on the open interval $(a,b)$. So if $f(a)=f(b)$ then there is at lest one point $c$ in $(a,b)$ where $f'(c)=0$
Can I use this logic? and if so how?

A:

If $f$ is not identically zero, there must be some minimal $N$ such that $a_N\neq0$. This implies
$$f(x)=x^N\sum_{n=0}^\infty a_{n+N}x^n.$$
In particular, we have $\lim_{x\to0}\frac{f(x)}{x^N}=a_N$. Since $x_k\neq0$ and $f(x_k)=0$, this implies
$$0=\frac{f(x_k)}{x_k^N}\to a_N\qquad\text{as }k\to\infty,$$
that is, $a_N=0$ which is a contradiction. This completes the proof.


Q:

python tuple with missing entry

I am trying to parse a bibtex file with python3's bibtexparser module.
A sample bibtex file is:
@article{ebert2013,
  Title={First-principles calculation of the Gilbert damping parameter via the linear response formalism with application to magnetic transition metals and alloys},
  Author={Mankovsky, S. and K{\"o}dderitzsch, D. and Woltersdorf, G and Ebert, H.},
  Volume={87},
  Pages={1},
  Year={2013},
  Journal={Phys. Rev. B}
}
@article{ebert2011,
  title = {\textit{Ab Initio} Calculation of the Gilbert Damping Parameter via the Linear Response Formalism},
  author = {Ebert, H. and Mankovsky, S. and K{\"o}dderitzsch, D. and Kelly, P. J.},
  journal = {Phys. Rev. Lett.},
  volume = {107},
  pages = {066603},
  month = {Aug},
  publisher = {American Physical Society}
}
@article{paudyal2013,
  author={Narayan Poudyal and J Ping Liu},
  title={Advances in nanostructured permanent magnets research},
  journal={Journal of Physics D: Applied Physics},
  volume={46},
  number={4},
  pages={043001},
  year={2013}
}

Note See the 2nd item does not have any year key.
Now, I am trying to parse this file as:
    import bibtexparser
    from bibtexparser.bparser import BibTexParser
    # from bibtexparser.bwriter import BibTexWriter
    from bibtexparser.bibdatabase import BibDatabase

    db = BibDatabase()
    with open('report.bib') as bibtex_file:
        parser = BibTexParser()
        db = bibtexparser.load(bibtex_file, parser=parser)
        for i in range(0, len(db.entries)):
            try:
                tuples = (db.entries[i]["title"],db.entries[i]["author"],
                         db.entries[i]["journal"],db.entries[i]["year"])
            except(KeyError):
                continue
            print(tuples)

Since, it does not find the year entry, it is skipping the 2nd element all together; giving output as:
('First-principles calculation of the Gilbert damping parameter via the linear\nresponse formalism with application to magnetic transition metals and alloys', 'Mankovsky, S. and K{\\"o}dderitzsch, D. and Woltersdorf, G and Ebert, H.', 'Phys. Rev. B', '2013')
('Advances in nanostructured permanent magnets research', 'Narayan Poudyal and J Ping Liu', 'Journal of Physics D: Applied Physics', '2013')

But, the desired behaviour is to get the entry with a NULL value for the missing item.
How I can do that?
I have actually gone through this and this se question among others, but have not gained much.
Kindly help.

A:

use .get, and you can remove your try/except for KeyError as well
db.entries[i].get("year")

With dictionaries, it is often recommended to use dict.get(<key>, default=None), to prevent KeyError exceptions, while iterating on non-sanitized data.
Also have a look to dict.pop(<key>, default) which also prevents exceptions but forces you to provide a default value.


Q:

Any CUDA operation after cudaStreamSynchronize blocks until all streams are finished

While profiling my CUDA application with NVIDIA Visual Profiler I noticed that any operation after cudaStreamSynchronize blocks until all streams are finished. This is very odd behavior because if cudaStreamSynchronize returns that means that the stream is finished, right? Here is my pseudo-code:
std::list<std::thread> waitingThreads;

void startKernelsAsync() {
    for (int i = 0; i < 200; ++i) {
        cudaHostAlloc(cpuPinnedMemory, size, cudaHostAllocDefault);
        memcpy(cpuPinnedMemory, data, size);
        cudaMalloc(gpuMemory);

        cudaStreamCreate(&stream);
        cudaMemcpyAsync(gpuMemory, cpuPinnedMemory, size, cudaMemcpyHostToDevice, stream);
        runKernel<<<32, 32, 0, stream>>>(gpuMemory);
        cudaMemcpyAsync(cpuPinnedMemory, gpuMemory, size, cudaMemcpyDeviceToHost, stream);

        waitingThreads.push_back(std::move(std::thread(waitForFinish, cpuPinnedMemory, stream)));
    }

    while (waitingThreads.size() > 0) {
        waitingThreads.front().join();
        waitingThreads.pop_front();
    }
}

void waitForFinish(void* cpuPinnedMemory, cudaStream_t stream, ...) {
    cudaStreamSynchronize(stream);
    cudaStreamDestroy(stream);  // <== This blocks until all streams are finished.
    memcpy(data, cpuPinnedMemory, size);
    cudaFreeHost(cpuPinnedMemory);
    cudaFree(gpuMemory);
}

If I put cudaFreeHost before cudaStreamDestroy then it becomes the blocking operation.
Is there anything conceptually wrong here?
EDIT: I found another weird behavior, sometimes it un-blocks in the middle of processing of streams and then processes the rest of streams.
Normal behavior:

Strange behavior (happens quite often):

EDIT2: I am testing on Tesla K40c card with compute capability 3.5 on CUDA 6.0.
As suggested in comments, it may be viable to reduce number of streams however in my application the memory transfers are quite fast and I want to use streams mainly to dynamically schedule work to GPU. The problem is that after stream finishes I need to download data from pinned memory and clear allocated memory for further streams which seems to be blocking operation.
I am using one stream per data-set because every data-set has different size and processing takes unpredictably long time.
Any ideas how to solve this?

A:

I haven't found why the operations are blocking but I concluded that I can not do anything about it so I decided ti implement memory and streams pooling (as suggested in comments) to re-use GPU memory, pinned CPU memory and streams to avoid any kind of deletion.
In case anybody would be interested here is my solution. The start kernel behaves as asynchronous operation that schedules kernel and callback is called after the kernel is finished.
std::vector<Instance*> m_idleInstances;
std::vector<Instance*> m_workingInstances;

void startKernelAsync(...) {
    // Search for finished stream.
    while (m_idleInstances.size() == 0) {
        findFinishedInstance();
        if (m_idleInstances.size() == 0) {
            std::chrono::milliseconds dur(10);
            std::this_thread::sleep_for(dur);
        }
    }

    Instance* instance = m_idleInstances.back();
    m_idleInstances.pop_back();

    // Fill CPU pinned memory

    cudaMemcpyAsync(..., stream);
    runKernel<<<32, 32, 0, stream>>>(gpuMemory);
    cudaMemcpyAsync(..., stream);

    m_workingInstances.push_back(clusteringInstance);
}

void findFinishedInstance() {
    for (auto it = m_workingInstances.begin(); it != m_workingInstances.end();) {
        Instance* inst = *it;
        cudaError_t status = cudaStreamQuery(inst->stream);
        if (status == cudaSuccess) {
            it = m_workingInstances.erase(it);
            m_callback(instance->clusterGroup);
            m_idleInstances.push_back(inst);
        }
        else {
            ++it;
        }
    }
}

And at the and just wait for everybody to finish:
virtual void waitForFinish() {
    while (m_workingInstances.size() > 0) {
        Instance* instance = m_workingInstances.back();
        m_workingInstances.pop_back();
        m_idleInstances.push_back(instance);
        cudaStreamSynchronize(instance->stream);
        finalizeInstance(instance);
    }
}

And here is a graph form profiler, works as a charm!


Q:

What's the correct way to do a rotating log with python twisted?

I'm using Twisted 14.0.2 and I was wondering what's the correct way of doing a rotating log file without blocking I/O?

A:

Log files are pretty much inherently blocking things.  Eventually Twisted may integrate a non-blocking log consumer with an intelligent buffering policy, but that day is not here yet.  Good luck!


Q:

Model return values from another file not working with Sequelize.js

I have the following code that does not work currently.
var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models.

//Alter table as needed but do NOT force the change.  If an error occurs we will fix manually.
connection.sync({ alter: true, force: false }).then(function() {
  models.users.create({
    name: 'joe',
    loggedIn: true
  }).then( task => {
    console.log("saved user!!!!!");
  });
  process.exit();//close the nodeJS Script
}).catch(function(error) {
  console.log(error);
});

sequelize-lib.js
var Sequelize = require('sequelize');

exports.getSequelizeConnection = function(stage){
  var argv = require('minimist')(process.argv.slice(2)); //If this file is being used in a script, this will attempt to get information from the argument stage passed if it exists

  //Change connection settings based on stage variable.  Assume localhost by default.
  var dbname = argv['stage'] ? argv['stage']+"_db"                              : 'localdb';
  var dbuser = argv['stage'] ? process.env.RDS_USERNAME                         : 'admin';
  var dbpass = argv['stage'] ? process.env.RDS_PASSWORD                         : 'local123';
  var dbhost = argv['stage'] ? "database-"+argv['stage']+".whatever.com"  : 'localhost';

  //If state variable used during require overide any arguments passed.
  if(stage){
    dbname = stage+"_db";
    dbuser = process.env.RDS_USERNAME
    dbpass = process.env.RDS_PASSWORD
    dbhost = "database-"+stage+".whatever.com"
  }

  var connection = new Sequelize(dbname,dbuser,dbpass, {
    dialect: 'mysql',
    operatorsAliases: false, //This gets rid of a sequelize deprecated warning , refer https://github.com/sequelize/sequelize/issues/8417
    host: dbhost
  });
  return connection;
}

exports.setModels = function(connection){
  //Import all the known models for the project.
  const fs = require('fs');
  const dir = __dirname+'/../models';

  var models = {}; //empty model object for adding model instances in file loop below.

  //@JA - Wait until this function finishes ~ hence readdirSync vs regular readdir which is async
  fs.readdirSync(dir).forEach(file => {
    console.log(file);
    //Split the .js part of the filename
    var arr = file.split(".");
    var name = arr[0].toLowerCase();
    //Create a modle object using the filename as the reference without the .js pointing to a created sequelize instance of the file.
    models[name] = connection.import(__dirname + "/../models/"+file);
  })

  //Showcase the final model.
  console.log(models);

  return models; //This returns a model with reference to the sequelize models
}

I can't get the create command to work however with this setup.  My guess is the variables must not be passing through correctly somehow.  I'm not sure what I'm doing wrong?
The create command definitely works because if in the sequelize-lib.js I modify the setModels function to this...
exports.setModels = function(connection){
  //Import all the known models for the project.
  const fs = require('fs');
  const dir = __dirname+'/../models';

  var models = {}; //empty model object for adding model instances in file loop below.

  //@JA - Wait until this function finishes ~ hence readdirSync vs regular readdir which is async
  fs.readdirSync(dir).forEach(file => {
    console.log(file);
    //Split the .js part of the filename
    var arr = file.split(".");
    var name = arr[0].toLowerCase();
    //Create a modle object using the filename as the reference without the .js pointing to a created sequelize instance of the file.
    models[name] = connection.import(__dirname + "/../models/"+file);
    models[name].create({
      "name":"joe",
      "loggedIn":true
    });
  })

  //Showcase the final model.
  console.log(models);

  return models; //This returns a model with reference to the sequelize models
}

Then it works and I see the item added to the database! (refer to proof image below)

Take note, I am simply running create on the variable at this point.  What am I doing wrong where the model object is not passing between files correctly? Weird part is I don't get any errors thrown in the main file?? It's as if everything is defined but empty or something and the command is never run and nothing added to the database.
I tried this in the main file also and no luck.
models["users"].create({
    name: 'joe',
    loggedIn: true
  }).then( task => {
    console.log("saved user!!!!!");
  });

The purpose of this all is to read models automatically from the model directory and create instances that are ready to go for every model, even if new one's are added in the future.
UPDATE::
So I did another test that was interesting, it seems that the create function won't work in the .then() function of the sync command.  It looks like it was passing it correctly though.  After changing the front page to this...
var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models using connection previosly created.

models["users"].create({
  "name":"joe",
  "loggedIn":true
});

//Alter table as needed but do NOT force the change.  If an error occurs we will fix manually.
connection.sync({ alter: true, force: false }).then(function() {
  process.exit();//close the nodeJS Script
}).catch(function(error) {
  console.log(error);
});

Doing this seems to get create to work.  I'm not sure if this is good form or not though since the database might not be created at this point? I need a way to get it to work in the sync function.

A:

Well I answered my question finally, but I'm not sure I like the answer.
var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models using connection previosly created.

//Alter table as needed but do NOT force the change.  If an error occurs we will fix manually.
connection.sync({ alter: false, force: false }).then( () => {
  models["users"].create({
    "name":"joe",
    "loggedIn":true
  }).then( user => {
    console.log("finished, with user.name="+user.name);
    process.exit();
  }).catch( error => {
    console.log("Error Occured");
    console.log(error);
  });
}).catch(function(error) {
  console.log(error);
});

turns out that process.exit was triggering before create would occur because create happens async.  This means that all my code will have to constantly be running through callbacks...which seems like a nightmare a bit.  I wonder if there is a better way?


Q:

Y a-t-il une abréviation qui permet de préciser: "ou dit autrement. blabla", "=. blabla" (autre que "CAD")

La plus proche qui me vient à l'esprit c'est CAD (c'est à dire), mais elle ne va pas dans ce genre de phrase :

il y a des mots qui ont le même sens (CAD synonymes), et il y en a
  d'autre qui blabla...

Un autre exemple:

les sociétés à petite échelle (CAD traditionnelles) sont blabla...

le CAD ne va pas parce que le sens exact du terme entre parenthèses ne devrait pas être "c'est à dire", mais "ou dit autrement".
La distinction est subtile, mais j'ai besoin de précision.

A:

Quant à l'utilisation de l'abréviation CAD, on notera qu'on utilise plutôt « c.-à-d. » pour c'est-à-dire; les traits d'union sont requis, et c'est usuellement en minuscule. Généralement, on préfère aussi l'abréviation française à l'abréviation latine (i.e.).
Si on veut dire que ce qui est entre parenthèses est dit plus simplement ou autrement comme on explique, je me range derrière l'idée qu'on n'a pas besoin de le préciser; c'est la nature même de la parenthèse qui donne un rôle particulier au terme.


Q:

IntelliJ version 12.2 reformat on file save

How to set reformat and remove unused imports upon file save( Ctrl + S) in IntelliJ version 12.2?

A:

When working in IntelliJ IDEA, files are always saved automatically by the IDE. Because of that, there is no need to ever press Ctrl-S, and therefore IntelliJ IDEA does not provide a way to execute actions when files are saved.
Unused imports can be removed automatically directly as files are being edited: Settings | Editor | Auto Import | Optimize imports on the fly
Reformatting code automatically can be performed before a VCS commit; there's a corresponding checkbox in the Commit Changes dialog.


Q:

unable to obtain stable firefox connection in 60 seconds (127.0.0.1:7055) -CentOS

I get the error: unable to obtain stable firefox connection in 60 seconds (127.0.0.1:7055) when I run this code:
require 'watir-webdriver'
require 'headless'

headless = Headless.new
headless.start

begin
    browser = Watir::Browser.start "https://google.com"
rescue Exception => e
    puts e
    puts "Exiting..."
    exit
end

browser.goto "http://google.com"
puts browser.url
browser.close

I am using: I am using Firefox version 38.7.0, Headless gem version 2.2.3 and Selenium-Webdriver gem version 2.53.0.
I have tried:

Updating  selenium-webdriver
Uninstalling headless, selenium and Firefox and reinstalling
them.
Restarting the server
Updating Firefox to 45.0

The same code works fine in other test environments.
Updates:
I have tried running the same code with Chrome as suggested by a poster. I got the error message: unable to connect to chromedriver 127.0.0.1:9515
Just to be sure everything is installed right I just ran the following:
yum install xorg-x11-server-Xvfb

Response:
Package xorg-x11-server-Xvfb-1.15.0-36.el6.centos.x86_64 already installed and latest version
Nothing to do

I also ran:
yum install firefox

Response:
Package firefox-38.7.0-1.el6.centos.x86_64 already installed and latest version
Nothing to do

A:

So it turns out that it was a user rights issue that was causing the problem. I logged in as the root user and was pleasantly surprised to see that the code ran without any errors.


Q:

Paraview programmatically Reset Session

In Paraview, one can do Edit -> Reset Session.
It brings a clean state.
How can that be done programmatically, from a python script?
I mean it to work for both the GUI (at the python shell and as a macro) and CLI (pvpython).
PS: I wouldn't know what are the differences between Reset Session and closing / reopening Paraview.
I did not test it thoroughly, but in all I could observe, they behave the same.
PS2: I am currently using a contrived way, but it is not quite equivalent to Reset Session.
def reset_session() :
    RemoveViewsAndLayouts()
    clear_pipeline()
    return

def clear_pipeline() :
    srcs = GetSources()
    for key, val in srcs.items() :
        #print( "key = " + str(key) + ", value = " + str(val) )
        #print( "   (" + str(type(key)) + "),  (" + str(type(val)) + ")" )
        Delete(val)
        del val
    return

PS3: I tested an answer with this minimal code, executed from the GUI from Macros -> mymacro, and it crashes.
Disconnect()
Connect()

A:

For ParaView <= 5.7.1 : Reset Session remove all the proxies. It is really close to closing reopening the application and can be considered as such.
To do that in Python, since ResetSession is not implemented, use the following :
Disconnect()
Connect()


Q:

html nested table hide or show table row by clicking table row first td

I am doing one project, in which I want to display data in nested table structure, like in link
http://www.aspdotnet-suresh.com/2012/05/gridview-with-in-gridview-or-nested.html
In that please check in down demo. It was implemented in grid view in asp.net. But I am trying to implementing in html. I got solution but, problem is that in that table if I am clicking any where in the row it is displaying next row. but I need first td of tr is clicked then only I have to display the tr other wise nothing,
and my html code is below.
Please anybody help me.

                        TD1
                        TD2
                        TD3

                                        nestedTD1
                                        nestedTD2

                                        nestedTD3
                                        nestedTD4

                        TD1
                        TD2
                        TD3

                                        nestedTD1

                                        nestedTD3

A:

use td:first in your selector to select the first td and parent().next() to toggle the next tr
try this
 $(".toptable tr.accordion td:first").click(function(){
                       //--^^^^^^^^---here
     $(this).parent().next().fadeToggle();
      //----^^^^^^^^^---here
});

updated
after the comment below

it is not not working for second row.means if iam clicking on second row first td it has to show some other table row.

try this
$(".toptable tr").find('td:first').click(function(){
     $(this).parent().next().fadeToggle();
});

working fiddle


Q:

How to make a fluid sidebar?

I'm creating a sidebar with this CSS code:
.sidebar {
position: absolute;
z-index: 100;
top: 0;
left: 0;
width: 30%;
height: 100%;
border-right: 1px solid #333;
}

But the sidebar width doesn't scale when I change the browser width. How can I make the sidebar fluid?
Thanks.

A:

Look at the height in body in CSS part.
Here is a working example for you:
Your HTML:

This design uses a defined body height of 100% which allows setting the contained left and
right divs at 100% height.

This design uses a defined body height which of 100% allows setting the contained left and
right divs at 100% height.

Your CSS:
body {
margin:0;
padding:0;
width:100%; /* this is the key! */
}

#sidebar {
position:absolute;
right:0;
top:0;
padding:0;
width:30%;
height:100%; /* works only if parent container is assigned a height value */
color:#333;
background:#eaeaea;
border:1px solid #333;
}

#content { margin-right: 200px; }


Q:

How to parse xml in ANSI or Unicode in javascript?

I'm trying to fetch and parse an XML-file through javascript. I don't control the XML-file.
Now somehow the encoding of some XML-files changed, which results in the code not being able to parse the file as far as I can tell. It used to be ANSI, some are Unicode now (and those are failing). Is there a way for me to correctly get the content, so both versions (ANSI and Unicode) work?
Files just start with:
<?xml version="1.0"?>
And the only thing in javascript to to parse is:
var parser = new DOMParser();
var dom = parser.parseFromString(responseDetails.responseText,"application/xml");

jQuery-answers are fine btw, not using it for this part but it is available.

A:

If the encoding isn't correctly specified, I think you're going to have to chop the header off, then attach a new header specifying a candidate encoding. Parse that, and if it fails, attach a new header with a new candidate encoding. And so on.
Of course, a successful parse doesn't imply you've got the right encoding, but an encoding that passes the parsing stage.
The real fix is to correct the original XML, unfortunately.


Q:

NSDate Formatter in an NSTimer

So I have an NSTimer and im using a date formatter to pause and play the timer but when i start the timer it starts at 07:00:00 when i want it to start at 00:00:00.
My timer code is
-(void) updateTimer {

    NSDate *currentDate = [NSDate date];

    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"hh:mm:ss";
    //[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];

    NSString *timeString = [dateFormatter stringFromDate:timerDate];
    hhmmssLabel .text = timeString;
    pauseTimeInterval = timeInterval;

}

-(void)pauseTimer {

    [tickerTimer invalidate];
    tickerTimer = nil;
    [self updateTimer];
}

-(void) unPauseTimer {

    startDate = [NSDate date] ;
    startDate = [startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))];
    tickerTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/1.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
}

Im assuming it has to do with the time zone so i commented it out which didnt help. I can't get it to start at 00:00:00

A:

I think you can simplify you code a litte.  Your requirements are not too complicated (you are just dealing with intervals not absolute dates), so it would be ok to use something like this:
NSDate * currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];

// NSTimeInterval is in measured in Seconds
NSInteger hours = ( (NSInteger) timeInterval / 3600.0 );
NSInteger mins  = ( (NSInteger) (timeInterval / 60) % 60 );
NSInteger secs  = ( (NSInteger) timeInterval % 60.0 );

NSString * timeString = [NSString stringWithFormat:%02u:%02u:%02u, hours, mins, secs];

Otherwise try to look at this answer.  Perhapse you need @"HH:mm:ss" (for 24 hour time) or [NSTimeZone timeZoneWithName:@"UTC"]];


Q:

Custom ArrayAdapter, super can't be resolved

public class ImageAdapter extends ArrayAdapter<ImageView> {
    Context context;
    String[] PosterList;

    public ImageView(Context context, String[] PosterList){
        super(context, 0, PosterList);
        this.context = context;
        this.PosterList = PosterList;
    }
}

So in the code snippet above, is the constructor for a custom ArrayAdapter. The "super" method can not be resolved. I'm not sure why, considering that the method signature written above matches one of the constructors on the android website for ArrayAdapter. How can I fix this?
Since I'm using Picasso to download images into a gridview, I'm copying a array of strings (that are actually URLs) so they can be processed by Picasso in the getView method and return an ImageView object.

A:

Change
 public class ImageAdapter extends ArrayAdapter<ImageView>
 ...
     public ImageView(Context context, String[] PosterList)

to (respectively)
 public class ImageAdapter extends ArrayAdapter<String>
 ...
     public ImageAdapter(Context context, String[] PosterList)

You are defining the wrong constructor.


Q:

Click on the screen or any element to execute a function

How can I reverse a function so when I click on an input it transforms the y value to -100% and when i click elsewhere on the screen or another element it reverse so the value returns to 0%.
I want to do it in js not in css

let movingName = document.querySelectorAll('.span-name');
let input = document.getElementsByTagName('input')

input[0].onclick = function() {
  movingName[0].style.transform = "translateY(-100%)";
}
.span-name {
  position: relative;
  color: black;
  bottom: 34px;
  left: 10px;
  font-size: 18px;
  padding: 2px;
  z-index: 1;
  pointer-events: none;
  display: block;
  width: fit-content;
  transition: 500ms;
}
<input type="email" name="email_config" required>
Email Configuration

A:

Try using the body to get that click event and filter the events basis the target.

let movingName = document.querySelectorAll('.span-name');
let input = document.getElementsByTagName('input')

document.getElementsByTagName('body')[0].onclick = function(e) {
    var tagName = e.target.tagName;
    if (tagName !== 'INPUT') {
        movingName[0].style.transform = "translateY(100%)";
    }
}

input[0].onclick = function() {
  movingName[0].style.transform = "translateY(-100%)";
}
.span-name {
  position: relative;
  color: black;
  bottom: 34px;
  left: 10px;
  font-size: 18px;
  padding: 2px;
  z-index: 1;
  pointer-events: none;
  display: block;
  width: fit-content;
  transition: 500ms;
}

    <input type="email" name="email_config" required>
    Email Configuration


Q:

How to set up friends as recipients in public activity?

I have set up a friendship model for my app,
create_table "friendships", force: :cascade do |t|
  t.integer  "user_id"
  t.integer  "friend_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

And the model looks like this,
belongs_to :user
belongs_to :friend, :class_name => "User"

And this is my user model,
has_many :friendships
has_many :friends, :through => :friendships
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_friendships, :source => :user

And I have tracked my movie model with the Public Activity gem,
include PublicActivity::Model
tracked owner: -> (controller, model) { controller && controller.current_user }
tracked :params => {
  :title => :get_title,
  :poster => :get_poster
}

has_and_belongs_to_many :users

The current situation is that when a user adds a activity to the app, every other user sees that notificiation. What I would like is to only send the activity to the friends of the user.
I think all the necessary data and links are preset, but I'm unsure on how to hook it all up.

A:

I think you would have to do this through custom activity.
For example,
When a new movie is created , you can do the create activity a callback method,
after_create :create_activity

def create_activity
   user.friends.each do |friend|
      self.create_activity action: :new , parameters: {title:title,poster:poster}, recipient: friend, owner: current_user
  end
end

however this solution is very inefficient. I am not sure if there is a method provided for the gem that you can create multiple activities all together, like ActiveRecord, Moview.create([{title:1},{title:2}]). Otherwise you many want to move this into a background job, something like sidekiq .


Q:

Parsing from WTForms into an Array in MongoDB

I'm attempting to parse from WTForms a list of Ingredients and a Method to create a cookbook page in jinja, the app so far reads from the database and can display the data best in an ordered list from the array. My problem is werkzeug is throwing an error when attempting to submit the data, and therefore not pushing any data from the forms into the database.
I've attempted to use custom forms within the form group for the page itself, this has enabled me to at least display the forms with more forms for the ingredients. I had also tried using the prebuilt WTForms imports for this too.
I've taken a look on the documentation for wtforms and the mongodb documentation too and this hasnt helped clarify my issue.
For code this is my approuting
def addrecipe():
    if 'username' not in session:
        flash('Not possible for none members! Please create an account.')
        return redirect(url_for('register'))

    form = RecipeForm()
    user = mongo.db.users.find_one({"name": session['username'].title()})

    if request.method == 'POST' and form.validate_on_submit():
        recipe = mongo.db.Recipes
        recipe.insert_one({'recipe_name': request.form['recipe_name'],
                    'recipe_type': request.form['recipe_type'],
                    'recipe_desc': request.form['recipe_desc'],
                    'serving': request.form['serving'],
                    'prep_time': request.form['prep_time'],
                    'cook_time': request.form['cook_time'],
                    'ingredients': request.form['ingredients'],
                    'method': request.form['method'],
                    'img_url': request.form['image']})
        flash('Recipe success!')
        return redirect(url_for('index'))
    return render_template('addrecipe.html', form=form)

My database looks similar however the Ingredients and the method parts are arrays.
The forms page here

class IngredientForm(FlaskForm):
    description = StringField()

class MethodsForm(FlaskForm):
    method = StringField()

class RecipeForm(FlaskForm):
    recipe_name = StringField('Recipe Name:')
    recipe_type = StringField('Recipe Type:')
    recipe_desc = StringField('Description:')
    serving = StringField('Serving Size:')
    prep_time = StringField('Preparation Time:')
    cook_time = StringField('Cooking Time:')
    ingredients = FieldList(StringField(IngredientForm), 'Ingredients:', min_entries=4, max_entries=25)
    method = FieldList(StringField(MethodsForm), 'Method:', min_entries=4, max_entries=10)
    img_url = StringField('Got a photo link?:')
    submit = SubmitField('Add Recipe')

I'm expecting my submit button to push straight out to the database with a new recipe that then enables my templating to build this to my landing page immediately, however the werkzeug error is showing 400: bad request KEYError 'Ingredients'.
I Appreciate any help with this, this is all a little new to me on the backend side!

A:

So, after doing some digging and playing around with the code as per usual it was something I hadn't actually thought of yesterday due to being so engrossed in other ways to do it. It was a basic bit of vanilla python to split these items into an array.
In my app.py file I have amended it to use a .split(",") separator to parse these into the arrays in the database.
recipe.insert_one({'recipe_name': request.form['recipe_name'],
                            'recipe_type': request.form['recipe_type'],
                            'recipe_desc': request.form['recipe_desc'],
                            'serving': request.form['serving'],
                            'prep_time': request.form['prep_time'],
                            'cook_time': request.form['cook_time'],
 Here -->                  'ingredients': request.form['ingredients'].split(","),
   Here -->                'method': request.form['method'].split(","),
                            'img_url': request.form['img_url']})

This results in it parsing directly to the database without a problem. However limiting the number of fields present (This should be sorted easily enough with some scss for those particular forms.)
Updated forms.py
class RecipeForm(FlaskForm):
    recipe_name = StringField('Recipe Name:')
    recipe_type = StringField('Recipe Type:')
    recipe_desc = StringField('Description:')
    serving = IntegerField('Serving Size:')
    prep_time = IntegerField('Preparation Time:')
    cook_time = IntegerField('Cooking Time:')
    ingredients = StringField('Ingredients:')
    method = StringField('Method:')
    img_url = StringField('Got a photo link?:')
    submit = SubmitField('Add Recipe')


Q:

NullPointerException in RecyclerView espresso test on hdpi device

I have the following test written for RecyclerView
 @Test
  fun testHomeActivity_recyclerViewIndex0_configurationChange_displaysWelcomeMessageCorrectly() {
    launch(HomeActivity::class.java).use {
      onView(isRoot()).perform(orientationLandscape())
      onView(
        atPositionOnView(R.id.home_recycler_view, 0, R.id.welcome_text_view )
      ).check(matches(withText(containsString("Welcome"))))
    }
  }

It gets passed successfully on my real device, but gets failed on Nexus S hdpi emulator device. With the following error:
kotlin.KotlinNullPointerException
at org.oppia.app.recyclerview.RecyclerViewMatcher$Companion$atPositionOnView$1.matchesSafely(RecyclerViewMatcher.kt:52)
at org.oppia.app.recyclerview.RecyclerViewMatcher$Companion$atPositionOnView$1.matchesSafely(RecyclerViewMatcher.kt:28)
at org.hamcrest.TypeSafeMatcher.matches(TypeSafeMatcher.java:65)
at androidx.test.espresso.base.ViewFinderImpl$MatcherPredicateAdapter.apply(ViewFinderImpl.java:130)
at androidx.test.espresso.core.internal.deps.guava.collect.Iterators$5.computeNext(Iterators.java:637)
at androidx.test.espresso.core.internal.deps.guava.collect.AbstractIterator.tryToComputeNext(AbstractIterator.java:141)
at androidx.test.espresso.core.internal.deps.guava.collect.AbstractIterator.hasNext(AbstractIterator.java:136)
at androidx.test.espresso.base.ViewFinderImpl.getView(ViewFinderImpl.java:69)
at androidx.test.espresso.ViewInteraction$2.call(ViewInteraction.java:280)
at androidx.test.espresso.ViewInteraction$2.call(ViewInteraction.java:272)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

I don't think it really concerns the issue but here is home_recycler_view.xml :
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

  <data>

    <import type="org.oppia.app.R" />

    <variable
      name="presenter"
      type="org.oppia.app.home.HomeFragmentPresenter" />
  </data>

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:gravity="center"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
      android:id="@+id/home_recycler_view"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:clipToPadding="false"
      android:overScrollMode="never"
      android:paddingTop="36dp"
      android:paddingBottom="@dimen/bottom_white_space"
      android:scrollbars="none" />
  </LinearLayout>
</layout>

I have tried looking for it everywhere like here and here

A:

Ok I solved the issue. Basically, on orientation change recyclerview scrolls up a little bit so the view I am trying to find gets hidden.
I added this line to scroll to that position, and then check the text.
onView(withId(R.id.home_recycler_view)).perform(scrollToPosition<RecyclerView.ViewHolder>(0))


Q:

calculate each chunk by group using dplyr?

How can I get the expected calculation using dplyr package?
row value   group   expected
1   2       1       =NA
2   4       1       =4-2
3   5       1       =5-4
4   6       2       =NA
5   11      2       =11-6
6   12      1       =NA
7   15      1       =15-12

I tried
df=read.table(header=1, text='    row    value  group
1   2   1
2   4   1
3   5   1
4   6   2
5   11  2
6   12  1
7   15  1')

df %>% group_by(group) %>% mutate(expected=value-lag(value))

How can I calculate for each chunk (row 1-3, 4-5, 6-7) although row 1-3 and 6-7 are labelled as the same group number?

A:

As your group variable is not useful for this, create a new variable aux and use it as the grouping variable:
library(dplyr)
df$aux <- rep(seq_along(rle(df$group)$values), times = rle(df$group)$lengths)

df %>% group_by(aux) %>% mutate(expected = value - lag(value))

Source: local data frame [7 x 5]
Groups: aux

  row value group aux expected
1   1     2     1   1       NA
2   2     4     1   1        2
3   3     5     1   1        1
4   4     6     2   2       NA
5   5    11     2   2        5
6   6    12     1   3       NA
7   7    15     1   3        3

A:

Here is a similar approach. I created a new group variable using cumsum. Whenever the difference between two numbers in group is not 0, R assigns a new group number. If you have more data, this approach may be helpful.
library(dplyr)

mutate(df, foo = cumsum(c(T, diff(group) != 0))) %>%
group_by(foo) %>%
mutate(out = value - lag(value))

#  row value group foo out
#1   1     2     1   1  NA
#2   2     4     1   1   2
#3   3     5     1   1   1
#4   4     6     2   2  NA
#5   5    11     2   2   5
#6   6    12     1   3  NA
#7   7    15     1   3   3


Q:

How can I make text that impedes on it's underline 'block out' the underline with whitespace in HTML/CSS?

Is there any way to reproduce the following effect with HTML/CSS:
http://i.imgur.com/ASdXb.png
Basically I want to have my link text 'take priority' and block out some white space around any letters that cross the underline/border-bottom.

A:

It can be done, it looks like a perfect example for a useful LESS mixin. http://jsfiddle.net/elclanrs/r6Rmh/
p {
    display: inline-block;
    font: bold 24px Arial;
    border-bottom: 3px solid black;
    text-shadow: -3px 0 white, 3px 0 white;
    line-height: 21px;
}


Q:

指定したアルバム内への画像の保存方法について

iOSにて、あるボタンを押して「写真」配下にアルバムを作成し、そのアルバム内に撮影した写真を保存する機能を加えようとしています。
ただ、アルバムの作成はできたものの、そのアルバムを指定して写真を保存するということができていません。(下記では、「カメラロール」に保存されてしまいます。)
こちらの方法について見つけることができず、ご存知のかたいらっしゃいましたら、ご教授いただければ幸いです。
なお、現在作成しているコードは下記のとおりです。
【アルバムを作成する】
@IBAction func tapAddBookBtn(sender: AnyObject) {
    var titleTextField: UITextField?

    //タイトル入力をpopupで求める
    let alertController: UIAlertController = UIAlertController(title: "タイトル登録", message: "本のタイトルを入力してください", preferredStyle: .Alert)

    //cancelボタン
    let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
        print("Pushed CANCEL")
    }
    alertController.addAction(cancelAction)

    //タイトル登録ボタン
    let registAction: UIAlertAction = UIAlertAction(title: "登録", style: .Default) { action -> Void in
        print("regist")
        print(titleTextField?.text)

        let albumName :String = readPhotoAlbum.applicationName + (titleTextField?.text)!

        PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> Void in
            self.request = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(albumName)
            },completionHandler: { (isSuccess, error) -> Void in
                if isSuccess == true {
                    print("Success!")
                }
                else{
                    print("error occured")
                }
        })
    }
    alertController.addAction(registAction)

    alertController.addTextFieldWithConfigurationHandler { textField -> Void in
        titleTextField = textField
        textField.placeholder = "Title"
    }

    presentViewController(alertController, animated: true, completion: nil)

}

【画像を保存する(カメラロール)】
@IBAction func tapSaveBtn(sender: AnyObject) {

    //保存確認
    let alertController: UIAlertController = UIAlertController(title: "保存確認", message: "本当に保存してよいですか?", preferredStyle: .Alert)

    //保存確認->cancel
    let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: .Cancel) { action -> Void in
        print("Pushed CANCEL")
    }
    alertController.addAction(cancelAction)

    //保存確認->保存
    let saveAction: UIAlertAction = UIAlertAction(title: "保存", style: .Default) { action -> Void in
        print("save")

        //savingView配下のeditingPhoto等を1枚の画像として保存
        UIGraphicsBeginImageContextWithOptions(self.editingPhoto.frame.size, false, 0)
        self.savingView.layer.renderInContext(UIGraphicsGetCurrentContext()!)

        let exportImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        //写真保存(「特定のアルバム」内には保存できていない。)
        UIImageWriteToSavedPhotosAlbum(exportImage,
            self, "image:didFinishSavingWithError:contextInfo:", nil)
        }
    }
    alertController.addAction(saveAction)

    presentViewController(alertController, animated: true, completion: nil)
}

なお環境は、iOS9,xcode7.0.1です。
よろしくお願いいたします。

※追記
Harawoさんの回答を参考にし、下記で動くことを確認しました。
【アルバムを作成する】
@IBAction func tapAddBookBtn(sender: AnyObject) {
    var titleTextField: UITextField?

    //タイトル入力をpopupで求める
    let alertController: UIAlertController = UIAlertController(title: "タイトル登録", message: "本のタイトルを入力してください", preferredStyle: .Alert)

    //cancelボタン
    let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
        print("Pushed CANCEL")
    }
    alertController.addAction(cancelAction)

    //タイトル登録ボタン
    let registAction: UIAlertAction = UIAlertAction(title: "登録", style: .Default) { action -> Void in
        print("regist")
        print(titleTextField?.text)

        let albumName :String = readPhotoAlbum.applicationName + (titleTextField?.text)!

        PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> Void in
            self.request = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(albumName)
            },completionHandler: { (isSuccess, error) -> Void in
                if isSuccess == true {
                    print("Success!")
                }
                else{
                    print("error occured")
                }
        })
    }
    alertController.addAction(registAction)

    alertController.addTextFieldWithConfigurationHandler { textField -> Void in
        titleTextField = textField
        textField.placeholder = "Title"
    }

    presentViewController(alertController, animated: true, completion: nil)

}

【画像を保存する(カメラロール)】
@IBAction func tapSaveBtn(sender: AnyObject) {

    //保存確認
    let alertController: UIAlertController = UIAlertController(title: "保存確認", message: "本当に保存してよいですか?", preferredStyle: .Alert)

    //保存確認->cancel
    let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: .Cancel) { action -> Void in
        print("Pushed CANCEL")
    }
    alertController.addAction(cancelAction)

    //保存確認->保存
    let saveAction: UIAlertAction = UIAlertAction(title: "保存", style: .Default) { action -> Void in
        print("save")

        //savingView配下のeditingPhoto等を1枚の画像として保存
        UIGraphicsBeginImageContextWithOptions(self.editingPhoto.frame.size, false, 0)
        self.savingView.layer.renderInContext(UIGraphicsGetCurrentContext()!)

        let exportImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        //アルバム名を指定する
        let albumTitle = titleTextField

        var theAlbum: PHAssetCollection?

        // アルバムを検索
        let result = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.Any, options: nil)
        result.enumerateObjectsUsingBlock({(object, index, stop) in
            if let theCollection = object as? PHAssetCollection where
                theCollection.localizedTitle == albumTitle
            {
                theAlbum = theCollection
            }
        })
        // アルバムにイメージを保存
        if let anAlbum = theAlbum {
            PHPhotoLibrary.sharedPhotoLibrary().performChanges({
                let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(exportImage)
                let assetPlaceholder = createAssetRequest.placeholderForCreatedAsset!
                let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: anAlbum)
                albumChangeRequest!.addAssets([assetPlaceholder])
                }, completionHandler: nil)
            print("save image into the Album.")
        }
    }
    alertController.addAction(saveAction)

    presentViewController(alertController, animated: true, completion: nil)
}

A:

iOS 8より、Photo.appのライブラリにアクセスするフレームワークに、Photos Frameworkが推奨されることになりました。
Photos Framework Reference
以下、一例として、「MyAlbum」という名前のアルバムに、UIImageインスタンスを保存するコードを載せておきます。（ボタンを押したら、保存）
@IBAction func savePhoto(sender: AnyObject) {
    let albumTitle = "MyAlbum" // アルバム名
    let savingImage = UIImage(named: "a.png")! // 保存するイメージ
    var theAlbum: PHAssetCollection? // アルバムをオブジェクト化
    // フォトライブラリからMyAlbumを検索
    let result = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.Any, options: nil)
    result.enumerateObjectsUsingBlock({(object, index, stop) in
        if let theCollection = object as? PHAssetCollection where
        theCollection.localizedTitle == albumTitle
        {
            theAlbum = theCollection // 見つかったら、theAlbumに代入
        }
    })
    // アルバムにイメージを保存する
    if let anAlbum = theAlbum {
        PHPhotoLibrary.sharedPhotoLibrary().performChanges({
            let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(savingImage)
            let assetPlaceholder = createAssetRequest.placeholderForCreatedAsset!
            let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: anAlbum)
            albumChangeRequest!.addAssets([assetPlaceholder])
        }, completionHandler: nil)
    } else {
        print("MyAlbum was not found.")
    }
}

iOS 9よりAssets Library FrameworkはDeprecatedになります。ご注意ください。Assets Libraryより、Photosのほうがいくぶん使いやすくなったかなという印象があります。


Q:

How does one use "gcloud compute operations list" with a filter by instance name?

The root problem is that I have a project that has many tens of thousands of operations, such that it's very difficult to track down operations associated with specific instances being created or deleted. So, I'm looking for a way to list operations by target.
The deprecated gcutil docs talk about setting filter expressions to possibly filter operations by target instance name or instance selfLink, but there doesn't seem to be any mention of a similar filter expression in gcloud compute operations list described here:
gcloud compute operations list [NAME …] [--format FORMAT] [--help] [--limit LIMIT] [--log-http] [--project PROJECT_ID] [--quiet, -q] [--regexp REGEXP, -r REGEXP] [--sort-by SORT_BY] [--trace-token TRACE_TOKEN] [--uri] [--global | --regions [REGION,…] | --zones [ZONE,…]] [-h]

The only non-global flags listed there are the following:
--global
If provided, only global resources are shown.
--limit LIMIT
The maximum number of results.
--regexp REGEXP, -r REGEXP
A regular expression to filter the names of the results on. Any names that do not match the entire regular expression will be filtered out.
--regions [REGION,…]
If provided, only regional resources are shown. If arguments are provided, only resources from the given regions are shown.
--sort-by SORT_BY
A field to sort by. To perform a descending-order sort, prefix the value of this flag with a tilde (~).
--uri
If provided, the list command will only print URIs for the resources returned. If this flag is not provided, the list command will print a human-readable table of useful resource data.
--zones [ZONE,…]
If provided, only zonal resources are shown. If arguments are provided, only resources from the given zones are shown.

Furthermore, the examples given by the gcutil docs don't seem to work:
$ gcutil listoperations --zone us-east1-a --filter="target eq '.*dhuo.*'"
WARNING: 'gcutil' has been deprecated and soon will be removed from Cloud SDK distribution.
WARNING: Please use 'gcloud compute' instead.
WARNING: For more information see https://cloud.google.com/compute/docs/gcutil
Error: Invalid value for field 'filter': 'target eq '.*dhuo.*''.  Unrecognized field name in list filter: target.

That's despite the raw API docs describing 'target' as an example here:
Filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following:
FIELD_NAME COMPARISON_STRING LITERAL_STRING
FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. For example, if you search for machineType in the Firewalls collection, the filter will fail, because the machineType field is specific to instances and other resources do not have that property.
COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals).
LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, when filtering instances by name, name eq my-instance won't work, but name eq .*my-instance will work.
For example, for Operation resources, you could filter by the type of the operation:

filter=operationType ne insert
The above filter returns only results whose type field does not equal insert. You can also enclose your literal string in single, double, or no quotes. For example, all three of the following would be valid expressions:

filter=operationType ne "insert"
filter=operationType ne 'insert'
filter=operationType ne insert
If you use a complex regular expression, you need to encode the special characters, including quotes. Consider the following regular expression:

target eq 'example-name-[0-9]+'
To use the expression, you would need to encode it:

filter=target+eq+%27example-name-%5B0-9%5D%2B%27
If you are using the API through a client, such as client libraries, or gcloud compute, keep in mind that your client might encode your regular expression automatically so that you will not need to encode it yourself.

Is there something I'm doing wrong, and is it indeed possible to filter zone operations based on the name of the instance I'm trying to insert?

A:

I'm not sure how to do it using gcloud, but you can still use gcutil:
gcutil listoperations --zone us-east1-a --filter="targetLink eq '.*dhuo.*'"

So it is almost the same as your, but should use 'targetLink' instead of 'target'.


Q:

Linux from scratch: 'tools/include' is not a directory when installing linux-5.5.3 API Headers

I am working on linux from scratch and I am at section 5.6 linux-5.5.3 API Headers. I was able to extract the tar, cd into the new directory, and make. At this point I am inside the linux-5.5.3 directory. The command I am having trouble with is this:
cp -rv usr/include/* /tools/include

It just returns:
cp: target '/tools/include' is not a directory

What does work for me is changing the command to:
cp -rv usr/include/* ./tools/include

I did this because the only "tools" directory I know of is two levels up at the top. Here is an approximate tree:
mnt/lfs (mount point for the lfs partition)
|-sources
| |-*Many tar archives*
| |-linux-5.5.3
|   |-*Some Directories*
|   |-usr
|     |-include
|-tools

I followed along with the book 100% and compiled all the other packages as instructed.
My question: How should I proceed? Should I just do what works with the upper-level "tools" directory or should I go back and troubleshoot? If I should troubleshoot, what specifically should I do?
This is the chapter I am reading for reference: http://www.linuxfromscratch.org/lfs/view/stable/chapter05/linux-headers.html

A:

I followed along with the book 100%

No, you did not. The symlink from /tools to $LFS/tools is created in chapter 4.2 Creating the $LFS/tools Directory:

mkdir -v $LFS/tools
ln -sv $LFS/tools /

You ask:

what specifically should I do?

It is imperative that you follow the instructions exactly. It is even more important that for each and every command in the book, you fully understand the command, you fully understand what the command does, you fully understand why the command is there, and you fully understand why the command is at that place.

How should I proceed? Should I just do what works with the upper-level "tools" directory […]?

This is a good example of the above: this can't work, and it is important to understand why it can't work.


Q:

Fill ComboBox on form in a method triggered by a button

First of all, if I click a button the method cbBefüllen will execute.
private void btnEntfernen_Click(object sender, EventArgs e)
{
    FeiertageEntfernen entfernen = new FeiertageEntfernen();
    entfernen.cbBefüllen();
    entfernen.Show();
    entfernen.Focus();
}

The following method is just here as an interface between my form and a class. (Please don't ask, in my code I have some good reasons for it ;) ).
public void cbBefüllen()
{
    database.cbFeiertagebefüllen();
}

The method cbFeiertagebefüllen (tries to) fills my ComboBox, which is located in the form "feiertagentfernen".
public void cbFeiertagebefüllen()
{
    FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();
    string Query = @"select bezeichnung from feiertage";
    using (var command = new SQLiteCommand(Query, sqlite_conn))
    {
        if (sqlite_conn.State != ConnectionState.Open)
        {
            sqlite_conn.Open();
        }
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                string übergabe = reader.GetString(0);
                feiertagentfernen.cbFeiertag.Items.Add(übergabe);
            }
        }
    }
}

But after this whole process my ComboBox is still empty. The reader in the last picture picks the correct value from the database, but somehow it won't write it into the ComboBox.

A:

Your problem is in this line:
FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();

in your cbFeiertagebefüllen()
You make a new form but you want your combo box from the form from the 1st piece of code to be filled. To fix this you could pass along an instance of the form to the filling method.
The updated 2 pieces of code will be (first piece can be left alone):
In cbBefullen:
database.cbFeiertagebefüllen(this);
//'this' means we're passing along the form as parameter

In cbFeiertagebefüllen:
public void cbFeiertagebefüllen(FeiertageEntfernen feiertagentfernen)
{
    string Query = @"select bezeichnung from feiertage";
    using (var command = new SQLiteCommand(Query, sqlite_conn))
    {
        if (sqlite_conn.State != ConnectionState.Open)
        {
            sqlite_conn.Open();
        }
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                string übergabe = reader.GetString(0);
                feiertagentfernen.cbFeiertag.Items.Add(übergabe);
            }
        }
    }

}


Q:

How do I add features to a syntax definition in Sublime Text without editing it?

For example, I would like to highlight @param, @type, and @return (i.e. epytext declarations) in my Python docstrings.  I have figured out how to do this by simply editing Python/Python.tmLanguage; however, I would really like to put this in its own file, for a couple of reasons:

I don't always want to apply this highlighting.  It's only for projects that use epydoc as their documentation tool; in other projects, I would want to highlight reStructuredText instead.
When Sublime Text updates, I'd like to have my own syntax as an overlay onto the included features. there are several features of Python that Sublime's author may choose to include in future versions and I don't want to have to manually figure out what I changed each time an update modifies the base Python syntax definition.
I keep my own editor configuration in version control, but I want that to be my own original stuff; I don't want to be burdened with having to carry copies (possibly proprietary? I don't know, it doesn't seem to have an independent license) of syntax definitions that come with Sublime.

Is there a way to put highlighting rules into a separate file, perhaps to only be applied to a particular scope?

A:

Sounds to me like you want to create your own syntax file, inherit from the Python syntax file (source.python), and make your changes and customizations there. Sublime Text 2 uses the .tmLanguage format for syntax files, which is a bit complex, but fortunately most of the work has already been done for you, just by inheriting from source.python.
What you want to do is set up a regex pattern to match the substrings that you want to highlight, and give that pattern a name; something like punctuation.definition.comment.epydoc, to follow the convention set in Java/JavaDoc.tmLanguage. Then, check your color scheme file (ending in .tmTheme) and make sure there are settings for the scope that you've chosen -- or for one of its parents, since ST2 should use proper scoping rules for this sort of thing.
To use the syntax file you've created, stick it in Packages/User (so that ST2 doesn't overwrite it on upgrades), open a Python file in the editor, and then select your new syntax from the dropdown list in the bottom right corner of the window. If you've set up everything correctly, the epydoc strings should change to be whatever color you've set in your color scheme.
Good luck! And post a link somewhere when you've got a syntax file that works, so others can see and use it, as well!


Q:

Find an appropriate Lyapunov function for the nonlinear system of differential equations

I have tried numerous functions for $V(x)$ but I am having trouble finding one that tells me about the stability at the equilibrium point.  Any ideas of one that may work?

A:

try the first one again (V(x) = ax^2 +by^2), except let a=b after you multiple V'(x)f(x).
you will see that one pair of terms cancels. pull out the -2b and then 3 of the terms will be a difference of squares. factor those terms and you will be left with one term that is squared and one power that is to the 4th (so they are both positive). Since this positive term is multiplied by a -2, the whole thing is negative and QED.


Q:

A field of type "String" does not appear in the result (json) serialization of the vraptor controller

A field of type "String" does not appear in the result of the serialization controller
result.use(Results.json()).indented().from(list).serialize();

Some fields appear, and another not appear when null, the field I want is to type "String" and implemented the "get" and "sets" and this always filled
PS: I am using vraptor framework

A:

I solved using the "include":
result.use(Results.json()).indented().from(list)
                .include("codigoComposto").serialize();


Q:

How do I stop an Eclipse Editor from closing in an RCP

I am working on an Eclipse based RCP.  We have a need to prevent one of the opened editors from being closed by the user.
The desired behavior is:

the user clicks the X in the editor window or "CTRL+W"
a dialog pops up saying: "If you close this editor, your activity will stop. Do you want to?"
if they click yes, it closes, if no, it stays open.

Oh yeah, and is this even possible?
Thanks,
gk

A:

You could use a org.eclipse.ui.ISaveablePart2, more specifically the method promptToSaveOnClose().
However, as said in this thread,

it will only be shown if the editor is dirty at the time it is closed.

See an example in this SaveableHelper.java source file.
See also the article Prevent that a RCP Editor is closed, which explains how this method works:

A:

You can also cancel the saving in
@Override
public void doSave(IProgressMonitor monitor) {

by calling
monitor.setCanceled(true);

In the EditorPart implementation


Q:

Solve $3619t = 133$ in $\mathbb Z_{4557}$

What I understand:
This question asks to solve for $t$ such that when $(3619 \times t)$ is divided by $4557$ the remainder is $133$
I have found a Bezout identity
$7 = 34 \times 3619 - 27 \times 4557$ and
$1 = 34 \times 517 - 27 \times 651$ and
and I see that  $133 = 7 \times 19$ so
$133 = 646 \times 3619 - 513 \times 4557$
Somehow we are supposed to arrive at $t \equiv 646 \pmod{651}$ and I feel like I've worked out all the bits and pieces but having trouble putting it together

A:

Start it over, on a new, clear page.
So, what we have is that $7$ is the greatest common divisor: $3619=7\cdot 517$, $4557=7\cdot 651$, and $133=7\cdot 19$, so it reduces to
$$517t\equiv 19 \pmod{651}$$
then, I would use $517\equiv -134 \pmod{651}$..


Q:

¿Cómo comparar modelos logit anidados mediante ANOVA en R?

Tengo dos modelos logit binomial:

Modelo A:

modelo_logit_viv <- glm( SAP ~sexo + edad + peso + niv_est + enf_cron +  sit_lab +
                           frec_act_fis   + GHQ_12 + ingreso_eq +
                           n_dormitorios + cont_indus +    delincuencia, # variables de estudio
                         data = datos_modelo, family = binomial(link = "logit"),na.action = "na.omit")

Modelo B (modelo anidado de A):

modelo_logit <- glm(SAP ~ sexo + edad + peso + niv_est + enf_cron  +  sit_lab +
                       frec_act_fis   + ingreso_eq + GHQ_12,
                       data = modelo_logit_viv$model, family = binomial(link = "logit"))

c(edad, peso, ingreso_eq, GHQ_12) Son variables contínuas, el resto son variables categóricas (factor).
Quiero analizar si las características de la vivienda (variables de estudio) tienen influencia en el estado de salud auto-percibido (SAP). Todas las variables son significaivas en ambos modelos. Sin embargo, quiero realizar un análisis de la varianza (ANOVA) entre estos dos modelos para comprobar que el modelo B es mejor que el modelo B. Así que ejecuto:
anova(modelo_logit,modelo_logit_viv)
Y obtengo la siguiente tabla:
  Resid. Df Resid. Dev Df Deviance
1     16805      15439
2     16802      15420  3   18.644

¿Puede la interpretación de esta tabla decirme si hay una influencia entre las características de la vivienda y el estado de salud?
Otra forma de formular esta pregunta es: ¿ Es el 18.644 el estadístico de prueba F que debo comparar con la tabla F de Snedecor para determinar si se acepta o no la hipótesis nula de que existen diferencia de medias entre ambos modelos?
Si no, ¿cómo puedo comparar estos dos modelos con un ANOVA en R?

A:

El término de desviación que vemos al ejecutar anova(modelo_logit,modelo_logit_viv) es la diferencia entre la suma de los errores de la predicción, así que si el modelo_logit perdice mejor que el modelo_logit_viv, la desviación debería disminuir, como es el caso.
Esto sugiere que efectivamente las variables de estudio tienen poder explicativo o alguna asociación con la variable dependiente SAP.
Podemos comprobar esto mediante el test Chi-cuadrado que viene implementado en anova(). Un ejemplo con el dataframe iris:
data = iris
data$Species=ifelse(data$Species=="versicolor",1,0)
full_model = glm(Species ~ .,data=data,family=binomial)
red_model = glm(Species ~ Sepal.Width,data=data,family=binomial)

anova(red_model,full_model,test="Chisq")
Analysis of Deviance Table

Model 1: Species ~ Sepal.Width
Model 2: Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
  Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1       148     151.93
2       145     145.07  3   6.8562  0.07662

Por otra parte, si las variables de estudio incluidas en el modelo son significativas bajo el test de Wald (podemos ver esto ejecutando summary(modelo_logit_viv)) el ratio de verosimilitud debería ser similar, así que de paso calculamos también el pseudo R^2 de McFadden:
modelo_nulo <- glm(SAP~1, family = "binomial",data = datos_modelo)

pseudo_R_viv_signif <- 1 - logLik(modelo_logit_viv)/logLik(modelo_nulo)
pseudo_R_viv_signif  # 0.49

pseudo_R <- 1 - logLik(modelo_logit)/logLik(modelo_nulo) # 0.48
pseudo_R

Vemos que los valores son muy similares c(0.49,0.48) y el test de Chi-cuadrado en mi modelo también es significativo. Podemos concluir entonces que las variables de estudio sí son relevantes a la hora de explicar el estado de salud (SAP)


Q:

Testing After Insert Trigger with Assertion - Is the system slow?

I have an after insert trigger on a custom object which has a lookup relationship to the Opporutnity object.
When I create a new child record, the trigger fires and updates a checkbox on the Opportunity. The trigger works fine, I can test this via the UI and there are no problems.
I have just written a test class for this opportunity which does the following:

Creates an Opp
Asserts that the checkbox field is false
Creates a child record
Asserts that the checkbox field is true

(it does a bit more but this is all that's relevant)
Originally, I created a boolean variable which equalled  Opporutnity.child__c, and then used this in my assertion.
This failed every time.
So instead, I created a List, queried for the field and then used that in my assertion and it passed.
Does anyone know why the original assertion failed? Does this have something to do with it being an after update trigger? Or is the system just slow sometimes?
Thanks in advance
As requested, here is the code:
NOTE: this is working code. My question is why do I have to query for the data each time rather than asserting via the new opp.child__c field? Ideally I wanted to do something like:
system.assert(true, oppname.child__c 'child should be true');
Thanks
Trigger:
trigger updateOppCheckbox on Bonus_Calculator__c (after insert, before delete) {

    if (trigger.isinsert)
    {
    // Create a list of Opps to update
        List<Opportunity> oppList = new List<Opportunity>();
        system.debug('opportunity = '+ oppList);

    // Create a set of related opps
        set <id> ids = new set <id>();
        for (Bonus_Calculator__c newSet : Trigger.new)
        ids.add(newSet.opportunity__c);

    // Add child checkbox to map
        map <id,Opportunity> childMap = new map<id,Opportunity>();
        for (Opportunity o:[select child__c, bonusId__c from opportunity where id in :ids])
        childMap.put(o.id, o);

    // Loop over records and set checkbox to true
        for (Bonus_Calculator__c newBonus : Trigger.new) {

            Opportunity o = childMap.get(newBonus.opportunity__c);
            o.child__c = true;
            o.bonusId__c = newBonus.id;
            oppList.add(o);

2nd half of trigger that deals with 'if trigger is delete' has been removed for presentation purposes.
...Here is the test class
// Create Test records and delete them. Assert that checkbox is updated.

@isTest (SeeAllData=true)
public class updateOppCheckbox_Test2 {

    static testmethod void oppCheckboxTest(){

        // Create Opps from test utilities class
        List<Opportunity> sipOpp = testUtilities.createTestOpps(1);
        Opportunity sipOpp0 = sipOpp.get(0);
        Integer sipOppListSize = sipOpp.size();
        system.assertEquals(1, sipOppListSize,  'sipOpp List size should be 1');

        // Check that Opp Checkbox is not checked before SIP is created
        system.assertEquals(false, sipOpp0.Child__c, 'Child__c should be false');

        // Create the SIP
        bonus_calculator__c bc1 = new bonus_calculator__c(opportunity__c = sipOpp0.Id);
        insert bc1;

        // Query for child field
        List <Opportunity> qOpp = [SELECT Id, child__c from Opportunity where Id = :bc1.Opportunity__c];
        system.debug('qOpp =' + qOpp);
        Opportunity o = qOpp.get(0);
        boolean child = o.Child__c;

        // Assert child__c has been updated via trigger
        system.assertEquals(true, child, 'Child should equal true');

        // Delete Bonus Record
        delete bc1;

        // Query for child field
        List <Opportunity> qOpp2 = [SELECT Id, child__c from Opportunity where Id = :bc1.Opportunity__c];
        system.debug('qOpp2 =' + qOpp2);
        Opportunity o2 = qOpp2.get(0);
        boolean child2 = o2.Child__c;

        // Assert child__c has been updated via trigger
        system.assertEquals(false, child2, 'Child should equal false');

    }
}

A:

Your testmethod is way too verbose. Here is a simplified version
static testmethod void oppCheckboxTest(){

// Create Opps from test utilities class
List<Opportunity> sipOppList = testUtilities.createTestOpps(1);
system.assertEquals(1, sipOppList.size(),  'sipOpp List size should be 1');  // you're verifying your test factory is working, probably unnecessary

// Check that Opp Checkbox is not checked before SIP is created
system.assertEquals(false, sipOppList[0].Child__c, 'Child__c should be false');

// Create the SIP
bonus_calculator__c bc1 = new bonus_calculator__c(opportunity__c = sipOppList[0].Id);
insert bc1;

// Query for child field
List <Opportunity> oppResList = [SELECT Id, child__c from Opportunity where Id = :sipOppList[0].Id];
system.assertEquals(true, oppResList[0].child__c, 'Child should equal true');

delete bc1; // Delete Bonus Record

// Query for child field on parent Oppo
oppoResList = [SELECT Id, child__c from Opportunity where Id = :sipOppList[0].Id];

system.assertEquals(false, oppoResList[0].child__c, 'Child deleted so parent should note absence of children');
}


Q:

Eclipse SVN Commit "fails" after upgrading from Ubuntu 10.04 LTS to 12.04 LTS

while upgrading from Ubuntu 10.04LTS to 12.04LTS, we kept all necessary configurationfiles (svn, trac, apache2) alive. At first all seemed working fine. We could still connect to Trac and SVN using latest version of subclipse 1.8.18, check out and update files, but when it comes to committing changes to SVN, all clients always get the following message:
    RA layer request failed
svn: Commit failed (details follow):
svn: MERGE of '/svn/some/path': 200 OK (http://our.server.ip.here)

The weird thing is, that committing the data is actually working, but eclipse somehow doesn't recognize this, which obviously has to do with the error showed above. I checked several configuration files, compared those with several guides, "how to install svn/trac to ubuntu", but all seems fine. I also tried to Team-Cleanup and Refresh my projects, like suggested in other posts who had the same problem, without success.
Can anyone point me in the right direction concerning this error?

A:

If anyone should ever have the same problem, here how we solved it:
During the upgrade from Ubuntu 10.04 to 12.04 LTS, Ubuntu reinstalled trac Version 0.12, instead of keeping Version 1.xx . This caused our CommitHooks to fail, because trac 0.12 does not support multiple projects.
After reupgrading trac from Version 0.12 to 1.xx, it worked fine again!


Q:

custom knockout binding in object literal

how can i implement multiple custom knockout bindings that can be declared in an object literal?
basically instead of doing this:
 <input data-bind="customBinding1:observable1, customBinding2: observable2 }" />

I would like to be able to do this:
<input data-bind="customBinding0: { customBinding1: observable1, customBinding2: observable2 }" />

thanks in advance.

A:

With Knockout, bindings are specified in name/value pairs, where name is the name of the binding, and value is the value that will be retrieved within the binding using valueAccessor().
It sounds like you may be wanting to pass multiple values in to a binding, like your kendo example shows.  Although each binding can only have a single value, that value can be anything.  This means you can pass in an object literal as the value, and the object can have as many properties as you want.  These properties can also be of any type that you want - you'll just need to handle them correctly inside your binding.
Here's a simple example:
View

Binding
ko.bindingHandlers.myBinding = {
    init: function(element, valueAccessor) {
        var options = valueAccessor() || {};

        //this gives you the value of setting1
        var setting1 = ko.utils.unwrapObservable(options.setting1);

       //if you need to do something just when `setting1` changes,
       //  add a subscription to the value like so:
       if( ko.isObservable(options.setting1) ){
           options.setting1.subscribe(function(newValue){
              //do something because the setting1 value changed
           });
       }
    }
};

You also have the option of specifying multiple bindings, each with its own value, and referencing the additional bindings and values from within the first one.  Knockout's options and optionsText bindings are an example of this approach.
Excellent Resource: http://www.knockmeout.net/2011/07/another-look-at-custom-bindings-for.html
Take some time to study and experiment with the examples at the link above.  There's a lot of good information here that covers what you need to do.


Q:

Shrubs, weeds and raccoons have reclaimed (the) empty neighbourhoods

From The Economist's article on Detroit's doldrums:

Detroit’s population has fallen by 60% since 1950. ... Shrubs, weeds
  and raccoons have reclaimed empty neighbourhoods.

Would it be acceptable to put the definite article before the "empty neighborhoods"?
Both the reader and the writer are aware where exactly these neighborhoods are, from the preceding text. Therefore the noun should have definite reference; hence,

Detroit’s population has fallen by 60% since 1950. ... Shrubs, weeds
  and raccoons have reclaimed the empty neighbourhoods.

If the first quote is more appropriate, why? How would adding THE shift the meaning?

A:

There is a subtle difference between the two. In the original sentence, saying "reclaimed empty neighborhoods" means that some amount of empty neighborhoods has been reclaimed. It doesn't mean that all of them have.
However when you add the to the sentence, you're now referring to the set of all the empty neighborhoods in Detroit. This changes the meaning a bit. It's likely that not all of the neighborhoods have been overtaken by wildlife, hence the author's decision to omit the.

A:

(In this answer, I will reach the same conclusion WendiKidd does, but I will do so in my own way.)
The definite article is a pragmatic signal.  It tells the listener (or reader) to locate the noun it modifies within the conceptual space that is shared with the speaker (or writer).  Detroit has been introduced into the discourse, but particular neighborhoods in Detroit have not; if the definite article were used, then as WendiKidd says, it could only refer to "the neighborhoods of Detroit", that is, all neighborhoods of Detroit.
Without an article, there is no such signal.  Instead, the author speaks of neighborhoods in general, limited by context to the topic of Detroit, giving us the meaning some neighborhoods in Detroit.  Since the meaning differs (some versus all), inserting the definite article is not appropriate.
However, you must not generalize from this that the definite article means all.  It does not.  If the author had previously talked about specific neighborhoods, then these neighborhoods would be within the shared conceptual space, able to be referred to by a definite article.  Nor should you conclude that the definite article must refer to information overtly introduced in the current article or conversation (compare "the President of the United States") or to information familiar to the reader (compare "beware of the dog").  This is why I call it a pragmatic signal; what exactly the reader does with it depends on context, and which article if any is appropriate cannot be determined from syntax alone.
Unfortunately, a complete explanation of definiteness is beyond the scope of this answer.


Q:

Additional Line Spacing Issue on Custom Font

I use a custom font / custom Typeface for a TextView on my app. The TextView displays a paragraph of a text, but with the additional line spacing from the font itself it's rather irritating. So there's like a quite gap between one line with another on the paragraph. Can anybody know how to reduce the spacing through XML or programmatically?

A:

You can use the lineSpacingMultiplier attribute of your TextView to reduce/increase the spacing. Like this:
<TextView
    android:lineSpacingMultiplier="0.6"
    ...
    />


Q:

How to ensure a date is valid?

My code below assigns certain parts of a file name to a variable. What is important here is the variable "yearandmonth" which is a string formatted as "yyyy-mm"
Dim fileparts() As String
            Dim delimiter As String = " - "
            Dim company As String
            Dim type As String
            Dim bank As String
            Dim bankaccount As String
            Dim yearandmonth As String
            Dim fileyear As String
            Dim filemonth As String

            fileparts = Split(localFileName, delimiter)
            company = fileparts(0)
            type = fileparts(1)
            bank = fileparts(2)
            bankaccount = fileparts(3)
            yearandmonth = Left(fileparts(4), 7) ' RESULTS IN A STRING THAT WILL LOOK LIKE "yyyy-mm"
            fileyear = Left(yearandmonth, 4) ' results in "yyyy"
            filemonth = Right(yearandmonth, 2) ' results in "mm"

How can I ensure that the output from "yearandmonth" is a valid year, month and that it contains the "-"?

A:

You can use the DateTime.TryParse Method to validate if the date string is a valid date format as the code below :
Dim dateStrings() As String = {"yyyy-mm"}
Dim dateValue As Date

If DateTime.TryParseExact(mystring, dateStrings, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue) Then
    'Do for Valid Date
Else
    'Do for Invalid Date
End If


Q:

Can I merge/sync a sub-folder from one branch to the root of another in git?

I want to have a /doc folder in master and easily merge/sync it to the root of a gh-pages branch. What is the easiest way to do this?

A:

One nice trick would be to declare the branch gh-branch as a submodule in your master branch (also more detailed in "How to add a git repo as a submodule of itself?").
That way, when you are in your master branch, you see a folder gh-branch which represents the gh-branch content.
You could then:

version doc only in the gh-branch
have a symlink doc in your master branch, linked to gh-branch/doc

That way, you maintain the doc/ content only in one place.

A:

#!/bin/sh

# if there's a docbranch tree and it matches master:doc,
# then get out now, there's nothing to do:

current=`git rev-parse -q --verify docbranch:` \
&& test $current = "`git rev-parse -q --verify master:doc`" \
&& exit 0

# update the docbranch ref to a new commit ...
git update-ref refs/heads/docbranch $(
        # ... which has master:doc, parented on docbranch if that exists yet
        git commit-tree ${current:+-p docbranch} -m "updating" master:doc
)

You can use that as your post-commit hook and chmod +x it, every time you commit anything, if the master doc directory has changed it will commit it to the head of docbranch.
Since the tree's already committed, the only thing this adds is the (~200 byte) commit object itself.


Q:

HTML5 Canvas line draw between two clicks, live

You might see that this is my first post so excuse any beginner mistakes using stackoverflow.
I'm currently working on a floor plan web app where you can simply draw lines to create the floor plan of your housing.
The wanted effect is:
When clicking once the user draws a temporary line where the start point X is the clicked point and the target point Z is the mouse which the user can move around.
I'm currently using canvas for this effect but somehow the line is invisible or just not there. I've tried some debugging which brought me here.
This is the current code:
    function drawLineXY(fromXY, toXY) {
    if(!lineElem) {
        lineElem = document.createElement('canvas');
        lineElem.style.position = "absolute";
        lineElem.style.zIndex = 100;
        document.body.appendChild(lineElem);
        console.log("Added line element");

    }
    var leftpoint, rightpoint;
    if(fromXY.x < toXY.x) {
      leftpoint = fromXY;
      rightpoint = toXY;
    } else {
      leftpoint = toXY;
      rightpoint = fromXY;
    }

    var lineWidthPix = 4;
    var gutterPix = 0;
    var origin = {x:leftpoint.x-gutterPix,
                  y:Math.min(fromXY.y, toXY.y)-gutterPix};
    lineElem.width = "1000px";
    lineElem.height = "1000px";
    lineElem.style.left = "0px";
    lineElem.style.top = "0px";
    var ctx = lineElem.getContext('2d');
    // Use the identity matrix while clearing the canvas
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, lineElem.width, lineElem.height);
    ctx.restore();
    ctx.lineWidth = 4;
    ctx.strokeStyle = '#09f';
    ctx.beginPath();
    ctx.moveTo(fromXY.x - origin.x, fromXY.y - origin.y);
    ctx.lineTo(toXY.x - origin.x, toXY.y - origin.y);
    ctx.stroke();
    console.log("drawing line..");
}

    function moveHandler(evt) {
    var startCentre, startBounds;
    var targets = [];

    if(clicked.length === 2) {
      targets = clicked;
    } else if(clicked.length === 1) {
      targets.push(clicked[0]);
      if(typeof hoverElement !== 'undefined') {
        targets.push(hoverElement);
      }
    }

    if(targets.length == 2) {
        var start = {x:targets[0], y:targets[0]};
        var end = {x:targets[1], y:targets[1]};
        drawLineXY(start, end);

    } else if(targets.length == 1) {
        var start = {x:targets[0], y:targets[0]};

        drawLineXY(start, {x:evt.clientX, y:evt.clientY});
    }
};

    function clickHandler(e) {
    if(clicked.length == 2) {
        clicked = [];
    }
    clicked.push(e.target);
};

document.onclick = clickHandler;
document.onmousemove = moveHandler;

As you can see in drawLineXY's last line I've made a debug console log "drawing line"
This works as I move the mouse around. Like it should.
But there is no line, does someone has help?
PS: #canvas is specified in style.css.

A:

I created a very basic example of probably what you are trying to achieve:

let c, ctx, fromXY, toXY;

window.onload = function(){
  document.onclick = clickHandler;
  document.onmousemove = moveHandler;
  c = document.getElementById("myCanvas");
  ctx = c.getContext("2d");
  reset();
}

function draw(){
  clear();
  ctx.beginPath();
  ctx.moveTo(fromXY.x, fromXY.y);
  ctx.lineTo(toXY.x, toXY.y);
  ctx.stroke();
  ctx.closePath();
}

function clear(){
  ctx.clearRect(0, 0, c.width, c.height);
}

function reset() {
  fromXY = {};
  toXY = {};
}

function moveHandler(e) {
  if(typeof fromXY.x !== "undefined"){
    toXY.x = e.clientX;
    toXY.y = e.clientY;
    draw();
  }
}

function clickHandler(e) {
  if(typeof fromXY.x === "undefined"){
    fromXY.x = e.clientX;
    fromXY.y = e.clientY;
  }else{
    reset();
  }
}
<canvas id="myCanvas" height="500" width="500"></canvas>

You can set line options in the draw() function, and if you want the lines to persist, you would save their fromXY and toXY in an array and redraw them as well.


Q:

Why wasn't Fiona in human form in Shrek: Forever After?

Why wasn't Fiona in human form? Rumpelstiltskin had the contract signed by Shrek costing his existence. Shrek didn't exist, which means that Fiona was always a human (unless at night when the curse took place) when she was imprisoned in the castle. However she is seen as a female warrior ogre in the tribe/clan.
Regarding that:

She escaped herself so she couldn't have a true love to kiss her (so as to become an ogre).
She did not turn human when it was daylight when Rumpelstiltskin was defeated.

A:

I believe that in Shrek: Forever After, Fiona wasn't ever seen during the day.  Shrek spent only a single day in that reality, starting at sunrise.  After the next sunrise, he would disappear.
He didn't encounter Fiona until after dusk, when the curse would transform her into an ogre.
At the end of the movie, he hadn't faded away (and thus the sun hadn't risen) completely before the contract was nullified.  Had the sun fully risen (and thus triggered her change to human) Shrek would have already faded entirely away.
More to the point, Rumplestiltskin, who adheres strictly to the letter of his word, promises to let "all ogres" go free in return for Shrek's surrender.  He specifically does not release Fiona, as she isn't "all ogre".  He points out that she's only half-ogre, being human during the day.
Ergo, the curse was still in place during this movie, and would have been broken at the climax, except that the entire world was invalidated simultaneously.