text:
Q: How to Disable Material Design Style in WPF I am using Material Design in XAML to style my WPF UI controls. I defined the default theme in the App.xaml file.
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

However, I want some of my controls to have the default WPF look and feel, but it looks like the Material Design in XAML overrides the WPF default control style.
Example: The button below automatically takes its style from the Material design without specifying it.
<Button Content="Hello" Width="100"/>

How can I disable the Material Design in some controls?

A: Setting the Style property to x:Null makes it fall back to the default Style that is implemented in the framework assembly:
<Button Content="Hello" Width="100" Style="{x:Null}" />

The other option would be to remove the <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" /> from your App.xaml and explicitly set the Style property of all controls that do you want to have the Material Design look.

A: You can create an empty style inside a ResourceDict like this:
<Window.Resources>
        <ResourceDictionary>
            <Style x:Key="styleless" />
        </ResourceDictionary>
</Window.Resources>

and assign it to your button like this:
<Button Style="{StaticResource styleless}" />


text:
Q: Get Element on Scroll using Jquery i have been trying to get Element when i scroll . basically my aim is to get Element while scrolling
e.g  i have

 1

2

3

is there any way to get id of Div when i scroll to element as ids are dynamic
regards

A: I don't know if it's what you are looking for :
$("div").on('mousewheel DOMMouseScroll', function(e) {
    var id = $(this).attr("id");
    console.log(id);
})

A: You can use this code. On #parent scroll, id of element that is in screen, written in console.

$("#parent").scroll(function() {
    var winHeight = $(this).height();
    var scrollTop = $(this).scrollTop();

    $(".child").each(function(index){
        var elemHeight = $(this).height();
        var elementTop = $(this).position().top;

        if (elementTop < scrollTop + winHeight && scrollTop < elementTop + elemHeight)
           console.log($(this).attr("id"));
    });
});
#parent {
    height: 150px;
    overflow: auto;
}

.child {
    height: 300px;
}

#child1 {
    background: red;
}

#child2 {
    background: blue;
}

#child3 {
    background: green;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: duplicated animation after update to Android Jelly Beans I'm using JQuery 1.1.0 and Phonegap 1.9.0 to develop a html5 App for Android. I have a little animation which draws a battery on the canvas and updates it. It looks like a battery, which is loading. It worked very well on android 4.0.4.
Yesterday I received the update to Android 4.1.1 on my Galaxy Nexus. After that change I had issues with my animation. Now it draws to images on the canvas, one is in front and the other is behind with wrong coordinates. I think it has something to do with the Changes to Java Script Engine V8, maybe caching issues?! On every browser on my PC the animation works very well.
My html code is:
<!DOCTYPE html>

<title>Hella App</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="jquery.mobile-1.1.1.min.css"/>

Battery State

Car Data

        <canvas id="myBatteryCanvas" width="device-width"
            height="device-height">
            Sorry, your browser doesn't support canvas technology
        </canvas>

Connect

Cars

Info

My java script code, which I'm loading:
    var canvas = document.getElementById("myBatteryCanvas");
      var ctx = canvas.getContext("2d");
      var x = 50;
      var y = canvas.height - 30;
      var mx = 2;
      var my = 1;
      var WIDTH = canvas.width;
      var HEIGHT = canvas.height;
     var prozent = 1;

  function drawRect(y, farbe) {
ctx.beginPath();
ctx.rect(124, y, 50, 21);
ctx.fillStyle = farbe;
ctx.fill();

window.setTimeout("draw()", 10);
 }

 function draw() {
if (y >= 80) {
    y -= my;
    window.setTimeout("drawRect(y,'red')", 10);
} else if (y >= 50) {
    y -= my;
    window.setTimeout("drawRect(y,'orange')", 10);
    ctx.rect(124, 50 + 50, 50, 40);
    ctx.fillStyle = 'orange';
    ctx.fill();

} else {
    ctx.rect(124, 50, 50, canvas.height - 60);
    ctx.fillStyle = 'lightgreen';
    ctx.fill();
}

document.getElementById('batteryProzent').innerHTML = '> ' + prozent + ' %';
prozent++;
if (prozent % 4 == 0)
    prozent++;
 }

 function init() {
ctx.rect(122, 40, 54, 100);
ctx.fillStyle = 'floralwhite';
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = '#303030';
ctx.stroke();

draw();
 }

Another nice issue: If I use this html page as the first page to start with inside the Phonegap code, there is no problem. But if I use it inside the whole App, I'm facing the problems.
For this reason, I post my first page too:
<!DOCTYPE html>

<title> BLE App</title>

<meta name="viewport" content="width=device-width, initial-scale=1">

<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="apple-touch-icon" href="Logo.png" />

<link rel="stylesheet" href="jquery.mobile-1.1.0.min.css"/>

 BLE

    Find BLE Devices:

    Search

Connect

Cars

Info

Is there somebody with same issues? Can somebody help?
Thanks so far!
UPDATE:
I updated JQuery to 1.7.2 and JQuery Mobile to 1.1.1. But still there is no change. The animation isn't working.

A: Possible solution:
Removing the following line from jquery-mobile-css eliminates the problem:
/*content area*/
.ui-content { border-width: 0; overflow: visible; overflow-x: hidden; padding: 15px; }

(removing "overflow-x: hidden" is sufficient).
A better solution is to override the "overflow-x" attribute on the surrounding div-element (not the canvas-element itself).
Example (for battery-status):

 <canvas id="myBatteryCanvas" width="device-width" height="device-height">
    Sorry, your browser doesn't support canvas technology
 </canvas>

See also http://code.google.com/p/android/issues/detail?id=35474

A: When things go wrong when you transition from one page to another but not when you load the page itself standalone, it sounds like you need to (un)load stuff during the page transitions. jQuery Mobile loads anything inside
...
 on a page transition. That also means that anything outside these divs is ignored. Not only that, but the javascript code from the previous page still continues on to the next.
I see the two blocks of  at the bottom of the 2 HTML pages and only one of those will load, namely the one on the page that you refresh at. Make sure these scripts are loaded by inserting the the scripts inside the data-role="page divs
You should change the following

to

per the jQM documentation you shouldn't use $(document).ready(...)

A: We are having the same issue here with our phone running Android 4.1.1. We have an html5 canvas application that displays a slider. The image of the slider is displayed 2 times. On our android 4.1, 4.0, 2.3 devices it displays fine. I don't think you can workaround this defect with a simple java script change. It is simply broken in the latest Jellybean patch.
We've used Nexus S and Galaxy Nexus phones with multiple different versions of android to prove this out (it's not phone specific).


text:
Q: How do I have the nearest element to a certain element in a set? Let say that I have a set as so:
Set<DueDate> dueDates;

class DueDate{
     Date date;
}

I need to find the nearest date element that comes right after a specified date.
The set contains around a 1000 entries. Is it ok if I just iterate over the set to find the nearest date entry or I have to use some type of sort or data structure to do it in a more efficient way.

A: TreeSet is a NavigableSet implementation. Your requirements are not precise, so I'm not sure if you are looking for the higher() (strictly greater) or ceiling() (greater or equal) method, but one of those should meet your needs.


text:
Q: how to connect to an ftp server? How do I connect to an FTP server using a command prompt?
The ftp site I am trying to connect to is
ftp.bom.gov.au/anon/gen/
I used to be able to type in ftp ftp.bom.gov.au/anon/gen/ in the command prompt and it would challange me for a username and password
but now it says unknown host.
I can still get to it from a browser
ftp://ftp.bom.gov.au/anon/gen/
Is there something I am missing?
Thanks

A: You can't specify the path in the command. You should use ftp ftp.bom.gov.au and then cd /anon/gen/ to change the path.


text:
Q: Add special Character to All Wordpress Titles Is there a way to force a "#" sign to automatically be added to the beginning of all wordpress post titles?
I know you can force it to be capitalized or lowercase, etc.. but can you add a special character or word to the beginning of them all?
Thanks!

A: I think amanda was talking about all titles, not online browser's title..
You could use this function as a plugin, or in your functions.php page:
add_filter('the_title', function($title) { return '#'. $title;})

A: In your template folder search for the header.php file and then inside this file search for the <title> tag.
Now add a # right after the <title> and it will occur on all pages.


text:
Q: ¿Cómo sombrear el resto de la pantalla cuando abro un menú? Estoy tratando de sombrear el resto de la pantalla cuando abro un menú con JavaScript, el problema es que inputs, selects, buttons, etc.. no se sombrean, solamente al fondo se le aplica el sombreado. Este es mi código JavaScript para abrir y cerrar el menú:
////Function to open the menu
function openNav(element) {
    document.getElementsByTagName('html')[0].style.overflow = 'hidden';
    if(screen.width < 577) {
        document.getElementById('sideNav').style.width = '310px';
        document.body.style.backgroundColor = "rgba(0,0,0, 0.6)";
        document.body.style.transition = "0.5s";
    }
    else {
        document.getElementById('sideNav').style.width = '350px';
        document.body.style.backgroundColor = "rgba(0,0,0,0.6)";
    }
}

//Function to close the menu
function closeNav(element) {
    document.getElementsByTagName('html')[0].style.overflow = 'visible';
    document.getElementById('sideNav').style.width = '0';
    document.body.style.backgroundColor = "white";
}

Esto es el resultado que obtengo:

Espero y me puedan ayudar, gracias de antemano!!

A: Intenta mejor agregando un overlay. Para referencia puedes ver este enlace
De esta forma lo que pasará es que un div con fondo opaco semitransparente se colocará entre tu sideNav y la parte de detrás opacando todo lo demás.
Lo que tendrías que hacer es agregar en tu documento este elemento:

Con estos estilos:
#overlay {
    position: fixed;
    display: none;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 2;
    cursor: pointer;
}

Además agrega a los estilos de tu sideNav un z-index: 3;
Y en tu script cambia por esto:
function openNav(element) {
    document.getElementsByTagName('html')[0].style.overflow = 'hidden';
    if(screen.width < 577) {
        document.getElementById('sideNav').style.width = '310px';
        document.getElementById("overlay").style.display = "block";
    }
    else {
        document.getElementById('sideNav').style.width = '350px';
        document.getElementById("overlay").style.display = "block";
    }
}

function closeNav(element) {
    document.getElementsByTagName('html')[0].style.overflow = 'visible';
    document.getElementById('sideNav').style.width = '0';
    document.getElementById("overlay").style.display = "none";
}


text:
Q: ActiveRecord change column default value (not working) I've got a companies table in my database with two columns (size and state) that I wish to add default values to. Currently there is no default value and the columns are not set to null: false. I've tried using the update_column and update_column_default methods as outlined in the docs, but neither seems to be doing anything. I'm able to run the migration but there are no changes to the table.
I've tried update_column like so:
class AddDefaultValuesToCompanies < ActiveRecord::Migration
    def change
        def up
            change_column :companies, :state, :string, default: 'MA'
            change_column :companies, :size, :string, default: '1-10'
        end

        def down
            change_column :companies, :state, :string, default: nil
            change_column :companies, :size, :string, default: nil
        end
    end
end

I've also tried using update_column_default like so:
class AddDefaultValuesToCompanies < ActiveRecord::Migration
    def change
        def up
            change_column_default(:companies, :state, 'MA')
            change_column_default(:companies, :size, '1-10')
        end

        def down
            change_column_default(:companies, :state, nil)
            change_column_default(:companies, :size, nil)
        end
    end
end

What am I missing here?

A: Your migration will only change the default value for newly created records.  I would write a rake task to update the existing values in the DB.  Use something like
Companies.where(state: "").map{|c| c.update_attribute(state: "ma")


text:
Q: React-redux-router migrate to connect-react-router I build the project from https://github.com/briancappello/flask-react-spa
and try to upgrade the dependencies .
Then i got this error.
I follow the connect-react-router guide setting , then this error happened.
This error happened when create reducer ,
when initial reducer the method pass undefind ibj to reducer method
then history's createHref need get pathname from this obj
and this error happen...
Anyone can gave some advise?  Maybe is dependency issue ?
error stack

Uncaught TypeError: Cannot read property 'pathname' of undefined
      at createPath (history.js:70)
      at createHref (history.js:366)
      at eval (redux.js:361)
      at Array.forEach ()
      at assertReducerShape (redux.js:359)
      at combineReducers (redux.js:422)
      at createReducer (reducers.js?9c0a:11)
      at configureStore (configureStore.js?2ddb:35)
      at Module.eval (index.js?7df2:24)
      at eval (index.js:109)

reducer.js
import { combineReducers } from 'redux'
import { connectRouter } from 'connected-react-router'
import formReducer from 'redux-form/es/reducer'

import { loadingBarReducer } from 'react-redux-loading-bar'

import securityReducer from 'security/reducer'
import flashReducer from 'site/reducers/flash'

const createReducer = (injectedReducers) => combineReducers({
    router: connectRouter(injectedReducers),
    security: securityReducer,
    flash: flashReducer,
    form: formReducer,
    loadingBar: loadingBarReducer,

    ...injectedReducers,
})
export default createReducer

configureStore.js
import { applyMiddleware, compose, createStore } from 'redux'
import { routerMiddleware } from 'connected-react-router'
import { connectRouter } from 'connected-react-router'
import { loadingBarMiddleware } from 'react-redux-loading-bar'
import createSagaMiddleware from 'redux-saga'
import createReducer from 'reducers'
import getSagas from 'sagas'
import { flashClearMiddleware } from 'site/middleware/flash'

const isDev = process.env.NODE_ENV !== 'production'
const hasWindowObject = typeof window === 'object'

const sagaMiddleware = createSagaMiddleware()

export default function configureStore(initialState, history) {
  const middlewares = [
    sagaMiddleware,
    routerMiddleware(history),
    loadingBarMiddleware({ promiseTypeSuffixes: ['REQUEST', 'FULFILL'] }),
    flashClearMiddleware,
  ]

  const enhancers = [
    applyMiddleware(...middlewares),
  ]

  const composeEnhancers =
    isDev && hasWindowObject && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      : compose
  const store = createStore(
    createReducer(history),
    initialState,
    composeEnhancers(...enhancers)
  )

  // extensions
  store.runSaga = sagaMiddleware.run
  store.injectedReducers = {}
  store.injectedSagas = {}

  let runningSagas = sagaMiddleware.run(function *() {
    yield getSagas()
  })

  if (module.hot) {
    module.hot.accept('./reducers', () => {
      const nextCreateReducer = require('./reducers').default
      store.replaceReducer(connectRouter(history)(nextCreateReducer(store.injectedReducers)))
    })

    module.hot.accept('./sagas', () => {
      const nextGetSagas = require('./sagas').default
      runningSagas.cancel()
      runningSagas.done.then(() => {
        runningSagas = sagaMiddleware.run(function *() {
          yield nextGetSagas()
        })
      })
    })
  }

  return store
}

here is my dependencies
"dependencies": {
    "@babel/polyfill": "7.4.3",
    "@hot-loader/react-dom": "^16.8.6",
    "acorn": "^6.4.1",
    "babel-polyfill": "^6.26.0",
    "chalk": "2.4.2",
    "classnames": "^2.2.6",
    "compression": "1.7.4",
    "connected-react-router": "^6.8.0",
    "core-js": "^3.6.4",
    "date-fns": "^2.11.0",
    "fontfaceobserver": "2.1.0",
    "history": "4.9.0",
    "hoist-non-react-statics": "3.3.0",
    "immer": "3.0.0",
    "immutable": "^3.8.2",
    "intl": "1.2.5",
    "invariant": "2.2.4",
    "ip": "1.1.5",
    "isomorphic-fetch": "^2.2.1",
    "js-cookie": "^2.2.1",
    "lodash": "^4.17.15",
    "minimist": "^1.2.5",
    "normalize.css": "^8.0.1",
    "path-to-regexp": "^6.1.0",
    "prop-types": "15.7.2",
    "query-string": "^6.11.1",
    "react": "16.8.6",
    "react-bulma-components": "^3.2.0",
    "react-dom": "16.8.6",
    "react-helmet": "6.0.0-beta",
    "react-highlight": "^0.12.0",
    "react-intl": "2.8.0",
    "react-loadable": "^5.5.0",
    "react-redux": "^7.2.0",
    "react-redux-loading-bar": "^4.6.0",
    "react-router-dom": "5.0.0",
    "react-svg": "^11.0.14",
    "redux": "4.0.1",
    "redux-form": "^8.2.3",
    "redux-saga": "1.0.2",
    "reselect": "4.0.0",
    "sanitize.css": "8.0.0",
    "seamless-immutable": "^7.1.4",
    "styled-components": "4.2.0",
    "utf-8-validate": "^5.0.2",
    "warning": "^4.0.3"
  },
  "devDependencies": {
    "@types/react": "^16.9.23",
    "add-asset-html-webpack-plugin": "3.1.3",
    "canvas": "^2.6.1",
    "circular-dependency-plugin": "5.0.2",
    "compare-versions": "3.4.0",
    "compression-webpack-plugin": "2.0.0",
    "coveralls": "3.0.3",
    "css-loader": "2.1.1",
    "eslint": "5.16.0",
    "eslint-config-airbnb": "17.1.0",
    "eslint-config-airbnb-base": "13.1.0",
    "eslint-config-prettier": "4.1.0",
    "eslint-import-resolver-webpack": "0.11.1",
    "eslint-plugin-import": "2.17.2",
    "eslint-plugin-jsx-a11y": "6.2.1",
    "eslint-plugin-prettier": "3.0.1",
    "eslint-plugin-react": "7.12.4",
    "eslint-plugin-react-hooks": "1.6.0",
    "eslint-plugin-redux-saga": "1.0.0",
    "express": "^4.17.1",
    "express-http-proxy": "^1.6.0",
    "fibers": "^4.0.2",
    "file-loader": "3.0.1",
    "html-loader": "0.5.5",
    "html-webpack-plugin": "3.2.0",
    "image-webpack-loader": "4.6.0",
    "imports-loader": "0.8.0",
    "jest-cli": "24.7.1",
    "jest-dom": "3.1.3",
    "jest-styled-components": "^6.3.4",
    "jsdom": "^16.2.1",
    "json-loader": "^0.5.7",
    "lint-staged": "8.1.5",
    "ngrok": "3.1.1",
    "node-plop": "0.18.0",
    "node-sass": "^4.13.1",
    "null-loader": "0.1.1",
    "offline-plugin": "5.0.6",
    "plop": "2.3.0",
    "pre-commit": "1.2.2",
    "prettier": "1.17.0",
    "react-app-polyfill": "0.2.2",
    "react-hot-loader": "^4.12.20",
    "react-test-renderer": "16.8.6",
    "react-testing-library": "6.1.2",
    "redbox-react": "^1.6.0",
    "resolve-url-loader": "^3.1.1",
    "rimraf": "2.6.3",
    "sass": "^1.26.3",
    "sass-loader": "^8.0.2",
    "shelljs": "0.8.3",
    "style-loader": "0.23.1",
    "stylelint": "10.0.1",
    "stylelint-config-recommended": "2.2.0",
    "stylelint-config-styled-components": "0.1.1",
    "stylelint-processor-styled-components": "1.6.0",
    "svg-url-loader": "2.3.2",
    "terser-webpack-plugin": "1.2.3",
    "url-loader": "1.1.2",
    "webpack": "^4.42.1",
    "webpack-bundle-analyzer": "^3.6.1",
    "webpack-cli": "3.3.0",
    "webpack-dev-middleware": "3.6.2",
    "webpack-hot-middleware": "2.24.3",
    "webpack-pwa-manifest": "^4.2.0",
    "whatwg-fetch": "3.0.0"
  }

index.js
import 'babel-polyfill'

// this must come before everything else otherwise style cascading doesn't work as expected
import 'main.scss'

import { AppContainer as HotReloadContainer } from 'react-hot-loader'
import { areComponentsEqual } from 'react-hot-loader';
import React from 'react'
import ReactDOM from 'react-dom'
import {createBrowserHistory} from 'history'

import configureStore from 'configureStore'
import App from 'components/App'
import { login } from 'security/actions'
import { flashInfo } from 'site/actions'
import SecurityApi from 'security/api'
import { storage } from 'utils'

const APP_MOUNT_POINT = document.getElementById('app')

const initialState = {}
const history = createBrowserHistory()
const store = configureStore(initialState, history)

const renderRootComponent = (Component) => {
  ReactDOM.render(
    <HotReloadContainer>
      <Component store={store} history={history} />
    </HotReloadContainer>,
    APP_MOUNT_POINT
  )
}

const token = storage.getToken()
store.dispatch(login.request())
SecurityApi.checkAuthToken(token)
  .then(({ user }) => {
    store.dispatch(login.success({ token, user }))
  })
  .catch(() => {
    store.dispatch(login.failure())
  })
  .then(() => {
    store.dispatch(login.fulfill())
    renderRootComponent(App)
    const isAuthenticated = store.getState().security.isAuthenticated
    const alreadyHasFlash = store.getState().flash.visible
    if (isAuthenticated && !alreadyHasFlash) {
      store.dispatch(flashInfo('Welcome back!'))
    }
  })

if (module.hot) {
  module.hot.accept('./components/App.js', () => {
    ReactDOM.unmountComponentAtNode(APP_MOUNT_POINT)
    const NextApp = App.default
      areComponentsEqual(NextApp)
    renderRootComponent(NextApp)
  })
}

App.js
import React from 'react'
import { Provider } from 'react-redux'
import { ConnectedRouter } from 'connected-react-router'
import Helmet from 'react-helmet'
import  { history } from './index'
import { NavBar, ProgressBar } from 'components'
import { SITE_NAME, COPYRIGHT } from 'config'
import Routes from 'routes'

const AppLayout = () => (
  <div className="fixed-nav-top">
    <Helmet titleTemplate={`%s - ${SITE_NAME}`}
            defaultTitle={SITE_NAME}
    />
    <ProgressBar />
    <header>
      <NavBar />
    </header>
    <main>
      <Routes />
    </main>
    <footer className="center">
       Copyright {new Date().getFullYear()} {COPYRIGHT}
    </footer>
  </div>
)
export default (props) => (
  <Provider store={props.store}>
    <ConnectedRouter history={history}>
      <AppLayout />
    </ConnectedRouter>
  </Provider>
)

A: Please check the path of
import  { history } from './index'


text:
Q: How to configure JIRA_HOME? How to configure JIRA_HOME? I'm getting an error:

Configured jira.home '/Users/codedroid/Downloads/atlassian-jira-5.1-standalone' must not be a parent directory of the webapp servlet path '/Users/codedroid/Downloads/atlassian-jira-5.1-standalone/atlassian-jira'

Changed it and now I get this:

Configured jira.home '/Users/codedroid/Downloads/atlassian-jira-5.1-standalone/atlassian-jira' must not be the same as the webapp servlet path '/Users/codedroid/Downloads/atlassian-jira-5.1-standalone/atlassian-jira'

A: Have a look in here, if you're still having troubles please write what did you set JIRA_HOME to be and where did you defined it, thanks.
EDIT
Yea, that documentation is more of 'how to' instead of 'what'. A better explanation of what the JIRA_HOME should be is writen in more details here.
Anyway, if you feel that the documentation are confusing or just bad, you could do everyone a favour and write it at the bottom of the page, under comments, so other could see it easily.

A: The JIRA documentation does NOT! make it clear even to a seasoned programmer that this JIRA_HOME directory is referring to a data directory and not the installation directory.  If there are any JIRA folks out there please fix this outragious misunderstanding in your documentation. JAVA_HOME refers to you guessed it the installation location of java.  Its called a 'convention' if you want to invent some other meaning please say so it your documentation and don't wast valuable developer time on installing your productivity tool. Think its not a problem?  Google 'must not be the same as the webapp servlet path' and see what you get back.  Thanks for wasting my afternoon, and no doubt the time of many others.
  (warning) However, avoid locating the JIRA Home Directory inside the JIRA Installation Directory.

This appears in only documentation point and is not the first place people look as noted above

A: Just create a folder named JIRA, then set the environment variable JIRA_HOME as D:\JIRA, as well as the application properties file.
# jira-application.properties
jira.home = D:\\JIRA

Don't be confused with the JAVA_HOME, JIRA_HOME has absolutely nothing to do with the folder of your zip ball downloaded from official website.

A: JIRA_HOME is an empty folder where JIRA will create everything it needs in a RUNTIME.
It is NOT a folder where your unpacked JIRA distribution resides.
P.S. yes it is confusing still in 2021


text:
Q: How to check if a method has been called on a given jQuery selector? I'm using jasmine to conduct testing.
Basically I want to make sure that a specific method is being executed for a given jQuery selector.
e.g.
$('.hidden-tag').show()

Currently I have the following:
describe("Test", function () {
  beforeEach(function () {
    spyOn(window, '$').andCallThrough();

    loadFixtures('my_fixture.html');
  });

  it("should call show method on the jQuery selector '.hidden-tag'", function () {
    expect($).toHaveBeenCalledWith('.hidden-tag');
  });

});

The first part works. How do I get it to check that the 'show' method is being called?

A: Use :visible selector like,
alert($('.hidden-tag').is(":visible"));

Use $('.hidden-tag').is(":visible") in if condition like
if($('.hidden-tag').is(":visible"))
{
    expect($).toHaveBeenCalledWith('.hidden-tag');
}

A: Try install Fire Bug in Firefox. In that open Console and you will get if there is any error in calling 'show' method.
Also You can insert alert(message) just before and after the method. If previous alert() is not called, then problem lies somewhere before 'show' and if after alert() is not called, then 'show' got some bug.


text:
Q: Calling .length() in the for declaration is slower than doing so before the loop? In Java code, I think this:
for (int i = 0; i < s.length(); i++) {
    // do a lot of something
}

Is slower than this:
int length = s.length();
for (int i = 0; i < length; i++) {
    // do a lot of something
}

Please tell me whether I'm correct.

A: In theory the first code sample could be slower because it calls s.length() once per iteration. But it's possible that the JVM will optimize the first piece of code for you. Use the simpler approach unless benchmarks show that:

*

*You are in a performance critical piece of code.

*Storing the length in the local variable actually does give a speed up.


text:
Q: How to Loop Through Folders and Subfolders in multilevel I need to create an API with Node.js (and TypeScript just to use types, but no impact at all for this question) where the user inserts any GitHub Repo's link and the API returns via web scraping all files and their extensions, sizes and total of lines.
My code works well getting the top level files. I'm stuck with folders because they might have subfolders and more subfolders and more files inside them. And of course, there is no absolute number of how many levels it goes down nor how many files could be there.
What did I try to do so far?

*

*Recursion. The problem is it is a higher level for me and I can't handle such task.

*I prepared the code to be able to make the function call itself over and over, but it returns an error.

I'll post my code below, but if you want, feel free to get access to it at https://github.com/raphaelalvarenga/git-hub-web-scraping
This the request structure (feel free to change the repo, like searching for facebook/react or any other, for example):

This is the controller:

IMPORTANT! Note the getRowData() method being called in the line 16 passing the HTML parameter got in line 13.
This is the getRowData module. I'm stuck at lines 37 and 38 where I exactly try to use recursion passing HREF atribbute to make a new request and calling getRowData() again inside itself.

And finally, this is the error:

Just as a bonus, it's authorized the request take long time at first, but the subsequent requests shouldn't take too much to be executed. Any ideas?
Thanks for now.
EDIT:
I forgot to say that APIs to get data from GitHub aren't allowed.


text:
Q: Mongodb group by select nonexistent column I am a MongoDB novice. I am trying to group data from a document, which works. But I now want to add a column with static data in it.
For example, I could write something like this in SQL.
select e.dptId, count(e.empId), 'foo' as foo
from employee e
group by e.dptId, 'foo'

I have tried this,
db.employee.aggregate(
    { $group: {
        _id: { dptId: '$dptId', foo: 'foo' },
        empCount: { $sum: 1 }
    }}
);

which gives me "exception: field path references must be prefixed with a '$'. I cant prefix it with $, as that would be a field reference.
I have also tried this,
db.employee.aggregate(
    { $group: {
        _id: { dptId: '$dptId' },
        empCount: { $sum: 1 },
        foo: 'foo'
    }}
);

which gives me "exception: the group aggregate field 'temp' must be defined as an expression inside an object".
I have tried playing with braces, without braces (as shown) etc. Still no luck. Is it even possible in mongodb.

A: One trick would be to conditionally assign a value with the $ifNull operator:
db.employee.aggregate(
    { $group: {
        _id: { dptId: '$dptId',
               foo: { $ifNull: ['$foo', 'foo'] }
             },
        empCount: { $sum: 1 }
    }}
);

Above, it just looks for a field called foo and if it's not present, sets the foo grouped field to the value of foo. You could change the field MongoDB checks for as well.
You may be able to use $concat as well to get your desired outcome:
db.employee.aggregate(
{ $group : {
    _id : { dptId: '$dptId',
            foo: { $concat : [ "foo" ] }
          },
    empCount: { $sum: 1 }
}});


text:
Q: Xamarin Android LinkAssemblies task failed Using Visual Studio 2017 Preview 15.4.0 and the latest updates to everything as of today.
Whenever I build my project I get this error, as a workaround I have been turning linking to 'none' as suggested nearly everywhere, but this isn't a fix, and I would really appreciate some useful advice on what I can do to be able to publish this app the way it is supposed to be. The error is:

Severity  Code    Description Project File    Line    Suppression State
  Error     The "LinkAssemblies" task failed unexpectedly.
  Mono.Linker.MarkException: Error processing method: 'System.Void
  Android.Support.CustomTabs.Chromium.SharedUtilities._MobileServices.CustomTabActivityHelper::LaunchUrlWithCustomTabsOrFallback(Android.App.Activity,Android.Support.CustomTabs.CustomTabsIntent,Android.Net.Uri,Android.Support.CustomTabs.Chromium.SharedUtilities._MobileServices.ICustomTabFallback)'
  in assembly: 'Microsoft.Azure.Mobile.Client.dll' --->
  Mono.Cecil.ResolutionException: Failed to resolve System.Void
  Android.Support.CustomTabs.CustomTabsIntent::LaunchUrl(Android.App.Activity,Android.Net.Uri)
  at Mono.Linker.Steps.MarkStep.HandleUnresolvedMethod(MethodReference
  reference)    at Mono.Linker.Steps.MarkStep.MarkMethod(MethodReference
  reference)    at
  Mono.Linker.Steps.MarkStep.MarkInstruction(Instruction instruction)
  at Mono.Linker.Steps.MarkStep.MarkMethodBody(MethodBody body)    at
  Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method)
  at Mono.Linker.Steps.MarkStep.ProcessQueue()    --- End of inner
  exception stack trace ---    at
  Mono.Linker.Steps.MarkStep.ProcessQueue()    at
  Mono.Linker.Steps.MarkStep.Process()    at
  Mono.Linker.Steps.MarkStep.Process(LinkContext context)    at
  Mono.Linker.Pipeline.Process(LinkContext context)    at
  MonoDroid.Tuner.Linker.Process(LinkerOptions options, LinkContext&
  context)    at
  Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver
  res)    at Xamarin.Android.Tasks.LinkAssemblies.Execute()    at
  Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
  at
  Microsoft.Build.BackEnd.TaskBuilder.d__26.MoveNext() com.tapig.ria.quickmeme C:\Program
  Files (x86)\Microsoft Visual
  Studio\Preview\Community\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets   1591

I cannot remove this package as it is required by the Facebook. Android SDK wrapper client, but I also can't have my app size increased because of this issue, any ideas welcome.
EDIT: If I enable Android 4.4, which debugs perfectly on a device, I get this error too, under the same heading.
Mono.Linker.MarkException: Error processing method: 'System.Void Acr.UserDialogs.Fragments.AbstractDialogFragment`1::OnKeyPress(System.Object,Android.Content.DialogKeyEventArgs)' in assembly: 'Acr.UserDialogs.dll' ---> System.ArgumentNullException: Value cannot be null.
Parameter name: instruction
   at Mono.Cecil.Cil.InstructionOffset..ctor(Instruction instruction)
   at Mono.Cecil.Cil.CodeReader.ReadScope(ScopeDebugInformation scope)
   at Mono.Cecil.Cil.CodeReader.ReadScopes(Collection`1 scopes)
   at Mono.Cecil.Cil.CodeReader.ReadScope(ScopeDebugInformation scope)
   at Mono.Cecil.Cil.CodeReader.ReadScopes(Collection`1 scopes)
   at Mono.Cecil.Cil.CodeReader.ReadScope(ScopeDebugInformation scope)
   at Mono.Cecil.Cil.CodeReader.ReadDebugInfo()
   at Mono.Cecil.Cil.CodeReader.ReadMethodBody()
   at Mono.Cecil.Cil.CodeReader.ReadMethodBody(MethodDefinition method)
   at Mono.Cecil.MethodDefinition.<>c.<get_Body>b__41_0(MethodDefinition method, MetadataReader reader)
   at Mono.Cecil.ModuleDefinition.Read[TItem,TRet](TRet& variable, TItem item, Func`3 read)
   at Mono.Cecil.MethodDefinition.get_Body()
   at Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method)
   at Mono.Linker.Steps.MarkStep.ProcessQueue()
   --- End of inner exception stack trace ---
   at Mono.Linker.Steps.MarkStep.ProcessQueue()
   at Mono.Linker.Steps.MarkStep.Process()
   at Mono.Linker.Steps.MarkStep.Process(LinkContext context)
   at Mono.Linker.Pipeline.Process(LinkContext context)
   at MonoDroid.Tuner.Linker.Process(LinkerOptions options, LinkContext& context)
   at Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver res)
   at Xamarin.Android.Tasks.LinkAssemblies.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() com.tapig.ria.quickmeme C:\Program Files (x86)\Microsoft Visual Studio\Preview\Community\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets 1591

A: Microsoft.Azure.Mobile.Client.dll is being referred from a different location in the android project references. Changing that will fix your issue.

A: I had similar issue, though the reason went from Xamarin.Auth library. By default, it automatically resolved to Xamarin.Android.Support.CustomTabs v 23.3.0. The fix was to manually add higher version to Android project (as of now it is 26.1.0.1).


text:
Q: Partition function for two systems The goal. Calculate the partition function of the following systems:

*

*A gas of $N$ non-interacting distinguishable particles with non-degenerate energy levels $E_0=0$ and $E_1=\epsilon$;

*A chain of $N$ sites that can be either open ($E=\epsilon>0$) or closed ($E=0$) such that if the $i$-th element is open, then all elements $j<i$ are open.

First system. if $k$ particles are in the excited state, the corresponding microstate has total energy $E_k=k\epsilon$. There are $\binom{N}{k}$ ways to choose such $k$ particles out of the $N$ particles in the gas; the remaining $N-k$ particles are then fixed at energy $E_0=0$. Therefore in total
$$Z=\sum_{k=0}^N\binom{N}{k} \exp(-\beta k\epsilon)=\sum_{k=0}^N \binom{N}{k} [\exp(-\beta \epsilon)]^k=[1+\exp(-\beta\epsilon)]^N.$$
Second system. if the rightmost open link is at position $0<k<N$, we get a microstate with energy $E=k\epsilon$, same as above. On the other hand, there is now no degeneracy on microstates. In total,
$$Z=\sum_{k=0}^N\exp(-\beta k\epsilon)=\sum_{k=0}^N[\exp(-\beta\epsilon)]^k=\frac{1-e^{-(N+1)\beta\epsilon}}{1-e^{-\beta\epsilon}}.$$
Is everything I've done above correct?


text:
Q: How save log file in linux sever while sending logs to elk using syslog I using docker and elk stack for the logs. I have send log of my microservices using syslog in my logback.xml file. However, there are no log files in the server even though microservices created log files in my local computer when I run with Eclipes IDE. I also used docker-compose file to up Logstash, Elasticsearch and Kibana. The problem is when we need to down docker containers, there are no previous logs. Which is a big issue.
Here are problems
1 Is their a way to save log file in the server while sending logs to elk stack?
2 If not, Is their a way to permanently save log with elk-stack?
I have also added my docker-compose file for elk stack, logstash.config file and logback.xml of microservice.
docker-compose.yml
version: '3'
services:
    elasticsearch:
        image: elasticsearch:6.5.0
        ports:
            - '9200:9200'
            - '9300:9300'
    kibana:
        image: kibana:6.5.0
        ports:
            - '5601:5601'
        depends_on:
            -  elasticsearch
    logstash:
        image: logstash:6.5.0
        ports:
            - '5000:5000'
        volumes:
            - $PWD/elk-config:/elk-config
        command: logstash -f /elk-config/logstash.config
        depends_on:
            -  elasticsearch

logstash.config
input {
    tcp {
    type => syslog
    port => 5000
    }
    udp {
    port => 5000
    type => syslog
    }
}
filter {
    if [type] == "syslog" {
        grok {
             match => { "message" => "%{TIMESTAMP_ISO8601:timestamp}\s+%{LOGLEVEL:severity}\s+\[%{DATA:service},%{DATA:trace},%{DATA:span},%{DATA:exportable}\]\s+%{DATA:pid}\s+---\s+\[%{DATA:thread}\]\s+%{DATA:class}\s+:\s+%{GREEDYDATA:rest}" }
        }
    }
}
output {
    elasticsearch {
    hosts => "elasticsearch"
    ssl => "false"
    index => "my-logs"
    document_type => "v1"
    }
}

logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="5 seconds">
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>

    <property scope="context" name="my-service" value="my-service"/>
    <property name="LOG_FILE" value="${BUILD_FOLDER:-logs}/${my-service}"/>
    <property name="CONSOLE_LOG_PATTERN"
          value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>

<!-- Appender to log to console -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <!-- Minimum logging level to be presented in the console logs-->
        <level>DEBUG</level>
    </filter>
    <encoder>
        <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        <charset>utf8</charset>
    </encoder>
</appender>

<!-- Appender to log to file -->
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_FILE}</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
        <maxHistory>10</maxHistory>
    </rollingPolicy>
    <encoder>
        <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        <charset>utf8</charset>
    </encoder>
</appender>

<!-- Appender to log to file in a JSON format -->
<appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_FILE}.json</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>
        <maxHistory>10</maxHistory>
    </rollingPolicy>
    <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
        <providers>
            <timestamp>
                <timeZone>UTC</timeZone>
            </timestamp>
            <pattern>
                <pattern>
                    {
                    "severity": "%level",
                    "service": "${springAppName:-}",
                    "trace": "%X{X-B3-TraceId:-}",
                    "span": "%X{X-B3-SpanId:-}",
                    "parent": "%X{X-B3-ParentSpanId:-}",
                    "exportable": "%X{X-Span-Export:-}",
                    "pid": "${PID:-}",
                    "thread": "%thread",
                    "class": "%logger{40}",
                    "rest": "%message"
                    }
                </pattern>
            </pattern>
        </providers>
    </encoder>
</appender>

<appender name="SYSLOG"
    class="ch.qos.logback.classic.net.SyslogAppender">
    <syslogHost>172.26.83.148</syslogHost>
    <port>5000</port>
    <facility>LOCAL1</facility>
    <suffixPattern>[%thread] %logger %msg</suffixPattern>
</appender>

<root level="INFO">
    <appender-ref ref="console"/>
    <appender-ref ref="logstash"/>
    <appender-ref ref="flatfile"/>
    <appender-ref ref="SYSLOG"/>
</root>

What am I doing wrong here? Any help would be grateful.
Thank you very much in advance.

A: You need to change
volumes:
  - $PWD/elk-config:/elk-config

to
volumes:
  - $PWD/elk-config:/elk-config
  - $PWD/logs:/logspath/inside/container/

So that logs from inside the container actually get saved to your host machine as well. That is the way you will see files on the host machine

A: The high level workflow for logging with containers is:
application stdout/stderr -> docker logging driver -> remote logging server

This follows the designed started by the 12 factor app principles. The advantage of this design is the app can be moved from environment to environment without needing to be reconfigured. Instead the docker host itself is responsible for getting the logs to the remote server.
Logging drivers have many options. The default is a json logging driver which wraps the stdout in some json metadata to track details like when each line was written, and whether it was stdout or stderr. You can switch this logging driver to go to elastic via fluentd or gelf. However, I'm not a fan of changing the logging driver for two reasons. First, if the logging driver ever hangs, which can happen when your logging server has an outage, your apps may hang if they fill up their stdout buffer, turning a small logging outage into a large business outage. And second, without the json logging driver, docker logs will not work, removing the ability of local admins to assist in debugging issues.
Instead, my preference is to use some kind of logging forwarder. With Elastic, the common forwarder is Filebeat (if you were on Splunk, they have a universal forwarder of their own). You then leave docker logs using the json logging driver, allowing docker logs to work on existing containers. And Filebeat relays those container logs to the central Elastic server, giving you persistence when the containers are deleted.
For more details on running Filebeat, see the Elastic documentation: https://www.elastic.co/guide/en/beats/filebeat/current/running-on-docker.html


text:
Q: SQL: Change query output to have two separate columns from having rows with 2 values For some reason my query output is grouping together 2 columns into 1, and putting the 2 values in the same row like this:
PATIENT_NAME
--------------------------------------------------------
INSURANCE
-------------------------
Aimie Pepsodent
Manulife

Aka Fresh
Blue Cross

Apple Addaye
Blue Cross

But I want them to appear in two separate columns like my teacher's output:
PATIENT_NAME   INSURANCE
-------------- ----------------
Apple Addaye   Blue Cross
Roy Alflush    No Insurance
Shane Cane     No Insurance

Is there a way I can change it to this?
Right now my sql query looks like this:
select (fname||' '||lname) patient_name,
       (nvl(l4_insurance_cos.company_name, 'No Insurance')) insurance
from l4_patients
left join l4_insurance_cos
on l4_patients.ins_id = l4_insurance_cos.id
order by l4_patients.lname;

A: This is a pure SQLPlus display issue. The size of the line is too small for the two columns to fit in it, so SQLPlus splits the results on two lines.
You need to adjust the linesize of your terminal, and/or the display width of each column - by default, it corresponds to the maximum length of the resultset column (if you concatenate two columns in the query, that's the sum of the length of the two columns, with a limit of 4000 bytes for varchars).
The actual values will depend on your terminal and table definition, but here is an example:
set linesize 140                -- allow a total of 140 characters per line
column patient_name format a80  -- 80 characters for column "patient_name"
column insurance    format a60  -- 60 characters for column "insurance"

Then, you can run your query.


text:
Q: Adding TextView to a LinearLayout with text taken from SharedPreferences key I'm trying to create a list of keys from a SharedPreferences object. Since the user can add new pairs key-value, I need to do it dynamically.
Here is the onCreate function of my activity:
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LayoutInflater inflater = this.getLayoutInflater();
        LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.activity_show_saved, null);

        this.add_here = (LinearLayout)layout.findViewById(R.id.saved_list);

        // Loading shared preferences
        SharedPreferences sp = this.getSharedPreferences("saved_sequences", MODE_PRIVATE);
        Map<String, ?> kv = sp.getAll();

        int i = 0;
        // Iterating through shared preferences
        for(Map.Entry<String, ?> entry : kv.entrySet()) {
            Toast.makeText(this, entry.getKey(), Toast.LENGTH_SHORT).show();
            TextView to_add = new TextView(this);
            to_add.setText(entry.getKey());
            to_add.setId(i++);
            this.add_here.addView(to_add, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        }

        this.setContentView(layout);
    }

Where this.add_here is a class variable declared as private LinearLayout. And here is the xml file which is being inflated:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/background"
    tools:context=".ShowSaved" >

    <com.google.ads.AdView
        android:id="@+id/adViewTop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ads:adUnitId="*****************"
        ads:adSize="SMART_BANNER"
        ads:testDevices="TEST_EMULATOR"
        ads:loadAdOnCreate="true" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:id="@+id/saved_list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

        </LinearLayout>

    </ScrollView>

</LinearLayout>

Unfortunately I get a blank screen. The problem is in adding the TextViews, since the Toast inside the while correctly shows saved keys as it's expected to do.

A: I've just done similar dynamic list, but my TextView is a part of a stand-alone layout.
Perhaps this will do the trick for you.
This code works for me:
        final ScrollView ll = (ScrollView) getLayoutInflater().inflate(
                R.layout.dropdown_list, null);

        final LinearLayout container = ((LinearLayout) ll
                .findViewById(R.id.dropdown_list_container));

        if (myObjectsCount > 0) {

            for (final MyObject ci : myObjects()) {

                LinearLayout item = ((LinearLayout) getLayoutInflater()
                        .inflate(R.layout.list_item, null));

                TextView tv = ((TextView) item
                        .findViewById(R.id.list_item_text));
                tv.setText("your text here");

                container.addView(item);

            }
        }

And the layout for the text view:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/buttons"
android:clickable="true"
android:gravity="center_vertical"
android:orientation="horizontal" >

<TextView
    android:id="@+id/list_item_text"
    style="@android:style/Widget.TextView"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:gravity="center_vertical" />

</LinearLayout>

A: As someone have already stated in the comments, that was not the right way of doing it. Here is the result achieved using a ListView. Have a look.
public class ShowSaved extends Activity implements OnItemClickListener {

    // Layout
    private ListView add_here;
    private TextView empty_view;

    // String Array
    private ArrayList<String> string = new ArrayList<String>();

    // SharedPreferences object and editor
    private SharedPreferences sp;

    // Array adapter for ListView add_here
    private ArrayAdapter<String> saved;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setContentView(R.layout.activity_show_saved);

        this.add_here = (ListView)findViewById(R.id.saved_list);
        this.empty_view = (TextView)findViewById(R.id.empty_text);

        // Loading shared preferences and editor
        this.sp = this.getSharedPreferences("saved_sequences", MODE_PRIVATE);

        // Creating the Adapter with all strings in an array
        this.saved = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, string);
        this.saved.setNotifyOnChange(true);

        // Retrieving all pairs in SharedPreferences sp
        Map<String, ?> kv = sp.getAll();

        // Iterating through shared preferences
        for(Map.Entry<String, ?> entry : kv.entrySet()) {
            saved.add(entry.getKey());
        }

        // Setting Adapter to ListView and empty View
        this.add_here.setEmptyView(empty_view);
        this.add_here.setAdapter(this.saved);

        // Setting Listener for ListView add_here
        this.add_here.setOnItemClickListener(this);
    }

Note: this code won't compile on its own since it lacks the onItemClick function required for the OnItemClickListener interface.


text:
Q: Include NULL in WHERE Array? I'm working with left joins that are creating NULL values. Let's say I'm interested in how many users have a basic plan or no plan at all (indicated by a NULL record in the left join)
SELECT u.id, s.plan_type
FROM users as u
LEFT JOIN subscriptions as s on s.user_id = u.id
WHERE s.plan_type IN (NULL, 'basic')

The above does not work as intended, likely because it doesn't recognize it as NULL. I'd have to write something like WHERE s.plan_type IS NULL OR s.plan_type = 'basic'
I was wondering if there was a short hand for that, or if you always have to use IS NULL to identify NULL values

A: s.plan_type IN (NULL, 'basic') is just shorthand for (s.plan_type = NULL OR s.plan_type = 'basic').
Anything = NULL always returns NULL, not true. And only true qualifies in a WHERE clause. So rephrase:
SELECT u.id, s.plan_type
FROM   users u
LEFT   JOIN subscriptions s ON s.user_id = u.id
WHERE (s.plan_type = 'basic' OR
       s.plan_type IS NULL);

To be precise, that's only correct if subscriptions.plan_type is defined NOT NULL. Failing that, the resulting NULL value could be just that, not a missing plan.
This alternative formulation does not share the same ambiguity for a resulting NULL:
SELECT u.id, s.plan_type
FROM   users u
JOIN   subscriptions s ON s.user_id = u.id
WHERE  s.plan_type = 'basic'
UNION ALL
SELECT u.id, NULL  -- always means missing
FROM   users u
WHERE  NOT EXISTS (SELECT FROM subscriptions WHERE user_id = u.id);

And it may be faster, because Postgres (like most RDBMS) often doesn't perform well with OR'ed predicates. See about "ugly OR":

*

*Why is an OR statement slower than UNION?
If referential integrity is guaranteed with a FK constraint from subscriptions.user_id to users.id, and s.user_id is defined NOT NULL you can omit the users table from the first SELECT:
SELECT user_id AS id, plan_type
FROM   subscriptions
WHERE  plan_type = 'basic'
UNION ALL
SELECT id, NULL
FROM   users u
WHERE  NOT EXISTS (SELECT FROM subscriptions WHERE user_id = u.id);

Might be fastest.
Aside: No array is involved here. You show the form of IN using a list. See:

*

*IN vs ANY operator in PostgreSQL

A: If your table isn't so huge, you could use coalesce to handle null before matching
select u.id, s.plan_type
from users as u
left join subscriptions as s on s.user_id = u.id
where coalesce(s.plan_type,'basic') = 'basic';

Note that the use of function on the left side of the where clause will make the query unsargable.


text:
Q: When source_address of python socket.create_connection is used? socket.create_connection(address[, timeout[, source_address]])

Any example to show the usage of source_address?

A: As the documentation says:

If supplied, source_address must be a 2-tuple (host, port) for the socket to bind to as its source address before connecting. If host or port are '' or 0 respectively the OS default behavior will be used.

In other words, it's used when you need to bind the socket before connecting. If you don't know why you'd ever need to do that, you don't need to do it. But here's a brief sketch of an example: An FTP server needs to be able to make an outgoing data connection on the same interface as the incoming control connection. You can do that by binding the same local address that the control connection has. So:
def make_data_conn(controlconn, port, timeout):
    return socket.create_connection((controlconn.getpeername()[0], port),
                                    timeout,
                                    (controlconn.getsockname()[0], 0))

A: My question is clear enough. Now, I know the answer.
I know how to inspect source code, I read the source code of method socket.create_connection(address[, timeout[, source_address]]), I asked for source_address, it's all about binding.
I have this question because I am a beginner, I have no background knowledge of socket programming, so I find a book named "Foundations of Python Network Programming" to read. In chapter 3 TCP, section One Socket per Conversation, i got it and made an example.
import socket

baidu = ('www.baidu.com', 80)
zero = ('0.0.0.0', 9001)

def test(addr, src_addr):
    try:
        sock = socket.create_connection(addr, 3, src_addr)
        print sock.getsockname()
        print
        sock.sendall('GET / HTTP/1.1\r\n\r\n')
        data = sock.recv(1024)
        print data
    finally:
        try:
            sock.close()
        except:
            pass

test(baidu, zero)
#test(baidu, None)

you can toggle the two test functions to see the differences.


text:
Q: I am trying to create a log file using the logging module in Python, however, I keep receiving a FileNotFoundError: [Errno 2] I am trying to create a daily log file for an automated task using the logging module in Python, however, I keep receiving a FileNotFoundError: [Errno 2] No such file or directory: 'directory/str(through_time) log.log'
here is my code:
through_time = date.today()

logging.basicConfig(
    filename=r'directory' + '/' + str(through_time) + ' log' + '.log',
    filemode='w',
    level=logging.INFO,
    format='%(asctime)s:%(levelname)s:%(message)s')

I have multiple scripts that do this exact same thing and use the same exact logging code and it works just fine. I have manually made sure that the directory is created, however, the str(through_time) + ' log' + '.log' file is not being created like it does in my other scripts and I'm not sure why. Is it because of the fact that I included the absolute path? I have always included the absolute path as well as the file name and it has always worked.
Does anyone know why this is happening? Like I stated above, I have multiple scripts that utilize the same logging.basicConfig() code with different directories and they work just fine and the log file is created for their directories.
I am using Spyder IDE (which I'm not fond of) could this be an issue? I usually use PyCharm and the code works just fine in PyCharm using the same steps. Just doesn't work in Spyder.
I tried to create the directory manually and I expected that this would solve the error and create the log file within the directory that I just manually created, however, it did not.
I have run into this error before and creating the directory manually has always worked, but it's not this time.


text:
Q: How to install HPLIP 3.20.3 or above in Ubuntu 20.04 When trying to install HPLIP 3.20.5 or 3.20.9 it crashes due to dependency problem mainly because of pyqt5 and lot of other dependencies.
If I tried to install those dependencies manually some of them are not listed in Ubuntu repository. From where I will get those dependencies.
Thanks for any help...

A: I have an HP DeskJet Ink Advantage 4535 All-In-One printer and the HPLIP version 3.21.2 works on my Ubuntu 20.04 LTS version. However, I must point out that the first installation of the HPLIP package (downloaded from the HPLIP website because the Ubuntu's package did not work) did not install properly. It failed to install my printer in wireless mode. But second time I went ahead and installed the printer in USB mode. It required a rebooting of the system. And currently it is working fine in USB mode and even the scanning function works smoothly. The GUI tray still poses problem.


text:
Q: Clicking inside TinyMCE editor is firing onChange event I am using TinyMCE 4.1.6. I need to check for content changes. I tried using the onChange event (also tried with isDirty, keyup event).
OnChange is useful for capturing all the changes including formatting. But when the editor is clicked inside, the event fires and shows content changed, though nothing changed.
As an alternative, I have also tried storing old content and comparing with changed content using Jquery's data() function. But what happens is that when the editor is clicked inside, it adds data-mce-selected="1" as below:
<table data-mce-selected="1" class="mce-item-table" border="0"..>

So when this is compared with the old content it shows that the content changed.
Any help is appreciated.

A: Try putting
e.preverntDefault()
e.stopImmediatePropagation()

just after the event handler function starts, I think it will stop mce from adding data-mce-selected="1" and your approach of comparing old data would work.


text:
Q: mutate multiple variables with different names in one function...? I am trying to replace update values for x, q, z using the recently available version of the variable indexed by date. In STATA, we can easily do it as a for loop (see sample code below).
STATA

*

*y refers to the date value of 20191125

local y 20191125

foreach v in attend child sibling{
replace `v'=`v'`y' if !missing(`v'`y')
}

Data
+----+----+---+-----------+-----------+-----------+
|attend  | child | sibling | attend20191125 | child20191125 | sibling20191125 |
+----+----+---+-----------+-----------+-----------+
| 1  | 2  | 3 |         6 |         8 |         0 |
| 1  | NA | 0 |         1 |         1 |         1 |
| NA | 0  | 1 |         5 |         4 |         2 |
+----+----+---+-----------+-----------+-----------+

Potential output:
+----+----+---+-----------+-----------+-----------+
|attend  | child | sibling | attend20191125 | child20191125 | sibling20191125 |
+----+----+---+-----------+-----------+-----------+
| 1  | 2  | 3 |         6 |         8 |         0 |
| 1  |1   | 0 |         1 |         1 |         1 |
| 5  | 0  | 1 |         5 |         4 |         2 |
+----+----+---+-----------+-----------+-----------+

I know how to replace NA values for one column from another column. How can I do the same using purrr dynamically? How can I tell R to replace values from a variable with the same name + date prefix? I have about 25 variables in my dataset that require this.
#Method 1: I can do it one variable at a time
df%<>%
mutate(attend=ifelse(is.na(attend)==T, attend20191125, attend),
       child=ifelse(is.na(child)==T, child20191125, child),
       sibling=ifelse(is.na(sibling)==T, sibling20191125, sibling))

#Method 2: using mutate_at (but not sure how I can dynamically refer to the date indexed variable?).

df%<>%
mutate_at(c("attend", "child", "sibling"), .=ifelse(is.na(.)==T, var20191125, .))

A: This is one way:
get_replacement <- function(.) {
  name <- names(.)
  vals <- .[[1]]
  out <- ifelse(is.na(vals), df[[str_c(name, "20191125")]], vals)
  rlang::list2(!!name := out)  # dynamically set column name
}

df %>%
  lmap_at(vars(attend, child, sibling), get_replacement)


text:
Q: How should I get an OAuth2.0 Access token in swift? I am trying to make an Unsplash photo client, which requires me to use the website's API. As per the documentation, in order to have access to photo related info( like pageURls, imagesURLs etc ) oAuth2.0 is required. It states I must do the following things :

*

*Direct the user to https://unsplash.com/oauth/authorize with some query parameters.

*If the user accepts the request, the user will be redirected to the                                            redirect_ui(one of the parameters)  , with the authorization code in the code query parameter

*Make a POST request to https://unsplash.com/oauth/token with some parameters.

This is how I tried to implement this in code:
ViewController.swift
 class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    authenticator()
    // Do any additional setup after loading the view, typically from a nib.
}

func authenticator(){

    Alamofire.request(.GET, "https://unsplash.com/oauth/authorize", parameters: [
    "client_id": "2902affb00634248f77b3c5c7a4ba4232fa36e3cbaad826b223a27f3df57e642"
    , "redirect_uri": "Sample//:" ,
      "response_type" : "code" ,
      "scope":"" ]).responseJSON{ response in
print("original URL request : \(response.request) ")
print("URL response : \(response.response) ")
    }

    Alamofire.request(.POST, "https://unsplash.com/oauth/authorize", parameters: [
        "client_id"    : "2902affb00634248f77b3c5c7a4ba4232fa36e3cbaad826b223a27f3df57e642",
        "client_secret":"6e85c0e5bcda025f0553e1343dcbdd8a892b0db1cc3a653055d84ce44c217bb9",
        "redirect_uri" : "Sample//:" ,
        "code" : "c15781809f4ee781e6019b958a2702be0dab61e89df96863693dbd7d48bacd53" ,
        "grant_type":"authorization_code" ])
        .responseJSON { response in
            print(response.request)  // original URL request
            print(response.response) // URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization

            if let JSON = response.result.value {
                print("JSON: \(JSON)")
        }
    }
}

But this is what I get :
  Optional(<NSMutableURLRequest: 0x7f9cf959f700> { URL:        https://unsplash.com/oauth/authorize })
  Optional(<NSHTTPURLResponse: 0x7f9cf941f920> { URL: https://unsplash.com/oauth/authorize } { status code: 422, headers {
"Accept-Ranges" = bytes;
Connection = "keep-alive";
"Content-Length" = 8440;
"Content-Type" = "text/html; charset=utf-8";
Date = "Thu, 18 Aug 2016 15:24:30 GMT";
Server = Cowboy;
"Strict-Transport-Security" = "max-age=31536000";
Via = "1.1 vegur, 1.1 varnish";
"X-Cache" = MISS;
"X-Cache-Hits" = 0;
"X-Ratelimit-Limit" = 100;
"X-Ratelimit-Remaining" = 94;
"X-Request-Id" = "f00ae2f9-6369-4526-9b28-283c294e2a30";
"X-Runtime" = "0.012134";
"X-Served-By" = "cache-sin6920-SIN";
"X-Timer" = "S1471533870.429494,VS0,VE550";
 } })
   Optional(<3c21444f 43545950 45206874 6d6c3e0a 3c68746d 6c3e0a3c 68656164 3e0a2020 ....2e 636f6d2f 616e616c 79746963 732e6a73 272c2767 6127293b 0a0a2020 20206761 28276372 65617465 272c2027 55412d33 36303439 3637302d 34272c20 27617574 6f27293b 0a202020 20676128 2773656e 64272c20 27706167 65766965 7727293b 0a202020 20676128 2773656e 64272c20 27657665 6e74272c 20276163 74696f6e 272c2027 34323227 293b0a20 203c2f73 63726970 743e0a0a 3c2f626f 64793e0a 3c2f6874 6d6c3e0a>)
   FAILURE

How shall I resolve this error?

A: Did you figure this out ? If not I will give you a hint. Follow my step you will get success with Access-Token return from Unsplash.
First, we will find-out how to use this request https://unsplash.com/oauth/authorize. With this request you need use UIWebView because this will return you a HTML page.
Try this https://unsplash.com/oauth/authorize?client_id=Your_App_ID&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&scope=public+read_user+write_user+read_photos+write_photos+write_likes+read_collections+write_collections with UIWebView.
After this request by using UIWebView you will get a code returned like this https://unsplash.com/oauth/authorize/f2ad36deb30b37a2614898e366b84e7c0f68fccd0358565cfbdc2637e*****
The code after /authorize/ is the code you need to fill your code parameter with request https://unsplash.com/oauth/token - Now you can use Alamofire to get your Token.
Just give questions if you still having problems


text:
Q: pyPdf for Python 2.7 does not work with py2exe and cx_freeze? everyone,
I wrote a little program using pyPdf for Python 2.7. And it has been tested in Python. Now I want it to be converted to exe file to run it in Windows. Neither py2exe or cx_freeze works out. The exe file does not run.
It looks like it does not contain the pyPdf module in the output folder.
The folder structure is like this:
dist\
    tcl [folder]
    tk [folder]
    _ctypes.pyd
    _tkinter.pyd
    bz2.pyd
    Filing.exe
    python27.dll
    tcl85.dll
    tk85.dll
    unicodedata.pyd

Filing.exe is the program.
I try to run the exe under command window, and the error message is like this:
Traceback (most recent call last):
 File "C:\python27\lib\site-packages\cx_Freeze\initscripts\console.py", line 27, in <module>
    exec code in m.__dict__
 File "filing.py", line 1, in <module>
ImportError: No module named pyPdf

Please help.
Thank you, all!
When I freeze it, the output shows like this:
C:\Python27\Scripts>cxfreeze pypdf_test.py
copying C:\Python27\lib\site-packages\cx_Freeze\bases\Console.exe -> C:\Python27
\Scripts\dist\pypdf_test.exe
copying C:\Windows\system32\python27.dll -> C:\Python27\Scripts\dist\python27.dl
l
writing zip file C:\Python27\Scripts\dist\pypdf_test.exe

  Name                      File
  ----                      ----
m StringIO
m UserDict
m __builtin__
m __main__                  pypdf_test.py
m _abcoll
m _codecs
m _codecs_cn
m _codecs_hk
m _codecs_iso2022
m _codecs_jp
m _codecs_kr
m _codecs_tw
m _multibytecodec
m _struct
m _warnings
m _weakref
m _weakrefset
m abc
m base64
m binascii
m bz2                       C:\Python27\DLLs\bz2.pyd
m codecs
m copy
m copy_reg
m cx_Freeze__init__         C:\Python27\lib\site-packages\cx_Freeze\initscripts\
Console.py
P encodings
m encodings.aliases
m encodings.ascii
m encodings.base64_codec
m encodings.big5
m encodings.big5hkscs
m encodings.bz2_codec
m encodings.charmap
m encodings.cp037
m encodings.cp1006
m encodings.cp1026
m encodings.cp1140
m encodings.cp1250
m encodings.cp1251
m encodings.cp1252
m encodings.cp1253
m encodings.cp1254
m encodings.cp1255
m encodings.cp1256
m encodings.cp1257
m encodings.cp1258
m encodings.cp424
m encodings.cp437
m encodings.cp500
m encodings.cp720
m encodings.cp737
m encodings.cp775
m encodings.cp850
m encodings.cp852
m encodings.cp855
m encodings.cp856
m encodings.cp857
m encodings.cp858
m encodings.cp860
m encodings.cp861
m encodings.cp862
m encodings.cp863
m encodings.cp864
m encodings.cp865
m encodings.cp866
m encodings.cp869
m encodings.cp874
m encodings.cp875
m encodings.cp932
m encodings.cp949
m encodings.cp950
m encodings.euc_jis_2004
m encodings.euc_jisx0213
m encodings.euc_jp
m encodings.euc_kr
m encodings.gb18030
m encodings.gb2312
m encodings.gbk
m encodings.hex_codec
m encodings.hp_roman8
m encodings.hz
m encodings.idna
m encodings.iso2022_jp
m encodings.iso2022_jp_1
m encodings.iso2022_jp_2
m encodings.iso2022_jp_2004
m encodings.iso2022_jp_3
m encodings.iso2022_jp_ext
m encodings.iso2022_kr
m encodings.iso8859_1
m encodings.iso8859_10
m encodings.iso8859_11
m encodings.iso8859_13
m encodings.iso8859_14
m encodings.iso8859_15
m encodings.iso8859_16
m encodings.iso8859_2
m encodings.iso8859_3
m encodings.iso8859_4
m encodings.iso8859_5
m encodings.iso8859_6
m encodings.iso8859_7
m encodings.iso8859_8
m encodings.iso8859_9
m encodings.johab
m encodings.koi8_r
m encodings.koi8_u
m encodings.latin_1
m encodings.mac_arabic
m encodings.mac_centeuro
m encodings.mac_croatian
m encodings.mac_cyrillic
m encodings.mac_farsi
m encodings.mac_greek
m encodings.mac_iceland
m encodings.mac_latin2
m encodings.mac_roman
m encodings.mac_romanian
m encodings.mac_turkish
m encodings.mbcs
m encodings.palmos
m encodings.ptcp154
m encodings.punycode
m encodings.quopri_codec
m encodings.raw_unicode_escape
m encodings.rot_13
m encodings.shift_jis
m encodings.shift_jis_2004
m encodings.shift_jisx0213
m encodings.string_escape
m encodings.tis_620
m encodings.undefined
m encodings.unicode_escape
m encodings.unicode_internal
m encodings.utf_16
m encodings.utf_16_be
m encodings.utf_16_le
m encodings.utf_32
m encodings.utf_32_be
m encodings.utf_32_le
m encodings.utf_7
m encodings.utf_8
m encodings.utf_8_sig
m encodings.uu_codec
m encodings.zlib_codec
m errno
m exceptions
m genericpath
m imp
m itertools
m linecache
m nt
m ntpath
m os
m posixpath
m quopri
m repr
m stat
m string
m stringprep
m strop
m struct
m sys
m traceback
m types
m unicodedata               C:\Python27\DLLs\unicodedata.pyd
m warnings
m weakref
m zipimport
m zlib

Missing modules:
? pyPdf imported from __main__

copying C:\Python27\DLLs\bz2.pyd -> C:\Python27\Scripts\dist\bz2.pyd
copying C:\Python27\DLLs\unicodedata.pyd -> C:\Python27\Scripts\dist\unicodedata
.pyd

C:\Python27\Scripts>

OK. I checked the pyPdf's location, it is here:
>>import pyPdf
>>print pyPdf
module 'pyPdf' from 'C:\Python27\lib\site-packages\pypdf-1.13-py2.7.egg\pyPdf\__init__.pyc'

How can I bring pyPdf to the exe program then?

A: Re-posting as an answer:
It seems to be something odd with modules installed inside .egg directories - cx_Freeze apparently isn't seeing setuptools' modifications to the path.
I've filed a cx_Freeze issue about it, but in the meantime, the easy solution is to copy the Python package to somewhere on your PYTHONPATH, like the site-packages folder.


text:
Q: How to change device language without user interference automatic through coding I want to change the device language without any user interaction programmatically. I have tried this method.
I am getting the following error.
Error:
java.lang.NoSuchMethodError: No interface method updateConfiguration(Landroid/content/res/Configuration;)
    V in class Landroid/app/IActivityManager;
    or its super classes (declaration of 'android.app.IActivityManager' appears in /system/framework/framework.jar)

Is there any other way to solve this?

A: i found answer for that we need to add line in menifest file   " uses-permission android:name="android.permission.CHANGE_CONFIGURATION" and allow permission to mobile by using adb command "adb grant mypackage android.permission.CHANGE_CONFIGURATION" and and i use reflection class method as i mention link above in my question its working


text:
Q: getting TypeError: metaclass conflict from PyErr_NewException Trying to create a c type exception in python 3.6 using ctypes.pythonapi, this is my code:
exc = ctypes.pythonapi.PyErr_NewException(b"error_logging.BackgroundTimeoutError", ctypes.pythonapi.PyExc_Exception, 0)
raise exc

I keep getting this error:
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

The BackgroundTimeoutError is a class that derives from Exception:
class BackgroundTimeoutError(Exception):

I also tried the following:
PyErr_NewException(b"error_logging.BackgroundTimeoutError", ctypes.py_object(BaseException), 0)

Then I get this error:
TypeError: exceptions must derive from BaseException


text:
Q: css touch-action none on body, pinch-zoom on element I am trying to apply this:
body {
  touch-action: none;
}

.left-side {
  touch-action: pinch-zoom;
}

The touch-action: none is working, but left-side is now :(
What am I doing wrong? Or does the body override everything?

A: The touch-action value pinch-zoom, is a modifier of sorts. According the The MDN spec, it is used in combination with other values:

The touch-action property may be specified as either:

*

*any one of the keywords auto, none, manipulation, or

*one of the keywords pan-x, pan-left, pan-right, and/or one of the keywords pan-y, pan-up, pan-down, plus optionally the keyword pinch-zoom.

pinch-zoom does nothing on its own, it simply lets the browser know that it should allow two finger gestures to be used; to control the actions listed along with it.
So if you want to allow multi finger support to pan the page sideways, you would use:
.left-side {
   touch-action: pan-x pinch-zoom;
}

Note: Keep in mind that this functionality is only for touch devices; mouse and accessible systems won't reflect any functionality changes with it.

A: These properties are not really what they look to be:

The touch-action CSS property allows a developer to restrict how a user can interact with an element which is especially helpful to
prevent events being dispatched when it's not necessary.

You cannot really add any touch interaction that was not there already, but you can restrict touch interactions that are there if you need to. So what does the pinch-zoom do then?

If you pinch on a website it'll generally zoom in on the pages
content. Defining a touch-action will prevent this behavior, but
adding pinch-zoom will re-enable this behavior.

I am not aware of any pinch-zoom CSS solution, but it's doable with a bit of javascript (touchstart, touchmove, touchend give you all you need). There are also libraries providing convenient wrappers for common gestures, like hammerjs.
You can read more about touch-action here.


text:
Q: Cannot communicate with my Kubernetes Cluster using Terraform I was trying to get started with AWS EKS Kubernetes cluster provisioning using Terraform. I was following the tutorial and got stuck on the moment with the kubeconfig file.
After the command: terraform output kubeconfig > ~/.kube/config, I should be able to communicate with the cluster. Unfortunately, when I try to use any command together with kubectl, for example cluster-info, I get an error error loading config file, yaml: line 4: mapping values are not allowed in this context
This is the code of the outputs.tf file:
# Outputs
#

locals {
  config_map_aws_auth = <<CONFIGMAPAWSAUTH

apiVersion: v1
kind: ConfigMap
metadata:
  name: aws-auth
  namespace: kube-system
data:
  mapRoles: |
    - rolearn: ${aws_iam_role.demo-node.arn}
      username: system:node:{{EC2PrivateDNSName}}
      groups:
        - system:bootstrappers
        - system:nodes
CONFIGMAPAWSAUTH

  kubeconfig = <<KUBECONFIG

apiVersion: v1
clusters:
- cluster:
    server: ${aws_eks_cluster.demo.endpoint}
    certificate-authority-data: ${aws_eks_cluster.demo.certificate_authority[0].data}
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: aws
  name: aws
current-context: aws
kind: Config
preferences: {}
users:
- name: aws
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1beta1
      command: aws-iam-authenticator
      args:
        - "token"
        - "-i"
        - "${var.cluster-name}"
KUBECONFIG
}

output "config_map_aws_auth" {
  value = local.config_map_aws_auth
}

output "kubeconfig" {
  value = local.kubeconfig
}```


text:
Q: How to use array_diff for same value used multiple times within an array? I've two different arrays with multiple values, they are as follows,
$a1 = ['a','b','c','sadasd','sadasd','sadasd','sadasd'];
$b1 = ['d','a','c','sadasd'];

$removed = array_diff($a1,$b1);
$added = array_diff($a1,$b1);

Now array_diff works perfectly but I'm facing issue for differentiating with same name value used multiple times
What I'm getting right now is
$removed =>

Array
(
    [1] => b
)

$added =>

Array
(
    [0] => d
)

Which is original behaviour of array_diff but, how to get result something like as
$removed =>

Array
(
    [1] => b
    [4] => sadasd
    [5] => sadasd
    [6] => sadasd
)


text:
Q: MAP is a solution to $L(\theta) = \mathcal{I}[\theta \ne \theta^{*}]$ I have come across these slides (slide # 16 & #17) in one of the online courses. The instructor was trying to explain how Maximum Posterior Estimate(MAP) is actually the solution $L(\theta) = \mathcal{I}[\theta \ne \theta^{*}]$, where $\theta^{*}$ is the true parameter.
Can someone please explain how this follows?
Edit: Added the slides, in case the link goes broken.

A: From going through the slides you shared, it seems to me that the idea is to explain how MAP estimation can be used to estimate different properties of the posterior, such as mean, mode, and median. I will attempt to explain this in the context of General Bayesian Estimators as presented in Stephen M. Kay's book, Fundamentals of Statistical Signal Processing.
Let's start by considering three types of Risk (i.e., cost functions) associated with estimating the parameter $\theta$:

*

*$C(e) = e^2$

*$C(e) = |e|$

*$if -\delta < e < \delta, C(e)=0$; else $C(e)=1$

where, $e = \theta - \hat{\theta}$, in which $\hat{\theta}$ is the estimated value and $\theta$ is the true parameter.
In Bayesian estimation, the objective is to minimize the expected risk, that is:

$E[C(e)]= \int_X \int_{\theta} C(e)p(X,\theta)d\theta dX = \int_X \left[\int_\theta C(e)p(\theta|X)d\theta\right] p(X)dX$

since we only care about $\theta$, we will focus on the inner integral $\min_{\theta}\int_\theta C(e)p(\theta|X)d\theta$.
Now, depending on which $C(e)$ we choose, the estimator will give us a different property of the posterior. For example, if we choose the first case, $C(e) = e^2$, the minimizing $\theta$ for $\int_\theta C(e)p(\theta|X)d\theta$, is the mean. Since you're question is with regards to the indicator function $I[\hat{\theta}\ne \theta]$, I'll address the third risk mentioned above (which if you think about it for $\delta\rightarrow 0$ is equivalent to using the indicator).
For Case 3 above:

$\int_\theta C(e)p(\theta|X)d\theta = \int_{-\infty}^{\hat{\theta}-\delta}p(\theta|X)d\theta + \int_{\hat{\theta}+\delta}^{\infty}p(\theta|X)d\theta = 1 - \int_{\hat{\theta}+\delta}^{\hat{\theta}+\delta}p(\theta|X)d\theta$

which for $\delta \rightarrow 0$ is minimized when $\hat{\theta}$ corresponds to the mode of the posterior.

A: In the specific case the parameter space $\Theta$ is finite or countably infinite$$\Theta=\{\theta_1,\theta_2,\ldots\}$$ the posterior loss associated with the indicator loss is equal to the probability of being wrong $\mathbb{P}(\hat{\theta}\ne\theta|x)$ and it is minimised when the posterior probability of being correct $\mathbb{P}(\hat{\theta}=\theta|x)$ is maximised. This means that $\hat{\theta}$ is the mode of the posterior distribution or the MAP.
However, this association of MAP and $0-1$ loss is a "folk theorem" in that it is incorrect in most settings, i.e., it does not hold for continuous parameter spaces where $\mathbb{P}(\hat{\theta}=\theta|x)=0$ for all $\hat{\theta}$'s and it further conflicts with the results of Druihlet and Marin (BA, 2007), who point out that the MAP ultimately depends on the choice of the dominating measure. (Even though the Lebesgue measure is implicitly chosen as the default.)
For instance, Evans and Jang posted an arXiv paper in 2011 where they discuss the connection between MAP, least relative surprise (or maximum profile likelihood) estimators, and loss functions. The core of the matter is that neither MAP estimators, nor MLEs are really justified by a decision-theoretic approach, at least in a continuous parameter space. And that the dominating measure [arbitrarily] chosen on the parameter space impacts the value of the MAP, as demonstrated by Druihlet and Marin in 2007. They start in the finite case with the loss function
$$
\mathrm{L}(\theta,d) = \mathbb{I}\{\Psi(\theta) \ne d) / \pi_\Psi(\Psi(\theta))
$$
where they consider the estimation of the transform Ψ(θ) by d, inversely weighted by the marginal prior on this transform. In the special case of the identity transform, this loss function leads to the MLE as the Bayes estimator. In the general case, the Bayes estimator is the maximum profile likelihood estimator (LRSE). However, this loss function does not generalise to countably infinite (and obviously continuous) parameter spaces and in such settings the authors can only provide LRSEs as limits of Bayes procedures. The loss function adopted in the countable case is for instance
$$
\mathrm{L}(\theta,d) = \mathbb{I}\{\Psi(\theta) \ne d\} / \max\{\eta,\pi_\Psi(\Psi(\theta))\}
$$
with the bound decreasing to zero. In the continuous case, the indicator does not work any longer, thus the choice made by the authors is to discretise the space Ψ(Θ) by a specific choice of a partition of balls whose diameters λ go to zero. In the spirit of Druihlet and Marin, this choice depends on a metric (and further regularity conditions). Furthermore, the LRSE itself
$$
\max_{\psi}\pi_\psi(\psi|x)/\pi_\psi(\theta)
$$
does depend on the version chosen for the densities (if not on the dominating measure), unless one imposes everywhere the Bayes equality
$$
\pi_{\psi}(\psi|x)/\pi_\psi(\theta)=f(x|\psi)/m(x)
$$
everywhere, when
$$
f(x|\psi)=\int_{\{\theta;\Psi(\theta)=\psi\}}f(x|\theta)\pi(\theta)\mathrm{d}\theta
$$
and
$$
m(x)=\int f(x|\theta)\pi(\theta)\mathrm{d}\theta
$$
in the spirit of our Savage-Dickey paradox paper.
Robert Bassett and Julio Deride arXived a paper in 2016 discussing the position of MAPs within Bayesian decision theory.

"…we provide a counterexample to the commonly accepted notion of MAP
  estimators as a limit of Bayes estimators having 0-1 loss."

The authors mention my book The Bayesian Choice stating this property without further precautions and I completely agree to being careless in this regard! The difficulty stands with the limit of the maximisers being not necessarily the maximiser of the limit. The paper includes an example to this effect, with a prior as above,  associated with a sampling distribution that does not depend on the parameter. The sufficient conditions proposed therein are that the posterior density is almost surely proper or quasiconcave.
See also an alternate characterisation of MAP estimators by Burger and Lucka as proper Bayes estimators under another type of loss function, albeit a rather artificial one.
The authors of this arXived paper start with a distance based on the prior; called the Bregman distance, which may be the quadratic or the entropy distance depending on the prior. Defining a loss function that is a mix of this Bregman distance and of the quadratic distance
$$
||K(\hat u-u)||^2+2D_\pi(\hat u,u)
$$
produces the MAP as the Bayes estimator. One might still wonder about the dominating measure but both the loss function and the resulting estimator are clearly dependent on the choice of the dominating measure… (The loss depends on the prior but this is not a drawback per se.)

A: I will give the summary of the text mentioned about this problem in Chapter 5, Bayesian Statistics, Machine Learning: A probabilistic perspective - by Murphy.
Let us say we observed some data $X$, and we want to comment about the posterior distribution of parameters $p(\theta|X)$. Now, the point estimate of the mode of this posterior distribution, which is widely known as the MAP, has certain drawbacks.
Unlike the mean or median, this is an 'untypical' point, in the sense that it does not consider all the other points while being estimated. In the case of estimating the mean/median, we take all the other points into consideration.
So, as expected, in highly skewed posterior distributions, the MAP(and, by extension, the MLE) does not truly represent the actually posterior.
So, how do we summarize a posterior using a point estimate such as Mean/Median/Mode?
This is where people use decision theory - essentially a Loss function $L(\theta, \hat{\theta})$ which is the loss one incurs if the truth is $\theta$ and $\hat{\theta}$ is our estimate. We can choose a variety of Loss functions and our objective here is to minimize the expected value of Loss function.
If the Loss function $L(\theta, \hat{\theta})$ is set as $\mathbb{I}(\hat{\theta}\ne\theta|x)$, an Indicator function for the all times when we CAN NOT estimate the truth, then minimizing the expected value of Loss function wrt $\theta$ is equal to Maximizing this function $\mathbb{I}(\hat{\theta}=\theta|x)$ wrt $\theta$. From this, it is intuitive to guess that Posterior mode minimizes the expected value of loss function. The details of this calculation can be seen in  the above answer.


text:
Q: iOS Back Button Vertical Position I have a custom back button in my app in the Navigation Bar and for the life of me, cannot figure out why it is being pushed up. It is in normal position in iOS 11.0 and up, but for any version below 11.0, the image is pushed slightly up vertically (with the top of the button touching the bottom of the status bar).
App Delegate Code:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

let navigationBarAppearace = UINavigationBar.appearance()
UINavigationBar.appearance().backIndicatorImage = UIImage(named: "backButton")
    UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "backButton")
    UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 5.0, vertical: -60.0), for: .default)

Has anyone else encountered this?
Edit: Added two screenshots. First one shows on simulator in iOs 9.3 (the lowest version I need to support) and second shows in iOS 11.4. The second screenshot in 11.4 is how the button should be positioned.
Simulator iOS 9.3
Simulator iOS 11.4


text:
Q: Persist checkbox values on postback in MVC3 Model:
  public class UserViewModel
    {
        public UserDetail user { get; set; }
        public List<int> SelectedRoles { get; set; }
    }

HttpGet Action:
   public ActionResult Index()
   {
        ViewBag.Roles = list of roles (List<Roles>)
        return View();
   }

View:
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{

    foreach (var item in ViewBag.Roles)
    {

      <input id="SelectedRoles" name="SelectedRoles" type="checkbox" value="@item.Id" >
      @item.Name
    }

    <input type="submit" value="Submit"/>
}

HttpPost Action:
 [HttpPost]
  public ActionResult CreateUser(UserViewModel model, FormCollection form)
  {
     foreach (int roleId in model.SelectedRoles)
     {

         Here I am getting IDs of SelectedRoles as roleId
     }
  }

On HttpPost I want to persist checkbox values as I have selected. How to do it in MVC3?

A: It looks like the checkboxes are bound to a property on the ViewBag. You have to re-assign the roles on the ViewBag in the post action, so that the UI can be rebound when the view is rendered after the post action has executed.
The viewbag will not persist between different view renderings, so it must be reset


text:
Q: pymunk custom complex creatures I am trying to create an evolution simulator, something very similar to this. As for tools I am using pymunk physics simulator with pygame.
My creatures consist of few circles with their respective bodies fixed together with DampedSprings as muscles. Springs give me a nice effect of expanding and contracting muscles however they do not hold their "angular position". What I mean by that is that when creature is spawned with triangular shape, in the moment it falls on the ground the top node just falls on the ground -> does not hold its shape.
spawned creature
deformated creature
What I wish would happen is that the creature would hold its shape when it falls down on the ground = the top node would stay at the top like it is at the moment of spawn while still maintaining the ability to simulate variable length of muscle.
Anybody have an idea how could I solve this issue please ?
Thank you!

A: I guess the reason is the springs are not strong enough to hold back. But maybe if you make the springs stronger (stiffer?) the effect doesnt look well?
One idea I think you can try is to add a DampedRotarySpring (http://www.pymunk.org/en/latest/pymunk.constraint.html#pymunk.constraint.DampedRotarySpring) as well for each DampedSpring you have. That way you have one spring working to keep angles, and one to keep distance.


text:
Q: How to split a read Text File into "\n"s? I need to split a text file into sentences, which are separated by moving to the next line.
Imagine this text:
Hey what's up
How are you doing?
Enjoy your coding!

This is the way I figured out to get the text from the file and save it:
ifstream file;
string text, finaltext;
file.open("input.txt", ios::in);

    while(getline(file, text)){
    finaltext += text;
}

cout<<finaltext;

So this actually does the job, but for a weird reason it Skips the "\n", and the result I get is this:
Hey what's upHow are you doing?Enjoy your coding!

So i need to find a new way to do this, making sure that finaltext gets the text separated by "\n"s. Can someone please help me? I'd be forever grateful. Thank you guys.

A: If you're getting each line seperately, you can try something like this:
file.open("input.txt", ios::in);

while (getline(file, text)) {
    finaltext += text;
    finaltext += "\n";
}

This way, you're adding the newline character yourself.

A: There is a difference between the functions ssize_t getline(char **restrict lineptr, size_t *restrict n, FILE *restrict stream) (which you get when you run man getline) and istream& getline (istream& is, string& str) which you are using. From the manpage of the first one:

getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr.  The buffer is null-terminated and includes the newline character, if one was found.

From the manpage of the second one:

If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).

This might explain your confusion. So, as others have said, you'll just have to add it yourself.

A: Here you go, you just needed to concatenate '\n'
while (getline(file, text))
    {
        finaltext =finaltext + "\n" + text;
    }

    cout << finaltext;

As mentioned by Sandburg, + operator was almost deprecated with C++17 so you can use append() or insert() here.


text:
Q: Best way to store data during runtime I am currently working on a vocabulary trainer for android smartphones. There will be hundreds of index cards that are going to be used by multiple activities. It would be too expensive to load all index cards from database each time a new activity needs them. Sometimes an activity modifies a index card. The modification should be visible too all other activities.
Question:
All index card are stored in an ArrayList of type IndexCard. Should I store it in a class extending from Application or should I rather pass the whole ArrayList to activities using bundles?
This blog tells me, that my first idea would be no good practice, http://www.developerphil.com/dont-store-data-in-the-application-object/
What way is the more efficient and what is good practice?

A: Well, i prefer storing it into the database as you already mentioned and loading it in the first start to an Map which holds serialized Objects. You can also store the serialized Objects and keep an index in the Database. So you will only need to load the indexes and have an reference to the serialized Object as soon as you need it. Accessing those files should be by far faster then reading the database.
Storing thise in a SingleTon Object is not a good idea, since the GC will destroy it and/or the application pretty fast in this case.   Those called "Soft-References" are the best way. If you really want to store a huge collection of data (which i dont prefer) you may want to use vanilla-java https://code.google.com/p/vanilla-java/wiki/HugeCollections

A: Have you thought about storing it in SharedPreferences?  I also have a rather large XML data file (250k) in my app.  During app launch, I read the data file into an ArrayList of custom object, serialize the ArrayList, and store it as String in SharedPreferences.  I used Gson library and it's very quick and easy to store and load ArrayList objects as string.


text:
Q: How to locate block code In Debug Memory Graph I've got a custom view captured by a __NSMallocBlock__
The block's description is just
<__NSMallocBlock__: 0x600000a5f7a0>

So how can I locate the block code now?

A: You should edit your scheme settings, and under "Diagnostics" » "Logging" and enable "Malloc Stack".

Then, when select the "Memory Inspector", you'll see your stack trace:

You can even click on the arrow next to your method name in the stack and it will jump you to that portion of code where this block was allocated. In my example above, the block was allocated in viewDidLoad.

Make sure to turn off this setting when you're done with your diagnostics.


text:
Q: update record in MySQL table using select statement I'm trying to update the last inserted record and assign to it's column  - campaign_id the value in id (same record).
i came up with this query :
UPDATE campaigns
SET campaign_id= (select id order by id desc LIMIT 1)
WHERE id = (select id order by id desc LIMIT 1)

but for some reason i can't understand it updated the ENTIRE table, why is that?

A: I think the following is what you were intending to do:
UPDATE campaigns
SET campaign_id = id
WHERE id = (SELECT id FROM campaigns ORDER BY DESC LIMIT 1);

Whether or not this be logically correct depends on whether the record with the max id is actually the latest record.  I can imagine that not being the case, but perhaps the logic in the above subquery could be changed to cover this possibility.