text:
Q: pl/sql function called how many times? Assume you have the following update:
Update table set col1 = func(col2)
where col1<>func(col2)

The func function is evaluated two times for every row, or once for every row?
Thanks,

A: For 11g, it will be called once for every new occurence of col2. For the next calls, a cached result is used if caching is enabled.

A: This is the kind of situation where some experimentation is useful (this was conducted on 10g). Using the following query, we can tell that normal functions, using the same parameters (in this case, none) will be executed each time they are called:
select dbms_random.value() from all_tables

This is because Oracle assumes that a function will not return the same value consistently unless you tell it otherwise.  We can do that by creating a function using the deterministic keyword:
CREATE FUNCTION rand_det
   RETURN NUMBER
   DETERMINISTIC AS
BEGIN
   RETURN DBMS_RANDOM.VALUE ();
END;

Using this function instead of dbms_random in the first query tells us that the query is being executed only once, despite the many calls.  But this only clarifies the select section.  What if we use the same deterministic function in both a select and a where clause. We can test that using the following query:
SELECT rand_det
FROM   all_tables
WHERE  rand_det > .5;

You may have to run this several times to see our proof, but, eventually, you'll see a list of values less than 0.5. This provides us with evidence that even the deterministic function is being executed twice: once for each section it appears in. As an alternative, you can modify our deterministic function as follows, then run the subsequent query, which will reveal 2 lines written to DBMS_OUTPUT.
CREATE OR REPLACE FUNCTION rand_det
   RETURN NUMBER
   DETERMINISTIC AS
BEGIN
   DBMS_OUTPUT.put_line ('Called!');
   RETURN DBMS_RANDOM.VALUE ();
END;

SELECT rand_det
FROM   all_tables;

A: While I like Allan's answer for showing how to investigate this, I think the real lesson to take away is that you shouldn't rely on the answer to this question if you can avoid it.
Here's a useful post on the topic from Tom Kyte ("I've written thousands of times that you cannot rely on how many times or when or if SQL will call your function.")  Even prior to 11g introducing the result cache, there are no guarantees about how many times a function will be called in processing a SQL statement.  It can depend on the execution plan, which can change over time.
If your concern is performance and your function is deterministic, the 11g result cache is probably sufficient -- it won't guarantee a specific limit on the number of calls to the function, but should reduce the number of redundant calls significantly.  (See link provided in @cularis answer.)
If for some reason you actually want to ensure that the two calls to the functions are distinct, I think the only way you could force that would be to add a second parameter to the function that is actually ignored but serves to prevent the result cache or optimizer from seeing the calls as identical.


text:
Q: Beamer - Disable Fira Font in Metropolis Theme Is it possible to disable the Fira Font in the Metropolis theme when using LuaTex and fontspec?
I would like to have the same fallback font that Metropolis uses when compiling with LaTex.
the MVE:
\documentclass{beamer}
\usetheme{metropolis}

% Font configuration
\usepackage{fontspec}
\usepackage{unicode-math}

\title{A minimal example}
\date{\today}
\author{Matthias Vogelgesang}
\institute{Centre for Modern Beamer Themes}
\begin{document}
  \maketitle
  \section{First Section}
  \begin{frame}{First Frame}
    Hello, world!
  \end{frame}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Relating Differential equations and exact differential forms I'm reading Fundamentals of Differential Equations by Nagle.
Given the equation
$$\frac{dy}{dx}=f(x,y)$$
Nagle says at times we can rewrite as an exact differential form
$$M(x,y)dx+N(x,y)dy=0$$
So it seems this is the case if it holds that
$$f(x,y)= \frac{-M(x,y)}{N(x,y)}$$
and if we do cross multiplying, we go from the differential equation to the differential form. But why is this so? I think I was taught in my calculus classes that $dy/dx$ is notation for $y'$ and not literally a ratio of $dy$ and $dx$ which the professor at that time said were "deep concepts" and that sometimes you can't do "intuitive" algebraic operations with them.  So why can we do it here?
As a side note, I have read Analysis on Manifolds by Munkres about 1.5 years ago, and he talks about (exact) differential forms. Sadly I forgot a lot after that and looking again at the definition of differential forms, it's pretty abstract, and takes many other ideas to "build up to" (ie alternating tensors, dual transformations, tangent spaces, etc). So maybe there's some neat connection between differential equations and differential forms that I'm missing?
Thanks a lot in advance, any guidance is greatly appreciated.


text:
Q: Create Object of new different Class every time I want to create objects of a new class(different name specifically) continuously.
public static void main(String args[]) {
    while (true) {
        Object obj = getNewClassObject();
        System.out.println(obj.getClass.getName());
    }
}

public static Object getNewClassObject() {
    // some code
}

The task is what should we write in the method so it returns an Object of different class every time and the program prints different class name in each line.
I have tried using Anonymous class, Inner class, lambdas etc.. but they all return the same class name.
My current "lame" solution is creating new class files inside a play application(has reloading ability) and then using reflection lib(or just java code) to load class and get the object of the new class.
But it takes a lot of memory also reflection method getSubTypeOf() takes a lot of time ~100 secs and after some time I get OutOfMemoryError.
I hope there is a better way to do it. I am thinking something like unloading or releasing class metadata to free up memory.

A: With Javassist try
private static ClassPool pool = ClassPool.getDefault();
private static RandomString rs = new RandomString();

public static Object getNewClassObject() {
    String name = rs.nextString();
    Object obj = null;

    try {
        obj = pool.makeClass(name).toClass().newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return obj;
}

RandomString is from here: How to generate a random alpha-numeric string?
pom.xml
<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.27.0-GA</version>
</dependency>


text:
Q: Bluetooth "out of band" (OOB) pairing on Android? I've been searching the internet and haven't seen anything in the way of how to exactly implement OOB pairing. I was hoping somebody here could point me to some example code to help me out.  The chat example in the Android developers site didn't really dive into this type of pairing at all.
Basically, I have an Android tablet that I want to securely pair with a device, written in C++, that has no built in display/IO mechanism.   The tablet to be paired will act as the GUI/IO interface and I'll send message back and fourth over Bluetooth.  Thus I want to securely pair the tablet with each device through the OOB paring scheme.
I understand the concept of OOB but I'm having difficulty finding the proper methods to call when looking on the android.developers.com site for my android client code.  Also when looking at the bluez stuff I can't find much to go on for my C++ written server.
The basic use case is the user will connect the tablet to the device via a USB connection.  The USB connection will facilitate the passing of keys/mac addresses for each device and then using that information pair Bluetooth with each other.
I can figure out the USB part but once I have the keys and necessary information on the client and server I can't seem to track down the correct methods to call for both ends to successfully and securely pair.
I already have a client/server talking via an insecure connection so really the only part I'm having trouble with is the actually pairing on both ends.  As once I'm paired I can used a secureRFComm to do all of my future messaging.

A: There are no public APIs yet on androind to allow for OOB pairing.
It is possible nnly if you can or are willing to modify the underlying BlueZ stack to expose the OOB paring hooks to the applicaiton. (Non trivial task)
What OOB mechanism are you plannin on using ? NFC ?

A: I have my issue 95% solved but I have hit a small road block.  First I'll update this post with a more concrete answer to the original question and post my question at the end.
To recap, my task is to use out of band (oob) pairing to securely pair an android tablet using Honeycomb 3.2 to a beagle board through USB.  I can't post specific code, but I'll give you all the steps needed to get this done.
On the beagle board, I have the bluez 4.96 stack installed with the dbusoob plugin installed.  To confirm this is set up correctly install 2 Bluetooth dongles on the beagle board and run the OOB Test Code found in in the bluez archive in the test folder.  This is a python script.  The script should successfully pair the 2 Bluetooth dongles, if not bluez is probably not setup correctly.
To get USB communications with a tablet working you need to install mtpfs and mtp-tools.  These are used to mount your tablet.  They way I solved getting OOB information between the 2 devices were to mount the tablet on the beagle board.  Once mounted the tablet and beagle board can write out a file with the information needed.
On the android side OOB is not supported in the public API so things get tricky.  I believe this is because Honeycomb 3.2 does not have a bluez stack that officially supports OOB bonding, but Google has some kind of implementation coded in.  I believe this because if you look at gingerbread source code for the Bluetooth Adapter and Bluetooth Device classes you can see OOB methods available but not exposed through the documented API.
These methods are still public so you can call them through reflection.  Using reflection you can also get all of the method signatures in a class.  This is how I figured out what methods I had available to me.
Beware though that many are not documented and it's not obvious what some do.  The important ones to make note of are the readOutOfBandData() in the adapter class and setDeviceOutOfandData() in the device class.
Another gotcha you might run into is when you write your oob data to a file on the tablet to be read by the beagle board.  Since android uses mtp you must index your file after it is written to the internal sdcard storage.  To solve this you need to make use of the MediaScannerConnection class and the scanFile() method.
Hopefully the above helps anybody else with this same issue.
Now on to my question.  I have my android application working great and my beagle board code is the testOOB example updated to have one end read OOB information from a file.  Now the issue I see is when executed everybody sees each other great, but on the tablet I still get a message asking if I want to pair with device xyz.  There are no keys or numbers.  It just asks "Pair with Device XYZ" or something along those lines.
If I press "pair" it's all paired from the tablets point of view, BUT the python script returns that the paring failed.  The python script on the beagle board is calling the actual method to do the bonding between the devices.  Even when I have the android initiate the createBond call I see the same outcome.  I can guarantee that I have set the required OOB data on both ends before trying to pair in both cases so that doesn't seem to be it.
So my issues that I'm hoping somebody can help me with are:
1) Why do I even get a message on android if the OOB data is exchanged properly?  Is there another call I'm missing and on which end?
2)  Why does the beagle board python script return paring failed even thought I press "pair" popup displayed on the tablet.  The tablet and blues monitor both show the devices as paired.  Some again I'm leaning towards the idea that I am missing something.
Thanks to anybody that can help :)
EDIT:
To add more information here is the logcat output:
D/UIBluetooth( 4363): !!!!!! Start Bond !!!!!!
D/BluetoothService( 1703): Setting out of band data for: 00:02:76:24:C2:8F:[-37, -1, 65, -42, -121, -75, -60, -4, -47, -86, -88, 14, 64, 83, 16, 96]:[-112, 34, 121, -97, 15, -54, -83, -
93, 104, -83, -124, -25, 89, 114, 66, 62]
D/BluetoothBondState( 1703): 00:02:76:24:C2:8F bond state 10 -> 11 (0)
D/UIBluetooth( 4363): createOobBond Successful
V/BluetoothEventManager( 2174): Received android.bluetooth.device.action.BOND_STATE_CHANGED
D/BluetoothEventLoop( 1703): Property Changed: Devices : 1
D/BluetoothEventLoop( 1703): Device property changed: 00:02:76:24:C2:8F property: Connected value: true
I/BluetoothEventLoop.cpp( 1703): agent_event_filter: Received method org.bluez.Agent:RequestOobData
I/BluetoothEventLoop.cpp( 1703): agent_event_filter: Received method org.bluez.Agent:RequestOobData

The last two line seems to be triggering the popup on Android to either Pair/Cancel with the Device in questions.  I would like Android to know to just auto bond and not even ask.  I could be missing a call or doing something out of order for all I know.  The last thing I do in my code is to create the bond which seems to be the obvious place to do it....
Thanks for any suggestions!


text:
Q: List Directories and get the name of the Directory I am trying to get the code to list all the directories in a folder, change directory into that folder and get the name of the current folder. The code I have so far is below and isn't working at the minute. I seem to be getting the parent folder name.
import os

for directories in os.listdir(os.getcwd()):
    dir = os.path.join('/home/user/workspace', directories)
    os.chdir(dir)
    current = os.path.dirname(dir)
    new = str(current).split("-")[0]
    print new

I also have other files in the folder but I do not want to list them. I have tried the below code but I haven't got it working yet either.
for directories in os.path.isdir(os.listdir(os.getcwd())):

Can anyone see where I am going wrong?
Thanks
Got it working but it seems a bit round about.
import os
os.chdir('/home/user/workspace')
all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]
for dirs in all_subdirs:
    dir = os.path.join('/home/user/workspace', dirs)
    os.chdir(dir)
    current = os.getcwd()
    new = str(current).split("/")[4]
    print new

A: You seem to be using Python as if it were the shell. Whenever I've needed to do something like what you're doing, I've used os.walk()
For example, as explained here: [x[0] for x in os.walk(directory)] should give you all of the subdirectories, recursively.

A: Listing the entries in the current directory (for directories in os.listdir(os.getcwd()):) and then interpreting those entries as subdirectories of an entirely different directory (dir = os.path.join('/home/user/workspace', directories)) is one thing that looks fishy.

A: import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in dirs:
        print os.path.join(root, name)

Walk is a good built-in for what you are doing

A: For New Versions of Python
I liked the answer of @RichieHindle but I add a small fix for it
import os

folder = './my_folder'

sub_folders = [name for name in os.listdir(folder) if os.path.isdir(os.path.join(folder, name))]

print(sub_folders)

otherwise it's not really work for me

A: This will print all the subdirectories of the current directory:
print [name for name in os.listdir(".") if os.path.isdir(name)]

I'm not sure what you're doing with split("-"), but perhaps this code will help you find a solution?
If you want the full pathnames of the directories, use abspath:
print [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)]

Note that these pieces of code will only get the immediate subdirectories.  If you want sub-sub-directories and so on, you should use walk as others have suggested.

A: Slight correction for python3 (same answer as @RichieHindle)
This will print all the subdirectories of the current directory in an array:
print( [name for name in os.listdir(".") if os.path.isdir(name)] )

To make the above simpler to read
for name in os.listdir("."):
    if os.path.isdir(name):
        print(name)

If you want the full pathnames of the directories, use abspath:
print( [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)])

Note that these pieces of code will only get the immediate subdirectories.


text:
Q: htc files: Why not to use them? I am developing a web application that aims to give a desktop feeling for the end user. That means I need a cross-browser feeling to the application (who doesn't? eheh).
So, I found about .htc files, for working around some IE tweaks (doesn't support border-radius yet, for example). My doubt is: Why isn't everyone using them? Does it come with some problems I am ignoring? From the place I am seeing, it appears to be almost the holy grail for the front-end programmers...

A: Quoting Wikipedia:

HTML Components (HTCs) are a
  nonstandard mechanism to implement
  components in script as Dynamic HTML
  (DHTML) "behaviors"[1] in the
  Microsoft Internet Explorer web
  browser. Such files typically use an
  .htc extension.
An HTC is typically an HTML file (with
  JScript / VBScript) and a set of
  elements that define the component.
  This helps to organize behavior
  encapsulated script modules that can
  be attached to parts of a Webpage DOM.

In two paragraphs, the following are mentioned:

*

*Internet Explorer

*JScript

*VBScript

*nonstandard

I think it's obvious why not everybody is using this technology.

A: How to use border-radius.htc with IE to make rounded corners

The server has to server the HTC with the correct MIME type (text/x-component)

That alone is enough to stop JavaScript frameworks such as jQuery or MooTools from being able to use them. The dependency on configuring anything a server in order to get client-side functionality working is beyond unacceptable.
It's a real pity though, htc files really are capable of a lot of interesting things.


text:
Q: how we open activity when app is closed in android I used calling functionality in my application. when the app is in the foreground then the application is working well. but when the app is in the background then how to open incoming call Activity in android. When a push notification is appeared then open incoming call Activity in android. how to perform this task?

A: Android 10 (API level 29) and higher place restrictions on when apps can start activities when the app is running in the background. These restrictions help minimize interruptions for the user and keep the user more in control of what's shown on their screen.
https://developer.android.com/guide/components/activities/background-starts

A: You have to call it in firebase messaging service.
 Intent intent = new Intent(this, IncomingCallActivity.class);
                    intent.putExtra(Constants.KEY_FIRST_NAME, firstName);
                    intent.putExtra(Constants.KEY_LAST_NAME, lastName);
                    intent.putExtra(Constants.KEY_EMAIL, email);
                    intent.putExtra(Constants.KEY_ID, id);
                    intent.putExtra(Constants.KEY_DP, dp);
                    intent.putExtra(Constants.CALL_TYPE, callType);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    this.startActivity(intent);

in manifest
 <activity
            android:name="IncomingCallActivity"
            android:screenOrientation="portrait"
            android:showOnLockScreen="true"
            android:showWhenLocked="true"
            android:turnScreenOn="true" />

 <service
            android:name="MessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

A: Notifications may have a pending intent attached. This pending intent may start an activity. See Notification.Builder.setContentIntent()

A: You can add a Pending Intent to your notification, so when user clicks on it, your intent will be launched.
To create a Pending Intent you should:

*

*Create a normal Intent to your destination Activity.
val goActivity = Intent(context, Activity::class.java)

*Create a Pending Intent passing a context, a request code to identify the Pending Intent, your normal Intent and a flag to configure the way your Intent is launched.
val goActivityPending = PendingIntent.getActivity(context, pendingIntentCode, goActivity, PendingIntent.FLAG_NEW_TASK)

*Add your Pending Intent to your notification builder with method setContentIntent.
val notification = NotificationCompat.Builder(context, channelId) .setContentTitle(context.getString(R.string.notificationTitle)) .setContentText(context.getString(R.string.notificationContent)) .setContentIntent(goActivityPending)
That's it! When you click the notification, your activity will be oppened. You can also use addAction() to add buttons to your notification with different Pending Intents.
If you want to know more about Intent flags, read this: Pending Intent Flags


text:
Q: Is it possible (reasonable) to expose a SOAP WS as JMS? If so, what would be the message like? An XML document with the SOAP request or response?
Does this makes sense?

A: Glassfish thinks so:
https://jms-ws-transport.dev.java.net/
An asynch message would imply either no response or a simple ACK ("We got your message; we'll get back to you.") to me.


text:
Q: webpack build xxx.vue error when use UglifyJs I use webpack build vue and use UglifyJs,but its error,for this:
ERROR in index.js from UglifyJs
SyntaxError: Unexpected token punc «(», expected punc «:» [index.js:386,6]

hello.vue code like this:
<script>
export default {
  name: 'app',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

webpack.config.js code like this:
{
    test: /\.vue$/,
    loader: 'vue-loader',
    options: {
        babel: {
            babelrc: false,
            presets: ['es2015', "stage-2"],
            plugins: ['babel-plugin-transform-runtime']
        }
}
...

new webpack.optimize.UglifyJsPlugin({
    sourceMap: false,
    mangle: false,
    compress: {
        warnings: false
        drop_console: true
    }
})

package.json code for this:
"dependencies": {
    "autoprefixer": "^6.6.1",
    "babel": "^6.5.2",
    "babel-core": "^6.21.0",
    "babel-loader": "^6.2.10",
    "babel-plugin-transform-runtime": "^6.15.0",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-stage-2": "^6.18.0",
    "cross-env": "^3.1.4",
    "css-loader": "^0.26.1",
    "html-loader": "^0.4.4",
    "sass-loader": "^4.1.1",
    "url-loader": "^0.5.7",
    "vue-html-loader": "^1.2.3",
    "vue-loader": "^10.0.2",
    "vue-style-loader": "^1.0.0",
    "vue-template-compiler": "^2.1.8",
    "webpack": "^2.1.0-beta.25",
    "webpack-dev-server": "^2.1.0-beta.9",
    "vue": "^2.1.8"
}

After build,the code like this:
/* harmony default export */ exports["default"] = {
  name: 'app',
  data() {
    return {
      msg: 'Welcome to Your Vue.js App'
    };
  }
};

I found after build, hellow.vue file to index.js,its code ES6 doesnt to ES5,so UglifyJs is error.
I tried all the methods, but it failed.
Please help me,thanks.

A: I just solved this issue myself. To apply babel to .vue files as well you must not specify babel options inside your webpack.config.js but inside a .babelrc file instead.
1) Remove the options property from the vue-loader entirely so it looks like this:
{
  test: /\.vue$/,
  loader: 'vue-loader'
}

2) Create a .babelrc file in your project root (next to package.json and webpack.config.js) with the following content:
{
  "presets": [
    ["es2015"],
    ["stage-2"]
  ],
  "plugins": ["babel-plugin-transform-runtime"],
  "comments": false
}

But beware: this is a JSON5 file, not an ordinary JSON file or JavaScript file!

I'm not sure if your options.babel: {} approach is supposed to work but the .babelrc approach is used by the official vue-cli templates and it also works for my custom setup.

A: I came across the same issue, and I don't want to implement .babelrc.
Firstly your webpack config isn't in the format recognized by vue-loader:
test: /\.vue$/,
loader: 'vue-loader',
options: {
    babel: {
        babelrc: false,
        presets: ['es2015', "stage-2"],
        plugins: ['babel-plugin-transform-runtime']
    }
}

After reading the Vue-loader advanced configuration, I was using the following:
test: /\.vue$/,
loader: 'vue-loader',
options: {
    loaders: {
        js: 'babel-loader'
    }
}

I read that the vue-loader detects babel-loader, so I figured it would detect the same configuration, unfortunately not. My babel-loader looks like this:
test: /\.js$/,
loader: 'babel-loader',
options: {
    plugins: ['transform-runtime', 'transform-object-rest-spread'],
    presets: ['es2015']
}

I came across no way to specify the loader except just via string. So I tried the webpack 1.x string options format, and it worked!:
test: /\.vue$/,
loader: 'vue-loader',
options: {
    loaders: {
        js: 'babel-loader?presets[]=es2015&plugins[]=transform-runtime'
    }
}


text:
Q: Growing or descending stack In the context of operating systems and processes, which design is better - A growing or descending stack [User mode/kernel mode stack] ?

A: It depends upon placement of the heap and library mappings; if the libraries and heap are low, then growing the stack downwards makes a lot of sense. If the libraries and heap are high, then growing the stack upwards makes a lot of sense. And both seem pretty arbitrary to me.

A: From a security point of view, I prefer the stack growing upwards, as it reduces the probability of a buffer overflow attack succeeding; there are several architectures that have dedicated stack manipulation instructions that assume a particular direction, so you may not always get to choose (for example, the Motorola 68000 MOVEM intstruction has register indirect with predecrement mode for source and register indirect with postincrement mode for destination operands, but not the other way 'round).


text:
Q: Fail to install Anaconda on a mounted folder [Please remove this file manually (you may need to reboot to free file handles)] I am trying to install anaconda on a a mounted network drive which I think is a bit slow, I am running this command:
./conda.exe constructor --prefix /mnt/nasquatch/data/colabs/anaconda3/ --extract-conda-pkgs
(I am using this command and not the ./Anaconda3-2022.05-Linux-x86_64.sh -u -b -p /mnt/nasquatch/data/colabs/anaconda3 to avoid extracting the packages each time)
and get this error:
./conda.exe constructor --prefix /mnt/nasquatch/data/colabs/anaconda3/ --extract-conda-pkgs
Extracting : regex-2022.3.15-py39h7f8727e_0.conda:   0%|▎                                                                                1/431 [00:04<34:57,  4.88s/it]
Could not remove or rename /mnt/nasquatch/data/colabs/anaconda3/pkgs/libspatialindex-1.9.3-h2531618_0u9jnfyfi/pkg-libspatialindex-1.9.3-h2531618_0.tar.zst.  Please remove this file manually (you may need to reboot to free file handles)

concurrent.futures.process._RemoteTraceback:
'''
Traceback (most recent call last):
  File "concurrent/futures/process.py", line 384, in wait_result_broken_or_wakeup
  File "multiprocessing/connection.py", line 256, in recv
TypeError: __init__() missing 1 required positional argument: 'msg'
'''

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "entry_point.py", line 69, in <module>
  File "concurrent/futures/process.py", line 559, in _chain_from_iterable_of_lists
  File "concurrent/futures/_base.py", line 608, in result_iterator
  File "concurrent/futures/_base.py", line 445, in result
  File "concurrent/futures/_base.py", line 390, in __get_result
concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.
[69850] Failed to execute script entry_point
'''

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "entry_point.py", line 69, in <module>
  File "concurrent/futures/process.py", line 559, in _chain_from_iterable_of_lists
  File "concurrent/futures/_base.py", line 608, in result_iterator
  File "concurrent/futures/_base.py", line 445, in result
  File "concurrent/futures/_base.py", line 390, in __get_result
concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.
[69655] Failed to execute script entry_point

I have permission for the folder, I think it just a bit slow in updating it, from what I see here:
https://github.com/conda/conda/blob/fc92ea3353cce71df24fac31ce333ec9f8cf7ba7/conda/gateways/disk/delete.py#L153
there is a max_retries variable, but I do not see that it is used at all. I assume if I would have managed to increase its value it will work, but as I am working with a conda.exe I am not sure how to modify/debug the code.
I also think that maybe mounting the system differently might help.
Any IDEAs?
(I've opened this ticket in conda github, no repones yet)

A: Ok,
I've found the problem (when trying to move an already installed version [on the same path] to the NAS].
The problem is I was missing the mfsymlinks option for the CIFS mount options in /etc/fstab
Hope it helps anyone in the future


text:
Q: Jquery click function not loading new content For some reason jquery does not load the new html into the #textoPequeno div.
It actually removes the old content, that as far as it gets.
Here's the html code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link href="css/style.css" media="screen" rel="stylesheet" type="text/css">

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

                Linux Logo

Home

Home

Home

Home

Home

Opera ahora
 mas acojedor...

En su nueva versión, Opera apuesta por un nuevo diseño y pestañas visuales, un motor más veloz que incrementa su velocidad en un 40% frente a su anterior versión y un mejor soporte de estándares.

And the jquery code
    $("li a").live("click", function(){
       $("#textoPequeno").load($(this).attr('href')+' .main');
       return false;
});

Please check the live sample:
http://gabrielmeono.com/working/
EDIT:
If I remove the main from the javascript code, the page will not load inside the div. It will remain as it is.

A: get rid of + ' .main'
$("li a").live("click", function(){
   $("#textoPequeno").load( $(this).attr('href') );
   return false;
});

is fine as long as there is content at 'href' to load into #textoPequeno

A: Your code is fine, your html is wrong.
It looks like you're trying to create stand alone pages that also has the capabilities of being loaded through ajax.
You are appending ' .main' to your .load() call, which is equivalent to selecting '.main' from the returned content.  If you are doing that, all your html pages need to have an element with class='main' in it.
My suggestion would be to use id='main' instead of a class. Then change your call to: $("#textoPequeno").load($(this).attr('href')+' #main');

A: rkw's answer is correct. I would add that you could also move the #main to the actual href prop. It may not seem like much, but it will reduce some overhead and in the event your AJAX call fails (Or for a few other reasons) the user is directed to the actual href - they would be sent to the correct spot.


text:
Q: QRegExp problem I have written
QRegExp rx("");

RegExp in order to match

kind of substring in a string, in order to extract the width and height. But this does not match. Please tel me what I have done wrong.

A: \d does not match the period in your height.
A regular expression that would work would be something like:

Also, the obligatory comment that it is a bad idea to parse HTML using Regex.

A: The last \d doesn't take account of the dot inside the number, and you are missing '=' after 'height'.

A: What about :
QRexExp rx("<img src=[^<]+/\> ");

Hope it helps !


text:
Q: How to count the number of elements accessed in a list? Suppose that we have made kn total accesses to the elements in a list L of n elements, for some integer k >= 1. What are the minimum and maximum number of elements that have been accessed fewer than k times?

A: It is a mathematical problem, but I'll try to explain.
For the minimum:
Imagine that for every n number of times the list is accessed, every individual element is accessed. Then doing that k times will make sure every element is accessed k times. Minimum = 0.
For the maximum:
Just imagine that only one element is accessed every single time. Then 1 element is visited kn times and the rest 0. Maximum = n-1.
Hope that helps!


text:
Q: How to use the animate? I'm just beginner for JavaScript, but I try to do some function and I follow some guy on the internet
I'm trying to do Hide and Show the Menu.
My purpose is When I move my mouse to the Menu, it will show from bottom to up and when I move my mouse to outside it will be move slowly from up to bottom.
I can do with Click Function, but When I try with movemouse and mouseleave, it can not work.
I create 2 function
function showSelect() {
    $("#select").animate({"bottom": 0}, 300, 'linear');
}
function hideSelect() {
    $("#select").animate({"bottom": -148}, 300, 'linear');
}

And this code move my mouse :
$("#select").mousemove(function() {
    $("#select").showSelect();
}).mouseleave(function() {
    $("select").hideSelect();
});

I hope some one can give me some advices. Thanks

A: Just call the function as you're already binding element in that function to animate:
    //$("#select").showSelect();
    showSelect();

As per your requirement, I think you need mouseenter and mouseleave:
$('#select').mouseenter(function() {
    showSelect();
}).mouseleave(function(){
    hideSelect();
});

A: Here is your jsfiddle link
You need to apply following code
$( "#select" ).mouseout(function() {
 $("#select").animate({
    width: "70%",
    opacity: 0.4,
    marginLeft: "0.6in",
    fontSize: "3em",
    borderWidth: "10px"
  }, 1500 );
  });
  $( "#select" ).mouseover(function() {
 $("#select").animate({
    width: "90%",
    opacity: 0.4,
    marginLeft: "0.6in",
    fontSize: "3em",
    borderWidth: "10px"
  }, 1500 );
  });

A: Hei guy, try this:
$('#select').hover(function (){
    // when mouse hover
    showSelect();
}, function (){
    // when mouse out
    hideSelect();
});


text:
Q: How do you write the TSQL to calculate duration using the following table and data
CREATE TABLE [dbo].[AccountStatus](
[Id] [INT] NOT NULL,
[AccountId] [VARCHAR](15) NOT NULL,
[Status] [VARCHAR](15) NOT NULL,
[DateChanged] [DATETIME] NOT NULL
)

INSERT AccountStatus (Id,AccountId,Status,DateChanged) VALUES (1 , 'A', 'Imported', '1/1/2014')
INSERT AccountStatus (Id,AccountId,Status,DateChanged) VALUES (1 , 'A', 'Validated', '1/12/2014')
INSERT AccountStatus (Id,AccountId,Status,DateChanged) VALUES (1 , 'A', 'Contacted', '1/21/2014')
INSERT AccountStatus (Id,AccountId,Status,DateChanged) VALUES (1 , 'A', 'Qualified', '2/1/2014')
INSERT AccountStatus (Id,AccountId,Status,DateChanged) VALUES (1 , 'A', 'Closed', '2/10/2014')

How would one create output using tql showing the duration a given account was in a status?
The values are immutable and will never be updated.
I am looking for
Status | Start | End | Duration

I am have a real brain freeze.
Thanks
G

A: If I've understood your problem correctly, I would use the following approach.
Please note that the code is not tested as you did not supply data (I wrote the code "in the air").
You would be making it a lot simpler to get answers if you post DDL & Data with your questions.
--  First sequence all Statuses, on a per account basis
;WITH StatusSeq AS
(
    SELECT   Id
            ,Seq    = ROW_NUMBER() OVER (PARTITION BY AccountID ORDER BY DateChanged)
            ,AccountId
            ,[Status]
            ,DateChanged
    FROM dbo.AccountStatus
)
--  Second: Join the table to itself, so that on the right hand side
--          of the current row, you read the Status tha immediately followed
SELECT   T1.AccountID
        ,T1.[Status]
        ,StartDT    = T1.DateChanged
        ,EndDT      = T2.DateChanged
        --  I've chosen to show the date difference as days here,
        --  you may want to choose something else
        ,Duration   = DATEDIFF(DAY, T1.DateChanged, T2.DateChanged)
FROM StatusSeq  T1
JOIN StatusSeq  T2  ON T1.Seq = T2.Seq - 1

A: Assuming there is a row for Start and End:
SELECT Status,
  MIN(DateChanged) AS [Start],
  MAX(DateChanged) AS [End],
  MAX(DateChanged) - MIN(DateChanged) AS [Duration]
FROM AccountStatus
GROUP BY Status

You will have to play around with Duration using CONVERT


text:
Q: How to Search & replace in gvim the following pattern search Hi guys need solution on this i want to replace with backslash in front of the square brackets,like this if i have [0] or [9] or any number, i want to search & replace it with \[0\] or \[9\]

A: You can use this command:
:%s/\[\(\d\+\)\]/\\[\1\\]/g

A: You can also use that command:
:%s;\[\d\+\ze\];\\&\\


text:
Q: Table of content with long entry across two pages In my thesis, I have a section with a very long name, which must appear in its entirety in the table of content.
The title consists of three lines and, unfortunately, it is split in two different pages. Is there any way to fix this by putting the whole section title in the second page?
Thanks!

A: You can adopt this answer given by Karl. In case if you want the section to stay in the current page as a whole, you may use
\addtocontents{toc}{\protect\enlargethispage{\baselineskip}} % here

Change \baselineskip suitably.
Code: (adopted from linked answer):
\documentclass[12pt]{book}

\begin{document}

\tableofcontents

\chapter{Chapter}
\section{Section}
\section{Section}
\chapter{Chapter}
\section{Section}
\subsection{Subsection}
\subsection{Subsection}
\section{Section}
\subsection{Subsection}
\subsection{Subsection}
\chapter{Chapter}
\section{Section}
\section{Section}
\chapter{Chapter}
\section{Section}
\subsection{Subsection}
\subsection{Subsection}
\section{Section}
\subsection{Subsection}
\subsection{Subsection}
\chapter{Chapter}
\section{Section}
%\addtocontents{toc}{\protect\pagebreak[4]} % here
\addtocontents{toc}{\protect\enlargethispage{\baselineskip}} % here
\section{Section that has some long lines Section that has some long lines Section that has some long lines Section that has some long lines Section that has some long lines}
\subsection{Subsection}
\subsection{Subsection}
\subsection{Subsection}

\end{document}

A: If the \documentclass is a standard class you can switch to a counterpart KOMA-Script class. These classes prevent splitting of entries in lists like the table of contents automatically. The document classes article, report, and book can be replaced by scrartcl, scrreprt, and scrbook, respectively.
(Because KOMA-Script uses styles for the headings that differ from the styles in the standard classes, it is advisable to load the class with the headings=standardclasses option if the old familiar appearance is desired.)


text:
Q: Is there a way to quit Node.js and launch VIM on a file? I'm creating a simple terminal-based file manager on Node.js. Is there any way I can, from while my program is running on the terminal, quit it and open a file with VIM?

A: Simply:
require('child_process').spawn('vim', ['test.txt'], {stdio: 'inherit'});

If there is nothing left in the Node.js event loop when vim exits, then node will exit automatically as well. Or, if you need to guarantee node will exit when vim does:
var vim = require('child_process').spawn('vim', ['test.txt'], {stdio: 'inherit'});
vim.on('exit', process.exit);

As for closing the node application before vim exits, that's not really possible because vim inherits standard input/output/error streams from the spawning process (node) which are destroyed when node exits.


text:
Q: Variables in nested Foreach-Object and Where-Object I'm wondering how to work with nested Forach-Object, Where-Object and other Cmdlets in Powershell. For example this code:
$obj1 | Foreach-Object {
    $obj2 | Where-Object { $_ .... }
}

So in the code block of Foreach-Object I use the elements of $obj1 as $_. But the same happenn in the code block of Where-Object with $obj2. So how can I access both objects elements in the Where-Object code block? I would have to do $_.Arg1 -eq $_.Arg1 but this makes no sense.

A: afaik, You'll need to keep a reference to the outer loop by putting it in a local variable.
$obj1 | Foreach-Object {
    $myobj1 = $_
    $obj2 | Where-Object { $_ .... }
}

A: If the match is simple enough, you can get rid of the inner code block and avoid a local variable.
$obj1 | Foreach-Object {
    $obj2 | Where property -eq $_.property
}

e.g:
$array = ("zoom", "explorer", "notreal")
$array | foreach { get-process | where ProcessName -EQ $_ | Out-Host }

A: Another way do address this is with a slighty different foreach
ForEach($item in $obj1){
    $obj | Where-Object{$_.arg -eq $item.arg}
}

Still boils down to about_Scopes. $_ is always a reference to the current scope. As you must know ($_.Arg1 -eq $_.Arg1) would just be refering to itself.

A: You can also use scopes nowdays, e.g. a foreach inside a foreach can be accessed with $_ and the parent foreach can be accessed within the child loop using $script:_


text:
Q: Hierarchy of value classes in Scala? I have defined the following class hierarchy where I want to restrict the the type parameter to be conformable with Double...
sealed abstract class Quantity[-T](value: T)(implicit ev: T <:< Double)

case class DiscreteQuantity(value: Long) extends Quantity[Long](value)

case class ContinuousQuantity(value: Double) extends Quantity[Double](value)

...is it possible to re-write the above hierarchy so that the concrete types are value classes?  From the docs I know that value classes can not be extended, so that rules out having Quantity inherit from AnyVal.  In order for concrete classes to inherit from AnyVal I need to make Quantity a trait, which is fine, but then I lose the contra-variant annotation on the type parameter.
Thoughts?

A: It is possible, but as I said in the comment: <:< and <: don't include weak conformance, so basically only Quantity[Double] can exist.
sealed trait Quantity[-T <: Double] extends Any {
  protected[this] def value: T
}

case class ContinuousQuantity(value: Double) extends AnyVal with Quantity[Double]


text:
Q: Stored procedure within function failing because of missing values I can't figure out where my error lies here, but I'm calling this function and sending the 3 required arguments but the procedure is failing at execute.
I added a dump and die statement and it prints all 4 parameters being used in the procedure. One thing I'm concerned about is making sure all 4 things are being properly sent in as strings, as they should all be strings in the procedure.
Maybe it's something else because when I add the 4 param values manually into my IDE they successfully enter into the database. Is there an issue with how I'm sending these values?
    function createUser($out2,$email,$access){

        $type = 'web';

        $userStmt = \DB::connection('odbc')->getPdo()->prepare("call schema.insertUser(?,?,?,?)");

        $userStmt->bindParam(1, $out2, PDO::PARAM_STR,20);
        $userStmt->bindParam(2, $email, PDO::PARAM_STR,140);
        $userStmt->bindParam(3, $access, PDO::PARAM_STR, 2500);
        $userStmt->bindParam(4, $type, PDO::PARAM_STR, 20);

        dd("Out" . $out2 . "Email" . $email . "Access" . $access . "Type" . $type);
        $userStmt->execute();
    }

Dumping $userStmt
PDOStatement {#845 ▼
  +queryString: "call schema.insertuser(?,?,?,?)"
  errorInfo: array:4 [▼
    0 => ""
    1 => 0
    2 => " ((null)[0] at (null):0)"
    3 => ""
  ]
}


text:
Q: count the value is display on apache-tomcat i have try to develop count the value is displayed on my apache-tomcat console window.
here am using following code:
public class RetailerWs {
 public int data(){
int count=0;

count++;

try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/pro","root","");

    PreparedStatement statement =  con.prepareStatement("select * from orders where status='Q' AND date=CURDATE()");
     ResultSet result = statement.executeQuery();

}

      catch(Exception exc){
      System.out.println(exc.getMessage());
      }

    return count;
       }

        }

my another class is:
  public class Demo {
  public static void main(String[] args){
    RetailerWs obj = new RetailerWs();
    System.out.println(obj.data());
   }

  }

In my database have 2 values are matched above query.but the output is displayed is always 1.why dis error is occurred here.please help me what loop condition is am used here.give me some solutions.

A: You aren't actually looking at the results of your query. count is 1 because of the count++ earlier in the code.
You need something like:
while(result.next()) {
    // Do something with the row returned.
    // e.g. count += result.getInt[1]; if the first col is a count.
}

A: add this lines after execute a query.
count = 0;
while ( result.next() )
count++;


text:
Q: AlertDialog - How to update message after an event happened I am trying to show an alert dialog with a progress bar and a message showing that "Bluetooth is connecting".
I want to change that text to "Bluetooth Connected" when the connection is successful.
However, after calling the second time the alert dialog, I get an error

The specified child already has a parent. You must call removeView() on the child's parent first.

I've found several similar problems but couldn't manage to find a solution yet.
My Code:
I first call
showProgressBar("Connecting to Bluetooth...");

Then, based on the result of the callback method, I try to show again / update the alert dialog with different message
  @Override
/*
* Callback method that is triggered once we have a result about the bluetooth connection
* */
public void isBluetoothConnected(boolean isConnected)
{
    if (isConnected)
    {
        showProgressBar("CONNECTED!");
    }
    else
    {
        showProgressBar("Bluetooth Not Connected");
    }
}

And this is how I create the alert dialog
public void showProgressBar(String loadingStatus)
{
    activity.runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            if (progressDialog!=null)
            {
                progressDialog.dismiss();
            }

            progressDialog = getDialogProgressBar(loadingStatus).create();
            progressDialog.show();
        }
    });
}

public AlertDialog.Builder getDialogProgressBar(String loadingStatus)
{
    ProgressBar progressBar = new ProgressBar(context);
    if (builder == null)
    {
        builder = new AlertDialog.Builder(context);
        builder.setCancelable(false);
        builder.setMessage(loadingStatus);
        builder.setNegativeButton("Cancel", null);

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        progressBar.setLayoutParams(lp);
        builder.setView(progressBar);
    }
    return builder;
}

My question is, while the alert dialog is shown, how can I update the displayed message every time?

A: You would need to create an XML layout file containing a TextView and your progressbar instead of instantiating it in your code.
Apply your layout using dialog.setView(R.layout.yourLayout).
Then you can use dialog.findViewById(R.id.yourTextViewID) to get the desired TextView. Once you retrieved it, you can call setText(yourText) on the view.
You don't need to call dialog.setMessage(yourMessage) if you choose to go that way.
I hope this helps.
If you still hesitate, you can read this:
https://developer.android.com/guide/topics/ui/declaring-layout
Alternatively, you can setMessage on the dialog itself. (instead of builder)
https://www.google.com/url?sa=t&source=web&rct=j&url=https://stackoverflow.com/questions/16105920/refresh-or-change-the-alertdialog-message&ved=2ahUKEwjez_bI9tnoAhWtzoUKHbWNBbUQjjgwAHoECAUQAQ&usg=AOvVaw1SuAepw8YnMEtSb4Ga2yeI

A: Try this
 @Override
/*
 * Callback method that is triggered once we have a result about the bluetooth connection
 * */
public void isBluetoothConnected(boolean isConnected)
{
    if (isConnected)
    {
        showProgressBar("CONNECTED!");
    }
    else
    {
        if(progressDialog != null && progressDialog.isShowing()) {
            progressDialog.setMessage("Bluetooth Not Connected");
        } else {
            // handle
        }
    }
}


text:
Q: How to use SpriteKit Particle File in a project developed with SceneKit? I'm making a simple ARKit App with SceneKit and need to add some particle effect. Usually I could create a SceneKit Particle File, design some particle effect and use it like this
let smoke = SCNParticleSystem(named: "xxx.scnp", inDirectory: nil)!
let hole = SCNNode()
hole.addParticleSystem(smoke)

But since Xcode12, I can only create a SpritKit Particle File whose suffix is .sks. The code above could not work anymore with this file. I am a newbie in ARKit. May anyone tell me how to integrate the particle effect into my SceneKit project? Thanks a lot.

A: SpriteKit particles implementation
If you wanna use 2D particles in 3D scene, there are two regular ways to show SpriteKit scenes in SceneKit. The first way is to assign SKScene as material for SceneKit's geometry:
// 2D scene
let skScene = SKScene()

guard let emitter = SKEmitterNode(fileNamed: "sparks.sks")
else { return }

emitter.position = CGPoint(x: 10, y: 25)
emitter.targetNode = skScene
skScene.addChild(emitter)

// 3D scene
let plane = SCNPlane(width: 5, height: 5)
plane.materials.first?.diffuse.contents = skScene

let planeNode = SCNNode(geometry: plane)
sceneView.scene.rootNode.addChildNode(planeNode)

The second way – assign SKScene to virtual surrounding environment of SceneKit.
sceneView.scene.lightingEnvironment.contents = skScene

SceneKit particles implementation
The regular way for working with particles in SceneKit is its native particle system:
let particleSystem = SCNParticleSystem()
particleSystem.birthRate = 50

particleSystem.particleSize = 0.5
particleSystem.particleLifeSpan = 10
particleSystem.particleColor = .green

let particlesNode = SCNNode()
particlesNode.addParticleSystem(particleSystem)
sceneView.scene.rootNode.addChildNode(particlesNode)

P. S.
About deprecated preconfigured SCNP file and its replacement read HERE.
If you want to setup such phenomenon as 3D fire, the best way to do it – do it in Scene graph. For better result use 2 or 3 particle system objects with different parameters.
For better understanding how to setup 3D fire based on png samples (sources) open Apple Motion 5 app scene and click on Inspector button.

Then, try to implement a fire with the same look in SceneKit's Scene graph.

A: For some unknown reason Apple removed the SCNP (SceneKit particle file) template from the recent XCode editions.
You have the following options:

*

*Download any sample code project from Apple or GitHub that contains one or more .scnp files. Grab the file from there and implement it into your AR-Project. You can still edit the file within XCode as usual. (Particle Systems Editor)

*Create your particle system entirely in code.
like so:
let myParticleSystem = SCNParticleSystem()

then you configure everything you want within the instance: myParticleSystem


text:
Q: How do I check method level spring security I have implemented spring security in controller method.
Below is my spring security.xml

 -->

<!-- URL pattern based security -->
<security:http auto-config="false" entry-point-ref="authenticationEntryPoint"
    use-expressions="true">
    <custom-filter ref="authenticationFilter" position="FORM_LOGIN_FILTER" />
    <security:intercept-url access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" pattern="/common/admin/**" />
    <security:intercept-url pattern="/common/accounting/**" access="hasRole('ROLE_USER')" />
    <security:logout logout-url="/j_spring_security_logout" invalidate-session="true" logout-success-url="/login"/>

</security:http>

Below is my controller
@Secured({"ROLE_ADMIN"})
@RequestMapping(value = "/common/admin/addAdmin", method = RequestMethod.GET)
public String add(ModelMap map) {
    map.addAttribute(new Administrator());
    return "/common/admin/addAdmin";
}

@Secured({"ROLE_ADMIN"})
@RequestMapping(value = "/common/admin/addAdmin", method = RequestMethod.POST)
public String processadd(
        @ModelAttribute("administrator") Administrator administrator) {
    this.administratorManager.addAdmin(administrator);
    return "/common/admin/success";
}

I allow the url /common/admin/** for both admin and user role. But i do some restriction in the admin controller. when user is go in to /common/admin/* as a user role, he can but he can also go in to method that is only for admin role only.
How can I solve it?
Thanks!

A: You already have added the @Secured annotation.
But you need to enable it:
<!-- secured-annotations = (@Secured("ROLE_ADMIN")) -->
<!-- jsr250-annotations = (@RunAs @RolesAllowed @PermitAll @DenyAll @DeclareRoles) -->
<!-- pre-post-annotations = @PreAuthorized("hasAuthority('ROLE_ADMIN')") -->
<global-method-security
    secured-annotations="enabled"
    jsr250-annotations="disabled"
    pre-post-annotations="disabled">
</global-method-security>

@Secured can take a single or several roles.

*

*@Secured("ROLE_USER")

*@Secured({"ROLE_USER", "ROLE_ADMIN"})  //grand access if the user has one of this roles

BWT: From Spring Security 3 Book (http://www.springsecuritybook.com/):

The @Secured annotation is functionallz and syntactiallz the same as @RollesAllowed ... As @Secured functions the same as the JSR standard @RollesAllowed there's not reallz a compelling reason to use it (@Secured) in in new code...

(do not forgett to enable it jsr250-annotations="enabled")

A: I believe you could have multiple roles defined with @Secured annotation . Is this what you need?
If this is the case , try  @RolesAllowed

A: Check this FAQ. Make sure the global-method-security element is in the web context file if you want to apply security to Spring MVC controllers.
Also, you may need to enable class proxying, using
<global-method-security secured-annotations="enabled" proxy-target-class="true" />

if your controller implements an interface and the method you are securing is not part of that interface (you'll also need cglib as an additional dependency in your app for this).

A: IF you want to use annotations, better put the following in servlet.xml. There is no point of enabling the annotations n spring-security-xml as it will not take any effect.

Putting above in servlet.xml will do the trick.


text:
Q: kendo multi select drag drop selection I am using kendo-ui in my angular (1.5.1) app. I want to add drag/drop support in multiselect so that users can drag and drop selection from one multiselect to another multiselect. I have tried following kendo drag/drop guideline. The problem is multiselect datasource is not updating with removed/added value. Since server side filtering is used, whenever I programmatically try updating the multiselect value, it gets cleared. Can anyone please guide me how to attain this with some example snippets? Thanks!
Updated with code snippets that I used:
on change function in multiselect -
                    change: function (e) {
                        if (e.sender.list.length > 0) {
                            var targetElement = $(e.sender.list[0]).find('div.k-list-scroller .k-item.k-state-hover.k-state-focused.k-state-selected p')

                            if (targetElement.length > 0) {
                                //get object from datasource
                                var selectedItem = _.find(scope.unifyMultiSelect.dataItems(), function (i) {
                                    return i[scope.options.dataValueField] == targetElement[0].innerText;
                                });

                                initializeDraggable(multiSelect.tagList, selectedItem);
                            }
                        }
                    },

initializeDraggable function -
                function initializeDraggable(ul, selectedItem) {
                    $(ul).find('li:last-child').kendoDraggable({
                        group: "multiSelectGroup",
                        dataValue: selectedItem,
                        hint: function (element) {
                            scope.unifyMultiSelect.value(_.without(scope.unifyMultiSelect.dataItems(), selectedItem));
                            return element.clone();
                        }
                    });
                };

A: The issue been solved long back. Sorry for the late update. Solution I provided may not be best, but it suffices my need. Later I will try to improve it further.
In short, first I updated the datasource with blank array then updated the latest drop value inside a $timeout so the update reflects. Since the drag and drop happening between independent multiselect directive instances, I also had to pass the invoker multiselect instance to drop end so that I can update the prior instance datasource once the drop operation is complete. Snippets are below
Drop Target initialization function -
            $scope.initializeDropTarget = function () {
                $scope.unifyMultiSelect.tagList.parent().kendoDropTarget({
                    group: "multiSelectGroup",
                    drop: function (e) {
                        var parentMultiselectOptions = e.draggable.options.parentMultiselectOptions;

                        //check if drop target is different multiselect instance
                        if (parentMultiselectOptions.instanceId != $scope.options.instanceId) {
                            var item = e.draggable.options.dataValue;

                            var multiselectItems = $scope.options.getSelectedObjects();

                            var selectedItem = _.find(multiselectItems, function (i) {
                                return i[$scope.options.dataValueField] == item[$scope.options.dataValueField];
                            });

                            if (!selectedItem) {
                                multiselectItems.push(item);
                                $scope.options.setSelectedObjectValues([]);

                                $timeout(function () {
                                    $scope.options.setSelectedObjectValues(multiselectItems);
                                }, 500);

                                finalizeDraggableItem(e.draggable);
                            }
                        }
                        //if dropped to same multiselect instance
                        else {
                            finalizeDraggableItem(e.draggable);
                        }
                    }
                });
            };

finalizeDraggableItem function -
            function finalizeDraggableItem(draggable) {
                var parentMultiselectOptions = draggable.options.parentMultiselectOptions;
                var item = draggable.options.dataValue;

                var multiSelectItems = parentMultiselectOptions.getSelectedObjects();

                parentMultiselectOptions.setSelectedObjectValues([]);

                $timeout(function () {
                    var filteredItems = _.filter(multiSelectItems, function (i) {
                        return i[$scope.options.dataValueField] != item[$scope.options.dataValueField];
                    });

                    //re organize selection if dropped to same multiselect
                    if (parentMultiselectOptions.instanceId == $scope.options.instanceId) {
                        filteredItems.push(item);
                    }

                    parentMultiselectOptions.setSelectedObjectValues(filteredItems);

                    draggable.destroy();
                    draggable.element.remove();
                }, 500);
            };

initialize Draggable function -
            $scope.options.initializeDraggable = function (selectedItems, isLastElement) {
                var listElements = isLastElement ? $scope.unifyMultiSelect.tagList.find('li:last-child') : $scope.unifyMultiSelect.tagList.find('li');

                for (var i = 0; i < selectedItems.length; i++) {
                    var selectedItem = selectedItems[i];
                    var element = $(_.find(listElements, function (el) {
                        return el.innerText.trim().replace(/\s+/g, " ") == selectedItem[$scope.options.dataTextField].trim().replace(/\s+/g, " ");//remove extra spaces and check
                    }));

                    if (element.length > 0) {
                        element.kendoDraggable({
                            group: "multiSelectGroup",
                            dataValue: selectedItem,
                            parentMultiselectOptions: $scope.options,
                            hint: function (element) {
                                return element.clone();
                            }
                        });
                    }
                }
            };

Closing the issue as resolved. Please let me know if anybody needs any assistance on this. Thanks!


text:
Q: Symfony2 @UniqueEntity constraint on 2 foreign keys not working use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
@UniqueEntity({"store_id","user_id"})

php app/console doctrine:schema:update --force

Nothing to update - your database is already in sync with the current
  entity metadata.

I tried to delete and create the table again, there is no unique key created.

A: Try:
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

@UniqueEntity(fields={"store_id","user_id"})

Bear in mind the validator has nothing to do with the underlying database schema, it just validates the current state of the object. If you want to create a custom unique index consult the @UniqueConstraint annotation in doctrine:
/**
 * @Entity
 * @Table(name="ecommerce_products",uniqueConstraints={@UniqueConstraint(name="search_idx", columns={"store_id", "user_id"})})
 */
class ECommerceProduct
{
}


text:
Q: correct way of doing NOT like I am using ruby on rails 3.0.5 and I have following code
scope :foo, where('users.email NOT LIKE "%edu%"')

Will the above code work in all three databases: mysql, sqlite3 and postgresql.
Is there a better way to do that using Arel.

A: where(:conditions => ["not(users.email LIKE %?%)",'edu'])


text:
Q: Does the Web Speech API in Chrome (and Edge) use an offsite server for STT? Recently I found the Web Speech API as well as a simple HTML/JS speech-to-text example from Google.
I started playing with the API and made changes to the JS and HTML in the example above to see how it performed.  There does not appear to be any network behavior in the debugging console, however, since speech-to-text is a native API, I wonder if the browser itself makes any off-site request to a third-party server for the purpose of converting speech to text, or if it truly is built into the browser directly and would function in a completely offline environment.
Question: Is the web speech API completely private such that all voice-to-text conversion happens on a local machine, or does it make remote requests?
(I realize that this is, perhaps, only tangentially related to programming in JS/HTML... so if it is OT then please point me to where on SE that this question should be asked so I can close and move it.)


text:
Q: LSH and minhasing - Why does hashing the signature matrix make sense? I'm learning about LSH and minhashing and I'm trying to understand the rational of hashing the signature matrix:
We divide the signature matrix to bands and we hash (using which hash function?) every portion of column to k buckets. Why would it make sense? If we use a regular hash function then even a slight difference in two columns would probably lead to different buckets.
I do understand the relation between the signature matrix to Jacard distance but I don't understand the next step which is essentially hashing that distributes items evenly.


text:
Q: How do I pass a unique_ptr argument to a constructor or a function?

I'm new to move semantics in C++11 and I don't know very well how to handle unique_ptr parameters in constructors or functions. Consider this class referencing itself:
#include <memory>

class Base
{
  public:

    typedef unique_ptr<Base> UPtr;

    Base(){}
    Base(Base::UPtr n):next(std::move(n)){}

    virtual ~Base(){}

    void setNext(Base::UPtr n)
    {
      next = std::move(n);
    }

  protected :

    Base::UPtr next;

};

Is this how I should write functions taking unique_ptr arguments?
And do I need to use std::move in the calling code?
Base::UPtr b1;
Base::UPtr b2(new Base());

b1->setNext(b2); //should I write b1->setNext(std::move(b2)); instead?

A: Here are the possible ways to take a unique pointer as an argument, as well as their associated meaning.
(A) By Value
Base(std::unique_ptr<Base> n)
  : next(std::move(n)) {}

In order for the user to call this, they must do one of the following:
Base newBase(std::move(nextBase));
Base fromTemp(std::unique_ptr<Base>(new Base(...));

To take a unique pointer by value means that you are transferring ownership of the pointer to the function/object/etc in question. After newBase is constructed, nextBase is guaranteed to be empty. You don't own the object, and you don't even have a pointer to it anymore. It's gone.
This is ensured because we take the parameter by value. std::move doesn't actually move anything; it's just a fancy cast. std::move(nextBase) returns a Base&& that is an r-value reference to nextBase. That's all it does.
Because Base::Base(std::unique_ptr<Base> n) takes its argument by value rather than by r-value reference, C++ will automatically construct a temporary for us. It creates a std::unique_ptr<Base> from the Base&& that we gave the function via std::move(nextBase). It is the construction of this temporary that actually moves the value from nextBase into the function argument n.
(B) By non-const l-value reference
Base(std::unique_ptr<Base> &n)
  : next(std::move(n)) {}

This has to be called on an actual l-value (a named variable). It cannot be called with a temporary like this:
Base newBase(std::unique_ptr<Base>(new Base)); //Illegal in this case.

The meaning of this is the same as the meaning of any other use of non-const references: the function may or may not claim ownership of the pointer. Given this code:
Base newBase(nextBase);

There is no guarantee that nextBase is empty. It may be empty; it may not. It really depends on what Base::Base(std::unique_ptr<Base> &n) wants to do. Because of that, it's not very evident just from the function signature what's going to happen; you have to read the implementation (or associated documentation).
Because of that, I wouldn't suggest this as an interface.
(C) By const l-value reference
Base(std::unique_ptr<Base> const &n);

I don't show an implementation, because you cannot move from a const&. By passing a const&, you are saying that the function can access the Base via the pointer, but it cannot store it anywhere. It cannot claim ownership of it.
This can be useful. Not necessarily for your specific case, but it's always good to be able to hand someone a pointer and know that they cannot (without breaking rules of C++, like no casting away const) claim ownership of it. They can't store it. They can pass it to others, but those others have to abide by the same rules.
(D) By r-value reference
Base(std::unique_ptr<Base> &&n)
  : next(std::move(n)) {}

This is more or less identical to the "by non-const l-value reference" case. The differences are two things.

*

*You can pass a temporary:
Base newBase(std::unique_ptr<Base>(new Base)); //legal now..

*You must use std::move when passing non-temporary arguments.
The latter is really the problem. If you see this line:
Base newBase(std::move(nextBase));

You have a reasonable expectation that, after this line completes, nextBase should be empty. It should have been moved from. After all, you have that std::move sitting there, telling you that movement has occurred.
The problem is that it hasn't. It is not guaranteed to have been moved from. It may have been moved from, but you will only know by looking at the source code. You cannot tell just from the function signature.
Recommendations

*

*(A) By Value: If you mean for a function to claim ownership of a unique_ptr, take it by value.

*(C) By const l-value reference: If you mean for a function to simply use the unique_ptr for the duration of that function's execution, take it by const&. Alternatively, pass a & or const& to the actual type pointed to, rather than using a unique_ptr.

*(D) By r-value reference: If a function may or may not claim ownership (depending on internal code paths), then take it by &&. But I strongly advise against doing this whenever possible.

How to manipulate unique_ptr
You cannot copy a unique_ptr. You can only move it. The proper way to do this is with the std::move standard library function.
If you take a unique_ptr by value, you can move from it freely. But movement doesn't actually happen because of std::move. Take the following statement:
std::unique_ptr<Base> newPtr(std::move(oldPtr));

This is really two statements:
std::unique_ptr<Base> &&temporary = std::move(oldPtr);
std::unique_ptr<Base> newPtr(temporary);

(note: The above code does not technically compile, since non-temporary r-value references are not actually r-values. It is here for demo purposes only).
The temporary is just an r-value reference to oldPtr. It is in the constructor of newPtr where the movement happens. unique_ptr's move constructor (a constructor that takes a && to itself) is what does the actual movement.
If you have a unique_ptr value and you want to store it somewhere, you must use std::move to do the storage.

A: Let me try to state the different viable modes of passing pointers around to objects whose memory is managed by an instance of the std::unique_ptr class template; it also applies to the the older std::auto_ptr class template (which I believe allows all uses that unique pointer does, but for which in addition modifiable lvalues will be accepted where rvalues are expected, without having to invoke std::move), and to some extent also to std::shared_ptr.
As a concrete example for the discussion I will consider the following simple list type
struct node;
typedef std::unique_ptr<node> list;
struct node { int entry; list next; }

Instances of such list (which cannot be allowed to share parts with other instances or be circular) are entirely owned by whoever holds the initial list pointer. If client code knows that the list it stores will never be empty, it may also choose to store the first node directly rather than a list.
No destructor for node needs to be defined: since the destructors for its fields are automatically called, the whole list will be recursively deleted by the smart pointer destructor once the lifetime of initial pointer or node ends.
This recursive type gives the occasion to discuss some cases that are less visible in the case of a smart pointer to plain data. Also the functions themselves occasionally provide  (recursively) an example of client code as well. The typedef for list is of course biased towards unique_ptr, but the definition could be changed to use auto_ptr or shared_ptr instead without much need to change to what is said below (notably concerning exception safety being assured without the need to write destructors).
Modes of passing smart pointers around
Mode 0: pass a pointer or reference argument instead of a smart pointer
If your function is not concerned with ownership, this is the preferred method: don't make it take a smart pointer at all. In this case your function does not need to worry who owns the object pointed to, or by what means that ownership is managed, so passing a raw pointer is both perfectly safe, and the most flexible form, since regardless of ownership a client can always produce a raw pointer (either by calling the get method or from the address-of operator &).
For instance the function to compute the length of such list, should not be give a list argument, but a raw pointer:
size_t length(const node* p)
{ size_t l=0; for ( ; p!=nullptr; p=p->next.get()) ++l; return l; }

A client that holds a variable list head can call this function as length(head.get()),
while a client that has chosen instead to store a node n representing a non-empty list can call length(&n).
If the pointer is guaranteed to be non null (which is not the case here since lists may be empty) one might prefer to pass a reference rather than a pointer. It might be a pointer/reference to non-const if the function needs to update the contents of the node(s), without adding or removing any of them (the latter would involve ownership).
An interesting case that falls in the mode 0 category is making a (deep) copy of the list; while a function doing this must of course transfer ownership of the copy it creates, it is not concerned with the ownership of the list it is copying. So it could be defined as follows:
list copy(const node* p)
{ return list( p==nullptr ? nullptr : new node{p->entry,copy(p->next.get())} ); }

This code merits a close look, both for the question as to why it compiles at all (the result of the recursive call to copy in the initialiser list binds to the rvalue reference argument in the move constructor of unique_ptr<node>, a.k.a. list, when initialising the next field of the generated node), and for the question as to why it is exception-safe (if during the recursive allocation process memory runs out and some call of new throws std::bad_alloc, then at that time a pointer to the partly constructed list is held anonymously in a temporary of type list created for the initialiser list, and its destructor will clean up that partial list). By the way one should resist the temptation to replace (as I initially did) the second nullptr by p, which after all is known to be null at that point: one cannot construct a smart pointer from a (raw) pointer to constant, even when it is known to be null.
Mode 1: pass a smart pointer by value
A function that takes a smart pointer value as argument takes possession of the object pointed to right away: the smart pointer that the caller held (whether in a named variable or an anonymous temporary) is copied into the argument value at function entrance and the caller's pointer has become null (in the case of a temporary the copy might have been elided, but in any case the caller has lost access to the pointed to object). I would like to call this mode call by cash: caller pays up front for the service called, and can have no illusions about ownership after the call. To make this clear, the language rules require the caller to wrap the argument in std::move if the smart pointer is held in a variable (technically, if the argument is an lvalue); in this case (but not for mode 3 below) this function does what its name suggests, namely move the value from the variable to a temporary, leaving the variable null.
For cases where the called function unconditionally takes ownership of (pilfers) the pointed-to object, this mode used with std::unique_ptr or std::auto_ptr is a good way of passing a pointer together with its ownership, which avoids any risk of memory leaks. Nonetheless I think that there are only very few situations where mode 3 below is not to be preferred (ever so slightly) over mode 1. For this reason I shall provide no usage examples of this mode. (But see the reversed example of mode 3 below, where it is remarked that mode 1 would do at least as well.) If the function takes more arguments than just this pointer, it may happen that there is in addition a technical reason to avoid mode 1 (with std::unique_ptr or std::auto_ptr): since an actual move operation takes place while passing a pointer variable p by the expression std::move(p), it cannot be assumed that p holds a useful value while evaluating the other arguments (the order of evaluation being unspecified), which could lead to subtle errors; by contrast, using mode 3 assures that no move from p takes place before the function call, so other arguments can safely access a value through p.
When used with std::shared_ptr, this mode is interesting in that with a single function definition it allows the caller to choose whether to keep a sharing copy of the pointer for itself while creating a new sharing copy to be used by the function (this happens when an lvalue argument is provided; the copy constructor for shared pointers used at the call increases the reference count), or to just give the function a copy of the pointer without retaining one or touching the reference count (this happens when a rvalue argument is provided, possibly an lvalue wrapped in a call of std::move). For instance
void f(std::shared_ptr<X> x) // call by shared cash
{ container.insert(std::move(x)); } // store shared pointer in container

void client()
{ std::shared_ptr<X> p = std::make_shared<X>(args);
  f(p); // lvalue argument; store pointer in container but keep a copy
  f(std::make_shared<X>(args)); // prvalue argument; fresh pointer is just stored away
  f(std::move(p)); // xvalue argument; p is transferred to container and left null
}

The same could be achieved by separately defining void f(const std::shared_ptr<X>& x) (for the lvalue case) and void f(std::shared_ptr<X>&& x) (for the rvalue case), with function bodies differing only in that the first version invokes copy semantics (using copy construction/assignment when using x) but the second version move semantics (writing std::move(x) instead, as in the example code). So for shared pointers, mode 1 can be useful to avoid some code duplication.
Mode 2: pass a smart pointer by (modifiable) lvalue reference
Here the function just requires having a modifiable reference to the smart pointer, but gives no indication of what it will do with it. I would like to call this method call by card: caller ensures payment by giving a credit card number. The reference can be used to take ownership of the pointed-to object, but it does not have to. This mode requires providing a modifiable lvalue argument, corresponding to the fact that the desired effect of the function may include leaving a useful value in the argument variable. A caller with an rvalue expression that it wishes to pass to such a function would be forced to store it in a named variable to be able to make the call, since the language only provides implicit conversion to a constant lvalue reference (referring to a temporary) from an rvalue. (Unlike the opposite situation handled by std::move, a cast from Y&& to Y&, with Y the smart pointer type, is not possible; nonetheless this conversion could be obtained by a simple template function if really desired; see https://stackoverflow.com/a/24868376/1436796). For the case where the called function intends to unconditionally take ownership of the object, stealing from the argument, the obligation to provide an lvalue argument is giving the wrong signal: the variable will have no useful value after the call. Therefore mode 3, which gives identical possibilities inside our function but asks callers to provide an rvalue, should be preferred for such usage.
However there is a valid use case for mode 2, namely functions that may modify the pointer, or the object pointed to in a way that involves ownership. For instance, a function that prefixes a node to a list provides an example of such use:
void prepend (int x, list& l) { l = list( new node{ x, std::move(l)} ); }

Clearly it would be undesirable here to force callers to use std::move, since their smart pointer still owns a well defined and non-empty list after the call, though a different one than before.
Again it is interesting to observe what happens if the prepend call fails for lack of free memory. Then the new call will throw std::bad_alloc; at this point in time, since no node could be allocated, it is certain that the passed rvalue reference (mode 3) from std::move(l) cannot yet have been pilfered, as that would be done to construct the next field of the node that failed to be allocated. So the original smart pointer l still holds the original list when the error is thrown; that list will either be properly destroyed by the smart pointer destructor, or in case l should survive thanks to a sufficiently early catch clause, it will still hold the original list.
That was a constructive example; with a wink to this question one can also give the more destructive example of removing the first node containing a given value, if any:
void remove_first(int x, list& l)
{ list* p = &l;
  while ((*p).get()!=nullptr and (*p)->entry!=x)
    p = &(*p)->next;
  if ((*p).get()!=nullptr)
    (*p).reset((*p)->next.release()); // or equivalent: *p = std::move((*p)->next);
}

Again the correctness is quite subtle here. Notably, in the final statement the pointer (*p)->next held inside the node to be removed is unlinked (by release, which returns the pointer but makes the original null) before reset (implicitly) destroys that node (when it destroys the old value held by p), ensuring that one and only one node is destroyed at that time. (In the alternative form mentioned in the comment, this timing would be left to the internals of the implementation of the move-assignment operator of the std::unique_ptr instance list; the standard says 20.7.1.2.3;2 that this operator should act "as if by calling reset(u.release())", whence the timing should be safe here too.)
Note that prepend and remove_first cannot be called by clients who store a local node variable for an always non-empty list, and rightly so since the implementations given could not work for such cases.
Mode 3: pass a smart pointer by (modifiable) rvalue reference
This is the preferred mode to use when simply taking ownership of the pointer.  I would like to call this method call by check: caller must accept relinquishing ownership, as if providing cash, by signing the check, but the actual withdrawal is postponed until the called function actually pilfers the pointer (exactly as it would when using mode 2). The "signing of the check" concretely means callers have to wrap an argument in std::move (as in mode 1) if it is an lvalue (if it is an rvalue, the "giving up ownership" part is obvious and requires no separate code).
Note that technically mode 3 behaves exactly as mode 2, so the called function does not have to assume ownership; however I would insist that if there is any uncertainty about ownership transfer (in normal usage), mode 2 should be preferred to mode 3, so that using mode 3 is implicitly a signal to callers that they are giving up ownership. One might retort that only mode 1 argument passing really signals forced loss of ownership to callers. But if a client has any doubts about intentions of the called function, she is supposed to know the specifications of the function being called, which should remove any doubt.
It is surprisingly difficult to find a typical example involving our list type that uses mode 3 argument passing. Moving a list b to the end of another list a is a typical example; however a (which survives and holds the result of the operation) is better passed using mode 2:
void append (list& a, list&& b)
{ list* p=&a;
  while ((*p).get()!=nullptr) // find end of list a
    p=&(*p)->next;
  *p = std::move(b); // attach b; the variable b relinquishes ownership here
}

A pure example of mode 3 argument passing is the following that takes a list (and its ownership), and returns a list containing the identical nodes in reverse order.
list reversed (list&& l) noexcept // pilfering reversal of list
{ list p(l.release()); // move list into temporary for traversal
  list result(nullptr);
  while (p.get()!=nullptr)
  { // permute: result --> p->next --> p --> (cycle to result)
    result.swap(p->next);
    result.swap(p);
  }
  return result;
}

This function might be called as in l = reversed(std::move(l)); to reverse the list into itself, but the reversed list can also be used differently.
Here the argument is immediately moved to a local variable for efficiency (one could have used the parameter l directly in the place of p, but then accessing it each time would involve an extra level of indirection); hence the difference with mode 1 argument passing is minimal. In fact using that mode, the argument could have served directly as local variable, thus avoiding that initial move; this is just an instance of the general principle that if an argument passed by reference only serves to initialise a local variable, one might just as well pass it by value instead and use the parameter as local variable.
Using mode 3 appears to be advocated by the standard, as witnessed by the fact that all provided library functions that transfer ownership of smart pointers using mode 3. A particular convincing case in point is the constructor std::shared_ptr<T>(auto_ptr<T>&& p). That constructor used (in std::tr1) to take a modifiable lvalue reference (just like the auto_ptr<T>& copy constructor), and could therefore be called with an auto_ptr<T> lvalue p as in std::shared_ptr<T> q(p), after which p has been reset to null. Due to the change from mode 2 to 3 in argument passing, this old code must now be rewritten to std::shared_ptr<T> q(std::move(p)) and will then continue to work. I understand that the committee did not like the mode 2 here, but they had the option of changing to mode 1, by defining std::shared_ptr<T>(auto_ptr<T> p) instead, they could have ensured that old code works without modification, because (unlike unique-pointers) auto-pointers can be silently dereferenced to a value (the pointer object itself being reset to null in the process). Apparently the committee so much preferred advocating mode 3 over mode 1, that they chose to actively break existing code rather than to use mode 1 even for an already deprecated usage.
When to prefer mode 3 over mode 1
Mode 1 is perfectly usable in many cases, and might be preferred over mode 3 in cases where assuming ownership would otherwise takes the form of moving the smart pointer to a local variable as in the reversed example above. However, I can see two reasons to prefer mode 3 in the more general case:

*

*It is slightly more efficient to pass a reference than to create a temporary and nix the old pointer (handling cash is somewhat laborious); in some scenarios the pointer may be passed several times unchanged to another function before it is actually pilfered. Such passing will generally require writing std::move (unless mode 2 is used), but note that this is just a cast that does not actually do anything (in particular no dereferencing), so it has zero cost attached.

*Should it be conceivable that anything throws an exception between the start of the function call and the point where it (or some contained call) actually moves the pointed-to object into another data structure (and this exception is not already caught inside the function itself), then when using mode 1, the object referred to by the smart pointer will be destroyed before a catch clause can handle the exception (because the function parameter was destructed during stack unwinding), but not so when using mode 3. The latter gives the caller has the option to recover the data of the object in such cases (by catching the exception). Note that mode 1 here does not cause a memory leak, but may lead to an unrecoverable loss of data for the program, which might be undesirable as well.
Returning a smart pointer: always by value
To conclude a word about returning a smart pointer, presumably pointing to an object created for use by the caller. This is not really a case comparable with passing pointers into functions, but for completeness I would like to insist that in such cases always return by value (and don't use std::move in the return statement). Nobody wants to get a reference to a pointer that probably has just been nixed.

A: Yes you have to if you take the unique_ptr by value in the constructor. Explicity is a nice thing. Since unique_ptr is uncopyable (private copy ctor), what you wrote should give you a compiler error.

A: Edit: This answer is wrong, even though, strictly speaking, the code works. I'm only leaving it here because the discussion under it is too useful. This other answer is the best answer given at the time I last edited this: How do I pass a unique_ptr argument to a constructor or a function?
The basic idea of ::std::move is that people who are passing you the unique_ptr should be using it to express the knowledge that they know the unique_ptr they're passing in will lose ownership.
This means you should be using an rvalue reference  to a unique_ptr in your methods, not a unique_ptr itself. This won't work anyway because passing in a plain old unique_ptr would require making a copy, and that's explicitly forbidden in the interface for unique_ptr.  Interestingly enough, using a named rvalue reference turns it back into an lvalue again, so you need to use ::std::move inside your methods as well.
This means your two methods should look like this:
Base(Base::UPtr &&n) : next(::std::move(n)) {} // Spaces for readability

void setNext(Base::UPtr &&n) { next = ::std::move(n); }

Then people using the methods would do this:
Base::UPtr objptr{ new Base; }
Base::UPtr objptr2{ new Base; }
Base fred(::std::move(objptr)); // objptr now loses ownership
fred.setNext(::std::move(objptr2)); // objptr2 now loses ownership

As you see, the ::std::move expresses that the pointer is going to lose ownership at the point where it's most relevant and helpful to know. If this happened invisibly, it would be very confusing for people using your class to have objptr suddenly lose ownership for no readily apparent reason.

A: tl;dr: Do not use unique_ptr's like that.
I believe you're making a terrible mess - for those who will need to read your code, maintain it, and probably those who need to use it.
Only take unique_ptr constructor parameters if you have publicly-exposed unique_ptr members.
unique_ptr's wrap raw pointers for ownership & lifetime management. They're great for localized use - not good, nor in fact intended, for interfacing. Wanna interface? Document your new class as ownership-taking, and let it get the raw resource; or perhaps, in the case of pointers, use owner<T*> as suggested in the Core Guidelines.
Only if the purpose of your class is to hold unique_ptr's, and have others use those unique_ptr's as such - only then is it reasonable for your constructor or methods to take them.
Don't expose the fact that you use unique_ptrs internally.
Using unique_ptr for list nodes is very much an implementation detail. Actually, even the fact that you're letting users of your list-like mechanism just use the bare list node directly - constructing it themselves and giving it to you - is not a good idea IMHO. I should not need to form a new list-node-which-is-also-a-list to add something to your list - I should just pass the payload - by value, by const lvalue ref and/or by rvalue ref. Then you deal with it. And for splicing lists - again, value, const lvalue and/or rvalue.

A: Base(Base::UPtr n):next(std::move(n)) {}

should be much better as
Base(Base::UPtr&& n):next(std::forward<Base::UPtr>(n)) {}

and
void setNext(Base::UPtr n)

should be
void setNext(Base::UPtr&& n)

with same body.
And ... what is evt in handle() ??

A: To the top voted answer. I prefer passing by rvalue reference.
I understand what's the problem about passing by rvalue reference may cause. But let's divide this problem to two sides:

*

*for caller:

I must write code Base newBase(std::move(<lvalue>)) or Base newBase(<rvalue>).

*

*for callee:

Library author should guarantee it will actually move the unique_ptr to initialize member if it want own the ownership.
That's all.
If you pass by rvalue reference, it will only invoke one "move" instruction, but if pass by value, it's two.
Yep, if library author is not expert about this, he may not move unique_ptr to initialize member, but it's the problem of author, not you. Whatever it pass by value or rvalue reference, your code is same!
If you are writing a library, now you know you should guarantee it, so just do it, passing by rvalue reference is a better choice than value. Client who use you library will just write same code.
Now, for your question. How do I pass a unique_ptr argument to a constructor or a function?
You know what's the best choice.
http://scottmeyers.blogspot.com/2014/07/should-move-only-types-ever-be-passed.html


text:
Q: Convert from to string in database to boolean property Entity Framework 4.1 i am working on a legacy oracle database that uses  character literals T and F in the database for its boolean values however i would like the Entity property to reflect a proper boolen value is there a wy to convert this value when the model is binding   it is a read only database so inserts are not important

A: It's not possible. You will have to map a string property to the database table column and then use a not mapped boolean property:
public string MyStringProperty { get; set; }

[NotMapped]
public bool MyBoolProperty
{
    get { return MyStringProperty == "T"; }
    set { MyStringProperty = value ? "T" : "F"; }
}

A: I would suggest wrapping up or extending the generating type to add this sort of functionality ...
entity framework will generate objects that basically match what the data in the database tables looks like so if you have a table called "Contacts" you'll get an object called "Contacts", I think (although i could be wrong) the classes are defined as partial so it generates something like ...
public partial class Contact {
  string BoolReally {
    get; set;
  };
}

you then add a new property like this ...
public partial class Contact {
  bool MyBool get {
    return (legacyValue == "T") ? true : false;
  }
}

Now when you declare a Contact instance just fish the value from "MyBool" instead.
...
That's extending, wrapping up would be something like this ...
public class MyContact {
     public Contact Contact;
     public bool MyBool {
         get {
             return Contact.BoolAsString;
         }
     }
}

similar thing ... just need to consume the object slightly differently :)