text:
Q: Feature-length animated movie from 80s or early 90s about humans avoiding androids Back somewhere between 1995 and 1998 I have watched feature-length animated movie on home video. Sadly, tape was broken and I have never seen last 15-20 minutes. Animation quality was remarkably better than anything on TV at that time, so I think it was relatively new then. I don't remember anything from plot for certain, probably because I was too young to understand any of it (but hey, if it's animated it must be for children, right?).
What I do remember, though:

*

*There were only two main human characters - male and female. I'd say they were in 20s. Female might have been introduced in later part of the movie. If there were other humans, they didn't play significant enough role for me to remember them.

*There were a lot of androids, all looking exactly the same. They were painted black or dark-grey. Being androids, they were very human-like. I think they had blank heads, as if wearing helmets. I think they had very smooth movements and maybe main characters initially thought that they are humans?

*Androids had some specific, in-universe name. I think it did end with "-oid". It might have been in a title of movie.

*Main characters preferred to avoid these androids, rarely engaging in open confrontation.

*I don't remember any cities, forests, seas or grasslands. Most of the action was out in open air on some desert and/or rocky area, like real-world planet Mars.

*Art style was realistic. Think of something similar to The End of Evangelion.

*Colors were rather dim, with heavy usage of dark orange/red.

*There was shooting. I think that shooting device had big caliber, like Samus' in Metroid games. It shot laser beams or some kind of waves. Humans definitely shot at androids, but I don't remember if androids ever shot back.

*I think androids were empty inside. Main characters might have discovered that when they shot android for the first time and investigated the body.

*I think that close to end there was a scene with human(s?) floating in some reddish substance. That might have been a dream, some kind of out-of-body experience or them dying.

So, I remember rather visuals than plot, making it much harder for me to find. I did went through some "100 of best animes" lists and Wikipedia list on robot characters, but couldn't find it. So far I am only sure that it wasn't something from Robot Carnival.
Does anyone remember that movie and can name it?

A: Survey says! Gandahar  :-P

The peaceful people of Gandahar are suddenly attacked by an army of automatons known as the Men of Metal, who march through the villages and kidnap their victims by turning them to stone. The resulting statues are collected and then transferred to their base. At the capital city of Jasper, the Council of Women orders Sylvain to investigate. On his journey, he encounters the Deformed, a race of mutant beings who were accidentally created via genetic experimentation by Gandahar's scientists. Despite their resentment, they are also threatened by the Men of Metal and offer to help Sylvain.

Glad I could help (yeah, what WERE your parents thinking! :-P)


text:
Q: Retrieving image from database - image not displayed Here is the code I am using to try and retrieve an image from a database:
<?php
if($id)
{
    //please change the server name username and password according to your mysql server setting
    $mysql_server="localhost";
    $mysql_username="myuser";
    $mysql_password="mypass";
    $mysql_database="mydb";
    //connect to database using above settings
    @MYSQL_CONNECT("localhost",$mysql_username,$mysql_password);
    @mysql_select_db("mydb");
    //select the picture using the id
    $query = "select bin_data,filetype from todo where id=$id";
    //execute the query
    $result = @MYSQL_QUERY($query);
    //get the picture data which will be binary
    $data = @MYSQL_RESULT($result,0,"bin_data");
    //get the picture type. It will change according to file extension it may be either gif or jpg
    $type = @MYSQL_RESULT($result,0,"filetype");
    //send the header of the picture we are going to send
    Header( "Content-type: $type");
    //send the binary data
    echo $data;
};

?>

Instead of displaying the requested image, it displays this icon: (not sure what you call it)... http://i.imgur.com/bo6Jg.png
Here are all the columns in my table: http://i.imgur.com/PuWvl.png
I'm pretty positive I'm doing everything right...not sure what's going on. Help anyone? Thanks in advance!

A: IMO only constants should be uppercase (tho I gladly did not know they could be upper),
Anyway Try this:
<?php
$file_not_found = '../not_found_image.jpg';
//Get the id param from GET else null
$id = (isset($_GET['id']) && is_numeric($_GET['id']))?$_GET['id']:null;

if($id != null) {
    $mysql_server="localhost";
    $mysql_username="myuser";
    $mysql_password="mypass";
    $mysql_database="mydb";
    //Connect to database using above settings
    mysql_connect($mysql_server,$mysql_username,$mysql_password) or die(mysql_error());
    mysql_select_db($mysql_database) or die(mysql_error());
    //Select the picture using the id
    $query = "SELECT `bin_data`, `filetype` FROM todo WHERE id=".(int)mysql_real_escape_string($id)." LIMIT 1";
    //Execute the query
    $result = mysql_query($query);

    //Found
    if(mysql_num_rows($result)==1){
        //Get the picture data which will be binary
        $data = mysql_result($result,0,"bin_data");
        //Get the picture type. It will change according to file extension it may be either gif or jpg
        $type = mysql_result($result,0,"filetype");
        //Send the header of the picture we are going to send + cache
        header('Cache-Control: private, max-age='.(60*60*24*365));
        header('Expires: '.gmdate(DATE_RFC1123,time()+60*60*24*365));
        header("Pragma: private");

        header('Content-Type: '.$type);
        header('Content-Length: ' . strlen($data));
        //Send the binary data
        echo $data;

    }else{
    //Not found
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Type: image/jpeg');
    header('Content-Length: ' . filesize($file_not_found));
    readfile($file_not_found);
    }

}else{
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Type: image/jpeg');
    header('Content-Length: ' . filesize($file_not_found));
    readfile($file_not_found);
}
?>

A: Try this..
 header("Content-type: image/gif");
 $expires = 60*60*24*14;
 header("Pragma: public");
 header("Cache-Control: maxage=".$expires);
 header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');
 error_reporting(0);
 require_once "class/dbconn.php";
 $id=$_GET['id'];

 $sql="select thumbimage from image where img_id=$id";
 $rs=mysql_query($sql) or die (mysql_error());
 $row =mysql_fetch_array($rs,MYSQL_BOTH);
 $data = $row[0];
 print $data;

redpajama_set_name: RedPajamaStackExchange


text:
Q: liferay 5.2 redirection to mobile page I work with liferay 5.2
I developed a Java EE application
I am currently working in mobile version
I find a problem since my application is not responsive
So my solution is to develop several mobile modules to consume with the mobile device
My problem is with the login page of liferay
I want to find a way to make the redirection
either redirect to mobile page or to the web page
the redirection to the web page is done with this way in the portal-ext.properties file
default.landing.page.path=/group/inbox

how can I add make the redirection to mobile page
updated :
using liferay 6  I can use this code and add test to make the redirection
public class LoginPostAction extends Action

{

    public void run(HttpServletRequest request, HttpServletResponse response)
            throws ActionException {

                ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
                        WebKeys.THEME_DISPLAY);
                Device device =themeDisplay.getDevice() ;
                Dimensions dimensions = device.getScreenSize();
                float height = dimensions.getHeight();
                float width = dimensions.getWidth();

                String brand = device.getCapability("brand_name") ;

            }

}

this is the jar of liferay :
liferay-portal-service-6.1.1.jar
but i didn't find the way using liferay 5.2


text:
Q: Google desktop logo looks bad The Google Desktop icon in the system tray in Unity looks ugly:

Any way around this?

A: I had this issue too, but fpoehler ( http://ubuntuforums.org/member.php?u=1174921 ) solved it here: http://ubuntuforums.org/showthread.php?t=1466473&page=4 .
"
The themes that work should be the ones which have the same panel background as normal application windows. That's why the problem is not apparent there. However, newer themes often use a different color or a background image for the panel.

The fix is to apply the panel's properties (background color or background image) to GtkPlug widget class, which is not considered in most stock themes.

Steps:
1) Find out your panel's background color or the path to its background image (in case it has one).
For the color the hexadecimal value is needed (e.g. "#A1B2C3).
The image in most cases resides in /usr/share/themes/<Your_Theme's_Name>/gtk-2.0/ or a subfolder of that.

For Radiance theme it is
/usr/share/themes/Radiance/gtk-2.0/apps/img/panel.png
2) (In case there is a background image) copy the background image to your home folder (or a subfolder of your home folder).

3) Open (or create) the file named ".gtkrc-2.0" in your home folder.
4) Copy the following into the file:
style "GoogleDesktopIconFix" {
    # In case your panel has a background image, add this line
    bg_pixmap[NORMAL] = "subfolder/panel.png"     # replace "panel.png" with the actual file name or (relative) path

    #In case your panel has no background image, add this line
    bg[NORMAL] = "#000000"              # replace "#000000" with your color value
}
class "*oPlug"    style "GoogleDesktopIconFix"

5) Open a terminal and type
    Code:
pkill gnome-panel
"

Results:
 (color)                                                  (Background)
ps.: if it doesn't work:
1) Change  class "*oPlug" for class "GtkPlug"
2) Put the "relative" path to the background (example: if I put the background image at "~/gdesk/panel.png" I had to put the path "gdesk/panel.png")


text:
Q: Infix to postfix using two stacks I need help with my evaluate method. The output I am getting is totally wrong. MY CODE DOES THIS: Input: ( 5 + 3 ) * 3 Output: Operand Stack: [ (, 5, + 3 + , ), * 4 *  ] Operator Stack: [ ] THE OUTPUT SHOULD BE: Operand Stack: [ 5 3 + 4 * ] Operator Stack: [ ]  *Note: Spaces are supposed to be between the numbers
Here is my evaluating method:

/**
  * Evaluates the specified postfix expression. If an operand is encountered,
  * it is pushed onto the operand stack. If an operator is encountered, two
  * operands are popped, the expression is evaluated, and the result is
  * pushed onto the operand stack.
  *
  * @param expr string representation of a postfix expression
  * @return value of the given expression
  */
 public String evaluate(String expr) {

  // A variable to hold the resulting postfix expression.
  String result;
  // A string variable to hold the individual elements of user's input string.
  String token;
  // A parser to read the individual tokens of user input, tokens must be separated by whitespace.
  Scanner parser = new Scanner(expr);

  while (parser.hasNext()) {
   // Evaluating the expression one token at a time.
   token = parser.next();

   // 1) An operand is either the first or second operand for an operator.
   // If the operator stack is empty or if a left parenthesis is on top of the stack,
   // the operand is the first operand for an operator. Push the operand onto the operand stack.
   if (operatorStack.isEmpty() || operatorStack.peek().equals("(")) {
    // Operand 1
    operand1 = token;

    // Pushing operand1 onto the operand stack
    operandStack.push(operand1);
   }

   // 1) Otherwise, the operand is the second operand for an operator. The first operand should be on top of
   // the operand stack, and the operator should be on top of the operator stack. Pop the
   // first operand and the operator from the stacks, and form the postfix expression
   // representing applying the operator to its two operands. This expression is an operand
   // to which another operator may be applied, so push it onto the operand stack.

   else {
    // Operand 2
    String operand2 = token;

    // Popping current operator and operand1
     operand1 = operandStack.pop();
     currentOperator = operatorStack.pop();

    // Forming the resulting expression
     resultingExpression = (operand1 + " " + operand2 + " " + currentOperator + " ");

    // Pushing the resulting expression onto the operandStack
    operandStack.push(resultingExpression);

   }

   // 2) A right parenthesis marks the end of an infix operand expression. The matching left
   // parenthesis should be on top of the operator stack, and the postfix operand expression
   // corresponding to the infix operand expression should be on top of the operand stack.
   // Pop the left parenthesis off the operator stack. If the stack is now empty or if the token
   // on top of the stack is another left parenthesis, the operand on top of the operand stack
   // is the first operand for an operator, assuming the end of the whole infix expression has
   // not been reached. In this case, do nothing further.Otherwise, the postfix expression
   // on top of the operand stack is the second operand for an operator.
   // The first operand should be immediately below it, and the operator should be on
   // top of the operator stack.Pop both operands and the operator from the stacks, and form
   // the postfix expression representing applying the operator to its operands. As in 1
   // above, push this expression onto the operand stack.

   if (isRightParen(token)) {
    // Popping left parenthesis
    operatorStack.pop();

    if (operatorStack.isEmpty() || operatorStack.peek().equals("(")) {
     // First operand for an operator
     operand1 = operandStack.peek();
    }

    else {

     // Second operand for an operator
     operand2 = operandStack.peek();

     // Pop both operands
     operandStack.pop();
     operandStack.pop();

     // Pop operator
     currentOperator = operatorStack.pop();

     // Forming the resulting expression
     resultingExpression = (operand1 + " " + operand2 + " " + currentOperator + " ");

     // Pushing the resulting expression onto the operandStack
     operandStack.push(resultingExpression);
     }

    }

   // 3) To process an operator or a left parenthesis, simply push it onto the operator stack.

    // If token is an operator push it on the operator stack.
     if (isOperator(token)) {
      operatorStack.push(token);
       }
    // If token is a left parenthesis push it on to the operator stack.
     else if (isLeftParen(token)) {
      operatorStack.push(token);
      }

   }

  // Returning the completed postfix result
  result = ("Operand Stack: " + operandStack.toString() + " " + "Operator Stack: " + operatorStack.toString());
  return result;
 }

A: Taking a quick looksie at your code, I can give you the following suggestions without giving away the actual answer, because it would seem that this is some sort of class project?  Take a look at EWD's Shunting-yard Algorithm, and at Reverse Polish Notation (RPN). Both of these Wikipedia articles contain the pseudocode that describes how to implement the algorithm.
I hope this helps, and best of luck!


text:
Q: Facebook oauth login not returning email I am using this plugin for oauth login, here is my FB response while doing aouth login:
{"state":"","access_token":"XYZ","expires_in":5110943,"client_id":"CLIENT ID","network":"facebook","display":"popup","redirect_uri":"http://localhost/XYZ123/www/callback.html","scope":"email,basic","expires":1439628780.389}}

The problem is i am not getting email of user. As per other SO solutions :
I have verified email so that should not be a matter. I am not getting FB message regrading verifying email.
Here is output of CLIENT ID/permissions
{
  "data": [
    {
      "permission": "email",
      "status": "granted"
    },
    {
      "permission": "public_profile",
      "status": "granted"
    }
  ]
}

A: You need to make an API call to get the users profile. Email is not included in the authResponse object.
var fb = hello('facebook');
fb.login({scope:'email'}).then(function(){
   return fb.api('me');
}).then(function(res){
   // do something with res.email
}, console.error.bind(console) );

A: email
Provides access to the person's primary email address via the email property on the user object.
Do not spam users. Your use of email must comply with both Facebook policies and with the CAN-SPAM Act.
Note, even if you request the email permission it is not guaranteed you will get an email address. For example, if someone signed up for Facebook with a phone number instead of an email address, the email field may be empty.
Review
Your app may use this permission without review from Facebook.


text:
Q: C# dot net web service for alerts I want to create a C# dot net web service that will be checking for alert messages from a certain table in sql and then it sends the alert message to a certain URL e.g. I have a certain URL that I will use to pass the data like: http://SMSAlerts/Message?msisdn=phoneno&text=message, so here I will just pass the phone number and the message to the URL.
The question is, how will I Design the web service such that it will keep on checking that table for new alerts every time all by its self so that it can send to that URL? The table for the alerts is populated by another application.
Please help me know I can do this.

A: The web service should not do the work. It should just update a list of urls somewhere (i.e. on a database table).
Then you should develop a daemon (i.e. a windows service or a console application) that does the work polling data and using registered urls.


text:
Q: Is it possible to auto-fill with zeroes when subtracting output of two calls to `summary` on factors? Suppose I want to compare two lists of equal size using the frequency of values in each list.
Consider the following script.
foo = c(24,24,24,3,10,2)
bar =  c(24,24,10,3,3,2)

summary(as.factor(foo))
summary(as.factor(bar))

summary(as.factor(foo)) -  summary(as.factor(bar))

As long as the set of discrete values in foo and bar are identical, this works reasonably well. Here is some output:
 2  3 10 24
 1  1  1  3

 2  3 10 24
 1  2  1  2

 2  3 10 24
 0 -1  0  1

However, if there is some value in bar which is not in foo, then, we get the undesirable default behavior of recycling the shorter vector and also a mismatch of counts. Consider the case where
bar =  c(24,24,11,3,10,2)

Then, our output looks like this, along with a warning message.
 2  3 10 24
 1  1  1  3

 2  3 10 11 24
 1  1  1  1  2

 2  3 10 11 24
 0  0  0  2 -1
Warning message:
In summary(as.factor(foo)) - summary(as.factor(bar)) :
  longer object length is not a multiple of shorter object length

The desired output is:
 2  3 10 11 24
 0  0  0  -1 1

In particular, note that a 0 has been filled for the missing 11 in foo, and that the value for 24 is 3 - 2 = 1 .
How can I achieve the desired output?

A: You can achieve this by using the same levels when turning foo and bar into factors.
> foo2 = factor(foo, levels=sort(union(foo, bar)))
> bar2 = factor(bar, levels=sort(union(foo, bar)))
> summary(foo2) - summary(bar2)
 2  3 10 11 24
 0  0  0 -1  1

A: i have no idea why you want to do this:
> summary(factor(foo, levels=union(foo,bar))) -  summary(factor(bar, levels=union(foo,bar)))
24  3 10  2 11
 1  0  0  0 -1


text:
Q: Prove that $|A|=|\mathbb R |$ Consider a set $A=\{f \in \mathbb N^\mathbb N : (\forall n)\; f(n)\mid f(n+1)\}$, where
$\mid$ stands for a relation of divisibility. Prove that $|A|=|\mathbb R |$
My attempts:
It was easy to show that $|A|\leqslant|\mathbb R |$ since $f \in \mathbb N^\mathbb N$, and $\mathbb N^\mathbb N = \mathbb R$.
Unfortunately I have no idea how to show that $|A|\geqslant|\mathbb R |$. Could you help me, please?

A: Assume that $|[0,1]|=|\mathbb{R}|$.
For each $x\in[0,1]$, let $x_n$ be the $n^\text{th}$ term of the binary expansion of $x$.
Define $f_x(n)$ recursively by $f_x(1)=2$ and $f_x(n+1)=2^{1+x_n}*f_x(n)$.
For each $x\in[0,1]$ and $n\in\mathbb{N}$, $f_x(n)|f_x(n+1)$ and each function $f_x$ is different.
Therefore, $|A|\geq|\mathbb{R}|$.
I say $\geq$ because you could create many variations on this idea.

A: Consider the map $F\colon A\longrightarrow\mathbb{N}^{\mathbb{N}}$ defined by $$F(f)(n)=\begin{cases}f(1)&\text{ if }n=1\\\frac{f(n)}{f(n-1)}&\text{ otherwise.}\end{cases}$$This map is a bijection. Therefore, $|A|=\bigl|\mathbb{N}^{\mathbb{N}}\bigr|=|\mathbb{R}|$.


text:
Q: iOS idleTimerDisabled behavior My iPhone application has two states: UI and Game.
Game is played using device tilting only so I switched auto-sleep off on game start:
[[UIApplication sharedApplication].idleTimerDisabled = TRUE;

But as soon as I return to UI, I want auto-sleep to be active again. So on game finish I restore it:
[[UIApplication sharedApplication].idleTimerDisabled = FALSE;

After a long game playing, it resulted in immediate darkening of the first UI screen that I go after the game.
So it seems that when idle timer was disabled it was still calculating time. And it had fired immediately after "enabling". How can I fix this problem?

A: I don't know if the idleTimer can be reset programmatically, but an option is to require the user to touch the screen before it goes back.
Another option is set your own timeout once you are back and wait for it to complete before you set idleTimerDisabled = NO. Remember to clear this timeout if you start the game again.

A: This answer may be usefull.
I also had problems when using Music/Audio players, which seemed to reactivate the timer.
ps: in ObjectiveC you should use YES/NO instead of FALSE/TRUE


text:
Q: mathematics as a science of finding patterns Many months ago I read a (quite nice) article saying that mathematics is a systematic study on finding patterns. It went on to enumerate the different fields of mathematics (algebra, geometry, calculus, statistics) and what those corresponding patterns are.
Now I am looking for that article and I couldn't find it. Anyone who have read (or even have their own versions), please come and give a suggestion.


text:
Q: Maintaining Multiple state values in a Custom React Hook I'm looking for a clean way to store several simple values in a custom react hook. It feels uncomfortable to have to return multple setters and getters. I could pass in one value for each, that is const modalState = useState(false) then reference modalState[0] and [1] but that feels odd to.  What I don't like about my function below is it returns 10 values. That seems like a lot.
function useNotesModal() {
  const [showModal, setShowModal] = useState(false);
  const [modalNoteId, setModalNoteId] = useState(0); // if 0, means create note in modal
  const [modalNoteTitle, setModalNoteTitle] = useState("");
  const [modalNoteDescription, setModalNoteDescription] = useState("");
  const [modalNoteTagIds, setModalNoteTagIds] = useState([]);

  return {
    showModal,
    setShowModal,
    modalNoteId,
    setModalNoteId,
    modalNoteTitle,
    setModalNoteTitle,
    modalNoteDescription,
    setModalNoteDescription,
    modalNoteTagIds,
    setModalNoteTagIds,
  };
}
export default useNotesModal;

A: You can batch the returned values, for example - as values, and actions:
function useNotesModal() {
  const [showModal, setShowModal] = useState(false);
  const [modalNoteId, setModalNoteId] = useState(0); // if 0, means create note in modal
  const [modalNoteTitle, setModalNoteTitle] = useState("");
  const [modalNoteDescription, setModalNoteDescription] = useState("");
  const [modalNoteTagIds, setModalNoteTagIds] = useState([]);

  return {
    values: {
      showModal,
      modalNoteId,
      modalNoteTitle,
      modalNoteDescription,
      modalNoteTagIds
    },
    actions: {
      setShowModal,
      setModalNoteId,
      setModalNoteTitle,
      setModalNoteDescription,
      setModalNoteTagIds,
    }
  };
}

Another option is to batch them automatically by value and set:

const { useState, useEffect } = React;

function useNotesModal() {
  const states = {
    showModal: useState(false),
    modalNoteId: useState(0),
    modalNoteTitle: useState(""),
    modalNoteDescription: useState(""),
    modalNoteTagIds: useState([])
  }

  return Object.fromEntries(
    Object.entries(states)
      .map(([k, [value, set]]) => [k, { value, set }])
  );
}

const Demo = () => {
  const notesState = useNotesModal();

  useEffect(() => {
    setTimeout(() => {
      notesState.modalNoteId.set(101);
    }, 2000);
  }, []);

  console.log(notesState);

  return
{notesState.modalNoteId.value}
;
}

ReactDOM.render(
  <Demo />,
  root
);

A: One possible approach would be to just use a single object to hold the state, and return a setter for that object.
Something like:
function useNotesModal() {
  const [state, setState] = useState({
    showModal: false,
    modalNoteId: 0,
    modalNoteTitle: "",
    modalNoteDescription: "",
    modalNoteTagIds: [],
  });

  function setFieldState(fieldName, value){
    setState({...state, [fieldName]: value});
  }

  return [state, setFieldState];
}

// Then, to use:

const [modalState, setModalState] = useNotesModal();

const showModal = modalState['showModal'];

setModalState("showModal", true);

The key in this case is to ensure you return a new object every time the internal state is updated.


text:
Q: PHPStan Symfony: no value type specified in iterable type array I wanted to test my little symfony project today with PHPStan, and I got this error when I want to test User Entity (Entity/User.php), which I don't have clue what does it mean:
  89     Method App\Entity\User::setRoles() has parameter $roles with no value type specified in iterable type array.
          See: https://phpstan.org/blog/solving-phpstan-no-value-type-specified-in-iterable-type

UserEntity was made with maker bundle, and the code inside is automatically made
<?php

namespace App\Entity;

#[ORM\Entity(repositoryClass: UserRepository::class)]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id;

    #[ORM\Column(type: 'string', length: 180, unique: true)]
    private string $username;

    /**
     * @var array <String>
     */
    #[ORM\Column(type: 'json')]
    private array $roles = [];

    #[ORM\Column(type: 'string')]
    private string $password;

    /**
     * @var Collection <int, Cart>
     */
    #[ORM\OneToMany(mappedBy: 'customer', targetEntity: Cart::class)]
    private Collection $carts;

    public function __construct()
    {
        $this->carts = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @deprecated since Symfony 5.3, use getUserIdentifier instead
     */
    public function getUsername(): string
    {
        return $this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;

        return $this;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUserIdentifier(): string
    {
        return $this->username;
    }

    /**
     * @return string[]
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    /**
     * @param array $roles
     * @return $this
     */
    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see PasswordAuthenticatedUserInterface
     */
    public function getPassword(): string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Returning a salt is only needed, if you are not using a modern
     * hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
     *
     * @see UserInterface
     */
    public function getSalt(): ?string
    {
        return null;
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials(): void
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    /**
     * @return Collection<int, Cart>
     */
    public function getCarts(): Collection
    {
        return $this->carts;
    }

    public function addCart(Cart $cart): self
    {
        if (!$this->carts->contains($cart)) {
            $this->carts[] = $cart;
            $cart->setCustomer($this);
        }

        return $this;
    }

    public function removeCart(Cart $cart): self
    {
        if ($this->carts->removeElement($cart)) {
            // set the owning side to null (unless already changed)
            if ($cart->getCustomer() === $this) {
                $cart->setCustomer(null);
            }
        }

        return $this;
    }
}

I have included both doctrine and symfony packages for phpstan!

A: Solved. Just added thie above setRoles()
    /**
     * @param array<string> $roles
     * @return $this
     */
    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

More information and solution can be founded here: https://phpstan.org/blog/solving-phpstan-no-value-type-specified-in-iterable-type


text:
Q: Vertical scroll in a ListBox Hi I have a list box as below inside a grid. I cant make the items inside the ListBox scrollable when the number of items exceed the height of the ListBox.
I added VerticalScrollBarVisibility="Visible" to the ListBox tag but it doesn't work at all.
Read somewhere about scrolling doesnt work in a stack panel.
Anyone can help me with this? Thanks in advance!
<ListBox>
    <TreeView>
       <TreeView.Resources>
           <HierarchicalDataTemplate>
               <StackPanel>
                 <TextBlock />
                 <TextBox></TextBox>
               </StackPanel>
           </HierarchicalDataTemplate>
       </TreeView.Resources>
    </TreeView>
</ListBox>

A: You should be using the ScrollView property:
<ListBox ScrollViewer.VerticalScrollBarVisibility="Auto"
         ScrollViewer.CanContentScroll="True">
    <TreeView>
        <TreeView.Resources>
            <HierarchicalDataTemplate>
                <StackPanel>
                    <TextBlock/>
                    <TextBox></TextBox>
                </StackPanel>
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>
</ListBox>

It Should work...


text:
Q: C compiling error so i'm learning at the moment programming in C language. We are working with ubuntu, so i installed one at home, but i'm having a lot of problems while compiling.
for compiling i'm using gcc file_name.c
this is my code:
#include <stdio.h>
main (){
 printf ("hello world\n");
}

but the thing is, it gives me this type of error:
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12

/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 20 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 21 has invalid symbol index 22
/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_line): relocation 0 has invalid symbol index 2
/usr/lib/gcc/i686-linux-gnu/4.8/../../../i386-linux-gnu/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: error: ld returned 1 exit status

What did i do wrong ? ty in advance for your time

A: Please try with:
#include <stdio.h>
int main()
{
    printf ("hello world\n");
    return 0;
}

And fot the compilation use:
gcc file.c -o compiledFile

A: Try this instead:
#include  <stdio.h>

int main(void)
{
   printf("Hello, world!\n");
   return 0;
}

A: It is true that main should return an int, but there seems to be a problem with your compiler installation. While you do not get it fixed, since you are doing simple things, you can also use an online compiler such as http://www.tutorialspoint.com/compile_c_online.php
It is very easy to use.

A: So guys... i searched a little bit more and i found that i needed to install this:
sudo apt-get install mingw32

after i did this, the gcc file.c command worked and it created a a.out file
after that it worked just fine.
Ty all for you time and sugestions!

A: You should type void or int with a return value at the end of the programm:
void main() {
}

or
int main(void){
    return 0;
}

and use Visual Studio. It is better :)


text:
Q: Why is signed and unsigned addition converted differently for 16 and 32 bit integers? It seems the GCC and Clang interpret addition between a signed and unsigned integers differently, depending on their size. Why is this, and is the conversion consistent on all compilers and platforms?
Take this example:
#include <cstdint>
#include <iostream>

int main()
{

    std::cout <<"16 bit uint 2 - int 3 = "<<uint16_t(2)+int16_t(-3)<<std::endl;
    std::cout <<"32 bit uint 2 - int 3 = "<<uint32_t(2)+int32_t(-3)<<std::endl;
    return 0;
}

Result:
$ ./out.exe
16 bit uint 2 - int 3 = -1
32 bit uint 2 - int 3 = 4294967295

In both cases we got -1, but one was interpreted as an unsigned integer and underflowed.  I would have expected both to be converted in the same way.
So again, why do the compilers convert these so differently, and is this guaranteed to be consistent? I tested this with g++ 11.1.0, clang 12.0. and g++ 11.2.0 on Arch Linux and Debian, getting the same result.

A:
Why is this,

C (and hence C++) has a rule that effectively says when a type smaller than int is used in an expression it is first promoted to int (the actual rule is a little more complex than that to allow for multiple distinct types of the same size).
Section 6.3.1.1 of the Rationale for International Standard Programming Languages C claims that in early C compilers there were two versions of the promotion rule. "unsigned preserving" and "value preserving" and talks about why they chose the "value preserving" option. To summarise they believed it would produce correct results in a greater proportion of situations.
It does not however explain why the concept of promotion exists in the first place. I would speculate that it existed because on many processors, including the PDP-11 for which C was originally designed, arithmetic operations only operated on words, not on units smaller than words. So it was simpler and more efficient to convert everything smaller than a word to a word at the start of an expression.
On most platforms today int is 32 bits. So both uint16_t and int16_t are promoted to int. The artithmetic proceeds to produce a result of type int with a value of -1.
OTOH uint32_t and int32_t are not smaller than int, so they retain their original size and signedness through the promotion step. The rules for when the operands to an arithmetic operator are of different types come into play and since the operands are the same size the signed operand is converted to unsigned.
The rationale does not seem to talk about this rule, which suggests it goes back to pre-standard C.

and is the conversion consistent on all compilers and platforms?

On an Ansi C or ISO C++ platform it depends on the size of int. With 16 bit int both examples would give large positive values. With 64-bit int both examples would give -1.
On pre-standard implementations it's possible that both expressions might return large positive numbers.

A: When you do uint16_t(2)+int16_t(-3), both operands are types that are smaller than int.  Because of this, each operand is promoted to an int and signed + signed results in a signed integer and you get the result of -1 stored in that signed integer.
When you do uint32_t(2)+int32_t(-3), since both operands are the size of an int or larger, no promotion happens and now you are in a case where you have unsigned + signed which results in a conversion of the signed integer into an unsigned integer, and the unsigned value of -1 wraps to being the largest value representable.

A: A 16-bit unsigned int can be promoted to a 32-bit int without any lost values due to range differences, so that's what happens. Not so for the 32-bit integers.

A:
So again, why do the compilers convert these so differently,

Standard quotes for [language-lawyer]:

[expr.arith.conv]
Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way.
The purpose is to yield a common type, which is also the type of the result.
This pattern is called the usual arithmetic conversions, which are defined as follows:

*

*...

*Otherwise, the integral promotions ([conv.prom]) shall be performed on both operands.
Then the following rules shall be applied to the promoted operands:

*

*If both operands have the same type, no further conversion is needed.

*Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank shall be converted to the type of the operand with greater rank.

*Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.

*Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type shall be converted to the type of the operand with signed integer type.

*Otherwise, both operands shall be converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

[conv.prom]
A prvalue of an integer type other than bool, char8_t, char16_t, char32_t, or wchar_t whose integer conversion rank ([conv.rank]) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.
These conversions are called integral promotions.

std::uint16_t type may have a lower conversion rank than int in which case it will be promoted when used as an operand. int may be able to represent all values of std::uint16_t in which case the promotion will be to int. The common type of two int is int.
std::uint32_t type  may have the same or a higher conversion rank than int in which case it won't be promoted. The common type of an unsigned type and a signed of same rank is an unsigned type.

For an explanation why this conversion behaviour was chosen, see chapter "6.3.1.1 Booleans, characters, and integers" of "
Rationale for
International Standard—
Programming Languages—
C". I won't quote the entire chapter here.

is this guaranteed to be consistent?

The consistency depends on relative sizes of the integer types which are implementation defined.


text:
Q: Android and bluetooth headset volume My problem is - how to set up bluetooth incall audio volume.
Since there some apps for this, no one of them works.
Anyway - no app - create one for yourself. I'm very begginer in android development, so i've tried use audioManager.setStreamVolume(), but without any luck - only internal audio has changed after this.
Even playing with startBluetoothSCO() wasn't the answer.
After looking in logcat, how os responds to pressing volume keys, i found out, that after startBluetoothSCO() volume keys in my phone sends AT commands instead of mangling streams (AT+VGM=0...15).
So my code should look something like this:
AudioManager audioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
audioManager.startBluetoothSco();
// send AT commands
audioManager.stopBluetoothSco();

Crawling thru web provide me answer that there's no way to directly access modem (and propably other comm ports) from Android API.
So, maybe someone has any goddamn idea how to prevent resetting BT volume on each connect/disconnect to headset? Using code that i could use by myself, or using some 3-rd party app that is available somewhere.
OS: GB 2.3.4, SGS
Thanks for any ideas.

A: You can send AT commands via RFCOMM connection. But you must do this before the Android has created Headset/Handsfree Profile connection (Called Phone audio in bluetooth settings menu), or at least disconnect the HSP/HFP then connect via RFCOMM on either of the two (Both HSP and HFP should work with unsolicited +VGS commands), set the volume, and then reconnect.


text:
Q: Headers guards still yield redefinition errors I'm writing some templated data structures for future use and have a class Node that appears in both my singly linked list and graph implementations. Each of these headers have header guards, but I'm still getting an error of redefinition:
In file included from driver.cc:4:
./Graph.h:7:7: error: redefinition of 'Node'
class Node {
      ^
./SinglyLinkedList.h:5:7: note: previous definition is here
class Node {
      ^
1 error generated.

SinglyLinkedList.h

#ifndef SINGLY_LINKEDLIST_H
#define SINGLY_LINKEDLIST_H

template <class T>
class Node {
    public:
        Node<T>() {}
        Node<T>(T init) { data = init; }

        void setData(T newData) { data = newData; }
        void setNext(Node<T> *nextNode) { next = nextNode; }

        const T getData() { return data; }
        const Node<T> *getNext() { return next; }
    private:
        T data;
        Node<T> *next;
};

template <class T>
class SLL {
    public:
        SLL<T>() { head = NULL; }
    private:
        Node<T> *head;
};

#endif

Graph.h

#ifndef GRAPH_H
#define GRAPH_H

#include <vector>

template <class T>
class Node {
    public:
        Node<T>() {};
        Node<T>(T init) { data = init; }
    private:
        T data;
};

template <class T>
class Edge {
    public:
        Edge<T>(Node<T> a, Node<T> b);
    private:
        Node<T> to;
        Node<T> from;
};

template <class T>
class Graph {
    public:
        Graph<T>(bool direction) { directed = direction; }
        const bool getDirection() { return directed; }
    private:
        std::vector<Edge<T> > adjList;
        bool directed;
};

#endif

driver.cc

#include <iostream>
#include <string>
#include "SinglyLinkedList.h"
#include "Graph.h"

int main()
{
    Graph<int> Hello(false);

    return 0;
}

I know the classes are not complete and I know there's no need to reinvent the wheel because everything I'll ever need exists in std, but can someone explain why there's a redefinition error of the class Node?
My assumption is that the compiler doesn't see a definition of SINGLY_LINKEDLIST_H, so it creates a definition for everything in its class; then it again doesn't see GRAPH_H and attempts to create a definition for everything in the Graph class which yields an error.
If this is so, how should I proceed? Create a separate Node class? Make a Node header which has things that might be needed for both data structures?
Just looking for tips.
Thanks,
erip

A: You need to either:

*

*Factor Node class into separate header file.

*Or Rename the Node class to differentiate.

*Put Node classes into separate namespaces.

As demonstrated in your question, both header files contain a definition of a Node class, and you have confused the compiler.


text:
Q: Vim - permit quitting with new modified files The default behavior of Vim seems to be that :q will raise an error if the buffer is modified, and :q! will quit the buffer even if modified.  I would like to change the behavior of :q so it will only raise an error if the buffer is modified AND is associated with an existing file.  In other words, if a new buffer was created (e.g. by :new or by :e nonexistentfile.txt) and was modified without being written, I want :q to discard the changes.

A: I think what you want is to create scratch buffers.
command! Scratch new | setlocal buftype=nofile bufhidden=hide noswapfile

Just issue :Scatch to create a scratch buffer


text:
Q: same height of multiple li in javascript i am new in javascript. its working fine if we refresh the page but its not working when we resize the window.
$(window).load(function(){
    equl_height();
});

$(window).resize(function(){
    equl_height();
});

function equl_height () {
    var highestBox = 0;
    $('ul li').each(function(){
        if($(this).height() > highestBox){
            highestBox = $(this).height();
        }
    });
    $('ul li').height(highestBox);
}

A: window.addEventListener("resize", equl_heigh);
cheers!

A: Problem is in how you measure height of an li. use scrollHeight instead of height(). Check this fiddle.
Update your equl_height method with
function equl_height () {
    console.log( "resizing" );
    var highestBox = 0;
    $('ul li').each(function(){
        //var height = $(this).outerHeight();
        var height = $(this)[0].scrollHeight;
        if(height > highestBox){
            highestBox = height;
        }
    });
    $('ul li').outerHeight(highestBox);
}

Also, since resize event can be fired at a higher rate so try this throttling trick as well.


text:
Q: Removing matlab version checking code I recently downloaded some code from matlab site to run it with octave. When I try to run a test.m file created by me that calls several functions from the downloaded source code files I receive:

octave:2> test
error: `verLessThan' undefined near line 101 column 8
error: called from:
error:   /media/34GB/escola/efficientLBP/assignUserInputs.m at line 101, column 5
error:   /media/34GB/escola/efficientLBP/efficientLBP.m at line 113, column 1
error:   /media/34GB/escola/efficientLBP/test.m at line 5, column 7

checking the source file I found this code
    if isempty(funcParamsNames)
       isNoFuncParamsNames=true;
    else
       if verLessThan('matlab', '7.14') % again, old version do not support 'stable'.
          funcParamsNames=unique(funcParamsNames); % This can lead to bugs :(
       else
          funcParamsNames=unique(funcParamsNames , 'stable');
       end%
       isNoFuncParamsNames=false;
    end

So I was wondering  if there is a way to make octave to recognizance this function.
Thanks for your time.

A: Octave seems to know an equivalent function unique, however, I see no option like Matlabs 'stable'.
Try unique and see what it does I guess?
if isempty(funcParamsNames)
   isNoFuncParamsNames=true;
else
   funcParamsNames=unique(funcParamsNames);
   isNoFuncParamsNames=false;
end

A: you can do unique with 'stable' yourself:
x = rand(1,10);x(5) = x(1);
% if you have 'stable'
y1 = unique(x,'stable');
% if you don't have 'stable'
[y2,ia] = unique(x);
[ia,idxs] = sort(ia);
y2 = y2(idxs);
% compare
isequal(y1,y2)


text:
Q: How to compete on a scarce spec'd project to avoid team death-march I'm time+cost estimating a semi-complex software solution, that hasn't got specific requirements in about 75% of features. I would still like to make as good estimate as possible, by getting additional data from the client. There will still be parts that may end up not being able to develop, since there's too many dependencies with other products/technologies and lack of definition. I also have a very tight schedule to produce this estimate.
There will also be other contenders on this project. Client expects a price+duration (and probably also features) and I know everyone will be off. I know that's impossible, but tell that to marketing people. Another problem is that I'm talking to middle-man and not directly to the client. I can get confidence with middle-man only, but not with the deciding client. Which is a different problem altogether.
What disclaimer/info can I put in my price plan/contract not to kill team with this project, so when project starts slipping (in terms of cost/time/features) we will be covered with some sort of payment. I would of course like to be paid by sprints or releases with relation to time, but I doubt client could be convinced in this. I'm sure we can finish this product before deadline and also create a great product, but how can I convice client to believe me?
Question
What can I do to get this project and avoid death march situation at the same time?
Any suggestion welcome!
EDIT: Outcome
In the end we (me and my co-worker) convinced the client we need at least a week to evaluate the product. So we did. We also pushed (and got) a slot for a few hours long meeting with the client to clarify any outstanding requirements' questions. So we did. Meeting was done after we made the first estimate draft, so we were sure we have all the questions to point out specifics that were either completely misunderstood or too vague to estimate. I hope we get the project, because it would mean 8 months of full time work for us, plus a reasonable pay. We'll know in about a week and a half.
Of course I also pointed out that the way we'll be delivering this product will get them exactly where they want to be with a product that will actually be what they wanted. And also that we only commit to price and time, but not functionality, because it is and will be subject to change. I think we made a good enough impression.

A: EDIT:
Addressing the middle-men situation.  I think the best course of action would be to submit a list of risks along with your bid as a courtesy to the customer.  Kind of like giving them a heads-up on what their project limitations are.  This will cost you some work up front but I think it could help you win the project.

you have two options
make a best-guess and double or triple your estimate (your competition is probably doing the same thing.)
explain to the customer that you can't bid work like this, and tell him that everyone else that gives him a fixed estimate is probably not being completely truthful.
At the end of the day, if you can't make money on the work, the there is not point in trying for it.
Personally, I prefer the latter, up-front and honest communication with your customers will take you farther than any bid tricks ever will.

A: A few things I'd say you should think about:
Assumptions:  There's no one disclaimer you can add but you need to fill the gaps in the requirements with sensible assumptions and document them.  Nothing major or scary, just a section in your spec/bid with a list of bullet points saying what you assumed to be true which was missing (e.g. users details will be pulled using LDAP and no admin screens will be written to cover user admin).
This gives you clarity in estimating as you now have a full scope to work from, but it also means that if the client comes back with things which are wildly different you have a fair basis to start talking about raising change requests and varying the cost.  Alternatively they may come back during the negotiations saying this assumption or that one isn't true and you have more information.
Out of Scope:  A specific case of assumptions - list things which you aren't including (e.g.  No integration will exist with system X).  Again this allows you to have a full scope and a reasonable case for potentially varying cost at a later stage.
Assumptions and out of scope are particularly applicable when things are mentioned in passing but not really followed up, or for things which they say could wait for a second phase.  These are often the things the client will believe are being done as part of the main project but the project team don't.
Hopefully the thoroughness and insight from the assumptions and scope you define will help inspire confidence with the ultimate client too.
Contingency:  A tricky one but you should add contingency in two ways:
(1) for specific risks.  For things which might mean something takes longer than you've estimated then put in an amount to cover that weighted by the chance of it happening.  Add all these up and that's your risk contingency.
(2) Shit happens contingency - unpredictable shit happens on IT projects.  Add between 10% and 20% to cover this.
Whether you hide contingency from your commercial people and the client or not depends on your relationship but if it gets removed they need to understand what that means (essentially you WILL over run).
Understand the relationship between effort and cost:  As a technologist your role is to provide an estimate of the effort based on the information you have.  You need to then communicate that with assumptions, level of contingency and so on to your commercial team who can convert it into a monetary value.  The thing to be clear with them on is that if they want to drop the cost that doesn't change the effort.
There are loads of good reasons for writing down the cost to the client (to build a relationship, because you'll end up with stuff you can reuse later and so on) but people need to understand that unless the scope changes the effort stays the same - the reduction comes out of the profit.

A: In this economic environment, there are a lot of companies competing for a little work. Someone is bound to give them a very sweet bid that will

*

*Not be able to deliver on,

*Kill their team with, or

*Both.

When they can't deliver at the agreed price, they will start to cut down on the quality in order to deliver something and get paid.
Your challenge is to present that fact to your prospect in a professional manner, and convince them that you will work very hard to deliver at a reasonable cost, but also to deliver exactly what they need.  The fact that you're going back for more detail, and the method you approach the project with (agile... but be sure and explain the business benefit to them) helps ensure that they will end up with what they really need.
Remember, they want to get the software delivered that they need at the lowest possible price.
Convince them that you will deliver exactly to their needs, and that your price is reasonable.

A: Welcome to the world of fixed priced development services :-)
Techniques for to win this project and avoid death march situation at the same time:

*

*Don't underbid a project.  Bid for what you think the project will take and add some percentage for things likely to go wrong.

*If you are missing 75% of the detail, odds are the project will be significantly different than you currently expect.  Document some reasonable detail assumptions within the outline of the defined work.  When the project actually starts and the details don't match the assumption, you have an opportunity to negotiate the costs for the changes.  At that time, you may also be in a better position to know how much you are over/under and attempt to compensate with this quote.

*Your goal in an SOW (statement of work) should be to define enough details so that it gives you an opportunity to renegotiate the cost of changes when you know more about the project. Write these as positives, as much as possible.  Note, it is unlikely that people that actually understand the project will read or understand the SOW...I base this on the point that you are given few details to quote.  This means it isn't a consultative sale and neither party is really focused on building the 'right' solution.

*If you can get a contract as T&M (time and materials) great.  I doubt you'll get it or unable to get it without some restrictions that essentially defeat the purpose of a T&M.  Your potential customers look at this as them accepting all of the risks around your abilities.

*Hopefully, you aren't the first at your company to do this.  Find out, historically, how projects have been and the typical result rates.  Many software development groups charge an hourly rate that is significantly higher than cost...but their quotes tend to be lower and not actual hours.  Customers often will argue more about the hours/days than the actual quote.  Enterprises tend to be used to paying high hourly rates.

*Figure out your department's expected margin (profit you need to gain from the job).  This may help you to understand how much of a 'death march' you may face when your project slips.

*In the SOW specify the level of detail that will be required in a specification before you begin work.  While Agile and other customer focused processes take an approach that oriented at finding the best solution, they aren't designed to keep costs under control in a fixed bid environment.  You will need to take a waterfall approach to requirements and then build in an agile fashion so that you can adjust along the way.  The specification, like the SOW, will give you an opportunity to bill for changes.  While the customer won't like this, it will put the burden and risks associated with requirements on them and not your team.

Note, to be successful with these negotiations, you needs a supportive management, sales and project management team.  If you don't have that, you are bound to always be on 'death marches.'  Even if you forgo quality, process, testing and other items, you'll find there's never enough time for a project.

A: i have a blog article which may have a few tips in it for you:
http://pm4web.blogspot.com/2009/06/surviving-under-resourced-project.html
one of the other posters here has a good point to. there will always be someone who will offer a lower price to get the work. and the developer will suffer for it later (i.e. having to do a lot of free work to satisfy the client).
some clients need to have this experience before it clicks that you cant do IT projects on the cheap without paying some kind of price.
LM

A: Go for realism. Avoid promising too much, then make a point of it.
A lot of customers out there have been burnt by unrealistic offerers who fail to deliver as promised.
Emphasize the need for a specifications sprint. Convey a focus on core functionality and commitment to deliver rather than a feature bonanza. Offer a primary development phase to deliver core functionality.
Communicate the power and safety of the agile approach. Credit the customer with the ability to see good sense.
In short: Strive to come across as realistic and serious (more so than your competitors). The most important thing for any serious customer in the end is not the price, but a confidence that the product will be delivered on time and budget.


text:
Q: Geopoint constructor can not be resolved in Android Studio when using intValue of 2 doubles In the following creation of a GeoPoint both

latitude.intValue()

and

longitude.intValue()

are underlined in red in Android Studio
 Double latitude = location.getLatitude()* 1E6;
 Double longitude = location.getLongitude() * 1E6;

 Barcode.GeoPoint point = new Barcode.GeoPoint(latitude.intValue(),longitude.intValue());

Can someone tell me what I´m doing wrong here?
PS: These are my Imports
import android.app.DialogFragment;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.location.Location;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.vision.barcode.Barcode.GeoPoint;
import java.util.ArrayList;
import java.util.List;

A: try like this:
 Barcode.GeoPoint point = new Barcode.GeoPoint(Integer.valueOf(latitude),Integer.valueOf(longitude);

or you can use like this:
public static GeoPoint coordinatesToGeoPoint(double[] coords) {
    if (coords.length > 2) {
        return null;
    }
    if (coords[0] == Double.NaN || coords[1] == Double.NaN) {
        return null;
    }
    final int latitude = (int) (coords[0] * 1E6);
    final int longitude = (int) (coords[1] * 1E6);
    return new GeoPoint(latitude, longitude);
}

and other simple way is:
GeoPoint coordinates are based in microdegrees (degrees * 1e6)
float lat = -23.4456f;
float lng = 45.44334f;
GeoPoint gp = new GeoPoint((int)(lat * 1E6), (int)(lng * 1E6));


text:
Q: Break a text file after every 15 minutes time interval based on time values and count average numeric value for "File Count" in Nodejs? I have a text file with around 2000 lines of data which reflect a 24 hour time period, and number of files opened at different times. I need to break a file at every 15 minutes interval and need to count and print average number of files opened at every  15 minute interval?
The file format looks like this :
[
 |Time: 01:22:52.106 |File Count: 40
|Time: 01:22:52.402 |File Count: 45
|Time: 01:23:45.960 |File Count: 30
|Time: 01:23:46.231 |File Count: 30
|Time: 01:27:03.289 |File Count: 31
|Time: 01:27:03.706 |File Count: 32
|Time: 01:27:04.215 |File Count: 33
|Time: 01:27:04.830 |File Count: 31
|Time: 01:27:05.514 |File Count: 32
|Time: 01:27:05.912 |File Count: 32
|Time: 01:27:06.216 |File Count: 32
|Time: 01:27:06.216 |File Count: 32
|Time: 01:27:06.471 |File Count: 32
|Time: 01:27:06.472 |File Count: 32
|Time: 01:27:06.834 |File Count: 33
|Time: 01:33:58.900 |File Count: 31
|Time: 01:33:59.357 |File Count: 31
|Time: 01:35:41.991 |File Count: 32
|Time: 01:35:42.635 |File Count: 32
|Time: 01:35:43.276 |File Count: 32
|Time: 01:43:04.393 |File Count: 32
|Time: 01:43:04.669 |File Count: 32
|Time: 01:48:53.450 |File Count: 30
|Time: 01:48:53.716 |File Count: 30
|Time: 01:48:54.129 |File Count: 31
|Time: 01:48:54.316 |File Count: 30
|Time: 01:53:52.937 |File Count: 31
|Time: 01:53:53.212 |File Count: 30
|Time: 01:53:53.531 |File Count: 30
|Time: 01:54:12.570 |File Count: 32
|Time: 01:54:12.834 |File Count: 32
|Time: 01:58:10.622 |File Count: 29
|Time: 01:58:52.862 |File Count: 31
|Time: 01:58:53.133 |File Count: 31
|Time: 01:58:53.432 |File Count: 31
|Time: 01:59:44.771 |File Count: 31
|Time: 01:59:45.102 |File Count: 30
|Time: 02:01:40.451 |File Count: 30
|Time: 02:04:18.265 |File Count: 32
|Time: 02:04:18.558 |File Count: 33
|Time: 02:04:18.919 |File Count: 32
|Time: 02:05:09.987 |File Count: 31
|Time: 02:05:10.725 |File Count: 31
|Time: 02:05:10.942 |File Count: 31
|Time: 02:05:11.572 |File Count: 31
|Time: 02:09:09.052 |File Count: 32
|Time: 02:09:09.370 |File Count: 31
|Time: 02:09:09.714 |File Count: 31
|Time: 02:10:42.097 |File Count: 32
|Time: 02:10:42.312 |File Count: 33
|Time: 02:15:28.439 |File Count: 33
|Time: 02:16:56.419 |File Count: 30
|Time: 02:16:56.764 |File Count: 29
|Time: 02:16:57.105 |File Count: 31
|Time: 02:16:57.403 |File Count: 31
|Time: 02:19:44.922 |File Count: 0
|Time: 02:19:45.200 |File Count: 31
|Time: 02:20:00.930 |File Count: 31
|Time: 02:20:01.281 |File Count: 30
|Time: 02:20:01.542 |File Count: 30
|Time: 02:20:34.771 |File Count: 31
|Time: 02:20:35.040 |File Count: 31

1 hour data looks like this , any suggestion for solutions ?

A: Here is a working solution.
I guess you will need adjustments for the complete file.
const fs = require('fs');

// import text file
let text = fs.readFileSync('./files.txt', 'utf-8');

//split text file to array and remove all Unnecessary characters
let arr = text.split(/\[|\]|,|: |\|Time|\|File Count|\r?\n|\r/g);

// remove empty elements
let filterdArr = arr.filter((el) => {
  return el != "" && el !== " ";
})

//decler array for file data objects
let fileDataArr = [];

//populate file data array with objects in this form:
// { time: <miliseconds>, fileCount: <number> }
filterdArr.forEach((el, i) => {
  if (i % 2 === 0) {
    fileDataArr.push({
      time: getMiliseconds(el),
      fileCount: +filterdArr[i + 1],
    })
  }
});

// declere array for time periods
let timePeriodsArr = [];

// populate time eriods array with objects for each time period
for (let i = 0; i < 24; i++) {
  let hours = i < 10 ? '0' + i : i;
  for (let x = 0; x < 60; x += 15) {
    let mins = x === 0 ? '00' : x;
    timePeriodsArr.push({
      timePeriod: `${hours}:${mins}`,
      fileCountAvg: 0,
    })
  }
}

// get array length
let arrLng = timePeriodsArr.length - 1;

// for each time period get start and end time in miliseconds
timePeriodsArr.forEach((timeObj, i) => {
  let startMs = getMiliseconds(timeObj.timePeriod)
  let endMs = i + 1 < arrLng ? getMiliseconds(timePeriodsArr[i + 1].timePeriod) : 86400000;
  let counter = 0;

  // check for each file data object if fits the current time period and calculate the average
  fileDataArr.forEach((fileObj, x) => {
    if (fileObj.time >= startMs && fileObj.time < endMs) {
      timeObj.fileCountAvg += fileObj.fileCount;
      counter++;
    }
  })
  timeObj.fileCountAvg = Math.round(timeObj.fileCountAvg / counter);
});

// time to miliseconds function
function getMiliseconds(el) {
  el = el.split(/:|\./g);
  if (el.length === 4) {
    return (+el[0] * 60 * 60 + +el[1] * 60 + +el[2]) * 1000 + +el[3];
  } else {
    return (el[0] * 60 * 60 + el[1] * 60) * 1000;
  }
}

console.log(timePeriodsArr);

You can download the the working solution here: https://github.com/yochanan-sheinberger/break-text-file.git


text:
Q: Google places api returns duplicate places I'm searching for places by keyword within an array of LatLngBounds.
    var boundsarr = new Array();

    boundsarr[0] = new google.maps.LatLngBounds(
        new google.maps.LatLng(25.941886953491675, -80.17411103748543),
        new google.maps.LatLng(25.947676224813897, -80.16767330177947)
    );
    boundsarr[1] = new google.maps.LatLngBounds(
        new google.maps.LatLng(25.941886953491675, -80.16767330177947),
        new google.maps.LatLng(25.94622890698334, -80.1644544339265)
    );
    boundsarr[2] = new google.maps.LatLngBounds(
        new google.maps.LatLng(25.927413775186118, -80.1644544339265),
        new google.maps.LatLng(25.94622890698334, -80.15962613214703)
    );
    boundsarr[3] = new google.maps.LatLngBounds(
        new google.maps.LatLng(25.927413775186118, -80.15962613214703),
        new google.maps.LatLng(25.931755728677782, -80.15801669822054)
    );
    boundsarr[4] = new google.maps.LatLngBounds(
        new google.maps.LatLng(25.927413775186118, -80.15801669822054),
        new google.maps.LatLng(25.933203046508336, -80.15318839644107)
    );
    boundsarr[5] = new google.maps.LatLngBounds(
        new google.maps.LatLng(25.92886109301667, -80.15318839644107),
        new google.maps.LatLng(25.933203046508336, -80.15157896251458)
    );

then adding markers on the map, to and array, and creating a list of places returned using the markers array. Duplicate entries show up in the list and I can't figure out why..
Example: http://jsfiddle.net/2KrmY/. How can I prevent duplicates from showing? Any help is greatly appreciated!

A: As an interim solution, could you build an array of found places in your Callback each time and then within the same loop, see if the place has a count of >1, then don't call createMarker if so?
Not sure if perfect, but see below:
var foundPlaces = [];
var found;

function callback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      found = 0;
      foundPlaces.push(results[i].id);
      for (var j = 0; j < foundPlaces.length; j++) {
        if (foundPlaces[j] === results[i].id) {
          found++;
          console.log(foundPlaces[j], results[i].id);
        }
      }

      if (found < 2) {
        createMarker(results[i]);
      }
    }
  }
}

http://jsfiddle.net/2KrmY/15/

A: The bounds parameter is described as below:

The bounds within which to search for Places. Both location and radius
  will be ignored if bounds is set.

But for the second bounds in your code example, 2 results outside the bounds get into the result.
You could display the bounds area by using:
new google.maps.Rectangle({
    strokeColor: 'red',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: 'bulue',
    fillOpacity: 0.6,
    map: map,
    bounds: bounds
});

And then you can see the result.
Check The demo.
This may be a bug of the google map api.

A: You need to check before adding new bounds, as when you click again it generates new marker in the same place..
use this...
map.getBounds().contains(marker.getPosition())
refer old Post
this will return true or false after checking this you may render/add the marker
I have tried in the fiddle but still no success... as its JASON syntax..
and JavaScript require specific function for the user defined data type.. I am trying to create custom function to eliminate duplicate JSON object....
I will keep you posted with updated fiddle as soon as its ready, till then you may try on your own..
I hope this will do..


text:
Q: can I use lists as positions for a stepper motor to rotate to in python? So I want to know if its possible for me to use list/array and set each element to a position and make the stepper motor rotate to that element position?

A: It is perfectly possible to use list/array here, but the key point is what is your requirement and how your code works out, because there are many types of stepper motors and different use cases for controlling the position, for example, if there are position sensors? if the initial position matters? unidirectional? error tolerance?


text:
Q: Why is my JSON response being returned surrounded with square brackets[]? I'm trying to figure out why my JSON response is being surrounded with square brackets. I'm using ASP.NET web API and Angular. I'm thinking that this is the reason that my Angular code is not printing to the HTML.
namespace GeekQuiz.Controllers
{
    public class TrialController : ApiController
    {
        private TriviaContext db = new TriviaContext();

        // GET api/trial
        public IQueryable<TriviaQuestion> GetTriviaQuestions()
        {
            return db.TriviaQuestions;
        }
    }
}

The above code is from my TrialController which I'm making a get call from Angular.
var app = angular.module('myApp', []);
app.controller('questCtrl', function ($scope, $http) {
    $http.get("/api/trial").success(function (data, status, headers, config) {
        $scope.options = data.options;
    }).error(function (data, status, headers, config) {
        $scope.title = "Oops... something went wrong";
        $scope.working = false;
    });
});

Here is my view page:
@{
    ViewBag.Title = "Contact";
}

@ViewBag.Title.

@ViewBag.Message

            {{ option.id }}
            {{ option.title }}
            {{ option.questionId }}

<address>
    One Microsoft Way

    Redmond, WA 98052-6399

    P:
    425.555.0100
</address>

<address>
    Support:   Support@example.com

    Marketing: Marketing@example.com
</address>
@section scripts {
    @Scripts.Render("~/Scripts/angular.js")
    @Scripts.Render("~/Scripts/app/quest-controller.js")
}

I'm playing around with ASP.NET and trying to learn how to build a restful application with Angular and .NET. I'm using this tutorial angular with ASP.NET and a Lynda.com course on ASP.NET.
Here is my JSON response. How do I get ride of the square brackets? I don't know why they are there.
[
  {
    "options":[
      {"id":1,"title":"2000","questionId":1},
      {"id":2,"title":"2001","questionId":1},
      {"id":3,"title":"2002","questionId":1},
      {"id":4,"title":"2003","questionId":1}],
    "id":1,
    "title":"When was .NET first released?"
  },
  {
    "options":[
      {"id":5,"title":"Contoso Ltd.","questionId":2},
      {"id":175,"title":"System.DateTime","questionId":44},
      {"id":176,"title":"System.Float","questionId":44}
    ],
    "id":44,
    "title":"Which of the following is NOT a value type in the .NET Framework Common Type System?"
  }
]

Here is what a successful working JSON response looks like:
{
  "options":[
    {"id":85,"title":"DOS","questionId":22},
    {"id":86,"title":"Altair Basic","questionId":22},
    {"id":87,"title":"PC Basic","questionId":22},
    {"id":88,"title":"Windows","questionId":22}
  ],
  "id":22,
  "title":"What was Microsoft's first product?"
}

Maybe this would be helpful:
namespace GeekQuiz.Models
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public class TriviaQuestion
    {
        public int Id { get; set; }

        [Required]
        public string Title { get; set; }

        public virtual List<TriviaOption> Options { get; set; }
    }
}

This code is the TriviaQuestion model, maybe I'm not treating this correctly.
If any awesome .NET programmer is looking for a disciple let me know.

A: Because IEnumerable<T> is serialized to JSON array.
About the Angular part...
I guess that $scope.options = data.options; is wrong, because you're returning the array itself from the WebAPI, and I can't find a reason to think that your options are being serialized in an object which contains a property options but it seems like your data is returned as a JSON array as is.
Probably your binding will work if you turn the so-called assignment to $scope.options = data;.


text:
Q: Django annotated queryset - resulting SQL query duplicates Let's imagine I have two models: User and Event:
class User(models.Model):
    email = models.EmailField(_('Email'), max_length=255, unique=True, db_index=True)

class Event(models.Model):
    class Type(models.IntegerChoices):
        ONE = 1, 'One'
        TWO = 2, 'Two'

    type = models.PositiveSmallIntegerField('Type', default=Type.ONE, choices=Type.choices, null=False, blank=False)
    when = models.DateTimeField(_('When?'), blank=True, null=True)

Now I have a queryset that is defined like below, to filter on users whose number of events are a multiple of 5. Using the db-side function Mod().
cycle_size = 5

users = User.objects.annotate(
    event_count=Coalesce(Subquery(
        Event.objects.filter(
            user__pk=OuterRef('pk')
        ).order_by(
            'user__pk'
        ).annotate(
            count=Count('pk', distinct=True)
        ).values(
            'count'
        ),
        output_field=models.IntegerField()
    ), 0),
    event_cycle_mod=Mod(F('event_count'), Value(cycle_size ))
).filter(
    event_count__gt=0,
    event_cycle_mod=0
)

It works.
But
The resulting SQL query that is generated looks like the following:
SELECT
  `user`.`id`,
FROM
  `user_user`
WHERE
  (
    `user_user`.`id` IN (
      SELECT
        V0.`id`
      FROM
        `user_user` V0
      WHERE
        (
          COALESCE(
            (
              SELECT
                COUNT(DISTINCT U0.`id`) AS `count`
              FROM
                `event_event` U0
              WHERE
                (
                  U0.`user_id` = V0.`id`
                )
              GROUP BY
                U0.`user_id`
              ORDER BY
                NULL
            ),
            0
          ) > 0
          AND MOD(
            COALESCE(
              (
                SELECT
                  COUNT(DISTINCT U0.`id`) AS `count`
                FROM
                  `event_event` U0
                WHERE
                  (
                    U0.`user_id` = V0.`id`
                  )
                GROUP BY
                  U0.`user_id`
                ORDER BY
                  NULL
              ),
              0
            ),
            5
          ) = 0.0
        )
    )
  )

The question is the following: is it normal that the whole COALESCE() and COUNT() function calls get repeated? Would it be normal to expect a AS COUNT and a HAVING or similar, instead of that duplication of code? Is there a way to avoid that duplication that I am not aware of? :-)
I have noticed this "bug" that seems to be related, but it has been flagged as fixed for a long while: https://code.djangoproject.com/ticket/26658
If useful: running django 3.1.3 and Mysql 5.7.xx.
(please ignore the nesting of bits like user_user.id IN (SELECT V0.id FROM user_user V0 -- they are the result of a dynamic building of the queryset).
Thanks!


text:
Q: Rules for type check in Swift builds? I've wanted to speed up my build times, so one of the steps was using Other Swift Flags and
-Xfrontend -warn-long-function-bodies=100
-Xfrontend -warn-long-expression-type-checking=100

But I'm not really sure how type checks work. For example, here's a simple func for creating random CGFloat. Type check for it is over 200ms
static func randomColorValue() -> CGFloat {
    return CGFloat(Int.random(in: 0...255))/255.0
}

But on changing to something like this
  static func randomColorValue() -> CGFloat {
         let rnd    = Int.random(in: 0...255)
         let frnd   = CGFloat(rnd)
         let result = frnd/255.0

         return result
     }

or like this
static func randomColorValue() -> CGFloat {
     let rnd    : Int     = Int.random(in: 0...255)
     let frnd   : CGFloat = CGFloat(rnd)
     let result : CGFloat = frnd/255.0

     return result
 }

type check is still over 200ms.

What's wrong here? Is there any set of rules and best practices for dealing with build times?
My Mac is a bit older (2012), maybe that's the problem?

EDIT:
After turning off -warn-long-function-bodies problematic line appeared, and that is
CGFloat(rnd)

It appears that casting Int to Float, Double or CGFloat shows slowing down of 150ms.

A: Note that warn-long-function-bodies is unsupported (it was added as an experimental flag). If you remove it, I find that the expression time is often reported as twice as fast, which makes be believe that using the two measurements together is causing interference. Measurement takes time, too. warn-long-expression is a supported option.


text:
Q: Rails: Dealing with child objects on AngularJS I'm very new to AngularJS and MVVM in general and was looking for the best way to deal with displaying a model that also needs to display a couple of fields from child model objects on the web UI.
At the moment following basic tutorials my model object in my AngularJS controller reflects exactly my Rails model, and so I can't access fields from my child objects and just see their IDs from the foreign key columns in the database.
I'm wondering what the best convention is for dealing with this situation?

*

*do I create a tableless model in Rails that contains only the fields needed by the presentation layer. Me defining what the presentation layer needs in Rails seems like it defeats the point of using MVVM.

*do I create something on the AngularJS side that queries for the child objects using those exposed foreign key IDs? If so, how do I optimise it to avoid performing a request for each of my 50 objects in the table.

A: Yeah! You should define your api to contain all the data needed for a request. You don't need to create a tabless model for that.
If for example a fetch the json for a Post, Author and Comments json representation also should be there, or at least some part of it.
You might want to take  a look at https://github.com/rails-api/active_model_serializers or https://github.com/nesquena/rabl


text:
Q: Change BackColor of Disabled ComboBox and CheckBox I'm setting up a Windows Form application and i'm creating a read only version of a form and another version of the same form for adding/modifying information. In the read only version I am setting up the form so that all of the form components are read only. By default in Visual Studio 2008, when a form component is disabled, the BackColor property of that component is changed to a grey(ish) color. This can be simply rectified by setting the BackColor property of the component after it has been disabled; However this is not the case with a ComboBox or a CheckBox. Once these components are disabled I am unable to modify their colours. Does anyone know how to change the colour of these components after they have been disabled? I've tried the following code but to no avail.
comboBoxCategory.Enabled = false;
comboBoxCategory.BackColor = Color.White;

Any help would be much appreciated.
Thanks.

A: You can't.
For the check box, just handle the OnCheck event and undo it.
The simplest solution for the combo box is to only populate the one item.  Let the user drop-down if they click, but there will be nothing to change it to.

A: I don't believe that you can do this with these controls out of the box. You may have to extend the combobox and override the OnPaint() method.
You could also leave the combobox enabled, store the selected value (when changed to readonly mode) and use the SelectedIndexChanged event to maintain the selection.
I believe the same will need to be done for the checkbox, but use the CheckChanged event

A: Change the BackColor of the ComboBox and CheckBox immediately after you have disabled them by code
Their is not event that will trigger on these controls when they get disabled or enabled

A: I think this is what you were looking for:
    comboBoxCategory.BackColor = System.Drawing.Color.White;

A: This code I made it in VB it could help you solve your problem .
Put this code in your Form change comboBox1  to your control name ,
change the color to whatever you like     .BackColor = Color.White
Dim lbl_Box As Label
Private Sub Disable_control()

    If ComboBox1.Enabled = True Then
        lbl_Box = New Label
        With lbl_Box
            .Name = "lbl_Box"
            .BackColor = Color.White
            .Top = ComboBox1.Top + 1
            .Left = ComboBox1.Left
            .Width = ComboBox1.Width - 21
            .Text = ComboBox1.Text
            .Font = ComboBox1.Font
            .Padding = New Padding(0, 2, 0, 0)
        End With
        Me.Controls.Add(lbl_Box)
        ComboBox1.Enabled = False
        lbl_Box.BringToFront()
    Else
        lbl_Box.Dispose()
        Me.Controls.Remove(lbl_Box)
        ComboBox1.Enabled = True
    End If
End Sub

You can put the code with some changes in ComboBox1_EnabledChanged Event  rather then calling the procedure if you want.


text:
Q: Returning values from callback(s) in Python I am currently looking at trying to use a callback in Python.
What I would like to do is return a value from the callback and then use this return value for conditional processing. So for example if the user enters "Y" I would like to print something to the console.
As I am new to Python the code below is as close as I can get currently but:
a) I am not sure if it is the Pythonic way of doing it
b) the correct way of doing it?
    class Observable:
        def subscribe(self,callback):
            self.callback = callback

        def fire(self):
            self.callback()

    class CallBackStuff:
        def doCallback(self):
            userInput = raw_input("Please enter Y or N?")
            return userInput

    if __name__ == '__main__':
        s = CallBackStuff()
        o = Observable()
        o.subscribe(s.doCallback)
        t = o.fire()
        print t

A: The easiest way I can think of to do this in your code is to just store the input as
a variable in the CallBackStuff object. Then after you've called the call-back function, you can just access the input data from the CallBackStuff instance. Example below.
class Observable:
    def subscribe(self,callback):
        self.callback = callback

    def fire(self):
        self.callback()

class CallBackStuff:
    storedInput = None # Class member to store the input
    def doCallback(self):
        self.storedInput = raw_input("Please enter Y or N?")

if __name__ == '__main__':
    s = CallBackStuff()
    o = Observable()
    o.subscribe(s.doCallback)
    o.fire()
    print s.storedInput # Print stored input from call-back object

A: class Observable(object):
    def __call__(self, fun):
        return fun()

class Callback(object):
    def docallback(self):
        inp = raw_input()
        return inp

if __name__ == "__main__":
    print Observable()(Callback().docallback)


text:
Q: Overful hbox with chemformula Chemical formulae often give overful hboxes.
How do I prevent that, and I mean something more automatic than just adding a \linebreak everywhere where this is an issue?
Should not Latex put a box (and every letter or word or syllable is a box, isn't it?) on the next line if it does not fit on the current one? This is especially true, when i explicitly put the formula in a mbox which gives the same result in the example.
\documentclass[12pt,a4paper]{scrartcl}
\usepackage[left=1.5cm,right=1.5cm,top=2cm,bottom=2cm,includeheadfoot]{geometry}
\usepackage[british,ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{chemmacros}
\chemsetup{modules={scheme}}
\renewcommand\cmpd[1]{\textbf{#1}}
\begin{document}
\section{Ziel des Versuchs}
Ziel des Versuchs war die Synthese des Katalysators \iupac{Tetra|kis(tri|phenyl|phos|phin)palladium(0)} (\ch{[Pd(PPh3)4]}, \cmpd{3}) und dessen Verwendung in einer Kreuzkupplungsreaktion zur Synthese von Biphenyl (\cmpd{6}).
\end{document}

writing
\mbox{\ch{[Pd(PPh3)4]}}

does not change anything


text:
Q: Publish word 2016 taskpane add-in manifest in SharePoint 2013 with commands section(VersionOverrides) I am trying to develop a Word 2016 add-in and publish the manifest file to the SharePoint 2013 Add-in Catalog. I use Visual Studio 2015 and Microsoft Office Developer Tools for Visual Studio 2015 and chooses the Visual C# -> Office/SharePoint-> Web Add-ins->Word Add-in template.
If I deploy this project to the IIS and put the manifest file generated from visual studio in a network share, then it works fine and I can see the addin in word 2016 from the network share.
But if I try to put the same manifest file in the Add-in Catalog of the SharePoint 2013 in our environment, then the state of the manifest is "not valid".  After some research I found in SharePoint logs the message "Invalid Agave manifest 'AgaveCatalog/WordWebAddInTestManifestManifest.xml': Der Typ 'http://schemas.microsoft.com/office/officeappbasictypes/1.0:VersionOverrides' ist nicht deklariert.". translated: "The type 'http://schemas.microsoft.com/office/officeappbasictypes/1.0:VersionOverrides' is not declared"
So I deleted all VersionOverrides references from the manifest and now its valid and word can see this add-in from SharePoint catalog. But this mean, I cannot use the "commands" feature in the manifest file to customize my add-in.
The Question: Is it possible to use commands(VersionOverrides) in the manifest file for word 2016 add-ins in the SharePoint 2013 Add-in catalog and if yes, how?

A: No, it is not possible. The SP Add-in catalog is not a supported method to deploy add-ins with commands. You can try the new Admin center though. For future reference here is a useful FAQ for commands.


text:
Q: How can I sync worlds from my phone to console? I have an iPhone SE running iOS 12.4 with minecraft 1.12.0 and a nintendo switch with bedrock 1.12.0. I have downloaded an addon world to my phone and I want to get it on my nintendo switch. Is there any way I can do this without a computer?

A: Turn the world on pocket edition to a .mcworld file.
You can do this by zipping all content from the world file in file explorer on the iPhone, and then renaming the file from "yourWorldName.zip" to "yourWorldName.mcworld. You should be able to find the original world file under "games/mojang/minecraftworlds/yourWorldName".
This type of file can be opened by any device, so you can import it to your switch.


text:
Q: How do I make a mod_rewrite rule that uses the sub-domain name to rewrite the URL? How do I make a mod_rewrite rule that uses the sub-domain name to rewrite the URL?
What I want to do is something like this:
Forward requests FROM  http://agency1.company.com  TO:  https://appname.company.com/appname/login.jsp?agencyName=agency1
It doesn't need to be a live proxy; It can just be a meta-refresh type of thing or a basic URL forward.   Seems like this would be a common scenerio but I can't find an example on the internet.   Lots of examples on the net of a URI rewrite but not many concerning a full URL rewrite (as I am trying to do above).

A: You can use RewriteCond on the HTTP_HOST value to do this.  There's a couple examples of this usage in the Apache URL Rewriting Guide.  You would do something like this:
RewriteEngine on
RewriteCond   %{HTTP_HOST}                 ^[^.]+\.company\.com$
RewriteRule (.*) https://appname.company.com/$1?agencyName=%1 [R,L,QSA]

This is untested, and might not work as is, but should point you in the right direction.

A: For this you can use Back-references.
RewriteEngine On
RewriteCond %{HTTP_HOST} ([^\.]+)\.domain\.com  [NC]
RewriteRule ^(.*)$ https://appname.company.com/appname/login.jsp?agencyName=%1 [R=301,L]

However, note this will end up redirecting again once the 301 is followed, IF the redir is to happen on HTTP only use the following block.
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ([^\.]+)\.domain\.com  [NC]
RewriteRule ^(.*)$ https://appname.company.com/appname/login.jsp?agencyName=%1 [R=301,L]

%1 refers to the first regex "capture" in the RewriteCond line, if you were to utilize mutliple points %2 and so on would become available.


text:
Q: Is it possible to list/access files stored after ios app update? I store videos using AVAsset library. It's all working fine and I can watch videos offline.
But when the app gets updated, video stop playing.
The file was, let's say, downloaded to this location:
file:///private/var/mobile/Containers/Data/Application/5D5DE2DB-4518-453D-AD27-5E32E5665FAF/Library/.../2921436_AE26A440BC211429.movpkg

But if I do FileManage.fileExists after app update, it says file doesn't exist.
I tried listing using this code to list all files:
extension FileManager {
    func urls(for directory: FileManager.SearchPathDirectory, skipsHiddenFiles: Bool = true ) -> [URL]? {
        let documentsURL = urls(for: directory, in: .userDomainMask)[0]
        let fileURLs = try? contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: skipsHiddenFiles ? .skipsHiddenFiles : [] )
        return fileURLs
    }
}

It lists all files but the uuid of the file path is different than that of older stored file and it doesn't list the older file.
The question is is it possible to access the old downloaded file?


text:
Q: Microsoft Outlook 2010 doesn't remember BPOS password I have a BPOS account and Outlook was set up for this account by the Microsoft Online Sign-in application. If the Sign-in application isn't open and I open Outlook, it always asks me for the account's password, even if I tell it to remember it. This doesn't happen if I have the Sign-in application open.
Is there a way to make Outlook not ask for the password when the Sign-in application isn't open?

A: According Microsoft's BPOS representatives no. I tried to get this functionality right after we switched.  According to the documentation in the coming Microsoft Live 365, which is the maturation of BPOS, this functionality will be default. The time frame for this move is this calendar year according to MS, but your company may differ.
HTH


text:
Q: Using Gmail API with Python, searching messages return Requested entity was not found I am working in gmail api using python and django. In this case I need to work in the backend offline authentication. After create the url to auth the backend and create the credentials I need to get specific message with the id message.
This the code:
   state = request.GET['state']
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( client_secrets_file='credentials.json', scopes='https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/gmail.metadata https://www.googleapis.com/auth/userinfo.email openid https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.compose',state=state)
    flow.redirect_uri = 'https://domian.com/auth/oauth'
    authorization_response = request.build_absolute_uri()
    flow.fetch_token(authorization_response=authorization_response, client_secret='<client_secret>', code=request.GET['code'])
    request.session['credentials'] = {
        'token': credentials.token,
        'refresh_token': credentials.refresh_token,
        'token_uri': credentials.token_uri,
        'client_id': credentials.client_id,
        'client_secret': credentials.client_secret,
        'scopes': credentials.scopes
    }

service =  build('gmail', 'v1', credentials=credentials)
results = service.users().messages().get(userId='me', id='<id>', format='minimal').execute()

Django return:
HttpError at /auth/oauth
<HttpError 404 when requesting https://gmail.googleapis.com/gmail/v1/users/me/messages/1273369159314488?format=minimal&alt=json returned "Requested entity was not found.">
But the id message exist and is correct.
Even I use others endpoints like labels and works good the query.
Somene have any suggestions?
Regards


text:
Q: How to solve TSP problem with more than 3 nodes in the tutorial of Max-Cut and Traveling Salesman Problem Qiskit 0.24.0? I had to try the example of qiskit's Traveling Salesman Problem  with 3 nodes and executing it at IBM backend called simulator_statevector.Can execute and get the result normally.
But when trying to solve the TSP problem with more than 3 nodes,I changed n = 3 to n = 4.
# Generating a graph of 3 nodes
n = 4
num_qubits = n ** 2
ins = tsp.random_tsp(n, seed=123)
print('distance\n', ins.w)

# Draw the graph
G = nx.Graph()
G.add_nodes_from(np.arange(0, ins.dim, 1))
colors = ['r' for node in G.nodes()]

for i in range(0, ins.dim):
    for j in range(i+1, ins.dim):
        G.add_edge(i, j, weight=ins.w[i,j])

pos = {k: v for k, v in enumerate(ins.coord)}

draw_graph(G, colors, pos)

And I changed backend from Aer.get_backend ('statevector_simulator') running on my device to provider.backend.simulator_statevector running on the IBM backend.
aqua_globals.random_seed = np.random.default_rng(123)
seed = 10598
backend = provider.backend.simulator_statevector
#backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)

But the result that comes out with an error.
energy: -1303102.65625
time: 5626.549758911133
feasible: False
solution: [1, 0, 2, []]
solution objective: []
Traceback (most recent call last):
  File "<ipython-input-10-bc5619b5292f>", line 14, in <module>
    draw_tsp_solution(G, z, colors, pos)
  File "<ipython-input-4-999185567031>", line 29, in draw_tsp_solution
    G2.add_edge(order[i], order[j], weight=G[order[i]][order[j]]['weight'])
  File "/opt/conda/lib/python3.8/site-packages/networkx/classes/coreviews.py", line 51, in __getitem__
    return self._atlas[key]
TypeError: unhashable type: 'list'

Use %tb to get the full traceback.

How should I fix it? Please give me some advice.

A: I found the answer, my method is to increase the Ansat number of reps from 5 to 7.
from solving TSP 4 node problem
spsa = SPSA(maxiter=300)
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=7, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa, quantum_instance=quantum_instance)

result = vqe.run(quantum_instance)


text:
Q: SharedConfigLoadError while creating Amazon EKS Cluster When trying to run this on terminal,
eksctl create cluster \
--name dev \
--version 1.14 \
--region us-west-2 \
--nodegroup-name demo \
--node-type t3.medium \
--nodes 3 \
--nodes-min 1 \
--nodes-max 4 \
--ssh-access \
--ssh-public-key my-public-key.pub \
--managed

Getting this error:
panic: SharedConfigLoadError: failed to load config file, /home/thira/.aws/credentials
caused by: INIParseError: invalid state with ASTKind {completed_stmt {0 NONE 0 []} false [{section_stmt {1 STRING 0 [78 111 110 101]} true []}]} and TokenType op

A: I have met similar problem, I am using powershell as a cicd agent. I need to use s3 backend as a terraform state store. So I just echo aws access id and secret in to ~/.aws/credentials, but this error happened. Then I found the root cause is windows file format, we need to transfer the file to linux file format. I lookuped how to transfer windows file to linux file in powershell on internet, so the finall solution for my problem is :
[string]::Join( "`n", (gc  ~/.aws/cred)) | sc ~/.aws/credentials
Below is my whole codes:
if (Test-Path ~/.aws) {
  Remove-Item ~/.aws -Recurse -Force -EA SilentlyContinue
}
mkdir ~/.aws
echo "[services]" > ~/.aws/cred
echo "aws_access_key_id = ${bamboo.S3_BACK_ACCESS}" >> ~/.aws/cred
echo "aws_secret_access_key = ${bamboo.S3_BACK_SECRET}" >> ~/.aws/cred
[string]::Join( "`n", (gc  ~/.aws/cred)) | sc  ~/.aws/credentials
cat ~/.aws/credentials

About how to convert window file to linux file in PowerShell, I referred the link:
UNIX format files with Powershell
Hope it can help others!