text:
Q: embedding hyperlinks in a HTML5 video player Is there anyway to embed html hyperlinks (readable when javascript is off in the browser) within an HTML5 video player?
Maybe an embedded link within the video musing CSS, or a link in the title bar?
Thanks

A: Presumably, you're looking for something like:
<!DOCTYPE html>

<video controls='true'>
<source src='video.ogv' type='video/ogg'>
 test link
</video>

Unfortunately, this doesn't work quite the way that you expect. Per W3C:

Content may be provided inside the
  video element. User agents should not
  show this content to the user; it is
  intended for older Web browsers which
  do not support video, so that legacy
  video plugins can be tried, or to show
  text to the users of these older
  browsers informing them of how to
  access the video contents.

Thus, the content (the  tag in the example) isn't a general failover - it's just for legacy browsers. In order to handle playback errors more gracefully, you'll need to have JavaScript enabled and running on the page.
A quick and dirty solution may be to add a CSS background with some text directions, ie:
<video controls='true' style="background-image:url(image.png);width:420px;height:300px">
<source src='video.ogv' type='video/ogg'>
 test link
</video>

Unfortunately, wrapping the whole thing in an  tag doesn't make it linkable - you'd still need to use an onclick function with JavaScript enabled.
Hope that helps!
Best,
Zach
Developer, LongTail Video


text:
Q: How do I use Redux Toolkit with multiple React App instances? We have written a React app using Redux via Redux Toolkit. So far so fine.
Now the React app shall be rendered into multiple different elements (each element shall get a new app instance) on the same page.
The rendering part is straight forward: We just call ReactDOM.render(...) for each element.
The Redux part again brings some headache.
To create a new Redux store instance for each app instance, we call the configureStore function for each React app instance. Our slices look similiar to this:
import { createSlice } from '@reduxjs/toolkit'
import type { RootState } from '../../app/store'

// Define a type for the slice state
interface CounterState {
  value: number
}

// Define the initial state using that type
const initialState: CounterState = {
  value: 0,
}

const counterSlice = createSlice({
  name: 'counter',
  // `createSlice` will infer the state type from the `initialState` argument
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    }
  },
});

export const increment = (): AppThunk => async (
  dispatch: AppDispatch
) => {
  dispatch(indicatorsOrTopicsSlice.actions.increment());
};

export const decrement = (): AppThunk => async (
  dispatch: AppDispatch
) => {
  dispatch(indicatorsOrTopicsSlice.actions.decrement());
};

// Other code such as selectors can use the imported `RootState` type
export const selectCount = (state: RootState) => state.counter.value

export default counterSlice.reducer

Please note, that currently we create and export each slice statically and only once. Here comes my first question: Is this actually valid when creating multiple store instances or do we actually need to create also new slice instances for each app/store instance?
For the simple counter example provided, doing not so, seems to work, but as soon as we use an AsyncThunk as in the example below the whole thing breaks.
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from './userAPI'

// First, create the thunk
const fetchUserById = createAsyncThunk(
  'users/fetchByIdStatus',
  async (userId, thunkAPI) => {
    const response = await userAPI.fetchById(userId)
    return response.data
  }
)

// Then, handle actions in your reducers:
const usersSlice = createSlice({
  name: 'users',
  initialState: { entities: [], isLoading: false, hasErrors: false },
  reducers: {
    // standard reducer logic, with auto-generated action types per reducer
  },
  extraReducers: (builder) => {
    builder.addCase(fetchUserById.pending, (state, action) => {
      state.isLoading = true;
    });
    builder.addCase(fetchUserById.rejected, (state, action) => {
      state.isLoading = false;
      state.hasErrors = true;
    });
    builder.addCase(fetchUserById.fulfilled, (state, action) => {
      // Add user to the state array
      state.entities.push(action.payload);
      state.isLoading = false;
      state.hasErrors = true;
    });
  },
});

I believe the breaking starts here because of interdifferences between the events fired from dispatching the AsyncThunk.
Thereby I think the solution is to call the createAsyncThunk function for each app/store/slice instance. Are there any best practices for doing so? Of course this breaks the beauty and functionality of static exports and requires kind of a mapping, hence I'm asking.

A: My original suspicion that the AsyncThunk-part was responsible for the interferences between the stores of the different React app instances was wrong.
The source was something different not visible in the examples provided in my question.
We use memoized selectors via createSelector from reselect. Those were created and exported like the rest statically which in fact is a problem when working with multiple store/app instances. This way all instances use the same memoized selector which again doesn't work correctly thereby, since in the worst scenario the stored values of the dependency selectors are coming from the use from another store/app instance. This again can lead to endless rerenderings and recomputations.
The solution I came up with, is to create the memoized selectors for each app instance freshly. Therefore I generate a unique id for each app instance which is stored permanently in the related Redux store. When creating the store for an app instance I create also new memoized selectors instances and store them in a object which is stored in a static dictionary using the appId as the key.
To use the memoized selectors in our components I wrote a hook which uses React.memo:
import { useMemo } from "react";
import { useSelector } from "react-redux";
import { selectAppId } from "../redux/appIdSlice";
import { getMemoizedSelectors } from "../redux/memoizedSelectors";

// Hook for using created memoized selectors
export const useMemoizedSelectors = () => {
  const appId = useSelector(selectAppId);
  const allMemoizedSelectors = useMemo(() => {
    return getMemoizedSelectors(appId);
  }, [appId]);

  return allMemoizedSelectors;
};

Then the selectors can be used in the components like this:
function MyComponent(): ReactElement {
  const {
    selectOpenTodos,
  } = useMemoizedSelectors().todos;
  const openTodos = useSelector(selectOpenTodos);
  // ...
}

and the related dictionary and lookup process would look like this:
import { createTodosMemoizedSelectors } from "./todosSlice";

/**
 * We must create and store memoized selectors for each app instance on its own,
 * else they will not work correctly, because memoized value would be used for all instances.
 * This dictionary holds for each appId (the key) the related created memoized selectors.
 */
const memoizedSelectors: {
  [key: string]: ReturnType<typeof createMemoizedSelectors>;
} = {};

/**
 * Calls createMemoizedSelectors for all slices providing
 * memoizedSelectors and stores resulting selectors
 * structured by slice-name in an object.
 * @returns object with freshly created memoized selectors of all slices (providing such selectors)
 */
const createMemoizedSelectors = () => ({
  todos: createTodosMemoizedSelectors(),
});

/**
 * Creates fresh memoized selectors for given appId.
 * @param appId the id of the app the memoized selectors shall be created for
 */
export const initMemoizedSelectors = (appId: string) => {
  if (memoizedSelectors[appId]) {
    console.warn(
      `Created already memoized selectors for given appId: ${appId}`
    );
    return;
  }
  memoizedSelectors[appId] = createMemoizedSelectors();
};

/**
 * Returns created memoized selectors for given appId.
 */
export const getMemoizedSelectors = (appId: string) => {
  return memoizedSelectors[appId];
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Twitter bootstrap Row nolink in a table using ajax I am using Twitter Bootstrap in my project. I am also using rowlink to make a row clickable.
It's working fine.
The problem is when I implemented ajax pagination. The new content loaded in this request didn't have appear with the link in the intire row.
Table Row Structure:

            <input type="checkbox" name="chkMovieId" value="@Model.Id">

    @Model.Title
    @Model.Descr
    @(Model.Year != 0 ? Model.Year.ToString() : string.Empty)
    @(Model.Duration != "0" ? Model.Duration+ " min" : string.Empty)
    @(Model.Avaiable ? "Yes" : "No")
    @(Model.Sold ? "Yes" : "No")


text:
Q: Jetpack wordpress JSON API is not working I have installed Jetpack Plugin and using JSON data in my iOS App.
Now Jetpack JSON Plugin is not working.
I use my website like this.
https://public-api.wordpress.com/rest/v1/sites/www.myWebsite.com/posts/

I have already connected with wordpress account.
Now Jetpack is showing error like this.
{"error":"jetpack_error","message":"The Jetpack site is inaccessible or returned an error: transport error - HTTP status code was not 200 [-32300]"}

How to solve it?

A: I used iPage Hosting for my website. Problem solved when i report it to hosting service and they fixed it.

A: I Am using TNP HOST web hosting and it worked for me .
Asked from support team and dont know exactly what they did but it worked .


text:
Q: vulnerabilities in password hashing The Python code attached receives the hash function of an input string (for example, the user's password) and generates a 156-bit Hash using MD5.What vulnerabilities that make password hashing unsuitable can exist in this code.
#
from Crypto.Hash import MD5
import binascii

def hash(msg):

# pad message to 16 bytes
if len(msg) < 16:
    msg = msg + (16 - len(msg)) * 'A'

# pick first 16 bytes
msg = msg[:16]

# converts message to upper case
msg = msg.upper()

# create MD5 objects
h1 = MD5.new()
h2 = MD5.new()

# hash two parts of message separately
h1.update(msg[:8])
h2.update(msg[8:16])

# concatenate the two hashes
h = h1.digest() + h2.digest()
return h

# print message
print(binascii.hexlify(hash("Hello, this is a great passphrase, and I am
wondering if anyone can crack it")))

A: There has been a password handling protocol in Windows called LM (LAN Manager) that had similar flaws to what we see here. I kind of feel like solving a quiz question you were supposed to do yourself... but since I enjoy it, who cares.
Going from the top:

*

*Padding is ok.

*Picking first 16 bytes is not ok. You should never reduce the entropy.

*Cutting in two is not ok. It's much easier to brute force 8 characters than 16 characters.

*Upper-case is not ok. Reduces the entropy again.

*MD5 is not ok for crypto purposes any more.

I think this is it.


text:
Q: Passing data between two android apps using intent I have two separate android apps, AppA and AppB. I am trying to get AppA to launch AppB (which is a game app). After the user is done playing the game (AppB), it will send the game records back to AppA.
So, AppA is launching AppB correctly, but when user is done with playing the game (AppB), AppB crashes while sending the data back to AppA, and this error shows up:

Process: com.joy.AppB, PID: 20265
                                                                      android.content.ActivityNotFoundException: Unable to find explicit activity class {com.joy.AppA/com.joy.AppA.views.activities.StartGameActivity}; have you declared this activity in your AndroidManifest.xml?

AppA package name : com.joy.AppA
Activity class name : com.joy.AppA.views.activities.StartGameActivity
AppB package name : com.joy.AppB
Activity class name : com.joy.AppB.MainActivity

Here is what I've done so far:
AppA's StartGameActivity:
//To launch AppB game
Intent launchGameIntent = getPackageManager().getLaunchIntentForPackage("com.joy.AppB");
startActivity(launchGameIntent);

//To retrieve game scores from AppB game
Intent intent = getIntent();
String[] gameRecords_array = intent.getStringArrayExtra("gameRecord");

AppA's AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.joy.AppA">
.
.
.
<activity
        android:name="com.joy.AppA.views.activities.StartGameActivity"
        android:label="Start Game">
        <intent-filter>
            <action android:name="android.intent.action.SEND" />
        </intent-filter>
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".views.activities.DashboardActivity" />
    </activity>

AppB's MainActivity:
Intent i = new Intent();
i.setComponent(new ComponentName("com.joy.AppA","com.joy.AppA.views.activities.StartGameActivity"));
i.setAction(Intent.ACTION_SEND);
i.putExtra("gameRecord", gameRecord_array);
startActivity(i);

AppB's AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.joy.AppB" >

<supports-screens android:resizeable="true" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@drawable/app_icon"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
.
.
.

Thanks in advance for your help!

A: Try this:
AppA's AndroidManifest.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.joy.AppA">
    .
    .
    .
    <activity
            android:name="com.joy.AppA.views.activities.StartGameActivity"
            android:label="Start Game">

            <intent-filter>
                <action android:name="com.joy.AppA.views.activities.LAUNCH_IT" />
            <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".views.activities.DashboardActivity" />

        </activity>

Then to send data to app a activity from app b, do this:
Intent i = new Intent();
i.setAction("com.joy.AppA.views.activities.LAUNCH_IT");
i.putExtra("gameRecord", gameRecord_array);
startActivity(i);

A: Maybe it can be useful:
Content Provider and Content Resolver components.
Content Resolver makes request to Content Provider, and the provider respond. This is similar to a communication between two different applications.
For example a client (Resolver) and a content manager(Provider).
This is an example tutorial: https://www.tutorialspoint.com/android/android_content_providers.htm
Hope it helps!


text:
Q: Activity Log Alerts in Azure I have created an Activity Log Alert in Azure that does a custom log search against an Application Insights instance.
The alert is working and action groups is notified through the channels I have set up.
The problem I'm having is to create that alert in the arm template we are using to deploy the resources.
When looking at the automation script in the portal the alerts are left out and is not visible. (microsoft.insights/scheduledqueryrules)
I can't find any information online on how to write the condition in the template so it works with a custom log search.
Any suggestions where to find info on how to write the condition or how to extract the template from the portal for those alerts.

A: This is an ARM template part that creates an alert with a scheduled query. It also adds an array of action groups that get notified when the alert is triggered:
{
  "name": "[parameters('scheduleQueryMonitorApplicationError')]",
  "type": "microsoft.insights/scheduledqueryrules",
  "apiVersion": "2018-04-16",
  "location": "[resourceGroup().location]",
  "tags": {
    "[concat('hidden-link:', resourceGroup().id, '/resourceGroups/', parameters('resourceGroupName'), '/providers/microsoft.insights/components/', parameters('applicationInsightsName'))]": "Resource"
  },
  "properties": {
    "description": "[parameters('scheduleQueryMonitorApplicationError')]",
    "enabled": "true",
    "source": {
      "query": "traces | where severityLevel == 3",
      "queryType": "ResultCount",
      "dataSourceId": "[resourceId('microsoft.insights/components', parameters('applicationInsightsName'))]"
    },
    "schedule": {
      "frequencyInMinutes": 5,
      "timeWindowInMinutes": 5
    },
    "action": {
      "odata.type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction",
      "severity": "3",
      "aznsAction": {
        "actionGroup": "[array( resourceId('microsoft.insights/actiongroups', parameters('actionGroupName')) )]"
      },
      "trigger": {
        "threshold": 1,
        "thresholdOperator": "GreaterThan"
      }
    }
  },
  "dependsOn": [
    "[resourceId('microsoft.insights/components', parameters('applicationInsightsName'))]"
  ]
},

A: Please see this stackoverflow thread, where a similar question was asked.  Elfocrash mentions that he wrote a blog post about that, explaining how it works. I tried his method and it works.


text:
Q: Adding tooltip to disabled Dropdown.Toggle If Dropdown.Toggle is not disabled tooltip works. When Dropdown.Toggle has the class
.disabled {
     pointer-events: none;
}.

Tooltip does not work.
I'm using the library: react-bootstrap andreact-tooltip.
Example: https://stackblitz.com/edit/react-tnh9rr
class App extends Component {
  constructor() {
    super();
    this.state = {
      disabled: true
    };
  }

  render() {
    return (
      <Dropdown className = {`${this.state.disabled  ? 'disabled' :     null}`} onClick={this.checkStatus}>
        <Dropdown.Toggle  data-tip="hello world" variant="success" id="dropdown-basic">
            Change status
        <ReactTooltip/>
        </Dropdown.Toggle>
        <Dropdown.Menu >
            <Dropdown.Item>AAAAAAA</Dropdown.Item>
        </Dropdown.Menu>
      </Dropdown>
    );
  }
}

CSS
.disabled {
    pointer-events: none;
}

A: You can directly check the state property(disabled) when the particular function is called with onClick event on Dropdown component.pointer-events: none disables all the mouse events and hence we are unable to see the tooltip as tooltip mostly gets triggered when you hover it on the button and since hover is also a kind of event in mouse no event is triggered
.


text:
Q: Depending on completion of multiple parallel gulp tasks I have a complex NodeJS application, composed from several yarn workspace packages. The following gulpconfig.ts file defines a gulp build task for the entire set of packages:
import { series, parallel, TaskFunction, src, dest } from 'gulp';
import gulpTslint from 'gulp-tslint';
import { createProject } from 'gulp-typescript';
import tslint, { Linter } from 'tslint';
import { resolve } from 'path';
import { DestOptions } from 'vinyl-fs';
import { exec } from 'child_process';
import { promisify } from 'util';

const execPromise = promisify(exec);

interface GulpTasks {
  [key: string]: TaskFunction;
}

type TaskFunctionCallback = (error?: any) => void;

class Project {
  public projectFiles: NodeJS.ReadWriteStream;
  public constructor(
    public readonly projectDirectory: string,
    public readonly sourcemaps: boolean = false,
  ) {
    this.projectFiles = src('./src/**/*.ts', { cwd: projectDirectory, sourcemaps });
  }

  public lint(): this {
    this.projectFiles = this.projectFiles.pipe(
      gulpTslint({
        tslint,
        configuration: resolve(__dirname, 'tslint.json'),
        program: Linter.createProgram(
          resolve(this.projectDirectory, 'tsconfig.json'),
          this.projectDirectory,
        ),
      }),
    );

    return this;
  }

  public build(): this {
    const opts: DestOptions = {};
    if (this.sourcemaps) {
      opts.sourcemaps = true;
    }
    this.projectFiles = this.projectFiles
      .pipe(createProject(resolve(this.projectDirectory, 'tsconfig.build.json'))())
      .pipe(dest(resolve(this.projectDirectory, 'dist'), opts));

    return this;
  }
}

const buildDatabase = (cb: TaskFunctionCallback): NodeJS.ReadWriteStream =>
  new Project(resolve(__dirname, 'server/database')).build().projectFiles;

const buildSharedCommon = (cb: TaskFunctionCallback): NodeJS.ReadWriteStream =>
  new Project(resolve(__dirname, 'shared/common')).lint().build().projectFiles;
const buildSharedFrontoffice = (cb: TaskFunctionCallback): NodeJS.ReadWriteStream =>
  new Project(resolve(__dirname, 'shared/frontoffice')).lint().build().projectFiles;
const buildSharedBackoffice = (cb: TaskFunctionCallback): NodeJS.ReadWriteStream =>
  new Project(resolve(__dirname, 'shared/backoffice')).lint().build().projectFiles;

const buildClientCommon = (cb: TaskFunctionCallback): NodeJS.ReadWriteStream =>
  new Project(resolve(__dirname, 'client/common')).lint().build().projectFiles;
const buildClientFrontoffice = async (cb: TaskFunctionCallback): Promise<unknown> =>
  execPromise('yarn run build', { cwd: 'client/frontoffice' });
const buildClientBackoffice = async (cb: TaskFunctionCallback): Promise<unknown> =>
  execPromise('yarn run build', { cwd: 'client/backoffice' });

const buildServerCommon = (cb: TaskFunctionCallback): NodeJS.ReadWriteStream =>
  new Project(resolve(__dirname, 'server/common')).lint().build().projectFiles;
const buildServerFrontoffice = (cb: TaskFunctionCallback): NodeJS.ReadWriteStream =>
  new Project(resolve(__dirname, 'server/frontoffice')).lint().build().projectFiles;
const buildServerBackoffice = (cb: TaskFunctionCallback): NodeJS.ReadWriteStream =>
  new Project(resolve(__dirname, 'server/backoffice')).lint().build().projectFiles;

const tasks: GulpTasks = {
  build: parallel(
    buildDatabase,
    series(
      buildSharedCommon,
      parallel(buildSharedBackoffice, buildSharedFrontoffice),
      parallel(
        series(buildClientCommon, parallel(buildClientFrontoffice, buildClientBackoffice)),
        series(buildServerCommon, parallel(buildServerFrontoffice, buildServerBackoffice)),
      ),
    ),
  ),
};

export = tasks;

Because of how my application is structured, the buildServerCommon depends on buildDatabase. The buildDatabase however doesn't depend on anything, and takes a long time, which is why I start it in parallel with the rest.
With the setup above though, buildDatabase may (and does) finish later than buildServerCommon starts.
How can I make buildServerCommon start only after buildDatabase and buildSharedCommon, but still have everything else start as early as possible?
Basically, in my dependency tree:

*

*I have "client", "server" and "shared" package folders.

*"{client,server,shared}/common" is required by the "frontoffice" and "backoffice" packages in that same package folder.

*"shared/{common,frontoffice,backoffice}" is required by both the "client" and "server" of the respective package.

*"server/database" is special, in that it only exists in "server", and is required by "server/common".

I tried to use
const tasks: GulpTasks = {
  build: series(
    parallel(buildSharedCommon, buildDatabase),
    parallel(buildServerCommon, buildSharedFrontoffice, buildSharedBackoffice),
    parallel(
      series(buildClientCommon, parallel(buildClientFrontoffice, buildClientBackoffice)),
      parallel(buildServerFrontoffice, buildServerBackoffice),
    ),
  ),
};

but that isn't optimal, since buildSharedFrontoffice and buildSharedBackoffice are not being compiled until buildDatabase is done, and from there the client is also needlessly delayed.

A: If you used earlier versions of Gulp, be aware that the argument ordering of serial() differs from earlier versions using task().   In particular the arguments to serial() are executed one after another in the order they are listed.
So, if you need buildDatabase to complete before buildServerCommon, they need to appear in the expected order inside the same serial function call.   I think you then need something more like this:
const tasks: GulpTasks = {
build: parallel(
    series( buildDatabase, buildServerCommon /* ... others? */ ),
    buildSharedCommon,
    buildSharedFrontoffice,
    // ... others?
    )
};

This of course assumes that buildSharedCommon and buildSharedFrontoffice have no dependencies on the message in the serial() block.
I look at it this way, in gulp 3, gulp tasks worked to figure-out the right build order from all the defined of task declaration, while in gulp 4, you have to be explicit using the new series and parallel constructs.   In that sense gulp has become more procedural than declarative.

A: I think most optimal solution is to wait for all shared packages to be built and then fork in 2 parallel branches for client and server.
const tasks: GulpTasks = {
    build: series(
        series(buildSharedCommon, parallel(buildSharedFrontoffice, buildSharedBackoffice)),
        parallel(
            series(buildClientCommon, parallel(buildClientFrontoffice, buildClientBackoffice)),
            series(buildDatabase, buildServerCommon, parallel(buildServerFrontoffice, buildServerBackoffice))
        )
    )
  };

Fastest/ideal execution path would be to spin 3 tasks in parallel, then to wait 2 out of 3 to complete, for two different continuations (client and server). That does not work out of the box with Gulp and would require your code to handle synchronization.


text:
Q: Do we put negative sign while calculating inward flux by Gauss Divergence theorem? Suppose we have a vector field $\vec A=ax\hat i + by\hat j+cz\hat k$ and we want to calculate its  inward flux $\int \vec A\cdot\vec {dS}$ over the spherical surface  $x^2+y^2+z^2=1$(with area vector directed radially inwards) by using Gauss Divergence theorem.
We do this by calculating divergence of $\vec A$ which is  $a+b+c$. Now as volume element $dτ$ doesn't have direction, how will someone tell while doing $\int (\vec\nabla\cdot\vec A)d\tau$
that we are calculating flux through outer surface or inner surface. I mean the "effect" of area vector being outward or inward in the original calculation seems to be missing. Why is this happening?
Do I have to put negative by myself to take into consideration the inward flux?

A: The Gauß-Integral-Theorem
$$
\int_V d\tau (\vec{\nabla}\cdot\vec{A})=\int_{\partial V} (d\vec{S} \cdot \vec{A}),
$$
hast the requirement that the Volume $V$ in the formula is enclosed by the surface $\partial V$, such that the direction of a small area $d\vec{S}$ is going outwards of the volume. If you want to define your $d\vec{S}$ going inwards, then the volume in the formula would be the complement (going from the surface to infinity) of the one you are using. For this infinite volume Gauß's Theorem does not hold (at least mathematically, as you need a compact volume). Also the direction of the area-vector of a closed surface is generally defined as going out of the volume which implicates everything above.
Thus
$$
\int_{\partial V} (d\vec{S} \cdot \vec{A})=\int_V d\tau (\vec{\nabla}\cdot\vec{A})=(a+b+c)\int_V d\tau=+(a+b+c)\frac{4}{3}\pi.
$$
An example where you can see that the vector of a surface has to be pointing outwards of its enclosed volume is (for $\vec{r}=(x,y,z)^T$):
$$
\int_{\partial V} (d\vec{S} \cdot \vec{r})=\int_V dV (\vec{\nabla}\cdot\vec{r})=3\int_V dV=3V>0.
$$
With $d\vec{S}\parallel\vec{r}$ follows:
$$
\hat{dS}\cdot\hat r>0\Rightarrow\hat{dS}=\hat r
$$


text:
Q: This setting managed by Administrator - error unable to fix I am seeing virus & threat protection settings on my windows with message 'This setting managed by Administrator'. With this I am unable to manipulate the real time protection.
I found solutions but none of them seem to work.

*

*Solution One - Delete registry keys for windows defender and realtime protection and restart. I am getting access denied or unable to add/remove keys error.

*Solution Two - Tried enable/disable windows defender in group policy editor but still it is showing the same error.

Please see the screenshots & screenvideos attached.
Screen video can be seen here - https://gifyu.com/image/SE9ms
Virus Threat Protection Screenshot
Error Received when tried to change registry key


text:
Q: I'm having trouble with the layout in tablet and mobile views on my portfolio and elements aren't displaying properly I'm hoping someone can help direct me with troubleshooting for my portfolio page. I'm currently having issues with a few things and I'm not sure why or how to deal with them. Whenever I try to view them in tablet/mobile views on the deployed link the layout is completely different than when I run a live server with npm start.
The first issue about section in mobile and tablet views displays each paragraph in columns and the black background doesn't cover all of the text or the image.
The second issue is the contact page doesn't display the links on mobile even though the text color is set to black and the contact header doesn't show up on the page.
It was made in React. Below will be the deployed link and link to the github.
https://refactored-potato.netlify.app/
https://github.com/GSometimes/refactored-potato
I would really appreciate any help or guidance on sorting this out.
Thank you.

A: first piece of advice is that you have used TOO MUCH CSS, please use only what you really need. You don't need every css property to use on every element.
Your text/paragraphs are showing in column as their parent's display style is set first as inline and then flex. Either don't use it or write display: block


text:
Q: Scala pattern matching fails on recursive types in 2.10 I have the following example code:
trait Recurse[T <: Recurse[T]] {
  def method = "This is a method on recurse"
}

class Foo extends Recurse[Foo] {
  override def toString = "This is a foo"
}

object Example {
  def generate: Recurse[_ /*<: Recurse[_]*/] = new Foo()
  def main(args: Array[String]) {
    val foo = generate
    foo match {
      case m: Foo => println("match: " + m)
      case _ => println("baa")
    }
    println(foo.method)
  }
}

This code compiles and runs correctly on 2.9.x (outputs "match: This is a foo" followed by "This is a method on recurse"), but it does not work on 2.10.2.  Instead I get the compile-time error: type arguments [_$1] do not conform to trait Recurse's type parameter bounds [T <: Recurse[T]]
What is interesting about this is that the problem occurs only in the pattern matcher.  If I remove the match block, the code compiles and the code outputs "This is a method on recurse".
Even more interesting is that the pattern match will still fail to compile even if the only thing in it is the default case!  The compiler simply will not accept an object with a recursive existential type for a pattern match.  However, if value of foo is specified explicitly ("val foo = new Foo()"), or if the type parameter is not recursive, then the code will compile even on 2.10.
What is going on here?  Why does this break pattern matching even if the type parameter is not involved in the match in any way?  Is there any way to rewrite this in a 2.10-compatible way?

A: This was SI-7716 and is fixed in 2.10.3 and 2.11.

A: I believe this is a regression in the Scala compiler. Why not file it?


text:
Q: Why doesn't my Textbox react on IsMouseOver in the Style for the ControlTemplate So I am trying to style my TextBox a little bit, the idea was that I wanted to style the BorderBrush when hovering over the TextBox but for some reason it didnt change the Border, so I tried changing the Background as well, and same thing there. That's when I realized it doesnt react to the IsMouseOver but it does set the background and everything else that I did, it's just the event IsMouseOver that it's not reacting to.
The Control
<TextBox Width="700"
         Height="340"
         HorizontalAlignment="Right"
         Margin="0,0,230,140"
         Foreground="#8bf502"
         TextWrapping="Wrap"
         Style="{DynamicResource TextboxStyle}"/>

The Style
<Style TargetType="{x:Type TextBox}" x:Key="TextboxStyle">
    <Setter Property="OverridesDefaultStyle" Value="True"></Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="TextBox">
                <Border Background="#424242">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="BorderBrush" Value="Orange"></Setter>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

A: To change the Background of the Border, give the Border a Name and add TargetName="MyBorder" to the Setter

A: You are missing a TargetName and a BorderThickness:
<Style TargetType="{x:Type TextBox}" x:Key="TextboxStyle">
    <Setter Property="OverridesDefaultStyle" Value="True"></Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="TextBox">
                <Border Name="border" BorderThickness="2" Background="#424242">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter TargetName="border" Property="BorderBrush" Value="Orange"></Setter>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

There is no Border unless you set the BorderThickness property of it to something else than 0.

A: You are using a custom Template, but your template does not apply the border properties of the templated TextBox.  Try adding the following to the Border element in your template:
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"

There's actually a few ways you can approach this: use template bindings and put the trigger in the Style; use template bindings and put the trigger in the template; use an explicit target element and put the trigger in the template (as others here have suggested); etc.  The "right" approach depends on how/if you want the control to respond when the property is changed.  For example: if someone sets a new BorderBrush directly on the TextBox, do you want that to supersede your orange hover effect or not?  It's worth reading up on value precedence of dependency properties to understand the implications of how and where certain properties are set.
It's worth noting that your template is incomplete and won't work if you want the text to be editable (or selectable).  A TextBox expects its template to have a specially named ScrollViewer where an editable text view can be injected.  Try replacing your ContentPresenter with the following:
<ScrollViewer x:Name="PART_ContentHost"
              Padding="{TemplateBinding Padding}" />

Note that the x:Name attribute must match exactly.


text:
Q: VBA Type Mismatch Error With Range.Value and Range.Row I have the following VBA code and it seems to work partially? Sometimes it works, and sometimes it doesnt. I am getting a type mismatch error on the "If Len(c.Value) > 30 And c.Row <> 1" Then line. Any help would be great, thanks.
Sub GSSLength()
    Dim c As Range
    Dim ws As Worksheet
    Dim j As Long

    j = 0

    For Each ws In ActiveWorkbook.Worksheets
        If ws.Name Like "BOM" Then
            For Each c In ws.Range("A2:R10000")
                If Len(c.Value) > 30 And c.Row <> 1 Then
                    ws.Cells(c.Row, c.Column).Interior.ColorIndex = 3
                    j = j + 1
                End If
             Next c
        End If
    Next ws

    If j > 0 Then
        MsgBox j & " errors found where the length of cell is longer than 30 characthers, please correct in columns that are red."
    End If

End Sub

A: I'm assuming this isn't your final code..? The range you've specified will never have Row = 1 and you're using "BOM" in a Like statement that seems unnecessary. Maybe you've put this in just for this question.
Ignoring those oddities, you've probably got a cell in that range that contains an error. You can trap these out like so:
For Each ws In ActiveWorkbook.Worksheets
    If ws.Name Like "BOM" Then
        For Each c In ws.Range("A2:R10000")

            If Not (IsError(c)) Then

                If Len(c.Value) > 30 And c.Row <> 1 Then
                    ws.Cells(c.Row, c.Column).Interior.ColorIndex = 3
                    j = j + 1
                End If
            End If
         Next c
    End If
Next ws

A: Thanks for all the tips, I just noticed that I had an error in my cells where it was a number format instead of a string, and the LEN function was throwing an error there.


text:
Q: Crash when closing window in a MacOS application? I am attempting to create a functional MacOS application but with absolutely no xib or storyboard file just to see how it is done.
In the AppDelegate.m I create and show a window and set the application to terminate after last window closed:
#import "AppDelegate.h"
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)Notification {
    NSWindow *const Window = [[NSWindow alloc] initWithContentRect:(NSRect){.size = {800, 512}} styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:YES];
    [Window center];
    [Window makeKeyAndOrderFront:Window];
    // Insert code here to initialize your application
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)Sender {
    return YES;
}
@end

AppDelegate.h:
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject<NSApplicationDelegate>
@end

In the Main.m file is the following:
#import <Cocoa/Cocoa.h>
#import "AppDelegate.h"
int main(void) {
    @autoreleasepool {
        [NSApplication sharedApplication].delegate = (AppDelegate *){[[AppDelegate alloc] init]}; // I also tried using setDelegate to no avail
        [NSApp run];
    }
    return 0;
}

A window is created, but the issue is that when I close the window, the app crashes, showing an Thread 1: EXC_BAD_ACCESS (code=1, address=0x20) at the [NSApp run] line in Main.m. Somehow the application does not terminate properly and crashes instead. Clearly I am missing something but the question is what?
Edit: I noticed an odd occurance which is that the crash only occurs when ARC (Automatic Reference Counting) is enabled.

A: The problem is the window is automatically released (and thus deallocated) upon closure. This, combined with the automatic reference counting, presumably creates a sort of double free error. To solve this problem without disabling ARC or disabling releaseWhenClosed, Window is made a global or instance variable. Doing so will prevent ARC from releasing the window after already having been released by being closed.
NSWindow *Window;
// ...
- (void)applicationDidFinishLaunching:(NSNotification *)Notification {
    Window = [[NSWindow alloc] initWithContentRect:(NSRect){.size = {800, 512}} styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:YES];
    [Window center];
    [Window makeKeyAndOrderFront:Window];
    // Insert code here to initialize your application
}


text:
Q: SharePoint 2013 - Alternative ways to make Web Parts If I don't have SharePoint Designer 2013 or Visual Studio, are there are web applications I can simply install and run and experiment with,  to make custom parts for SharePoint 2013?

A: The answer is yes. You can also create a part of SharePoint 2013 or other version by html, xml and javascript. In this way you can use javascript object model (JSOM).
Follow the following links to get knowledge about that:
http://social.technet.microsoft.com/wiki/contents/articles/20764.sharepoint-2013-build-a-webpart-using-html-javascript-and-the-xml-viewer-web-part.aspx
And here are the link to reference to use JOSM:
http://msdn.microsoft.com/en-us/library/jj163201(v=office.15)
Hope this help.


text:
Q: Sorting with condition in based on negative and positive value in SSRS I am trying to sort based on below condition where I have hidden one numeric value with '-' i want to sort in a manner that however I sort (desc,asc) '-' should come on top or at the bottom but it does not affect my sorting, below goes an example
and - can be a negative or positive value
before sorting
1
2
3
-
5
6
7

after sorting
-
1
2
3
5
6
7

A: You can set the sort order expression to be something like
=Val(Fields!myColumn.Value)

This will return zero for the - row and the numeric value for the other rows.
If this does not help, edit the question (rather than add more comments) and show what the data looks like that comes from your dataset query in the report.

A: It is quite unclear what the data type of the column is, because - is not a numeric value.
However, regardless of the type, this does what you want:
order by col

If the column is a number and - is NULL, this works because an ascending sort puts NULL values first.
If the column is a string and '-' is the value, this works because '-' sorts before numbers.
Here is a db<>fiddle.

A: Sort using a CASE expression:
SELECT *
FROM yourTable
ORDER BY
    CASE WHEN col = '-' THEN 0 ELSE 1 END,
    col;

Actually, it appears that you are mixing character and numeric data in the same column.  In order to bear the value -, it must be text, so we should probably do a bit extra work to make sure the text numbers sort properly:
SELECT *
FROM yourTable
ORDER BY
    CASE WHEN col = '-' THEN 0 ELSE 1 END,
    TRY_CONVERT(NUMERIC(10), col);


text:
Q: Avoiding recomputing values in WHERE statement already computed in column list I would really love to not have to recompute values in my WHERE statement that have already been computed in the column list.
For example, I have to do this:
SELECT albumId, fnAlbumGetNumberOfPhotos(album.albumId) AS albumPhotoCount
FROM album
WHERE albumIsActive = 1
AND fnAlbumGetNumberOfPhotos(album.albumId) > 0

But would like to know why I can't do it like this, or if there are any other workarounds that don't require calling the function again:
SELECT albumId, fnAlbumGetNumberOfPhotos(album.albumId) AS albumPhotoCount
FROM album
WHERE albumIsActive = 1
AND albumPhotoCount > 0

This is a simplified version of a much more complex query, but it illustrates the problem.
Surely there must be a way to handle this without multiple function calls??
Help is greatly appreciated. Thanks

A: Use HAVING.
SELECT albumId, fnAlbumGetNumberOfPhotos(album.albumId) AS albumPhotoCount
FROM album
WHERE albumIsActive = 1
HAVING albumPhotoCount > 0

HAVING is calculated after the SELECT, when albumPhotoCount exists.


text:
Q: React Native - Require Image source with default source I am fetching a list of IDs from an API, most of which I have an associated image stored locally. However, some IDs don't have an image and thus return an error when trying to require their source.
Here is how I'm getting my source:
<Image style={{height: '100%', width: '100%'}} source={require('../assets/character-images/' + this.character.id + '.jpg'))}/>

How can I have a default fallback source? I wouldn't even mind just not loading the image if it is not found... I just can't get rid of this error. Thanks.

A: You can handle the onError event on the image, and render a different image instead. A sample component that accepts a default image can be found bellow.
export default class ImageWithFailback extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      hasError: false
    };
  }
  _onError = () => {
    this.setState({ hasError: true });
  }
  render() {
    const failBackImage = <Image source={this.props.default} style={this.props.style} />;

    if (this.state.hasError) return failBackImage;

    return (
      <Image
        {...this.props}
        onError={this._onError}
        renderIndicator={_ => failBackImage}
      />
    );
  }
}

A: Since assets you are loading are predefined in project why not simply check if you are able to load it?
Say for example you have character-images/1, character-images/2, character-images/3 then you could do something like this:
const availableCharacterIds = ['1', '2', '3']
const assetToLoad = availableCharacterIds.includes(`${this.character.id}`) ?
  require('../assets/character-images/' + this.character.id + '.jpg') : null

Then in your render JSX:
<Image style={{height: '100%', width: '100%'}} source={assetToLoad}/>

A: You could use this small function to see if the image exists, then dynamically decide to render it or not:
const tryRequire = (path) => {
  try {
   return require(`${path}`);
  } catch (err) {
   return null;
  }
};

then in your render method
{this.state.ids &&
    this.state.ids.map((id) => {
        return (
            <Image style={{height: '100%', width: '100%'}} source={this.tryRequire('../assets/character-images/' + id + '.jpg') !== null ? require('../assets/character-images/' + id + '.jpg') : require('../assets/fallbackimg.png')}/>;
        );
    })}

or if you dont want to render an img at all (no fallback img), you can simply add a filter
{this.state.ids &&
    this.state.ids
        .filter((id) => return this.tryRequire('../assets/character-images/' + id + '.jpg') === null)
        .map((id) => {
            return (
                <Image style={{height: '100%', width: '100%'}} source={this.tryRequire('../assets/character-images/' + id + '.jpg')}/>;
    );
})}

A: To dynamically check if the file is present or not you can use fs.exist and then add it to an array of available ids if its present and then while rendering you can check if id you are about to render is available or not and if its not available show the default image.
You can use code like below to check if fileExists.
checkIfFileExists=(id)=>{
RNFetchBlob.fs.exists(PATH_OF_FILE).then((exist) => {
    return exist;
})
.catch(() => return false)
}


text:
Q: Hiberante + Struts + Spring Security : Tomcat server not starting : Context Initialization Failed
Possible Duplicate:
"java.lang.NoSuchFieldError: NONE" in hibernate with Spring 3, maven, JPA, c3p0

I am trying a integration of Struts2 + Spring Security3.1.1 + Hibernate 4.1.1
While starting my tomcat server I am getting the following error:
    09 Nov 2012 11:06:52 ERROR context.ContextLoader - Context initialization failed
java.lang.NoSuchFieldError: NULL
    at org.springframework.expression.TypedValue.<clinit>(TypedValue.java:32)
    at org.springframework.expression.spel.support.StandardEvaluationContext.setRootObject(StandardEvaluationContext.java:88)
    at org.springframework.expression.spel.support.StandardEvaluationContext.<init>(StandardEvaluationContext.java:74)
    at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:124)
    at org.springframework.beans.factory.support.AbstractBeanFactory.evaluateBeanDefinitionString(AbstractBeanFactory.java:1299)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.evaluate(BeanDefinitionValueResolver.java:224)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:311)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:630)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1035)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:939)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:649)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:282)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:204)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3972)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4467)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:519)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
9 Nov, 2012 11:06:52 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.NoSuchFieldError: NULL
    at org.springframework.expression.TypedValue.<clinit>(TypedValue.java:32)
    at org.springframework.expression.spel.support.StandardEvaluationContext.setRootObject(StandardEvaluationContext.java:88)
    at org.springframework.expression.spel.support.StandardEvaluationContext.<init>(StandardEvaluationContext.java:74)
    at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:124)
    at org.springframework.beans.factory.support.AbstractBeanFactory.evaluateBeanDefinitionString(AbstractBeanFactory.java:1299)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.evaluate(BeanDefinitionValueResolver.java:224)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:311)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:630)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1035)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:939)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:649)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:282)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:204)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3972)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4467)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:519)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
9 Nov, 2012 11:06:52 AM org.apache.catalina.core.StandardContext start
SEVERE: Error listenerStart
9 Nov, 2012 11:06:52 AM org.apache.catalina.core.StandardContext start
SEVERE: Context [/PayPilotWeb] startup failed due to previous errors
9 Nov, 2012 11:06:52 AM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
log4j:ERROR LogMananger.repositorySelector was null likely due to error in class reloading, using NOPLoggerRepository.

My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:commons-context.xml</param-value>
</context-param>
<display-name> Web Application</display-name>
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter>
    <filter-name>action2-cleanup</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
</filter>
<filter>
    <filter-name>sitemesh</filter-name>
    <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
</filter>
<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>action2-cleanup</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>sitemesh</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>*.html</url-pattern>
</filter-mapping>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<session-config>
    <session-timeout>15</session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>/home.html</welcome-file>
</welcome-file-list>

Security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"

xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">

<debug />
<global-method-security pre-post-annotations="enabled" />
<http pattern="/styles/**" security="none" />
<http pattern="/images/**" security="none" />
<http pattern="/js/**" security="none" />
<http pattern="/login.html*" security="none" />
<http auto-config="true" authentication-manager-ref="authenticationManager" use-expressions="true" access-decision-manager-ref="accessDecisionManager">
    <form-login login-page='/login.html' default-target-url='/about.html' always-use-default-target='false' authentication-failure-url="/login.html?failed=true"/>
    <intercept-url pattern="/**/*.html" access="isFullyAuthenticated()" />
    <http-basic />
    <session-management invalid-session-url="/login.html">
        <concurrency-control max-sessions="1" />
    </session-management>
    <logout logout-success-url="/login.html?logout=true" logout-url="/logout.html" invalidate-session="true" delete-cookies="JSESSION" />
    <access-denied-handler ref="deniedAccessHandler" />

</http>
<authentication-manager alias="authenticationManager" >
    <authentication-provider user-service-ref="userDetailsService">
        <password-encoder ref="passwordEncoder">
             <salt-source ref="saltSource" />
        </password-encoder>
    </authentication-provider>
</authentication-manager>
<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
    <beans:constructor-arg index="0">
        <util:list>
            <beans:bean class="org.springframework.security.web.access.expression.WebExpressionVoter" />
        </util:list>
    </beans:constructor-arg>
    <beans:property name="allowIfAllAbstainDecisions" value="false" />
</beans:bean>
<beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>
<beans:bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">

    <beans:property name="userPropertyToUse" value="username" />
</beans:bean>
<beans:bean id="userDetailsService" class="com.impl.UserServiceImpl" />

commons-context.xml
    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/aop     http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<import resource="classpath:security.xml" />
<context:annotation-config />
<tx:annotation-driven />
<context:component-scan base-package="com.web" />
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean" />
<bean id="propertyConfigurer" class="org.jasypt.spring.properties.EncryptablePropertyPlaceholderConfigurer">
    <constructor-arg ref="configurationEncryptor" />
    <property name="locations">
        <list>
            <value>classpath:commons.properties</value>
        </list>
    </property>
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="searchSystemEnvironment" value="true" />
    <property name="ignoreResourceNotFound" value="true" />
    <property name="order" value="1" />
</bean>
<bean id="configurationEncryptor" class="com.PasswordEncryptor" />
<!-- Database and Hibernate Configuration %Starts-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${app.db.driverclass}" />
    <property name="url" value="${app.db.jdbcurl}" />
    <property name="username" value="${app.db.username}" />
    <property name="password" value="${app.db.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="annotatedClasses">
        <list>
            <value>com.dao.ABC</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${app.db.dailect}</prop>
            <prop key="initialSize">5</prop>
            <prop key="maxActive">${app.db.maxpoolsize}</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
        </props>
    </property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory">
        <ref bean="mySessionFactory"/>
    </property>
</bean>

POM.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>abc</groupId>
    <artifactId>abc</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>abc</name>
    <properties>
        <java-version>1.6</java-version>
        <org.springframework-version>3.1.2.RELEASE</org.springframework-version>
        <org.springsecurity-version>3.1.1.RELEASE</org.springsecurity-version>
        <org.aspectj-version>1.7.0</org.aspectj-version>
        <org.slf4j-version>1.6.1</org.slf4j-version>
        <org.struts-version>2.3.4</org.struts-version>
        <hibernate.jpa.version>2.0-cr-1</hibernate.jpa.version>
        <org.hibernate-version>3.6.0.Final</org.hibernate-version>
    </properties>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${org.springsecurity-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${org.springsecurity-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${org.springsecurity-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <scope>compile</scope>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${org.springframework-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${org.springframework-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${org.springframework-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.1.1.Final</version>
            <!-- will come with Hibernate core -->
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.2-pre4</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-jms_1.1_spec</artifactId>
            <version>1.1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <scope>compile</scope>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.jtds</groupId>
            <artifactId>jtds</artifactId>
            <version>1.2.4</version>
            <scope>compile</scope>
            <classifier/>
        </dependency>
        <dependency>
            <groupId>org.jasypt</groupId>
            <artifactId>jasypt</artifactId>
            <version>1.4</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>${org.struts-version}</version>
            <scope>compile</scope>
            <exclusions>
                <exclusion>
                    <artifactId>tools</artifactId>
                    <groupId>com.sun</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-json-plugin</artifactId>
            <version>${org.struts-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>opensymphony</groupId>
            <artifactId>sitemesh</artifactId>
            <version>2.4.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>${org.struts-version}</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>repository.springframework.maven.release</id>
            <name>Spring Framework Maven Release Repository</name>
            <url>http://maven.springframework.org/release</url>
        </repository>
        <repository>
            <id>repository.springframework.maven.milestone</id>
            <name>Spring Framework Maven Milestone Repository</name>
            <url>http://maven.springframework.org/milestone</url>
        </repository>
    </repositories>
</project>

Please help me guys.
Let me know if you need any more details from me.

A: You defined a constant
<org.springframework-version>3.1.2.RELEASE</org.springframework-version>

and use it for some of the Spring dependencies, still you defined some of them with different version:
<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-orm</artifactId>
     <version>3.1.1.RELEASE</version>
</dependency>

It is asking for troubles.
You also use Hibernate-Spring components from 2 different versions:
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory">
        <ref bean="mySessionFactory"/>
    </property>
</bean>

Look at the packages:
hibernate3 and hibernate4.
You defined constant:
<org.hibernate-version>3.6.0.Final</org.hibernate-version>

but still hardcode your Hibernate version:
 4.1.1.Final

Also note that Spring Security 3.1.X uses Spring 3.0.X
Take a look at the versions of the jars at your classpath.
Make sure you only have one version of Spring at your classpath.


text:
Q: dpkg: error: cannot stat pathname '/tmp/apt-dpkg-install-Ktak9B/14-libobjc4_12.2.0-9_amd64.deb': Too many levels of symbolic links I recently tried to update packages. I got an error, though. The error was
dpkg: error: cannot stat pathname '/tmp/apt-dpkg-install-Ktak9B/14-libobjc4_12.2.0-9_amd64.deb': Too many levels of symbolic links

Can someone help?


text:
Q: When should dimensional-reduction be used? Yesterday I asked this question in which I had 180 subjects with 500 features each. While I was sure that dimensional-reduction is a must in this case (500 features), most of the answers I got said that 500 are not too many.
So, My question is: Is there any rule of thumb when one should use dimensional-reduction before the classifier? How many features is too many? (I guess it is depends upon the ratio between the number of subjects and features. Isn't it?)

A: Rather than asking "when use" let's look at "why use" - I believe this nicely leads us to the "when" answer.
My understanding is that dimensionality reduction is mainly done to

*

*speed up learning (many features lead to longer computations) and compress data (many features take a lot of disk/memory space). In this view, you should reduce dimensions only if running time or data size is "unacceptable", and you reduce the feature space until things become "acceptable".

"Unacceptable" is, obviously, defined solely by the task at hand.  Modern computers can handle a lot of computations and store a lot of data - which is why, I think, you was told that 500 features is not too much. There are few other reasons for dimensionality reduction I can think of:

*

*matrix inversion problems - an algorithm can build a matrix from sample set, and if some features are interdependent this makes the marix non-invertible. But in practice it's not a big deal and gets circumvented via Moore-Penrose pseudoinverse so, in my view, this one should not be the reason for dimensionality reduction.

*data visualization - the rule of thumb here is to extract features until you're left with a maximum of two, due to a deficiency in human cognition :)

A: As far as I know, we don't have a rule of thumb regarding when to use dimensional reduction. I'm also thinking that, is depends upon the ratio between the number of subjects and features. Also other factors such as processing power of the system you are going to deploy your learning algorithm, might have to consider.
Further, dimensional reduction techniques such as sparse auto-encoder are capable of finding interesting patterns in the data, hence improve the accuracy of algorithms. Therefore one might think that it is always better to use a dimensional reduction method.

A: The number of features is not the only reason for reduction. It is also important to check what are these features.
Although this is a computer science oriented site, the issues of memory and run time are relevant but they shouldn't be the only focus of many of the learning tasks.
When you are selecting your features, you should have some kind of hypothesis regarding what is relevant for the task in hand. If you selected you features in a random way, or in a way that is not related to the task you wish to learn, it is OK to continue using "random" methods to reduce this number. But if you had some hypothesis about the features, I would try to keep as many of them as possible in the learning process.
In general, the better understanding you have and the better planning of your task regarding what are the best features to learn with, the better your results will be.

A: If the complexity of your model or classifier trained on those n features scales badly (e.g. the number of parameters grows as O(n^3)), then even 500 features can be a problem. Not only because the optimization takes longer, but also because you might not have enough data to constrain your parameters, which would lead to overfitting.
By reducing model complexity, dimensionality reduction can therefore also act as a means of regularization.

A: I saw another very interesting usage case for dimensionality reduction in a video from stanford a while ago. They scanned a bunch of people with a body scanner, and used that to generate 3d models. After they had a bunch of data they applied dimensionality reduction to reduce the amount of variables they had to work with. And modifying those variables allowed them to quickly change the height/weight/gender of the resulting 3d models.


text:
Q: What's the literal meaning of liftimes in a Rust function / struct definition? I've been trying to find a good explanation of Rust lifetimes. I get the idea that they are our way of telling the compiler which variables have to outlive which, so it can verify that references are non-dangling without having to check every code path. What I don't get is what we are actually saying when we use them. Take this example:
fn foo<'a>(bar: &'a i32, baz: &'a i32) -> &'a i32 {
    bar
}

fn main() {
    let m = 5;
    let x = &m;
    {
        let n = 6;
        let y = &n;
        {
            let z = foo(x, y);
            dbg!(z);
        }
        dbg!(y);
    }
    dbg!(x);
}

This compiles and runs fine. Here x, y, and z all live for different lengths of time. The underlying data, m and n, survive for different times as well. So clearly when we declared the arguments and the return value of foo to all have lifetime 'a, we weren't saying they all live for the exact same stretch of the program. (I'm trying not to say "lifetime", sorry for the awkward phrasing.)
The other interpretation that I've heard is we're saying there exists some lifetime 'a at the intersection of the lifetimes of bar, baz, and the return value. However, this would be a trivial statement, as clearly they are all in scope at the moment we call foo.
What it seems to me we are saying, is that there exists some lifetime 'a such that bar and baz outlive 'a, and the return value is outlived by 'a. This would mean that lifetime annotations have a different meaning when used on arguments versus when used on return values: it would mean that annotations on arguments are lower bounds on the lifetime and annotations on return values are upper bounds. This interpretation makes the most sense, but I have a feeling that this isn't correct either, because I think &'a T is (sort of like) a type, and it wouldn't make sense for a type to have a different meaning on arguments versus on return values. If the same notation has a different meaning in different places, then wouldn't it add a layer of impurity into the language where the same syntax can have different meanings and we just have to memorize which places it has each meaning?
So can anyone explain what lifetimes actually mean?
As a part two to this question, can we also explain what lifetimes mean in a struct definition? I'm asking for this as well because I suspect the answer is different than for function definitions. Here's an example:
struct Foo<'a> {
    bar: &'a i32
};

fn main() {
    let foo = Foo { bar: &5 };
}

Again, here it seems like we're saying that foo.bar outlives 'a and foo is outlived by 'a. So again we have this different meaning for lifetimes on the struct template parameter versus on the struct member.

A:
The other interpretation that I've heard is we're saying there exists some lifetime 'a at the intersection of the lifetimes of bar, baz, and the return value.

This seems reasonable.
You can think of that at the point of the foo(x, y) call the compiler tries to satisfy the types of the parameters with the types of the provided arguments, and "casts" implicitly if they are compatible.
You can "cast" a longer lifetime to a shorter one for a simple reference, so if lifetime of z is 'z, the compiler is able to unify the call to:
let z: &'z i32 = foo<'z>(x as &'z i32, y as &'z i32);

However, this would be a trivial statement, as clearly they are all in scope at the moment we call foo.

I wouldn't call it trivial, but indeed it is easier if you have all your code in one function to perform this scope analysis, and it is indeed performed in C/C++ and some other languages. Performing it for the whole program tree would take too long, and explicit annotations help with that. Imagine a more complex case: foo internally calls bar, bar calls baz, some intermediate structs are created and moved with those refs, those include nested structs, and what if that it is not just a linear piece of code, but async, and wraps things in Futures, and awaits them along the way...

annotations on return values are upper bounds

It doesn't have to. In your case return <'a> is the same as the lower bound, but it could be tied to &'s self or be 'static, or something else.
If your function foo accepts covariant types like x: &'a i32 and y: &'b i32 where 'a: 'b - yes, they unify to the one with a lower bound, but if your function accepts contravariant types like x: Fn(&'a i32) -> () and y: Fn(&'b i32) -> (), then it unifies to the one with an upper bound, because now foo() is responsible for calling, and if it is able to provide a longer-lived argument for both - it works for both.

So again we have this different meaning for lifetimes on the struct template parameter versus on the struct member.

The declaration of Foo<'a> just gives a name to the lifetime of bar field. When you create foo, the compiler performs inference based on the lifetimes (or scopes) of the arguments, and deduces that in that particular case for example 'a = 'static, because 5 is a constant, kind of like if you were able to manually write:
let foo = Foo<'static> { &5 as &'static i32 }

On the other hand if you create it with "z" from the previous example, it could be:
let z = ...
let foo = Foo<'z> { z as &'z i32 }

Note: there's no way to specify local code block lifetimes to hint/force compiler to use them, we can only specify it on the function boundaries or in types.

A: This link that @user4815162342 shared seems to explain what's happening pretty well. I'm going to try and paraphrase my takeaways:
First off, the lifetime is part of the type. Longer lifetimes are subtypes of shorter lifetimes (that they outlive on both ends). This makes sense because if you expect your value to live for some short lifetime, then it's certainly fine if it also lives for some longer time. Just like how if you're expecting something with the parent type Animal then it's certainly fine if it's of the more specific subtype Cat. (It's a bit more complicated than this, read that link to learn about type covariance.)
Second, you can always put subtypes into variables that expect supertypes. Say we have the type hierarchy Cat: Animal: Life. A function that takes an Animal could also take a cat, but couldn't take a Life because it may use more specific properties of Animals. (Of course in Rust we couldn't have instances of Animal and Life, but let's ignore that for now.) Conversely, a function that returns an Animal could have its return value used as a Life, but it couldn't be used as a Cat because it might not be a Cat.
Combine these two points and the behavior of a function fn foo(&'a T) -> &'a T makes sense: the value passed to the argument must be a subtype of &'a T, so it must live at least as long as 'a. The value returned can only be used as a supertype of &'a T, so it can only be assumed to live as long as 'a. Together we get that the argument outlives the return value.


text:
Q: Windows Sandbox Mapped Folder Not Working I made a sandbox configuration file with a mapped folder and some other settings, but when I open sandbox (by double clicking the config file), my mapped folder doesn't show up on the desktop of the VM.
This is my config file:
<Configuration>
<Networking>Enable</Networking>
<VGpu>Enable</VGpu>
<MappedFolders>
    <MappedFolder>
        <HostFolder>H:\Sandbox-Files\</HostFolder>
        <ReadOnly>true</ReadOnly>
    </MappedFolder>
</MappedFolders>

Can anyone tell me what I'm doing wrong?

A: So I found out I had to also add a line in the config file to specify where the folder would be located in the VM.
<Configuration>
    <Networking>Enable</Networking>
    <vGPU>Enable</vGPU>
    <MappedFolders>
        <MappedFolder>
            <HostFolder>C:\Users\flgc\Documents\projects\@planner\@work\planner_django_old_db\planner\build_production</HostFolder>
            <ReadOnly>true</ReadOnly>
            <SandboxFolder>C:\Users\WDAGUtilityAccount\Desktop\Sandbox-Files\</SandboxFolder>
        </MappedFolder>
    </MappedFolders>
</Configuration>

I had to add the SandboxFolder tag for it to work.

A: You do not HAVE TO add the  tag unless you do not want it on your desktop. If it works with it then that's great for you, but from my experience Sandbox prefers your location to not have the / after the folder at the end. My 1st one ran where maybe 1 in 5 times the mapped folder wouldn't be there & I'd just close & restart. Then I removed the trailing / & it always showed up. I wanna say it was fine at 1st but maybe an update made it stop working all the time, but that was awhile ago so I cannot say for sure


text:
Q: "Swap not available" - I must manually "swapon" after every reboot I am on Ubuntu 12.04, Thinkpad Edge 13, encrypted home. A message in the System Monitor tells me that swap is "not available". I can get it back using the swapon option in gparted (I thought I could also do sudo swapon -a in a terminal, but that does not work). The problem is that I have to swapon after every reboot. How can I switch it back on so it stays on even after a reboot?
my fstab:
# # <file system> <mount point> <type> <options> <dump> <pass>
proc /proc proc nodev,noexec,nosuid 0 0
# / was on /dev/sda5 during installation
UUID=47641b93-9d12-4e6a-b803-dde28f0e5725 / ext4 errors=remount-ro 0 1

A: After the upgrade to 12.04, certain little anomalies occurred. I was unaware my swap partition wasn't working until I tried to open a large file in Gimp.
blkid shows:
/dev/sdb6: UUID="3e0550cf-4a55-4aa8-80fa-24103c1b25a7" TYPE="swap"

but it is not active according to System Monitor. The UUID was definitely right but no go ... not sure how I got to this command:
blkid -p /dev/mapper/foo-swap_1
error: /dev/mapper/foo-swap_1: No such file or directory

File manager showed me a 0 byte icon, filename control, -- so what was supposed to be written there? By what?
sudo swapon --all --verbose yielded
swapon: cannot find the device for UUID=3e0550cf-4a55-4aa80fa-24103c1b25a7

I edited the /etc/fstab file adding
/dev/sdb6   none    swap    sw  0   0

Reboot and System Monitor shows it active.
This was the first site I found for help; in my case, the UUID did not work even though it was in fstab, so there is something missing 'in the middle'. This may help someone, who knows.

A: You have no configuration for swap in /etc/fstab. Add following line to that file:
UUID=<uuid> none   swap    sw    0       0

You have to replace <uuid> with the uuid of your swap partition. To do that, run sudo blkid
$ sudo blkid
/dev/sda1: LABEL="System Reserved" UUID="88A0D0A1A0D09752" TYPE="ntfs"
/dev/sda2: UUID="0620D9F920D9EFA3" TYPE="ntfs"
/dev/sda5: UUID="c282b418-2045-4852-8789-88a44360a0bb" TYPE="ext4"
/dev/sda6: UUID="f99c6a0c-790a-45ca-a1a9-8874f5a2999b" TYPE="ext4"
/dev/sda7: UUID="4cc2e909-ebd1-4c72-abee-aa32035bf330" TYPE="swap"

This is a list of my partitions, and as you see, /dev/sda7 is my swap partition. So you can copy the value of UUID corresponding to your swap, omitting the quotes, and use it for your fstab file.


text:
Q: Generating .class file for JVM I am working on a project that requires me to generate a java ".class" file on the go that can be later on compiled on the JVM. After learning and working with MSIL (Microsoft IL) which is also a stack based intermediate programming language, the following are the problems I am facing :

*

*As compared to the IL (for C# or VB) the java bytecode in ".class" file contains information in a structured manner and as far as i could understand the file, it contains the metadata apart from the program data, is it true?? Can i generate the same in a template form for every class file??

*Is it compulsory to generate the class file in binary??

I have refered to " Programming for the Java™ Virtual Machine By Joshua Engel " but it has not served my purpose as I have already learned about the JVm instruction set.
Can anybody please help me with this?? All help will be highly appreciated.
An example for generating a simple class file would be really helpful as i could not locate a single 1 yet.

A: Example using the ASM bytecode library converted to work with .NET using the IKVM Java-to-.NET compiler:
hello.cs:
using System;
using System.IO;
using org.objectweb.asm;

namespace test.helloWorld
{
    public class helloDump
    {

        public static byte[] dump ()
        {

            ClassWriter cw = new ClassWriter(0);
            MethodVisitor mv;

            cw.visit(Opcodes.__Fields.V1_6, Opcodes.__Fields.ACC_PUBLIC + Opcodes.__Fields.ACC_SUPER, "hello", null, "java/lang/Object", null);

            mv = cw.visitMethod(Opcodes.__Fields.ACC_PUBLIC, "<init>", "()V", null, null);
            mv.visitCode();
            mv.visitVarInsn(Opcodes.__Fields.ALOAD, 0);
            mv.visitMethodInsn(Opcodes.__Fields.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
            mv.visitInsn(Opcodes.__Fields.RETURN);
            mv.visitMaxs(1, 1);
            mv.visitEnd();

            mv = cw.visitMethod(Opcodes.__Fields.ACC_PUBLIC + Opcodes.__Fields.ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
            mv.visitCode();
            mv.visitFieldInsn(Opcodes.__Fields.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
            mv.visitLdcInsn("Hello World!");
            mv.visitMethodInsn(Opcodes.__Fields.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
            mv.visitInsn(Opcodes.__Fields.RETURN);
            mv.visitMaxs(2, 1);
            mv.visitEnd();

            cw.visitEnd();

            return cw.toByteArray();
        }

        public static void Main(string[] args)
        {
            FileStream helloWorldFile = new FileStream("hello.class", FileMode.Create);
            byte[] helloWorldClass = dump();
            helloWorldFile.Seek(0, SeekOrigin.Begin);
            helloWorldFile.Write(helloWorldClass, 0, helloWorldClass.Length);
        }
    }
}

commands:
$ ikvmc -out:org.objectweb.asm.dll -target:library -version:3.2.0.0 asm-3.2.jar
$ mcs -r:org.objectweb.asm.dll  hello.cs
$ mono hello.exe
$ ls hello.class
$ java hello

A: You may want to look at the ASM bytecode library.  It's pretty popular.  A lot of JVM languages use it: Clojure, Groovy, Jython, JRuby.
But I do agree with other postsers that it may be simpler to generate the Java source and compile it with javac to get your .class file.  Depends a lot on what you need to do.

A: Have you looked at BCEL?
http://en.wikipedia.org/wiki/Byte_Code_Engineering_Library
It's bundled with JRE now.

A: Save the following to Simple.java and do javac Simple.java from the command line (assuming you have JDK installed)
public class SimpleJava {
  public static main(String[] args) {
    System.out.println("Big Sorry, couldn't stop myself ;-)");
  }
}

That's at least a standard way to generate a simple class file ;)

A: Serious answer.
I'd auto-generate Java code and use the Java compiler to generate the class file. This look a lot easier then battling BCEL. At least because it's easier to code an algorithm in a 'higher' language than in Java Byte Code.
Any other programming language that produces byte code will do aswell, but i guess Java is one of the easiest approaches.
And coming to your questions,
(1) Yes, some metadata is pretty static. Wikipedia has a nice overview of the class file format
(2) Yes, the classfile is 'binary'. There is no alphanumerical language (like assembler) for java bytecode (at least I haven't heard of any such tool, javap can print bytecode readable but there's no way back)
Edit
Still hard to guess, what you really want to do, but just in case, you want to write a classfile around an arithmetic expression that can evaluate that arithmetic expression in a java virtual machine, then you really could start with creating a template class file.
In that case I'd code this 'evaluator' in Java and test it until it evaluates all valid inputs. I'd use a private field to hold the expression, initialised with a dummy expression.
The classfile of my Java coded evaluator would be a perfect template for the 'dynamic' class generation - I just had to find out how to 'replace' the dummy expression with a real one, recreate valid classfile (you may have to adjust some pointers because of different string lengths) and it should work.
Even if this guess is totally wrong, it may serve as case study and may help you on your way :)