text:
Q: Undefined Index .. But I have done the same thing in short..then running I am making online examination.. the data are passing from page to examination page. but the value of radio button is not passing from examination page to result page. I have checked that the course name and subject names are passing. I have added the timer section. Which is working good. The value of radio button inside the while is not passing to result..
EXAM CODE

 <title>EXAM</title>

 <?PHP
 //$i=1;
 $j=1;
 $user_name = "root";
 $password = "";
 $database = "online_exam";
 $server = "127.0.0.1";
 $db_handle = mysql_connect($server, $user_name, $password);
 mysql_connect($server, $user_name, $password);
 $db_found = mysql_select_db($database);
 if ($db_found)
 { session_start();
   $i=$_SESSION['$i'];
   $sub = $_SESSION['$sub'];
  /*if(isset($_POST['b_subject']))
    {
       $selected_button=$_POST['subject'];
       if($selected_button=='subject1')
            $_SESSION['$sub']= "GK";
       else if($selected_button=='subject2')
            $_SESSION['$sub']="math";
        else
            print "error";
    }*/
     if(isset($_POST['subject'])){
           $selected_button=$_POST['subject'];
  }
  else
  {
           $selected_button="default button";
  }
 while($j<$i)
    {
      if($selected_button=='subject'.$j)
            $s= $sub[$j];
     $j++;
    }
 //print $_SESSION['$sub'];
 //print $selected_button;
//print $_SESSION['$cour'];
//print
// //assign $_SESSION['array'] to $array
 //print $sub[1];
 /* foreach($sub as $value) {
     print $value; //print $array contents
  }*/

      $c = $_SESSION['$cour'];
  //$s = $_SESSION['$sub'];
  $SQL = "SELECT ques FROM ques_ans WHERE course='$c' AND subj='$s'";
  $result = mysql_query($SQL);
  echo '<FORM name ="form1" method ="post" action="result_a.php" >';
  while ( $db_field = mysql_fetch_assoc($result) )
    {
         print $db_field['ques']."
";
?>

         <Input type = 'Radio' Name ='ques<?PHP echo $i;?>' value= '1'>YES
         <Input type = 'Radio' Name ='ques<?PHP echo $i;?>' value= '0'>NO

<?PHP
          $i++;
    }
  $_SESSION['$i']= $i;
  //$_SESSION['ques'] = $que;
  $_SESSION['$sub'] = $s;
  echo '<input type="submit" name="submit" id="submit" value="SUBMIT"/></FORM>';
  mysql_close($db_handle);
}
$targetDate = time()+(330*60) + (1*30);
$actualDate = time()+(330*60);
$secondsDiff = $targetDate - $actualDate;
$remainingDay     = floor($secondsDiff/60/60/24);
$remainingHour    = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
?>

Time Left

<?php echo "$remainingHour hours, $remainingMinutes minutes, $remainingSeconds seconds";?>

Inside the result the line " $selected_radio = $_POST['ques'.$i];" is showing error that "Undefined index: ques1" , "Undefined index: ques2", ... so on....
RESULT CODE

 <title>RESULT</title>

 <?PHP
  $i=1;
  $count=0;
 $ans= "";
 session_start();
    //$i=$_SESSION['$i'];
$s=$_SESSION['$sub'];
$c=$_SESSION['$cour'];
//$que[]=$_SESSION['ques'];
//print $c.$s;
 $user_name = "root";
 $password = "";
 $database = "online_exam";
 $server = "127.0.0.1";
 $db_handle = mysql_connect($server, $user_name, $password);
 $db_found = mysql_select_db($database,$db_handle);
 $SQL = "SELECT ans FROM ques_ans WHERE course='$c' AND subj='$s'";
 $result = mysql_query($SQL);
 while ( $db_field = mysql_fetch_array($result) )
    {
        $selected_radio = $_POST['ques'.$i];
        if ($selected_radio == '1')
         {
            $ans='1';
         }
        else if ($selected_radio == '0')
         {
            $ans='0';
         }
         if($ans==$db_field['ans'])
    $count++;
         $i++;
    }
 print $count;
?>

A: you never define $i = anything before you attempt to perform $i++;, you cannot autoincrement an integer without declaring it's starting value.
Therefore your fields are all actually just
name="ques"

Without any integer appended to them. Define $i = 1; or $i = 0; depending on your desire, and this will be resolved.


text:
Q: redux state value changed at second click I m new at redux and I have integrated it with my react app , but I have a note about a small test .
At the next example I see that the value of user added on my second click.
the reducer:
const initialState = {
    user: '',
    password: ''
}

export const admin = (state = initialState, action) => {
    switch (action.type) {
        case 'admin':
            return state = {
                user: action.user,
                password: action.password
            }
        default:
            return initialState;
    }
}

action :
const adminAction = (user, password) => {
    return {
        type: 'admin',
        user: user,
        password: password
    }
}

export default adminAction;

changing state in store.

const admin = useSelector(state => state.admin);
const dispatch = useDispatch();

var user,pass = '';

const adminChangeUsername = (event) => {
  user = event.target.value;
}

const adminChangePassword = (event) => {
  pass = event.target.value;
}

const click= (event) => {
    event.preventDefault();
    dispatch(adminAction(user,pass));
    console.log(store.getState())
    console.log(admin.user)
}

the click void associated to a button .
when doing the first click this is what happens :
   the value has changed in the store but the admin.user value is still empty.
when clicking a second time :
   The store values have updated
   The admin value has been added .
My question is why does only the second click trigger the retrieval of the value from store?

A: The reason why you are seeing the old value of admin in the click function is due to closures which cause the stale props and state problem. How do JavaScript closures work?

Every function in JavaScript maintains a reference to its outer
  lexical environment. This reference is used to configure the execution
  context created when a function is invoked. This reference enables
  code inside the function to "see" variables declared outside the
  function, regardless of when and where the function is called.

In a React function component, each time the component re-renders, the closures are re-created, so values from one render don't leak into a different render. It's for this same reason why any state you want should be within useState or useReducer hooks because they will remain past re-renders.
More information on the react side of it in React's FAQ

In addition to the main answer for the question, you should useState for the values of user and pass in your component. Otherwise the values don't stay between re-renders.
You could otherwise go without using controlled components, but not use a weird mix of both.
Working example below:

const initialstate = {
  user: '',
  password: '',
};

const adminReducer = (state = initialstate, action) => {
  switch (action.type) {
    case 'admin':
      return (state = {
        user: action.user,
        password: action.password,
      });
    default:
      return initialstate;
  }
};

const adminAction = (user, password) => {
  return {
    type: 'admin',
    user: user,
    password: password,
  };
};

const store = Redux.createStore(Redux.combineReducers({ admin: adminReducer }));

const App = () => {
  const store = ReactRedux.useStore();
  const admin = ReactRedux.useSelector((state) => state.admin);
  const dispatch = ReactRedux.useDispatch();
  const [user, setUser] = React.useState('');
  const [pass, setPass] = React.useState('');

  const adminChangeUsername = (event) => {
    setUser(event.target.value);
  };

  const adminChangePassword = (event) => {
    setPass(event.target.value);
  };

  const click = (event) => {
    event.preventDefault();
    dispatch(adminAction(user, pass));
    console.log('store has the correct value here', store.getState());
    console.log('admin is the previous value of admin due to closures:', admin);
  };

  return (

      <input
        onChange={adminChangeUsername}
        value={user}
        placeholder="username"
      />
      <input
        onChange={adminChangePassword}
        value={pass}
        type="password"
        placeholder="password"
      />
      <button onClick={click}>submit</button>

This shows the current value of user and password in the store

User: {admin.user}

Pass: {admin.password}

  );
};

ReactDOM.render(
  <ReactRedux.Provider store={store}>
    <App />
  </ReactRedux.Provider>,
  document.querySelector('#root')
);

Example with original vars instead of useState. You'll notice in this case by using the vars and keeping the value prop on the inputs, it prevents entry to the password input. The reason why it "works" on the user input is because the user variable started off as undefined rather than an empty string.

const initialstate = {
  user: '',
  password: '',
};

const adminReducer = (state = initialstate, action) => {
  switch (action.type) {
    case 'admin':
      return (state = {
        user: action.user,
        password: action.password,
      });
    default:
      return initialstate;
  }
};

const adminAction = (user, password) => {
  return {
    type: 'admin',
    user: user,
    password: password,
  };
};

const store = Redux.createStore(Redux.combineReducers({ admin: adminReducer }));

const App = () => {
  const store = ReactRedux.useStore();
  const admin = ReactRedux.useSelector((state) => state.admin);
  const dispatch = ReactRedux.useDispatch();

  var user,pass='';

  const adminChangeUsername = (event) => {
    user = event.target.value;
  };

  const adminChangePassword = (event) => {
    pass = event.target.value;
  };
  const click = (event) => {
    event.preventDefault();
    dispatch(adminAction(user, pass));
    console.log('store has the correct value here', store.getState());
    console.log('admin is the previous value of admin due to closures:', admin);
  };

  return (

      <input
        onChange={adminChangeUsername}
        value={user}
        placeholder="username"
      />
      <input
        onChange={adminChangePassword}
        value={pass}
        type="password"
        placeholder="password"
      />
      <button onClick={click}>submit</button>

This shows the current value of user and password in the store

User: {admin.user}

Pass: {admin.password}

  );
};

ReactDOM.render(
  <ReactRedux.Provider store={store}>
    <App />
  </ReactRedux.Provider>,
  document.querySelector('#root')
);

Example with fully uncontrolled inputs. This doesn't need the vars at all:

const initialstate = {
  user: '',
  password: '',
};

const adminReducer = (state = initialstate, action) => {
  switch (action.type) {
    case 'admin':
      return (state = {
        user: action.user,
        password: action.password,
      });
    default:
      return initialstate;
  }
};

const adminAction = (user, password) => {
  return {
    type: 'admin',
    user: user,
    password: password,
  };
};

const store = Redux.createStore(Redux.combineReducers({ admin: adminReducer }));

const App = () => {
  const store = ReactRedux.useStore();
  const admin = ReactRedux.useSelector((state) => state.admin);
  const dispatch = ReactRedux.useDispatch();

  const click = (event) => {
    event.preventDefault();
    const user = event.currentTarget.user.value;
    const pass = event.currentTarget.pass.value;
    dispatch(adminAction(user, pass));
    console.log('store has the correct value here', store.getState());
    console.log('admin is the previous value of admin due to closures:', admin);
  };

  return (

      <form onSubmit={click}>
        <input name="user" placeholder="username" />
        <input name="pass" type="password" placeholder="password" />
        <button type="submit">submit</button>
      </form>

This shows the current value of user and password in the store

User: {admin.user}

Pass: {admin.password}

  );
};

ReactDOM.render(
  <ReactRedux.Provider store={store}>
    <App />
  </ReactRedux.Provider>,
  document.querySelector('#root')
);

Why closures are relevant to the post
Because of the synchronous nature of the original code, it's possible to say that the reason the admin.user value that's logged isn't the new value is simply because the component hadn't re-rendered yet. However, the point remains that the admin value for that render is set in stone and will never change due to a closure. Even if React rendered synchronously with the redux state updating, admin wouldn't change.
It's for reasons like this that it's important to think about the closures and how everything fully works even in the simpler cases so you don't mess up in the more complicated ones.
For example of how incorrect mental models can hinder you, imagine that you assume that the reason the console.log(admin.user) doesn't show the correct value in the original example is solely because the component hadn't re-rendered yet. You might assume that putting a timeout to wait for the re-render would let you see the new value.
Imagine trying to add an auto-save functionality where you want to save the current value of admin to localstorage or an API every 10 seconds. You might put an effect with an interval of 10 seconds that logs admin with an empty dependency array because you want it to not reset until the component unmounts. This is clearly incorrect because it doesn't include the admin value in the dependencies, but it will highlight that no matter how many times you submit the values and change admin in the redux state, the value in this effect never changes because this effect will always be running from the initial value of admin on the first render.
useEffect(()=>{
  const intervalId = setInterval(()=>{console.log(admin)},10000);
  return ()=>clearInterval(intervalId);
},[])

Closures are the overall issue and you can easily get in trouble if you have the wrong mental model for how things work.

More information on closures:

A closure is the combination of a function bundled together (enclosed)
  with references to its surrounding state (the lexical environment). In
  other words, a closure gives you access to an outer function's scope
  from an inner function. In JavaScript, closures are created every time
  a function is created, at function creation time.

*

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
As mentioned in the MDN web docs, every time a function is created, the function gains permanent access to the variables in the surrounding code. Essentially, the functions get access to everything within scope for them.
In react function components, each render creates new functions.
In this example, when App is rendered:
const App = ()=>{
    const admin = useSelector(state => state.admin);
    const dispatch = useDispatch();

    var user,pass = '';

    const adminChangeUsername = (event) => {
      user = event.target.value;
    }

    const adminChangePassword = (event) => {
      pass = event.target.value;
    }

    const click= (event) => {
        event.preventDefault();
        dispatch(adminAction(user,pass));
        console.log(store.getState())
        console.log(admin.user)
    }

}

*

*the admin variable is initialized into the scope of App based on the current state of the redux store (i.e. { user: '',  password: ''}).

*The dispatch variable is initialized to be redux's store.dispatch

*user is initialized to undefined

*pass is initialized to ''

*the adminChangeUsername and adminChangePassword functions are initialized. They have access to (and use) user and pass from the closure that they create.

*click is initialized. It has access to (and uses) user, pass, store, and admin from it's closure.

click always only has access to the admin value from the current re-render when it was created because the click function created a closure around it when it was created. Once the click event occurs, and adminAction is dispatched, click won't change which render it was from, so it will have access to the admin variable that was initialized when it was. And each render, the admin variable is re-initialized and is thus a different variable.

Also the main issue here not just the asynchronous nature but the fact
  that state values are used by functions based on their current
  closures and state updates will reflect in the next re-render by which
  the existing closures are not affected but new ones are created. Now
  in the current state the values within hooks are obtained by existing
  closures and when a re-render happens the closures are updated based
  on whether function is recreated again or not

*

*usestate-set-method-not-reflecting-change-immediately - Shubham Khatri
No matter if you put a timeout in the click handler, the admin value will never be the new value because of that closure. Even if React happens to re-render immediately after calling dispatch.
You can use a useRef to create a mutatable value who's current property will remain the same between re-renders, and at that point, the asynchronous nature of React's re-renders actually comes into play because you'd still have the old value for a few more miliseconds before react re-renders the component.

In this example https://codesandbox.io/s/peaceful-neumann-0t9nw?file=/src/App.js, you can see that the admin value logged in the timeout still has the old value, but the adminRef.current value logged in the timeout has the new value. The reason for that is because admin points to the variable initialized in the previous render, while adminRef.current stays the same variable between re-renders. Example of the logs from the code sandbox below:

The only thing that might really surprise you about the order of events in this is that useSelector is called with the new data before the re-render occurs. The reason for this is that react-redux calls the function whenever the redux store is changed in order to determine if the component needs to be re-rendered due to the change. It would be entirely possible to set the adminRef.current property within the useSelector to always have access to the latest value of admin without store.getState().
In this case, it's easy enough to just use store.getState() to get the current redux state if you need access to the latest state outside of the hook's closure. I often tend to use things like that in longer-running effects because store doesn't trigger re-renders when changed and can help performance in performance critical locations. Though, it should be used carefully for the same reason of it being able to always get you access to the latest state.
I used a timeout in this example because that's the best way to highlight the actual nature of the closure's effect in this. Imagine if you will that the timeout is some asynchronous data call that takes a bit of time to accomplish.

A: The admin object will be fed after the next component rerendering process, after the whole click callback has been executed.
Indeed, it is based on the value provided by useSelector that is triggered ONCE during a rendering.
admin.user being checked in the click callback, the component has not been reredenring yet, thus showing the current empty string value the first crossing.
1) Component is rendered for the first time.
2) useSelector is called.
3) Click is made.
4) Action is dispatched.
5) admin.user is still empty since 2) is has not been run again yet.
6) After click callback finishes, a rerendering is about to be made so useSelector is triggered again, grabbing the admin value!
Moral of the story:
Don't expect value provided from useSelector to be immediately synchronised within the click callback.
It needs rerendering process to happen.
Besides, and just to improve your code, you can replace:
return state = {
                user: action.user,
                password: action.password
}

by this:
return {
         user: action.user,
         password: action.password
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: inverse transform throws error in LSTM prediction I am having a LSTM which will predict the  value for the next timestep .So my inputs are scaled into the LSTM like below:
test_X = reframed.values
test_X = test_X[:test_X.shape[0], :]
scaler = PowerTransformer()
test_X = scaler.fit_transform(test_X)
test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
print(test_X.shape)

(1, 1, 17)

Then I predict like below :
yhat = model.predict(test_X)

And I have a value for that .
Now I want to inverse scale it so I apply
inv_yhat = scaler.inverse_transform(yhat)

But this throws an error like below :

ValueError: Input data has a different number of features than fitting
  data. Should have 17, data has 1

Not sure why is this error throwing when the model already predicted the value but just inverse scaling is left.
EDIT :
I use the scalers like this in my training
scaler_x = PowerTransformer()
scaler_y = PowerTransformer()
train_X = scaler_x.fit_transform(train_X)
train_y = scaler_y.fit_transform(train_y.reshape(-1,1))
test_X = scaler_x.fit_transform(test_X)
test_y = scaler_y.fit_transform(test_y.reshape(-1,1))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)

import joblib
joblib.dump(scaler_x, 'scaler_x.gz')
joblib.dump(scaler_y, 'scaler_y.gz')

Then I scale my new fetaures like below :
scaler = joblib.load('scaler.gz')
test_X =scaler.transform(test_X)

still throwing the same error.
Any help is appreciated.

A: You're trying to do the inverse transform on your y data when you only applied the transform to the x data. The difference in the number of features (17 for x; 1 for y) is why you get that error
EDIT:
You need to create separate scalers for your x and y data e.g.
scaler_x = PowerTransformer().fit(test_x)
scaler_y = PowerTransformer().fit(test_y) # can be any transformer
scaled_test_x = scaler_x.transform(test_x)
scaled_test_y = scaler_y.transform(test_y)

Then when you want to make a prediction from your fitted model:
yhat = model.predict(test_x)
inv_yhat = scaler_y.inverse_transform(yhat)


text:
Q: How to access user control's image from parent page? I have a user control that upload image and show it to users. After upload image in parent page I want to save the image URL to database but I can't. This is my code that I used but the image is null.
Image img = new Image();
img = this.Uploade1.FindControl("Image1") as Image;

My code:  My User Control:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<contenttemplate>

                        <asp:Image ID="Image1" runat="server" Height="100" ImageAlign="Middle" Width="100" />

                        <asp:Label ID="StatusLabel" runat="server" Font-Names="Tahoma" Font-Size="8pt" Visible="False"></asp:Label>

                        <asp:FileUpload ID="FileUploadControl" runat="server" />

                        <asp:Button ID="btnUpload" runat="server" OnClick="ButtonUpload_Click" Text="بارگذاری" />

        </contenttempl

protected void ButtonUpload_Click(object sender, EventArgs e)
    {
        //Path to store uploaded files on server - make sure your paths are unique
        string Id = Request.QueryString["id"];
        //string thumbPath = "../upFiles/_thumb_" + Guid.NewGuid().ToString() + ".jpg";
        //string filePath = thumbPath.Replace("_thumb_", "");
        string filePath = "../upFiles/" + Guid.NewGuid().ToString() + ".jpg";

        try
        {
            // Check that there is a file
            if (FileUploadControl.HasFile)
            {
                if (FileUploadControl.PostedFile.ContentType == "image/jpeg")
                {
                    if (FileUploadControl.PostedFile.ContentLength  0) && (System.IO.Path.GetExtension(myFile.FileName).ToLower() == ".jpg"))
                        {
                            // Read file into a data stream
                            byte[] myData = new Byte[nFileLen];
                            myFile.InputStream.Read(myData, 0, nFileLen);
                            myFile.InputStream.Dispose();

                            // Save the stream to disk as temporary file.
                            // make sure the path is unique!
                            System.IO.FileStream newFile
                                    = new System.IO.FileStream(Server.MapPath(filePath.Remove(0,3)),
                                                    System.IO.FileMode.Create);
                            newFile.Write(myData, 0, myData.Length);

                            newFile.Close();

                            System.IO.File.Delete(Server.MapPath(filePath.Remove(0, 3) +"_temp.jpg"));

                            //. new cpode
                            Image1.ImageUrl = filePath.Remove(0, 3);
                        }
                    }

        }
        catch (Exception ex)
        {
            StatusLabel.ForeColor = System.Drawing.Color.Red;
            StatusLabel.Text =  ex.Message;
        }
    }

A: You can use Session to save image url, then in child page retrive that and save to database.
first page:
Session["url"] = imageUrl;

second page:
string url = (string)Session["url"] ;
//save to database


text:
Q: What is the radius of the inscribed circle of an ideal triangle I wanted to calculate the radius of the inscribed circle of an ideal triangle.
and when i dat calculate it i came to $\ln( \sqrt {3}) \approx  0.54 $ (being arcos(sec (30^o)) but then
at https://en.wikipedia.org/w/index.php?title=Ideal_triangle&oldid=668440011
it says that the equilateral triangle that is made by connecting the intersections of the ideal triangle and its [[inscribed circle]]  has a side length of $ 4\ln \left( \frac{1+\sqrt 5}{2}\right) \approx 1.925 $
but this would mean that the radius is less than half the side which is impossible
so didI make a mistake, or is wikipedia wrong?
PS the wikipedia page is corrected now and gives the right values)

A: I think the Beltrami-Klein model is particularly useful here since a hyperbolic line is just a straight chord there. For simplicity use a regular triangle as the inscribed ideal triangle. Its inscribed circle has an Euclidean radius which is half that of the fundamental circle. So the chord along the radius gets divided $1:1$ by the midpoint but $3:1$ by the point on the circle, therefore the radius is
$$\frac12\ln\left(\frac11\cdot\frac31\right)\approx0.54$$
just as you computed.
Now to the edge length of the inscribed triangle. A bit of messing around with the Pythagorean theorem will tell you that the ratio between the Euclidean edge length and the length of its supporting chord is $1:\sqrt5$. Which means one endpoint divides the chord in a ratio of $\sqrt5-1:\sqrt5+1$ and the other in the reciprocal ratio $\sqrt5+1:\sqrt5-1$ so the length between them is
$$\frac12\ln\left(\frac{\sqrt5+1}{\sqrt5-1}\cdot\frac{\sqrt5+1}{\sqrt5-1}\right)
=\ln\frac{\sqrt5+1}{\sqrt5-1}
\approx0.96$$
This looks like a factor of two mistake. Some extra computation shows that this is in fact the case, since
$$\frac{\sqrt5+1}{\sqrt5-1} = \frac{\sqrt5 + 3}2 =
\left(\frac{\sqrt5 + 1}2\right)^2 = \varphi^2$$
I will edit Wikipedia.

A: In the upper half plane model, we take the ideal triangle as $x=-1,$ $x=1,$ and $x^2 + y^2 = 1.$ For this problem, you want the inscribed circle, which is $$ x^2 + (y-2)^2 = 1,  $$
which meets the ideal triangle at $(-1,2),$ $(1,2),$ $(0,1).$
The diameter along the $y$ axis goes from $(0,1)$ to $(0,3).$ The geodesic center of the circle is at the geometric mean of $1$ and $3,$ therefore $(0, \sqrt 3).$ Recall from my 2012 answer that this geodesic is $(0,e^t).$ Therefore the radius is $\log {\sqrt 3} - \log 1$ = $(1/2) \log 3.$
One edge of the inscribed triangle passes through $(1,2),$ $(0,1).$ This segment is unit speed parametrized by
$$ 2 + \sqrt 5 \tanh t, \sqrt 5 \operatorname{sech} t  $$
and both ending $t$ values will be negative, because $0 < 2$ and $1 < 2.$
Let us just use the reciprocal of $\cosh t$ and be careful a bout signs.
One endpoint has
$$ \frac{\sqrt 5}{ \cosh t} = 1  $$ and the other has
$$ \frac{\sqrt 5}{ \cosh t} = 2,  $$ so
$$ \cosh t = \frac{\sqrt 5}{2} $$ and
$$ \cosh t = \sqrt 5 $$
Looked it up, $$ \operatorname{arcosh} x = \log \left(x + \sqrt {x^2 - 1}\right) $$ so the absolute value of the $t$ difference is
$$ \log \left( \sqrt 5 + 2 \right) -  \log \left( \frac{\sqrt 5 + 1}{2} \right) = \log (\varphi^2 + \varphi) - \log \varphi = \log (\varphi + 1) = \log (\varphi^2) = 2 \log \varphi \approx 0.96242365 $$


text:
Q: What does printing an empty line do? I know this question may well be the silliest question you've heard today, but to me it is a big question at this stage of my programming learning.
Why is the second empty line needed in this Python code? What does that line do?
print 'Content-Type: text/plain'
print ''
print 'Hello, world!'

A: A blank line is required between the headers and the body in an HTTP response, so a CGI script will print a blank line at just that spot. There's no need for the quotes though, since an unadorned print will output a blank line.

A: Did you even tried to telnet web-server?
It needs \n.
So, it's what it does, you can write it in one line if needed.
print 'Content-Type: text/plain\n\nHello World'

A: It prints an empty line, just as you have said.  It will leave a blank line in the output.  The print statement prints its arguments, and then a newline, so this prints just a newline.
You could accomplish the same thing with just:
print


text:
Q: Is it safe to update ::before and ::after clearfix to a simple ::after one? At present, a framework I work with utilises the classic clearfix:
@mixin clearfix {
    zoom: 1;

    &::before,
    &::after {
        content: '';
        display: table;
    }

    &::after {
        clear: both;
    }
}

I would like to know if it's safe to drop the use of the ::before now that IE7 is no longer supported, so that I can clearfix an element that might also require a pseudo element for decorative purposes. My proposal is to turn it into the following:
@mixin clearfix {
    &::after {
        clear: both;
        content: '';
        display: table;
    }
}

As far as I'm aware this will work just as it does with the ::before, but I wanted to make absolutely certain before making the change as this would affect literally hundreds of thousands of users if I got it wrong, and I don't want to be that guy.
Thanks in advance!

A: I decided to modify the mixin so that I can use the simple version on cue, otherwise allowing it to default to the current version.
I also noticed that IE8 wasn't supported either, as there are double-colons used for the pseudos, so I fixed that too while I was there...
@mixin clear-fix($simple: false) {
    @if $simple != true {
        zoom: 1;

        &:before,
        &:after {
            content: '';
            display: table;
        }

        &:after {
            clear: both;
        }
    }
    @else {
        &::after {
            clear: both;
            content: '';
            display: table;
        }
    }
}

Usage:
@include clear-fix; // prints out old-skool :before/:after with IE7/8 support
@include clear-fix(true); // prints out simple ::after method


text:
Q: how to make a time-out deco to a function? I'm trying to make a decoration on some specific functions. If the functions works more than, say five seconds, the deco will raise errors or interrupt the function.
def time_limit(func):
    def time_out():
        raise AssertionError

    @wraps(func)
    def deco(*args, **kwargs):
        timer = Timer(5, time_out)
        timer.start()
        res = func(*args, **kwargs)
        return res

    return deco

however even though the deco works, the function still works without interruptions:
In [69]: @time_limit
...: def f():
...:     time.sleep(6)
...:     print 'aaa'
...:

In [70]: f()
Exception in thread Thread-2764:
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File      "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 1073, in run
self.function(*self.args, **self.kwargs)
File "<ipython-input-68-cc74c901d8b8>", line 4, in time_out
raise AssertionError
AssertionError

aaa

How to fix the problem?
ps. I'm using apscheduler to circulalte the function, so a time-out decoration is better.


text:
Q: dataTable does not show newly added item after save I have a simple form using primefaces and JSF. On clicking save, it displays another jsf page where I have a primefaces datatable. It should display the newly created record in the datatable which is not the case. In order to see the new record, I have to go back to another page, then reopen the page where I have the datatable. And I can see the new record. How to solve this issue such that on clicking save I can see the new record?
    <p:dataTable id="dta" value="#{CarComponent.listCars}"  var="current" rows="15" paginator="true" paginatorPosition="bottom">
    </dataTable>

     //method where listCars is populated
     public String carLists(){
        listCars = new arrayList(carDao.findAll());
        return "/jsf/listOfcars.xhtml";
     }

     //save method - on clicking save it should display the datatable

      public String save(Cars car){
        carService.save(car);
       return  "/jsf/listOfcars.xhtml";
       }

      public String getlistCars() {
          return listCars;
       }

      public void setlistCars(String listCars) {
          this.listCars = listCars;
      }

A: I can only guess, but I assume that the CarService class is at least ViewScoped or even SessionScoped? In either way, as Fritz said in the comment, the list of cars is obviously not updated since the view is not re-rendered.
You can either do a redirect with return "/jsf/listOfCars.xhtml?faces-redirect=true" if the bean is @ViewScoped, or you have to add the newly generated car to the list of cars like
public String saveCar(Car car) {
    carService.save(car);
    listCars.add(car);
    return "/jsf/listOfCars.xhtml";
}


text:
Q: Dimension out of range when applying l2 normalization in Pytorch I'm getting a runtime error:

RuntimeError: Dimension out of range (expected to be in range of [-1, 0], but got 1)`

and can't figure out how to fix it.
The error appears to refer to the line:
i_enc = F.normalize(input =i_batch, p=2, dim=1, eps=1e-12)  # (batch, K, feat_dim)

I'm trying to encode image features (batch x 36 x 2038) by applying a L2 norm. Below is the full code for the section.
def forward(self, q_batch, i_batch):

    # batch size = 512
    # q -> 512(batch)x14(length)
    # i -> 512(batch)x36(K)x2048(f_dim)
    # one-hot -> glove
    emb = self.embed(q_batch)
    output, hn = self.gru(emb.permute(1, 0, 2))
    q_enc = hn.view(-1,self.h_dim)

    # image encoding with l2 norm
    i_enc = F.normalize(input =i_batch, p=2, dim=1, eps=1e-12)  # (batch, K, feat_dim)

    q_enc_copy = q_enc.repeat(1, self.K).view(-1, self.K, self.h_dim)

    q_i_concat = torch.cat((i_enc, q_enc_copy), -1)
    q_i_concat = self.non_linear(q_i_concat, self.td_W, self.td_W2 )#512 x 36 x 512
    i_attention = self.att_w(q_i_concat)  #512x36x1
    i_attention = F.softmax(i_attention.squeeze(),1)
    #weighted sum
    i_enc = torch.bmm(i_attention.unsqueeze(1), i_enc).squeeze()  # (batch, feat_dim)

    # element-wise multiplication
    q = self.non_linear(q_enc, self.q_W, self.q_W2)
    i = self.non_linear(i_enc, self.i_W, self.i_W2)
    h = torch.mul(q, i)  # (batch, hid_dim)

    # output classifier
    # BCE with logitsloss
    score = self.c_Wo(self.non_linear(h, self.c_W, self.c_W2))

    return score

I would appreciate any help.
Thanks

A: I would suggest to check the shape of i_batch (e.g. print(i_batch.shape)), as I suspect i_batch has only 1 dimension (e.g. of shape [N]).
This would explain why PyTorch is complaining you can normalize only over the dimension #0; while you are asking for the operation to be done over a dimension #1 (c.f. dim=1).


text:
Q: Are there technical reasons EF 5 isn't fully supported on .NET4.0? I wanted to upgrade my app to EF 5 to take advantage of features like support for enum spatial etc. However, I was not able to upgrade unless I move to .Net 4.5.
I would like to know what features of .Net 4.5 does EF 5 use that it can not be done in .Net 4.0?

A: My understanding is that EF >= 4.1 (including EF 5) consists of

*

*the EF "core libraries" like (System.Data.Entity.dll) which are part of the .NET Framework

*the additional package/assembly you can download via Nuget which contains the DbContext API and Code-First development

There were plans and an attempt in summer 2011 (the Entity Framework June 2011 CTP) to release the enum, spatial support and other new features (except Code-First Migrations) as an update of the core librares before .NET 4.5 is released. But the EF team has decided that such out-of-band updates are possible for the NuGet package (that's why EF 4.3 already has the Migrations feature that didn't require to touch the core libraries), but for the core libraries they are too difficult and can't be done before .NET 4.5 release:

There are two logical parts to the Entity Framework, the core
  components that ship inside the .NET Framework and Visual Studio and
  the 'out of band' components that we can update on a much more
  frequent schedule. We are currently looking at how we can update the
  core components on a more frequent cadence as well. The 'EF June 2011
  CTP' was our first attempt at shipping the core components more
  frequently and it's become clear we're just not technically ready to
  do this yet.
Core components include:

*

*Core EF Runtime (System.Data.Entity.dll & System.Web.Entity.dll)

*EF Designer

  Out of band components include: (We will likely ship more out of band
  components in the future)

*

*The DbContext API & Code First (EntityFramework.dll)

*T4 Templates for using DbContext API with Model First & Database First

*EF Power Tools

*Code First Migrations

(Quote from here.)
That means that enum support for EF will be part of the .NET 4.5 core libraries and not of the downloadable EF 5 NuGet package. Hence the new EF features like enum and spatial support are not available together with .NET 4.0.
More about the history and reason of separating "EF Core libraries" from "EF NuGet package" is here: http://blogs.msdn.com/b/adonet/archive/2011/10/18/how-we-talk-about-ef-and-its-future-versions.aspx


text:
Q: Disable viewing directory tree via url I bought a domain name and am trying to figure out how to configure it responsibly. I haven't set up an index.html file yet and I've noticed that if I hit my domain, I see my file directory tree and I can dive down to all the files within my browser. Is there a way that I can disable this? I am hosting it on Apache

A: If you are using IIS.

*

*Right-click on your website, and choose Properties.

*Select Home Directory tab.

*Uncheck the Directory browsing.

A: You can try a few things:

*

*create an empty file named index.html and upload it into the public_folder

*create an .htaccess file with the following contents: Options -Indexes

*If you have some kind of cpanel for your site, look for options to disable directory browsing.

Creating the index.html file is probably the easiest and most consistent way to go.
FYI, my .htaccess info came from techiecorner.com


text:
Q: What is the best way to calculate an element's angle when multiple rotates are applied to it If you do a rotateX(180deg) rotateY(180deg) it's upside down now. So if the mouse is set to move a child element up on drag that child element will now be moving down (depending on how you have things set up).
-webkit-transform: rotateX(?deg) rotateY(?deg) rotateZ(?deg); // where does it point?

ONLY SETUP FOR WEBKIT
Take a look at the fiddle (code is a mess, stripped down). Draw 360 tic marks, arranged in a circle, on your computer monitor. How can you tell what tic mark the arrow is pointing to (assuming the box is at the exact center of the circle)?
A tutorial that covers the basics is here, here.
*edit - the transform-origin being used is at the center of the cube

A: Note: Everything that follows assumes you are using a vector that passes through the origin, as in this example. In your original example the vector is additionally offset from the origin by the vector [0, 0, 60]. This complicates calculations slightly, so I have used the simplified version in my explanation.
Your vector is currently defined by spherical coordinates Euler angles consecutively applied rotations to a predefined vector. Here is how you can use your rotations to determine the cartesian coordinates of the final vector:

*

*Let us say your vector is [0, 1, 0] (assuming the arrow is 1 unit long and starts at the origin)

*Apply x, y and z rotations by multiplying your vector by the rotation matrices described here in any order, replacing θ with the corresponding angle in each case:

*The resulting vector is your original vector transformed by the specified x, y and z rotations
Once you have obtained the rotated vector, finding the projection of the vector on the x-y plane becomes easy.
For example, considering the vector [10, 20, 30] (cartesian coordinates), the projection on the x-y plane is the vector [10, 20, 0]. The angle of this vector from the horizontal can be calculated as:

tan-1(20/10) = 1.107 rad (counter clockwise from the positive x axis)
                    = 63.43 deg (counter clockwise from the positive x axis)

This means the arrow points between the 63rd and 64th "tick marks" counting counter clockwise from the one pointing directly to the right.


text:
Q: How can I supress BalloonTipClicked event when clicking a notifyIcon? On my form I have a notifyIcon. I have handlers for both Click & BalloonTipClicked bound to the notifyIcon.
Now, if the balloon is showed and I click on the notifyIcon the BalloonTipClicked gets fired and after that the Click fires. I'm not sure if this is intended behaviour but I only want to have the Click fired, how can I achieve that?
private void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
{
    Console.WriteLine("notifyIcon balloontip click"); // This fires first
}

private void notifyIcon1_Click(object sender, EventArgs e)
{
    Console.WriteLine("notifyIcon click"); // This fires after balloontipclick
}

A: It is not best practice but you can add a boolean variable. And on notifyicon.mousehover event set this variable to false. And on baloontipclick check if that variable is false exit sub else the sub will be executed


text:
Q: Need help with reflection example from "The Ruby Programming Language" In this example from The Ruby Programming Language (p.270), I'm confused why the instance_eval method on the last line of the sample code defines a class method called String.empty.
Don't you use class_eval to define a class method and instance_eval when you want to define an instance method?
o.instance_eval("@x") # Return the value of o's instance variable @x

# Define an instance method len of String to return string length
String.class_eval("def len; size; end")

# Here's another way to do that
# The quoted code behaves just as if it was inside "class String" and "end"
String.class_eval("alias len size")

# Use instance_eval to define class method String.empty
# Note that quotes within quotes get a little tricky...
String.instance_eval("def empty; ''; end")

A:
Don't you use class_eval to define a
  class method and instance_eval when
  you want to define an instance method?

Unfortunately, it is not as straightforward as that.
First take a closer look at what the examples of class_eval are doing. class_eval is a method which comes from Ruby's module class so can be called on any class or module. When you use String.class_eval you are evaluating the given code in the context of the class. i.e. when you write String.class_eval("def len; size; end") it's exactly like you reopened the class and typed the code passed to class_eval e.g.
class String
  def len
    size
  end
end

Thus to add a class method using class_eval you would write String.class_eval("def self.empty; ''; end") which has the same effect as:
class String
  def self.empty
    ''
  end
end

instance_eval is defined in Ruby's Object class so is available on any Ruby object. In the general case it can be used to add a method to a specific instance. e.g. if we have a String str and say:
str.instance_eval("def special; size; end")

Then this will alias special to size just for str but not for any other String object:
irb(main):019:0> "other".special
NoMethodError: undefined method `special' for "other":String
        from (irb):19

To understand what is going on with String.instance_eval remember that the class String is itself an object (an instance of the class Class) and that there is such a singleton instance object of every class defined. When you use String.instance_eval you are evaluating the given code in the context of the String instance object. i.e. it is equivalent to reopening String's metaclass and typing the code passed e.g.
class String
  class << self
    def empty
      ''
    end
  end
end

A: This is the general theme:

Use ClassName.instance_eval to define
  singleton methods.
Use ClassName.class_eval to define
  instance methods.

This post has a very neat explanation, give it a shot...


text:
Q: reCaptcha and Silverstripe I implemented Recaptcha to Silverstripe and it seems to work.
The only problem is that the formular and the captcha code are at the very end of the page and if you type in a wrong code then the page reloads and jumps back to the top so that the user doesn´t see the formular and captcha code anymore.
how can i make the window not to scroll to the top after entering a wrong captcha code?

A: Since the HTTP spec doesn't allow to a serverside redirection including an anchor tag, you'll need to use JavaScript to accomplish this. Since the field is highlighted with a validation message in the standard SilverStripe form rendering, you can use this to determine the state of the field once the submitted form loads again.
jQuery(document).ready(function() {
    var captchaEl = jQuery('#MyCaptcha');
    if(captchaEl.find('.message.required').length) {
        window.scrollTo(0, captchaEl.scrollTop());
    }
});


text:
Q: Magento1.9 - How to rewrite exact url using xml I want to rewrite /custom link from /catalogsearch/result/?q=some&attr=value for this I have added below code in my module config.xml
...
<rewrite>
    <mymodule>
        <from><![CDATA[/custom/]]></from>
        <to><![CDATA[catalogsearch/result/index/q/some/attr/value/$1]]></to>
        <complete>1</complete>
    </mymodule>
</rewrite>
...

From above code url /custom showing content of search page, but the other url including custom also rewritten from above code. for example /custom-page or custom-page1.
How to rewrite exact url?

A: To override the Catalog Search controller,
I request you to use below method instead of old frontend:
<config>
  <frontend>
    <routers>
       <catalogsearch>
          <args>
            <modules>
              <yournamespace_module before="Mage_CatalogSearch">Yournamespace_Module</yournamespace_module>
            </modules>
          </args>
       </catalogsearch>
    </routers>
  </frontend>
</config>

It will redirect every request with your custom one.
hope this will work for you.


text:
Q: HQL Custom class Can someone point me what is wrong with this HQL using custom class? custom class is RegionSummary
select new com.entity.RegionSummary(
   awb.fxOriginCode,
   awb.productCode,
   region.regionCode,
   region.zoneCode,
   sum(awb.revenue),
   SUM(awb.chargeableWeightKG),
   SUM(awb.chargeableWeightPounds)
)   From com.entity.AWB awb, com.entity.RegionZoneDestination region
where awb.fxDestinationCode = region.destinationCode
  and awb.status <> :strStatus
  and awb.billPeriod=:strBillPeriod
group by awb.fxOriginCode, awb.productCode, region.regionCode,  region.zoneCode
order by awb.fxOriginCode, awb.productCode, region.regionCode,  region.zoneCode

org.hibernate.HibernateException: org.hibernate.QueryException: Incorrect query syntax [select new com.entity.RegionSummary(awb.fxOriginCode, awb.productCode, region.regionCode, region.zoneCode, sum(awb.revenue), SUM(awb.chargeableWeightKG), SUM(awb.chargeableWeightPounds))   From com.entity.AWB awb, com.entity.RegionZoneDestination region where awb.fxDestinationCode = region.destinationCode  and awb.status <> :strStatus  and awb.billPeriod=:strBillPeriod group by awb.fxOriginCode, awb.productCode, region.regionCode,  region.zoneCode  order by awb.fxOriginCode, awb.productCode, region.regionCode,  region.zoneCode]


text:
Q: using git over ssh programmatically in C# I need to draw source code from a GIT repository in my system.
I use C# as a backend technology and so far I have succeeded with ordinary protocols.
I'm wrapping the Git.exe to call specific git commands.
When calling Git Clone "AnyUrlRepositoryOverSSH" git.exe fails. it happens because the call
wasn't made over ssh transmission or the ssh protocol fails to deliver my public key.
I need to call a SSH client and through that client make a call to GIt.exe . How can it be done?


text:
Q: Change, reset and increment time in python I need to increment time in python and if the value of the range in loop increments, I need to set time to the original value.
example
start_time = '0230'
start_time = datetime.strptime(start_time, '%H%M')

difference_time = '0030'
difference_time = datetime.strptime(differece_time, '%H%M')

differnce_delta = timedelta(
    hours=difference.hour, minutes=difference.minute)

listvar = [5, 3, 4]

for i in range(3):
    x = listvar[i]
    for loop in range(x)
        print(f'{start_time.hour}:{start_time.minute}')
        start_time += difference_delta

Now if the the value of i becomes 2, I want start_time to get back to original value i.e 0230.

A: You can use another variable as a place holder for the original value.
    start_time = '0230'
    start_time_holder = '0230'
    start_time = datetime.strptime(start_time, '%H%M')

    difference_time = '0030'
    difference_time = datetime.strptime(differece_time, '%H%M')

    differnce_delta = timedelta(
        hours=difference.hour, minutes=difference.minute)

    listvar = [5, 3, 4]

    for i in range(5):
        start_time = start_time_holder
        x = listvar[i]
        for loop in range(x):
            print(f'{start_time.hour}:{start_time.minute}')
            start_time += difference_delta

FYI: you would get a index out of range error at x = listvar[i] because the range is 5 but the list length is only 3


text:
Q: How to limit DTPickers available date? I have these 2 DTpickers in my visual basic form:

After the user picks a date from the upper DTPicker, I want the second DTPicker  below it to be limited in selection.
e.g If I picked a date from the upper DTPicker, let's say 12/07/2017, the one below it will be limited to 13/07/2017 and above it (limited to the day after the first DTPicker, and up). How can I achieve this?

A: Set the MinDate property of next DTPicker in according of the date selected in DTPicker1:
Private Sub DTPicker1_Change()
    DTPicker2.MinDate = DateAdd("d", 1, DTPicker1.Value)

    ' You can also automatically select the first day allowed
    DTPicker2.Value = DTPicker2.MinDate
End Sub


text:
Q: Creating a survey in HTML how to link the checkboxes to a Graph? Hi everyone so for a school project the teacher asked us to create a survey in HTML and js.
I've already created the layout with checkboxes but now I would like to link those checkboxes to the chart when the user clicks on the submit button.
sidenote : my HTML class is in French so if anyone speaks french i think it'll be easier for you to understand but any help would be appreciated
here is my code :
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Questionnaire Style De Coaching</title>

    <link rel="stylesheet" href="./css/reset.css">
    <link rel="stylesheet" href="./css/style.css">

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap" rel="stylesheet">

        <title>JavaScript Chart on COVID-19 Data</title>

PROFIL PERSONNEL

Les styles de coaching

Selectioner une ou plusieures options:

1. Vos collaborateurs n'ont pas ete sensibles a vos conversations amicales et a vos attentions concernant leurs conditions de travail. La qualite et le respect des details sont en chute libre.

        <input type="checkbox" id="A1" name="Q1" value="A">
        Pour chacun, vous precisez sa zone de responsabilite, les procedures adequates et les details. Vous lui demandez fermement des respecter et obtenez son accord.

        <input type="checkbox" id="A2" name="Q1" value="B">
        Vous reunissez le groupe pour retablir la situation. Vous reconnaissez les capacites et la qualite de chacun et faites appel a leur esprit d'equipe.

        <input type="checkbox" id="A3" name="Q1" value="C">
        Vous effecturez, avec chacun de vos collaborateurs, une analyse detaillee de ses resultats. Puis vous fixez, avec leur accord, des objectif et des delais realistes.

        <input type="checkbox" id="A4" name="Q1" value="D">
        Vous n'intervenez pas en tant que responsable. Au cours d'une reunion informelle, vous faites remarquer cependant: "Si les choses continuent comme ca, il faudra bientot qu'on fasse toutes les petites annonces".

2. Les resultats de l'equipe s'ameliorent. Chacun de vos collaborateurs est conscient des normes et des objectifs qu'il doit attendre et vous souhaitez vous assurer que la progression se prosuit.

        <input type="checkbox" id="B1" name="Q2" value="A">
        Vous engagez un dialogue avec chacun pour le feliciter de l'amelioration de ses resutats, et vous assurez un suivi precis des normes et des objectifs a attendre.

        <input type="checkbox" id="B2" name="Q2" value="B">
        Vous vous dites que vous n'avez pas de raison d'intervenir et vous investissez ce temps dans une recherche creative de nouvelles astuces de rentabilite. Vous participez aux reunions.

        <input type="checkbox" id="B3" name="Q2" value="C">
        Lors d'une reunion, vous declarez votre satisfaction d'appartenir a une equipe de cette qualite et votre certitude que chacun continuera a s'investir pour le bien commun.

        <input type="checkbox" id="B4" name="Q2" value="D">
        Vous soulignez a chacun les progres. Vous rappelez l'importamce des delais et de la tache a accomplir

3. Le groupe manifeste des difficultes a resoudre un probleme dans son champ de responsabilite. Par ailleurs, la performance du groupe et les relations interpesonnelles sont bonnes.

        <input type="checkbox" id="C1" name="Q2" value="A">
        Vous proposez puis organisez une reunion de resolutions de problemes, que vous animez, en veillant a ce qu'elle reste centree sur les objectifs definis.

        <input type="checkbox" id="C2" name="Q2" value="B">
        Dans l'ensemble, vous trouvez que "ca tourne rond". Cependant, au cours d'entretiens spontanes, vous proposez differents solutions.

        <input type="checkbox" id="C3" name="Q2" value="C">
        Vous prenez des mesures correctives et vous deonnz de nouvelles instructions qui obtiennent l'accord de vos collaborateurs.

        <input type="checkbox" id="C4" name="Q2" value="D">
        Vous valorisez le bon esprit de votre equipe et l'encouragez a travailler sur le probleme. Vous vous declarez disponible pour une intervention eventuelle.

4. Une nouvelle procedure doit etre mise en oeuvre dans votre service. Le climat dans l'equipe et les resultats de vos collaborateurs sont bons. Ils acceptent et comprennent bien les avantage de ce changement.

        <input type="checkbox" id="D1" name="Q2" value="A">
        Vous provoquiez une reunion pour conserver ce climat et stimulez de facon positive chacun de vos collaborateurs.

        <input type="checkbox" id="D2" name="Q2" value="B">
        Vous soulignez l'importamce de ce changement et annoncez que vous en surveillerez la mise en oeuvre et le suivi.

        <input type="checkbox" id="D3" name="Q2" value="C">
        Vous leur dites que vous etes sur que "cela va marcher", et leur demandez qu'ils determinent donc leurs propres orienations. Pendant ce temps vous vous centrez sur les implications de ce changement.

        <input type="checkbox" id="D4" name="Q2" value="D">
        Au cours d'entretiens individuels, vous demandez a vos collaborateurs de vous faire part de leurs suggestions afin de reflechir aux implications de cette modification.

5. La performance du groupe baisse depuis plusieurs mois. Les membres de l'equipe se deseteressent des objectifs communs. Il vous faut continuellement leur rappeler de tenir les delais. Dans le passe, la redefinition des fonctions a permis d'ameliorer la situation.

        <input type="checkbox" id="E1" name="Q2" value="A">
        Vous dites a votre equipe : "j'ai vu la concurrence hier. Ils m'ont dit "heureusement qu'on vous a" " .Puis vous demandez une reunion pour remetre les pendules a l'heure.

        <input type="checkbox" id="E2" name="Q2" value="B">
        Vous recevez chacun de vos collaborateurs pour redefinir avec lui ses fonctions, puis, au cours d'une  d'une reunion de travail, vous batissez, avec eux, une procedure de suivi  des objectifs communs.

        <input type="checkbox" id="E3" name="Q2" value="C">
        Vous convoquez vos collaborateurs un par un, vous leur reprecisez leur zone de responsabilite et leurs objectifs. Vous en surveillez la mise en oeuvre.

        <input type="checkbox" id="E4" name="Q2" value="D">
        Vous partagez avec votre equipe votre vision pessimiste de la situation. Puis, vous les associez a une definition globale des objectifs et des fonctions pour les remotiver.

6. Vous etes nomme responsable d'une unite de travail qui etait auparavant dirigee de facon tres efficace et trop directive a votre gout. Tout en maintenant la productivite, vous souhaitez humainiser les rapports de travail.

        <input type="checkbox" id="F1" name="Q2" value="A">
        Vous reconnaissez les merites de chacun et ce qu'il apporte au groupe, et entreprenez une action de "cohesion d'equipe" pour que le groupe se sente utile et que chacun s'y sente biena sa place.

        <input type="checkbox" id="F2" name="Q2" value="B">
        En attendant de bien comprendre la situation relationnelle, vous insistez sur l'importamce de delais et de l'action a accomplir.

        <input type="checkbox" id="F3" name="Q2" value="C">
        Vous modulez vos interventions de facon creative eb fonction des reaction de chacun face a vote nouvelle nomination.

        <input type="checkbox" id="F4" name="Q2" value="D">
        Vous commencez a associer chacun aux decisions le concernant puis mellez au point, en groupe, une procedure de gestion des resultats en fonction des objectifs.

7. Vous envisagez des changement majuers dans la struture de votre equipe. Certains membres du groupe ont fait des suggestions positives concernant ces changement. De plus, l'ensemble a, jusque la, demontre une bonne capacite d'adaptation dans ses activites quotidiennes.

        <input type="checkbox" id="G1" name="Q2" value="A">
        Vous tenez comple des suggestions faites et definissez a chacun les modifications de poste envisages. Vous annoncez que vous surpervisez la mise en oeuvre.

        <input type="checkbox" id="G2" name="Q2" value="B">
        Apres vous etre assure de l'adhesion de l'ensemble du groupe aux changement, vous l'incitez a en organiser la mise en oeuvre. Vous leur dites que vous leur faites pleinnent confiance.

        <input type="checkbox" id="G3" name="Q2" value="C">
        Vous tenez comple, objctivement, des propositions concretes qui vous sont et seront suggerees tout en assurant la coherence de l'ensemblede l'action.

        <input type="checkbox" id="G4" name="Q2" value="D">
        Hors hierarchie, vous participez aux reunions habituelles et donnez spontannement toutes vos idees.

8. La performance technique du groupe et les relations interpersonnelles sont bonnes.

        <input type="checkbox" id="H1" name="Q2" value="A">
        C'est une situation de reve! Vous etes pret pret a vous intergrer au groupe en tant qu'apporteur d'idees, mais vous le laissez travailler tranquille et imaginez de nouveaux debouches. Vous profitez de chaque occasion pour stimuler le groupe avec des idees astucieuses de developpement.

        <input type="checkbox" id="H2" name="Q2" value="B">
        Vous reunissez votre groupe et, les ayant felicites individuellement pour leurs performances, vous les associez a une etude d'efficacite acrue.

        <input type="checkbox" id="H3" name="Q2" value="C">
        Vous donnez les instructions necessaires pour la mise en oeuvre de nouvelles technique de production jugees plus perfomantes a long terme.

        <input type="checkbox" id="H4" name="Q2" value="D">
        Lors d'une reunion, vous montrez votre satisfaction du client qui regne au sein de l'equipe et vous faites part de votre plaisir d'appartenir a un groupe de cette qualite.

9. Votre superieur vous a charge de diriger un comite qui doit faire des propositions de changement relatif aux methodes de production. Le groupe ne voit pas clairement ses objectifs, l'absenteisme aux sessions est eleve, et les reunions ont pris un caractere mondain. Les membre du groupe ont cependent toutes les capacites necessaires pour mener a bien cete qu'on leur a confiee.

        <input type="checkbox" id="I1" name="Q2" value="A">
        Vous faites monter du the et des petits fours et vous dites au comite que si tout le monde a l'air de se desinteresser de la chose, autant que l'on passe un bon momment ensemble, avant le naufrage! Apres cela, vous decrivez la situation et demandez qu'on s'y  mette serieusement.

        <input type="checkbox" id="I2" name="Q2" value="B">
        Vous faites, par note individuelle a chacun des membres du comite, un descriptif detaille de la situation assorti de vos reflexions puis vous les reunissez pour recueillir leurs suggestions et demarrer une nouvelle procedure de travail efficace.

        <input type="checkbox" id="I3" name="Q2" value="C">
        Vous rappelez le comite a l'ordre et donnez a chacun de ses membres des objectifs et des delais precis. Vous annoncez qu'ils seront controles de facon suivie.

        <input type="checkbox" id="I4" name="Q2" value="D">
        Pour preparer la reunion suivante, vous profitez de rencontres occasionnelles pour manifester votre inquietude et faire appel a leur esprit de groupe pour repartir du bon pied.

10. Vos collaborateurs qui prennent habituellement a coeur leurs responsabilites ne semblent pas prets a adherer a vos recentes redefinition des fonctions.

        <input type="checkbox" id="J1" name="Q2" value="A">
        Vous montrez que vous etes conscient de leurs inquietudes faceaux recentes redefinitions de fonction et vous les impliquez progressivement dans la mise en oeuvre du changement afin que chacun s'y sente a l'aise.

        <input type="checkbox" id="J2" name="Q2" value="B">
        Vous reaffirmez votre position, vous donnez des instructions claires et obtenez l'engagement de mise en application.

        <input type="checkbox" id="J3" name="Q2" value="C">
        Vous reagissez immediatement. Vous leur dites la semaine derniere, vous aviez des collaborateurs de tout premier plan mais que la direction a du les changer sans vous en avertr car vous ne les reconnaissez plus, que s'ils voulaient bien reprendre leur personnalite d'orgine, ils remettraient rapidement les choses sur rail!

        <input type="checkbox" id="J4" name="Q2" value="D">
        Vous expliquez dans le detail la necessite du changement. Vous recueillez et prenez en comple les suggestions de chacun et veillez au respect des nouvelles definitions.

11. Vous venez d'etre nomme dans une nouvelle fonction. Votre predecesseur intervenait peu aupres de son equipe. Le groupe semble faire correctement son travail et les relations sont bonnes.

        <input type="checkbox" id="K1" name="Q2" value="A">
        Afin de "prendre en mains" cette nouvelle equipe, vous prenez les mesures necessaires pour mettre en oeuvre vos methodes de travail.

        <input type="checkbox" id="K2" name="Q2" value="B">
        Vous associez l'ensemble de vos collaborateurs aux decisions et soutenez leurs bonnes initiatives.

        <input type="checkbox" id="K3" name="Q2" value="C">
        Vous analysez, avec chacun, la qualite de ses performances, puis vous etudiez, dans le detail, l'utillite d'adopter de nouvelles methodes de travail.

        <input type="checkbox" id="K4" name="Q2" value="D">
        Il n'y a aucune raison de bousculer tout ca. Vous continuez de laisser le groupe travailler par lui-meme. Occasionnellement, vous faites part de vos idees d'amelioration.

12. Des informations recentes montrent qu'ild existe des difficultes dans votre equipe. Le groupe a, dans le passe, prove sa capacite a resoudre les probleme tout en maintement une bonne ambiance. De plus, chacun est competient a son poste.

        <input type="checkbox" id="L1" name="Q2" value="A">
        Vous menez une equite aupres de chacun de vos collaborateurs pour bien cerner les difficultes puis, ensemble, vous etudiez les solutions possibles et choississez la plus performante.

        <input type="checkbox" id="L2" name="Q2" value="B">
        C'est pour vous l'occasion revee de vraimnet deleguer. Vous veillez au grain mais vous les laissez se debrouiller.

        <input type="checkbox" id="L3" name="Q2" value="C">
        Vous prenez rapidement les mesures necessaires pour retablir la situation, vous donnez de nouvelles instructionset obtenez l'accord du groupe.

        <input type="checkbox" id="L4" name="Q2" value="D">
        Vous faites savoir que vous etes au courant de leurs difficultes et que vous leur fautes confiance. D'ailleurs, vous leur rappelez que par le passe, ils s'etaient bien sortis d'affaires.

    <input type="button" id="boutton" onclick="show()" value="Voir mes resulats" class="resultats"></input>

<button type="button" class="btnsave" style="display: none;">Sauvegarder</button>

Developper par Juneid Gaffar, Dieudonne Omba, Boulaid Boudada

© College la cite

And here is a picture of what the teacher asks us to to :
Picture example
Thank you


text:
Q: How would I do this set partition problem? A = {red, blue, green, purple}
B = {red, red, green}
Let E = {blue, red, green, purple, orange, black} and Let F = {black, orange}, do A, B, F form a partition of E? If not, which condition of a partition is not satisfied?
I'd say yes because the resulting partitions would be:
{ red, blue, green, purple, black, orange }
{ red, blue, green, purple}, { black, orange }
{ red, blue, green, purple, black, orange }, { red, green }
{ red, blue, green, purple }, { red, green, black, orange }
{ red, blue, green, purple }, { red, green }, { black, orange }
Which contains a set that is equal to set E.
I'm probably doing this wrong.

A: So the sets $A$, $B$, and $F$ would form a partition of $E$ if the following three conditions were satisfied:

*

*$A\cup B\cup F = E$

*None of $A$, $B$, or $F$ is the empty set,

*The intersection of any two of these three sets must be empty.

Are all three of these conditions satisfied for your sets?


text:
Q: rails fields_for object is nil, when I try to access an attribute Have three models:
class Offer < ActiveRecord::Base
   has_many :offer_items
end

class OfferItem < ActiveRecord::Base
  belongs_to :offer
  belongs_to :partner_product
  accepts_nested_attributes_for :partner_product
end

class PartnerProduct < ActiveRecord::Base
 has_many :offer_items
 accepts_nested_attributes_for :offer_items
end

In the form where offer is edited, there is fields_for to edit offer_item
<% f.fields_for :offer_items do |offer_item_form| -%>
 <div class='offer_item'>
   <%= render :partial => 'offer_item_fields', :locals => {:offer_item_form => offer_item_form}%>
      </div>
<% end -%>

The code chunk in the partial:
<%= offer_item_form.object.partner_product.name%>

throws an error

undefined method `name' for nil:NilClass
Extracted source (around line #29):

<%= offer_item_form.object.partner_product.name%>

but when I don't ask the name, like this
<%= offer_item_form.object.partner_product%>
<%= debug( offer_item_form.object.partner_product)%>

get in the browser:
#<PartnerProduct:0x007fa8785ff938>

--- !ruby/ActiveRecord:PartnerProduct
attributes:
id: 1
partner_id: 586
name: a
stock_volume: 0
source_price: 0
created_at: 2012-05-31 14:05:47 Z
updated_at: 2012-05-31 14:05:47 Z

I'm not just wondering, why I can't access a 'name' attribute and changed the partner_product to nil, but I really should show it. Any help is welcome!
Thanks


text:
Q: Error while running bundle install: bundle is locked to a parser I just cloned a new repo and tried to run bundle install but getting following error
Fetching gem metadata from https://abcderepos.net/api/gems/rubygems/...........
Your bundle is locked to parser (2.5.0.4), but that version could not be found in any of the sources listed in your Gemfile. If
you haven't changed sources, that means the author of parser (2.5.0.4) has removed it. You'll need to update your bundle to a
different version of parser (2.5.0.4) that hasn't been removed in order to install.

Any idea why i am getting this error?

A: Looks like parser version 2.5.0.4 was pulled from rubygems. I ran into the same issue today as well. You will either need to update your parser version to 2.5.0.5 or downgrade to 2.5.0.3.
UPDATE: They have documentation here to support why it was removed

A: The solution is bundle update parser --patch. (Do not change Gemfile.lock manually.)


text:
Q: Vim with YouCompleteMe , Error I followed this guide to set up YouCompleteMe for my server. This is what i did:
cd ~/.vim/bundle
git clone https://github.com/Valloric/YouCompleteMe.git
cd YouCompleteMe
git submodule update --init --recursive
./install.sh --clang-completer

followed by adding this to my vimrc :

let g:ycm_global_ycm_extra_conf = "~/.vim/.ycm_extra_conf.py"

and my .ycm_extra_conf.py has https://github.com/rasendubi/dotfiles/blob/master/.vim/.ycm_extra_conf.py
When I start my vim, its really slow to start up (takes about 30 seconds), then I get this error:

Traceback (most recent call last):   File
  "/home/stu9/s15/hxg7013/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/packages/urllib3/connection.py",
  line 137, in _new_conn
      (self.host, self.port), self.timeout, **extra_kw)   File "/home/stu9/s15/hxg7013/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/packages/urllib3/util/connection.py",
  line 91, in create_connection
      raise err   File "/home/stu9/s15/hxg7013/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/packages/urllib3/util/connection.py",
  line 81, in create_connection
      sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception
  occurred: Traceback (most recent call last):   File
  "/home/stu9/s15/hxg7013/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/packages/urllib3/connectionpool.py",
  line 559, in urlopen
      body=body, headers=headers)   File "/home/stu9/s15/hxg7013/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/packages/urllib3/connectionpool.py",
  line 353, in _make_request
      conn.request(method, url, **httplib_request_kw)   File "/usr/lib/python3.5/http/client.py", line 1106, in request
      self._send_request(method, url, body, headers)   File "/usr/lib/python3.5/http/client.py", line 1151, in _send_request
      self.endheaders(body)   File "/usr/lib/python3.5/http/client.py", line 1102, in endheaders
      self._send_output(message_body)   File "/usr/lib/python3.5/http/client.py", line 934, in _send_output
      self.send(msg)   File "/usr/lib/python3.5/http/client.py", line 877, in send
      self.connect()   File "/home/stu9/s15/hxg7013/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/packages/urllib3/connection.py",
  line 162, in connect
      conn = self._new_conn()   File "/home/stu9/s15/hxg7013/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/packages/urllib3/connection.py",
  line 146, in _new_conn
      self, "Failed to establish a new connection: %s" % e) requests.packages.urllib3.exceptions.NewConnectionError:
  : Failed to establish a new connection: [ Errno 111]
  Connection refused During handling of the above exception, another
  exception occurred: Traceback (most recent call last):   File
  "/home/stu9/s15/hxg7013/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/adapters.py",
  line 376, in send
      timeout=timeout   File "/home/stu9/s15/hxg7013/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/packages/urllib3/connectionpool.py",
  line 609, in urlopen
      _stacktrace=sys.exc_info()[2])   File "/home/stu9/s15/hxg7013/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/packages/urllib3/util/retry.py",
  line 273, in increment
      raise MaxRetryError(_pool, url, error or ResponseError(cause)) requests.packages.urllib3.exceptions.MaxRetryError:
  HTTPConnectionPool(host='127.0.0.1', port=37001): Max retries exceeded
  with url: /shutdown (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 111]
  Connection refused',)) During handling of the above exception, another
  exception occurred: Traceback (most recent call last):   File
  "", line 1, in    File
  "/home/stu9/s15/hxg7013/.vim/bundle/YouCompleteMe/autoload/../python/ycm/youcompleteme.py",
  line 337, in OnVimLeave
      self._ShutdownServer()   File "/home/stu9/s15/hxg7013/.vim/bundle/YouCompleteMe/autoload/../python/ycm/youcompleteme.py",
  line 214, in _ShutdownServer
However, after this, I'm able to use vim fine (its still sluggish, but
  I'm able to use it).


text:
Q: Weird crash using Restkit MainQueueManagedObjectContext - EXC_BAD_ACCESS Sometimes when I call saveToPersistent on the RestKit MainQueueManagedObjectContext I get the following error and the app crashes.
CoreData: error: Serious application error.  Exception was caught during Core Data change processing.  This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification.  -[UIBarButtonItem controllerWillChangeContent:]: unrecognized selector sent to instance 0x21e70300 with userInfo (null)

[UIBarButtonItem controllerWillChangeContent:]: unrecognized selector sent to instance 0x21e70300 with userInfo (null)

It seems that there are some kind of threading problem.
I save the context via a method like so:
- (BOOL)saveMainContext
{
    __block BOOL contextSaved = NO;
    [[[[CoreDataManager sharedInstance] objectStore] mainQueueManagedObjectContext] performBlockAndWait:^{
        NSError *error = nil;
        if ([[[[CoreDataManager sharedInstance] objectStore] mainQueueManagedObjectContext] saveToPersistentStore:&error]) {
            contextSaved = YES;
        }
    }];

    return contextSaved;
}

It crashes on the saveToPersistent method with EXC_BAD_ACCESS.
How can I fix this and what could be the reason for my NSFetchresultscontroller calling a method on a UIBarButtonItem?

A: Your saveMainContext method should only be called from the main thread and should simply be implemented as:
- (BOOL)saveMainContext
{
    NSError *error = nil;
    if ([[[[CoreDataManager sharedInstance] objectStore] mainQueueManagedObjectContext] saveToPersistentStore:&error]) {
        contextSaved = YES;
    } else {
        NSLog(@"Save error: %@", error);
    }

    return contextSaved;
}

Calling an instance of UIBarButtonItem suggests that you have a memory management issue in that something which is observing the context save is not removing itself before it is deallocated. Check all of your observers.


text:
Q: Does $\exists n : 6 + \sum_{i=2}^n p_i = x^6+y^6$ for $p_i$ the $i^{\text{th}}$ prime and $x,y\in\mathbb{Z}$? I noticed something about the prime numbers:

Pick the number $2$. Then, add the first odd prime, namely $3$. The result is $5 = 1^2+2^2$. Notice that the exponents are also the number we picked.
Pick the number $4$. Add the first odd prime, then the second, and the third, all the way up to $71$. It follows that $$4+3+5+\cdots + 67+71=5^4 + 2^4.$$

I cannot find a number $n$ such that when you add all the $n$ odd primes together, and then add $6$ (the next even number from $4$) then the result is $x^6+y^6$ for $x,y\in\mathbb{Z}$. Does there exist a number $n$ for this specific case? Is there a more mathematical way of finding out as opposed to brute-force?
Thank you in advance.

A: Heuristically: there are approximately $\Theta(\sqrt[3]{n})$ numbers $\leq n$ that are the sum of two sixth powers. (This is because there are $\Theta(\sqrt[6]{n})$ sixth powers less than $n$ and we're looking at the size of the set $S_{6,2}=\{x+y: x\in S_6, y\in S_6\}$ where $S_6$ is the set of sixth powers; generically we should expect that if we define $S_2=\{x+y: x, y\in S\}$ and $S$ is sparse enough, then $|S_2|$ will have size $\Theta(|S|^2)$, and this can be made rigorous.)  This means that we can think of the 'probability' that a random number of size $\approx N$ is a sum of two sixth powers as being approximately $\Theta(N^{-2/3})$.
Now, the size of the $n$th prime is approximately $n\log n$, so the sum of the first $n$ primes is roughly $\Theta(n^2\log n)$ (note that the initial term of $6$ doesn't impact these asymptotics at all).  Thus, using the probability estimate above, the probability that this is a sum of two sixth powers is $\Theta\left((n^2\log n)^{-2/3}\right)$ or $\Theta\left(n^{-4/3}(\log n)^{-2/3}\right)$.  Now, by linearity of expectation, the total number of solutions should be the sum of this probability over all possible $n$; in other words, $\sum_{n=1}^\infty a_n$ where $a_n\in\Theta\left(n^{-4/3}(\log n)^{-2/3}\right)$. But by the usual $p$-series comparison, we would expect this series to converge; in other words, we 'should' expect only a finite number of solutions in total.  This suggests that that finite number might be zero, so it is very possible that you won't find any solutions.
(Note that running the same asymptotic heuristic in the case of fourth powers yields the probability that the $n$th prime sum is a sum of fourth powers being roughly $\Theta\left((n^2\log n)^{-1/2}\right)$ or $\Theta\left(n^{-1}(\log n)^{-1/2}\right)$, and then the corresponding sum over all $n$ diverges, so we should expect infinitely many examples there.)

A: Let's look at some heuristics.
Pick some x and y. Then start with six, add consecutive primes, until the sum is ≥ $x^6 + y^6$. In other words, 6 + sum of odd primes up to $p_{i-1}$ is less than $x^6 + y^6$, and adding 6 + sum of odd primes up to $p_i$ is ≥ $x^6 + y^6$.
Let d = (6 + sum of odd primes up to $p_i$) - $(x^6 + y^6)$. Obviously $0 ≤ d < p_i$, and we have a solution if d = 0. Heuristically, we assume that d could be any of the numbers from 0 to $p_i - 1$ with equal probability $1 / p_i$.
Let $z = x^6 + y^6$. The i-th prime is quite roughly equal to $i · log i$, the sum of the first i primes is quite roughly $i^2 · log i / 2$, which makes $i^2 · log i ≈ 2z$, $i ≈ 2 (z / log z)^{1/2}$, $p_i ≈ (z · log z)^{1/2}$.
The chance that there is a solution for x, y is about $1 / (z · log z)^{1/2}$. Assuming x ≥ y, this is about $1 / (x^3 · (6 log x)^{1/2})$. If we add this for $0 ≤ y ≤ x$, the sum is about $1 / (x^2 · (6 log x)^{1/2})$. The sum of $1 / x^2$ is just π / 6, this sum is smaller, maybe 1/4.
A program that checks all cases with x ≤ 100 and therefore $z < 2·10^{12}$ is doable and has a chance of finding a solution (rough estimate 25%). Above that it is quite possible that a solution exists, but it would be unlikely (I'd say probability about 0.17%), and a solution would be hard to find.
If you examined all cases up to x ≤ 10,000, that would be a ridiculous amount of work (finding all primes up to $2·10^{24}$), and the chance that you still missed a solution is still about 0.0003%.
So a brute force search adding the primes up to $2·10^{12}$ has a reasonable chance of finding a solution. But even if you process all primes up to $2·10^{24}$, there is still a non-neglible chance that there is a solution further out.


text:
Q: Android ACTION_SEND with special file name I used to use following code for sharing file from my app:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(fPath)));
shareIntent.setType(fType);
mActivity.startActivity(Intent.createChooser(shareIntent, "SHARE"));

It usually works fine but recently I noticed that it will generate "No apps can perform this action" if there is special characters in the file name, e.g. "=" or Chinese/Japanese characters.
I tried to use recommended "FileProvider" to serve my file and pass a content uri to the sender. However, not all of the target applications can support content uri well, e.g. Wechat/EsfileManager etc.
Any idea?

A: try using URLEncoder for fileName Only:
              /* your file path */
fpath =  Environment.getExternalStorageDirectory() + File.separator + URLEncoder.encode(fileName);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(fPath)));


text:
Q: Google Maps radius around point I have a question regarding a specific algorithm, can you guys please help me understand the following code, I want to implementing it, however I want to understand the code before implementation, I hope you guys understand what I mean.
( 3959 * acos( cos( radians(-11232) ) * cos( radians( 21223 ) ) * cos( radians( 21223 ) - radians(23321) ) + sin( radians(-22321) ) * sin( radians( 23321) ) ) )

I understand it is looking for the radius, but how does it work? Good detail would be appreciated possible to a little maths formula.
Thanks in advance people.

A: This formula is for calculating the distance between two points on a sphere.
You can read an explanation here: http://en.wikipedia.org/wiki/Great-circle_distance.
11232 and 21223 are the coordinates on the sphere (although they look a bit strange to me), 3959 is the radius of the sphere.


text:
Q: How to popup window on MapLongClickListener? I want to make a popup window when long clicking on a map, here is my codes and popup.xml:
however the popupwindow didn't appear and the Log tells that the window is showing. Besides, there are many versions of the Constructor and showAtLocation functions and I am not very clear about the differences between them. Can someone find the mistakes in my code ? Thank you very much!
private void init()
{
    mGMap = ((MapFragment)  getFragmentManager().findFragmentById(R.id.map))
            .getMap();
    if( mGMap != null )
    {
        mGMap.setMyLocationEnabled(true);

        mGMap.getUiSettings().setMyLocationButtonEnabled(true);
        mGMap.getUiSettings().setRotateGesturesEnabled(true);
        mGMap.getUiSettings().setCompassEnabled(true);
        mGMap. setOnMapLongClickListener (new GoogleMap.OnMapLongClickListener(){
            @Override
            public void onMapLongClick(LatLng point) {
                // TODO Auto-generated method stub
                View popup_view = getLayoutInflater().inflate(R.layout.popup, null);
                PopupWindow popupWindow = new PopupWindow(popup_view);
                View parent =  ((MapFragment)  getFragmentManager().findFragmentById(R.id.map)).getView();
                WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                @SuppressWarnings("deprecation")
                int xoff = windowManager.getDefaultDisplay().getWidth() / 2 - popupWindow.getWidth() / 2;
                // 使其聚集
                popupWindow.setFocusable(true);
                // 设置允许在外点击消失
                popupWindow.setOutsideTouchable(false);
                popupWindow.showAtLocation(parent, Gravity.CENTER, xoff, 0);
                if(popupWindow.isShowing()){
                    Log.i(mainActivity.toString(), "pop up is showing");
                }
                popupWindow.update();
            }
        });
    }

And the following is my popup.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/location_time_tag"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="@string/loc_date" />

    <ListView
        android:id="@+id/listview_diary"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_alignParentLeft="true"
        android:smoothScrollbar="true"
        android:layout_below="@id/location_time_tag">
    </ListView>
    <EditText
        android:id="@+id/add_note"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/listview_diary"
        android:layout_alignParentLeft="true"
    />
    <Button
        android:id="@+id/add_text_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/add_note"
        android:layout_alignParentLeft="true"
        android:text="写日记"/>
    <Button
        android:id="@+id/del_text_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/add_text_btn"
        android:layout_alignParentRight="true"
        android:text="删日记"/>
</RelativeLayout>

A: as logs are saying that your popup window is open means you are adding wrong context for window.It means window is opened but in some other activity or in some other class.You should test applying proper context to window.


text:
Q: Show condition so $\beta_{m+1}$ is the solution of weighted least squares problem In my exercise we assume that $Y_i|X_i$ has distribution with density $f_i(y_i,\eta_i) $ for $i=1,...,n$ where $\eta_i=X_i^T$ is the linear predictor. The generalized linear model with an exponential dispersion distribution is a case with:
$$f_i(y_i,\eta_i)=e^{\frac{\theta(\eta_i)y_i-c(\eta_i)}{\Psi}}$$
It is assumed that assumed that $f_i(y_i, \eta_i)>0$ and we define that:
$$U_i(\eta_i)=\frac{\partial}{\partial \eta_i}log f_i(Y_i, \eta_i)$$
and
$$w_i=-E(\frac{\partial^2}{\partial^2 \eta_i}log f_i(Y_i, \eta_i))$$
We introduce now the score vector $U(\eta)=(U_1(\eta_1),..., U_n(\eta_n))^T$ and the diagonal matrix W with $W_{ii}=w_i$
I have that for the m'th Fisher Scoring step(fisher scoring algoitm) for solving the score equation amounts to solving the linear equation:
$$XU(\mu_m)-(X^TW_mX)(\beta-\beta_m)=0$$
Where here $W_m$ is defined in terms of $\eta=X\beta_m$.
in my book that for the Fisher Scoring Algoritm equation:
$$\beta_{m+1}=\beta_m+(X^TW_mX)^{-1}X^TU(\eta_m)$$
Now I have to show that if $w_{m,i}\geq 0$ then $\beta_{m+1}$ is the solution of weighted least squares problem with diagonal weight matrix $W_m$ and working responses $X_i^T\beta_m+U_i(\eta_m)/w_{m,j}$.
I'm not totally into the Fisher Scoring algoritm. Can anyone help me with this problem and how to set it up? Working responses what does that mean?

A:
the solution of weighted least squares problem with diagonal weight matrix $W_m$ and working responses $X_i^T\beta_m+U_i(\eta_m)/w_{m,j}$.
...
Working responses what does that mean?

The working response is the response $Y_{m,i}$ in the weighted least squares problem during the current step
$$\min_{\beta_{m+1}} W_{m,i} (Y_{m,i} - X_i^T\beta_{m+1})^2 $$
This response $Y_{m,i}$ is a transformed version of the current estimate.
$$Y_{m,i} = X_i^T\beta_m+U_i(\eta_m)/w_{m,j}$$
What you really want to solve is the least-squares problem with the transformed variable for the actual solution
$$Y_{\infty,i} = X_i^T\beta_\infty+U_i(\eta_\infty)/w_{\infty,j}$$
but since you do not know the solution $\beta_\infty$ you plugin the current solution $\beta_m$ and that is what you are 'working' with.


text:
Q: Need fix on stopping page reloading after file uploading I'm trying to upload files to the server without page refresh. The uploading works but the page reloads after the uploading is done which is not what I wanted. I'm redirecting to an iframe ("myFrame") to stop the page reloading but it appears this doesn't work correctly. What did I do wrong?
HTML
<form id="upload" target="myFrame" action="sql/main-pix-upload.php" method="post" enctype="multipart/form-data">
  <input id="main-pix" class="hidden" name="main_pix" type="file" onchange="uploadPix()" accept="image/*"/>

</form>

SCRIPT
function uploadPix(){
  var form = document.getElementById('upload');
  form.onsubmit = function(e){
    e.preventDefault()
    var formData = new FormData(this);
    $.ajax({
      url: 'sql/main-pix-upload.php',
      type: 'POST',
      data: formData,
      async: false,
      cache: false,
      contentType: false,
      processData: false
    })
  });
};

PHP
$account = $_SESSION['account'];
$order = $_SESSION['order'];
$id = $_SESSION['id'];

$pathPix = ('../accounts/'.$account.'/'.$order.'/pix/'.$id.'/');
if(!is_dir($pathPix)){
  mkdir($pathPix, 0777, true);
}

$file_name = $_FILES['main_pix']['name'];
$file_size = $_FILES['main_pix']['size'];
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$new_name = "main-pix.png";
$temp = ($_FILES["main_pix"]["tmp_name"]);
$target_file = ($pathPix.$new_name);

if(0 < $_FILES['main_pix']['error']){
  echo 'Error: ' . $_FILES['main_pix']['error'] . '
';
}else{
  move_uploaded_file($temp, $target_file);
}

A: Either use:
form.onsubmit = function(e) {
  e.preventDefault()
};

or:
form.addEventListener("submit", function(e) {
  e.preventDefault();
});

And then you have to make the HTTP-Call by yourself using AJAX.


text:
Q: How do I define AMPL like sets and parameters in Julia+JuMP? I need to define some constant parameter in Julia+JuMP, similarly to what you do in AMPL when you define
set A := a0 a1 a2;

param p :=
a0 1
a1 5
a2 10 ;

How do I define something like A and p in Julia?

A: JuMP itself doesn't define a special syntax for index sets beyond what's available in Julia. So, for example, you can define
A = [:a0, :a1, :a2]

where :a0 defines a symbol.
If you want to index a variable over this set, then the syntax is:
m = Model()
@variable(m, x[A])

JuMP also doesn't make a distinction between the data and the model in the same way as AMPL, so there's no real concept of a parameter. Instead, you just provide the data at the time when it's used. If I understand your question correctly, you could do something like
p = Dict(:a0 => 1, :a1 => 5, :a2 => 10)
@constraint(m, sum(p[i]*x[i] for i in A) <= 20)

This will add the constraint
x[a0] + 5 x[a1] + 10 x[a2] <= 20

Where we define p as a Julia dictionary. There's nothing specific to JuMP here, and really any julia expression can be provided as coefficient. One could just as easily say
@constraint(m, sum(foo(i)*x[i] for i in A) <= 20)

Where foo is an arbitrary Julia function that could perform a database lookup, compute digits of pi, etc.

A: I coudn't get the original answer of @mlubin working. Also, many examples around the web uses position-based indexing, that I don't feel so natural, so I rewritten the trnsport.gms example of the GAMS tutorial using dictionaries instead.. that feel much more close to gams/ampl "sets"..
#=
Transposition in JuMP of the basic transport model used in the GAMS tutorial

This problem finds a least cost shipping schedule that meets requirements at markets and supplies at factories.

- Original formulation: Dantzig, G B, Chapter 3.3. In Linear Programming and Extensions.
Princeton University Press, Princeton, New Jersey, 1963.
- Gams implementation: This formulation is described in        detail in:
Rosenthal, R E, Chapter 2: A GAMS Tutorial. In GAMS: A User's Guide.
The Scientific Press, Redwood City, California, 1988.
- JuMP implementation: Antonello Lobianco
=#

using JuMP, DataFrames

# Sets
plants  = ["seattle","san_diego"]          # canning plants
markets = ["new_york","chicago","topeka"]  # markets

# Parameters
a = Dict(              # capacity of plant i in cases
  "seattle"   => 350,
  "san_diego" => 600,
)
b = Dict(              # demand at market j in cases
  "new_york"  => 325,
  "chicago"   => 300,
  "topeka"    => 275,
)

#  distance in thousands of miles
d_table = wsv"""
plants     new_york  chicago  topeka
seattle    2.5       1.7      1.8
san_diego  2.5       1.8      1.4
"""
d = Dict( (r[:plants],m) => r[Symbol(m)] for r in       eachrow(d_table), m in markets)

f = 90 # freight in dollars per case per thousand miles

c = Dict() # transport cost in thousands of dollars per case ;
[ c[p,m] = f * d[p,m] / 1000 for p in plants, m in markets]

# Model declaration
trmodel = Model() # transport model

# Variables
@variables trmodel begin
    x[p in plants, m in markets] >= 0 # shipment quantities in cases
end

# Constraints
@constraints trmodel begin
    supply[p in plants],   # observe supply limit at plant p
        sum(x[p,m] for m in markets)  <=  a[p]
    demand[m in markets],  # satisfy demand at market m
        sum(x[p,m] for p in plants)  >=  b[m]
 end

# Objective
@objective trmodel Min begin
    sum(c[p,m]*x[p,m] for p in plants, m in markets)
end

print(trmodel)

status = solve(trmodel)

if status == :Optimal
    println("Objective value: ", getobjectivevalue(trmodel))
    println("Shipped quantities: ")
    println(getvalue(x))
    println("Shadow prices of supply:")
    [println("$p = $(getdual(supply[p]))") for p in plants]
    println("Shadow prices of demand:")
    [println("$m = $(getdual(demand[m]))") for m in markets]

else
    println("Model didn't solved")
    println(status)
end

# Expected result:
# obj= 153.675
#['seattle','new-york']   = 50
#['seattle','chicago']    = 300
#['seattle','topeka']     = 0
#['san-diego','new-york'] = 275
#['san-diego','chicago']  = 0
#['san-diego','topeka']   = 275

A much more commented version is available on my related blog post.


text:
Q: Hypothesis test: Testing for the median given a set of numbers Suppose $X_1,...,X_n$ are froma continous distribution and we test whether the median of these observations is 100 against the alternative that the median is greater than 100. Let $Y$ be the number of $X_i$'s greater than 100.
What is the distribution of $Y$ under the null hypothesis and if $n=4832$ and $Y=263$ find the p-value for this test?
For the first part I believe that the distribution of Y is  $Y\sim Bin(n,p=\#greater>100/n)$. And the second part I got
$H_o:median(X_1,..X_n)=100$ vs $H_A: median(X_1,..,X_n)>100$
$Pvalue=P(Y>100)=P(\dfrac{y-482*\frac{263}{482}}{\sqrt{482*\frac{263}{482}\frac{219}{482}}}> \dfrac{100-263}{\sqrt{482*\frac{263}{482}\frac{219}{482}}})=P(Z>\dfrac{-163}{\sqrt{10.9314}})=1$. Would this be a right way of getting the p-value? I think Y follows a binomial under the $H_0$.  I don't think we have use continuity correction. Thanks

A: Outline: We are assuming that the null hypothesis holds, that is, that  the median is $100$. We want to find out how unlikely is a result of $263$ or more test results $\gt 100$, under the hypothesis that the median is $100$. Under that hypothesis, $Y$ has binomial distribution with mean $(482)(1/2)=241$, and variance $(482)(1/4)$. (You are using the wrong $p$ for the binomial.)
The probability that such a binomial has value $\ge 263$ can be computed using the normal approximation to the binomial. Out of general caution, I would use the continuity correction.


text:
Q: LDAP Auth for Laravel 5.2 I've followed the instructions at https://github.com/strebl/ldap-auth with  a brand new laravel project and I can't seem to get it to work. I have done the following:
Added the following line to app.php
Ccovey\LdapAuth\LdapAuthServiceProvider::class

Changed the driver to LDAP in auth.php
'providers' => [
        'users' => [
            'driver' => 'ldap',
            'model' => App\User::class,
        ]
    ],

I've also created a adladap.php file that I haven't posted here.
I have also added middleware group in order to make sure the user was authenticated.
Route::group(['middleware' => 'auth'], function () {
    Route::get('/test', function(){ return "Test";});
}

However when I try to go to the test route I get the following error
InvalidArgumentException in CreatesUserProviders.php line 40:
Authentication user provider [ldap] is not defined.

I'm sure there's some simple configuration that I've been looking over but  for the life of me I can't figure out what it is.

A: If you are trying to do adminless LDAP, this might be of interest:
laravel-simple-ldap-auth


text:
Q: Newsletter preferences page should have an option to change your notifications email address When you are viewing an emailed newsletter, there is a link to "change your email preferences" on the emails. On my account it goes to https://stackexchange.com/users/101122/jessica-brown?tab=subscriptions
I would like to propose making this page more useful by adding a link to the page where you can update the email address for newsletter subscriptions. You can already do this for filters, why not for newsletters too?
From https://stackoverflow.com/users/preferences/272208 I can update my notification address, but is this where all newsletters go, or only stackoverflow's newsletter? It's not so clear from the URL (though actually updating my address there did appear to affect other network sites)