text:
Q: Future in the past narrative I'm having a little bit of difficulties with the future in the past narrative.

Zoe decided she would sell her downtown apartament, and with the money she would get and the cash she had been saving, she would buy herself a house in the suburbs.

Is everything in the sentence above correct? I feel like there might be too many "she"s and "would"s, but again, I have no idea how I could keep it clear without repeating these words.

A: It's all correct, and flows quite well.
If you're worried by the repeats of 'she would' then you could try 'and with the income from that and the cash she had been saving' - & you could place the end of the sentence earlier, as in:
"Zoe decided she would sell her downtown apartment, and buy herself a house in the suburbs with her savings and the income from that."
I think the perception of repetition comes from looking at it too often; as it is written, it follows Zoes' thought processes quite well. I think the shorter version isn't a whole lot shorter; just different in style.

A: If you said this had been written by a native speaker, I would have believed you.*
Your thinking that you need all those she's and would's in order to be clear is exactly right. Clearly you are using grammar to communicate, by empathizing with the listener's need for grammatical cues in order to understand the sentence. That's excellent.  You've even got nicely contrasting tenses in money she would get and cash she had been saving. It's done so simply—that is, it exploits English grammar so effectively—a reader hardly notices the complexity of what's being described.
Rhythm
The rhythm of the sentence is unusually good. Most native speakers don't write sentences that sound this nice! The line sounds almost like poetry. It strikes a nice balance between repeating and varying its rhythms, and the recurring rhythms are in sync with the grammar. Notice that money and cash both land on accented syllables.  The word herself is unnecessary, but it aids the rhythm—excellent choice.
Some of the other answers suggest ways to shorten the sentence, but I think the repeated use of would contributes a lot to that nice rhythm. It emphasizes the flow of events in Zoë's life. The shorter wordings emphasize the house and the money, and they break up the rhythm.
Here's how I'd tune it up just a tiny bit more. This version adds a that after decided so you get the same rhythm to occur twice at the beginning of the sentence, which fits the rest of the sentence a little better. And it replaces been saving with saved, to make saved better echo the verbs in the other "she"-clauses, and to make the contrast between tenses even stronger. I've marked the phrases with same grammar and rhythm in bold:

Zoë decided that she would sell her downtown apartment, and with the money she would get and the cash she had saved, she would buy herself a house in the suburbs.

Repetition
If you're looking for a generally applicable principle about repetition of grammatical words, it's: repetition is good as long as each repetition varies something from what came before and each repetition brings progress. This is an aesthetic matter, so that's not a strict rule, of course. But one reason the sentence works so well is that each repetition describes a different time, and the repetitions lead straight to a conclusion which comes latest in time as well as last in the sentence.
Seriously, if most of the sentences you write have this excellent parallel flow of rhythm and grammar, you should be writing English professionally.

* Except that apartament should be apartment.

A: Another phrasing would be: Zoe decided she would sell her downtown apartment and, with the money from that and the cash she'd been saving, buy herself a house in the suburbs. The "would" would be understood to apply to the whole rest of the sentence, basically.


text:
Q: Stemming words with NLTK (python) I am new to Python text processing, I am trying to stem word in text document, has around 5000 rows.
I have written below script
from nltk.corpus import stopwords # Import the stop word list
from nltk.stem.snowball import SnowballStemmer

stemmer = SnowballStemmer('english')

def Description_to_words(raw_Description ):
    # 1. Remove HTML
    Description_text = BeautifulSoup(raw_Description).get_text()
    # 2. Remove non-letters
    letters_only = re.sub("[^a-zA-Z]", " ", Description_text)
    # 3. Convert to lower case, split into individual words
    words = letters_only.lower().split()

    stops = set(stopwords.words("english"))
    # 5. Remove stop words
    meaningful_words = [w for w in words if not w in stops]
    # 5. stem words
    words = ([stemmer.stem(w) for w in words])

    # 6. Join the words back into one string separated by space,
    # and return the result.
    return( " ".join( meaningful_words ))

clean_Description = Description_to_words(train["Description"][15])

But when I test results words were not stemmed , can anyone help me to know what is issue , I am doing something wrong in "Description_to_words" function
And, when I execute stem command separately like below it works.
from nltk.tokenize import sent_tokenize, word_tokenize
>>> words = word_tokenize("MOBILE APP - Unable to add reading")
>>>
>>> for w in words:
...     print(stemmer.stem(w))
...
mobil
app
-
unabl
to
add
read

A: Here's each step of your function, fixed.

*

*Remove HTML.
Description_text = BeautifulSoup(raw_Description).get_text()

*Remove non-letters, but don't remove whitespaces just yet. You can also simplify your regex a bit.
letters_only = re.sub("[^\w\s]", " ", Description_text)

*Convert to lower case, split into individual words: I recommend using word_tokenize again, here.
from nltk.tokenize import word_tokenize
words = word_tokenize(letters_only.lower())

*Remove stop words.
stops = set(stopwords.words("english"))
meaningful_words = [w for w in words if not w in stops]

*Stem words. Here is another issue. Stem meaningful_words, not words.
return ' '.join(stemmer.stem(w) for w in meaningful_words])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Auto populate in Excel I would like to auto-populate a list in excel 2013.
For example, the A column would contain ingredients, the B column would contain a name.  The name is associated with the ingredient.  Further to the right on the spreadsheet the column would be titled by the name from B column and the ingredients list would auto-populate beneath that name.
Can someone help me create this?

A: Say you have your spreadsheet set up like this:

You've typed 'Cake' into E1. Then the formula you want in cell E2 is:
=IF(ISERROR(INDEX($A$1:$B$8,SMALL(IF($B$1:$B$8=$E$1,ROW($B$1:$B$8)),ROW(1:1)),2)),"",INDEX($A$1:$B$8,SMALL(IF($B$1:$B$8=$E$1,ROW($B$1:$B$8)),ROW(1:1)),1))

This is an array formula and must be confirmed with CTRL+SHIFT+ENTER. Then it can simply be dragged down (through the yellow section).
Source: http://thinketg.com/how-to-return-multiple-match-values-in-excel-using-index-match-or-vlookup/


text:
Q: Auto back-up VS2005 workspace All too often VS2005 will crash when compiling and I'll have to re-open it. That's all well and good,   a minor inconvenience really. But the annoying part is that it remembers the opened files from the last time I manually closed VS2005 and not the files that were open when it crashed.
Is there some way to back up my current workspace (the open files) so when it crashes and I reload it, it will remember what I had open?

A: Potentially relevant information from techie007's link:

When the solution is saved or closed, the environment calls the
  SavePackageSolutionProps method with a pointer to the SaveUserOptions
  method. An IStream containing the binary information to be saved is
  passed to the WriteUserOptions method, which then writes the
  information to the .suo file and calls the SaveUserOptions method
  again to see if there is another stream of information to write to the
  .suo file.
These two methods, SaveUserOptions and WriteUserOptions, are called
  recursively for each stream of information to be saved to the .suo
  file, passing in the pointer to IVsSolutionPersistence. They are
  called recursively to allow for the writing of multiple streams to the
  .suo file. In that way, user information is persisted with the
  solution and is guaranteed to be there the next time the solution is
  opened.


text:
Q: Redis taking too much time to execute simple commands during concurrent access Background of problem
Hello all , i have made a project in golang gin , and I have integrated the redis Clusterclient in it using "github.com/go-redis/redis/v7"
P.S. Redis that I am using is a redis cluster hosted on AWS
the redis commands that I am using are simply redis.Get and redis.Set only.
Now I have made one API and used caching in it, and when I run it locally, response times are around 200 to 300ms, which is awesome (thanks to Redis)
Main Problem
now when I start doing the load testing on the same API with around 100 concurrent users , response time gets significantly increased ( around 4 seconds). I used spans to monitor the time taken by a different part of the code, and I got this

Getting from primary, getting from secondary are for the redis.Get command
Setting the primary , setting the secondary are for redis.Set
both commands are taking around 1 sec to execute, which is unacceptable,

can anyone please tell me some way, so that I can tackle this problem
and reduce the time for the redis commands to execute

A: Ok so I have solved this somehow.
Firstly I have updated my golang redis client library from go-redis/v7 to go-redis/v8 . And it made a significant improvement. I will advise everyone to do the same.
But still I am suffering from high response time , so the next step for me wa sto change the redis infra. Earlier I was using a redis cluster which only had 1 shard, but now I have moved to another redis having 4 shards..
And it made a huge difference , my response goes from 1200ms to 180ms. Kindly note that these response time are coming when I am doing a load testing with 100 concurrent users with an average of about 130rps
So in short upgrade your redis client , upgrade your redis infra


text:
Q: How to use PersistentQueue in Reactor? I'm trying to configure Reactor to use Chronicle based persistence, and I cannot find by information about this in documentation. I see two ways:

*

*Create my own dispatcher supporting PersistentQueue

*Use EventBatcher with such queue to wrap my Reactor instance

Which option is better? Or maybe there is another solution which I overlooked?

A: Reactor doesn't have persistence built into the Reactor object (which is why you're not finding documentation on it :).
If you're trying to persist the Events coming through for resiliency and replay purposes, you'll probably want to use the EventBatcher. The test for EventBatcher has some code in it that shows how to combine an Observable and a PersistentQueue.
The option of writing your own PersistentDispatcher is certainly an interesting one. That path will be fraught with danger, though, as dispatching code is unforgiving when it comes to throughput. Even the smallest of changes can have drastic impacts on throughput. We've just re-written them as well to get more performance, so the latest code in master is different from the 1.0 release versions of the Dispatchers.
I wouldn't recommend taking the Dispatcher route right away, though. I'd try the EventBatcher first and only if that can't be used in your use case would I experiment with a custom Dispatcher. There are two new abstract base classes (here and here) to base new Dispatcher implementations on if you do decide to go that route.


text:
Q: WebPack bundling breaks CSS We have recently moved from Browserify to WebPack, while it has many nice plugins and optimisations, our (not so clean CSS) started to break.
I tracked the reason to a <style> block somehow inserted into the document.
A screenshot is attached, how to solve this?
Here is our webpack.conf.json
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
var BundleTracker = require('webpack-bundle-tracker');

module.exports = {
    context: __dirname,
    module: {
        loaders: [{
            loader: "babel-loader",
            include: [
                path.resolve(__dirname, "static/js")
            ],
            test: /\.js?$/,
            query: {
                plugins: ['transform-runtime'],
                presets: ['es2015', 'stage-0', 'react']
            }
        }, {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract({
                fallback: 'style-loader',
                use: 'css-loader'
            })
        }, {
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract({
                fallback: 'style-loader',
                use: 'css-loader'
            })
        }, {
            test: /\.(png|jpg|svg)?(\?v=\d+.\d+.\d+)?$/,
            loader: 'url-loader?limit=8192'
        }, {
            test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
            loader: 'url-loader?limit=10000&mimetype=application/font-woff'
        }, {
            test: /\.(ttf|otf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?|(jpg|gif)$/,
            loader: 'file-loader'
        }]
    },
    output: {
        path: path.resolve('./static/bundles/'),
        filename: "bundle.js"
    },
    plugins: [
        new BundleTracker({
            filename: './webpack-stats.json'
        }),
        new ExtractTextPlugin('bundle.css'),
        new OptimizeCssAssetsPlugin(),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            'window.$': 'jquery',
            NProgress: 'nprogress',
            toastr: 'toastr',
            Cookies: 'js-cookie',
            moment: 'moment'
        }),
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            minimize: true,
            compress: true,
            compressor: {
                warnings: true
            }
        })
    ],
    entry: [
        // npm js
        './node_modules/select2/dist/js/select2.full.js',
        './node_modules/jquery-ticker/jquery.ticker.js',
        './node_modules/card/dist/jquery.card.js',
        './node_modules/jquery-ui/ui/widgets/datepicker.js',
        './node_modules/js-cookie/src/js.cookie.js',
        './node_modules/moment-timezone/builds/moment-timezone-with-data.js',
        './node_modules/intl-tel-input/build/js/intlTelInput.js',
        './node_modules/bootstrap-toggle/js/bootstrap-toggle.min.js',
        // loader
        'bootstrap-loader',
        // run package
        './static/run.js',
        // old javascript
        './static/js/profile.js',
        './static/js/main.js',
        './static/js/index_orders.js',
        './static/js/footer.js',
        './static/js/django_jquery_csrf_setup.js'
    ]
};


text:
Q: Recuperar un valor post desde IONIC en PHP Buenas,
Estoy haciendo pruebas con IONIC, e intento hacer una API REST en PHP. Desde la app se envía el valor a través de la llamada siguiente:
     return this.http.post(this.url + '/', body, reqOpts);

El objeto que quiero recuperar es el body, según la consola del navegador:
     console.log(body):
     // respuesta:
     Object { email: "test@example.com", password: "test" }

No sé como recuperar el objeto, y he intentado:
        header('Access-Control-Allow-Origin: *');
        $header = $_SERVER['HTTP_ORIGIN']; // Esto devuelve correctamente Header: http://localhost:8100
        $password = filter_var($_REQUEST['password'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
        $input = json_decode(file_get_contents('php://input'),true);

Tanto $password como $input están vacíos, ni siquiera contienen arrays. Cómo puedo recuperar estos valores?
Gracias de antemano.

A: Bueno no se si estas utilizando algun framework con php  yo te recomendaria SLIM
esta es la manera que envio el post

$app->post('/api/cliente', function($request) {
  $data = $request->getParsedBody();

try {

  if(isset($data['clienteid']) && isset($data['cliente'])){
    $codigo= $data['clienteid'];
    $nombre = $data['cliente'];
    $contacto= $data['contacto'];
    $telefono= $data['telefono'];
    $identidad= $data['identidad'];
    $diavisita= $data['diavisita'];
    $ciudad= $data['ciudad'];
    $barrio= $data['barrio'];
    $referencia= $data['referencia'];
    $rutaid= $data['rutaid'];
    $sucursalid= $data['sucursalid'];
    $estado= $data['estado'];
    $longitud= $data['longitud'];
    $latitud= $data['latitud'];
    $celular= $data['celular'];
    $usuariid = $data['usuarioid'];
    $bloque = $data['bloque'];
    $calle = $data['calle'];
    $casa = $data['casa'];

    $sql = "
            insert into mobile_app_cliente
            (codigo,nombre,contacto,telefono,identidad,diavisita,ciudad,barrio,referencia,rutaid,sucursalid,estado,longitud,latitud,celular,usuarioid,bloque,calle,casa)
            values('$codigo','$nombre','$contacto','$telefono','$identidad','$diavisita','$ciudad','$barrio','$referencia','$rutaid','$sucursalid','$estado','$longitud','$latitud','$celular','$usuariid','$bloque','$calle','$casa')
    ";

  //  print_r($sql);
    $db= new db();
    $db = $db->connect();
    $stmt = $db->query($sql);
      $db = null;

  }else {
     echo '{"error":{"text":"Bad Request"}}';
  }

} catch (PDOException $e) {
     echo '{"error":{"text":'.$e->getMessage().'}}';
}

});


text:
Q: Android Studio Gradle sync failed :- Not a directory I am getting this weird error when I try to setup Android Studio 2.2 on Fedora 25. For what it's worth, I have oracle-java. I installed it using the rpm package found on their official website. The contents from the log file is given below :-
org.gradle.tooling.GradleConnectionException: Could not create an instance of Tooling API implementation using the specified Gradle installation '/home/nilesh/android-studio/gradle/gradle-2.10'.
    at org.gradle.tooling.internal.consumer.loader.DefaultToolingImplementationLoader.create(DefaultToolingImplementationLoader.java:92)
    at org.gradle.tooling.internal.consumer.loader.CachingToolingImplementationLoader.create(CachingToolingImplementationLoader.java:43)
    at org.gradle.tooling.internal.consumer.loader.SynchronizedToolingImplementationLoader.create(SynchronizedToolingImplementationLoader.java:42)
    at org.gradle.tooling.internal.consumer.connection.LazyConsumerActionExecutor.onStartAction(LazyConsumerActionExecutor.java:99)
    at org.gradle.tooling.internal.consumer.connection.LazyConsumerActionExecutor.run(LazyConsumerActionExecutor.java:82)
    at org.gradle.tooling.internal.consumer.connection.ProgressLoggingConsumerActionExecutor.run(ProgressLoggingConsumerActionExecutor.java:58)
    at org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor$1$1.run(DefaultAsyncConsumerActionExecutor.java:55)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.gradle.tooling.internal.consumer.BlockingResultHandler.getResult(BlockingResultHandler.java:46)
    at org.gradle.tooling.internal.consumer.DefaultModelBuilder.get(DefaultModelBuilder.java:49)
    at org.gradle.tooling.internal.consumer.DefaultProjectConnection.getModel(DefaultProjectConnection.java:35)
    at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.getBuildEnvironment(GradleExecutionHelper.java:481)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.doResolveProjectInfo(GradleProjectResolver.java:160)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.access$300(GradleProjectResolver.java:65)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:367)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:339)
    at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.execute(GradleExecutionHelper.java:230)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:97)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:65)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:41)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:49)
    at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:51)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:138)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:124)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3.execute(ExternalSystemUtil.java:419)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$4$2.run(ExternalSystemUtil.java:500)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:563)
    at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:142)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:446)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:392)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:127)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:126)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:366)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:55)
Caused by: net.rubygrapefruit.platform.NativeException: Failed to load native library 'libnative-platform.so' for Linux amd64.
    at net.rubygrapefruit.platform.internal.NativeLibraryLoader.load(NativeLibraryLoader.java:49)
    at net.rubygrapefruit.platform.Native.init(Native.java:55)
    at org.gradle.internal.nativeintegration.services.NativeServices.initialize(NativeServices.java:74)
    at org.gradle.internal.nativeintegration.services.NativeServices.initialize(NativeServices.java:60)
    at org.gradle.tooling.internal.provider.DefaultConnection.initializeServices(DefaultConnection.java:75)
    at org.gradle.tooling.internal.provider.DefaultConnection.configure(DefaultConnection.java:70)
    at org.gradle.tooling.internal.consumer.connection.AbstractPost12ConsumerConnection.configure(AbstractPost12ConsumerConnection.java:37)
    at org.gradle.tooling.internal.consumer.loader.DefaultToolingImplementationLoader.create(DefaultToolingImplementationLoader.java:84)
    at org.gradle.tooling.internal.consumer.loader.CachingToolingImplementationLoader.create(CachingToolingImplementationLoader.java:43)
    at org.gradle.tooling.internal.consumer.loader.SynchronizedToolingImplementationLoader.create(SynchronizedToolingImplementationLoader.java:42)
    at org.gradle.tooling.internal.consumer.connection.LazyConsumerActionExecutor.onStartAction(LazyConsumerActionExecutor.java:99)
    at org.gradle.tooling.internal.consumer.connection.LazyConsumerActionExecutor.run(LazyConsumerActionExecutor.java:82)
    at org.gradle.tooling.internal.consumer.connection.ProgressLoggingConsumerActionExecutor.run(ProgressLoggingConsumerActionExecutor.java:58)
    at org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor$1$1.run(DefaultAsyncConsumerActionExecutor.java:55)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Not a directory
    at java.io.UnixFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:1012)
    at net.rubygrapefruit.platform.internal.NativeLibraryLocator.find(NativeLibraryLocator.java:39)
    at net.rubygrapefruit.platform.internal.NativeLibraryLoader.load(NativeLibraryLoader.java:41)
    ... 18 more

Thanks in advance.

A: Delete everything in /Library/Java/Extensions


text:
Q: Saving a .tar.gz file located on server to a FILE object I'm currently working on a Python Flask API.
For demo purposes, I have a folder in the server containing .tar.gz files.
Basically I'm wondering how do I save these files knowing their relative path name, say like file.tar.gz, into a FILE object. I need the tar file in the format to be able to run the following code on it, where f would be the tar file:
 tar = tarfile.open(mode="r:gz", fileobj=f)
 for member in tar.getnames():
    tf = tar.extractfile(member)

Thanks in advance!

A: Not ver familiar with this but , just saving it normally with .tar.gz extension should work? if yes and if you have the file already compressed then a very simple code could do that,
compresseddata= 'your file'
with open('file.tar.gz') as fo:
    fo.write(compressed data)
    fo.flush().close()

Will this do the job , or am i getting something wrong here?


text:
Q: Sun PKCS#11 Wrapper how to debug CKR_TEMPLATE_INCONSISTENT Is there any way how to debug what is causing Sun PKCS#11 wrapper exception?:
sun.security.pkcs11.wrapper.PKCS11Exception: CKR_TEMPLATE_INCONSISTENT

I would like to know which attribute of PKCS#11 object is inconsistent and fix it.

A: It is quite tricky to find exactly what attribute is missing or provided incorrectly. The only way you could fix this is by trial and error. Since this exception is thrown by the token, it wouldn't be logged, which makes it much difficult to solve.
I would recommend first to better understand what type of token you are dealing with. This will give you a better idea of what type of object template it would expect.
For example, if the token only allows you to create sensitive keys, if you set the attribute value as false, the token would complain. So you have to try a combination of attributes and see if it succeeds in creating the object.
Another thing you could do is, if, the token comes with its own sdk or tools, that can interact with the token and create objects, create a test object using their sdk/tool, and then use the PKCS#11 interface to extract the object and see what template it has. You could use this as a base template.
If it doesn't you can try to create an object starting with a minimal template, with required values, like:

*

*Id (some random value)

*Label (alias name)

*Token (true recommended)

*Sensitive (true recommended)

*Algorithm/Mechanism (CKM_RSA_PKCS_KEY_PAIR_GEN / CKM_AES_KEY_GEN)

*Key Type (CKK_RSA / CKK_AES)

*Value Length (optional)

*Class (optional)

A: You can use a pkcs11 logging wrapper.
For instance: https://github.com/Pkcs11Interop/pkcs11-logger
You'll need some environment variables:

*

*PKCS11_LOGGER_LIBRARY_PATH -> path to the real pkcs11 library

*PKCS11_LOGGER_LOG_FILE_PATH -> path to the log file

*PKCS11_LOGGER_FLAGS -> flags (take a look at pkcs11-logger README.md

file)

A: I was doing some experiments with PKCS11 lib on C# and as far as I know, it's the same for Java or even JavaScript so...
When I tried to craft a "RSA key pair" I got a problem when declaring:

*

*CKA.CKA_CLASS, CKO.CKO_SECRET_KEY

Also when working with AES keys I got issues when I tried to create it with "Value_length" different from 32


text:
Q: Send form context through an html file by mail I want to send the context of my form rendering an HTML template, which I send by mail, but it sends me on behalf of the fields. Not the data that is entered in the fields.
I've tried several tags in the html file like: {{form.name_field}}. But it doesn't show the information
my funtion or views.py
def solit(request):
"""Gestion de solicitudes"""
if request.method == 'POST':
    form = SolitForm(request.POST)
    if form.is_valid():
        form.save()
        subject = 'Bienvenido {}'.format(request.user)
        from_email = 'xxxxxn@xxxx.com'
        html_content = render_to_string('plantillas/mailsended.html', {'form':form,'user':request.user})
        text_content = strip_tags(html_content)
        msg = EmailMultiAlternatives(subject, text_content, from_email, ['xxxxxxxx@xxxxx.com'])
        msg.attach_alternative(html_content, 'plantillas/mailsended.html')
        msg.send()
        print (form)
    return redirect ('home')
else:
    form = SolitForm()
return render(request, 'plantillas/testform.html', {'form':form})

my forms.py

class SolitForm(forms.ModelForm):
class Meta:
    """Formulario de solicitud"""

    model = peticion

    fields = [

        'disponer',
        'razon2',
        'periodo_init',
        'periodo_fin',
        'horas_r',
        'dias_r',

    ]

    labels = {

        'disponer':'Tipo de Solicitud',
        'razon2':'Razon',
        'periodo_init':'Rango de fecha inicial',
        'periodo_fin':'Fecha final',
        'horas_r':'Dias a adicionar, si es mas de 8 horas',
        'dias_r':'Horas a adiciona, si es menos de 1 dia',

    }

my models

class peticion(models.Model): #Modelo para (solicitar vacaciones y reportar tiempo)
peticion_choice = (
    ('Reportar', 'Reportar Tiempo'),
    ('Vacaciones', 'Vacaciones')
)

disponer = models.CharField(max_length=255, choices=peticion_choice, null=True, blank=False)
usuario = models.ForeignKey(users, on_delete=models.CASCADE, null=True, blank=True)
razon2 = models.TextField(max_length=255, null=True, blank=False)
periodo_init = models.DateField(max_length= 255, null=True, blank= False)
periodo_fin = models.DateField(max_length=255, null=True, blank=False)
created_day = models.DateTimeField(auto_now_add=True)
horas_r = models.IntegerField(null=True, blank=False)
dias_r = models.FloatField(null=True, blank=False)

and this is my html file
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

Nombre {{ user.nombre }} Apellido {{ user.apellido }}

     {{ form }}

I can send the context of the user logged into the application in that html file, but the context of the data sent in the fields not at the moment, how is it done?

A: Since your form saves an object (an instance of peticion) why don't you pass {'peticion': form.instance} to your context and then use that to print the various fields you need, e.g. {{ peticion.disponer }}. You should not pass a Form for printing the values.
Alternatively you can pass {'peticion': form.cleaned_data} which will pass the form's cleaned_data dictionary to the context.


text:
Q: Performance of using a large number of small VBOs I wanted to know whether OpenGL VBOs are meant to be used only for large geometry arrays, or whether it makes sense to use them even for small arrays.  I have code that positions a variety of geometry relative to other geometry, but some of the "leaf" geometry objects are quite small, 10x10 quad spheres and the like (200 triangles apiece).  I may have a very large number of these small leaf objects. I want to be able to have a different transform matrix for each of these small leaf objects. It seems I have 2 options:

*

*Use a separate VBO for each leaf object. I may end up with a large number of VBOs.

*I could store data for multiple objects in one VBO, and apply the appropriate transforms myself when changing the data for a given leaf object. This seems strange because part of the point of OpenGL is to efficiently do large numbers of matrix ops in hardware. I would be doing in software something OpenGL is designed to do very well in hardware.
Is having a large number of VBOs inefficient, or should I just go ahead and choose option 1?  Are there any better ways to deal with the situation of having lots of small objects?  Should I instead be using vertex arrays or anything like that?

A: The most optimal solution if your data is static and consists of one object would be to use display lists and one VBO for only one mesh. Otherwise the general rule is that you want to avoid doing anything other than rendering in the main draw loop.

*

*If you'll never need to add or remove an object after initialization (or morph any object) then it's probably more efficient to bind a single buffer permanently and change the stride/offset values to render different objects.

*If you've only got a base set of geometry that will remain static, use a single VBO for that and separate VBOs for the geometry that can be added/removed/morphed.

*If you can drop objects in or remove objects at will, each object should have it's own VBO to make memory management much simpler.

A: some good info is located at: http://www.opengl.org/wiki/Vertex_Specification_Best_Practices
I think that 200 triangles per one mesh is not so small number and maybe the performance with VBO for each of that meshes will not decrease so much. Unfortunately it is depended on hardware spec.
One huge buffer will no gain huge performance difference... I think that the best option would be to store several (but not all) objects per one VBO.
renderin using one buffer:
there is no problem with that... you simply have one buffer that is bound and then you can use glDrawArrays with different parameters. For instance if one mesh consists of 100 verts, and in th buffer you have 10 of those meshes you can use
glDrawArrays(triangles, 0, 100);
glDrawArrays(triangles, 100, 100);
glDrawArrays(triangles, ..., 100);
glDrawArrays(triangles, 900, 100);

in that way you minimize changing buffers and still you are able to render it quite efficient.
Are those "small" objects the same? do they have the same geometry but different transformations/materials? Because maybe it is worth using "instancing"?


text:
Q: Google Maps Engine API - KML Layers Obstructing New Markers Event I am currently building out a small widget that allows someone to see a kml heat map of the united states population density then select an area on that map and drop a market on to that location. The user then enters a number and that creates a mile radius to show the user how much area they cover.
My problem is that I have 63 .kml files for just one state in the US. I know I can remove the xml <name> and <description> to prevent the name from popping up when clicked, but I can't see that being practical with that many .kml files.
Is there a programmatic solution or API solution to prevent just the kml layers from being clickable?

   var citymap = {};

   citymap['chicago'] = {
     center: new google.maps.LatLng(41.878113, -87.629798),
     value: 2714856
   };
   citymap['newyork'] = {
     center: new google.maps.LatLng(40.714352, -74.005973),
     value: 8405837
   };
   citymap['losangeles'] = {
     center: new google.maps.LatLng(34.052234, -118.243684),
     value: 3857799
   };
   citymap['vancouver'] = {
     center: new google.maps.LatLng(49.25, -123.1),
     value: 603502
   };

   var cityCircle;

   function initialize() {
     // Create the map.
     var mapOptions = {
       zoom: 8,
       center: new google.maps.LatLng(34.7361, -92.3311),
       mapTypeId: google.maps.MapTypeId.TERRAIN
     };

     var map = new google.maps.Map(document.getElementById('map-canvas'),
       mapOptions);

     // Construct the circle for each value in citymap.
     // Note: We scale the area of the circle based on the population.
     for (var city in citymap) {
       var populationOptions = {
         strokeColor: '#FF0000',
         strokeOpacity: 0.8,
         strokeWeight: 2,
         fillColor: '#FF0000',
         fillOpacity: 0.35,
         map: map,
         center: citymap[city].center,
         radius: Math.sqrt(citymap[city].value) * 100
       };
       // Add the circle for this city to the map.
       cityCircle = new google.maps.Circle(populationOptions);
     }

     var ctaLayer = new google.maps.KmlLayer({
       url: 'http://www.census.gov/main/kml/countysubs_z6/AR/05003.xml'
     });
     ctaLayer.setMap(map);

     google.maps.event.addListener(map, 'click', function(e) {
       placeMarker(e.latLng, map);
     });
   }

   function placeMarker(position, map) {
     var marker = new google.maps.Marker({
       position: position,
       map: map
     });
     map.panTo(position);
   }

   google.maps.event.addDomListener(window, 'load', initialize);
      html,
      body,
      #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }

Discretionary note: Google API does not work well with Stack Overflow's code snippet's widget.

A: set the KmlLayer clickable option to false

clickable boolean If true, the layer receives mouse events. Default value is true.

var citymap = {};

   citymap['chicago'] = {
     center: new google.maps.LatLng(41.878113, -87.629798),
     value: 2714856
   };
   citymap['newyork'] = {
     center: new google.maps.LatLng(40.714352, -74.005973),
     value: 8405837
   };
   citymap['losangeles'] = {
     center: new google.maps.LatLng(34.052234, -118.243684),
     value: 3857799
   };
   citymap['vancouver'] = {
     center: new google.maps.LatLng(49.25, -123.1),
     value: 603502
   };

   var cityCircle;

   function initialize() {
     // Create the map.
     var mapOptions = {
       zoom: 8,
       center: new google.maps.LatLng(34.7361, -92.3311),
       mapTypeId: google.maps.MapTypeId.TERRAIN
     };

     var map = new google.maps.Map(document.getElementById('map-canvas'),
       mapOptions);

     // Construct the circle for each value in citymap.
     // Note: We scale the area of the circle based on the population.
     for (var city in citymap) {
       var populationOptions = {
         strokeColor: '#FF0000',
         strokeOpacity: 0.8,
         strokeWeight: 2,
         fillColor: '#FF0000',
         fillOpacity: 0.35,
         map: map,
         center: citymap[city].center,
         radius: Math.sqrt(citymap[city].value) * 100
       };
       // Add the circle for this city to the map.
       cityCircle = new google.maps.Circle(populationOptions);
     }

     var ctaLayer = new google.maps.KmlLayer({
       url: 'http://www.census.gov/main/kml/countysubs_z6/AR/05003.xml',
       clickable: false
     });
     ctaLayer.setMap(map);

     google.maps.event.addListener(map, 'click', function(e) {
       placeMarker(e.latLng, map);
     });
   }

   function placeMarker(position, map) {
     var marker = new google.maps.Marker({
       position: position,
       map: map
     });
     map.panTo(position);
   }

   google.maps.event.addDomListener(window, 'load', initialize);
html,
      body,
      #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }


text:
Q: How to stop allowing of special characters on keypress of input I have below input
handleNameChange(event = {}) {
        console.log('event', event);
        this.setState({ reportCalculationName: event.target.value });
    }

onKeyPress(event) {
    let character = event.keyCode;
    console.log('character', character);
}

   Calculation Name:
    <input type="text" className="" id="calculation-name" title="Name"
          onChange={this.handleNameChange}
           value=this.state.reportCalculationName } onKeypress={this.onKeyPress}/>

Keypress event is not even firing when I enter some special charcaters.I want to stop allowing  `,."'|/+=]   these characters in my input field in my react component

A: You can use event.preventDefault() to cancel the keypress event.
PseudoCode:
onKeyPress(event) {
    var key = window.event ? event.keyCode : event.which;
    if (key === [enter your value here]) {
        event.preventDefault(); <=== this will cancel the input
    } else {
       return true;
    }
    console.log('character', character);
    return false;
}

You can find more information here:
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault


text:
Q: How many admirals are in Starfleet? Let's say in the TNG era.
They seem to be pretty rare given that they have to be promoted mostly from the ranks of the most accomplished captains.    I would guess maybe twenty are encountered or mentioned over the course of TNG.
Are there a dozen or a hundred?

A: There is no canon or extended universe source that states unequivocally  the total number of admirals in Starfleet.  However, if we assume that each branch of Starfleet is administered by at least one admiral (of some rank), then we can easily arrive at a lower bound:
Here are the branches of Starfleet, according to Memory Alpha:

*

*Academy

*Administration

*Administrative Operations

*Advanced Technologies

*Applied Sciences Division

*Command

*Communications

*Control

*Daystrom Institute

*Dental (yes, really; Starfleet Dental is shown on Admiral Layton's display in DS9 : "Paradise Lost")

*Diplomatic Corps

*Engineering (including Engineering Corps)

*Exploration (including Deep Space Exploration)

*Fleet Supply and Inventory

*Information

*Office of the Inspector General

*Intelligence

*Internal Affairs

*Office of the Judge Advocate General

*Material Supply Authority

*Medical

*Mission Operations

*Office of Special Planning

*Operations

*Operational Support

*Orbital Operations

*Operational Safety and Health Command

*Planetary Geosciences

*Research and Development (General)

*Research and Development (Propulsion)

*Research and Development (Spaceframes)

*Science

*Section 31 (separate from Intelligence)

*Security

*Shipyards Operations

*Stellar Cartography

*Stellar Imaging

*Systems Management

*Tactical

*Tactical Analysis (separate from Tactical, apparently)

*Terrestrial Defense

*Training Command

This makes for at least 42 admirals of various ranks.  (We can assume that the Commander-in-Chief of Starfleet is the admiral who is the Branch Head of Starfleet Command.)
In any case, counting admirals by counting Starfleet branches would not include those admirals who are away on diplomatic or ambassadorial assignments, nor would it include admirals who are not Branch Heads but who serve on branch committees. Starfleet Tactical likely has a large committee of admirals who discuss short-term and long-term fleet strategy.  There may also be several admirals serving as instructors at Starfleet Academy.
So the best we can say is at least 42 admirals, but probably many more.

A: In the TNG episode "Phantasms" Picard sadly tells Riker (emphasis added):

I've been invited to the annual Starfleet Admirals' banquet. I've managed to avoid it for the past six years, but now it would seem my luck has run out. I can't think of anything more tedious. Fifty admirals shaking hands, making dull conversation, uninteresting food, boring speeches.

So we know there are at least 50 in Starfleet.

A: Praxis has listed the Starfleet Branches that should have admirals in command.
Note that Dr. Crusher was chief of Starfleet Medical during the second season and thus should probably have been a temporary admiral during that period.  Some people wonder when she took the bridge officers' test but she probably took the flag officers' test.
It is common for line admirals to be in command of fleets or the areas of sea they operate in.  In a space navy there may be both territorial (or in space volume) commands and fleet commands.
In an interstellar realm an admiral in command of a volume of space may be in charge of all the fleet defense units int a single solar systems, or in ten inhabited solar systems plus all the uninhabited solar systems beteen them, or some other number of solar systems.
Suppose that in one space navy a one star admiral is in command of 100 solar systems; a 2 star admiral commands all fleet units in 1,000 solar systems and has 10 one star admirals under him; a three star admiral commands all fleet units in 10,000 solar systems and has 10 two star admirals under him; a four star admiral commands all fleet units in 100,000 solar systems and has 10 three star admirals under him; a five star admiral commands all fleet units in 1,000,000 solar systems and has 10 four star admirals under him; and so on.
How far can it go?  In our galaxy a galactic empire ruling all the galaxy would rule at least 100,000,000,000 solar systems and the ranks would go up to at least ten star admiral.
What about admirals commanding fleets?
In the great sea battle of Jutland in 1916 between the British Grand Fleet under Admiral Jellico and the German High Seas Fleet under Vice Admiral Scheer there were 249 warships engaged, including 28 British battleships and 22 German Battleships.
Jellico had a vice admiral as second in command and a vice admiral as chief of staff and 13 vice admirals and rear admirals commanding various units.
Scheer had 8 vice admirals and rear admirals commanding various units.
in both fleets the battleships were grouped into battle squadrons that had two divisions each, with three or usually four battleships in a division.  Each division was commanded by an admiral with each squadron commanded by one of the admirals commanding a division.
So if a space fleet has a 1 star admiral commanded every five to ten space battleships, it might have a 2 star admiral commanding two such groups or ten to twenty ships in all, a 3 star admiral commanding two 2 star admirals and twenty to forty ships in all, a 4 star admiral commanding two  3 star admirals and forty to eight space battleships in all, a five star admiral commanding two 4 star admirals and eighty to one hundred sixty space battleships in all, a six star admiral commanding two 5 star admirals and one hundred sixty to three hundred twenty space battleships in all.
But in the DS9 episode "Sacrifice of Angels"  a fleet of 600 ships is commanded by Captain Sisko!  What?
In the Lensman series by E.E. Smith there are battles with fleets of millions of space battleships. Imagine how many different ranks of admirals there would have to be to command in such battles.
Since the federation occupies a volume containing hundreds of thousands to hundreds of millions of solar systems, and Starfleet has at least thousands of space warhips during the Dominion war, if Starfleet is logical it could have vast numbers of line admirals in far more ranks than the shows creators ever imagined.


text:
Q: Powershell script for listing specific expiring accounts I am a bit of a powershell novice so any help is greatly appreciated. I am using the following script to get and export a list of AD accounts that are expiring, that match the specific description item. I have not been able to get it to successfully include the expiration date. This is the script as it currently works.
   $users = Get-QADUser -SizeLimit 10000 -SearchRoot 'company.com/employees' -IncludedProperties "description" | where {$_.description -like "non-company*" }
@(foreach($user in $users)
{
$user | Select-Object DisplayName,LogonName,description

}) |  export-Csv "C:\Users\svcacct\Documents\Steve Test Scripts\test.csv" -noType

I have tried adding -filter {Enabled -eq $True -and PasswordNeverExpires -eq  $False} but it just fails.
Thanks for your help.

A: You can try this:
Import-Module ActiveDirectory
$users = Get-ADUser -Filter {(Enabled -eq $True -and PasswordNeverExpires -eq $False) -and (Description -like "non-company*")} -SearchBase "OU=employees,DC=Company,DC=com" -Properties Description,DisplayName,sAMAccountName

@(ForEach($user In $users){
    $user | Select-Object DisplayName,sAMAccountName,Description
}) | Export-Csv "C:\Users\svcacct\Documents\Steve Test Scripts\test.csv" -noType


text:
Q: Writing Test Coverage for Else I am struggling with covering this if-else conditional.
public void pullIDAnalyticsReportAPEX() {
    crsUpdate();
    generateJSON();
}
public String generateJSON() {
    currentPgId = ApexPages.currentPage().getParameters().get('id');
    serializedData = new List<Contact>();
    credRevId = new List<Credit_Review__c>();
    homeAddress1 = new List<FPC_Address__c>();
    guarantorId1 = [SELECT PG1__c FROM Credit_Review__c WHERE Id = :currentPgId].PG1__c;

    if (guarantorID1 == NULL) {
        String nulLReturn = 'Null Data';
        return nullReturn;
    }
    else {
        credRevId = [SELECT Id FROM Credit_Review__c WHERE Id = :currentPgId];
        serializedData = [SELECT Id, FirstName, LastName, Birthdate, SSN_Encrypted__c, SSN__c, MailingAddress, HomePhone, MobilePhone, Email FROM Contact WHERE Id = :guarantorId1];
        homeAddress1 = [SELECT Address_1__c, City__c, State__c, Zip_Code__c FROM FPC_Address__c WHERE Location_Type__c = 'Home Address' AND Contact__r.Id = :guarantorId1 ORDER BY CreatedDate DESC LIMIT 1];

        jk = new AccountWrapper(serializedData[0], credRevId[0], homeAddress1[0]);
        NewJSONString = JSON.serialize(jk);
        return NewJSONString;
    }
}

I am able to get through the if statement but not the else part. I have tried defining guarantorID1 with a hard coded value, queried for the ID, pulled it from a test contact, system.aserts, and other variations of these. In my test class I created an account, an opportunity, a credit review, a contact and tied all of these together. It is to my understanding that when you create a test-contact, it will be assigned an ID. I don't understand why I can't assign the contact ID as the PG1__c ID like so:
@isTest
static testmethod void firstTestAccount(){
    //no PG1__c ID
    Account a = new Account(Name = 'Test Account');
    insert a;
    Opportunity o = new Opportunity(AccountId = a.Id, Name = 'IDAnalyticsName', CloseDate = Date.today(), StageName = 'Prospecting');
    insert o;
    Contact c = new Contact(FirstName = 'FirstTest', LastName='LastTest', SSN_Encrypted__c ='000000000', HomePhone='7894561333', MobilePhone='9885556666', Email='test@test123.com', AccountId = a.Id);
    insert c;
    system.debug('this is the contact ID:' + c.Id);
    Credit_Review__c cr = new Credit_Review__c(Account__c = a.Id, Opportunity__c = o.Id); //**NOTE- THERE IS NO PG1__C IN HERE this is how I am able to get through the first part of the conditional**
    insert cr;
    system.debug('this is cr.id' + cr.Id);
    Consumer_Risk_Summary__c crs = new Consumer_Risk_Summary__c(Error_Message__c = 'ID Analytics encountered an error while processing the request.', Credit_Review__c = cr.Id);
    insert crs;
    system.debug('this is crs credit review' + crs.Credit_Review__c);

    //PG1__c ID is available
    Account a2 = new Account(Name = 'Test Account 123');
    insert a2;
    Opportunity o2 = new Opportunity(AccountId = a2.Id, Name = 'IDAnalyticsName22', CloseDate = Date.today(), StageName = 'Prospecting');
    insert o2;
    Contact c2 = new Contact(FirstName = 'FirstTest22', LastName='LastTest22', SSN_Encrypted__c ='000000000', HomePhone='7894561333', MobilePhone='9885556666', Email='test@test123.com', AccountId = a2.Id);
    insert c2;
    system.debug('this is the contact ID:' + c.Id);
    Credit_Review__c cr2 = new Credit_Review__c(Account__c = a.Id, Opportunity__c = o.Id, PG1__c = c2.Id); //**NOTE THERE IS A PG1__C IN THIS CREDIT REVIEW which should allow me to enter into the second half of the if/else**
    insert cr2;
    system.debug('this is cr.id2' + cr2.Id);
    Id guarantorId1 = [SELECT PG1__c FROM Credit_Review__c WHERE Id = :cr2.Id].PG1__c;
    system.assertNotEquals(null, guarantorId1);
    Consumer_Risk_Summary__c crs2 = new Consumer_Risk_Summary__c(Credit_Review__c = cr2.Id);
    insert crs2;
    system.debug('this is crs credit review' + crs2.Credit_Review__c);
}

A: None of the data you set matters during the test when you are basing the query:
guarantorId1 = [SELECT PG1__c FROM Credit_Review__c WHERE Id = :currentPgId].PG1__c;

On the currentPgId
currentPgId = ApexPages.currentPage().getParameters().get('id');

in fact, I do not understand how the query is not throwing an error (List has no rows for assignment to SObject) as currentPgId is null and you are attempting to pull a field from it
To set the value according to the code you have posted you need to set the Id URL parameter for the current page reference
PageReference pr = Page.[YOURPAGENAME];
pr.getParameters().put('id', guarantorId1);
test.setCurrentPage(pr);

Then when your test executes it will have the appropriate parameters set and get the correct record and enter the else


text:
Q: Level of a water tank with a microcontroller How do i measure the level of a water tank with a microcontroller?

A: One way of doing this is to place an led at the bottom of the tank pointing to the top, and a photodiode at the top of the tank, facing the LED. The LED will be attenuated by the water in the tank, you'll need to experiment to determine how much. Also, it's best to take a series of rapid measurements and average them when using this method.

A: I use a cheap stud sensor from the local hardware store with a photo transistor to sense the indicator led.  With this glued to the side of the tank it senses when the level rises above the sensor and alerts us to a high water condition.

A: There are a surprising number of ways to check for level.  There are sensors that use RF, sending a pulse down a waveguide and detecting the reflection off the surface of the liquid in the tank.  There's ultrasound, floats, bubbler tubes, pressure taps...  The method used depends on the size of the tank, the contents, ambient environment and other factors.

A: I'm surprised at all the complicated electronic solutions here, I would use a simple potentiometer. Most micro controllers have a basic analog i/p.
 +V
-----
  |
  |
  /
  \
  /<----------> to analog i/p
  \
  |
  |
-----
 GND

Use a standard water tank valve float (there may already be one). The remaining problem is coupling the float to the pot to get maximum swing (you could also use a slider pot).
                  |-|
                  | |
                  |o| <--------Slider pot.
                  |||
                  |||
                   |
                   |  <--------Coupling.
                   |
   ____            |
  (float)----------o-----o  <--Anchor point of float.
   ----

A: Simplest approach
Place a small tube in a corner of the tank that is slightly larger in diameter than a ping pong ball.
Place an infrared LED on one side of the tube and a photoresistor opposite of the LED (by drilling a hole in the tube of it's opaque or placing on the outside if its transparent). Hot glue the electrical parts to waterproof them and drop the ping pong ball into the tube.
When the water level raises or lowers to the point that the ping pong ball breaks the infrared beam you'll know it hit the desired level. This works if you just need a discrete (on/off) level indicator.
This system is also used in paintball guns designed to prevent you from chopping balls by assuring that the whole ball is in the firing chamber before allowing the electronic trigger to arm the firing solenoid.
It's simple, effective, and requires little or no calibration.

A: Well, assuming you are operating here on earth (as opposed to in orbit), you can use a float sensor that you measure using the micro. The question is: Do you need to know the exact level, or do you just need some sort of trip when it gets to high/low?
On the 'trip at specific level' theme, you can get switches like this - generally the float contains some kind of attitude sensing switch. When the water level is lower, the float ends up on it's side, and the switch is 'off', while raising the level forces the float upright, and therefore 'on'. These are often used for sump pumps. They are pretty reliable and very easy to deal with, though you have to be careful to anchor them correctly, and you have to be sure that nothing gets in the way of the float.
If you need to know the actual level, then you've got lots of choices, but it's less simple. You can go with something like an ultrasonic sensor (ultrasound beam firing down from the top of the tank to reflect off the water level).
These guys seem to make level indicators for BIG tanks which consist of a float and an external weight cabled together. As the float rides up and down on the fluid, the external indicator moves appropriately. You could build something similar, with nothing more complicated than photo-cells to read the level (if it's a large tank, or you want lots of granularity, you'd need a lot of photo-cells).
Alternately, taking the cabled float idea, you could put an idler wheel that moves whenever the cable moves, and then attach an encoder to that. This would allow you to track the level with pretty high accuracy.

A: I know that the soon to be released book Practical Arduino has a water tank depth sensor project included, which uses a differential pressure transducer to measure the water pressure at the bottom of the tank, and from that to calculate how full the tank is.
Schematics are on the above link, along with a link to the source code on github.
(Full disclosure: I have no association with the book, but have met one of the authors a couple of times at our local hackerspaces.)

A: A method I like, but have not tried is to put two insulated plates in the liquid.  No condution, electrolosis, contanimation....... They form the plates of a cap. and are used in some sort of oscillator ( choice up to you )  Because water is a good dialetric the frquency depends strongly on the amount of water between the plates.  Meaure the frequency to get the depth.
You might be able to get a similar result by applying an ac signal and measureing the current thru the cap.

A: More details would help, but I think the ultrasonic method is probably the simplest, conceptually, anyway (hence the need for more details :-]).  I threw together a level sensor for the fuel oil tank in my basement using a MaxSonar ultrasonic transducer.  I'm switching to a Parallax Ping sensor, as soon as I can get my hands on one.  The MaxSonar unit has proved to be somewhat of a pain; turns out it's only got a resolution of one inch (2.54cm), which equates to nearly 7 gallons in my tank.  I put the MaxSonar unit in a PVC cap at the top of the tank pointing down (out of reach of the liquid).

A: My two cents: http://www.circuitstoday.com/simple-water-level-idicator

A: One more clever approach:
Make use of the bigger thermal conductivity of the water (fluid). The idea is to have temperature sensor and measure difference of its self heating when submerged and when in free air.

A: Another solution (no pun intended);
Use a potentiometer as suggested above. The normal rotation range is 270 degrees.
Attach a float to the potentiometer using a boom arm. (length=1 unit)
Between full and empty the boom arm will move 90 degrees.
The ADC on a PIC is either 256 or 1024 steps (yes, zero is a step).
I'll use 256 steps for clarity.
270 degrees = 256 ADC steps.   270/90 = 3 (one third of potentiometer range)
255/3 = 85 ADC steps
Program some code to mark the 0 degree point (tank empty) when a button is pushed.
This stores an offset point in the PIC eeprom. Now the potentiometer does not have to be exactly at zero because this calibration point can be set.
Using trigometry calculate a lookup table (hint: php script) to correspond to each step of the ADC.
Hint: each ADC step corresponds to 90/85 = 1.0588 degrees.
Yes, you should have paid more attention in maths class. dumb waste of time back then, indespensible now. engage brain. learn trigonometry. teach others.
Acronym : The Old Arab Carried A Heavy Sack Of Hay.
The hypontenuse is the length of the boom arm. Make it 1 unit long. Lookup table then provides percentage of tank depth. (multiply by 100 of course)

A: Please check the following link:
http://www.edgefxkits.com/contactless-liquid-level-controller
I think it may be useful to you.


text:
Q: list of github repository files along with latest commiter I want to have all files content with their latest committer. Repository size is relatively small, less than 100 files.
I see one way to do that which seems bad performance-wise. Get repository tree and then check to each every sha belongs to ( skipping already knowns sha's ). Tarball the repository and download. This will cause inconsistency since downloading tarball and tree/sha' owner might run into race condition.
Any better solution in any programming language is fine ?
thanks

A: Using git blame to show what revision and author last modified each line of a file. Combined with find, you can check all the files content with their committer.
This bash script finds out all the files in current directory recursively, and git blame all the files and write the output to /tmp/git_files.log
find . -type f -exec sh -c 'echo {}; git blame {}; echo;' \; > /tmp/git_files.log


text:
Q: shouldPerformSegueWithIdentifier not working with SWRevealViewController I am trying to prompt an alert and request payment for premium features in my app before a segue happens, but shouldPerformSegue doesn't seem to be working. I have a SWRevealViewController that opens a side menu, from which I connected the segue manually in my Storyboard. I clicked the Segue and named identified it.
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
    if identifier == "advanced_segue" {
        purchaseRequest()
        print("shouldPerformSegue working")
        return false
    } else {
    return true }
}

Please see attached picture.

A: You are missing the segue class, try with SWRevealViewControllerSeguePushController or SWRevealViewControllerSegueSetController

A: Put a break point on the if statement to make sure it is entering. If it is, then it might be due to the kind of segue. Try using the library's custom "reveal view controller push controller" segue type.


text:
Q: How can I abort Spring-Boot startup? I'm writing a Spring-Boot application to monitor a directory and process files that are being added to it. I register the directory with WatchService in a configuration class:
@Configuration
public class WatchServiceConfig {

    private static final Logger logger = LogManager.getLogger(WatchServiceConfig.class);

    @Value("${dirPath}")
    private String dirPath;

    @Bean
    public WatchService register() {
        WatchService watchService = null;

        try {
            watchService = FileSystems.getDefault().newWatchService();
            Paths.get(dirPath).register(watchService, ENTRY_CREATE);
            logger.info("Started watching \"{}\" directory ", dlsDirPath);
        } catch (IOException e) {
            logger.error("Failed to create WatchService for directory \"" + dirPath + "\"", e);
        }

        return watchService;
    }
}

I would like to abort Spring Boot startup gracefully  if registering the directory fails. Does anybody know how I can do this?

A: The accepted answer is correct, but unnecessarily complex. There's no need for a Condition, and then checking for the existence of the bean, and then closing the ApplicationContext. Simply checking for the presence of the directory during WatchService creation, and throwing an exception will abort the application startup due to failure to create the bean.

A: Get the Application Context, e.g.:
@Autowired
private ConfigurableApplicationContext ctx;

Then call the close method if you cannot find the directory:
ctx.close();

That gracefully shutdowns the Application Context and thus the Spring Boot Application itself.
Update:
A more detailed example based on the code provided in the Question.
Main Class
@SpringBootApplication
public class GracefulShutdownApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(GracefulShutdownApplication.class, args);
        try{
            ctx.getBean("watchService");
        }catch(NoSuchBeanDefinitionException e){
            System.out.println("No folder to watch...Shutting Down");
            ctx.close();
        }
    }

}

WatchService Configuration
@Configuration
public class WatchServiceConfig {

    @Value("${dirPath}")
    private String dirPath;

    @Conditional(FolderCondition.class)
    @Bean
    public WatchService watchService() throws IOException {
        WatchService watchService = null;
        watchService = FileSystems.getDefault().newWatchService();
        Paths.get(dirPath).register(watchService, ENTRY_CREATE);
        System.out.println("Started watching directory");
        return watchService;
    }

Folder Condition
public class FolderCondition implements Condition{

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        String folderPath = conditionContext.getEnvironment().getProperty("dirPath");
        File folder = new File(folderPath);
        return folder.exists();
    }
}

Make the WatchService Bean @Conditional based on whether the directory is present or not.  Then in your Main Class, check whether the WatchService Bean exists, and if not shutdown the Application Context by calling close().

A: If you are OK with the messaging in the current IOException, you can have your bean throw it to abort startup:
@Bean
public WatchService watchService() throws IOException {
    WatchService watchService = FileSystems.getDefault().newWatchService();
    Paths.get(dirPath).register(watchService, ENTRY_CREATE);
    logger.info("Started watching \"{}\" directory ", dlsDirPath);
}

If you want a more friendly error message than the default IOException (to better help point users at the error), you can throw your own exception with a customized exception message:
@Bean
public WatchService watchService() {
    try {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        Paths.get(dirPath).register(watchService, ENTRY_CREATE);
        logger.info("Started watching \"{}\" directory ", dlsDirPath);
        return watchService;
    } catch (IOException e) {
        throw new IllegalStateException(
                "Failed to create WatchService for directory \"" + dirPath + "\"", e);
    }
}

A: https://docs.spring.io/spring-boot/docs/2.1.1.RELEASE/reference/htmlsingle/#boot-features-application-exit

Each SpringApplication will register a shutdown hook with the JVM to
  ensure that the ApplicationContext is closed gracefully on exit. All
  the standard Spring lifecycle callbacks (such as the DisposableBean
  interface, or the @PreDestroy annotation) can be used.
In addition, beans may implement the
  org.springframework.boot.ExitCodeGenerator interface if they wish to
  return a specific exit code when the application ends.

You should implement @PreDestroy methods which releases resources / files. Then during startup, when you detect some error, you could throw some RuntimeException - it start closing application context.


text:
Q: error: cannot find symbol variable listView private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        String item = (String) listView.getAdapter().getItem(position);
        Toast.makeText(getApplicationContext(),item+"선택",Toast.LENGTH_SHORT).show();
    }
}
}

After creating navigationDrawer, OnItemClick events were added to ListView.
But it doesn't work.
Error:(74, 36) error: cannot find symbol variable listView

The above error occurs. Could you tell me what's wrong?

A: The error says listView is not defined in your code, so there is no reference to this object. try to define it in this class or in the super class


text:
Q: How to check if javascript value is set correct or not I'm update value via javascript class. How to check the current value is set or not.
My code is below,
<script>
    $(document).ready(function() {
        $(".sampleClass").click(function(){
            var sampleValue = $(this).val();
            var samplePrice = $(".samplePriceValue").val();
            .....
        });
    });
</script>

A: In javascript we can use console.log() to check the current value. The value is displayed in console.
For example use this below line.
<script>
    $(document).ready(function() {
        $(".sampleClass").click(function(){
            var sampleValue = $(this).val();
            console.log(sampleValue);
            var samplePrice = $(".samplePriceValue").val();
            console.log(samplePrice);
            .....
        });
    });
</script>

Run your application.
And press F12 the console window will be opened in your browser. In console you can view the values.
The sample output
sampleValue
samplePrice


text:
Q: beautiful soup always returns the same tree even if page source is different I am trying to scrape data from a Hubspot report but after everytime I click on the next page button and try to get the info from the next page it seems to have not updated the page source. After stepping through the code I discovered that the page source returned from selenium webdriver indeed is different, but bs4 for some reason builds a tree exactly the same as the previous page, with a different page source somehow.
from time import sleep

from selenium.webdriver import Firefox, FirefoxOptions
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.remote.webelement import WebElement

from bs4 import BeautifulSoup, Tag

import pandas as pd

REPORT_URL = 'https://app.hubspot.com/reports-list/[REDACTED]'
PROFILE_DIRECTORY = '[REDACTED]'

rows = []
pages = 0

options = FirefoxOptions()
options.profile = FirefoxProfile(PROFILE_DIRECTORY)
driver = Firefox(options=options)
driver.get(REPORT_URL)

input("Please press enter to continue...")

last_src = None
while True:
    sleep(3)

    source = driver.page_source
    is_same = source == last_src
    last_src = source
    bs = BeautifulSoup(source, 'html.parser')

    tbody = bs.find('tbody')
    trows = tbody.find_all('tr')
    for row in trows:
        rot_tag: Tag = row
        tdata = rot_tag.find_all('td')

        row_list = []
        for cell in tdata:
            row_list.append(cell.text)
        rows.append(row_list)
    pages += 1

    next_button = bs.find('button', {
        'aria-label': 'Next page'
    })
    disabled = next_button.attrs.get('aria-disabled', 'true')
    if disabled == 'true':
        break
    else:
        try:
            next_button_clickable = driver.find_element(
                By.CSS_SELECTOR, 'button.'+'.'.join(next_button.attrs.get('class', [])))
            next_button_clickable.click()
        except:
            break

COLUMNS = [
    'create_date', 'timestamp_ad_interaction', 'interaction', 'program', 'campaign_id', 'ad_group_id',
    'ad_id', 'marketing_channel', 'original_source', 'latest_source', 'utm_term', 'utm_term_2', 'utm_medium',
    'utm_medium_2', 'utm_source', 'utm_source_2', 'fb_clid', 'goog_clid', 'fbclid', 'gclid'
]

df = pd.DataFrame(rows, columns=COLUMNS)
df.to_csv('ad_interactions-7_26.csv', index=False)
driver.quit()


text:
Q: Tracking operations in operation queue I have just started implementing some Operation Subclass' which handle some async work like downloading for me.  I am curious about best practice for managing the queue, specifically to make sure i don't add the same task twice.
Is there a method where i can add the operation to the queue with a name or is it a case of creating and managing a dictionary?  Say, when items are added to the queue you append entry to dictionary and when they are finished you remove entry from dictionary?  Performing conditional check beforehand?
This could achieved pretty easily as there is a notification block within the operation subclass.  It just seems a bit hacky.
Thanks for advice.
---- EDIT ----
So tried using this for loop elsewhere (cellForItemAt) to show activity indicator if item is in queue but it seems to only be checking the first item of the queue and return that but no others even if there are multiple operations in the queue with unique names:
            for operation in downloadQueue.operations {
                if operation.name == self.multiPartArray[collectionView.tag][indexPath.item].name  {                       innerCell.contentView.addSubview(self.activityIndicatorView)                       self.activityIndicatorView.centerXAnchor.constraint(equalTo: innerCell.contentView.centerXAnchor).isActive = true                     self.activityIndicatorView.centerYAnchor.constraint(equalTo: innerCell.contentView.centerYAnchor).isActive = true
                    self.activityIndicatorView.isHidden = false
                    self.activityIndicatorView.startAnimating()
                    innerCell.contentView.bringSubview(toFront: self.activityIndicatorView)
                    break
                } else {
                    print("Operation not in queue")
                }
            }

Seems to be doing the same thing when adding operations to the queue.  It checks the first operation.  If != opName then it will add the operation even if opName exist is in the queue but not the first item.

A: You can use the operation name to do this.
let yourOperationQueue = NSOperationQueue()

Set operation name every time when you add an operation and check with that name every time before you add the operation. Keep those operation names unique.
func addDownloadOperation()
{
    self.checkAndAddOperationWithName("DownloadOperation")
}

func addUploadOperation()
{
    self.checkAndAddOperationWithName("UploadOperation")
}

func checkAndAddOperationWithName(opName:String)
{
    var operationExist = false
    for operation in yourOpeartionQueue.operations
    {
        if operation.name == opName
        {
            print("Operation alreday added")
            operationExist = true
            break
        }
    }
    if !operationExist
    {
       self.addOperationToTheQueWithName(opName)
    }
}

func addOperationToTheQueWithName(opName:String)
{
    let someOperation = NSBlockOperation(block:{
        //some heavy operations
    })
    someOperation.name = opName
    yourOpeartionQueue.addOperation(someOperation)
    print("Operation \(opName) added")
}


text:
Q: Conditional script exiting and delegating control I'm wondering where in a process should the control of a script exiting be placed?
If a function is used to determine whether a script should continue or not, should control, based on the result, be in the caller or the callee?
Are there scenarios where it could be in either?
(I'm sure this question has broader implications so please feel free to extend the answer to a higher level practice in programming. That would be great actually)
I will list some examples below to consider as options of conditional script exiting and how control could be delegated or not.
Imagine should_continue is checking that a supplied arg is valid and its validity is required for the script to continue. Otherwise it exits.
'''
ex 1: return state to parent process to determine if script continues
'''
def should_continue(bool):
  if bool:
    return True
  else:
    return False

def init():
  if should_continue(True):
    print 'pass'
  else:
    print 'fail'

'''
ex 2: return state only if script should continue
'''

def should_continue(bool):
  if bool:
    return True
  else:
    print 'fail'
    sys.exit() # we terminate from here

def init():
  if should_continue(True):
    print 'pass'

'''
ex 3: Don't return state. Script will continue if should_continue doesn't cause termination of script
'''

def should_continue(bool):
  if not bool:
    print 'fail'
    sys.exit()

def init():
  should_continue(True)
  print 'pass'

A: It depends.
If it is feasible to exit as soon as should_continue checks as false, then do so. The alternative is to pass "stop" returns all the way up the call-chain which need to be checked at each level; this is error-prone and hard to read.
If merely exiting is not-so-very-desirable, and it often is not in case cleanup or "hey I quit because ..." is needed, then you shouldn't just exit. Since you used Python as the example, it has a spectacularly clean method of Exception handling:
class TimeToSayGoodbye(Exception):
    def __init__(self, reason):
        self.reason = reason

with a deeply nested function:
def way_down_the_stack():
    if not should_continue:
         raise TimeToSayGoodbye('drive safely')

and then if you do nothing else, Python generates a useful (but not pretty) backtrace. If your main looks like
def main():
    try:
        my_application()
    except TimeToSayGoodbye as e:
        print (e.reason)

Then your top-level is in control of a Goodbye that happens anywhere and none of the fifteen methods between my_application and way_down_the_stack needs to even know that the program might spontaneously end.


text:
Q: Segmentation fault when extending UIViewControllerAnimatedTransitioning I'm trying to provide a generic implementation of UIViewControllerAnimatedTransitioning using Swift protocols, but whenever I have an object which conforms to the protocol, I get the error:
Command failed due to signal: Segmentation fault: 11

When the generics are removed, I still get the problem.
Here's my protocol, with the generics commented out:
protocol TransitionControllerType: UIViewControllerAnimatedTransitioning {
//    typealias PresentingViewController: UIViewController
//    typealias PresentedViewController: UIViewController

    var isPresentation: Bool { get set }
    var presentationTransitionDuration: NSTimeInterval { get }
    var dismissTransitionDuration: NSTimeInterval { get }

    func prepareViewControllerForPresentation(viewController: UIViewController, presentingViewController: UIViewController)
    func presentViewController(viewController: UIViewController, presentingViewController: UIViewController)
    func dismissViewController(viewController: UIViewController, presentingViewController: UIViewController)
}

PresentingViewController and PresentedViewController would just be in place of UIViewController in prepareViewController(::), presentViewController(::), and dismissViewController(::).
I provide the implementation for UIViewControllerAnimatedTransitioning in an extension for TransitionControllerType:
extension TransitionControllerType {
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return isPresentation ? presentationTransitionDuration : dismissTransitionDuration
    }

    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        // Ensure there is a container view
        guard let containerView = transitionContext.containerView() else {
            return
        }

        // Get the view controllers
        let (fromViewController, toViewController) = transitionContext.viewControllers()

//        // Cast the view controllers
//        guard let presentedViewController = (isPresentation ? toViewController : fromViewController) as? PresentedViewController,
//            let presentingViewController = (isPresentation ? fromViewController : toViewController) as? PresentingViewController
//        else {
//            return
//        }
        guard let presentedViewController = (isPresentation ? toViewController : fromViewController),
            let presentingViewController = (isPresentation ? fromViewController : toViewController)
        else {
            return
        }

        // Get the views from the view controllers
        let presentedView = presentedViewController.view
        let presentingView = presentingViewController.view

        // If it's a presentation, prepare the view controllers
        if isPresentation {
            prepareViewControllerForPresentation(presentedViewController, presentingViewController: presentingViewController)
            containerView.addSubview(presentedView)
        }

        UIView.animateWithDuration(
            transitionDuration(transitionContext),
            delay: 0,
            usingSpringWithDamping: isPresentation ? PresentationSpringDamping : DismissSpringDamping,
            initialSpringVelocity: isPresentation ? PresentationSpringVelocity : DismissSpringVelocity,
            options: isPresentation ? UIViewAnimationOptions.CurveEaseOut : [],
            animations: {
                if self.isPresentation {
                    self.presentViewController(presentedViewController, presentingViewController: presentingViewController)
                } else {
                    self.dismissViewController(presentedViewController, presentingViewController: presentingViewController)
                }
            },
            completion: { success in
                transitionContext.completeTransition(success)

                // !!!: We have to manually add `presentationView` due to a bug
                // http://openradar.appspot.com/radar?id=5320103646199808
                if !self.isPresentation {
                    UIApplication.sharedApplication().keyWindow?.addSubview(presentingView)
                } else {
                    UIApplication.sharedApplication().keyWindow?.addSubview(presentedView)
                }
        })
    }

    func prepareViewControllerForPresentation(viewController: UIViewController, presentingViewController: UIViewController) { }
    func presentViewController(viewController: UIViewController, presentingViewController: UIViewController) { }
    func dismissViewController(viewController: UIViewController, presentingViewController: UIViewController) { }
}

Trying to run the project at this point will result in a successful build.
If I attempt to implement the protocol on an NSObject (for conformance to UIViewControllerAnimatedTransitioning), I get the segmentation fault error.
Below is the class that I use for the transitioningDelegate when presenting AddNewMenuViewController, and the TransitionControllerType used by
class AddNewMenuTransitionControllerDelegate: NSObject, UIViewControllerTransitioningDelegate {
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
        return AddNewMenuPresentationController(presentedViewController: presented, presentingViewController: presenting, blurStyle: .Dark)
    }

    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return AddNewMenuTransitionController(presentation: true)
    }

    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return AddNewMenuTransitionController()
    }
}

class AddNewMenuTransitionController: NSObject, TransitionControllerType {
    var isPresentation: Bool
    var presentationTransitionDuration: NSTimeInterval = 0.3
    var dismissTransitionDuration: NSTimeInterval = 0.3

    init(presentation: Bool = false) {
        self.isPresentation = presentation

        super.init()
    }
}

Why does the non-generic version result in the same segmentation fault as the generic version?

A: I don't think the compiler recognizes the default method implementation of animateTransition added by extension to the TransitionControllerType protocol when trying to figure if your AddNewMenuTransitionController class satisfies the UIViewControllerAnimatedTransitioning protocol (which is required by your declaration of the TransitionControllerType).
That may be a bit much to ask of the compiler since it would essentially need to pre-build the method list with the default implementation of TransitionControllerType while it is verifying availability of methods for one of its requirements.
This may work (but I haven't tried it) if you don't require UIViewControllerAnimatedTransitioning in the definition of TransitionControllerType but add it explicitly to your class definition instead.
I'm sure this is not as clean as what you were aiming for but the indirect default implementation of a method using an intermediate protocol seems to be too much for the compiler at this time.


text:
Q: Reference request – a priori estimate – mixed boundary condition I am interested in finding references regarding estimates of the form
$$ \| D^2 u\|_{L^2(\Omega)} \leq C(\|f\|_{L^2(\Omega)}+\|g\|_{S} )$$
where $\|D^2 u\|_{L^2(\Omega)}^2 = \sum\limits_{i,j \in \{1,2\}} \int_{\Omega}(\partial_{x_i x_j}u)^2$ and
$$ \begin{cases}
-\Delta u = f & \text{ in }\Omega \\
u = 0 & \text{ on } \Gamma_D \\
\frac{\partial u}{\partial n} = g & \text{ on } \Gamma_N
\end{cases} $$
and $\Omega\subset \Bbb{R}^2$ is polygonal (bounded, convex) such that the solution $u$ belongs to $H^2(\Omega)$ (in particular $g$ is regular enough). The space $S$ for $g$ is $H^{1/2}(\Gamma_N)$ (but I am interested in other options if available). The boundaries $\Gamma_D, \Gamma_N$ are both non-void and make a partition for $\partial\Omega$.
I was able to find in the book of Grisvard (Elliptic problems in nonsmooth domains) a similar result when $g\equiv 0$. However, I could not find this precise estimate for the non-homogeneous Neumann boundary conditions.

Can you point me to a reference that contains proofs of such estimates? In particular, I am interested in finding precisely the constant $C$ (if possible).


text:
Q: Convert numbered pinyin to pinyin with tone marks Is there any package which can convert numbered pinyin (e.g. dian4 nao3) to UTF-8 pinyin with tone marks (e.g. diàn nǎo)?
I found this (https://stackoverflow.com/a/8200388/2421048) Python script, so it should be possible with LuaLaTeX using directlua.

A: If you want to use xeCJK package, XeLaTeX is necessary instead of LuaLaTeX.
You can use xpinyin package for pinyin.
\documentclass{article}
\usepackage{xeCJK}
\setCJKmainfont{SimSun}
\usepackage{xpinyin}
\begin{document}

电脑 \pinyin{dian4 nao3}

\end{document}

You will get

电脑 diàn nǎo

A: In Luatex, the conversion can be achieved without extra packages.
Below is some example code, operating on input strings.
Note that I don't know anything about Chinese in general, nor Pinyin in
particular.
All I did was follow the WP entry
which seemed fairly straightforward.
Thus I expect the conversion to require further tweaking.
If it produces incorrect results then please extend your question with
more examples.
Here is the main TeX document (in Plain, but it should translate to
Latex):
%% load some font that covers the diacritic marks
\input luaotfload.sty
\font\diacritics = "file:lmroman10-regular.otf:mode=node" at 10pt
\diacritics

%% --------------------------------------------------------------------
%% load conversion routines; adjust filename here
\directlua{dofile "\jobname.lua"}

%% wrap converter in a TeX macro
\protected\def\convertpinyin#1{%
  %% switch to appropriate hyphenation pattern goes here
  \directlua{packagedata.pinyintones.convert ([==[#1]==])}%
}

%% --------------------------------------------------------------------
%% demo

\def\showtest#1{((#1) (\convertpinyin{#1}))\par}

\def\testa{dian4 nao3}
\def\testb{ma ma1 ma2 ma3 ma4}

\showtest\testa
\showtest\testb

\bye

It loads a Lua file of the same name, but you can change the call to
dofile() to something that fits your setup.
Here is the code:
local utf                 = utf or require "unicode.utf8"
local lpeg                = require "lpeg"

local unpack              = unpack or table.unpack
local type                = type
local iowrite             = io.write
local stringformat        = string.format
local tableconcat         = table.concat
local utfchar             = utf.char
local texsprint           = tex.sprint

local C, Cg, Ct           = lpeg.C, lpeg.Cg, lpeg.Ct
local P, R, S, lpegmatch  = lpeg.P, lpeg.R, lpeg.S, lpeg.match

packagedata               = packagedata or { }
packagedata.pinyintones   = packagedata.pinyintones or { }
local pinyintones         = packagedata.pinyintones

-----------------------------------------------------------------------
---                           conversion
-----------------------------------------------------------------------

local toneno      = R"05"
local consonant   = S"bcdfghjklmnpqrstvwxyz" + S"BCDFGHJKLMNPQRSTVWXYZ"
local vowel       = S"aeiou" + S"AEIOU" + "ü" + "Ü"
local nucleus     = Ct(C(vowel)^1)
local syllable    = Cg((consonant^1)^-1, "onset")
                  * Cg(nucleus,          "nucleus")
                  * Cg((consonant^1)^-1, "coda")
                  * Cg(toneno^-1,        "tone")
local skip        = (1 - syllable)^1 --- keep this stuff
local pinyin      = Ct((Ct(syllable) + C(skip))^1)

local vowelpositions = function (nucleus)
  local tmp = { }
  for pos, vowel in next, nucleus do
    tmp[vowel] = pos
  end
  return tmp
end

local precedence = { "a", "e", "o" }

local cmacron = utfchar (0x0304)
local cacute  = utfchar (0x0301)
local ccaron  = utfchar (0x030c)
local cgrave  = utfchar (0x0300)

local todiacritic = function (str)
  local result   = { }
  local analyzed = lpegmatch (pinyin, str)
  --inspect (analyzed)
  for i = 1, #analyzed do
    local elm = analyzed[i]
    local t   = type (elm)

    if t == "table" then --- syllable
      local nucleus  = elm.nucleus
      local nvowels  = #nucleus
      local tone     = elm.tone
      if tone then
        tone = tonumber (tone)
      end

      if not tone then --- add unmodified
        result[#result+1] = elm.onset
        result[#result+1] = tableconcat (nucleus)
        result[#result+1] = elm.coda
      else
        local tonified
        if nvowels == 1 then --- single vowel receives tone
          local vowel = nucleus[1]
          if tone == 1 then --- inlined for performance
            tonified = vowel .. cmacron
          elseif tone == 2 then
            tonified = vowel .. cacute
          elseif tone == 3 then
            tonified = vowel .. ccaron
          elseif tone == 4 then
            tonified = vowel .. cgrave
          else
            tonified = vowel
          end

        elseif nvowels > 1 then
          local positions = vowelpositions (nucleus)
          local pos

          --- 1) locate correct vowel
          for j = 1, 3 do
            pos = positions[precedence[j]]
            if pos then
              break
            end
          end
          if not pos then -- iu or ui, thus second gets tone
            pos = 2
          end

          local vowel = nucleus[pos]

          --- 2) place tone mark
          if tone == 1 then
            nucleus[pos] = vowel .. cmacron
          elseif tone == 2 then
            nucleus[pos] = vowel .. cacute
          elseif tone == 3 then
            nucleus[pos] = vowel .. ccaron
          elseif tone == 4 then
            nucleus[pos] = vowel .. cgrave
          end

          tonified = tableconcat (nucleus)
        else --- no vowel, could be mismatch
          tonified = ""
        end
        result[#result+1] = elm.onset
        result[#result+1] = tonified
        result[#result+1] = elm.coda
      end

    elseif t == "string" then
      result[#result+1] = elm
    end

  end
  return tableconcat (result)
end

-----------------------------------------------------------------------
--- export
-----------------------------------------------------------------------

pinyintones.convert = function (str)
  local converted = todiacritic (str)
  if converted then
    texsprint (converted)
  end
end

Result:

For convenience, I created a
gist of the code.

A: I have translated the Python script mentioned in the question to Lua. Compile it with LuaLaTex and it should work:
\documentclass{article}
\usepackage{fontspec}

\usepackage{luacode}
\begin{luacode*}
PinyinToneMark = {
  {'ā', 'á', 'ǎ', 'à'},
  {'ē', 'é', 'ě', 'è'},
  {'ī', 'í', 'ǐ', 'ì'},
  {'ō', 'ó', 'ǒ', 'ò'},
  {'ū', 'ú', 'ǔ', 'ù'},
  {'ǖ', 'ǘ', 'ǚ', 'ǜ'}
}

function convertPinyin(str)
  if str~= nil and string.len(str)>0 then
  local s = string.lower(str)
  local r = ''
  local t = ''
  for i = 1, string.len(s) do
    local c = s:sub(i,i)
    if c >= 'a' and c <= 'z' then
      t = t .. c
    elseif c >= '0' and c <= '5' then
        local tone = tonumber(c)
        if tone ~= 0 then
          if string.find(t, 'a') ~= nil then
              t = string.gsub(t, "a", PinyinToneMark[1][tone])
          elseif string.find(t, 'e') ~= nil then
              t = string.gsub(t, "e", PinyinToneMark[2][tone])
          elseif string.find(t, 'i') ~= nil then
              t = string.gsub(t, "i", PinyinToneMark[3][tone])
          elseif string.find(t, 'o') ~= nil then
              t = string.gsub(t, "o", PinyinToneMark[4][tone])
          elseif string.find(t, 'u') ~= nil then
              t = string.gsub(t, "u", PinyinToneMark[5][tone])
          elseif string.find(t, 'v') ~= nil then
              t = string.gsub(t, "v", PinyinToneMark[6][tone])
          end
        end
      r = r .. t
      t = ""
    end
  end
  tex.print(r)
  end
end
\end{luacode*}

\begin{document}
 \directlua{convertPinyin("dian4 nao3")}
\end{document}

This version handles only v and not u: or ü.


text:
Q: Why do I get an unneeded column in code first created table? I don't understand why EF creates a nullable TemplateTask_Id column in my TemplateTaskDependancies table. I thought using a modelbuilder configuration class would solve the problem, but I must be missing something.
My domain classes are as follows.
[Table("TemplateTaskDependancies")]
public class TemplateTaskDependancy : Dependancy<TemplateTask>,
                                      IDependancy<TemplateTask>
{
    [Column("TaskId")]
    public int TaskId { get; set; }

    [Column("NeededTaskId")]
    public int NeededTaskId { get; set; }

    [ForeignKey("TaskId")]
    public override TemplateTask Task { get; set; }

    [ForeignKey("NeededTaskId")]
    public override TemplateTask NeededTask { get; set; }
}

public abstract class Dependancy<T> : LoggedEntity
    where T : LoggedEntity
{
    [Column("TaskId")]
    public int TaskId { get; set; }

    [Column("NeededTaskId")]
    public int NeededTaskId { get; set; }

    [ForeignKey("TaskId")]
    public abstract T Task { get; set; }

    [ForeignKey("NeededTaskId")]
    public abstract T NeededTask { get; set; }

}

public interface IDependancy<T> where T : LoggedEntity
{
    int Id { get; set; }

    int TaskId { get; set; }

    int NeededTaskId { get; set; }

    T NeededTask { get; set; }

    T Task { get; set; }

    State { get; set; }
}

public abstract class LoggedEntity : IObjectWithState
{
     public int Id { get; set; }  // primary key

     // todo with Julie Lerman's repository pattern
}

In my context I have
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Conventions
               .Remove<OneToManyCascadeDeleteConvention>();
   modelBuilder.Configurations
               .Add(new TemplateTaskDependancyConfiguration());
}

public class TemplateTaskDependancyConfiguration :
             EntityTypeConfiguration<TemplateTaskDependancy>
{
    public TemplateTaskDependancyConfiguration()
    {
        HasRequired(x => x.NeededTask)
       .WithMany(y=>y.NeededTasks)
       .HasForeignKey(z=>z.NeededTaskId)
       .WillCascadeOnDelete(false);

        HasRequired(x => x.NeededTask)
       .WithMany(y => y.Dependancies)
       .HasForeignKey(z => z.TaskId)
       .WillCascadeOnDelete(false);

        HasRequired(x=>x.Task)
       .WithMany(y=>y.NeededTasks)
       .HasForeignKey(z=>z.NeededTaskId)
       .WillCascadeOnDelete(false);

        HasRequired(x => x.Task)
       .WithMany(y => y.Dependancies)
       .HasForeignKey(z => z.TaskId)
       .WillCascadeOnDelete(false);
    }
}

A: Because you have no primary key defined anywhere?
By the way, it's dependEncy.

A: It turned out that the problem was caused by an unneeded collection of
public List<TemplateTaskDependancy> Tasks

inside my TemplateTask class.
i.e the foreign key table contained an extra collection of objects.