text:
Q: how does numpy masking using arr[mask, ...] work? I read in numpy.delete documentation that given an array arr:
mask = np.ones(len(arr), dtype=bool)
mask[[0,2,4]] = False
result = arr[mask,...]

Is equivalent to np.delete(arr, [0,2,4], axis=0), but allows further use of mask.
From this I can see what arr[mask,...] does, and I have tested how it works and am able to use this to mask arrays. But I'm just curious, what exactly is this arr[mask,...] syntax? i.e. How do I use this syntax generally?

A: First make sure we understand a 1d case:
In [106]: arr = np.arange(10)
In [107]: mask = np.ones(arr.shape, bool)
In [108]: mask[[0,2,3,7]] = 0
In [109]: mask
Out[109]:
array([False,  True, False, False,  True,  True,  True, False,  True,
        True])
In [110]: arr[mask]
Out[110]: array([1, 4, 5, 6, 8, 9])

The len(arr) bit, and [mask,...] adds a bit of a complication, that I still need to sort out.
The actual code that implements this kind of delete is:
    slobj = [slice(None)]*ndim
    N = arr.shape[axis]
    ...
    keep = ones(N, dtype=bool)
    ...
    keep[obj, ] = False
    slobj[axis] = keep
    new = arr[slobj]

So in the example case:
In [112]: arr = np.arange(10).reshape(5,2)
In [113]: arr
Out[113]:
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])
In [114]: slobj = [slice(None), slice(None)]
In [115]: mask = np.ones(5,bool)
In [116]: mask[[0,2,4]] = 0
In [117]: mask
Out[117]: array([False,  True, False,  True, False])
In [118]: slobj[0] = mask
In [119]: slobj
Out[119]: [array([False,  True, False,  True, False]), slice(None, None, None)]
In [120]: arr[slobj]
Out[120]:
array([[2, 3],
       [6, 7]])


text:
Q: Is there a maximum right click context menu items limit I'm making a custom right click submenu (in Windows registry) using SubCommands, but after adding more options to it, some last options disappeared. Is there a maximum amount of items that are allowed? If so, is there a way to workaround? I'm on Windows 7. When I go to the registry, all the SubCommands are saved in the string value.

A: Yes! there's a limit of 16 entries for each context menu entry, including submenus and any entry inside of them.. If I'm not mistaken this limit exists since the dawn of Windows, at least as far back as Windows 95. At the time, leaving that feature without any limit could negatively impact system performance. This limit however, doesn't seem to apply to COM shell extensions, so there might be a solution around. I think it's best to organize and be more selective on what's included in the context menu.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pythonic composite for loop conditions In C++/C, I can write the following:
string s;
int window_len = 3;
for (int i = 0, j = window_len; j <= s.length(); i += window_len, j += window_len) {
  //do things with s.Slice(i, j)
}

Is there a pythonic way of expressing the above composite for loop?

A: One way that using the fact that floor dividing the length of the string by the "group"-size will truncate remaining characters:
>>> string = 'abcdefghijklm'
>>> size=2

>>> [string[i*size:(i+1)*size] for i in range(len(string) // size)]
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']

Or in a for-loop:
for i in range(len(string) // size):
    substr = string[i*size:(i+1)*size]
    # do stuff with substr

A: I think this gets at the concept in a similar way and doesn't require a lot of additional math:
strides = range(0, len(s)+1, window_len)
for i, j in zip(strides, strides[1:]):
    # do something with s[i:j]

A: Why, of course:
s = "Hello, world!"
[s[i:i + window_len] for i in range(0, len(s)-window_len+1, window_len)]
# ['Hel', 'lo,', ' wo', 'rld']


text:
Q: Google Sheets' conditional formatting on list from another sheet I have data validation set up in my sheet so that Sheet1 cells can accept one of the values from Sheet2 list.
Since Sheet2 has 2 columns, I would like to make conditional formatting so that if an item from column A is selected that I show one color, and if an item from column B is selected that I can show another one.
I have tried setting to format if

Text contains =JOIN(", ",INDIRECT("Sheet2!C2:C"))

As well as

Text contains =INDIRECT("Sheet2!C2:C")

But none of these work.
Can I do this somehow?
EDIT
Also tried to do

Custom formula =ArrayFormula(sum(countif(B2:I26, Studenti!B2:B)))>0

Which does seem to do its work on its own, but inside format rule doesn't

A: green color:
=FILTER(A1,COUNTIF(INDIRECT("Sheet2!C1:C"),A1))

red color:
=FILTER(A1,COUNTIF(INDIRECT("Sheet2!D1:D"),A1))


text:
Q: iPhone simulator crashed when I tried to take screenshot (⌘ + S) (using the libswiftFoundation.dylib plug-in) I am trying to take screenshot from iPhone 5 simulator. When I click ⌘ + S, the simulator crashes every time with error:-

Simulator quit unexpectedly while using the libswiftFoundation.dylib
  plug-in

A: If you run the screenshot command from terminal with the following it should save correctly. This seems to be a bug with Xcode versions 8.2.0 and 8.2.1.
xcrun simctl io booted screenshot

This will save to directly that Terminal is in. You can also add a path to the end of the command


text:
Q: React- redux non re-rendering with prop change I don't understand why react is not re-rendering after successful action and store update. I don't think I am mutating the state in my reducer as I perform all the arithmetic in my react component and then send the object trough dispatch. My react component has mapStateToProps hooked up and connect. Any help would be greatly appreciated.
Below is my react component.
const mapStateToProps = (state) =>({

name:state.user.name,
email:state.user.email,
password:state.user.password,
skill:state.user.skill,
goal:state.user.goal,
step1:state.user.step1,
step2:state.user.step2,
step3:state.user.step3,
step4:state.user.step4,
step5:state.user.step5,
completed:state.user.completed,

})

const mapDispatchToProps = (dispatch) => ({
  callApi: (value, state) => {

var obj = {
date:moment.tz(moment.tz.guess()).format(),
post:state.post,
email:state.email,
completed:(parseFloat(state.completed) + .75),
}

    API.addPost(obj)
    .then(function(res){
      dispatch(updateUser(res.data))
    })
  }

})
export default connect(mapStateToProps,mapDispatchToProps)(YourPage);

My reducer
import {UPDATE_USER, CREATE_USER,CREATE_SKILL,CHECK_USER} from '../actions/index';

const DEFAULT_STATE =

{
createdAt:"",
name:"",
email:"",
password:"",
skill:"",
goal:"",
step1:"",
step2:"",
step3:"",
step4:"",
step5:"",
posts:[],
completed:0
}

export default function(state = DEFAULT_STATE, action) {
  if (action.error) {
    action.type = 'HANDLE_ERROR'; // change the type
  }
  switch (action.type) {

    case UPDATE_USER:

    return Object.assign({},state,{

    completed:action.payload.completed

    })

A: Did you check in dev tools that your store is being updated? if not check if action ever hits the reducer(add console.log to reducer) and if console.log doesn't fire, Its probably that you invoked your imported action, rather then the action with a dispatch. make sure to invoke it with 'this.props.action()' rather than 'action()' unless you destructure it.

A: Your problem is elsewhere down the line
Add console.logs to check the following

*

*action type constants

*API responses

*default case in the reducer

The code below works properly
import React, { Component } from 'react';
import { render } from 'react-dom';
import { createStore, combineReducers } from 'redux';
import { connect, Provider } from 'react-redux';
import moment from 'moment';
import 'moment-timezone';
import './style.css';

const DEFAULT_STATE = {
  createdAt: "",
  name: "",
  email: "",
  password: "",
  skill: "",
  goal: "",
  step1: "",
  step2: "",
  step3: "",
  step4: "",
  step5: "",
  posts: [],
  completed: 0
};

const reducer = function (state = DEFAULT_STATE, action) {
  switch (action.type) {
    case 'update user':
      return Object.assign({}, state, {
        completed: action.payload.completed
      });
    default:
      return state;
  }
}

const reducers = combineReducers({
  user: reducer,
})

const updateUser = (payload) => ({
  type: 'update user',
  payload,
})

const API = {
  addPost: obj => new Promise(resolve => setTimeout(() => resolve({ data: obj }), 500))
}

const mapDispatchToProps = (dispatch) => ({
  callApi: (value, state) => {
    var obj = {
      date: moment.tz(moment.tz.guess()).format(),
      post: state.post,
      email: state.email,
      completed: (parseFloat(state.completed) + .75),
    }

    API.addPost(obj)
      .then(function (res) {
        dispatch(updateUser(res.data))
      })
  }

})

const store = createStore(reducers);

class App extends Component {
  render() {
    console.log(this.props);
    return (

        <button onClick={() => this.props.callApi(1, this.props)}>Call API</button>

Value: {this.props.completed}

    );
  }
}

const mapStateToProps = (state) => ({
  name: state.user.name,
  email: state.user.email,
  password: state.user.password,
  skill: state.user.skill,
  goal: state.user.goal,
  step1: state.user.step1,
  step2: state.user.step2,
  step3: state.user.step3,
  step4: state.user.step4,
  step5: state.user.step5,
  completed: state.user.completed,

})

const AppContainer = connect(mapStateToProps, mapDispatchToProps)(App);

render(
  <Provider store={store}>
    <AppContainer />
  </Provider>,
  document.getElementById('root')
);


text:
Q: OpenID Discovery Methods - Yadis VS HTML Recently, I've begun writing my own PHP OpenID consumer class in order to better understand openID. As a guide, I've been referencing the [LightOpenID Class][1]. For the most part, I understand the code and how OpenID works. My confusion comes when looking at the author's discover function:
function discover($url)
{
    if(!$url) throw new ErrorException('No identity supplied.');
    # We save the original url in case of Yadis discovery failure.
    # It can happen when we'll be lead to an XRDS document
    # which does not have any OpenID2 services.
    $originalUrl = $url;

    # A flag to disable yadis discovery in case of failure in headers.
    $yadis = true;

    # We'll jump a maximum of 5 times, to avoid endless redirections.
    for($i = 0; $i < 5; $i ++) {
        if($yadis) {
            $headers = explode("\n",$this->request($url, 'HEAD'));

            $next = false;
            foreach($headers as $header) {
                if(preg_match('#X-XRDS-Location\s*:\s*(.*)#', $header, $m)) {
                    $url = $this->build_url(parse_url($url), parse_url(trim($m[1])));
                    $next = true;
                }

                if(preg_match('#Content-Type\s*:\s*application/xrds\+xml#i', $header)) {
                    # Found an XRDS document, now let's find the server, and optionally delegate.
                    $content = $this->request($url, 'GET');

                    # OpenID 2
                    # We ignore it for MyOpenID, as it breaks sreg if using OpenID 2.0
                    $ns = preg_quote('http://specs.openid.net/auth/2.0/');
                    if (preg_match('#<Service.*?>(.*)<Type>\s*'.$ns.'(.*?)\s*</Type>(.*)</Service>#s', $content, $m)
                        && !preg_match('/myopenid\.com/i', $this->identity)) {
                        $content = $m[1] . $m[3];
                        if($m[2] == 'server') $this->identifier_select = true;

                        $content = preg_match('#<URI>(.*)</URI>#', $content, $server);
                        $content = preg_match('#<LocalID>(.*)</LocalID>#', $content, $delegate);
                        if(empty($server)) {
                            return false;
                        }
                        # Does the server advertise support for either AX or SREG?
                        $this->ax   = preg_match('#<Type>http://openid.net/srv/ax/1.0</Type>#', $content);
                        $this->sreg = preg_match('#<Type>http://openid.net/sreg/1.0</Type>#', $content);

                        $server = $server[1];
                        if(isset($delegate[1])) $this->identity = $delegate[1];
                        $this->version = 2;

                        $this->server = $server;
                        return $server;
                    }

                    # OpenID 1.1
                    $ns = preg_quote('http://openid.net/signon/1.1');
                    if(preg_match('#<Service.*?>(.*)<Type>\s*'.$ns.'\s*</Type>(.*)</Service>#s', $content, $m)) {
                        $content = $m[1] . $m[2];

                        $content = preg_match('#<URI>(.*)</URI>#', $content, $server);
                        $content = preg_match('#<.*?Delegate>(.*)</.*?Delegate>#', $content, $delegate);
                        if(empty($server)) {
                            return false;
                        }
                        # AX can be used only with OpenID 2.0, so checking only SREG
                        $this->sreg = preg_match('#<Type>http://openid.net/sreg/1.0</Type>#', $content);

                        $server = $server[1];
                        if(isset($delegate[1])) $this->identity = $delegate[1];
                        $this->version = 1;

                        $this->server = $server;
                        return $server;
                    }

                    $next = true;
                    $yadis = false;
                    $url = $originalUrl;
                    $content = null;
                    break;
                }
            }
            if($next) continue;

            # There are no relevant information in headers, so we search the body.
            $content = $this->request($url, 'GET');
            if($location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'value')) {
                $url = $this->build_url(parse_url($url), parse_url($location));
                continue;
            }
        }

        if(!$content) $content = $this->request($url, 'GET');

        # At this point, the YADIS Discovery has failed, so we'll switch
        # to openid2 HTML discovery, then fallback to openid 1.1 discovery.
        $server   = $this->htmlTag($content, 'link', 'rel', 'openid2.provider', 'href');
        $delegate = $this->htmlTag($content, 'link', 'rel', 'openid2.local_id', 'href');
        $this->version = 2;

        # Another hack for myopenid.com...
        if(preg_match('/myopenid\.com/i', $server)) {
            $server = null;
        }

        if(!$server) {
            # The same with openid 1.1
            $server   = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href');
            $delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href');
            $this->version = 1;
        }

        if($server) {
            # We found an OpenID2 OP Endpoint
            if($delegate) {
                # We have also found an OP-Local ID.
                $this->identity = $delegate;
            }
            $this->server = $server;
            return $server;
        }

        throw new ErrorException('No servers found!');
    }
    throw new ErrorException('Endless redirection!');
}

  [1]: http://gitorious.org/lightopenid

Okay, Here's the logic as I understand it (basically):

*

*Check to see if the $url sends you a valid XRDS file that you then parse to figure out the OpenID provider's endpoint.

*

*From my understanding, this is called the Yadis authentication method.

*If no XRDS file is found, Check the body of the response for an HTML <link> tag that contains the url of the endpoint.

What. The. Heck.
I mean seriously? Essentially screen scrape the response and hope you find a link with the appropriate attribute value?
Now, don't get me wrong, this class works like a charm and it's awesome. I'm just failing to grok the two separate methods used to discover the endpoint: XRDS (yadis) and HTML.
My Questions

*

*Are those the only two methods used in the discovery process?

*Is one only used in version 1.1 of OpenID and the other in version 2?

*Is it critical to support both methods?

*The site I've encountered the HTML method on is Yahoo. Are they nuts?

Thanks again for your time folks. I apologize if I sound a little flabbergasted, but I was genuinely stunned at the methodology once I began to understand what measures were being taken to find the endPoint.

A: Specification is your friend.
But answering your question:

*

*Yes. Those are the only two methods defined by the OpenID specifications (at least, for URLs -- there is a third method for XRIs).

*No, both can be used with both version of the protocol. Read the function carefully, and you'll see that it supports both methods for both versions.

*If you want your library to work with every provider and user, you'd better do. Some users paste the HTML tags into their sites, so their site's url can be used as an openid.

*Some providers even use both methods at once, to mantain compatibility with consumers not implementing YADIS discovery (which isn't part of OpenID 1.1, but can be used with it). So that does make sense.

And yes, HTML discovery is about searching for a <link> in the response body. That's why it's called HTML discovery.


text:
Q: Possible integer values of discriminants of irreducible integer-valued polynomials Background:
The discriminant of the constant polynomials is undefined.
Every linear polynomial has discriminant $1$.
No integer-valued polynomial with no rational non-constant square factor can have discriminant $0$.
The only possible integer fundamental discriminants of integer-valued quadratic polynomials are the integers congruent to $0$ or $1$ modulo $4$.
Proof: Every integer-valued quadratic polynomial is either of the form $ax^2+bx+c$ where $2a, 2b, c$ are integers such that $2a$ and $2b$ have the same parity. If $2a$ and $2b$ are even integers, i.e. $a$ and $b$ are integers, then $D=b^2-4ac$ is either $0$ or $1$ modulo $4$. If $2a$ and $2b$ are odd integers, i.e. $a$ and $b$ are half-integers, then $D=b^2-4ac$ is $\frac{1}{4}$ modulo $2$, which is never an integer. In any case, $ax^2+bx+c$ is irreducible iff $D$ isn't a rational square.
However, there are many integer-valued polynomials whose discriminant is either square $>1$ or congruent to $2$ or $3$ modulo $4$. For example for the cubics:

*

*$$\frac{1}{2}x^3-2x^2+\frac{1}{2}x-1,D=-29;$$

*$$\frac{1}{2}x^3+4x^2+\frac{5}{2}x-1,D=-26;$$

*$$x^3+x^2-2x-1,D=49;$$

*$$\frac{1}{2}x^3-\frac{3}{2}x-2x+2,D=79;$$
etc.

Main question: What are all the possible integer values of discriminants of irreducible integer-valued polynomials?


text:
Q: Find the coins required which sum to S and we can use coin only one time Given a list of N coins, their values (V1, V2, ... , VN), and the total sum S. Find the coins the sum of which is S. We can use one coin only one time.
I was recently studying the very same problem here and there, but there we can use the coins any number of times.
How to solve it?


text:
Q: Does this open compound noun require a hyphen when used as an adjective? A friend of mine works at a restaurant that sells tortilla soup; however, I think the soup tastes like hot dogs. There are thus three ways to write this: hot dog soup, hot-dog soup, hotdog soup.
Only the open compound form of hot dog soup appeals to me aesthetically, and, for the most part, native speakers know what a hot dog is and will draw the connection. But what if the soup in question were actually a hot dog-soup/dogsoup?
What is the "best" way to write hot dog soup? Why?

A: For the reason you suggest, "hot dog soup" looks a little like "hot dog-soup". If I saw either on a menu it might be the source of a few moments' humour.
I prefer "hot-dog soup" because I don't think many people write it as hotdog.

A: In most of the English-speaking world, there is no possibility of genuine ambiguity about what the meat in "hot dog soup" consists of—beyond the fact that hot dogs themselves are sometimes characterized as "mystery meat." Objectively, "hot dog soup" is no more ambiguous than "hot dog on a bun," and no one familiar with the U.S. term hot dog doubts what that is.
On the other hand, hot dog is a bit of an oddity in that Merriam-Webster spells the noun (referring to the sausage) as two words and the verb (meaning to show off by doing something flashy rather than merely workmanlike and efficient) as one word, closed up. A Google Ngram chart for the years 1900 to 2005 matching hot dog (blue line) against hotdog (red line)—with no differentiation between how the two terms are used—looks like this:

A specific comparison of plural noun forms—hot dogs (blue line) versus hotdogs (red line) across the same period yields a rather similar-looking chart:
:
It wouldn't surprise me if the closed-up hotdog eventually overtook the open hot dog in all senses of the term, but that obviously hasn't happened yet. If I were in charge of producing the printed menu for a restaurant that offered hot dog/hot-dog/hotdog soup, I might be inclined to run hotdog as one word, closed up, just to minimize the hilarity of easily amused diners. But then again, maybe a little hilarity in that setting is a good thing—as with the menu at a Chinese restaurant that offers such choices as "Strange flavor chicken."


text:
Q: Concatenation layer raise Value Error: as_list() is not defined on an unknown Tensor Shape I'm Trying to making DNN using Wide Deep Nural Network using keras the following code produces the following after trying to implement it, I also making my custome activation function Randomized Relu
here is the code for the Activation:
class RRELU(keras.layers.Layer):
    def __init__(self, lower, upper, **kwargs):
        super().__init__(**kwargs)
        self.lower = lower
        self.upper = upper
def call(self, inputs, training=None):
    if training:
        return tf.where(inputs >= 0, inputs, inputs /
                        np.random.uniform(self.lower, self.upper, 1)[0])
    return tf.where(inputs >= 0, inputs, 2*inputs/(self.lower+self.upper))
def compute_output_shape(self, batch_input_shape):
  return tf.TensorShape(batch_input_shape.as_list())
def get_config(self):
  base_config = super().get_config()
  return {**base_config, 'lower': self.lower, 'upper': self.upper}

here is the code for the model.
layer = []
layer.append(keras.layers.Input(shape = X_train.toarray().shape[1:]))
for i in range(10):
  layer.append(keras.layers.Dense(300))
  layer.append(RRELU(3, 8))
layer.append(keras.layers.Concatenate()([layer[0], layer[-1]]))
layer.append(keras.layers.Dense(2, activation='softmax'))
model39 = keras.models.Sequential(layer)

This line is producing the error:
layer.append(keras.layers.Concatenate()([layer[0], layer[-1]]))

Error msg:
ValueError                                Traceback (most recent call last)
<ipython-input-28-ad6c20fa06bd> in <module>()
      4   layer.append(keras.layers.Dense(300))
      5   layer.append(RRELU(3, 8))
----> 6 layer.append(keras.layers.Concatenate()([layer[0], layer[-1]]))
      7 layer.append(keras.layers.Dense(2, activation='softmax'))
      8 model39 = keras.models.Sequential(layer)

1 frames
/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     65     except Exception as e:  # pylint: disable=broad-except
     66       filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67       raise e.with_traceback(filtered_tb) from None
     68     finally:
     69       del filtered_tb

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_shape.py in as_list(self)
   1221     """
   1222     if self._dims is None:
-> 1223       raise ValueError("as_list() is not defined on an unknown TensorShape.")
   1224     return [dim.value for dim in self._dims]
   1225

ValueError: as_list() is not defined on an unknown TensorShape.

Thnks in Advance for any helpful comments.

A: The reason you get this error is explained in the documentation of tf.keras.Sequential:
"A Sequential model is appropriate for a plain stack of layers where each layer has exactly one input tensor and one output tensor."
This is due to the fact that when a layer is added to a Sequential model, the inputs of the added layer are automatically set to be the outputs of the previous one. Having a concatenation like yours would imply that the output of the first Dense layer would be used by both the next layer and the Concatenate layer downstream, which is against the idea of the Sequential models.
The solution is using the Functional API instead:
import numpy as np
X_train = np.zeros((1, 100))

layer = []
layer.append(keras.layers.Input(shape=X_train.shape[1:]))
layer.append(keras.layers.Dense(300)(layer[-1]))
for i in range(10):
  layer.append(keras.layers.Dense(300)(layer[-1]))
  layer.append(RRELU(3, 8)(layer[-1]))
layer.append(keras.layers.Dense(2, activation='softmax')(layer[-1]))
layer.append(keras.layers.Concatenate()([layer[1], layer[-1]]))

model = tf.keras.Model(inputs=layer[0], outputs=layer[-1])
model.summary()

__________________________________________________________________________________________________
 Layer (type)                   Output Shape         Param #     Connected to
==================================================================================================
 input_1 (InputLayer)           [(None, 100)]        0           []

 dense (Dense)                  (None, 300)          30300       ['input_1[0][0]']

 dense_1 (Dense)                (None, 300)          90300       ['dense[0][0]']

 rrelu (RRELU)                  (None, 300)          0           ['dense_1[0][0]']

 dense_2 (Dense)                (None, 300)          90300       ['rrelu[0][0]']

 rrelu_1 (RRELU)                (None, 300)          0           ['dense_2[0][0]']

...

 dense_10 (Dense)               (None, 300)          90300       ['rrelu_8[0][0]']

 rrelu_9 (RRELU)                (None, 300)          0           ['dense_10[0][0]']

 dense_11 (Dense)               (None, 2)            602         ['rrelu_9[0][0]']

 concatenate (Concatenate)      (None, 302)          0           ['dense[0][0]',
                                                                  'dense_11[0][0]']

==================================================================================================
Total params: 933,902
Trainable params: 933,902
Non-trainable params: 0
__________________________________________________________________________________________________


text:
Q: Add a menu to a GtkMenuToolButton (Python) In my Python application I have some GtkMenuItems (associated with the main GtkMenuBar), and some GtkMenuToolButtons inside my GtkToolbar.
- gtkMenuBar1
   - gtkMenuItem1
      - gtkMenuItem2
      - gtkMenuItem3
- gtkToolbar1
   - gtkMenuToolButton1

By default, gtkMenuToolButton1 is obviously empty. I want to do something like
self.ui.gtkMenuToolButton1.set_menu(self.ui.gtkMenuItem1)

But if I do that (inside finish_initializing() of my window), nothing changes. I'm new to Python and Gtk3. What am I doing wrong?

A: Check the examples in Python Gtk3 Tutorial

A: You have to add a Gtk.Menu object to the menu tool button, not a Gtk.MenuItem.


text:
Q: Remove trailing and leading char using csv.reader How can I remove a certain char if my value in second column of csv starts with "(" or end with ")", I'm very new to python guys help me to solve this
Example:
0023632fa4a860be8bc85ddf39fc19c3c4c2e6fe,(Java Archive (JAR) 4049-0),Not Supported,
005c41fc0f8580f51644493fcbaa0d2d468312c3,(WIN32 EXE 7-2),Ransom.Win32.TRX.XXPE50FFF027,

to
0023632fa4a860be8bc85ddf39fc19c3c4c2e6fe,Java Archive (JAR) 4049-0,Not Supported,
005c41fc0f8580f51644493fcbaa0d2d468312c3,WIN32 EXE 7-2,Ransom.Win32.TRX.XXPE50FFF027,

I have this code using DATA INFILE
TRIM(TRAILING ')' FROM TRIM(LEADING '('

How can I apply it here in my code:
with open(fullPath, 'rb') as file:
     csv_data = csv.reader(file)
     next(csv_data)

A: A solution using lstrip() and rstrip()
import csv

new_rows = []
with open('test.csv', 'rt') as file:
    csv_data = csv.reader(file, delimiter=',')
    for row in csv_data:
        new_rows.append([row[0],row[1].lstrip('(').rstrip(')'),row[2]])

print(new_rows) # Outputs ['0023632fa4a860be8bc85ddf39fc19c3c4c2e6fe,Java Archive (JAR) 4049-0Not Supported', '005c41fc0f8580f51644493fcbaa0d2d468312c3,WIN32 EXE 7-2ansom.Win32.TRX.XXPE50FFF027']

Edit
To save the edit on a new .csv file just add:
with open('test2.csv', 'wt') as file:
    writer = csv.writer(file)
    for row in new_rows:
        writer.writerow(row)

A: Here's one way of doing it, I've replaced the first occurrence and the last occurrence of '(' and ')' from the string. Hope it helps.
s = '''0023632fa4a860be8bc85ddf39fc19c3c4c2e6fe,(Java Archive (JAR) 4049-0),Not Supported,
005c41fc0f8580f51644493fcbaa0d2d468312c3,(WIN32 EXE 7-2),Ransom.Win32.TRX.XXPE50FFF027,'''

def last_replace(s, old, new, occurrence):
    '''Replaces the last occurence of the character'''
    li = s.rsplit(old, occurrence)
    return new.join(li)

new_string = [last_replace(line, ')', '', 1).replace('(', '', 1) for line in s.split('\n')]
print(new_string)

Output:
['0023632fa4a860be8bc85ddf39fc19c3c4c2e6fe,Java Archive (JAR) 4049-0,Not Supported,',
'005c41fc0f8580f51644493fcbaa0d2d468312c3,WIN32 EXE 7-2,Ransom.Win32.TRX.XXPE50FFF027,']

PS : I stole the last_replace function from here

A: This is a great opportunity to learn about regular expressions! Regular expressions are a method for recognising and dealing with patterns in text. Python has a regular expressions package as part of its standard library. I'm going to assume you're using Python 3 for the rest of this answer, where the package is named re.
The TLDR answer to your question is:
import re

string_without_parens = re.sub(r'(^\()|(\)$)', '', string_maybe_has_parens)

What's going on here, though? the re.sub() function takes three parameters, a regular expression string (denoted by the leading r), a string that you want to replace each match with, and the string you want to substitute in. The regular expression here is (^\()|(\)$). So what does that mean? Lets take it step by step:

*

*A set of parentheses () represents a capture group, these can be used to get the matches out, but I've used them as a way to group characters we're looking for together. There are two capture groups in this regular expression: (^\() and (\)$).

*Between these is a | character, this represents OR in regular expression language, so it's looking for something that matches either (^\() or (\)$).

*The first capture group (^\(): has two things inside it (well, three really, but we'll get to that). The first is ^, this is what is called an anchor, this one in particular says, "only look at the start of the string". The second (and third) characters are \( which says "I want to look for an opening parentheses". Because parentheses are using in regular expressions, we have to use the backslash character to "escape" it.

*The second capture group (\)$): contains an escaped closing parenthesis \) and other anchor. This anchor represents the end of the string, in the same way ^ represented the start.

*Together this says: "match an opening parentheses at the beginning or a closing parenthesis at the end", and the re.sub() function says replace anything that matches this pattern with '' (i.e. nothing).

Hope that helps! If you want to play more with regular expressions, you can try out regexr, which helped me wrap my head around them.


text:
Q: How to increase the sound Volume Output in Webrtc Am working on a webrtc android application and everything is working fine except two things...
which are;

*

*switching the default sound output device from the Earpiece to Speaker and vice versa..
I have tried to use the code below from this stackoverflow thread but they are not working

audioManager = (AudioManager) this.activity.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(true);
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);

*And improving the video performance, there is a lot of lagging in the video streams where even the stream hangs a lot. if there is any one who can help me on this too thanks a lot.
Below is my peerConnection configs

String fieldTrials = (PeerConnectionFactory.VIDEO_FRAME_EMIT_TRIAL + "/" + PeerConnectionFactory.TRIAL_ENABLED + "/");
PeerConnectionFactory.InitializationOptions initializationOptions =
                PeerConnectionFactory.InitializationOptions.builder(this)
                        .setFieldTrials(fieldTrials)
                        .createInitializationOptions();
PeerConnectionFactory.initialize(initializationOptions);

//Create a new PeerConnectionFactory instance - using Hardware encoder and decoder.
PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
DefaultVideoEncoderFactory defaultVideoEncoderFactory = new DefaultVideoEncoderFactory(
                rootEglBase.getEglBaseContext(),  /* enableIntelVp8Encoder */true,  /* enableH264HighProfile */true);
DefaultVideoDecoderFactory defaultVideoDecoderFactory = new DefaultVideoDecoderFactory(rootEglBase.getEglBaseContext());

peerConnectionFactory = PeerConnectionFactory.builder()
                .setOptions(options)
                .setVideoEncoderFactory(defaultVideoEncoderFactory)
                .setVideoDecoderFactory(defaultVideoDecoderFactory)
                .createPeerConnectionFactory();

Thanks

A: Need add this permission in manifest
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>


text:
Q: Rails+Bootstrap Modal renders but doesn't show I can get the modal to render in the DOM, but I can't get it to show, I get it to flash for an instant, but it doesn't stay. Here is the relevant code.
tasks_controller.rb
def edit
  @task = Task.find(params[:id])
  respond_to do |format|
    format.html
    format.js
  end
end

edit.js.erb
$(document).ready( function() {
  $("#edit_task_modal").html("<%= escape_javascript(render 'tasks/edit_task_modal') %>");
  $("#edit_task_modal").modal('show');
});

_edit_task_modal.html.erb

      <button id="close_edit_task_modal" type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Edit Task

    <%= form_for(:task, url: {action: 'update', id: @task.id},:html => {:class => 'form-horizontal'}) do |f| %>

          <%= render(partial: 'form', locals: {f: f}) %>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <%= f.submit 'Save Changes', class: 'btn btn-primary' %>

    <% end %>

_task_div.html.erb

  Title: <%= "#{task.title}" %>

  Description: <%= "#{task.description}" %>

  Status: <%= "#{task.status}" %>

  Due Date: <%= "#{task.due_date}" %>

  Completed Date: <%= "#{task.completed_date}" %>

    <%= link_to 'Edit', {controller: 'tasks', action: 'edit', id: task.id},  {:remote => true, 'data-toggle' =>  "modal", 'data-target' => '#edit_task_modal'}  %>

show.html.erb

EDIT: Added modal code

A: Turns out all I had to do was remove 'data-toggle'='modal' from the link to the modal.  The javascript was showing it, then the html would toggle it making it hidden again.


text:
Q: When will $A[x_1, \ldots, x_n]$ satisfy the dimension formula?
What property should $A$ satisfy so that $A[x_1, \ldots, x_n]$  satisfies the dimension formula,
  $$\mathrm{dim}(A[x_1, \ldots, x_n]) = \mathrm{dim}(A[x_1, \ldots, x_n]/\mathfrak{p}) + \mathrm{ht}(\mathfrak{p}),$$ for any prime ideal $\mathfrak{p}$ in $A[x_1, \ldots, x_n]$?

For instance, this property holds when $A$ is a field. Is there a general property that ensures this formula is satisfied?


text:
Q: Dynamically assigns different value for the environment variable upon a Docker service scale For some situation, we might need to scale up the service and assign the different value for the environment variable, for example, NODE_ID (to be used internally).
Usually, I create a script to run my service with a dynamic parameter as preferred scale.
$ docker run -e NODE_ID=node_01 ...
$ docker run -e NODE_ID=node_02 ...
...
$ docker run -e NODE_ID=node_20 ...

Question
Is there any way to achieve this with the docker swarm mode, e.g.
$ docker service create ... ?

A: I believe the only value you can get it the container id by using $(hostname). That gives you a unique value for each container. There is no way to provide a custom one.


text:
Q: How to select a node using Alpha Beta I am implementing an AI for an Othello game using MiniMax with Alpha Beta pruning. I have implemented an Alpha Beta algorithm that tells me the value that I can obtain, but not which node it is that I should select? So my question is how can I use Alpha-Beta to tell me which node I should select, not what the resultant value would be. Here is the pseudocode for my Alpha-Beta algorithm.
01 function alphabeta(node, depth, α, β, maximizingPlayer)
02      if depth = 0 or node is a terminal node
03          return the heuristic value of node
04      if maximizingPlayer
05          v := -∞
06          for each child of node
07              v := max(v, alphabeta(child, depth – 1, α, β, FALSE))
08              α := max(α, v)
09              if β ≤ α
10                  break (* β cut-off *)
11          return v
12      else
13          v := ∞
14          for each child of node
15              v := min(v, alphabeta(child, depth – 1, α, β, TRUE))
16              β := min(β, v)
17              if β ≤ α
18                  break (* α cut-off *)
19          return v

A: If you only want to know the best move in the root position, it is enough to remember which move in the root position had the highest score. For that, just returning the score is enough. No change in the pseudo-code is necessary.
As you are asking about the path to the critical node, I guess you are asking about a way to reconstruct the principal variation, which gives insights about the series of moves that the search expected.
In theory, you can just return the value and the principal variation from the recursive call. That allows you to reconstruct the path. Triangular PV-Tables are data structures optimized for that purpose.
If your search uses a transposition table, a simpler approach is just to start the root position and look up the best move in the transposition table. Then make that move and repeat (look up the best move, make the best move, lookup again, etc.) until the game is over or no entry has been found. In the end, the moves that were made are the principal variation.
The transposition table approach is not as precise as explicitly keeping track of the principal variation, but it is simple to implement and adds no overhead during the search.


text:
Q: Tests fail with has_paper_trail I have an app with two models - news and audio.
Having added paper_trail to the project, and putting has_paper_trail in both the models, the app works correctly, but some tests for the news model fail.
News items have a method that check the body for a valid audio URL, and then looks that up (Audio.find) based on the ID in the URL. It is this, and similar methods that call other models, that fail.
If I remove has_paper_trail from the audio spec, the news tests all pass. The audio tests all pass with or without.
PaperTrail is disabled for tests (and I have a test to check that is the case).
What is causing the news test that call a method on another model to fail, but work in production?

A: After spending a few more hours messing around with the code I found the problem and solution myself.
One of my included modules clashes with PaperTrail (it has callbacks).
I moved has_paper_trail to be first in the class declaration (before my modules) and the tests all started passing again.


text:
Q: Git roto : git add . da error: short read No such file or directory No sé porque pero en un momento cuando traté de agregar mi progreso a mi depósito que tenía :
(MoodEnv) mike@mike-thinks:~/Programing/Rasa/Moodbot$ git add .
Bus error (core dumped)

Entonces intento de nuevo pero me dice que un fichero ya existe :
(MoodEnv) mike@mike-thinks:~/Programing/Rasa/Moodbot$ git add .
fatal: Unable to create '/home/mike/Programing/Rasa/Moodbot/.git/index.lock': File exists.

If no other git process is currently running, this probably means a
git process crashed in this repository earlier. Make sure no other git
process is running and remove the file manually to continue.

Por eso :
(MoodEnv) mike@mike-thinks:~/Programing/Rasa/Moodbot$ rm .git/index.lock

    error: short read No such file or directory
    error: MoodEnv/lib/python3.5/site-packages/libfuturize/fixes/__pycache__/fix_UserDict.cpython-35.pyc: failed to insert into database
    error: unable to index file MoodEnv/lib/python3.5/site-packages/libfuturize/fixes/__pycache__/fix_UserDict.cpython-35.pyc
    fatal: updating files failed

Actualización 31/05/2018
No estoy seguro de que eso sea lo que funcionó, pero hizo :
rm -f ./.git/index.lock

Y ahora me dice :
(MoodEnv) mike@mike-thinks:~/Programing/Rasa/Moodbot$ git add .
(MoodEnv) mike@mike-thinks:~/Programing/Rasa/Moodbot$ git commit -m "milestone : ready to work, don't forget to add the true credentials"
[master 5db6840] milestone : ready to work, don't forget to add the true credentials
 19 files changed, 2127 insertions(+), 524 deletions(-)
 rewrite models/dialogue/policy_1_KerasPolicy/featurizer.json (92%)
 rewrite models/dialogue/policy_1_KerasPolicy/keras_arch.json (100%)
 rewrite models/dialogue/policy_1_KerasPolicy/keras_weights.h5 (73%)
(MoodEnv) mike@mike-thinks:~/Programing/Rasa/Moodbot$ git push origin master
Username for 'https://github.com': antoinecomp
Password for 'https://antoinecomp@github.com':
Counting objects: 23662, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (20906/20906), done.
Writing objects: 100% (23662/23662), 392.91 MiB | 1.41 MiB/s, done.
Total 23662 (delta 3553), reused 11501 (delta 2261)
remote: Resolving deltas: 100% (3553/3553), completed with 13 local objects.
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
remote: error: Trace: 18f9ed182009e2704aa994c425387a10
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File MoodEnv/lib/python3.5/site-packages/en_core_web_md/en_core_web_md-2.0.0/vocab/lexemes.bin is 123.03 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File MoodEnv/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so is 112.42 MB; this exceeds GitHub's file size limit of 100.00 MB
To https://github.com/antoinecomp/moodbot4.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/antoinecomp/moodbot4.git'

Parece que la razón porque no funciona esta a causa de un fichero que pesa mas que 100Mb. Es extraño porque pensaba que los añadí todos en el .gitignore pero tal vez uno se añadí. Aquí esta el .gitignore :
/MoodbotEnv/*

Intentando eliminar los archivos de gran tamano que que alguna vez pasaron por control de versiones siguiendo esta respuesta obtuve :
mike@mike-thinks:~/Programing/Rasa/Moodbot$ git rev-list --objects --all |\
 git cat-file --batch-check='%(objectsize) %(rest)' |\
 awk '$1 >= 100 * 2^20' |\
 sort --numeric-sort --key=1 |\
 numfmt --field=1 --to=iec-i --suffix=B --padding=7 --round=nearest
 112MiB MoodEnv/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so
 123MiB MoodEnv/lib/python3.5/site-packages/en_core_web_md/en_core_web_md-2.0.0/vocab/lexemes.bin

Pero para eliminar ese archivo de la historia para siempre, no funciona como en la respuesta, parece haber algún compromiso para hacer :
mike@mike-thinks:~/Programing/Rasa/Moodbot$ git filter-branch -f --index-filter
'git rm --cached --ignore-unmatch
MoodEnv/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so' HEAD
Cannot rewrite branches: Your index contains uncommitted changes.

A: Tu problema es que estás intentando pushear archivos que pesan más de 100Mb y github no permite eso. Yendo más allá, no tienes por qué tener bajo control de versiones las dependencias del proyecto.
Sería más sensato quitar esos archivos del control de versiones añadiendo MoodEnv al .gitignore y eliminarlos con  git rm --cached -f MoodEnv.
Sin embargo ya tienes esos archivos versionados, de manera que aunque los quites, siguen en tu historial y al hacer push intentará subir la referencia a esos archivos por el sólo hecho de que alguna vez estuvieron versionados.
La solución sería hacer
git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch MoodEnv' HEAD

Revisa esta respuesta para el procedimiento completo.
Al quitar el contenido de tu virtualenv del control de versiones, el resto de los colaboradores tendrán que recrear el virtualenv cuando quieran trabajar en el proyecto. Para eso tendrás que tener versionado el archivo requirements.txt con las dependencias.
pip freeze > requirements.txt
git add requirements.txt
git commit requirements.txt -m "añade requirements.txt"

Y luego tus colaboradores, si no tienen el directorio de virtualenv, tendrían que crearlo e instalar las dependencias (por ejemplo con  venv):
python3 -m venv "MoodEnv"
source MoodEnv/bin/activate
pip install -r requirements.txt

Y repetir el pip install cada vez que se añada una dependencia al proyecto.

A: Una solución si tienes el proyecto subido a un repositorio es hacer un clone del proyecto , coger el fichero .git y a partir de hay haces el commit.

*

*Borras el .git que tienes o mejor , lo copias cambiándole el nombre por si encuentras una solución más óptima.

*Clonas el repositorio de nuevo en otra carpeta con distinto nombre.

*Copias el git de ese repositorio , al que no le funciona correctamente el comando git , donde puedes hacer ya los comandos míticos.
git add .
git commit -m ""


text:
Q: Winter Bash Hats On profile pic are visible only to logged in users? If I am logged in, I can see that on the user's profile page, the hat is visible. But if I open the profile URL of the same user after logging out, there is no hat on the gravatar. Shouldn't it still be visible?

A: This is the case on those sites were you only get hats when you opt in, either by clicking "I love hats", or by simply wearing a hat. These sites are:

*

*Stack Overflow

*Tex

*Homebrew

*Quant

*Mechanics

*Bitcoin

*Linguistics

*Chinese

*Poker

*Mathematica

*Russian

*Open data

*Sound

For Stack Overflow, the reason is mainly performance; for the others it's because the sites didn't opt in to showing hats by default. Math Overflow is completely hatless.


text:
Q: strange JS syntax, what does it mean? I recently came across this strange JavaScript code:
export type ImageSource = {
  id: string,
  URI: string,
  thumbnail: string,
  title: ?string,
  description: ?string
}

type Props = {
  images: Array<ImageSource>,
  onPressImage?: Function,
  topMargin?: number,
  closeText?: string,
  infoTitleStyles?: Animated.View.style,
  infoDescriptionStyles?: Animated.View.style,
  enableTilt?: boolean
}

If I understand it correctly, string is a data type, but can someone explain, what is the difference between string and ?string.
Also, what does the following line of code mean:
topMargin?: number,

I've got it from a sample react-native app, I'm assuming, it signifies an optional property, but I can't find any explanation when googling for it.

A: This is most probably either Typescript or Flow. topMargin?: number represents an optional parameter and title: ?string represents maybe types.


text:
Q: Why an application starts with FPU Control Word different than Default8087CW? Could you please help me to understand what is going on with FPU Control Word in my Delphi application, on Win32 platform.
When we create a new VCL application, the control word is set up to 1372h. This is the first thing I don't understand, why it is 1372h instead of 1332h which is the Default8087CW defined in System unit.
The difference between these two:
1001101110010  //1372h
1001100110010  //1332h

is the 6th bit which according to documentation is reserved or not used.
The second question regards CreateOleObject.
function CreateOleObject(const ClassName: string): IDispatch;
var
  ClassID: TCLSID;
begin
  try
    ClassID := ProgIDToClassID(ClassName);
{$IFDEF CPUX86}
    try
      Set8087CW( Default8087CW or $08);
{$ENDIF CPUX86}
      OleCheck(CoCreateInstance(ClassID, nil, CLSCTX_INPROC_SERVER or
        CLSCTX_LOCAL_SERVER, IDispatch, Result));
{$IFDEF CPUX86}
    finally
      Reset8087CW;
    end;
{$ENDIF CPUX86}
  except
    on E: EOleSysError do
      raise EOleSysError.Create(Format('%s, ProgID: "%s"',[E.Message, ClassName]),E.ErrorCode,0) { Do not localize }
  end;
end;

The above function is changing control word to 137Ah, so it is turning on the 3rd bit (Overflow Mask). I don't understand why it is calling Reset8087CW after, instead of restoring the state of the word which was before entering into the function?

A: The 6th bit is reserved and ignored. Those two control words are in fact equal in the sense that the FPU behaves the same. The system just happens to set the reserved bit. Even if you attempt to set the value to $1332, the system will set it to $1372. No matter what value you ask the 6th bit to have, it will always be set. So, when comparing these values you have to ignore that bit. Nothing to worry about here.
As for CreateOleObject the authors decided that if you are going to use that function then you are also going to mask overflow when using the COM object, and indeed beyond. Who knows why they did so, and for 32 bit code only? Probably they found a bunch of COM objects that routinely overflowed, and so added this sticking plaster. It wasn't enough to mask overflow on creation, it also need to be done when using the object so The RTL designers chose to unmask overflow henceforth.
Or perhaps it was a bug. They decided not to fix it for 32 bit code because people relied on the behaviour, but they did fix for 64 bit code.
In any case this function does nothing very special. You don't need to use it. You can write your own that does what you want it to do.
Floating point control is a problem when working with interop. Delphi code expects unmasked exceptions. Code built with other tools typically masks them. Ideally you would mask exceptions when you call out of your Delphi code and unmask them on return. Expect other libraries to arbitrarily change the control word. Also be aware that Set8087CW is not thread safe which is a massive problem that Embarcadero have refused to address for many years.
There's no easy way forward. If you aren't using floating point in your program then you could simply mask exceptions and probably be fine. Otherwise you need to make sure that the control word is set appropriately at all points in all threads. In general that is close to impossible using the standard Delphi RTL. I personally handle this by replacing the key parts of the RTL with threadsafe versions. I have documented how to do so in this QC report: QC#107411.

A: Disclaimer: I debugged the questions in Delphi XE.
First, the second question.
If you look at the code of Set8087CW you will see that it stores the new FPU CW value in Default8087CW variable, and Reset8087CW restores FPU CW from Default8087CW; so the Reset8087CW call after Set8087CW does nothing at all, which is demonstrated by
Memo1.Lines.Clear;
Memo1.Lines.Add(IntToHex(Get8087CW, 4));   // 1372
Set8087CW( Default8087CW or $08);
Memo1.Lines.Add(IntToHex(Get8087CW, 4));   // 137A
Reset8087CW;
Memo1.Lines.Add(IntToHex(Get8087CW, 4));   // 137A

Evidently a bug.
Now the first question - it was interesting debugging exercise.
The Default8087CW value of Delphi VCL application is changed from hex 1332 to 1372 by Windows.CreateWindowEx function, called from Classes.AllocateHWnd, called from TApplication.Create, called from initialization section of Controls.pas unit.
Have a look at CreateWindowEx code - it explains what happens. I don't really want to discuss it further - the FPU support in Delphi is too messy and buggy.


text:
Q: Changing web.config and session lifecyle If I change (and upload) the web.config of an ASP.NET site, do existing users surfing the site lose their sessions?
Also, does the IIS server need to be reset?

A: If the session is in proc, then yes, they do loose their sessions.
If you are using a session server then no, they don't.
A new web.config would cause a restart of the site automaticlly, but should not require an IIS reset.

A: Modifying the web.config file will cause the application to restart an it is equivalent to recycling the application pool. If you are using InProc session management, then yes, all user sessions will be lost. No, an IIS reset is not needed.


text:
Q: C++ bitwise OR operator bool OrderUtils::shouldCptyAutoexecute(int Id)
{

bool res =
    dummyCache::instance().getVal(Id).getWhitelabelType() == "ABCD";
if (!res)
    res |= dummyCache::instance().getVal(Id).getIsPlc() == 1;

return res;
}

The above code checks for 2 Id's and returns true to res if any of the id is present in the database.
Can you suggest a way in which I can compare one more value from the databse table and return true to the value res..Also can you explain what does the second if statement do and the bitwise OR operator?

A: Sir, just let the short-circuit eval do this for you:
return dummyCache::instance().getVal(Id).getWhitelabelType() == "ABCD" ||
       dummyCache::instance().getVal(Id).getIsPlc() == 1;

If the first is true, the second will not fire. Moreover, I assure you a remotely-reasonable optimizing compiler will not re-fire instance().getVal(id) if the returned object has not changed between the getWhitelabelType() and getisPlc() calls. In fact, i would all-but-guarantee it if getWhiteLabelType() is const. (and it certainly looks like it should be).
Regarding the bit work. The expression was pretty-much whacked. though it will work. Unless I read it wrong (and trust me, the list of people that will tell me I am will let me know quickly) it is performing a boolean eval, promoting the resulting true/false bool to an int, promoting the current value of res from bool to int (which is zero, so nothing special there), bitwise-OR-ing that with the expression int, then demoting the final int back to a bool to store in res . I'm surprised this doesn't flag at least a warning on the compiler.
It likely should have been if (!res) res ||= expr, and even then, it is pointless, as you can just use short circuit eval as in the top of this answer to cut out the local res entirely. Consider if res were false. Then the equivalent expression would be res = false || expr. But thats just res = expr. In the !res state it executes in, you may as well just use an assignment.
Finally, regarding adding a third field to your eval, it depends entirely on how you want it added. for an additional logical OR it is pretty simple.
For an expression like (A || B || C) you can just
return dummyCache::instance().getVal(Id).AField() == ATestValue ||
       dummyCache::instance().getVal(Id).BField() == BTestValue ||
       dummyCache::instance().getVal(Id).CField() == CTestValue;

For more complex operations, some judicious use of parenthesis will go a long way. For example, to return (A || B) && C:
return (dummyCache::instance().getVal(Id).AField() == ATestValue ||
        dummyCache::instance().getVal(Id).BField() == BTestValue) &&
       dummyCache::instance().getVal(Id).CField() == CTestValue;

Or perhaps (A && C) || (B && !C) (ok this is getting a little overboard...)
return (dummyCache::instance().getVal(Id).CField() == CTestValue)
       ? (dummyCache::instance().getVal(Id).AField() == ATestValue)
       : (dummyCache::instance().getVal(Id).BField() == BTestValue);


text:
Q: Symfony Elasticsearch criteria I want to filter post criteria:
SELECT * FROM posts WHERE (title LIKE '%AA%' OR subtitile LIKE '%BB%') AND category = 'Car'

What I try:
$finder = $this->container->get('fos_elastica.finder.website.article');
$boolQuery = new \Elastica_Query_Bool();

$fieldQuery = new \Elastica_Query_Text();
$fieldQuery->setFieldQuery('title', '*keyword*');
$fieldQuery->setFieldParam('title', 'analyzer', 'my_analyzer');
$boolQuery->addShould($fieldQuery);

$fieldQuery1 = new \Elastica_Query_Text();
$fieldQuery1->setFieldQuery('subtitle', '*keyword*');
$fieldQuery1->setFieldParam('subtitle', 'analyzer', 'my_analyzer');
$boolQuery->addShould($fieldQuery1);

$fieldQuery2 = new \Elastica_Query_Text();
$fieldQuery2->setFieldQuery('category', 'Car');
$boolQuery->addMust($fieldQuery2);

$data = $finder->find($boolQuery);

I get ALL post of 'Car' category and some of this post contains 'keyword', but I need have only post of 'Car' category what contais keyword 'keyword' but not ALL
How to fix my code.

A: Replace both addShould with addMust.
I also recommend using https://github.com/ongr-io/ElasticsearchBundle instead of https://github.com/FriendsOfSymfony/FOSElasticaBundle :)


text:
Q: jQuery enable form if checked checkboxes into array I am trying to enable form if checkboxes that are currently checked and store them into an array.
Here is my form code so far:
<?php $index = 0; ?>
@foreach($dayOfWeek as $key => $day )

                {!! Form::text('parttimeAvailabilities['.$index.'][day]',$day, ['class' => 'form-control','disabled'])!!}
                {!! Form::hidden('parttimeAvailabilities['.$index.'][day]',$key, ['class' => 'form-control'])!!}
                {!! Form::hidden('parttimeAvailabilities['.$index.'][id]',null) !!}

                {!! Form::text('parttimeAvailabilities['.$index.'][start_time]', null, ['class' => 'form-control start_time','placeholder' => 'Start time', 'disabled'])!!}

                {!! Form::text('parttimeAvailabilities['.$index.'][end_time]', null, ['class' => 'form-control end_time','placeholder' => 'End time', 'disabled'])!!}

        {!! Form::text('parttimeAvailabilities['.$index.'][hours]', null, ['id' => 'hours','class' => 'form-control','readonly'])!!}

                {!! Form::checkbox('parttimeAvailabilities['.$index.'][available]')!!}

<?php $index++; ?>
@endforeach

and here's my jQuery code so far :
$('div.parttime').each(function(index) {
        var checkbox = $('input[name="parttimeAvailabilities['+index+'][available]"]');
        var startbox = $('select[name="parttimeAvailabilities['+index+'][start_time]"]');
        var endbox = $('select[name="parttimeAvailabilities['+index+'][end_time]"]');
        $(startbox).prop("enable", $(checkbox).prop('checked'));
        $(endbox).prop("enable", $(checkbox).prop('checked'));

        $('#driverForm').bootstrapValidator('addField', startbox, {
            validators: {
                notEmpty: {
                    message: 'The start time is required and cannot be empty'
                },
            }
        });
        $('#driverForm').bootstrapValidator('addField', endbox, {
            validators: {
                notEmpty: {
                    message: 'The end time is required and cannot be empty'
                },
            }
        });
        $(checkbox).on('click', function(e) {
            $(selectbox).select2('val', '');
            var bootstrapValidator = $('#driverForm').data('bootstrapValidator');
            bootstrapValidator.enableFieldValidators(startbox, !$(checkbox).prop('checked'));
            bootstrapValidator.enableFieldValidators(endbox, !$(checkbox).prop('checked'));
            $(startbox).prop("enable", $(checkbox).prop('checked'));
            $(endbox).prop("enable", $(checkbox).prop('checked'));
        });
    });

it throws this error :

bootstrapValidator.js:1521 Uncaught TypeError: Cannot read property
  'validators' of undefined

any idea ??


text:
Q: chrome.runtime.onMessage.addListener getting invoked on every tab open I am building an extension in which content script is injected on context menu click. This functionality is working. Now the problem I am facing is that, whenever I open a new tab, the
chrome.runtime.onMessage.addListener

will get triggered without context menu click. How can I invoke the onMessage.addListener only on context menu click.
background.js

on_message = async(message, sender, sendResponse) => {
    console.log("bg.on_message");
    sendResponse("from bg");

    chrome.storage.local.get("list_url", function (data) {
        if (typeof data.list_url != "undefined") {
            urls = data.list_url
        }
    });
    chrome.storage.local.get("list_ip", function (data) {
        if (typeof data.list_ip != "undefined") {
            ips = data.list_ip
        }
    });
    chrome.storage.local.get("list_hash", function (data) {
        if (typeof data.list_hash != "undefined") {
            hashes = data.list_hash;
        }
    });

    if (hashes){
        hash_report = await createHashReport(hashes)
        hash_table = await createHashTable(hash_report)
        chrome.storage.local.set({
            "scanHash": true,
            "hash_table": hash_table
          }, () => {});
    }
    if (ips){
        ip_report = await createIpReport(ips)
        ip_table = await createIpTable(ip_report)
        chrome.storage.local.set({
            "scanIp": true,
            "ip_table": ip_table
          }, () => {});
    }
    if (urls){
        url_report = await createUrlReport(urls)
        url_table = await createUrlTable(url_report)
        chrome.storage.local.set({
            "scanUrl": true,
            "url_table": url_table
          }, () => {});
    }
    if ( hashes.length>0 || urls.length>0 || ips.length>0 ){
        chrome.windows.create({url: "output.html", type: "popup", height:1000, width:1000});
    }
}

chrome.runtime.onMessage.addListener(on_message);

genericOnClick = async () => {

    // Inject the payload.js script into the current tab after the backdround has loaded
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.scripting.executeScript({
            target: { tabId: tabs[0].id },
            files: ["payload.js"]
        },() => chrome.runtime.lastError);
    });

}

payload.js
function extract() {

    htmlInnerText = document.documentElement.innerText;
    url_exp = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
    regex =  new RegExp(url_exp)
    list_url = htmlInnerText.match(url_exp)

    ip_exp = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/;
    list_ip = htmlInnerText.match(ip_exp)

    hash_exp = /\b[A-Fa-f0-9]{32}\b|\b[A-Fa-f0-9]{40}\b|\b[A-Fa-f0-9]{64}\b/g
    list_hash = htmlInnerText.match(hash_exp)

    chrome.storage.local.set({ list_url: removeEmails(removeDuplicates(list_url)), list_ip: removeDuplicates(list_ip), list_hash: removeDuplicates(list_hash) });

}

chrome.runtime.sendMessage( extract())

A: Remove the following definition from manifest.json.
  "content_scripts": [
    {
      "js": [
        "payload.js"
      ],
      "matches": [
        "<all_urls>"
      ]
    }
  ]


text:
Q: subset Armadillo field If I understand correctly, a field in Armadillo is like a List for arbitrary objects. For instance a set of matrices of different sizes, or matrices and vectors. In the documentation I have seen the type cube which can be used with slices so you can subset using them. However, it seems there is no specific method to subset the fields.
A simplified version of my code is:
arma::mat A = eye(2,2);
arma::mat B = eye(3,3)*3;
arma::mat C = eye(4,4)*4;
arma::field<arma::mat> F(3,1);
F(0,0) = A;
F(1,0) = B;
F(2,1) = C;

// to get matrices B and C
F.slices(1,2);

but get error
Error: field::slices(): indicies out of bounds or incorrectly used

A: Firstly, there is a small error in the code you presented:
F(2,1) = C;

I assume it should be:
F(2,0) = C;

Secondly, the function slices() is only valid for 3D fields. Your field F, however, is only a 2D field because you only specify rows and columns in the constructor. To access matrices B and C, you can instead use:
arma::field<arma::mat> G=F.subfield(1,0,2,0);

or:
arma::field<arma::mat> G=F.rows(1,2);

More info on the subfield views at this page.


text:
Q: Backup sql database to Google drive using jobs How to set up a sql job for automatic backup for a sql database (Database name: Test) to a Google drive

A: *

*Use the Google

*Next, you can see to https://sqlbackupandftp.com/ or https://sqlbak.com/ or anything else tool

*Or https://dba.stackexchange.com/questions/135662/backup-sql-server-to-google-drive
Good luck


text:
Q: Git: Limit files that are pushed to remote repo I have a web project the root of which is the root of my git repo. Git is tracking most of the files in this project and pushing to a remote repo. At the root of the project I have a web.config file which I would like to track locally but not push to our remote repo.
Is this even possible with git?

A: One way would be to add a virtual reference with Gitolite installed on the Git upstream repo side (the one you are pushing to).
That kind of update hook can analyze the content of the files which are push to and reject a push if it contains the wrong file.
The VREF FILETYPE is an example.

A: This is possible, just create a file in the root of your project, and name it .gitignore (don't forget the Dot (.) in front of the file name). Then edit the file and paste whatever file you want to be ignored, for example, I like to ignore all files that have .ini extensions, so my .gitignore looks like :
<<<<<<< HEAD
# built application files
*.ini
>>>>>>>

A: You could create a separate branch (I'll call it config) and add your file there and use that branch to track changes to that file, merging in changes from your another branch (likely master).  You would then be free to push changes to the master branch without needing to push the config file.  But you would need to be careful to avoid pushing from the wrong branch.
Another option might be to commit changes to the config file in a separate repository, and have a symlink or copy in the working tree for your current repository.  Adding that to the .gitignore file would prevent git in the current repository from listing that as something to be added.  This way would be less likely to result in accidentally pushing that file to your server.

A: VonC's answer is theoretically the best, assuming you can find a tool that can do the job for you based on the git repo of your flavor.
Mohamed is on to something, but didn't quite get there.
I copied the best bet from nasirkhan on this question
After your file is production-ready, e.g.: Web.config, run this command:
git update-index --assume-unchanged Web.config

If you need to update the web config again (Track Changes), run this:
git update-index --no-assume-unchanged Web.config

git-update-index documentation


text:
Q: how to hide navigation left and right based on first and last li how to hide navigation left and right based on first and last li
I have developed a slider using jQuery to displays 3 images out of the total number of images.
functions moveRight() and moveLeft() that displays a set of 3 images on clicking the navigation link.
Now i just i want to know how to hide navLeft and navright based on first and last image.
Code is here:-
Fiddle
<script>
        var currentImage = 3;
        var numImages = 0;

        jQuery('.gallery-li').each(function () {
            numImages++;
            if (numImages <= 3) {
                jQuery('.navRight').hide();
                jQuery('.navLeft').hide();
            } else {
                jQuery('.navRight').show();
            }
        });

        jQuery('a.navLeft').click(function () {
            moveLeft();
        });

        jQuery('a.navRight').click(function () {
            moveRight();
        });

    function moveRight() {
     jQuery(".gallery-li").animate({left: "-=380px",}, "slow" );
     jQuery('.navLeft').css('display' , 'block');
    }

    function moveLeft() {
        jQuery(".gallery-li").animate({left: "+=380px",}, "slow" );
    }

</script>

Images inside gallery-li is dynamic
Any help is highly appreciated

A: Use a variable to keep a track of your movements and make conditions to the borders to hide the arrows:
Just like this:
    var currentImage = 3;
    var numImages = 0;
    var shift = 0;
    var numberOfImagesShiftedByClick = 3;
    var numberOfImagesDisplayed = 5;

    jQuery('.gallery-li').each(function () {
        numImages++;
        if (numImages <= 3) {
            jQuery('.navRight').hide();
            jQuery('.navLeft').hide();
        } else
            $('.navRight').show();
    });

    jQuery('a.navLeft').click(function () {
        moveLeft();
    });

    jQuery('a.navRight').click(function () {
        moveRight();
    });

function moveRight() {
 jQuery(".gallery-li").animate({left: "-=380px",}, "slow" );
 jQuery('.navLeft').css('display' , 'block');
    shift++;
    if (1 + shift*numberOfImagesShiftedByClick + numberOfImagesDisplayed > numImages + 1)
        $("a.navRight").hide();
     $("a.navLeft").show();
}

function moveLeft() {
    jQuery(".gallery-li").animate({left: "+=380px",}, "slow" );
    shift --;
    if (shift == 0)
        $("a.navLeft").hide();
     $("a.navRight").show();
}

And here is a jsfiddle to show you this code in action: http://jsfiddle.net/Tfy8h/24/

A: Something like this will work (http://jsfiddle.net/QG9m4):
    var currentImage = 0;
    var numImages = jQuery('.gallery-li').length;

    jQuery('a.navLeft').click(function () {
        moveLeft();
    });

    jQuery('a.navRight').click(function () {
        moveRight();
    });

function updateNav() {
  var hideLeft = currentImage == 0;
  var hideRight = currentImage == numImages;

 if( hideLeft )
   jQuery('.navLeft').hide();
 else
   jQuery('.navLeft').show();

 if( hideRight )
   jQuery('.navRight').hide();
 else
   jQuery('.navRight').show();
}

function moveRight() {
 if( currentImage >= numImages )
   return;
 currentImage += 3;
 jQuery(".gallery-li").animate({left: "-=380px",}, "slow" );
 jQuery('.navLeft').css('display' , 'block');
 updateNav();
}

function moveLeft() {
    if( currentImage < 1 )
      return;
    currentImage -= 3;
    jQuery(".gallery-li").animate({left: "+=380px",}, "slow" );
    updateNav();
}

A: Try this:
var current = 3;
var numImages = $('.gallery-li').length;

jQuery('a.navLeft').click(function () {
    move();
});

jQuery('a.navRight').click(function () {
    move("right");
});
function move(d){
    if(d == "right"){
        current += 3;
        $(".gallery-li").animate({left: "-=380px",}, "slow" );
    }else{
        current -= 3;
        $(".gallery-li").animate({left: "+=380px",}, "slow" );
    }
    $(".navRight, .navLeft").show();
    if(current == 0) $(".navLeft").hide();
    if(current >=  numImages) $(".navRight").hide();
}

http://jsfiddle.net/Tfy8h/22/


text:
Q: Example equation translation in C? Originally I asked: How to tranlate equations to programming instructions. Judging by the content found @ Wikipedia: Category: Equations That's apparently too vague for simple Q&A. So I've deleted it.
Since I learn best by example, I would like to see what this equation looks like as a function in C.

(desired course is d, ground speed is Vg, heading is a, true airspeed is Va, wind direction is w, wind speed is Vw. d, a and w are angles. Vg, Va and Vw are consistent units of speed. \pi is 3.14159...)
The above equation is for calculating true ground speed Taken from the E6B flight computer
To be clear: I'm not asking for advice, opinions or rhetoric. I'm not asking you to do my homework. I'm asking for help to understand the process of translation from equation to functional implementation. Bear with me, I know there are quite a few aspects to be aware of in such an endeavour, I would simply like to explore the symmetry between these two symbol systems using my own knowledge, capabilities and understanding.
Due to the fact that I would like to explore the symmetry, I should ask that you keep program identifiers as closely related to their representation in the formula as possible. Key words, catch phrases and rule references pertinent to this example translation in context (code comments) are a plus.
If my question is flawed due to an OVERSIGHT, please express your opinion in the comments below.

A: You enter formulas very much like you would in a graphing calculator. The part with the cos would go like this:
#include <math.h>

int main(void) {
    double d, w, da;
    double result;

    result = cos( ( M_PI * ( d - w + da ) ) / ( 180 * M_PI / 180 ) );
}

You can probably add the rest of the formula quite easily. Of course you have to initialize all your variables with something reasonable before computing the result, and finally do something with it. Don't put it all on one line, use temporary variables (so in the next step you substitute the previous result for the entire cos expression) and split the calculation to parts that you can meaningfully describe in domain-specific terms, if possible.
Now regarding what to do differently in programming compared to a math publication, often other programmers won't be experts in your domain. I don't know at all for example what that formula does just by looking at it. Therefore I'd appreciate renaming the variables and adding comments relevant to the practical use of the formula (your question didn't originally explain what the variable names mean so I came up with very plausible ones). Like this:
#include <math.h>

int main(void) {
    double density, angledelta;
    double weight; /* Weight of cake with plate included. */
    double deg2rad;
    double result;

    deg2rad = M_PI / 180;

    /* Calculate X coordinate of next cake slice intersection with cake perimeter
       using fair cake splitting with density heuristics. */

    result = cos( ( M_PI * ( density - weight + angledelta ) ) / ( 180 * deg2rad ) );
}

A: To naively convert an equation into c you break it into parts based off the order of operations. Then you can refine it as needed.
The way I would break it down:
The function would have the parametres: d, w, deltaA, Va, Vw

*

*Step1 = d - w + ΔA

*Step2 = Math.PI * Step1

*Step3 = Step2 / 180 ignore the units(deg)

*Step4 = cos(Step3)

*Step5 = Va * Va

*Step6 = Vw * Vw

*Step7 = 2 * Va * Vw

*Step8 = Step5 + Step6 - Step7

*Step9 = Step8 * Step4

*Step10 = Math.sqrt(Step9)

*Return Step10


text:
Q: How can I get pstricks and tikz to work in the same document? I'm trying to get a \psbarcode in my document which also uses a tikzpicture. I'm using \usepackage{auto-pst-pdf,pst-barcode}, but---even though the document compiles and shows a document afterwards---the barcode doesn't show up... Any ideas what I should do exactly?

A: This works for me with pdflatex --shell-escape myfile assuming that the following is saved as myfile.tex.
\documentclass{article}
\usepackage{auto-pst-pdf}
\usepackage{pst-barcode}
\usepackage{tikz}
\begin{document}
    \begin{tikzpicture}
      \draw (0,0) circle(2cm);
    \end{tikzpicture}
    \begin{pspicture}
    \psbarcode[scalex=.75,scaley=.75]
    {Harish Kumar}{eclevel=L}{qrcode}
    \end{pspicture}
\end{document}

Edit
I think some more help is needed in compiling as per the comments. In TeXworks, Go to Edit → Preferences. The following window appears:

Here click Typesetting tab. In this click + button (shown with arrow above). In the small new tool window that opens,  enter the following values:

Click OK in all and come out. Now compile with pdflatexshell by selecting it in the drop down menu next to green arrow.

Hope it will be useful.
Flying with arara
You can also use the tex automation tool arara. Download and install arara. In texlive, it comes along with by default. Add a menu entry in TeXworks for arara. The elegantly written manual has a section on how to do this for different editors including TeXworks. Follow the steps above (for pdflatexshell) and in the new tool window type like this:

Now press OK whenver you find it and you will have a new menu in the drop down list next to green arrow. Choose arara in it. Add the line % arara: pdflatex: { shell: yes} like
% arara: pdflatex: { shell: yes}
\documentclass{article}
\usepackage{auto-pst-pdf}
\usepackage{pst-barcode}
\usepackage{tikz}
\begin{document}
    \begin{tikzpicture}
      \draw (0,0) circle(2cm);
    \end{tikzpicture}
    \begin{pspicture}
    \psbarcode[scalex=.75,scaley=.75]
    {Harish Kumar}{eclevel=L}{qrcode}
    \end{pspicture}
\end{document}

in your code and press green button:

A: Run with xelatex:
\listfiles
\documentclass{article}
\usepackage{pst-barcode}
\usepackage{tikz}
\begin{document}
    \begin{tikzpicture}
      \draw (0,0) circle(2cm);
    \end{tikzpicture}
    \begin{pspicture}(1in,1in)
    \psbarcode[scalex=.75,scaley=.75]{foo}{eclevel=L}{qrcode}
    \end{pspicture}
\end{document}


text:
Q: I get an error (No 'Access-Control-Allow-Origin' header is present on the requested resource) when I access my react app using Heroku I made a simple chat app using react and socket.io. It all went good,the app worked fine on localhost ,but when I deployed the app with Heroku ,I get the same error.
No 'Access-Control-Allow-Origin' header is present on the requested resource
This is how I connect to the server in the react app
import React,{Component} from 'react';
import './App.css';
import { SocketProvider } from 'socket.io-react';
import io from 'socket.io-client';

const socket = io.connect('https://react-zoichenger.herokuapp.com');

This is my nodejs server
const express =require('express')
const socket = require('socket.io')

var cors = require('cors')
var app = express()

app.use(cors())

const server = app.listen(4000,function(){
  console.log("Connected");
})

//Socket setup
const io = socket(server);

io.on('connection',(socket)=>{
  socket.on('sendMessage',(data)=>{
    console.log(data);
    io.emit('receiveMessage',data);
  })
  console.log('made socket connection')
});

A: Try to modify your server-side code
var io = require('socket.io')(server, { origins: '*:*'});


text:
Q: Getting another users email address in Facebook app Am developing a system for an app to award points users for recruiting their friends. When the friend accepts the request I can retrieve the id of the person who invited them but can not find their email.
Have tried:
    $fbInviter = $facebook->api("/$inviterId", 'GET');
    $fbInvEmail = $fbInviter['email'];

but it appears ['email'] isn't in the returned array.
The app requests permission from each user when the first access it aswell as requesting offline access so permissions shouldn't be a problem.
Any ideas?

A: There is no way to get the email address for a Facebook user other than the current user, and the current user's address is only available if they've granted you the email extended permission


text:
Q: How can I find the roots for $x^4-18x^2-8x+21$ in a nice form? I'm trying to find the roots for $x^4-18x^2-8x+21$. Theoretically, one can show that it has four real roots. But the following line returns four complicated forms including complex numbers.
Is there a way to reduce the results to be in a nice form?
Solve[x^4-18x^2-8x+21==0,x]

A: To make the radical representation explicitly real, use the TargetFunctions option with ComplexExpand
roots = Solve[x^4 - 18 x^2 - 8 x + 21 == 0, x] //
  ComplexExpand[#, TargetFunctions -> {Abs, Arg}] &

(*  {{x ->
       -Sqrt[3 + 4*Cos[(1/3)*ArcTan[
                       Sqrt[39]/5]]] -
         (1/2)*Sqrt[24 -
               16*Cos[(1/3)*ArcTan[
                       Sqrt[39]/5]] -
               8/Sqrt[3 + 4*Cos[(1/3)*
                         ArcTan[Sqrt[39]/5]]]]},
   {x ->
       -Sqrt[3 + 4*Cos[(1/3)*ArcTan[
                       Sqrt[39]/5]]] +
         (1/2)*Sqrt[24 -
               16*Cos[(1/3)*ArcTan[
                       Sqrt[39]/5]] -
               8/Sqrt[3 + 4*Cos[(1/3)*
                         ArcTan[Sqrt[39]/5]]]]},
   {x ->
       Sqrt[3 + 4*Cos[(1/3)*ArcTan[
                     Sqrt[39]/5]]] -
         (1/2)*Sqrt[24 -
               16*Cos[(1/3)*ArcTan[
                       Sqrt[39]/5]] +
               8/Sqrt[3 + 4*Cos[(1/3)*
                         ArcTan[Sqrt[39]/5]]]]},
   {x ->
       Sqrt[3 + 4*Cos[(1/3)*ArcTan[
                     Sqrt[39]/5]]] +
         (1/2)*Sqrt[24 -
               16*Cos[(1/3)*ArcTan[
                       Sqrt[39]/5]] +
               8/Sqrt[3 + 4*Cos[(1/3)*
                         ArcTan[Sqrt[39]/5]]]]}}  *)

roots // N

(*  {{x -> -3.80007}, {x -> -1.42412}, {x -> 0.896691}, {x -> 4.3275}}  *)

A: You can obtain Root objects with
Solve[x^4 - 18 x^2 - 8 x + 21 == 0, x] // FullSimplify

or
Solve[x^4 - 18 x^2 - 8 x + 21 == 0, x] // RootReduce

but numerical roots are perhaps easier to understand.
NRoots[x^4 - 18 x^2 - 8 x + 21 == 0, x]

Convert the output of NRoots with ToRules, and pick the real roots with Cases. Plot the equation with red real roots. I wish I had Manipulate when I was studying calculus.
Manipulate[
   Module[{r = Cases[x/.{ToRules[NRoots[x^4 + a x^2 + b x + c == 0, x]]},_Real]},
      Plot[
         x^4 + a x^2 + b x + c, {x, -5, 5},
         PlotLabel -> ToString@TraditionalForm[x^4+a x^2+b x+c]<>"=0\n roots \[Rule] "<>ToString[r],
         Epilog -> {Red, PointSize[0.02], Point[Thread[List[r, 0]]]},
         Frame -> True, BaseStyle -> {FontSize -> 16}, ImageSize -> 550]],
    {{a, -18.}, -20, 20, Appearance -> "Labeled"},
    {{b, -8.}, -20, 20, Appearance -> "Labeled"},
    {{c, 21.}, -100, 100, Appearance -> "Labeled"}]

A: More like a comment.
sol = x /. Solve[x^4 - 18 x^2 - 8 x + 21 == 0, x] // N // Chop

{-3.80007, -1.42412, 0.896691, 4.3275}

The roots may be approximated with
sol2 = RootApproximant[sol, 2]

which turn out to be quite decent approximations:
res = Table[x^4 - 18 x^2 - 8 x + 21 /. x -> sol2[[i]], {i, 1, 4}] // FullSimplify

N @ res

A: Your equation seems to be a casus irreducibilis; the solutions cannot be expressed using only real numbers.
You can make them "nicer" by using Root objects (try RootReduce).
RootReduce@Solve[x^4 - 18 x^2 - 8 x + 21 == 0, x]

{{x -> Root[21 - 8 #1 - 18 #1^2 + #1^4 &, 1]},
  {x -> Root[21 - 8 #1 - 18 #1^2 + #1^4 &, 2]},
  {x -> Root[21 - 8 #1 - 18 #1^2 + #1^4 &, 3]},
  {x -> Root[21 - 8 #1 - 18 #1^2 + #1^4 &, 4]}}

Or, you can use N and Chop to get arbitrary-precision real numbers.
Chop@N@Solve[x^4 - 18 x^2 - 8 x + 21 == 0, x]

{{x -> -3.80007}, {x -> -1.42412}, {x -> 0.896691}, {x -> 4.3275}}

A: Theres plenty of great answers here but I have some similar ideas I can give you..Maybe not as elegant or as advanced as others but it is straightforward.
 Clear[f, roots]
 f[x_] := x^4 - 18 x^2 - 8 x + 21

I would recommend NSolve because it is a numerical approximation, whereas Solve  is solving it explicitly
 roots = NSolve[f[x] == 0, x]
 ={{x -> -3.80007}, {x -> -1.42412}, {x -> 0.896691}, {x -> 4.3275}}

Checks that roots are right
 f[x] /. roots//Chop
 ={0, 0, 0, 0}

I don't think this offers anymore assistance than what is already here, but oh well. You could even plot some of the roots on a graph of the curve..Say the 1st and 4th root..
 Clear[x1, x2];
 x1 = x /. roots[[1]];
 x2 = x /. roots[[4]];

 Clear[curve];
 curve = Plot[f[x], {x, -6, 6},
 AxesLabel -> {"x", "y"}, Ticks -> None, BaseStyle -> {18, FontFamily -> "Georgia"}];

 PtLabel1 = Graphics[Text["( " <> ToString[x1] <> "," <> ToString[f[x1]] <> ")", {x1, f[x1] + 50}]];

 PtLabel2 = Graphics[Text["( " <> ToString[x2] <> "," <> ToString[f[x2]] <> ")", {x2, f[x2] + 50}]];

 pt1 = Graphics[{PointSize[0.02`], Point[{x1, f[x1]}]}];
 pt2 = Graphics[{PointSize[0.02`], Point[{x2, f[x2]}]}];
 Show[curve, PtLabel1, PtLabel2, pt1, pt2]


text:
Q: Laravel 4 hostgator hosting, mkdir(): Permission denied error I've uploaded laravel 4 app to hostgator and have problems with mkdir() function, it doesn't allow me to create folders even native laravel classes such us File throw an error because File.php also uses mkdir() , I tryed to have parent directory 777 , however it doesn't solve the problem, still 'Permission denied', how do I solve the problem? or maybe there are other good hostings? where I'll not have this error

A: You php apache user may be different try change owner to the directory to php apache user.
For laravel app directory permisssions

*

*Directories should be 755

*Files should be 644

*storage & bootstrap/cache 777


text:
Q: Calculate the Poll Result I have a page from where users can take a poll and submit their response. A poll contains
1. Poll title/Subject
2. Question/Heading (Can be One or more)
3. four options for each question (can select only one option)
The poll response is stored in MySQL table,

*

*id int(11)

*poll_headingid int(11)

*user_id int(11)

*response varchar(50)

*subject_id int(11)

I want to calculate that how many percentages of users have submitted a response to each question. I tried to use following query and got the following result

Can anyone please help me

A: Sorry for such basic question, but I figured it out. The correct query was
select response, count(*) / (select count(*) from tbl_parent) * 100 as
percentage from poll_result
WHERE response='d'
AND poll_headingid=12
AND subject_id=4


text:
Q: iOS Creating a file in the bundle using C++ not working on ios 6 If i create a file in the simulator i am successfull with:
const char* testFile = "Test.java";
ofstream createTest;
createTest.open(testFile);
createTest << [CodeView.text UTF8String] ;
createTest.close();

On iOS 5.0 this works fine, at least in the simulator but on my upgraded version of xcode (ios 6.1)this just throws me:
 libc++abi.dylib: terminate called throwing an exception

How do i bypass this error, (is there maybe a way to load /write to an existing file in a folder using c++?)

A: The application bundle on iOS is read-only.


text:
Q: Which are the wavenumbers for the fast Fast Fourier Transform? I am having a similar problem to the one discussed here: Computing wavenumbers for discrete Fourier transform
Say I performed a FFT on $N = 256$ points, are my wavenumbers indexed as [-128,127] or [-127,128]?

A: $e^{2i \pi n (k+N)/N} = e^{2i \pi n k/N}$ for $n \in \mathbb{Z}$.
Thus it makes a difference only when you use the DFT to interpolate the signal at non-integer values.
In that case it seems legitimate to ask : the interpolation is the smoothest possible, and it is real for real signals.
Those conditions give for $N$ even :
$$X(k) = \sum_{n=0}^{N-1} x(n) e^{-2i \pi nk/N}, \qquad x(t) = \frac{1}{N}\sum_{k=-N/2+1}^{N/2-1} X(k) e^{2i \pi tk/N}   \ \ + \ \ \frac{X(N/2)}{N} \cos(\pi t)$$
Note how $\int_0^N |x(t)|^2dt= \sum_{n=0}^{N-1} |x(n)|^2 - \frac{1}{2 N} |X(N/2)|^2$, so if  you prefer to preserve instead the energy and linearity, the interpolation won't be real for real signals anymore.


text:
Q: Flask, Bcrypt - ImportError: No module named ext.bcrypt Why the following?
from flask import Flask
from flask.ext.bcrypt import Bcrypt

 Python 2.7.12 (default, Dec  4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from flask import Flask
>>> from flask.ext.bcrypt import Bcrypt
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named ext.bcrypt

I have flask-bcrypt installed:
pip install Flask-Bcrypt
Requirement already satisfied: Flask-Bcrypt in /usr/local/lib/python2.7/dist-packages (0.7.1)
Requirement already satisfied: Flask in /usr/local/lib/python2.7/dist-packages (from Flask-Bcrypt) (1.0.2)
Requirement already satisfied: bcrypt in /usr/local/lib/python2.7/dist-packages/bcrypt-3.1.4-py2.7-linux-x86_64.egg (from Flask-Bcrypt) (3.1.4)
Requirement already satisfied: Jinja2>=2.10 in /usr/local/lib/python2.7/dist-packages/Jinja2-2.10-py2.7.egg (from Flask->Flask-Bcrypt) (2.10)
Requirement already satisfied: itsdangerous>=0.24 in /usr/local/lib/python2.7/dist-packages (from Flask->Flask-Bcrypt) (0.24)
Requirement already satisfied: Werkzeug>=0.14 in /usr/local/lib/python2.7/dist-packages (from Flask->Flask-Bcrypt) (0.14.1)
Requirement already satisfied: click>=5.1 in /usr/local/lib/python2.7/dist-packages (from Flask->Flask-Bcrypt) (6.7)
Requirement already satisfied: cffi>=1.1 in /usr/local/lib/python2.7/dist-packages/cffi-1.11.5-py2.7-linux-x86_64.egg (from bcrypt->Flask-Bcrypt) (1.11.5)
Requirement already satisfied: six>=1.4.1 in /usr/local/lib/python2.7/dist-packages/six-1.10.0-py2.7.egg (from bcrypt->Flask-Bcrypt) (1.10.0)
Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python2.7/dist-packages/MarkupSafe-1.0-py2.7-linux-x86_64.egg (from Jinja2>=2.10->Flask->Flask-Bcrypt) (1.0)
Requirement already satisfied: pycparser in /usr/local/lib/python2.7/dist-packages/pycparser-2.18-py2.7.egg (from cffi>=1.1->bcrypt->Flask-Bcrypt) (2.18)

This error leaves me nowhere to go.  I followed the docs here:
https://flask-bcrypt.readthedocs.io/en/latest/

A: Try using from flask_bcrypt import Bcrypt.
This is because the flask documentation on flask extensions implies that extensions in the form of Flask-Foo and are imported as: from flask_foo import Foo
http://flask.pocoo.org/docs/1.0/extensions/

A: In the recent flask's update, from flask.ext.xxx import xxx has been removed. You should import it directly from its package. And here is a related issue.
By the way, this package seems out of date(last updates two years ago).


text:
Q: AWS - access the file in a folder in a s3 bucket using Java I want to access the files in a particular s3 bucket folder (There's a folder structure).
I want to get that file as an File object in java. I have the bucket name, region name and the access id is with me.
Please let me know how to do this or a link that I can refer to.
Thanks in advance

A: The implementation to be used may be the same as the AWS documentation, however when it is necessary to read a file inside a folder, you need to specify which folder is the file.
For example, we want to get a file named listOfCountries.json inside the world folder, when you pass the key to access the S3 report folder.
System.out.println("Downloading an object");
fullObject = s3Client.getObject(new GetObjectRequest("bucketName", "world/listOfCountries.json"));

A: You can't get that as a File object in Java since it isn't a local file. You have to download it first if you want to use the File class. Otherwise look at the methods available in the AWS SDK for Java.


text:
Q: How to limit size of redirected stdout in exe4j We're using install4j/exe4j to create a windows launcher. We configure the redirection of stdout / stderr in Advanced Options / Exe4j Wizard - Redirection.
Is it possible to limit the size of the log generated? Or even better: something like the rolling file appender in log4j?
Regards,
Markus

A: No, this is not a supported feature as of 6.1.4. If you produce a lot of output, you would currently have to use a logging system that includes those features.


text:
Q: RUnit testing uninstalled package I am following the hints to this question, but I'm impatient and I would like to run my tests more quickly, without having to wait for the 30+ checks that R CMD check src invokes  before checking tests.
what I thought I could do was to add a --standalone option to the doRUnit.R suggested in that R-wiki page so that I could run the unit tests independently of R CMD.
I added these lines to the script:
  opt <- list(standalone=NULL)
  if(require("getopt", quietly=TRUE)) {
    ## path to unit tests may be given on command line, in which case
    ## we also want to move the cwd to this script
    opt <- getopt(matrix(c('standalone', 's', 0, "logical"),
                         ncol=4, byrow=TRUE))
    if(!is.null(opt$standalone)) {
      ## switch the cwd to the dir of this script
      args <- commandArgs()
      script.name <- substring(args[substring(args, 1, 7)=="--file="], 8, 1000)
      if(!is.null(script.name))
        setwd(dirname(script.name))
    }
  }

with this change, the script finds the test.*\.R files, independently from the directory from which I invoke the script.
the remaining problem now is that the doRUnit.R script loads the installed library, it does not source() the files that compose the library.
assuming that I want to load each and every file in the R directory, how would I do that?
assuming you have a better testing schema (satisfying the requirements "quick", "uninstalled"), what is it?

A: You may have to manually loop over the files in the R directory and source() them, maybe with something like source(dir("/some/Path", pattern="*.R", full.names=TRUE).
But I have the feeling that R CMD INSTALL does a little more. You may be better off working from the installed code.  And just running your unit tests directly, as you do and as the wiki page suggests, is already pretty good.  So no better scheme from me.  But keep us posted.
Edit:  Also note that R 2.10.1 gives us new options to accelerate R CMD INSTALL:

2.10.1 NEW FEATURES
R CMD INSTALL has new options --no-R,
  --no-libs, --no-data, --no-help, --no-demo, --no-exec, and --no-inst to suppress installation of the specified
  part of the package. These are
  intended for special purposes (e.g.
  building a database of help pages
  without fully installing all
  packages).

That should help too.

A: further additions/corrections to the script.
I can now invoke it as doRUnit.R --standalone
or have it invoked by R CMD check
      if(!is.null(script.name)) {
        setwd(dirname(script.name))
        path <- '../inst/RUnit/'
      }
.
.
.

  if (is.null(opt$standalone)) {
    cat("\nRunning unit tests of installed library\n")
    library(package=pkg, character.only=TRUE)
  } else {
    cat("\nRunning unit tests of uninstalled library\n")
    source(dir("../R/", pattern=".*\\.R", full.names=TRUE))
  }


text:
Q: Show if $ V_0^1(f, P) \le \sum_{i=1}^n (2c_i + \frac{3}{2\sqrt{c_i}}) (x_i - x_{i-1}), \forall P \in P[0,1]$ then $f$ is of bounded variation Let $V_a^b(f, P)$ denote the variation of $f$ on $[a,b]$ by partition $P$.

Say we have, $\forall P_0 =\{ 0 = x_0 < \cdots < x_n=1\}$,
  $$
V_0^1(f, P_0) \le \sum_{i=1}^n (2c_i + \frac{3}{2\sqrt{c_i}}) (x_i - x_{i-1})
$$
where $c_i \in (x_{i-1}, x_i)$. Show $f$ is of bounded variation.

Idea
Note that LHS is increasing as $|P|$ (# of elements) increases, where $P_0 \subset P$.
Since RHS is a Riemann sum of $g(x) := 2x + \frac{3}{2\sqrt{x}}$ on $[0,1]$,
RHS converges to $\int_0^1 \left( 2x + \frac{3}{2\sqrt{x}} \right)dx = 4$, as $|P|$ (# of elements) increases, where $P_0 \subset P$.
So LHS is bounded, so we have $f$ is of bounded variation.

I'm not sure my 'idea' is on the right way, and I'm also not sure how I can specify the idea into proof. Any help will be appreciated.

A: The argument here is not correct because the function $ x \mapsto \frac{2}{3\sqrt{x}}$ is not bounded on $(0,1]$ and is not Riemann integrable.  It is true that the improper integral converges, i.e.,
$$\lim_{a \to 0} \int_a^1 \frac{3}{2\sqrt{x}} \,dx = \lim_{a \to 0} (3 - 3\sqrt{a}) = 3,$$
but, in general, Riemann sums of improper integrals may not converge nor be bounded for arbitrarily chosen intermediate points.  In fact, for this function the problem will arise unless $c_1$ is specially chosen away from $0$.
As discussed here right- or left-hand sums of monotone functions may converge as the partition is refined but this still leaves a hole in your argument since $c_1 \in (0,x_1)$ is uncontrolled.
(As an aside the part $\sum_{i=1}^n 2c_i(x_i - x_{i-1})$ will converge as $x \mapsto 2x$ is Riemann integrable.)
It appears that you are trying to show that $f(x) = x^2 \sin x^{-3/2}, f(0) = 0$ is of bounded variation on $[0,1]$ by applying the mean value theorem and bounding the derivative as
$$|f'(c_i)| = \left|2c_i \sin c_i^{-3/2}- \frac{3}{2\sqrt{c_i}}\cos c_i^{-3/2}  \right| \leqslant 2c_i + \frac{3}{2\sqrt{c_i}}.$$
A valid approach is to write for any partition $P = \{0 = x_0 <x_1< \ldots< x_n = 1\}$,
$$\begin{align}\sum_{i=1}^n |f(x_i) - f(x_{i-1})| &= \sum_{i=2}^n\left|\int_{x_{i-1}}^{x_i}f'(t)\,dt\right| + |f(x_1) - f(0)| \\ &\leqslant \sum_{i=2}^n\int_{x_{i-1}}^{x_i}|f'(t)|\,dt + |f(x_1) - f(0)| \\ &= \int_{x_1}^1|f'(t)| \,dt + |f(x_1)| \\ &\leqslant \int_0^1 \left(2t + \frac{3}{2\sqrt{t}} \right) \, dt + \|f\|_\infty\end{align},$$
where the right hand side is bounded since the improper integral is finite and $f$ is bounded on $[0,1]$. It then follows that $V_f([0,1]) < \infty$.


text:
Q: exclude iCloud as option in NSSavePanel/NSOpenPanel I use iCloud file sync behind the scenes to keep instances of my Mac application in sync so I have the entitlement set for that.  Unfortunately, this means that iCloud also appears as a possible save location when I invoke NSSavePanel.
Because my app does not generate files that are intended to be reused or reimported back into my app, I have no iCloud open panel.  However my app does allow the user to export simple HTML or CSV reports.  I don't expect a reasonable user to choose iCloud as their save destination when exporting reports in my app, but Apple has now flagged this as a reason to reject the app since they conceivably could do that and then those files are effectively stranded in the cloud.
How can I suppress iCloud from the potential options when the user goes to save a file?

A: My app was also rejected for being able to save exported documents to iCloud. I specified in the note to the reviewer that it wasn't reasonable to save to iCloud, but they rejected it a second time. I asked about sample code on the review feedback, and on Apple's developer board, and got no response. Finally I gave up and just turned off iCloud support. It's convenient, but not necessary.
If you create a document in TextEdit, and export to PDF in iCloud, you create a file that TextEdit can't open. (Preview can.) By Apple's own rules, TextEdit should be rejected.

A: If you are using iCloud at all and have a save panel then iCloud will be an option as a save location. Hopefully that will be optional in the future, but for now my solution is to add an 'Open' option in my App Menu that allows my app to open my saved files with the system default application for that item.
For example, my app allows users to save reports as txt files. So when they go to open them again in iCloud they open in TextEdit.
It's a simple method that you can add to your AppDelegate and link to the 'Open' menu item.
- (IBAction)openDocument:(id)sender {
    NSOpenPanel *openPanel = [[NSOpenPanel alloc] init];
    if ([openPanel runModal] == NSOKButton)
    {
        NSURL *aFilePath = [[openPanel URLs] objectAtIndex:0];
        NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
        [workspace openURL:aFilePath];
    }
}