text:
Q: Why were R2-D2 and C3P0 being used by Rebels? Leia used R2-D2 and C3P0 to send a message to Obi-Wan Kenobi. R2-D2 was the primary astromech of Luke Skywalker. In Star Wars: Rebels, Bail Organa used R2-D2 and C3P0 against the Empire. Both droids always danced in rebel base and traveled with our heroes.
All this is despite the fact that C3P0 was designed by the first hand of Emperor in his childhood, and R2-D2 was his primary astromech and a friend of his? Couldn't this increase the probability of identity sabotage? Other than that, why would you trust those droids which were so close to the enemy? And, why couldn't they buy or pick a new shiny latest astromech and translator droid?

A: Despite C-3PO being crafted by Darth Vader, something that may not even be known by Princess Leia and especially wouldn't be known by Luke, he is in all regards an average protocol droid.

While it's true this makes it easy to disguise another protocol droid as him for infiltration, there's no reason for the Empire to try anything like this - he's a single little-known protocol droid that hardly does anything significant to help the Rebel cause.  It'd be much easier to plant an organic spy, who would be able to adjust to the situation and wouldn't be subject to repair jobs by the rebels that might reveal his nature as a spy.
R2-D2, despite being a remarkable little droid, is also a factory model, and despite carrying valuable information, isn't seen as much more than a piece of machinery by the imperial troops.
Couple that with the fact that they're always paired with Luke Skywalker, the irrefutable hero of the first Death Star run, and Princess Leia the once-princess of an entire planet, and you have two droids who are not much trouble to keep around, with two people who very much have the pull to keep them from being taken away.
As for why Luke and Leia want them kept around...well, they did save their lives that one time in the trash compactor...


text:
Q: Does the complexity of a basis function correspond to the number of DOF required to select it? My general question is whether the number of DOF lost when selecting a basis function from library is dependent on the complexity of the basis function.
More specifically: we try to fit a curve, which is perturbed during a certain time. To model the perturbation we use a library of basis functions starting from the earliest possible moment to the end of the data (so onset is not estimated). These basis functions have a standardized amplitude of 1 and are therefore scaled to match the observed data.

The basis functions are created using 3 parameters. Since we also estimate the scaling factor, we now consider this model to use 4 DOF (+ those used for the estimation of the global curve). However, intuitively, it would seem that we could defend using only 2 DOF, since there is 1) the scaling factor, 2) the selection of the basis function from the library, which is done with weighted non-linear sum of squared errors.
Would you have an idea whether this intuition is correct, and what formal way we can use to show this?
Many thanks in advance!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simple countdown - onClick button fires on render I'm trying to build a very simple 5 second countdown in React and can't seem to get it to work. In the code below, the timer starts as soon as the app renders for the first time, and then once it gets past 0 it seems to flicker and break down.
Any suggestions?

import './styles/App.css';
import { useState } from 'react';

function App() {

  const [ time, setTime ] = useState(5);

  const startCountdown = setInterval(() => {
      if (time < 0 ) {
        clearInterval(startCountdown);
      }
      setTime(time - 1);
  }, 1000);

  return (

{time}

      <button onClick={startCountdown}>Start</button>

  );
}

export default App;

A: You need to pass it as a function. Currently your assigning this as code block which will be executed straightway.
exp:
const startCountdown = () => setInterval(() => {
      if (time < 0 ) {
        clearInterval(startCountdown);
      }
      setTime(time - 1);
  }, 1000);


text:
Q: Search Box model where I have problem with model with use where.
I have in artists controller
  def search
@artists = Artist.where(params[:search])
end

and view artist
<%= form_tag(search_path) do %>
<%= search_field_tag(:search,"Search") %>
<%= submit_tag("Search") %>
<% end %>

In the partial view are all artists
And when I search something I have error.
SQLite3::SQLException: no such column: test1: SELECT "artists".* FROM "artists"  WHERE (test1)

A: Should be:
   @artists = Artist.where("name = ?", params[:search])

   @artists = Artist.where(name: params[:search]) # It is better

A: If you just want to search Artist.name, try changing your query to something like:
@artists = Artist.where("name = ?", params[:search])

That will produce a SQL query that looks like
SELECT "artists".* FROM "artists" WHERE ("name" = 'test1')

Instead of the one cited in your error message.
For more information on queries and how they work, you might want to look at:
http://guides.rubyonrails.org/active_record_querying.html#conditions


text:
Q: BEC and quantum liquid droplets My first question is: Is atomic Bose-Einstein condensate a gas?
My second question is: What are the difference between BEC and quantum liquid droplets?

A: *

*1) Yes, a Bose-Einstein condensate (BEC) is a gas. Hence, it is a metastable stable, as you know solids are the most stable state of matter. Three-body collisions happen at a rate $\propto n^2$, $n$ being the number density of atoms - these collisions make two atoms bond into a molecule, releasing the binding energy as kinetic energy of the third atom. The molecule is the start of the formation of the solid, while the third atom has enough energy to be ejected from whatever trap the BEC was sitting in, potentially colliding with other atoms in the process and heating them up.  This is why BECs only exist in dilute gases, i.e. low $n$, otherwise they would "die" very quickly.  I should also say that a BEC is only achievable is some kind of trap - when released, the non-zero (miniscule) temperature is still enough to disperse the cloud and kill it off.

*2) Quantum liquid droplets are denser (!= dilute) objects, hence why they are referred to as liquid or solid.  In order to achieve this one usually starts off with a BEC (as it is the easiest macroscopic quantum wavefunction to experimentally manufacture) and then modifies something in order for it to increase in density without dying. Usually this comprises changing the scattering length a, which measures the strength and the sign (attractive or repulsive) of atomic interactions. As an example, $^{39}K$ has a negative background scattering length so it will have attractive interactions, meaning a cold cloud of $^{39}K$ will implode and eventually explode (when $n$ becomes large enough for the 3-body losses mentioned earlier to win) - this is called a Bose-nova.  The point I am making here is that, if the intraspecies interactions were more repulsive, then the cloud could be squished a bit more (making it denser) without resulting in too much loss.  It seems that one of the most successful ways to get quantum liquids though (according to here) is by making a mixture of atoms in the BEC, and then turning the interspecies scattering length so as to balance it with the intraspecies interaction. Same idea as above, but within different species.
Quantum liquid droplets then become interesting because they are self-bound by this interaction. I.e. they do not need an external trap like the BEC. This draws interesting parallels to other self-bound objects in nature, like atomic nuclei or astronomical objects like white dwarfs or neutron stars, all allowed by a particular stabilisation mechanism arising from a balance of attractive forces and repulsive interactions


text:
Q: How to use symbolic expressions in ODE solvers I need to solve the following symbolic ODE using ode45 function:
function ydot=App1(~,y)
% clc;
% clear;
% close all;

syms x [1 4] real;
syms vv [1 2] real;
syms u [1 4] real;

f=sum(x.^2)-2*x(1)-3*x(2);
g1=-x(1);
g2=-x(2);
g3=-x(3);
g4=-x(4);
g=[g1 g2 g3 g4]';
h=[2*x(1)+x(2)+x(3)+4*x(4)-7;
x(1)+x(2)+2*x(3)+x(4)-6];

Psi=[-(gradient(f)+diff(g,'x1').*max(u'+g,0)+...
            diff(g,'x2').*max(u'+g,0)+...
            diff(g,'x3').*max(u'+g,0)+...
            diff(g,'x4').*max(u'+g,0)+...
            gradient(h(1))*vv(1)+...
            gradient(h(2))*vv(2));
            max(u'+g,0)-u';
            h;
            ];

% syms y [1 size(symvar(Psi),2)];
 ydot=subs(Psi,[x1, x2, x3, x4, u1, u2, u3, u4, vv1, vv2],sym('y',[1 10]));

I know that I need to convert it into function_handler:
aa=matlabFunction(App1);

But I don't know how to use in inside the ode45 function:
a = unifrnd(-3 , 3 , [1,10]);
[t,y]=ode45(@aa,[0,200],a);

MATLAB gives this error:
Not enough input arguments.

EDIT:
My real problem includes various functions with many parameters (that should be obtained through ODE45 function) and I'm looking for an automatic way to calculate the gradients and apply them inside the ODE45.


text:
Q: Change parent link colour when hover child link I'm trying to do this with CSS.
When I hover Customize or Widgets, I'd like the parent link (Dashboard) to have the red bg/white text styling.
http://jsfiddle.net/oxyns6w7/

.ab-item:hover {
    background:red;
    color:white
}

.ab-submenu li a:hover {
    background:green;
    color:white
}

   Dashboard

                        Customize
                        Widgets

How do I achieve this?


text:
Q: Finding MLE with ordered statistics? Let Y1 < Y2 < ... < Yn be the order statistics of a random sample of size n from the uniform distribution of the continuous type over the closed interval: $$[\theta - \rho, \theta + \rho]$$
Find the maximum likelihood estimators for $\theta$ and $\rho$. Are these two unbiased estimators?
Can anyone help with this problem? It looks like my one weakness with MLE is figuring them out when order statistics are introduced. Moreover, I have no idea how to determine if they're unbiased (I can't even figure out the respective pdf's-which I definitely need right?). I'd really appreciate any help someone can offer.


text:
Q: JMX Connection Hangs With the following super simple Java application:
class Main {
    static final private Logger logger = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) throws Exception {
        JMXServiceURL url = new JMXServiceURL(null, "localhost", 9999);
        logger.info("got JMXServiceURL");
        logger.info(String.format("JMXServiceURL=%s", url.toString()));

        try (JMXConnector connector = JMXConnectorFactory.connect(url)) {
            logger.info("got JMXConnector");
            MBeanServerConnection connection = connector.getMBeanServerConnection();
            logger.info("got MBeanServerConnection");
            logger.info(String.format("connection.getMBeanCount()=%d", connection.getMBeanCount()));
        }

        logger.info("exiting");
    }
}

I'm using a minimal build.gradle file with dependencies:
dependencies {
  implementation 'ch.qos.logback:logback-classic:1.2.3'
  implementation 'org.jvnet.opendmk:jmxremote_optional:1.0_01-ea'
}

Without the jmxremote_optional dependency, I get a java.net.MalformedURLException: Unsupported protocol: jmxmp error. I presume I've added the correct Maven dependency to resolve that.
When I run this, I get the following and then the application hangs indefinitely:
120     18:43:33.693 [main] INFO  jmxclient.Main - got JMXServiceURL
123     18:43:33.696 [main] INFO  jmxclient.Main - JMXServiceURL=service:jmx:jmxmp://localhost:9999

I definitely have a Java application exposing JMX metrics on that port:
time curl localhost:9999
curl: (52) Empty reply from server

real    0m0.020s
user    0m0.012s
sys 0m0.000s


text:
Q: Product Owner introduces ungroomed (unfamiliar, not estimated) User Story(s) into the Sprint Planning meeting A problem that I am facing and would like some input into is; a Product Owner introduces ungroomed (unfamiliar, not estimated) User Story(s) into the Sprint Planning meeting.
The issue that this has caused is the team rushes to understand and estimate the User Story(s), which puts significant time pressure on the commitment portion of the Sprint Planning meeting. The team also seems to be unsure of their estimate due to the rushed nature of grooming them in the Sprint Planning meeting. The end result of this is a rushed, half hearted Sprint commitment, which is usually an under-commitment due to so much uncertainty.
I have seen two distinctly different causes for the late introduction of the User Story(s):

*

*The team is new to Scrum and has been having difficulties grooming
stories, prior to planning.

*A brand new high priority User Story has
appeared just before the Sprint Planning meeting.

I have discussed these issues with the Product Owner and we have decided upon on actions, I am wondering what have you tried when the Product Owner introduces a brand new high priority User Story just before or even in the Sprint Planning meeting? What worked, what failed?
The team that is having difficulty grooming User Stories in new to Scrum; hence I suspect that some facilitation of their grooming sessions, mentoring and some time will help them.
Do you have any other suggestions for helping teams come up prompt Planning Poker estimates?

A: Given they've just been given the story during planning (regardless of it being a new story or not having estimated it earlier) you have a few choices.
First, you can ask the product owner if the story can be left on the backlog so that it can be properly checked and estimated during this sprint, and take it next sprint.
If that's not possible, another option is to do it in a spike - a time-boxed story to investigate something or to try something out - and then you'll have a head start for doing it next sprint.
Finally, if you really must start on it this sprint, then try and find out as much as you can during planning, and take the story but make it clear of the risk that it may not be completed this sprint. If it doesn't get completed, so be it, you've done some of it and now know a lot more about it for the next sprint.
Remember, estimates are just the best estimates with the information you have at the time, and can be revised later when you have more info.
Also remember you should be spending about 5%-10% of the sprint in refining the backlog. Doing this really helps keep the planning meetings shorter, more focused and more productive.

A: Estimation is not something that should be done off-the-cuff or quickly and without thought, regardless of your methodology. I wouldn't expect the team to be able to quickly come up with a reasonable estimate without having an opportunity to look at the user story and think about it for a while. At the same time, I do recognize that there are high priority new features, bug fixes, or feature modifications that need to be addressed quickly so that the customer can see added value. It's a trade-off between delivering the feature now versus maintaining schedule and/or quality that needs to be discussed.
If this is a continual thing, that suggests a problem with the process. That doesn't mean the process doesn't work, but rather (in this case) the Product Owner doesn't understand the value in the process. The Product Owner and the rest of the Scrum team need to be able to work together. Continuously sacrificing schedule or quality doesn't bode well for the project. At some point, I believe that the ScrumMaster, on behalf of the team, needs to draw a line and simply put the story in the backlog for estimation at a later time and not include it in the sprint. It will just be at the top of the backlog for the next one. This will reduce stress and allow for greater quality.

A: A useful tool in this situation is Planning Poker.  The team spends a few minutes asking the product owner questions about the story and then they each estimate the story points.  The variety of estimates are used to probe for gaps.  Using this tool over time, the PO will begin to realize what questions need to be answered before planning.
The Agile Project Manager (Scrum Master) should work closely with the Product Owner to develop appropriate sized clearly defined stories.  The PM should protect the developers from having to estimate incomplete stories and developers should not commit to a story that is not achievable - ever.


text:
Q: Using Google Places API in Google Sheets I'm using this tutorial (https://scrapediary.com/find-local-leads-with-google-places-api-and-sheets/) to scrape data from google places API into a google sheet. I copied the code exactly:
  var output = [ ["Name", "Place ID", "Latitude", "Longitude", "Types"]]
  var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?types=food&location=51.4977836,-0.1522502&radius=200&key=AIzaSyBtepY6mCTkHr3m4UCacxSkePkli5yEbCM";
  var response = UrlFetchApp.fetch(url)
  payload = JSON.parse(response)
  for (var x = 0; x < payload['results'].length; x++){
    var inner = [ payload['results'][x]['name'], payload['results'][x]['place'],payload['results'][x]['latitude'],payload['results'][x]['longitude'],payload['results'][x]['types']]
    output.push(inner)}
}

and I'm trying to run it in google sheets like this:
=placeSearch("Golf Course","51.4977836","-0.1522502","20000","i_put_my_api_key_here")
and it shows "Loading" and then returns nothing. I've double checked that the url itself works by pasting it into the browser and it returns the results in JSON format. I feel like there's a problem with pushing the results to the sheet but I can't find it

A: There is no doubt that the code you copied is working. Upon testing the same exact code you posted to replicate the problems, I only added return in the function to populate the cell.
See my exact code which worked and returned the data in sheets.
function placesAPI(keyword,latitude,longitude,radius,api_key,depth) {
  var output = [ ["Name", "Place ID", "Latitude", "Longitude", "Types"]]
  var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?types=food&location=51.4977836,-0.1522502&radius=200&key=AIzaSyBtepY6mCTkHr3m4UCacxSkePkli5yEbCM";
  var response = UrlFetchApp.fetch(url)
  payload = JSON.parse(response);
  for (var x = 0; x < payload['results'].length; x++){
    var inner = [ payload['results'][x]['name'], payload['results'][x]['place'],payload['results'][x]['latitude'],payload['results'][x]['longitude'],payload['results'][x]['types']]
    output.push(inner)}
  return(output); // added this code to put the value on the cell
}

In the function call, you need to use the api key in the url first to establish a connection. I have confirmed in my testing that if you used other api keys in the first function call, it will not return anything.
=placesAPI("Golf Course","51.4977836","-0.1522502","20000","AIzaSyBtepY6mCTkHr3m4UCacxSkePkli5yEbCM",20)
After that, it should return the same output below. Same with what we see when visiting the url manually.


text:
Q: display empty row SELECT
    workdate,
    SUM(Sam) ttlsam
FROM
    Sah
WHERE
    workdate BETWEEN '01 May 2016' AND ' 05 May 2016'
GROUP BY
    workdate

I have execute the above command and result is
Workdate ttlsam
02 may   10
03 may   20
04 may   40

Here 01 and 05 May are not showing because those two date has no data. But I want like this. I mean although 01 and 05 may don't have data they needs to display 0 or null value in ttlsam field
01 may   0
02 may   10
03 may   20
04 may   40
05 may   0

A: This hopefully should help if you want to do it in MS SQL
DECLARE @DateTable TABLE
(
    DateValue DATE NOT NULL
)

DECLARE @StartDate DATE
DECLARE @EndDate DATE
DECLARE @WorkingDate DATE

SET @StartDate = '01 MAY 2016'
SET @EndDate = '30 MAY 2016'

SET @WorkingDate = @StartDate

WHILE @WorkingDate <= @EndDate
BEGIN

INSERT INTO @DateTable
SELECT @WorkingDate

SET @WorkingDate = DATEADD(DAY,1,@WorkingDate)

END

SELECT * FROM @DateTable

DECLARE @tempData TABLE
(
    workdate date
    , Sam int

)

insert into @tempData
SELECT
    '01 MAY 2016',
    10

insert into @tempData
SELECT
    '01 MAY 2016',
    10

insert into @tempData
SELECT
    '03 MAY 2016',
    10

SELECT
    dates.DateValue,
    SUM(ISNULL(Sam,0)) ttlsam
FROM
    @DateTable dates
    left join
        @tempData Sah
        on
        dates.DateValue = sah.workdate
WHERE
    dates.DateValue BETWEEN '01 May 2016' AND ' 05 May 2016'
GROUP BY
    dates.DateValue

this would generate something like this:
DateValue   ttlsam
2016-05-01  20
2016-05-02  0
2016-05-03  10
2016-05-04  0
2016-05-05  0

Obviously without knowing what you actual data is behind the scenes I have assumed some things and limited the dataset to what you originally posted.
All I have done is created a dates table which is what you would use to be your summary table e.g. the dates you required. I have generated it for the first 30 days of may. But you could have it for a year etc. just change the values for the start and end dates.
We then just iterate through the dates and add them into the table.
Once this done you run your same query but with a join to this temp table you created. It will then group and sum the values. If there is no value present then it will do an ISNULL check and put a zero in it's place.
Hopefully this helps.

A: To get a time series without holes, suitable, for example, for graphing ttlsam vs. workdate, you need to explicitly construct all dates of interest. An example for Oracle.
Then you can select the sum of your Sam column for each date of interest rather than for each date in the original table.
Supposing you have populated a dates_of_interest table with a d column:
select d, sum(Sam) from dates_of_interest left outer join Sah on d=workdate group by d

A: SELECT
    dates.DateValue,
    SUM(ISNULL(Sam,0)) ttlsam
FROM
    @DateTable dates
    left join
        @tempData Sah
        on
        dates.DateValue = sah.workdate
WHERE
    dates.DateValue BETWEEN '01 May 2016' AND ' 05 May 2016'
GROUP BY
    dates.DateValue.  I want to add another condtion from SAH table such as "line like 'K%' what should I do.


text:
Q: What is causing the little white gap on the bottom of my music playlist image? I'll preface this by saying I only have the vaguest idea of what I'm doing, and if something works it's by pure fluke and I have absolutely no coding ability.
So using some other code I found scattered around the web (one piece for a long image scroll effect, the other to keep an image fixed at the bottom), I managed to make an iTunes and Spotify playlist mockup. You can see the full working thing here, but there's a problem. There's a little white gap at the bottom (between the long image, and the bottom fixed image.
And this is the code I used:

It took me about two days to even get to this point, faffing and tweaking until I got something that won't break my entire site and is actually functional.* The white gap is bugging me though. If anyone has any ideas on what could be causing it I'd greatly appreciate it. Is it something to do with them being seperate s? If so how can I seperate the code without them merging together?
Thanks guys and gals.

A:  is inline element by default, so I believe the white gap is caused by the whitespace before
.
Setting the style of your image to display: block should do the trick.

A: When I add this, it works:
.imageitunes, .imagespotify {
    line-height: 0px;
}


text:
Q: How to add button in custom View (ListRowView) without providing prior functionality, in Swift UI? Code below is working perfectly but i have an issue, i don't want to provide functionality here, i just want to add button (dropDownButton) and provide the functionality when using this custom view.
struct DrawerItemListRowView: View {

@State var iconName: Icon
@State var text: String
@State var dropDownButton = Button(action: {}) {
    Image(icon: .drawer)
}

var body: some View {

    HStack(alignment: .center, spacing: 15) {

        Image(icon: iconName)

        Text(text)
            .foregroundColor(.customLightBlack)
            .font(.custom(ubuntu: .regular, style: .title2))

        Spacer()

        dropDownButton
            .frame(width: 24, height: 24, alignment: .trailing)
    }
    .padding()
    .listRowSeparator(.hidden)
    .listRowBackground(Color.customBackground)
    .background(Color.clear)
}
}

struct DrawerItemListRowView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            DrawerItemListRowView(iconName: .mainCategory, text: "Shop by category")
            DrawerItemListRowView(iconName: .paymentMethod, text: "Payment Methods")
        }
        .previewLayout(.sizeThatFits)
        .background(.white)
    } }

A: You need to pass the action, not the button, as of type ()->Void.
Check out this example:
struct DrawerItemListRowView: View {
    let iconName: String
    let text: String
    let action: ()->Void   // Pass the action, not the button

    var body: some View {

        HStack(alignment: .center, spacing: 15) {

            Image(systemName: iconName)

            Text(text)
                .foregroundColor(.gray)

            Spacer()

            Button {
                action()    // Call the action
            } label: {
                Text(text)
                    .fixedSize()
            }
                .frame(width: 24, height: 24, alignment: .trailing)
        }
        .padding()
        .listRowSeparator(.hidden)
        .listRowBackground(Color.yellow)
        .background(Color.clear)
    }
}

struct Example: View {

    var body: some View {
        VStack {
            DrawerItemListRowView(iconName: "house", text: "Shop by category") {
                print("Bought")
            }
            DrawerItemListRowView(iconName: "minus", text: "Payment Methods") {
                print("Paid")
            }
        }
        .previewLayout(.sizeThatFits)
        .background(.white)
    }
}


text:
Q: Xcode project files disappear from left navigator after merging master into branch I am working in a small iOS team and tried merging the master branch into another branch. After I resolve merge conflicts, all the project files disappear from the left Xcode navigator. When I click on the project target in Xcode, it shows this popup:

I'm also getting an error that says the project cannot be loaded:

This might or might not be helpful in finding the solution, but I'm also failing a check on Github from Xcode Cloud saying I'm missing a scheme:

I have literally no idea what to do. What might be causing this issue, and how can I fix it?
One other dev on my team tried to remove a git ignore file that was committed earlier, but it didn't solve the problem. I've experienced this problem before and I think I resolved it by pressing git revert, but I cannot do that again.


text:
Q: MERN Delete request issues I'm wokring on a simple suggestion app it has authenctication and context api for State management, I can create, read, update and delete a suggestion but I've been trying to make a delete request but its not working.
I console.log the error message due to the conditional statement and its saying
Request failed with status code 403
I've tried everything but its not working
this is my code on expresss
router.delete("/bmi/delete/:id", async (req, res) => {
  const id = req.params.id;
  try {
    const suggest = await bmiCalc.findById(id);
    if (suggest.userId === req.body.userId) {
      await suggest.deleteOne();
      res.status(200).json("Suggestion deleted");
    } else {
      res.status(403).json("Not your Suggestion to delete");
    }
  } catch (error) {
    res.status(500).json("Error from server");
  }
});

This is the react axios request
const Home = () => {
  const { user } = useContext(AuthContext);
  const [data, setData] = useState([]);
const handleSuggestion = async (e) => {
    e.preventDefault();

    const fullDetail = {
      userId: user.users._id,
      bmiNumber: bmiNumber.current.value,
      country: country.current.value,
      messages: messages.current.value,
    };
    const res = await axios.post(
      "http://localhost:5000/app/bmi/bmiform/create",
      fullDetail,
    );
    setData([...data, res.data]);
    console.log(res.data);
  };

  const reload = () => {
    window.location.reload();
  };

  useEffect(() => {
    const getSuggestion = async () => {
      const res = await axios.get(
        `http://localhost:5000/app/bmi/all/${user.users._id}`,
      );
      await setData(res.data);
    };
    getSuggestion();
  }, [user.users._id]);

  const handleDelete = async (id) => {
    try {
      await axios.delete(`http://localhost:5000/app/bmi/delete/${id}`, {
        data: { userId: user.users._id },
      });

      setData(data.filter((post) => post._id !== id));
    } catch (err) {
      console.log(err.message);
    }
  };

I'm using chakra UI, here is the button for the onclick event

<Flex
        w={"100%"}
        h={"60vh"}
        padding={"8px"}
        gap={"8px"}
        flexWrap={"wrap"}
        justifyContent={"flex-start"}>
        {data.map((data) => {
          return (
            <Box
              key={data._id}
              width={["47%", "55%", "25%", "24%"]}
              height={["55%", "50%", "50%", "50%"]}
              bg={"#ffffff"}
              display={"flex"}
              flexDirection={"column"}
              borderRadius={7}
              gap={4}
              padding={5}>
              <Box w={"100%"} h={"5vh"} transition={"0.3s all"}>

 BMI: {data.bmiNumber}

 {data.country}

              </Box>
              <Box width={"100%"} height={"100%"} paddingTop={2}>

 {data.messages}

              </Box>
              <Flex width={"100%"} gap={1}>
                <Button
                  bg={"#541db5"}
                  type='submit'
                  width='100%'
                  outline='none'
                  border='none'
                  borderRadius={6}
                  color='#ffffff'
                  fontSize={20}
                  fontWeight={600}
                  marginBottom={4}
                  padding={4}>
                  edit
                </Button>
                {data.userId === user?.users._id && (
                  <Button
                    onClick={() => handleDelete(data._id)}
                    type='submit'
                    width='100%'
                    outline='none'
                    border='none'
                    borderRadius={6}
                    color='#ffffff'
                    fontSize={20}
                    fontWeight={600}
                    bg='#ef233c'
                    marginBottom={4}
                    padding={4}>
                    <DeleteIcon />
                  </Button>
                )}
              </Flex>
            </Box>
          );
        })}
      </Flex>

A: try console logging both of these too see why they are not equal.
suggest.userId
req.body.userId
Then investigate why they are not equal.

A: I just had this issue and fixed it a couple of minutes ago.
So basically MongoDB doesn't see those objectIds as equal
The best option to compare them is using suggest.userId.equals(req.body.userId)
this will result in true

A: In your router you need to access userId as
 req.body.data.userId

instead of
req.body.userId


text:
Q: How to get object's byte range using AWS S3 SDK for .Net I cannot see anything in the AWS S3 SDK for .Net that would allow me to get a range of bytes from S3 object. Is making a GET HTTP request with Range header to the S3 REST API the only way? In this case, is there anything in the SDK to generate the Authorization header for the request? Building the header manually looks quite complicated and time consuming.

A: Turns out the Amazon.S3.Model.GetObjectRequest class has a ByteRange property. Don't know how I missed it!


text:
Q: Null value is returned from stored procedure I have stored procedure which returns username. I am calling stored procedure from java(EclipseIDE). The returned value from Stored procedure is Null. How to avoid this Null Value.
This is my stored procedure
USE `employee`;
DROP procedure IF EXISTS `add1`;
DELIMITER $$
USE `employee`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `add1`(IN UserId int,
                                                   IN UserFirstName varchar(50),
                                                   IN UserLastName varchar(50),
                                                   IN Education varchar(50),
                                                   IN MarksInME int,
                                                   IN MarksInBE int,
                                                   IN MarksInPUC int,
                                                   IN Gender varchar(50),
                                                   OUT UserName varchar(50))
  BEGIN
    declare varName varchar(50);
    select UserFirstName into varName from User where UserId=3516;
    set UserName=varName;
    insert into   user(UserId,UserFirstName,UserLastName,Education,MarksInME,MarksInBE,MarksInPUC,Gender)
    values(UserId,UserFirstName,UserLastName,Education,MarksInME,MarksInBE, MarksInPUC,Gender);

  END$$
DELIMITER ;

I am calling Stored Procedure:
    java.sql.CallableStatement cStmt = conn.prepareCall("{call add1(?,?,?,?,?,?,?,?,?)}");
    cStmt.setInt(1,3541);
    cStmt.setString(2,"pALLAVI");
    cStmt.setString(3,"K");
    cStmt.setString(4,"BE");
    cStmt.setInt(5,0);
    cStmt.setInt(6,60);
    cStmt.setInt(7,600);
    cStmt.setString(8,"chetana@gmail.com");
    cStmt.registerOutParameter(9, java.sql.Types.VARCHAR);
    cStmt.execute();
    userName = cStmt.getString(9);

When I try to print the UserName its printed as Null?

A: UserId is hardcoded:
select UserFirstName into varName from User where UserId=3516;

Please check below query:
call add1(3541,'pALLAVI','K','BE',0,60,600,'chetana@gmail.com',@UserName);
SELECT @UserName;


text:
Q: Multiple SimpleJDBCCall beans causing Sonar issue in Java My application is springboot and I am having DatabaseConfig where multiple SimpleJDBCCall beans are configured to execute stored proc and am having DAO where am injecting beans using constructor. This is working well, however this is failing on sonar because I have more than 7 beans. We cannot tune Sonar settings as many teams use it. So please suggest here,
Below is how my DatabaseConfig looks
@Configuration
public class DatabaseConfig {

@Autowired
public JDBCTemplate jdbcT;

@Bean(spOne)
public SimpleJDBCCall spOne(){
   return new SimpleJDBCCall(jdbcT).withSchema(x).....;
}

@Bean(spTwo)
public SimpleJDBCCall spTwo(){
   return new SimpleJDBCCall(jdbcT).withSchema(x).....;
}

@Bean(spTen)
public SimpleJDBCCall spTen(){
   return new SimpleJDBCCall(jdbcT).withSchema(x).....;
}}

Below is how my DAO class looks like
@Repository
public class Dao{
private JDBCTemplate jdbcT;
private SimpleJDBCCall spOne; private SimpleJDBCCall spTwo; private SimpleJDBCCall spTen;

  public Dao(JDBCTemplate jdbcT, SimpleJDBCCall spOne; SimpleJDBCCall spTwo; SimpleJDBCCall spTen){
         this.jdbcT = jdbcT;
         this.spOne = spOne;
         this.spOne = spTwo; // More settings of storedProc beans.
         this.spOne = spTen;
}}

A: You could define a Map as constructor parameter, like this:
public Dao(JDBCTemplate template, Map<String, SimpleJDBCCall> jdbcCalls){

}

Spring will then add all bean instances of type SimpleJDBCCall into the map. The key of the map would be the bean names (in your case e.g. "spOne", "spTwo" etc.), and the value is the instance of the bean. If you still can do your usecase with this, it might be the easiest solution.
If you don't access specific beans in your code, but e.g. just iterate over all templates to execute a call, a List instead of the map could also be sufficient then.


text:
Q: Mixed Content and I can't find the probelm I can not find the problem. I looked and looked i just do not see any http:// link on this page...
The URL is Englsih-the
Mixed Content: The page at 'https://www.english-the-easy-way.com/' was loaded over HTTPS, but requested an insecure favicon 'http://www.english-the-easy-way.com/'. This request has been blocked; the content must be served over HTTPS.
Thank everyone...

A: You can use your browser's network inspector to see what's sent securely or not. In this case the browser tries to get a favicon for your page via https://www.english-the-easy-way.com/favicon.ico but is redirected.
Here's a screenshot of Firefox's network inspector. See how the marked line does not have a green padlock against it.

The network inspector in Firefox is part of the Web developer tools. Other browsers have similar capabilities.

A: If the page does not link to a custom favicon URL using <link rel=icon>, most browsers will try to retrieve it from the default location /favicon.ico instead.
In your case, https://www.english-the-easy-way.com/favicon.ico returns a 302 redirect to the plain-HTTP version of your website.
> GET /favicon.ico HTTP/2
> Host: www.english-the-easy-way.com

< HTTP/2 302
< location: http://www.english-the-easy-way.com

(In fact it looks like any requests for nonexistent files return the same 302 redirect instead of a normal 404 error. That's probably not a good idea.)

A: This question is a little old, but I got here from Google and it did help me, but I think what I already know can help.
The Issue of Redirection
Anyhoo, to add to user1686's answer, that's a problem where a page on a https url asks for a resource, in this case, the favicon, which redirecting to a non-https url. This is an issue because, for security reasons, browsers will not allow this.
As user1686 says, in Lisa's case, that happens because their website redirects every not found error (404) to a 302 redirect. Although user1686 says that's not a good idea, I think it's pretty common nowadays to have non-existing URLs redirecting to the closest URL, or sometimes to the index page, and, if you're doing maintenance of your website, you might make that a 302 (temporary redirection).
So, how to deal with that? Well, in her case, since her favicon.ico does not exist and that's the start of the problem, uploading the favicon will be enough. But if you're having problems where your https://example.com/favicon.ico is redirecting to http://example.com/favicon.ico, you might need to look at your redirecting settings, and where they are is going to depend on your server.
Apache
If you're using Apache, redirection settings are set in your .htaccess file, and, although you may have many of them, the relevant one will be the one in the root folder of your website (usually called www or web). Editing .htaccess is an art in itself, I recommend using these resources.
Nginx
If you're using Nginx, you are going to have to play with the main configuration files, probably using the try_files and/or the location directive. You can learn how to use them here. If you don't know where the main configuration file is, it's probably in /etc/nginx, /usr/local/nginx/conf ,  or /usr/local/etc/nginx.
IIS
If you use Microsoft's IIS, I'm guessing it will have to do with the URL rewrite .NET extension. You can find more about it here.


text:
Q: Google Authentication with Xamarin Forms app I've been looking all day for a nice and easy way to integrate Google authentication in a Xamarin Forms app. I've tried a couple of methods but since Google doesn't allow in-app browser view authentication anymore, all of the methods are deprecated (giving error 403, disallowed_useragent).
I had no idea that doing something this simple could become so hard.
There are methods I haven't tried yet, but they require platform specific code (code from before Xamarin Forms) and I don't want that, I want it to be directly cross-platform.
It appears that no one has an SDK for this. Anyone else figured it out?


text:
Q: DrawerLayout on top of Actionbar When using the drawer layout is there a way to overlay the drawer view over the action bar?  I do not want to hide the action bar when the drawer is shown.  I want the action bar to simply stay put, but be sent to the background.  An example of this is the iOS Play Music app...

My current implementation hides and shows the action bar when the drawer state changes, but I do not like this user experience.
        public void onDrawerClosed(View view) {
            getActionBar().show();
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().hide();
            invalidateOptionsMenu();
        }

A: I searched the web in order to find any good solution for this problem and haven't found. So I did a trick that did this.
First of all we need to request action bar overlay feature. So in onCreate()  of your activity, before setContntView() call: requestWindowFeature(com.actionbarsherlock.view.Window.FEATURE_ACTION_BAR_OVERLAY);
It will make everything including navigation drawer draw behind action bar. We don't need this, so we need to set the top margin of our FrameLayout which hosts our fragments in the activity with the exact height of the action bar. In the layout file of the activity we need to do the following:
<!-- Framelayout to display Fragments -->

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize" />

It will make only navigation drawer appear behind the action bar.
Now we will hide the action bar when the navigation drawer is opened on half, and will show it when the drawer is nearly closed. To do this we need to make the following in the activity:
@Override
    public void onDrawerSlide(View drawerView, float slideOffset) {
        super.onDrawerSlide(drawerView, slideOffset);

        if(slideOffset > 0.5){
            actionBar.setBackgroundDrawable(null);
            actionBar.hide();
        } else {
            actionBar.show();

            if(slideOffset < 0.1){
                actionBar.setBackgroundDrawable(layerDrawable);
            }
        }
    }

As you can see I also change the background drawable of the action bar to make it transparent when before I begin to hide it, and change it back with my custom background when I show it back.
My custom background is a layerListDrawable which is all transparent but have a divider in bottom with some shadow.
And to achieve this I have defined the following layer-list in XML:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent"/>
        </shape>
    </item>

    <item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp">
        <shape android:shape="rectangle">
            <solid android:color="#afafaf"/>
        </shape>
    </item>

    <item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp">
        <shape android:shape="rectangle">
            <gradient
                android:angle="270"
                android:startColor="#88afafaf"
                android:endColor="#33afafaf"
            />
        </shape>
    </item>
</layer-list>

And to get the background I need from this XML I do the following in the activity:
final ActionBar actionBar = getSupportActionBar();
        final LayerDrawable layerDrawable = (LayerDrawable) getResources()
                .getDrawable(R.drawable.shadow_divider);

        final TypedArray styledAttributes = getTheme().obtainStyledAttributes(
                new int[] { R.attr.actionBarSize });
        int topOffset = (int) (styledAttributes.getDimension(0, 0));
        styledAttributes.recycle();

        layerDrawable.setLayerInset(1, 0, topOffset - 3, 0, 2);
        layerDrawable.setLayerInset(2, 0, topOffset - 2, 0, 0);

        actionBar.setBackgroundDrawable(layerDrawable);

where R.drawable.shadow_divider is the XML layer-list I have defined earlier.
It looks really great! Hope it can help someone.
EDIT
I had a small bug here which can be a reason of a crush sometimes. Here is the fixed code:
  `
    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        **android:paddingTop="?attr/actionBarSize"**  />`

It should be paddingTop not layout_marginTop!

A: That's the proper effect in Android defaults. If you want to emulate the iOS effect, you'll probably have to do it yourself, because AFAIK the drawer component of the support library doesn't allow such type of configurations.
Anyway, every time a programmer codes a lot just to emulate some fancy (and much probably not worthy) iOS effect in Android, a little cat dies...

A: I don't think you'll be able to do this with Android's provided Navigation Drawer (without doing something really hacky), since doing this really goes against Android design patterns.  If you want a library that does what you're looking for, I've used this library before Android came out with it's own widget, and it does what you're looking for.

A: I found the answer in my question, also added an example project for reference. You can take a look to see if it works for you.
Android Navigation Drawer on top ActionBar

A: You can achieve this with ActionBarSherlock.
http://actionbarsherlock.com/

A: You will be able to do it but the drawer will look so awkward that you will not like it. I had the same requirement and I ended up using Radio Buttons customized to appear as tabs. You can also try hiding the tabs when the drawer opens and vice versa, but that certainly is not what you want here.
You can try to use ViewPager, tabbed indicator such  PagerTabStrip and/or TabPageIndicator.
Source.


text:
Q: Does reading or writing a whole 32-bit word, even though we only have a reference to a part of it, result in undefined behaviour? I'm trying to understand what exactly the Rust aliasing/memory model allows. In particular I'm interested in when accessing memory outside the range you have a reference to (which might be aliased by other code on the same or different threads) becomes undefined behaviour.
The following examples all access memory outside what is ordinarily allowed, but in ways that would be safe if the compiler produced the obvious assembly code. In addition, I see little conflict potential with compiler optimization, but they might still violate strict aliasing rules of Rust or LLVM thus constituting undefined behavior.
The operations are all properly aligned and thus cannot cross a cache-line or page boundary.

*

*Read the aligned 32-bit word surrounding the data we want to access and discard the parts outside of what we're allowed to read.
Variants of this could be useful in SIMD code.
pub fn read(x: &u8) -> u8 {
    let pb = x as *const u8;
    let pw = ((pb as usize) & !3) as *const u32;
    let w = unsafe { *pw }.to_le();
    (w >> ((pb as usize) & 3) * 8) as u8
}

*Same as 1, but reads the 32-bit word using an atomic_load intrinsic.
pub fn read_vol(x: &u8) -> u8 {
    let pb = x as *const u8;
    let pw = ((pb as usize) & !3) as *const AtomicU32;
    let w = unsafe { (&*pw).load(Ordering::Relaxed) }.to_le();
    (w >> ((pb as usize) & 3) * 8) as u8
}

*Replace the aligned 32-bit word containing the value we care about using CAS. It overwrites the parts outside what we're allowed to access with what's already in there, so it only affects the parts we're allowed to access.
This could be useful to emulate small atomic types using bigger ones. I used AtomicU32 for simplicity, in practice AtomicUsize is the interesting one.
pub fn write(x: &mut u8, value:u8) {
    let pb = x as *const u8;
    let atom_w = unsafe { &*(((pb as usize) & !3) as *const AtomicU32) };
    let mut old = atom_w.load(Ordering::Relaxed);
    loop {
        let shift = ((pb as usize) & 3) * 8;
        let new = u32::from_le((old.to_le() & 0xFF_u32 <<shift)|((value as u32) << shift));
        match atom_w.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
            Ok(_) => break,
            Err(x) => old = x,
        }
    }
}

A: This is a very interesting question.
There are actually several issues with these functions, making them unsound (i.e., not safe to expose) for various formal reasons.
At the same time, I am unable to actually construct a problematic interaction between these functions and compiler optimizations.
Out-of-bounds accesses
I'd say all of these functions are unsound because they can access unallocated memory.  Each of them I can call with a &*Box::new(0u8) or &mut *Box::new(0u8), resulting in out-of-bounds accesses, i.e. accesses beyond what was allocated using malloc (or whatever allocator).  Neither C nor LLVM permit such accesses.  (I'm using the heap because I find it easier to think about allocations there, but the same applies to the stack where every stack variable is really its own independent allocation.)
Granted, the LLVM language reference doesn't actually define when a load has undefined behavior due to the access not being inside the object.  However, we can get a hint in the documentation of getlementptr inbounds, which says

The in bounds addresses for an allocated object are all the addresses that point into the object, plus the address one byte past the end.

I am fairly certain that being in bounds is a necessary but not sufficient requirement for actually using an address with load/store.
Note that this is independent of what happens on the assembly level; LLVM will do optimizations based on a much higher-level memory model that argues in terms of allocated blocks (or "objects" as C calls them) and staying within the bounds of these blocks.
C (and Rust) are not assembly, and it is not possible to use assembly-based reasoning on them.
Most of the time it is possible to derive contradictions from assembly-based reasoning (see e.g. this bug in LLVM for a very subtle example: casting a pointer to an integer and back is not a NOP).
This time, however, the only examples I can come up with are fairly far-fetched: For example, with memory-mapped IO, even reads from a location could "mean" something to the underlying hardware, and there could be such a read-sensitive location sitting right next to the one that's passed into read.
But really I don't know much about this kind of embedded/driver development, so this may be entirely unrealistic.
(EDIT: I should add that I am not an LLVM expert.  Probably the llvm-dev mailing list is a better place to determine if they are willing to commit to permitting such out-of-bounds accesses.)
Data races
There is another reason at least some of these functions are not sound: Concurrency.  You clearly already saw this coming, judging from the use of concurrent accesses.
Both read and read_vol are definitely unsound under the concurrency semantics of C11.  Imagine x is the first element of a [u8], and another thread is writing to the second element at the same time as we execute read/read_vol.  Our read of the whole 32bit word overlaps with the other thread's write.  This is a classical "data race": Two threads accessing the same location at the same time, one access being a write, and one access not being atomic.  Under C11, any data race is UB so we are out. LLVM is slightly more permissive so both read and read_val are probably allowed, but right now Rust declares that it uses the C11 model.
Also note that "vol" is a bad name (assuming you meant this as short-hand for "volatile") -- in C, atomicity has nothing to do with volatile!  It is literally impossible to write correct concurrent code when using volatile and not atomics.  Unfortunately, Java's volatile is about atomicity, but that's a very different volatile than the one in C.
And finally, write also introduces a data race between an atomic read-modify-update and a non-atomic write in the other thread, so it is UB in C11 as well.  And this time it is also UB in LLVM: Another thread could be reading from one of the extra locations that write affects, so calling write would introduce a data race between our writing and the other thread's reading.  LLVM specifies that in this case, the read returns undef.  So, calling write can make safe accesses to the same location in other threads return undef, and subsequently trigger UB.
Do we have any examples of issues caused by these functions?
The frustrating part is, while I found multiple reasons to rule out your functions following the spec(s), there seems to be no good reason that these functions are ruled out!  The read and read_vol concurrency issues are fixed by LLVM's model (which however has other problems, compared to C11), but write is illegal in LLVM just because read-write data races make the read return undef -- and in this case we know we are writing the same value that was already stored in these other bytes! Couldn't LLVM just say that in this special case (writing the value that's already there), the read must return that value?  Probably yes, but this stuff is subtle enough that I would also not be surprised if that invalidates some obscure optimization.
Moreover, at least on non-embedded platforms the out-of-bounds accesses done by read are unlikely to cause actual trouble.  I guess one could imagine a semantics which returns undef when reading an out-of-bounds byte that is guaranteed to sit on the same page as an in-bounds byte. But that would still leave write illegal, and that is a really tough one: write can only be allowed if the memory on these other locations is left absolutely unchanged.  There could be arbitrary data sitting there from other allocations, parts of the stack frame, whatever.  So somehow the formal model would have to let you read those other bytes, not allow you to gain anything by inspecting them, but also verify that you are not changing the bytes before writing them back with a CAS. I'm not aware of any model that would let you do that. But I thank you for bringing these nasty cases to my attention, it's always good to know that there is still plenty of stuff left to research in terms of memory models :)
Rust's aliasing rules
Finally, what you were probably wondering about is whether these functions violate any of the additional aliasing rules that Rust adds. The trouble is, we don't know -- these rules are still under development.  However, all the proposals I have seen so far would indeed rule out your functions: When you hold an &mut u8 (say, one that points right next to the one that's passed to read/read_vol/write), the aliasing rules provide a guarantee that no access whatsoever will happen to that byte by anyone but you.  So, your functions reading from memory that others could hold a &mut u8 to already makes them violate the aliasing rules.
However, the motivation for these rules is to conform with the C11 concurrency model and LLVM's rules for memory access.  If LLVM declares something UB, we have to make it UB in Rust as well unless we are willing to change our codegen in a way that avoids the UB (and typically sacrifices performance). Moreover, given that Rust adopted the C11 concurrency model, the same holds true for that.  So for these cases, the aliasing rules really don't have any choice but make these accesses illegal.  We could revisit this once we have a more permissive memory model, but right now our hands are bound.


text:
Q: How to change even list to odd list in racket/scheme? I have the following code for even list:
(define (even xs)
    (cond
        ((null? xs) '())
        ((eq? (cdr xs) '()) '())
        (else (cons (cadr xs) (even (cddr xs))))))
;(even-list   '(a b c d)) produces (b d)

How can I do the same for odd list that  produce (a c) if  (odd-list   '(a b c d)) is enetered.

A: I'm sure you're asked to write this out fully, on your own. For that, do note that (in the code you provide) you're checking whether the cdr is empty list, because you're taking the cadr as your first element.
For odds, you don't need the cadr. The first element is at an odd position already.
But there's also a simple trick you could use.
Question: what effect does (cons 1 xs) have on the length of xs?


text:
Q: PhantomJS: view dependents such as .js, not just final html In PhantomJS, is there a way to view the dependents? For example, a page causes a JS script to load. Instead of just viewing the final browser html result, I'd like to see the js script.
What I want to see has Content-Type: application/json

A: It is possible.
In phantomjs you have the whole list of page callbacks.
Hooking to onResourceRequested and onResourceReceived will give you the desired information every time page tries to load anything.


text:
Q: Show that if $x$ is a primitive root modulo $p^r$, then $x$ is a primitive root modulo $p$ I'm trying to solve the following problem:
Let $p\geq 3$ be a prime number, let $r \in \Bbb N$, and let $x$ be a primitive root modulo $p^r$. Show that $x$ is a primitive root modulo $p$.

I'm pretty much out of ideas. I tried to use the following claim: $a$ is a primitive root modulo $n$ if and only if for every
prime $q$ such that $q$ divides $\varphi(n)$ we have:
$$a^{\frac{\varphi(n)}{q}}\not\equiv 1\pmod n$$
But got nothing.

A: Hint: If $x^{\frac{p-1}{2}} \equiv 1 \bmod p$, then $x^{\frac{p-1}{2}(p^{r-1})} \equiv 1 \bmod p^r$ by induction on $r$.


text:
Q: Unable to start activity ComponentInfo{...}: java.lang.NullPointerException As I just started my first Android application, I've been granted with my first issues.
The code below is quite simple and the only goal is to navigate from MainActivity.java to IMC.java
However, I've been looking for a solution to this on a lot of tutorial and I really don't get what I'm doing wrong...
package com.example.firstapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

    Button IMC;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        IMC = (Button) findViewById(R.id.buttonIMC);
        IMC.setOnClickListener(IMCListener);
    }

    // Listener du bouton IMC
    private OnClickListener IMCListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this,IMC.class);
                startActivity(i);
           }
    };
}

In the activity_main.xml, I got the following code:
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".IMC" >

    <Button
        android:id="@+id/buttonIMC"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="IMC" />

</RelativeLayout>

The stack trace is
11-03 16:30:04.877: E/AndroidRuntime(619): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.firstapp/com.example.firstapp.IMC}: java.lang.NullPointerException
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.os.Looper.loop(Looper.java:123)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.ActivityThread.main(ActivityThread.java:4627)
11-03 16:30:04.877: E/AndroidRuntime(619):  at java.lang.reflect.Method.invokeNative(Native Method)
11-03 16:30:04.877: E/AndroidRuntime(619):  at java.lang.reflect.Method.invoke(Method.java:521)
11-03 16:30:04.877: E/AndroidRuntime(619):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-03 16:30:04.877: E/AndroidRuntime(619):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-03 16:30:04.877: E/AndroidRuntime(619):  at dalvik.system.NativeStart.main(Native Method)
11-03 16:30:04.877: E/AndroidRuntime(619): Caused by: java.lang.NullPointerException
11-03 16:30:04.877: E/AndroidRuntime(619):  at com.example.firstapp.IMC.onCreate(IMC.java:57)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

And the manifest is here below
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.firstapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.firstapp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.firstapp.MainActivity2"
            android:label="@string/title_activity_main_activity2" >
        </activity>
        <activity
            android:name="com.example.firstapp.IMCActivity"
            android:label="@string/title_activity_imc" >
        </activity>
        <activity
            android:name="com.example.firstapp.Interest"
            android:label="@string/title_activity_interest" >
        </activity>
        <activity
            android:name="com.example.firstapp.IMC"
            android:label="@string/title_activity_imc" >
        </activity>
    </application>

</manifest>

The activity IMC is already set and is working properly (basically, it is only a simple computation)
And to be totally exhaustive here it is:
package com.example.firstapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.text.TextWatcher;
import android.text.Editable;

public class IMC extends Activity {
  // La chaîne de caractères par défaut
  private final String defaut = "Vous devez cliquer sur le bouton « Calculer l'IMC » pour obtenir un résultat.";
  // La chaîne de caractères de la megafonction
  private final String megaString = "Vous faites un poids parfait ! Wahou ! Trop fort ! On dirait Brad Pitt (si vous êtes un homme)/Angelina Jolie (si vous êtes une femme)/Willy (si vous êtes un orque) !";

  Button envoyer = null;
  Button raz = null;

  EditText poids = null;
  EditText taille = null;

  RadioGroup group = null;

  TextView result = null;

  CheckBox mega = null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // On récupère toutes les vues dont on a besoin
    envoyer = (Button)findViewById(R.id.calcul);

    raz = (Button)findViewById(R.id.raz);

    taille = (EditText)findViewById(R.id.taille);
    poids = (EditText)findViewById(R.id.poids);

    mega = (CheckBox)findViewById(R.id.mega);

    group = (RadioGroup)findViewById(R.id.group);

    result = (TextView)findViewById(R.id.result);

    // On attribue un listener adapté aux vues qui en ont besoin
    envoyer.setOnClickListener(envoyerListener);
    raz.setOnClickListener(razListener);
    taille.addTextChangedListener(textWatcher);
    poids.addTextChangedListener(textWatcher);

    // Solution avec des onKey
    //taille.setOnKeyListener(modificationListener);
    //poids.setOnKeyListener(modificationListener);
    mega.setOnClickListener(checkedListener);
  }

  /*
  // Se lance à chaque fois qu'on appuie sur une touche en étant sur un EditText
  private OnKeyListener modificationListener = new OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
      // On remet le texte à sa valeur par défaut pour ne pas avoir de résultat incohérent
      result.setText(defaut);
      return false;
    }
  };*/

  private TextWatcher textWatcher = new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
      result.setText(defaut);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
      int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
  };

  // Uniquement pour le bouton "envoyer"
  private OnClickListener envoyerListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
      if(!mega.isChecked()) {
        // Si la megafonction n'est pas activée
        // On récupère la taille
        String t = taille.getText().toString();
        // On récupère le poids
        String p = poids.getText().toString();

        float tValue = Float.valueOf(t);

        // Puis on vérifie que la taille est cohérente
        if(tValue == 0)
          Toast.makeText(IMC.this, "Hého, tu es un Minipouce ou quoi ?", Toast.LENGTH_SHORT).show();
        else {
          float pValue = Float.valueOf(p);
          // Si l'utilisateur a indiqué que la taille était en centimètres
          // On vérifie que la Checkbox sélectionnée est la deuxième à l'aide de son identifiant
          if(group.getCheckedRadioButtonId() == R.id.radio2)
            tValue = tValue / 100;

          tValue = (float)Math.pow(tValue, 2);
          float imc = pValue / tValue;
          result.setText("Votre IMC est " + String.valueOf(imc));
        }
      } else
        result.setText(megaString);
    }
  };

  // Listener du bouton de remise à zéro
  private OnClickListener razListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
      poids.getText().clear();
      taille.getText().clear();
      result.setText(defaut);
    }
  };

  // Listener du bouton de la megafonction.
  private OnClickListener checkedListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
      // On remet le texte par défaut si c'était le texte de la megafonction qui était écrit
      if(!((CheckBox)v).isChecked() && result.getText().equals(megaString))
        result.setText(defaut);
    }
  };
}

(this code above is not from me, it comes from a tutorial found on openclassroom)
Would you have any idea, it would be much appreciated :)
Thanks!

A: Line 57 of IMC.java envoyer.setOnClickListener(envoyerListener)

Looks like envoyer is null.
You have
   setContentView(R.layout.activity_main);

Your activity_main.xml does not have a button with that id R.id.calcul.
You need to change this
  setContentView(R.layout.imc); // layout xml for IMC Activity

Make sure it has a button with the id R.id.calcul and it will work.

A: Please check image size you're given & change image if possible
android:src="@drawable/youimage"


text:
Q: Programmatic selection of web page content with styles If I select with the mouse contents from any web page, copy them to the clipboard and then paste them on an email editor (e.g., Gmail) I get all sort of rich contents copied, like styles, images, etc.
I would like to do the same kind of rich content selection, but with javascript.
More specifically, I would like to select with javascript all contents inside a divin a web page I own, so that the user just has to press Ctrl+C and then paste the contents on an email editor.
Is there a way to do that? How?


text:
Q: Appfog mysql tunnel error - Encryption not available on this event-machine We've established a connection to appfog using caldecott and af tunnel command. We try to connect to a mysql service to load and execute a big .sql file to populate the db.
We tried it from 3 different machines Ubuntu on VirtualBox, Feora 18 on VirtualBox and native Ubuntu. We also tried it on another account, but we keep getting this error:
Launching 'mysql --protocol=TCP --host=localhost --port=10000 --user=uZVQhGhbYEzyb --password=pNu1l6xbXVhbj d39d6d0e6344b41a4aaeada16dfca2a46'

terminate called after throwing an instance of 'std::runtime_error'
 what():  Encryption not available on this event-machine
ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0

Aborted (core dumped)

A: For a Windows system, I got it to run by doing the following:

*

*Install Win32 OpenSSL v1.0.1e Light from here

*Install Visual C++ 2008 Redistributables from the same link if not already installed.

*Re-install eventmachine in Ruby with the newly installed open-ssl.

gem install eventmachine -- --with-ssl-dir=C:\OpenSSL-Win32

(you might need C:\OpenSSL-Win32\bin)
After the installation is complete, you're ready to tunnel to any service! (In my case postgresql)

A: Thanks to appfog customer support I managed to solve this problem. My distro lacked an ssl provider.
To solve this on fedora
yum install openssl openssl-devel
gem uninstall eventmachine
gem install eventmachine

However I still had a problem with executing big sql scripts. Does anyone know a neat solution to this issue?


text:
Q: Understanding DirectoryWatcher I've been trying to use and understand the DirectoryWatcher class from Microsoft's Cloud Mirror sample.  It uses ReadDirectoryChangesW to monitor changes to a directory.  I don't think it's reporting all changes, to be honest.  In any event, I had a question about the key part of the code, which is as follows:
concurrency::task<void> DirectoryWatcher::ReadChangesAsync()
{
    auto token = _cancellationTokenSource.get_token();
    return concurrency::create_task([this, token]
    {
        while (true)
        {
            DWORD returned;
            winrt::check_bool(ReadDirectoryChangesW(
                _dir.get(),
                _notify.get(),
                c_bufferSize,
                TRUE,
                FILE_NOTIFY_CHANGE_ATTRIBUTES,
                &returned,
                &_overlapped,
                nullptr));

            DWORD transferred;
            if (GetOverlappedResultEx(_dir.get(), &_overlapped, &transferred, 1000, FALSE))
            {
                std::list<std::wstring> result;
                FILE_NOTIFY_INFORMATION* next = _notify.get();
                while (next != nullptr)
                {
                    std::wstring fullPath(_path);
                    fullPath.append(L"\\");
                    fullPath.append(std::wstring_view(next->FileName, next->FileNameLength / sizeof(wchar_t)));
                    result.push_back(fullPath);

                    if (next->NextEntryOffset)
                    {
                        next = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(reinterpret_cast<char*>(next) + next->NextEntryOffset);
                    }
                    else
                    {
                        next = nullptr;
                    }
                }
                _callback(result);
            }
            else if (GetLastError() != WAIT_TIMEOUT)
            {
                throw winrt::hresult_error(HRESULT_FROM_WIN32(GetLastError()));
            }
            else if (token.is_canceled())
            {
                wprintf(L"watcher cancel received\n");
                concurrency::cancel_current_task();
                return;
            }
        }
    }, token);
}

After reviewing an answer to another question, here's what I don't understand about the code above: isn't the code potentially re-calling ReadDirectoryChangesW before the prior call has returned a result?  Or is this code indeed correct?  Thanks for any input.
Yes, I seem to have confirmed in my testing that there should be another while loop there around the call to GetOverlappedResultEx, similar to the sample code provided in that other answer.  I think the notifications are firing properly with it.
Shouldn't there also be a call to CancelIo in there, too?  Or is that not necessary for some reason?


text:
Q: URL Rewriting in ASP.NET Could anyone suggest me which is the best technique for URL rewriting for an ASP.NET 3.5 web application?
Thanks

A: If you are using IIS 7 for your ASP.NET application, you may want to download:

*

*Microsoft's URL Rewrite Module for IIS 7.0
If you are using IIS 6 or IIS 5, you may want to consider using the following open source component:

*

*UrlRewritingNet.UrlRewrite

A: With which web server?
If it's the Apache HTTP server, then mod_rewrite is probably your best bet.
The Wikipedia article probably sums it up best, covering the major web servers and web frameworks.

There is also the option of URL Rewriter And Reverse Proxy, which is a mod_rewrite clone for IIS 6 and IIS 7, and works with ASP.NET.

A: If you are using ASP.NET 3.5 SP1, use ASP.NET UrlRouting instead. Check this great article from Chris Cavanagh or this one from Phil Haack.

A: Daniel Vassallo is correct in that you need to use UrlRewritingNet.UrlRewrite to make this work.
However, I am going to warn you now that most host (from my experience) are not correctly setup to handle URL Rewriting.
If you find that you are getting 404 errors, then either your URLRewrite setup is wrong in the web.config, or they have 'verify file exist' checked in IIS.  Most host will change this for you if you request.
http://forums.asp.net/p/890825/1017645.aspx
http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/

A: The easiest solution is to pass all requests through the same script file (i.e. to index.php), and then parse the URL with script code. How you do this depends on your platform.

A: If you don't have the knowledge or the capability to install a URL re-writing plugin / module to your webserver or just need a simple re-write.
Below is a stripped down version of URL re-writing I do in IIS 6.
Here is a very basic version of URL rewriting that you can place into your Global.asax or Global.asax.cs file in the root of your website.
This snippet of code Redirects the url /Store/Categories/ to /Store/Default.aspx?action=categories while the user sees /Store/Categories/ in their URL, your application sees the URL as /Default.aspx?action=categories and Request["action"].ToString() will have the value of "categories"
void Application_BeginRequest(object sender, EventArgs e)
{
    string fullOriginalpath = Request.Url.ToString().ToLower();

    if (fullOriginalpath.Contains("/store/categories/"))
    {
        Context.RewritePath("/Store/Default.aspx?action=categories");
    }
    else if (fullOriginalpath.Contains("/store/products/"))
    {
        Context.RewritePath("/Store/Default.aspx?action=products");
    }
}


text:
Q: How to pass default value as 0 but not to reflect in HTML I am working in angular and I am passing 0 as default value in reactive form formControl. The default value is getting reflected in the HTML input. I dont want to show default value in HTML input field at first.
How can I achieve that ?
carnumbers: new FormControl('0', [Validators.minLength(1), Validators.maxLength(2), Validators.pattern("^[0-9]*$")])

Note: the default value must be 0

A: Use null or '' and change that to your default values as a preprocess step before submitting the form.

A: If you don't want show default value in View, you should use setValue or patchValue on formControl and pass emitModelToViewChange:false options to it.
 carnumbers = new FormControl(null, [Validators.minLength(1),
     Validators.maxLength(2), Validators.pattern("^[0-9]*$")]);

  ngAfterViewInit(){
      this.carnumbers.setValue(0,{emitModelToViewChange:false});
  }

Working Simple Example


text:
Q: Decoupling capacitor arrangement I came across this decoupling capacitor arrangement on the evaluation board for the AD5791.  It decouples the IC AD8676 with 10 caps!  I suspect its related to the AD8676 driving the reference inputs and thus requiring significant changes in current draw as new values are set on the AD5791 DAC.  However, it seems like a bit of overkill to me and I'm just wondering will I see any significant performance difference between this setup and an alternative with just a 0.1 and 10 uF on each power rail to GND?  If the answer is that the extra caps will help in this situation, then what is the optimal placement of the capacitors C28,29 in this diagram between the two voltage rails?

A: You're supposed to use those caps on different power pins.  It only looks like they're all in parallel in schematic form.  On a PCB the layout matters.
The schematic at the end of the datasheet shows this.

A: I would definitely put them on there. And pay close attention to their layout details.
Why in the world would you consider compromising a $100+ DAC board that has world-class (~6 decimal digit - 1ppm) performance (LTZ1000 ovenized voltage reference, ultraprecision op-amps) by trying to economize on a few  pennies worth of tiny passives?

A: *

*follow the layout of the demo card unless you know better.

This board has insanely low INL of 1 bit in a 20bit DAC and 10x 0.1uF caps have far lower ESR and Higher SRF than one 1uF ceramic cap.
I remember a problem in the late 70's with the best Burr Brown Hybrid ADC had INL issues which I surmised was due its internal Vref getting ground shift from the  TTL currents switch many bits at once in a linear sweep with several dead codes and hysteresis in the opposite direction. They fixed the problem on the next shipment.
The same holds challenge holds true with minimizing Vref changes in a 20bit DAC so extremely low ESR is needed to attenuate ripple from high speed switched capacitance of FETs.
So I am not surprised to see this common solution for solid low ESR supply filtering distributed to every IC. Even so you still need a variety of values with carefully selected S parameters matched to the ESL of DC grid traces to avoid anti-resonance with noise spectrum generated.

A: Sometimes you don't see any difference whether you use decoupling caps or not. The times when you discover a problem because you didn't put the right caps are really painful, trust me :) because the problems you have look extremely crazy and you never know what's the hell is going on.
Having said that, you should understand why there are these capacitors and make an educated decision. 10uF and 0.1uF cover different frequencies (because of internal ESL, ESR). The total capacitance may be a function of current consumption. And most important- in application notes, you will always find excessive recommendations, most of the times you can relax a bit. Of course, it depends on other aspects of your design and what risks are you prepared to take to save two/four/eight capacitors.

A:
Blockquote    It decouples the IC AD8676 with 10 caps!

No, it doesn't.  It decouples the AD8676 with 5 caps.  The other 5 are for other chips.
An Analog Devices top applications dude drove this home in a seminar in the 90's.  The applications details (schematics, decoupling scheme, demo board layouts, etc.) in their documentation has been tweaked to death.  ((Everything)) is important, every little detail.  If you want the part to deliver the performance they document, you can't change anything.  Beyond capacitor values, use the same manufacturer and part number.  He was serious - a 16 bit part can become a 12-bit part real fast.
Update:  There is no standard way to show decoupling caps on a schematic. Analog devices routinely shows them right at the component pins, but there is a difference between documenting a design and teaching a design.  Putting them at each device clutters up the area around the device where clarity is needed the most, which can be more important in a production / testing environment.
I do what you show, pile them up in a corner somewhere so the netlister and BOM creator can find them. I think it is a valid assumption that most designers know what is going on; the ones that don't, ask and learn.


text:
Q: Develop without Material Design I'm using Android Studio to develop some applications and I have Material Design even in Android 2.3! Can anyone suggest me another application that didn't FORCE Material Design? Or a way that remove material design?Thanks

A: There is no requirement for you to implement the Material Design aesthetic on any application, let alone the one that you are describing.
Moreover, Material Design is not responsible for your application size, any more than the white pixels on this Web page makes the page fat.
You did not provide any information about your application's setup. My guess is that you are using com.android.support:appcompat-v7 (AppCompatActivity, Theme.AppCompat, etc.). Those add ~1MB to an app's release size, and appcompat-v7 is what gives your app the Material Design look on older devices.
You do not have to use appcompat-v7. Simply remove it from your app/build.gradle file and remove any place where your code is leveraging it:

*

*Replace AppCompatActivity with Activity

*Replace Theme.AppCompat with other themes based on Android version

*Replace the app: prefix in your menu resources with android:

*And so on

Depending upon your app's configuration, you might be pulling in other libraries that themselves depend upon appcompat-v7 (e.g., com.android.support:design). You would need to get rid of those as well.
This will take some work for an existing application. Usually, it is easier to opt out of using appcompat-v7 at the outset.
This GitHub repo contains hundreds of sample apps from my book. Most of these do not use appcompat-v7.


text:
Q: Class TrueOleDBGrid80.TDBGrid of control DBGrid1 was not a loaded control class I have an existing vb project that uses True DBGrid. I opened the source file in a Win7 PC, and I installed True dbGrid 8.0 Pro. Now, the error comes out: Class TrueOleDBGrid80.TDBGrid of control DBGrid1 was not a loaded control class.
Is there any settings to solve this problem?
Thanks


text:
Q: Using Import-CSV to make HTTP Request Wonder if anyone can help. I'm trying to use powershell to import a list of domains and generate a HTTP request for each of them. Currently I've got this far:

$csvFilename = "C:\Sites\sites.csv"
$csv = Import-Csv $csvFilename -Header @("url") |
foreach {

   $HTTP_Request = [System.Net.WebRequest]::Create('$csv')

   $HTTP_Response = $HTTP_Request.GetResponse()

   $HTTP_Status = [int]$HTTP_Response.StatusCode

If ($HTTP_Status -eq 200) {
    Write-Host "Site is OK!"
}
Else {
    Write-Host "The Site may be down, please check!"
}

$HTTP_Response.Close()

}

I'm not sure why but the 'Create()' statement won't pick up the URL. Any ideas?
Many thanks

A: inside the foreach loop, you can access the current element with the automatic variable $_
so replace this line $HTTP_Request = [System.Net.WebRequest]::Create('$csv')
by
$HTTP_Request = [System.Net.WebRequest]::Create("$_")
but before as create method is waiting for a string,you will have to expand your url property (otherwise you get a pscustomObject not a string) :
Import-Csv c:\temp\urls.csv -Header "url" |select -expand url |%{ [System.Net.Webrequest]::Create("$_")}


text:
Q: What is the best approach to use different CFLAGS for the same source files? i need to build the same source tree twice,
1 - with normal cflags to build the project binary
2 - with cflags plus -fPIC to build a static library that would be some sort of SDK to develop project dynamic modules.
Using only one Makefile, what is the best approach to accomplish this?
It would be nice to do some sort of :
all: $(OBJECTS)

lib_rule: $(OBJECTS)
   CFLAGS += -fPIC

.cpp.o:
   $(CC) -c $< -o $@ $(CFLAGS)

But obviously it can't be done.
Thanks

A: GNU make offers also "Target-specific Variable Values". Consider the following Makefile:
# Makefile
CFLAGS := My Cflags

all: $(OBJECTS)
        @echo "$@ CFLAGS is: " $(CFLAGS)

lib_rule: CFLAGS += extended by -fPIC
lib_rule: $(OBJECTS)
        @echo "$@ CFLAGS is: " $(CFLAGS)

# Makefile - end.

$ make all
all CFLAGS is:  My Cflags
$ make lib_rule
lib_rule CFLAGS is:  My Cflags extended by -fPIC
$
(Please note: if you copy and paste the example, remember to re-add the tabstops in front of the command lines. I always get caught by that.)

A: Instead of placing the compiled .o files in the same directory as the source, I create them in labeled sub-directories.  In your case, you can have the static library files created as source_dir/lib/*.o and your normal files as source_dir/bin/*.o.  In your different build targets after you set up your unique CFLAGS, simply generate a DIR_NAME value holding the name of the appropriate sub-folder.  You can use this variable when you create the paths for the compiler to use when building and when linking.

A: One thing I've used in the past is a different extension:
.cpp.o:
    $(CC) -c $< -o $@ $(CFLAGS)

.cpp.lo:
    $(CC) -c $< -o $@ $(CFLAGS) $(EXTRA_CFLAGS)

You then build your static library from the .lo files and you binary from the .o files:
prog: a.o b.o

libsdk.a: a.lo b.lo

Assuming you are using GNU Make, you can use some built in functions to only have to maintain the list of objects one time:
OBJS = a.o b.o
LOBJS = $(patsubst %.o, %.lo, $(OBJS))

A: In a different make tool such as CMake, you can express something like that much more easily.
For instance, you could well do
set(sources ABC.cpp DEF.cpp XYZ.cpp)
ADD_LIBRARY(mylib STATIC ${sources})
add_executable(myExecutable  ${sources} main.cpp)

Or, you could repeatedly build the same directory with different flags by including it several times from the directory's logical parent, i.e.
set(MyTweakFlag 2)
add_subdirectory("libDir" "libDir2")
set(MyTweakFlag 3)
add_subdirectory("libDir" "libDir3")

...and then use if() or whatnot in the child directory to set the right flags.
Particularly if you have many such configurations, using make becomes quite fragile; make won't correctly find the transitive closure of recursive make dependancies (and certainly won't correctly find the dependancy on the makefile itself - if you change flags, say) so if you're going to do complicated makefile magic: do it with a better tool!
(CMake simply happens to be what I replaced make with, but there are various other replacements possible, of course)


text:
Q: remove index.php from zend framework url I am developing a module using zend framework and I have created a project using zf create project
command
when i try to access the url using ip/folder/controller/action it is giving error not found error when i try access using ip/folder/index.php/controller/action i am able to access but i am unable to include js,css files  in both cases and my htaccess is
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

and the index.php is
<?php

   // Define path to application directory
   defined('APPLICATION_PATH')
   || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/application'));

   // Define application environment
    defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV')
       ? getenv('APPLICATION_ENV') : 'production'));

   // Ensure library/ is on include_path
     set_include_path(implode(PATH_SEPARATOR,
     array(realpath(APPLICATION_PATH . '/library'), get_include_path(),
)));

/** Zend_Application */
require_once 'Zend/Application.php';

// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap()->run();

A: Try adding this to your .htaccess:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /([^/]+/)*index.php
RewriteRule ^index.php(.*)$ /path/to/your/installation$1 [R=301,L]

Replace /path/to/your/installation with the correct path

A: I just add this to the top of the index.php:
$_SERVER["REQUEST_URI"] = str_replace('index.php', '', $_SERVER["REQUEST_URI"]);

which is the other method suggested by Rob Allen at Akrabat.com


text:
Q: actix_web middleware ErrorHandlers return error message in ServiceResponse I am trying to capture errors that may occur for requests made to my server.
This came up when I was receiving a 400 on one of my POST requests (which was thrown before even getting to my request handler method) and I was receiving no feedback as to what the issue was after enabling the debug logs I saw the issue
[actix_web::types::json] Failed to deserialize Json from payload. Request path: /new_endpoint
Json deserialize error: invalid length: expected one of [36, 32], found 10 at line 2 column 20
[DEBUG actix_web::middleware::logger] Error in response: Deserialize(Error("invalid length: expected one of [36, 32], found 10", line: 2, column: 20))

Now, I want to be able to capture that error so that it can be sent back in the body of the 400 response.
I've started with
App::new()
    .wrap(ErrorHandlers::new().handler(http::StatusCode::BAD_REQUEST, handle_bad_request))

and in handle_bad_request I am able to modify the response body to contain new information
fn handle_bad_request<B>(mut res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<Body>> {
    res.response_mut().headers_mut().insert(
        http::header::CONTENT_TYPE,
        http::HeaderValue::from_static("application/json"),
    );
    let new_res: ServiceResponse<Body> = res.map_body(|_head, _body| {
        ResponseBody::Other(Body::Message(Box::new("New Response Body")))
    });
    Ok(ErrorHandlerResponse::Response(new_res))
}

Ideally what I want to do is take the error in ServiceResponse and send it back in the response. I am able to read the error by doing
match res.response().error() {
    Some(e) =>  println!("{0}", e),
    None =>  println!("Error None")
};

but as for actually taking that error and sending it back in the response I am not able to figure that out.

A: To solve this format!("{:?}", res.reponse().error()) was needed. That does return Some(error message) so just to account for that the following worked.
let errorMsg: String = match res.response().error() {
    Some(e) => format!("{:?}", e),
    None =>  String::from("Unknown Error")
};
let new_res: ServiceResponse<Body> = res.map_body(|_head, _body| {
    ResponseBody::Other(Body::Message(Box::new(errorMsg)))
});
Ok(ErrorHandlerResponse::Response(new_res))


text:
Q: Glassfish doctype description files missing In the glassfish-web.xml you have the doctype description file linked, like http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd.
This is downloaded and parsed by glassfish, when our application is deployed. glassfish.org is not available anymore so we changed to http://glassfish.java.net, but even that is not available anymore. Does anybody know, where to find the dtd's?
Maybe we could embed the dtd's as a permanent solution?

A: Your question is a little bit confusing because these files are actually NOT downloaded from the internet, this would mean that nobody could deploy anything without a connection to the internet.
The files are located in <YOUR_GLASSFISH_FOLDER>/glassfish/lib/dtds/
If you get an error message which says it can't locate the DTD to validate, you may have a formatting error in your XML file. Have a look at this question for more details.


text:
Q: The buttons in project delete the squares? I have problem with my C# winform project.
I have function that draw squares:
public void DrawingSquares(int x, int y)
{
  System.Drawing.Graphics graphicsObj;
  graphicsObj = this.CreateGraphics();
  Pen myPen = new Pen(System.Drawing.Color.Black, 5);
  Rectangle myRectangle = new Rectangle(x, y, 100, 100);
  graphicsObj.DrawRectangle(myPen, myRectangle);
}

private void button1_Click(object sender, EventArgs e)
{
  z = Convert.ToInt16(textBox1.Text)-1;
  k = Convert.ToInt16(textBox2.Text)-1;
  DrawAllSquares();
}

private void DrawAllSquares()
{
  int tempy = y;
  for (int i = 0; i < z; i++)
  {
    DrawingSquares(x, y);
    for (int j = 0; j < k - 1; j++)
    {
      tempy += 50;
      DrawingSquares(x, tempy);
    }
    x += 50;
    tempy = y;
  }
}

In my project, I have a function that I use to move button around the form at runtime, but when the button is moved onto the drawing the drawing is deleted.
What can I do to make the drawing permanent?

A: If you need permanently (in terms of application life time), by any means, you need to use it inside you Control's (the Control where rectangle is have to be drawn), OnPaint method.
If you need an animation too: it could be resolved by using a timer and changing coordinates that you pass like a parameters to your DrawSquares.
Hope this helps.
EDIT
A pseudocode:
public class MyControl : Control
{
    public override void OnPaint(PaintEventArgs e)
    {
       base.OnPaint(e);

       DrawingSquares(e.Graphics, valueX, valueY);
    }

    public void DrawingSquares(Graphics graphicsObj, int x, int y)
    {
       Pen myPen = new Pen(System.Drawing.Color.Black, 5);
       Rectangle myRectangle = new Rectangle(x, y, 100, 100);
       graphicsObj.DrawRectangle(myPen, myRectangle);
    }

}

valueX and valueY are relative X and Y coordinates where you want the rectangle to be drawn.
These coordinates can be constant values, or you can change them from some timer and call Invalidate() on MyControl, so paint will be executed.


text:
Q: plsregress - can anyone explain the normalisation of features? I am using plsregress in matlab as a feature reduction method before performing LDA. I am trying to cross validate my method, however have some trouble replicating their "data processing" stage.

plsregress uses the SIMPLS algorithm, first centering X and Y by subtracting off column means to get centered variables X0 and Y0. However, it does not rescale the columns. To perform PLS with standardized variables, use zscore to normalize X and Y.

in order to try and replicate this on my "test" set I have done the following:
test = test - repmat(mean(test), DIM(1), 1);

test = Xloadings\test';
test = test';

This for some reason does not quite work, and when applied to the training set, I do not achieve the same Xscores.
Is anyone able to explain if there is a step I am missing, or something I am doing wrong?
EDIT: In other words, how to I apply the model generated by PLS to another dataset?

A: I think you need to use the mean from the training set, not the test set.
This would also apply to normalization of sigma.
Use [Z,mu,sigma] = zscore(train).  Apply mu and sigma to test.


text:
Q: $x\cos(2x) + x^2\cos(4x) +... + x^n\cos(2nx)$ Expressing $x\cos(2x) + x^2\cos(4x) +... + x^n\cos(2nx)$ as a sum of two terms.
This is question from my exam. I tried to write it as sum and come to expression
$$
xe^{ixn}\frac{e^{-inx}-x^ne^{inx}}{e^{-ix}-xe^{ix}}
$$ but I don't know how to write this over $sin$ and $cos$ function

A: As hamam_Abdallah suggests, for real $x$, you have a partial sum
$$\sum_{k=1}^n x^k\cos(2kx)=\Re\left(\sum_{k=1}^n x^ke^{2kix}\right)=\Re\sum_{k=1}^n (xe^{2ix})^k=\Re\left(\frac{1-(xe^{2ix})^{n+1}}{1-xe^{2ix}}-1\right)$$
of a geometric series with the $k=0$ term missing. Now
$$\Re\left(\frac{1-(xe^{2ix})^{n+1}}{1-xe^{2ix}}-1\right)=\Re\left(\frac{xe^{2ix}-(xe^{2ix})^{n+1}}{1-xe^{2ix}}\right)=\Re\left(\frac{\left(xe^{2ix}-(xe^{2ix})^{n+1}\right)(1-xe^{-2ix})}{(1-xe^{2ix})(1-xe^{-2ix})}\right)$$
which for real $x$ simplifies to
$$\Re\left(\frac{\left(xe^{2ix}-x^2-(xe^{2ix})^{n+1}+x^{n+2} e^{2ixn}\right)}{1-2x\cos(2x)+x^2}\right)=
\frac{x\cos(2x)-x^2-x^{n+1}\cos(2x(n+1))+x^{n+2} \cos(2xn)}{1-2x\cos(2x)+x^2}.$$

A: Your sum is exactly the real part of the complexe sum
$$\sum_{p=1}^n x^pe^{2pix}=\sum_{p=1}^n (xe^{2ix})^p$$
this is a geometric series, given by
$$(xe^{2ix})\frac{1-(xe^{2ix})^n}{1-(xe^{2ix})}$$