Executemany() SQL-Update Statement with variables for column names

Question: I am really struggling with updating many rows in python using SAP HANA as my database and PyHDB for establishing the interface between both applications. Its working when I "hardcode" the columns, but I need to dynamically switch the columns by defining them inside of an array for example.
I am able to update in a hardcoded way the necessary columns by performing the following SQL-query:
sql = """UPDATE "ARE"."EMPLOYEES" SET "LIKELIHOOD_NO" = %s, "LIKELIHOOD_YES"= %s, "CLASS" = %s WHERE "EmployeeNumber" = %s;"""
cursor.executemany(sql, list)
connection.commit()

What I want to achieve is the following scenario:
 dynamic_columns = ["LIKELIHOOD_NO", "LIKELIHOOD_Yes"]
 sql = """UPDATE "ARE"."EMPLOYEES" SET dynamic_column = %s, "LIKELIHOOD_YES" = %s, "CLASS" = %s WHERE "EmployeeNumber" = %s;"""
 cursor.executemany(sql, list)
 connection.commit()

I am always getting the error that the relevant column / columns could not be found, but I cant figure out a way to solve this.
Comment: Just format the string before you pass it to executemany. """UPDATE "ARE"."EMPLOYEES" SET {dynamic_column} = %s, "LIKELIHOOD_YES" = %s, "CLASS" = %s WHERE "EmployeeNumber" = %s;""".format(dynamic_column=dynamic_columns[0])
Comment: ufff.. time for a coffee. havent even thought about this, works fine!  thank you for that.
Comment: Glad to help. Passing sql and list of parameters is good for user input to avoid sql injection, but if you know what you are inserting into the query you can also use just format :-)
Comment: I dont get the full point of your statement, do you mean that your mentioned example is vulnerable for sql injection?
Comment: No, I mean that unless you format sql string with data from the user, you can use format on the sql string. In your case it's ok.
Answer: You can use normal string interpolation (.format()) to add the dynamic column name. You can see in the code here that pyHDB supports "numeric" paramstyle:
for col in ['LIKELIHOOD_YES', 'LIKELIHOOD_NO']:
    sql = ('UPDATE "ARE"."EMPLOYEES" SET "{some_col}" = :1, "CLASS" = :2 '
           'WHERE "EmployeeNumber" = :3;').format(some_col=col)
    cursor.executemany(sql, list_of_tuples)

This code will run for both columns 'LIKELIHOOD_YES' and 'LIKELIHOOD_NO'. Adapt it as you need. It would work with a list of tuples like this:
list_of_tuples = [
    (value1, class_1, employee_no_1),
    (value2, class_2, employee_no_2),
    (value3, class_3, employee_no_3),
    (value4, class_4, employee_no_4),
]

The code in your question seems to be using the 'format' paramstyle instead, but that doesn't seem what pyHDB is using. See PEP 249 for more information on paramstyles.
Comment: thank you for that example. just one question to that particular term: SET "{some_col}" = :1 <-- the "1" means that it takes the first value of "list_of_tuples", correct?
Comment: @Alex it means first value from *each tuple* in the `list_of_tuples` - the query will run multiple times, one for each tuple.
Comment: the solution you have provided looks like a major boost in performance for me when updating the columns. at first it took around 6 seconds to update around 1500 columns, now its in the area of milliseconds. how is that possible?
Comment: @Alex that's the whole point of using parameterization and `executemany()` !!! It allows the database to cache the query plan and execute it with different arguments with no overhead.
Comment: brilliant. really brilliant. thank you for that point, it really keeps away a lot of headache!!


WPF MVVM databing to datagrid not updating

Question: I want to display a list of notes from an object in a WPF DataGrid using MVVM
XAML:
 <DataGrid
        x:Name="NoteGrid"
        ItemsSource="{Binding NoteObj.Notes}"
        SelectedItem="{Binding CurrentNote}"
        AutoGenerateColumns="False"
        CanUserAddRows="False"
        CellEditEnding="DataGrid_CellEditEnding">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Note" Binding="{Binding NoteText}" />
            <DataGridTextColumn Header="Type" Binding="{Binding Type.Name}" />
        </DataGrid.Columns>
    </DataGrid>

The return-value of NoteObj.Notes is EntitySet.
ViewModel:
private NoteObject noteObj;
public NoteObject NoteObj
{
    get { return noteObj; }
    set { noteObj = value; OnPropertyChanged("NoteObj"); }
}

public void AddNote()
{
    var note = new Note
    {
        NoteText = "Note text",
        NoteType = 1
    };

    NoteObj.Notes.Add(note);
    DC.SubmitChanges();
    OnPropertyChanged("NoteObj");
}

When NoteObj is set the DataGrid is filled with notes but the AddNote-method doesn't wotk!
The new note is added to the database, but the DataGrid is never updated.
Is it a problem eith EntitySet or am I missing something in the XAML?
Comment: Try adding [presentationtracesources](http://msdn.microsoft.com/en-us/library/system.diagnostics.presentationtracesources.tracelevel.aspx) and see if it gives you some hints in the output.
Comment: If I set the TraceLevel to "high" or "medium" the program crashes on SubmitChanges (row not found or something). No output!
Comment: which may indicate that there are problems with EF, not binding?
Comment: I use a LINQ to SQL datamodel auto-generated by VS2010.
Answer: This will only work if NoteObj.Notes implements INotifyCollectionChanged. You can achieve this by using the class ObservableCollection<T>.
Comment: Somehow I can't get this right. Do you have a link to an article/tutorial that shows such an implementation? Can't find one with LINQ to SQL...
Comment: "Pure" MVVM states that your entities have nothing to do with your UI, hence you would need to create a `NoteObjectViewModel` that contains a property `ObservableCollection Notes`. Because if you don't, you run into problems just like this.
Comment: Are you saying that I need to implement an ObservableCollection in my ViewModel, and "populate" this when the NoteObj is set?


See if left mouse button is held down through Powershell?

Question: So I'm trying to make a program in Powershell and I'm trying to see if the left mouse button is held down. Right now I'm using the method to run C# code in Powershell to try and do this but I have been looking for hours to find a way to see when the left mouse button is held down anywhere on the screen on any window. I can't really show what I have tried already because I've deleted them all, sorry ;(. If anyone could help, that would be amazing.
Edit:
This was the last thing that I tried.
$code = @"
using System;
namespace Auto
{
    public class Program
    {
        public static void Main(){
            while (true) {
        byte[] result = BitConverter.GetBytes(GetAsyncKeyState(1));
        if (result[1] == 0x80) {
          Console.WriteLine("Left Mouse Button Down");
        }
      }
        }
    }
}
"@

Add-Type -TypeDefinition $code -Language CSharp
iex "[Auto.Program]::Main()"

Comment: Your C# code is missing [a P/Invoke declaration for the `GetAsyncKeyState` WinAPI function](http://www.pinvoke.net/default.aspx/user32/GetAsyncKeyState.html)
Comment: As an aside: just call `[Auto.Program]::Main()` directly - no need for `Invoke-Expression` (`iex`), which [should generally be avoided](https://blogs.msdn.microsoft.com/powershell/2011/06/03/invoke-expression-considered-harmful/).
Comment: And that should be absolutely obvious by the error when trying to populate the $code variable  `The name 'GetAsyncKeyState' does not exist in the current context`
Answer: Ok so it turns out I needed to add...
[DllImport("user32.dll")]
private static extern short GetAsyncKeyState(System.Int32 vKey);

for GetAsyncKeyState to work and that was saying that DllImport wasn't found. I also needed to add using System.Runtime.InteropServices; at the top for DllImport to work as well. Now it works perfectly, thank you.


Putty 0.76 does not work on Ubuntu 22.04 unless with Sudo

Question: I recently upgraded Ubuntu to 22.04, and installed PuTTY 0.76 in it.
Sorry, I can't remember if I used apt install or a snap.
Putty initiates OK,  but when attempting a terminal session with an open, nothing happens.
Apparently Putty just terminates.
But I discovered that if I run Putty with sudo in a terminal session, it behaves properly.
As well, a simple SSH terminal without sudo is able to initiate a terminal session in the object machines.
I have been using Putty 0.76 in older versions of Ubuntu satisfactorily up to now.
Comment: any error message that would help ?
Comment: @Marco   Thanx for the suggestion. I found a Putty log and it said "Unable to load server:fixed" whatever that is....
Comment: Close to this one: https://askubuntu.com/q/1255916/57576
Comment: See Answer https://askubuntu.com/a/1407965/767949
Comment: Does this answer your question? [PuTTY: "unable to load font" in Ubuntu 20.04](https://askubuntu.com/questions/1255916/putty-unable-to-load-font-in-ubuntu-20-04)
Answer: It seems the default font for PuTTY 0.76 in Ubuntu 22.04 is "Server:Fixed".
Not sure what that is, but I browsed the available fonts in PuTTY, and chose one to my liking.
Now PuTTY is working OK!
Thanx, @Marco-  Yes, ALWAYS check those logs!

Don't forget to go back to the session and save to persist the change.
Comment: Had the same issue, your solution of changing the font worked. Thanks.


Using jq to convert object to key with values

Question: I have been playing around with jq to format a json file but I am having some issues trying to solve a particular transformation. Given a test.json file in this format:
[
 {
  "name": "A", // This would be the first key
  "number": 1,
  "type": "apple",
  "city": "NYC" // This would be the second key

 },
 {
  "name": "A",
  "number": "5",
  "type": "apple",
  "city": "LA"
 },
 {
  "name": "A",
  "number": 2,
  "type": "apple",
  "city": "NYC"
 },
 {
  "name": "B",
  "number": 3,
  "type": "apple",
  "city": "NYC"
 }
]

I was wondering, how can I format it this way using jq?
[
  {
    "key": "A",
    "values": [
      {
        "key": "NYC",
        "values": [
          {
            "number": 1,
            "type": "a"
          },
          {
            "number": 2,
            "type": "b"
          }
          ]
      },
      {
        "key": "LA",
        "values": [
          {
            "number": 5,
            "type": "b"
          }
        ]
      }
    ]
  },
  {
    "key": "B",
    "values": [
      {
        "key": "NYC",
        "values": [
          {
            "number": 3,
            "type": "apple"
          }
        ]
      }
    ]
  }
]

I have followed this thread Using jq, convert array of name/value pairs to object with named keys and tried to group the json using this expression
jq '. | group_by(.name) | group_by(.city) ' ./test.json

but I have not been able to add the keys in the output.
Answer: You'll want to group the items at the different levels and building out your result objects as you want.
group_by(.name) | map({
    key: .[0].name,
    values: (group_by(.city) | map({
        key: .[0].city,
        values: map({number,type})
    }))
})

Just keep in mind that group_by/1 yields groups in a sorted order. You'll probably want an implementation that preserves that order.
def group_by_unsorted(key_selector):
    reduce .[] as $i ({};
        .["\($i|key_selector)"] += [$i]
    )|[.[]];

Comment: Warning: group_by_unsorted as defined here might be useful in many cases, but it is not as generic as the builtin `group_by` because the latter, but not the former, is resistant to collisions.


Probability of winning at least one prize in a raffle

Question: "A guy bought $4$ tickets in a raffle of $200$ tickets, where $5$ of them gives a prize. What the probability of the guy winning at least $1$ prize".
My try
After a long analysis, i think the formula for exactly $1$ prize is:
$$\frac{\dbinom{5}{1}\dbinom{195}{3}}{\dbinom{200}{4}}$$
But the question is about at least $1$ prize, and i don't know if that affects my answer.
Is my answer right for exactly $1$ prize?
How do i compute the answer for at least 1 prize?
Thanks.
Comment: I told you to compare them.  I didn't tell you how to compare them.  Since you bring it up, yes, they would add to equal $1$, implying that the one is equal to $1$ minus the other.
Comment: Your analysis for exactly 1 prize is correct.  For at least one prize, you *could* then add this to the probability for getting exactly 2 prizes, exactly 3 prizes, and exactly 4 prizes all together.  This simplifies nicely using vandermonde's identity, but it is unnecessary since there is a much more convenient approach.  Compare the probability of getting at least 1 prize with the probability of getting zero prizes.
Comment: U mean $1-$ probability of winning **exactly** 0 prizes right?
Answer: When solving a question asking for the probability of at least 1 event, it is a good rule of thumb to first solve the complement -- the probability of 0 events occurring -- and then subtract from 1.
In this case, we want to find the probability that, given a guy has bought 4 raffle tickets, he wins 0 prizes.
If we logically walk through this, this is equal to the event that the all the 5 prizes go to a raffle ticket other than the 4 the guy has.
The probability of a single prize going to another raffle is $\frac{196}{200}$. This implies the probability of all 5 prizes going to another raffle is $(\frac{196}{200})^5$.
So the probability of winning at least 1 prize is equal to $1 - (\frac{196}{200})^5$.
Edit
In the previous solution, I made the erroneous assumption that this was a raffle drawn with replacement: that is, once a ticket has been selected, it is placed back into the bin.
To solve for a raffle drawn without replacement, we have to make a slight correction to the probabilities.
The probability of the event of the first prize going away is still $\frac{196}{200}$. However, as the winning ticket is thrown away, the probability of the event of the second prize going away is now $\frac{195}{199}$. And so forth.
In total, the probability of all 5 prizes going to another raffle will be $$\frac{196 \cdot 195 \cdot 194 \cdot 193 \cdot 192}{200 \cdot 199 \cdot 198 \cdot 197 \cdot 196}.$$
The probability, then, of winning at least 1 prize is the complement:
$$1 - \frac{196 \cdot 195 \cdot 194 \cdot 193 \cdot 192}{200 \cdot 199 \cdot 198 \cdot 197 \cdot 196}.$$
Comment: I'll make a quick edit -- thanks for the correction.
Comment: Watch how many terms are being multiplied on top compared to bottom.  Your answer wound up lying outside of $[0,1]$.  Using falling factorials or binomial coefficients is an easy way to avoid the issue of needing to write out so many individual multiplicands.
Comment: Oops sorry. I tried to avoid using factorials and binomial coefficients to get a simpler intuition behind the math. Of course if a person wanted to generalize to $n$ raffles out of $k$ draws, they should be using closed form expressions.


Is there a menu component in Rikulo

Question: I cannot find any examples in Rikulo on how to create and use menu bar, menu, sub menu and menu items.
could anyone point me in the right direction please?
regards
Answer: No, it is not supported. There are too many styles and variants. Many of them don't require much JS code. Here are some examples. You can port one to your application and wrap it as a Rikulo UI component, if you want.

I assumes you're talking about Rikulo UI. If you're using Bootjack, you can pick one from Bootstrap's 3rd party libraries.

Is there a menu component in Rikulo


Fetching Values from textField in a custom cell iPhone

Question: I have a custom cell in a table View, see below.

I have two textFields txt1 and txt2 in my custom cell, as seen below

How can i access the values i enter in each of the text fields so that i can add the values in to seperate Arrays...
the "Addset" button will increment the no of sections of the grouped table View there by incrementing the one more set.
my table view code is as follows.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID= @"catogoryCell";
    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellID];

    if(cell==nil)
    {
        NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:nil options:nil];

        for(id currentObject in nibObjects)
        {
            if([currentObject isKindOfClass: [CustomCell class]])
            {
                cell = (CustomCell *)currentObject;
            }
        }
    }

    //cell.txt1.text = @"0";

    return cell;
}

Thanks all..
Answer: Cells are reusable, so they need a more persistent way to keep their info.
Method 1:
You could hold some UITextField objects into an array in case you don't want to reuse the textfields as well, and at cellForRowAtIndexPath you'd only need to set the textfields to their cells such as:
cell.txt1 = [textFieldsArray objectAtindex:indexPath.section*2];
cell.txt2 = [textFieldsArray objectAtindex:indexPath.section*2+1]; //txt1 and txt2 properties should have assign

Method 2:
If you want to reuse the textfields as well I suggest using an array with mutable dictionaries, each dictionary holding the 'settings' for a cell. The textfields will be fully managed by the custom cell (e.g: at the UIControlEventValueChanged event update @"txt1" or @"txt2" values from the dictionary attached to the cell).
///somewhere in the initialization (in the class holding the tableview)
contentArray = [[NSMutableArray alloc] init];

///when adding a new cell (e.g: inside the 'Add set' action)
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"", @"txt1", @"", @"txt2", nil]];
//add a new cell to the table (the same way you do now when tapping 'Add set')

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ...
     [cell attachDictionary:[contentArray objectAtIndex:indexPath.section]];
    return cell;
}

///anywhere where you'd like to access the values inserted inside a cell
NSMutableDictionary *cell3Content = [contentArray objectAtIndex:3];
NSString *text1 = [cell3Content valueForKey:@"txt1"];
NSString *text2 = [cell3Content valueForKey:@"txt2"];

///CustomCell.m
-(id)initWithCoder:(NSCoder *)decoder{
    self = [super initWithCoder:decoder];
    if(!self) return nil;
    [txt1 addTarget:self action:@selector(txt1Changed:) forControlEvents:UIControlEventValueChanged];
    [txt2 addTarget:self action:@selector(txt2Changed:) forControlEvents:UIControlEventValueChanged];
    return self;
}
-(void)attachDictionary:(NSMutableDictionary *)dic{
    contentDictionary = dic;
    txt1.text = [contentDictionary valueForKey:@"txt1"];
    txt2.text = [contentDictionary valueForKey:@"txt2"];
}
-(void)txt1Changed:(UITextField *)sender{
    [contentDictionary setValue:txt1.text forKey:@"txt1"];
}

Comment: HI Thanks babbiidi, what are the contents in the textFieldarray??
Comment: `textFieldsArray` would hold `UITextField` objects, which can be initialized and set up when 'Add set' is tapped. They can be positioned correctly in the custom cell inside the `txt1` and `txt2` setters of the cell. I personally like the second method better since each cell will handle its content, plus it will use less memory.
Comment: Hi babbidi, i hav tried your code , but somewhere went wrong. The app creashes when the view loads. Could you provide some more stuff please? Is contentArray holds the textField objects??
Comment: No, for the second method `contentArray` contains `NSMutableDictionary` with 2 values at keys: `@"txt1"` and `@"txt2"` (which will be the text inserted in the cell textfields). Also, make sure that in `CustomCell.xib` you have the txt1 and txt2 linked to `IBOutlet UITextfield *txt1;` and `IBOutlet UITextField *txt2` from `CustomCell` class (not the owner, but the cell itself - make its type `CustomCell` in the xib). The code from the second block above (main comment) is about everything you need.
Answer: When you make the IBOutlet connections in your UITableViewCell subclass, connect them to properties in the File Owner (the viewController), instead of the view itself. That way you'll be able to access them from your viewController (the UItableViewDataSource)


Should I connect one cable to each outlet in a two-gang box?

Question: I removed a 1-gang box that had two 14-2 cables entering it with all wires connected to a single duplex outlet. Strange I thought. I need to install a 2-gang box with two duplex outlets in it. I had purchased 14-2 Romex prior to today because I thought I would find one sheath of 14-2 behind the 1-gang box. Based on the picture, I am assuming I lucked out and can just wire each cable to one duplex outlet. No need for pigtails. Am I right?

Update: I connected the two 14-2 Romex sheaths and two sets of pigtails (2 x black, 2 x neutral, 2 x ground) together with wire nuts, and then connected the other ends of the pigtails to the outlets. Everything is working perfectly. Thank you for the education and recommendations. Made this project easy.
Comment: The second set is likely for other outlets on the circuit meaning it's not live, and is dependent on the first. The outlet was probably just acting as a way to connect them in parallel.
Comment: Why do you want a 2-gang receptacle here? How many plugs do you want to connect? If more than 2, you can use a short extension cord to a plug strip. You will not be able to draw more current than the wire and breaker allows just by putting in another receptacle. See https://www.amazon.com/GE-54947-Grounded-6-Outlet-Tap/dp/B00006IBFA
Comment: @JimStewart—My home security company requires the home security radio device to be on a "separate [duplex] outlet" than that which the motherboard and gateway are plugged into, and it cannot be on a plug strip (since it would be on the same duplex outlet). The radio does not draw much current; I understand where you are coming from.
Comment: Are you sure they do not mean on a separate *circuit*? I am not up on security systems but I cannot see any advantage to the two loads being on separate duplex receptacles in the same box on the same circuit, i.e., protected by the same breaker. But hey it's done and should cause no problems.
Comment: @JimStewart—That is what I was thinking when the tech initially told me, but plugging into a receptacle on a different circuit seems impractical, although it makes more sense to you and I both. As I was explaining to him what I was planning on doing to add another outlet, he did not voice any dissent, as though the radio had to be on a different circuit. *shrugs*
Comment: In the UK (and possibly elsewhere) these might be two arms of a ring main, in which case you'd *still* want to join them together.
Answer: No. You have an upstream cable (source power) and a downstream cable (which feeds something else--more outlets or lights), and they need to be connected in order to maintain continuity throughout the circuit.
You'll need either pigtails (best practice, but a bit messy), or jumpers connecting the two receptacles (simpler, relies on the outlet hardware more).
Your fundamental misunderstanding was that you'd have two source cables connected to one outlet. That would result in an odd (and potentially dangerous) situation. An exception would be when half of the outlet is switched, and fed from a second cable. The telltale sign would be removed tabs on the sides of the outlet.
Comment: +1 But there are times when you might want two source cables (on separate breakers) attached to a single duplex outlet, such as setting it up for use of two high amperage devices at one time, but that would require separating the top and bottom of the duplex by removing both tabs.
Comment: Just for posterity, one case where there would legitimately be two source cables is when one outlet is switched and the other is not.  This is common when you want the switch by the door to turn on a standing floor lamp instead of a built in fixture.
Comment: @bib  It's something I would do, but it would also be unusual. OP can find out by a couple wraps of electrical tape on the loose wires to keep them from shorting, turn power back on, and search for other switches, receptacles or other things that now don't work.
Comment: Thank you. I definitely appreciated your prompt advice and education. I used pigtails. Everything is working perfectly. :)


Material UI accordion causes flickering of the page when collapsed or expanded

Question: import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Accordion from "@material-ui/core/Accordion";
import AccordionDetails from "@material-ui/core/AccordionDetails";
import AccordionSummary from "@material-ui/core/AccordionSummary";
import AddCircleIcon from "@material-ui/icons/AddCircle";
import RemoveCircleSharpIcon from "@material-ui/icons/RemoveCircleSharp";

import "../customCSS/container.css";
import "../customCSS/bootstrap-grid.min.css";
import "./Accordion.css";

const useStyles = makeStyles((theme) => ({
  root: {
    width: "100%",
    marginLeft: "auto",
    marginRight: "auto",
  },
}));

const accordionDetails = [
  {
    accordName: "panel1",
    accordControls: "panel1bh-content",
    accordId: "panel1bh-header",
    accordHeading: " What does the personal manager help me with?",
    accordDetails:
      "Right from party planning to sending invitation to all your family and friends, your personal manager will do it all.",
  },
  {
    accordName: "panel2",
    accordControls: "panel2bh-content",
    accordId: "panel2bh-header",
    accordHeading: " What does the personal manager help me with?",
    accordDetails:
      "Right from party planning to sending invitation to all your family and friends, your personal manager will do it all.",
  },
  {
    accordName: "panel3",
    accordControls: "panel3bh-content",
    accordId: "panel3bh-header",
    accordHeading: " What does the personal manager help me with?",
    accordDetails:
      "Right from party planning to sending invitation to all your family and friends, your personal manager will do it all.",
  },
];

const Accordions = () => {
  const classes = useStyles();
  const [expanded, setExpanded] = React.useState(false);

  const handleChange = (panel) => (event, isExpanded) => {
    setExpanded(isExpanded ? panel : false);
  };

  return (

      {accordionDetails.map((accord) => {
        return (
          <Accordion
            expanded={expanded === accord.accordName}
            onChange={handleChange(accord.accordName)}
          >
            <AccordionSummary
              expandIcon={
                expanded === accord.accordName ? (
                  <RemoveCircleSharpIcon style={{ color: "#aaaaaa" }} />
                ) : (
                  <AddCircleIcon style={{ color: "#aaaaaa" }} />
                )
              }
              aria-controls={accord.accordControls}
              id={accord.accordId}
            >

{accord.accordHeading}

            </AccordionSummary>
            <AccordionDetails>

{accord.accordDetails}

            </AccordionDetails>
          </Accordion>
        );
      })}

  );
};

export default Accordions;

CSS code
.MuiPaper-elevation1 {
  box-shadow: none !important;
}

.MuiAccordion-root {
  position: static !important;
  border-bottom: 1px solid #aaaaaa !important;
}

.MuiAccordionSummary-root {
  padding: 0 !important;
  justify-content: space-between !important;
}

.MuiAccordionSummary-content {
  width: 90% !important;
  flex-grow: 0 !important;
}

.MuiAccordionDetails-root {
  width: 90% !important;
}

.MuiAccordion-rounded {
  border-radius: 0 !important;
}

.MuiAccordionDetails-root {
  padding-left: 0 !important;
  padding-top: 0 !important;
  padding-bottom: 15px !important;
}

.accordion-heading {
  font-family: Montserrat !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  line-height: 1.4 !important;
  color: var(--black) !important;
}

.accordion-details {
  font-family: Montserrat;
  font-size: 12px;
  line-height: 1.4;
  color: #595959;
}

.MuiAccordionSummary-content.Mui-expanded {
  margin: 15px 0 !important;
}

.MuiAccordion-root.Mui-expanded {
  margin: 0 !important;
}

I have implemented materialui accordion. Whenever I expand or collapse it causes flickering of the page.  Their official documentation also has the same flickering experience when expanded or collapsed multiple times. I have added the link.
Here is the official documentation of the same
https://material-ui.com/components/accordion/#accordion
How do I resolve that issue ?
Note: Expand or collapse accordion multiple times to know the effect.
Answer: You are using root with 100% of width container. And when component expanding\hiding it add horizontal scrollbar at one moment and immediately remove it. If you change root style width on 99% all should works correct without flickering
const useStyles = makeStyles((theme) => ({
  root: {
    width: '99%',
  },
...
}));


Capturing group does not work with NSRegularExpression

Question: I'm trying to make NSRegularExpression working with capturing group pattern. I've got string abc{=2} and regular expression pattern {(.+)} to get =2 string but every attempt to create NSRegularExpression instance ends with
Optional(Error Domain=NSCocoaErrorDomain Code=2048 "The operation couldn't be completed. (Cocoa error 2048.)" UserInfo=0x7fad7253cb40 {NSInvalidValue={(.+)}})

Code:
var error: NSError?
let regexp = NSRegularExpression(pattern: "{(.+)}", options: .CaseInsensitive, error: &error)
println("error = \(error)")

I cannot find what's wrong with this pattern. I am using regex101.com page and it works there.
Thank you in advance!
Edit
I see that escaping curly brackets (\\{(.+)\\}) solves problem with error but then I've got {=2} instead of =2.
Comment: Your answer should work. But it's not as standard. Many languages etc don't even let you do lookarounds, but most allow capture groups.
Answer: This is a peculiarity of NSRegularExpression and perhaps more so NSTextCheckingResult. Your captured range is actually the range at index 1 of your NSTextCheckingResult result instance.
An example:
let rx = NSRegularExpression(pattern: "\\{(.+?)\\}", options: .CaseInsensitive, error: nil)!
let str = "abc{=2}"
let strRange = NSMakeRange(0, count(str))

rx.enumerateMatchesInString(str, options: nil, range: strRange, usingBlock: { result, flags, stop in
    if let range0 = result?.range {
        println( (str as NSString).substringWithRange(range0) ) // "{=2}"
    }
    if let range1 = result?.rangeAtIndex(1) {
        println( (str as NSString).substringWithRange(range1) ) // "=2" <-- this is what you want!
    }
})

For each NSTextCheckingResult instance, the range at index 0 is a range representing the capture of your entire pattern (the range property is a shortcut for index 0). Your captures groups' ranges are held at indexes 1 and beyond. From the NSTextCheckingResult docs rangeAtIndex: method:

A result must have at least one range, but may optionally have more (for example, to represent regular expression capture groups).

The simplest way of understanding this is to imagine you provided a regex pattern with no capture groups. What would matched and represented by an NSTextCheckingResult instance? The entire matched pattern!
It would be good practice to use NSTextCheckingResult's numberOfRanges property to make sure you have more than 1 range captured before you try to access your capture group's range. If you are using one capture group, you should expect numberOfRanges to be 2 if your capture group finds a match.
Finally, although this was not necessary, I added the ? modifier to your capture group (.+) to make (.+?). Your pattern was originally greedy inside the capture group, and the ? makes the pattern non-greedy. I find non-greedy to be more predictable in general when working with regular expressions.

I should also mention the reason your solution works (with the result at index 0). By using the lookahead/lookbehind, you have effectively excluded the {} braces from your pattern completely. If you check your result, you should see that your capture group result actually exists at index 1 (but gives the same result as index 0).
Comment: Thanks, spent a while combating this with ghetto range offsets.
Answer: I fixed this using different pattern. I don't know now if regex101.com matches it wrongly and correct match for my pattern is {=2} instead of '=2'.
I used positive lookbehind and positive lookahead to match this. This is the pattern:
(?<=\\{)(.+)(?=\\})


Dishwasher - valve on water pipe designed as not to be opened

Question: I'm connecting dishwasher in my new place and I'm baffled by the valve on the pipe. I swear it looks like it was designed so that it won't be opened. Unless it doesn't turn... but this is ball type.
In case it helps: I'm in the UK. Not being British I can't think of any way to open it...
Help?

There is small protrusion from the side of the white pipe which prevents me from turning. Weird, to say the least.
Comment: The photo is washed out so it's hard to see exactly what's going on, but it looks like there might be a small screw on top of the shut-off lever, can you take that screw off, remove the lever, and turn it 180 degrees so it's no longer blocked?
Comment: Looks like that valve is a quarter-turn mini lever ball valve, and currently turned off. Push the orange lever towards the grey pipe. They have a stop on them so that they can only move 90 degrees in either direction.
Comment: @Johnny - You were correct. After removing the lever I was able to open the valve. I was actually thinking it was something like this, but after removing the screw the lever would not budge, even after applying pliers and pulling up (carefully, so as not to damage anything). So gave up and asked about it here. Thank you for confirmation.
If you can convert your comment to answer I will mark it as accepted.
Comment: I agree Johnny , that or the Handel is 90 out. +
Comment: Even if that protrusion wasn't there it looks as though the screw-on hose connection would also be too close to allow the lever to turn. Can you push or pull it up or down at all?
Answer: The photo is washed out so it's hard to see exactly what's going on, but it looks like there might be a small screw on top of the shut-off lever, can you take that screw off, remove the lever, and turn it 180 degrees so it's no longer blocked?
Answer: It's a washing machine / dishwasher valve, probably with a check valve judging by its size - similar to http://www.screwfix.com/p/washing-machine-valve-with-check-valve-15mm-x/27660
Usually they open with the handle pointing away from 3/4" / service side.
It looks pretty corroded so you may struggle. You could replace with another compression fit (it's a 15mm to 3/4") or use a push-fit alternative
 http://www.johnguest.com/speedfit/product/valves/appliance-tap/
If you go down the push fit route and the existing white pipe is plastic, you need to cut the pipe square with a the proper tool and use a pipe insert.
Comment: It's very similar, but not quite the same valve as the one you linked. Thank you for the answer, though. I may replace it at some point, because my idea of a shut off valve is not in the least similar to the idea that's implemented in my new home... Unless it was one to build as cheap one as possible, not the one that works well in an emergency...


JSF 2: sharing scope among specific users

Question: i'm not sure if what i want is possible, but still...
i want to share a data among users, like done here.  however, unlike this example, which uses ApplicationScope to share the data, i want the data to be shared not among all users, but only for groups of users (something like private chat rooms, and not a public space as in that example).
currently i use ViewScope but in order to update the display of the participants, use the hack i found here, but this solution isn't very stable, as it throws JS error occasionally.
is there any sort of reasonable solution for my problem?
cheers,
eRez
Answer: Hold them in a Map in an application scoped bean where the map key is the group identifier.
E.g.
@ManagedBean
@ApplicationScoped
public class ChatManager {

    private Map<Group, Room> rooms;

    // ...
}

with
@ManagedBean
@ViewScoped
public class GroupChat {

    @ManagedProperty("#{chatManager.rooms[user.group]}")
    private Room room;

    // ...
}


Defiant Electronic Deadbolt does not retract fully

Question: Hi I installed a Defiant Electronic Deadbolt and for the past couple weeks it is not always opening properly. What happens is the bolt goes to retracts about 1/2 way and sort of sticks. Eventually the door opens and of course the lock itself errors and throws the red led.
Any Ideas? I know it was an inexpensive lock but still do not want to swap it out if there is a simple fix.
Comment: You need to determine if it is dragging on the strike plate or if it is rubbing in the deadbolt itself.  Would also try a drop of 3in1 oil on the deadbolt.  Other possibility is binding on the cam bar possibly from miss alignment.
Comment: What model is it?
Comment: Does it always slide in and out correctly when the door is open?
Comment: I'd look for physical blockage, either inside the lick cavity or binding the bolt.
Comment: I'd use [LockEase](https://www.amazon.com/gp/aw/d/B000CIJUGA/ref=mp_s_a_1_1?ie=UTF8&qid=1480811840&sr=8-1π=SY200_QL40&keywords=lock+ease&dpPl=1&dpID=417G7eiU2wL&ref=plSrch) rather than 3in1 oil.  Over time 3in1 oil will both attract dirt and dry/harden.  Lock ease is dry graphit in a quick evaporating and penetrating liquid, it won't gum up in the future. @spicetraders
Comment: Thanks all, I took it apart sort of and adjusted both plates, added a little dry lube from the trailer and so far so good
Answer: Answer from a comment made by the OP 6 years ago:

I took it apart sort of and adjusted both plates, added a little dry lube from the trailer and so far so good


Assertion to check array contents for duplicate values

Question: I have an array logic [254:0][7:0] array. By design, this array must consist all values from 0 to 254 exactly once.
I want to write a SystemVerilog assertion to test it.
So far, I came up with something like this:
    logic update_array_d;
    bit [254:0] a_array_dup_mask;

    always_ff @(posedge clock, negedge arstn)
        if(!arstn) update_array_d <= 1'b0;
        else update_array_d <= update_array;

    always_comb begin
        a_array_dup_mask= '0;
        if(update_array_d) begin
            a_array_dup_mask= '1;
            for(int i=0; i<254; i++)
                a_array_dup_mask[array[i]] = 1'b0;
        end
    end
    UNIQUE_ARRAY: assert property (
        @(posedge clock) disable iff (!arstn)
        update_array_d |-> a_array_dup_mask == '0
    );

Is there a more elegant way to implement it?
Answer: The code looks fine as long as it works for you and you find it easy to understand.

You could also consider this approach.
You declared array as a packed array.  Had you declared it as an unpacked array, such as:
logic [7:0] array [255];

then you would have been able to use the unique array method.  Refer to IEEE Std 1800-2017, section 7.12.1 Array locator methods.  But you would have also needed to declare an intermediate queue variable as well.  Whether this is more elegant is debatable.  Something along the lines of:
logic [7:0] array [255];
logic [7:0] q [$];
q = array.unique();
if (q.size() == $size(array)) // there are no duplicates in the array


Number after print_r output?

Question: I have the following PHP code:
<?php

  $array = ["test", "1", "2", "3"];

  $id = 0;

  echo "ID: 1 -
",  print_r($array), "

";

When I execute the code, the output is the following:
ID: 1 - Array
(
    [0] => test
    [1] => 1
    [2] => 2
    [3] => 3
)
1

If you look closely, you will notice a number after the array output of print_r. Why is this number showing up and is there a way to stop it from showing up?
Comment: `print_r($array, true)`
Comment: @splash58 Oh haha. Do you know why the number is showing up though?
Comment: By default `print_r()` writes output instantly. To add the output of `print_r()` inline so to speak you have to tell it not to output to the browser instantly using parameter 2 and setting it to `true` You are seeing the `1` as its the return value from the function call i.e. true
Comment: last 1 - return from print_r
Answer: Calling print_r() without a second parameter outputs the value and then returns true - which is the 1 your getting in the output.  You probably want to use print_r($array, true) to get it to return the value as a string and then be able to wrap it in the HTML tags you want.
Comment: Oh ok, makes sense thanks. Will accept the answer once possible.
Answer: print_r() without it's second argument will return boolean true, which turns to "1" when converted to a string.
Add true as the second parameter to make print_r return it's output.

Number after print_r output?


cannot save ArrayList to sharedpreferences

Question: I try to save an arrayList to sharedPreferences so as to load to recyclerview each time i enter the recyclerview activity, but it does not seem to work. I use a custom ClothModel and also i use gson library. Does sb can solve this issue?  My code is below
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_recycler_view)

    val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
    val layoutManager = LinearLayoutManager(applicationContext)

    clothesAdapter = ClothesAdapter(clothList)

    recyclerView.layoutManager = layoutManager
    recyclerView.itemAnimator = DefaultItemAnimator()
    recyclerView.adapter = clothesAdapter

    var bitmapStr = intent.getStringExtra("bitmapStr")

    thread {
        val url = URL(bitmapStr)
        bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream())
        this.runOnUiThread {
            prepareClothData()
        }
    }
}

private fun saveClothList() {
    val sharedPreferences = getSharedPreferences("preferences", MODE_PRIVATE)
    val editor = sharedPreferences.edit()
    val gson = Gson()
    val json = gson.toJson(clothList)
    editor.putString("clothlist", json)
    editor.apply()
}

private fun loadClothList() {
    val sharedPreferences = getSharedPreferences("preferences", MODE_PRIVATE)
    val gson = Gson()
    val json = sharedPreferences.getString("clothlist", null)
    val type: Type = object : TypeToken<ArrayList<ClothModel1>>() {}.type
    clothList = gson.fromJson(json, type)

    if (clothList == null) {
        clothList = ArrayList()
    }
}

private fun prepareClothData() {

    try {
        loadClothList()
    } catch (e: Exception) {
    }

    val cloth = ClothModel1("title", bitmap)
    clothList.add(cloth)

    saveClothList()

    clothesAdapter.notifyDataSetChanged()

}

Answer: Set the debugger to break on the line clothList = gson.fromJson(json, type) to see if clothList is populated as you expect. Also, it seems that you are recreating clothList with that line of code but do not inform the RecyclerView that it has a new data set to work with. See RecyclerView#swapAdapter() and RecyclerView#setAdapter().


Python, Pyramid, Chameleon : parse Chameleon template in string

Question: I have a Chameleon template stored as a string. I've got it in this form, because I need to do my own processing first. Following that, I want to parse the template, possibly using 'render to response':
render_to_response('templates/foo.pt',
        {'foo':1, 'bar':2},
        request=request)

However, I can't figure out how to parse a template stored in a string, rather than pointing to one in a file. Is this possible?
Answer:
However, I can't figure out how to parse a template stored in a
  string, rather than pointing to one in a file. Is this possible?

It seems so, according to the api documentation:
from chameleon import PageTemplate

t = PageTemplate('some string template')
rendered_content = t.render(encoding='utf-8')

Comment: Thanks Burhan! That's what I was looking for. I've made a slight change to your answer, adding the required 'request' argument.
Comment: Are you sure about `request`? It could be that you need to pass the variables that are in the template, so its not just the actual HTTP request. In the snippet I posted there are no variables to interpolate, hence no other arguments to `render`. If you had `Say hello ${foo}` then you would pass in the substitution for `foo` to `render(encoding='utf-8',foo='bar')`.
Comment: When working with templates in the context of my question (Pyramid), passing the request was necessary.


Follower's inventory doesn't show up for trade

Question: I came across this disturbing problem. I have Mjoll the Lioness as a follower, and I wanted to trade some things with her. I go to the "I want to trade a few things with you" dialog, and she responds "I can carry a good bit of gear", but the inventory doesn't show up at all.
I try the console command "openactorcontainer" but still her container won't show up. I can trade with other followers and the console command works on them but not to Mjoll.
How can I make her inventory show up??
Answer: What i did is, I opened the console, clicked on Mjoll and typed 'removeallitems player'. With this, I removed all of her items and added the to my inventory (so I don't lose anything I had given her).
After that I spoke to her and told her she was naked. She immediately wore her default armor. After that I could be able to trade with her again. I don't know which part of this process solved my problem, or if it was random.
By having her stuff, she had her default armor in 5 copies (cuirass, helmet, etc etc). This is due to a bug in the game where each follower, if dismissed, and aquired again, will add the default items in his/her inventory (instead of adding just the missing ones, or the ones that there is no replacer). If you dismiss and aquire the follower 5 times, he would have his initial armor five times in his inventory.
Comment: To use the removeallitems you have to: 1) open the console, 2) CLICK on the NPC who's items you want to remove (so that he is the target of the command), then 3) type *removeallitems ###*. The *###* part is the id of the NPC or player that the items will be TRANSFERED to. If you omit this part, all items from the target NPC will be removed. If you put a refId there, all items of the target NPC will be transfered to the NPC (or player) who has this id. SO, I wanted all of Mjoll's stuff to be transfered to me. Using the console, I clicked on Mjoll, and I entered *removeallitems player*
Answer: You can use the Ultimate Follower Overhaul mod to make sure that all items that your follower has in their inventory is viewable (and removable).
It has a feature that can "convert unmovable, invisible outfit follower has to regular gear that can be removed so followers will wear whatever player places in their inventory".
I believe it works for all items, not just outfits. It is commonly used to fix the issue where the follower insists on equipping a particular weapon or wearing a particular armor, which is not viewable and removable in a follower's inventory.
A usual occurrence of this issue is the 'invisible' Hunting bow that some followers also prefer to use, despite being given a better bow. The Unofficial Skyrim Patch (USKP) fixes that issue.

All followers will no longer have invisible Hunting Bows that can't be removed from them that they would use even in preference to much better bows they were given; they will now be visible and can be removed from the follower normally

Full USKP changelog
Comment: I am not sure if the hunting bow issue has been fixed. I already use all the three unofficial Skyrim Patches (the main one, with the ones for dawngard and hearthfire), and the Unlimited Follower Overhaul.

I had married Mjoll and parted ways with her before I had activate all those mods and patches though. I have been partner with Serana from Dawnguard. Since i hated having only one follower, I installed UFO and the unoficial patches, and after that I re-reqruited Mjoll, who also happen to be my wife. Maybe the problem existed before the patches, and it just wasn't fixed.
Comment: But my problem here, was NOT Mjoll's stuff. My problem was that I couldn't get her to even OPEN her inventory to me, to be able to trade with her. Even using the console with the command "openactorcontainer" on her, could not open the inventory. Seemed like a bug to me. I could do it with everyone else, but not with her. It happened that the problem solved "accidentaly" after I was playing around with console commands and I don't really remember what I did. I posted my solution as an answer though, here.
Comment: @Saysmaster I see. I initially thought that her inventory opens up, but her items do not appear.
Answer: I had the same problem and I managed to fix it (with a whole butt load of work.) I figure that the inventory only opens once appropriate dialogue has been audibly spoken, meaning that subtitles don't count. By appropriate dialogue I mean the words followers say when you ask to trade with them like the infamous "I am sworn to carry you burdens."
If you have any mod that messes with follower dialogue then that might be the culprit. All it took for me was an uninstall and the problem was solved (after 3 days of torture.)


Find the number of ways to put the balls into the boxes with no restrictions?

Question: Find the number of ways to put the 7 balls (Distinct) into the 3 boxes (Indistinguishable) without any restrictions ?

Can I apply stirling formula of 2nd kind in this case ?
Answer: Yes you can, Stirling numbers of the second kind give you the correct answer for this one:

The Stirling numbers of the second kind, written ${\displaystyle S(n,k)}$ or ${\displaystyle \lbrace \textstyle {n \atop k}\rbrace }$ or with other notations, count the number of ways to partition a set of ${\displaystyle n}$ labelled objects into ${\displaystyle k} $ nonempty unlabelled subsets

You have no restrictions so I assume you can have empty boxes. Therefore the total number of ways will be
n.o of ways to put all balls in 1 box + n.o of ways to put all balls in 2 boxes + n.o of ways to put all balls in 3 boxes.
There is only 1 way of having everything in the same box. Using the stirling numbers, there are $S(7, 2) $ ways of having the balls in 2 different boxes and $S(7, 3) $ ways of having them split between 3 boxes. Now just use the recurrence formula to calculate it.
Comment: You can because we took separately each case into consideration: 2 boxes empty, 1 box empty and no boxes empty
Comment: Yes thanks for clarification !! Okk just one more doubt, What if the boxes are distinguishable ? I know then it is 3^7, but i want to know with stirling numbers. I think we need to multiply all the cases by r!. Am i right ?
Comment: @Willturner yeah sure: i made a mistake. For 2 empty boxes you have $S(7,1) $ 1-partitions and then you have ${3\choose {1}} $ ways of deciding where to put it: $3\cdot S(7,1) $. For 1 empty box you have $S(7, 2) $ partitions and ${3\choose {2}} $ ways of distributing them hence making ${3\choose {2}}\cdot S(7,2) $ ways. Similarly for $S(7, 3) $
Comment: You must have a problem in your calculations, probably in the calculation of some Sterling number. Ensure you are computing $3S(7,1) + 3×2S(7,2) + 3! S(7,3) $ and that $S(7,1)=1, S(7,2)=73, S(7,3)=301$.
Comment: Can you please show ?
Comment: Done. Yoy should now be able to finish the exercise
Comment: Usually, we apply stirling such that no box is empty, but we can still apply like this right ?
Comment: For both distinct, it is =>  1!. S(7,1) + 2!. S(7,2)  + 3! .S(7,3) = 1933, but the answer is 2187. Can you please rectify me ?
Comment: Still not getting 2187.
Comment: My Bad !! Got it now . Thanks for both the questions.


PhoneGap for mobile and Appcelerator for desktop+mobile?

Question: It seems that PhoneGap is only for mobil devices while Appcelerator is for desktop and the mobile, am I correct?
Answer: yes Appcelerator can be used for both
http://www.appcelerator.com/products/titanium-cross-platform-application-development/
have not actually used it but did some investigation
Comment: Then the question if I can create desktop apps with PhoneGap. It seems to not be the case.
Comment: There are seeds of a desktop version, but limited: http://github.com/phonegap/phonegap-mac


Retrive average rating and total number of rating for each and every product in Laravel

Question: I'm trying to build a product rating system in Laravel. I have two different tables product and review where all products and reviews data are stored.
product Table has fields like id, name, price, etc.
review table has fields like id, product_id, rating, etc.
One product can have many reviews/ratings. I need to fetch all products with each product's average rating and total rating. I can fetch all products like the below:
$product = Product::all();

but how can I get average rating and total rating(count) also for each and every product? Every answer will be very helpful for me and admirable.
Answer: I recommend using query builder since I don't know your Models.
$productId = 1; // example product id

$ratingCount = DB::table('review')
->where('product_id', $productId)
->count();

$averageRating = DB::table('review')
->where('product_id', $productId)
->avg('rating');

$data = [
"ratingCount" => $ratingCount,
"averageRating" => $averageRating
];

return $data;

Edit
Our you can get each product average rating in one data with this:
$products = DB::table('product')
    ->leftJoin('review', 'review.product_id', '=', 'product.id')
    ->select(['product.*',
        DB::raw('AVG(review.rating) as ratingsAverage')
        ])
    ->get();

Hope this answer work and help you
Comment: Thanks for your answer but this will work for a single product only and also when I know the product_id. But I need this for all the products from the Product table. When I retrieve all products data from the product table, the average rating and total rating should include with that. So that I can show all the products with their rating into a single page. Is there any way to do that with a single eloquent query or query builder?
Comment: I got your point. What is relation name between Product Model and Review? I assume it named `reviews` with hasMany relation. Then try this ```$products = Product::with(['reviews'])
    ->leftJoin('review', 'review.product_id', '=', 'product.id')
    ->select(['product.*',
        DB::raw('AVG(review.rating) as ratingsAverage')
        ])
    ->get(); ```


How can I resume the match when playing offline with bots?

Question: Whenever I enter offline with bots, the match starts paused:

Using pause and unpause commands in the console apply a pause on top of the match pause.
How can I resume the game?
Comment: Did you also try pause/break? And I believe there was some console command like `pausable` or `sv_pausable` to make the game pause-able.
Answer: This appears to be something caused by spectating matches in GOTV in the same session as trying to play with bots. Restarting the game and going to the offline match first before anything else works fine.
Answer: Just type the following command into the console:
mp_unpause_match

Answer: sv_pausable 1

in order to have the ability to set :
pause

and
unpause


Time format not working in dc.js LineChart

Question: I have the following parsing code of time in h:m:s format
<code>            var ISO8601format=d3.time.format("%Y-%m-%dT%H:%M:%SZ");
            var hoursandminsformat=d3.time.format("%H:%M:%S");
            e.time=hoursandminsformat(ISO8601format.parse(e.time));
</code>
I have a json file with reading at different times from different sensors.
Sample data is=
<code>[
{"id":1,"time":"2015-03-29T20:32:24Z"},
{"id":2,"time":"2015-03-29T20:32:24Z"},
{"id":3,"time":"2015-03-29T20:32:24Z"},
{"id":1,"time":"2015-03-29T20:33:24Z"},
{"id":2,"time":"2015-03-29T20:33:24Z"},
{"id":3,"time":"2015-03-29T20:33:24Z"},
]
</code>
I am going to plot a dc.js rowchart where there will be time in minutes in the x axis and frequency in the y axis. I am using the following code to do this. But its returning NaNs.
<code>var freqchart= dc.lineChart("#chart1");
var countByTime=ndx.dimension(function (d) {return d.time; });
var freqbyTimeGroup = countByTime.group().reduceCount();
freqchart.width(400).height(200).transitionDuration(500)
    .dimension(countByTime).group(freqbyTimeGroup).elasticY(true).x(
                d3.time.scale().domain([d3.min(data,function(d){return d.time;}),
                                        d3.max(data,function(d){return d.time;})])).xUnits(d3.time.minutes).yAxisLabel("Frequency").xAxisLabel('Time').elasticX(true)
</code>
How can I solve this problem? Here is the jsfiddle that's not working
Comment: Why are you formatting the dates as strings before passing them to crossfilter? `d3.time.scale` is not going to work with strings. I would suggest doing the parse but not the format before crossfilter, and leave the formatting for the ticks. But there must be some reason, as you had this working correctly in another question.
Comment: I am parsing to time formtat using this code var ISO8601format=d3.time.format("%Y-%m-%dT%H:%M:%SZ");
            var hoursandminsformat=d3.time.format("%H:%M:%S");
            e.time=hoursandminsformat(ISO8601format.parse(e.time));
Comment: Yes, I tested your code and it is formatting the time properly. What I question is why you would format the date as a string before passing it to crossfilter. Ordinarily you will use Date objects in crossfilter and d3, and then only format them to strings for the ticks and labels and such.
Comment: Actually the data I am getting is giving me timestamp in the format given.. I want to show only H:M in the x axis. But its returning NaNs
Comment: The data is coming from hbase and the time format coming is "2015-03-29T20:33:24Z"
Comment: You gave the jsfiddle that worked for separate time. But not working in this case rather its returning NaNs
Comment: I don't think I am making myself clear, but I'm not sure how I can explain this differently. Your first code block, which I guess is running before you pass the data to crossfilter: that code is turning the dates into **strings**. Then you use a bunch of functions for the chart which expect **Dates**. I'm pretty sure this is where your NaNs are coming from, but please post another fiddle if this doesn't help.
Comment: Here is the updated jsfiddle. Can you please have a look at it? http://jsfiddle.net/6e67uzfn/18/
Comment: You can see this fiddle that times are coming correctly http://jsfiddle.net/6e67uzfn/20/
Comment: What is the mistake I am making. I am confused why should this happen. Its exactly your code and data in H:M:S format is right also
Answer: Hurray I got the solution. Here is the code
<code>   var data=[
    {"id":20,"time":"2015-03-29T20:32:24Z","speed":20},
    {"id":21,"time":"2015-03-29T20:32:24Z","speed":15},
    {"id":22,"time":"2015-03-29T20:32:24Z","speed":16},
    {"id":23,"time":"2015-03-29T20:33:25Z","speed":14},
    {"id":20,"time":"2015-03-29T20:33:26Z","speed":20},
    {"id":21,"time":"2015-03-29T20:34:24Z","speed":10},
    {"id":22,"time":"2015-03-29T20:34:24Z","speed":15},
    {"id":23,"time":"2015-03-29T20:35:24Z","speed":15},
]
    // The datset is much larger with many detector. This is sample
        var dateformat=d3.time.format("%H:%M:%S").parse;
        var ISO8601format=d3.time.format("%Y-%m-%dT%H:%M:%SZ");
        var hoursandminsformat=d3.time.format("%H:%M:%S");
    data.forEach(function(d) {
        d.time=d.time.substring(11,19);
        d.time=dateformat(d.time);
    });
</code>
Here is the working jsfiddle


Quick 2-color quantization for small images

Question: So I have a small (8x8 pixel) image in 24-bit color. I want to be able to (quickly) generate a color-quantized version of the image that only has two colors.
One naive approach is to cluster a luma histogram of the image (1-dimensional clustering is easier than the 2D or 3D case). The chroma can be generated by averaging the pixels in each cluster. Unfortunately, this technique doesn't really work well if the the image has uniform luma.
Any ideas?
Answer: The approach I would use, and indeed have used, would be to

run principal component analysis on your image data to generate "the" main axis
Project your pixels onto that axis (i.e. compute the dot product of each colour value against the axis)
Using the dot prods, sort the the colour values from smallest to largest and
Find the "partitioning" point, i.e. that splits smaller values in one set, larger in the other, that minimises, say, the mean squared error. i.e. each partition is represented by the average of its members and you compute the total error.

This last step, i.e. finding the best partition, can be done in linear time by starting with the "least" item in partition "A", all the rest in partition "B", and progressively shifting the next smaller over from "B" to "A, one at a time. You just need to keep separate sums of the values and sums of squares of the values for each partition and then you can compute the total MSE relatively cheaply.
Note that the function should follow a quadratic curve so it (should) begin decreasing until it reaches the minimum. Once it starts increasing again you can stop the search.
A cheap way to find the principal axis is to first generate the 3x3 covariance matrix and then use the "repeated matrix vector multiplication" trick to find the principal eigenvector (i.e. the principal axis)
Comment: Hmm this seems promising; I'll try it out and see how it goes
Comment: Alternatively, if you are after something that is quick to code (but not likely to be quite as good) another possible approach would be (a) find the average, (b) find the colour furthest from the average -call it X, (c) find the colour furthest from X, call it Y, then (d) run several iterations of k-means (https://en.wikipedia.org/wiki/K-means_clustering#Standard_algorithm) starting with X and Y as the initial reps.  It might do the trick.


Change default driver of network printer

Question: In Ubuntu 12.04, how do I set the driver for a network printer?
It used to be all in the wizard provided by system-config-printer, but now of course the system itself decides which driver to pick and I really need a different one than the default driver.
How do I do this?
Answer: Open System Settings, and click on Printers.  Once the window opens, right click on the printer that you want to change its driver, and choose Properties.

When the properties windows opens, click on Change to the right of Make and Model under Settings.

Once that window opens, choose driver source, and click on Forward.
Comment: Thanks. I just don't get why Ubuntu developers loooove to move things around every few months. It's extremely frustrating to have to search for settings in new places all the time.


Storing data locally on the client in AppEngine/GWT

Question: I'm currently developing an application with Appengine and GWT. I have to send a lot of data from an Android phone to the GWT client. My question is, is there a way or an API that I can store or cache this data on the local client?
The data which I'm talking about is just a lot of text from a database from Android. It would be awesome if I could store it somehow that the AppEngine server doesn't have to load the data and send it to the client every time the user connects to my application.
Answer: Use GWT's Storage API. The application will still need to go to the server if the local copy of your data is deleted or if the browser doesn't support HTML local storage.


calculating 2D rms in python

Question: I have a Nx2 array that stores the x,y coordinates of N different points. I have to calculate the spread of the data (I'm thinking of the rms). Are there any functions in scipy that do this job? If not, what is the most efficient way to compute this?
Comment: Have you actually done a search to see whether that's implemented in python/scipy? I come up with lots of results regarding that. Is speed really that important? What's the size of N? Have you tried implementing the RMS equation straight up? Is there any code we need to base improvements on? Have you benchmarked anything and what is an acceptable performance?
Answer: The root mean square is the standard deviation:
In [100]: np.random.seed(2015)

In [101]: A = np.random.random((10,2))

In [102]: A
Out[102]:
array([[ 0.73759523,  0.51757155],
       [ 0.88418945,  0.45172399],
       [ 0.94467608,  0.82238998],
       [ 0.06360332,  0.93889193],
       [ 0.33245351,  0.62721741],
       [ 0.00321837,  0.70402271],
       [ 0.07105811,  0.05554161],
       [ 0.28901979,  0.28649662],
       [ 0.2688956 ,  0.20721542],
       [ 0.25877509,  0.63308562]])

In [147]: np.std(A - A.mean(axis=0))
Out[147]: 0.29777164364514941

which is equivalent to:
In [146]: np.sqrt(((A - A.mean(axis=0))**2).mean())
Out[146]: 0.29777164364514941

calculating 2D rms in python


PiCamera not detected

Question: I started working with a fresh Raspi. Enabled the camera module from raspi-config, rebooted my RPi.
When I then ran this simple code:
from picamera import PiCamera
import time
camera=PiCamera()
camera.start_preview()

I get this long error saying Camera is not enabled. Try running 'sudo raspi-config' which I already have.
Additionally I tried running vcgencmd get_camera it says supported=1 detected=0
I have inserted my camera in correct orientation Double ensured it. But I'm still stuck. Appreciate any help.
Comment: your question would probably get a better answer on [Raspberry Pi Stackexchange](https://raspberrypi.stackexchange.com/)
Comment: Try taking a picture with `raspistill` to see if the hardware is found.
Answer: Maybe you have some issue when connect the camera with raspberry pi.

Maybe your charger is not well enough to give the proper power for raspberry pi. or
Maybe the cable which connect the camera and raspberry pi is broken. or
Maybe the slot for connecting the camera is broken.

PiCamera not detected


Uploading a file via an iPhone App

Question: Actually i am just trying to develop Box like app for iphone for practice, u may look over the link given below
Here's a link! for example
The  application should be capable of uploading his files of format .ppt, .doc, .jpeg, .txt, zip, etc. Just for sake of sever i am trying MAMP,  How can I upload the data to my local server.
Comment: Please go through these links [link1](http://forums.dropbox.com/topic.php?id=22090) [link2](http://bluemandala.com/buddypress-plugin/54/testing-local-mamp-website-on-iphoneipad-or-parallels/) [link3](http://stackoverflow.com/questions/4063119/test-local-websites-with-mamp-on-iphone) [link4](http://nclud.com/sketchbook/view-local-websites-iphone-ipad/) [link5](http://stackoverflow.com/questions/7741542/storing-data-on-a-server-from-an-app) [link6](http://stackoverflow.com/questions/4114124/make-virtual-host-available-through-local-network-for-iphone) may be helpful for you.
Answer: You'll have to figure out the server-end on your own, but I'm a big fan of using the ASIHTTPRequest library for this type of thing.  Here's their docs on how to upload data:
http://allseeing-i.com/ASIHTTPRequest/How-to-use#put_requests_and_custom_posts
Comment: thanks sir, it seems it will really help...

Uploading a file via an iPhone App


KSP throttle off after set time

Question: Is there a way I can automatically turn off a burn after a pre-set countdown?
For example, I have a 2 hour burn to do, so I want to start the burn, then leave it to do it's thing and automatically throttle down after the 2 hours without me needed to be at my computer.
Alternatively, I would like the throttle to automatically switch off when the maneuver gets to it's "green tick" zone.
Comment: Generally, asking for mods that do certain things are seen as recommendations, and off-topic. Better to just ask how to do it. Answers can still recommend mods.
Answer: I use MechJeb for this extensively. Once I was able to "master" the launching and orbit, and it started to become tedious, MechJeb did an extremely efficient job of getting into orbit and performing orbital transfers.
One thing of note, if you're playing on Career mode, the MechJeb parts that allow this functionality need to be unlocked via the science tree. (If you would otherwise feel guilt about using a mod for this, having to earn it may alleviate said guilt.) :)
Comment: MJ also helps a lot when you're deploying Kerbol-synchronous satellites for the LOS communications mods.

KSP throttle off after set time


C++ Behavior of priority_queue pop() and top() when queue is empty

Question: C++11.
If I try to pop off of an empty priority_queue, then I get a compile time error. Specifically,
#include <iostream>
#include <queue>

int main()
{
    std::priority_queue<int> pq;
    int x = pq.pop();
    std::cout << x << std::endl;
}

yields the compile-time error:
In function 'int main()': 7:20: error: void value not ignored as it ought to be

I am surprised that this is a compile-time error and not a runtime error, but that is another discussion.
What I don't understand is why the top method wouldn't do the same thing. In fact, if we change pop to top the code actually compiles and runs (albeit with a bizzare output). Specifically,
#include <iostream>
#include <queue>

int main()
{
    std::priority_queue<int> pq;
    int x = pq.top();
    std::cout << x << std::endl;
}

This code compiles, runs, and exits normally, but produces no output! It literally prints nothing. I do not understand how that can be.
Here are my questions:

Is the behavior for pop and top defined if the priority_queue is empty? I don't see any mention of this condition in the docs.
How is there no output in the second case? top returns a constant reference. So it must be pointing at something. I would imagine that it simply interprets whatever piece of memory it is pointing to as an integer. But that doesn't seem to be happening. It seems like the integer is behaving something like a nullptr.
Comment: I'm sorry but a RTFM is required here https://en.cppreference.com/w/cpp/container/priority_queue/pop
Comment: The [`pop`](https://en.cppreference.com/w/cpp/container/priority_queue/pop) function doesn't work as you expect that is should. The error message is spot-on. And is has nothing to do with the queue being empty or not (which can't be detected by the compiler!).
Comment: And attempting to get a reference to an element that doesn't exist (with e.g. the [`top`](https://en.cppreference.com/w/cpp/container/priority_queue/top) function) leads to [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior). You must always make sure that the queue is not empty before calling `top` (or `pop`).
Comment: Docs say the behaviour of `top` is equal to calling `front` method on underlying container. By default the underlying container is `std::vector`, and calling `front` on empty `std::vector` is UB.
Comment: The `pop` understanding was a dumb error. But I am confused by the UB comments
Comment: @YSC Your turn to translate RTFM into some friendly like Read the fine manual, or such now ;-)
Comment: Specifically, I thought that UB means that you don't know what you get in the variable `x`. But since the code runs and terminates normally, I assumed that x must have some value. What this value is should be undefined, but my understanding is that it must be pointing at SOME piece of memory.
Comment: It was not clear to me that UB behavior meant that, for instance, an integer might not even be interprettable as an integer after that point in the code.
Answer:
int x = pq.pop();

pop returns void. It is ill-formed to assign void to a variable. As the error says:

 void value not ignored as it ought to be

On the other hand:

int x = pq.top();

It is well-formed to assign an integer to a variable.

Is the behavior for pop and top defined if the priority_queue is empty?

No. The behaviour is undefined (for std::priority_queue<int>. The behaviour may be defined for other underlying containers).

How is there no output in the second case?

The behaviour is undefined.

Specifically, I thought that UB means that you don't know what you get in the variable x.

That's correct, but an incomplete description of UB. UB means that you cannot predict anything about the behaviour of the program.
Comment: @bremen_matt [Happy reading](https://stackoverflow.com/q/54120862/560648)! (Moral of the story: don't underestimate how _insanely, ridiculously, hugely complex_ is the mechanism that translates your source code to something that a computer can understand.)
Comment: I have seen cases, typically involving pointers, where clearly you can get really unexpected behavior. But that it happens in such a simple case really surprised me.
Answer: The behavior of calling std::priority_queue::top on an empty priority_queue depends on the underlying container.

Reference to the top element as if obtained by a call to c.front()

As your code showed, the default argument std::vector is used as the underlying container, and the behavior of calling std::vector::front on empty container is undefined; which means anything is possible.

Calling front on an empty container is undefined.

It's similar for std::priority_queue::pop, which will call pop_back on the underlying container; for std::vector::pop_back calling it on an empty container is UB too.

Calling pop_back on an empty container is undefined.

At last, std::priority_queue::pop returns nothing; that's why int x = pq.pop(); won't work (as the error message tried to tell you).
Answer: You are using the priority_queue incorrectly. From the docs on pop():

Return value
  (none)

Yet you try to bind that to an integral variable. This is the same as
void f() {};

int n = f();

and doesn't make any sense. Furthermore, for
int x = pq.top();

we again conclude from the docs that

Reference to the top element as if obtained by a call to c.front()

So the behavior depends on the front() member function of the underlying container. In your example, that's the default one, std::vector, hence from the docs:

Returns a reference to the first element in the container.
  Calling front on an empty container is undefined.

There you are in UB land, hence don't try to conclude anything from the output of your program.


NSNotification postNotificationName in AppDelegate but NSNotificationCenter in ViewController?

Question: I can't get the selector method, receiveChatText, in the NSNotificationCenter to execute and I am wondering if the problem is because the NSNotification postNotificationName is in AppDelegate.m but NSNotificationCenter is in ViewController.m?  I.E. can the postNotificationName know that the NSNotificationCenter is in another viewController file or is that something I need to tell it?
In a viewController.m I have
 -(id)init
 {
self = [super init];
if(self){
    [[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(receiveChatText:)
                                                      name:ChatMessageReceived
                                               object:nil];
 return self;
}

- (void)receiveChatText:(NSNotification *)note {
NSLog(@"received chat text");

}

and in the top level AppDelegate.m file I have the following:
 -(void) didReceiveMessage {
    [[NSNotificationCenter defaultCenter] postNotificationName:ChatMessageReceived
                                          object:nil
                                          userInfo:nil];
 }

Any ideas what could stop receiveChatText from being executed when didReceiveMessage is called?
Answer:
I can't get the selector method, receiveChatText, …

First, it's receiveChatText:, with the colon. This is important in Objective-C —receiveChatText: and receiveChatText do not refer to the same method.
Second, "selector" does not mean what you think it means. A selector is the name of a method. You pass in the selector for the message you want the notification center to send to the observer. That is, you are telling the notification center "when this notification arrives, send a receiveChatText: message to me [the view controller]".

… in the NSNotificationCenter …

The notification center doesn't have a receiveChatText: method. Your observer (self) does, which is why that's what you want the notification center to send the message to.

… to execute and I am wondering if the problem is because the NSNotification postNotificationName is in AppDelegate.m …

No such thing is in AppDelegate.m.
The app delegate posts a notification.

… but NSNotificationCenter is in ViewController.m?

No such thing is in ViewController.m.
The view controller observes for a notification.
As long as the view controller adds itself as an observer before the app delegate posts the notification, this will work. If it doesn't work, either one or both steps did not happen or they happened in the wrong order.

I.E. can the postNotificationName know that the NSNotificationCenter is in another viewController file or is that something I need to tell it?

The notification center isn't in either file. [NSNotificationCenter defaultCenter] is a singleton object, shared throughout your entire application amongst any objects that want to use it. That's how you're able to use it to have the app delegate communicate to the view controller and any other objects that are observing for the notification.
You are sending the default notification center a postNotificationName:object:userInfo: message. This is the same default notification center that you should have previously sent an addObserver:selector:name:object: message. As long as you start observing first, then send the notification to the same notification center, the notification center will be able to dispatch the notification to the observer(s) you added.

Any ideas what could stop receiveChatText

receiveChatText:

from being executed when didReceiveMessage is called?

didReceiveMessage did not post a notification. Assuming the code you showed in your question is accurate, this is not the case.
The view controller is not observing for the notification. Since it starts observing on creation, perhaps it hasn't been created yet. Or, it may be because you've overridden init rather than NS/UIViewController's initWithNibName:bundle:. Be aware of what different classes' designated initializers are; the documentation will usually say.
The view controller is not observing for the notification yet: You posted the notification before the view controller started observing for it (i.e., before you created the view controller).

You might also want to pass the chat text as the object of the notification, or in its userInfo, rather than forcing all observers of the notification to retrieve it from an unspecified source.
Comment: #2 above was the problem.  Previously I created viewController.m from another_viewController.m using initWithNibName.  Then inside viewController.m, as I posted, I had an init.  So I guess the initial initWithNibName overrode the later init.  So I created a viewController, from another_viewController.m, just using init, and the whole thing worked.  Thanks!
Comment: @James: No, `initWithNibName:bundle:` didn't override `init`. Again, you need to think in terms of messages. You implementing (overriding) `init` in your subclass only works when something initializes the object by sending it an `init` message. When it sends the object an `initWithNibName:bundle:` message, there is no reason to expect that that message will hit an `init` implementation instead. If you create it using `initWithNibName:bundle:`, you need to implement that. If you create it using `init`, you need to implement that. You need to implement the initializer (or initializers) you use.
Answer: +defaultCenter is a class method on NSNotificationCenter which will return the same NSNotificationCenter instance every time it is called in a given process regardless of where you call it from.
How is 'ChatMessageReceived' defined? It should be a NSString but is the name 'ChatMessageReceived' a valid symbol in the context of both of your classes?
Comment: ChatMessageReceived is defined as #define ChatMessageReceived @"ChatMessageReceived" in AppDelegate.m.  So yes it is a valid symbol in the context of both of my classes.
Answer: That looks like it should work, as long as the value of ChatMessageReceived is the same in both instances.
Have you used the debugger to verify that the init method in the view controller file is called before the notification is posted in didReceiveMessage?


How to interact with current running command cell in google colab?

Question: Here what the cell looks like
Cloning into 'XYZ'...
The authenticity of host 'github.com (192.**.###.113)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXUpJIGOCWGl7E1spRomTxdCARLviKw6E5SY8.
Are you sure you want to continue connecting (yes/no)?

How to give yes or no to this running command cell?
Answer: There's no easy way to interact with the process once it's running; two options:

Pass yes to the program from the shell, eg echo 'yes' | git ... or just y | git ... (if y works as a response).
If possible, clone via an https path instead of a git one.
Answer: Passing "-y" or "--yes" along with the command works.
For example:
!pip uninstall lightgbm --yes
Comment: This does not work with all CLIs, git clone does not accept --yes
Answer: I made a code line after the question and then typed: --y
it worked!


Running Celery as a Flask app with Gunicorn

Question: I'm running Celery as a Flask microservice where it has tasks.py with tasks and manage.py contains the call to run the flask server.
This is part of the manage.py

class CeleryWorker(Command):
    """Starts the celery worker."""
    name = 'celery'
    capture_all_args = True

    def run(self, argv):
        if "down" in argv:
            ret = subprocess.call(
                ['pkill', '-9', '-f', "my_app.celery"])
            sys.exit(ret)
        else:
            ret = subprocess.call(
                ['celery', 'worker', '-A', 'my_app.celery'] + argv)
            sys.exit(ret)

manager.add_command("celery", CeleryWorker())

I can start the service with either python manage.py runserver or `celery worker -A my_app.celery and it runs perfectly and registers all tasks in tasks.py.
But in production, i want to handle multiple requests to this microservice and want to add gunicorn to serve those requests. How do i do it?
I'm not able to figure out how i can run both my gunicorn command and celery command together.
Also, i'm running other api services using gunicorn in production from its create_app, since i dont need them to run the celery command.
Answer: Recommend to use Supervisor, which allow you to control a number of processes.
step1: pip install supervisor
step2: vi supervisord.conf
[program:flask_wsgi]
command=gunicorn -w 3 --worker-class gevent wsgi:app
directory=$SRC_PATH
autostart=true

[program:celery]
command=celery worker -A app.celery --loglevel=info
directory=$SRC_PATH
autostart=true

step3: run supervisord -c supervisord.conf
Comment: the file names are different supervisor.conf vs supervisord.conf


How are SC2 start locations fair?

Question: If I spawn at the 12 o'clock position typically the mineral line is above my hatchery/nexus/command center.  The workers have to run all the way around the structure to get those sweet blue crystals.  If I spawn at 6 o'clock, they're right there.
This seems like it would also affect future drones hatching from eggs on the wrong side of the base.
Doesn't this result in faster mining in the southern bases?
Answer: There are always some differences in starting locations. Hatchery position is only one of many. Another things - ramp position, configuration of air zone over base (on some locations it's usually bigger that others).
I believe that even on high-top-levels such things aren't statistically significant.
Comment: yea I think the most significant difference is Terran's ability to build add-ons on the wall.
Comment: If the small amount of time is not significant, why do professional players split their workers up when they initially assign them to mineral harvesting?
Answer: you'll lose like a second or so per worker, but that is only the first time, when the worker spawns. In aggregate it is probably a very small difference.
Comment: @Wikwocket, that's true, but only for Protoss and Terran.
Comment: Actually I think once you set a rally point, do newly-created units spawn on the side of the building closest to the rally point? If so, you only lose ~1 second for the starting 6 workers.
Answer: The starting locations are not fair, but they are assigned randomly.
You are guaranteed the same amount of minerals and gas and the same choke size. Other than that everything might vary:

Workers initial spawning position relative to minerals
Orientation of choke / ramp  (important for Terran)
Natural torwards or away from your opponent (important for Zerg)
Cliff (from base) towards or away from opponent (important against Terran - Reaper / Tanks and Protoss - Blink)
etc.

But most of these issues are insignificant on the long run, because you have the defenders advantage (aggressor has to walk to your base) and because important matches are played in a best of X fashion.
The best way to cope with that is to know all the pros and cons of your and your opponents starting location and exploit them to your advantage or take precautions against the weaknesses.
E.g. TvZ close locations is very good for early 2 Rax pressure, but TvZ far locations is very good for Zerg 3 base play.
Answer: As others have said, it is unfair but insignificant in the long run.  Even very early rushes are likely unaffected by the half-second difference in initial worker routing times.  Other seemingly random AI decisions are likely make a bigger difference.
On northern positions however, you have a small advantage in that units attacking your units or base from below are more exposed to targetting.  From the south, units close to the bottom of cliffs are partially occluded by the edge of the cliff itself because of the camera angle.  This is especially noticeable when doing a cannon rush strategy where the first cannon starts below the cliff.
Basically, this is one of a very large number of very small and rarely significant bits of the game left purely up to chance.

How are SC2 start locations fair?


is there cache in ubuntu when run command?

Question: I tried to running command docker in ubuntu 14:04(LTS).

It locates in /usr/bin
When I type "docker" in bash shell then error come up.
no such file or directory in /usr/local/bin/docker

I logged in root account.
After I type "sudo docker" then it execute normally.
Since I typed "sudo docker", just "docker" command excutes normally.
What's happening?
Is there caching system when running program by $PATH?
Thank you! Have a nice day :)
Comment: http://unix.stackexchange.com/questions/5609/how-do-i-clear-bashs-cache-of-paths-to-executables
Comment: This question is about using/configuring software rather than programming and it is [off-topic for Stack Overflow](http://stackoverflow.com/help/on-topic). [su] or [unix.se] would be a more appropriate site for this question.
Answer: Yes, most shells implement a lookup cache to remember where a command is found after performing path lookup. This cache can typically be viewed and/or manipulated with a hash command; consult your shell's man page for details.


which api use to post of facebook friend wall from blackberry?

Question: I am using graph API which is Facebook Me API in Blackberry to post on friends wall. But it is clearly listed that posting on friends wall functionality is removed with graph API. Please check this link for reference.
So,I am not able to post on friend's wall. However i am able to post on my own wall.
As i know there are other two ways it can be possible. Facebook FQL and Facebook Dialog.
So, is there any support for both to post on friend's wall?
Please reply me on same. For more information i want facebooki support for the blackberry 7.0 or more than that.
Answer: I don't think there is anyway else to phrase it: You cannot post to a friend's wall using the API period. There is no support for it, and it is listed right there in the roadmap.

We have found that posting content via API (stream.publish) on a friend's wall lead to a high incidence of user dissatisfaction (hiding content, blocking the app). After the migration period, posting content to friends' timelines via stream.publish will no longer be allowed. Please use the Feed Dialog for posting.

The feed dialog is a manual user generated action. FQL is not used for posting.
Comment: Thanks for the answer. But why you give me -ve for asking such question. Please let me know if i am wrong in any manner to ask question.


References in VB.net project

Question: The problem I have at work is that I have to re-add references every time I get a new project from SVN.  I'm trying to understand the process that the team need to follow to stop this happening.
The goal is so that anybody in the team can get the latest code and have a successful build.  However, we always seem to have issues with references missing.
As a general rule we have a "libs" folder within the project and reference anything we need from inside that. I'm not sure if this is the best approach?
I've just done a test by getting the latest version of a site from SVN. This particular site looks like it must have been set up as a website rather than a web project as there is no vbproj file.  I had a few references missing.  I went into the property pages of the site to check the locations of the references.  I thought the paths may be specific to somebody's machines but the references didn't even seem to be added.  So I added the references that I needed (They were in the "libs" folder).  Then everything built successfully but I had nothing marked to check in so what file actually changed when I added the references?
I think the problem may be a combination of web project verses websites and how visual studio treats them differently and how we are using the "libs" folder.  Thoughts?
Comment: Why aren't you using project references within the solution?
Comment: In the different companies I've worked for, we have a centralized *repository* (basically a folder on a network drive, that gets pulled down to our machines via a simple application) to a simple folder (aka `C:\references`). Then we also keep our projects in a simple location (aka `C:\projects`). This keeps everything pretty easy and simple to fix when broken between projects.
Comment: Generally for asp.net website projects you want to put your binary references in the `bin` directory.  Also when you pull down your source can you verify that the references were present in the `web.config`.  This isn't a problem in website application projects as your project file will contain the reference data.
Comment: I've just tried creating a web project instead of a website so that I can see the proj file.  If I add dll's to the libs folder it seems to use a relative path.  So looks like setting the projects up as web projects is probably the best way to go in the first instance.  Think the reason my original test failed was because of no proj file and the references to the .dll's were not in the config file.
Answer: You have two points here

where to keep references in multi-project solution
One way that will never fail you is to have a bin folder (aka libs - I really don't know why would people call it anything other than bin) ... so... to have a bin folder in the same location as solution, while projects would be in their separate sub folders.

--Solution Folder
  -- .sln
  -- bin
  -- Project1 Folder
  -- Project2 Folder
Now, in your bin you keep all .dll files, including ones you build and third party as well. Your projects will be referencing from this bin and build output will go into this bin. This bin should be part of version control. It is not recommended to check-in your DLLs into this bin but do check-in third party DLLs. Also notice, referencing from "under solution" will create reference with relative path - this is important.

how to deal with references in Web Site Project (vs Web Site Application)
This is not unusual that out of the version control you don't have references in your website. Here is what you need to do. For each DLL that Web Site Project references, you need to create DllName.dll.Refresh file under WebsiteProject-Bin in which you will set relative path to that dll. .refresh files should be checked-in. Once you build your libraries, only then you can build your website. It will pull all the DLLs you need to run it. With this setup, you now only need to make a virtual directory and point it to your WebsiteProject folder - you should have a running website.

Third point

Nuget
If your project(s) use nuget packages, create packages folder under your Solution folder and point there all nuget.config in your projects. This way you will have one central nuget repository, which will make your life easy.

If you follow these guidelines, you shouldn't have any problems building and deploying after Get Latest from version control. Just make sure that all existing references are relative.

References in VB.net project


How can I replace this shower drain cover?

Question: The drain cover that covers the vertical tub/shower overflow drain came off the other day, and it looks like the screw holding it in is rusted. I'm not sure any of my normal rusted screw removing skills will work in this tight space (and it's not obvious what will be there if I do remove it - will it be something I can then screw into still?).  The drain pipe is plastic. Probably 1980s construction.
Any suggestions for alternative covers or alternative attachment methods that don't involve replacing piping or calling a plumber??
Answer: The only way to properly repair it will involve getting access to the back of the tub to replace the overflow assembly.  Hopefully the other side of the wall is in a closet or someplace inconspicuous.
Cut a clean square hole at least 16 x16 inches. You can then frame the cut piece and replace it, allowing easy access in the future.
Once you get access, you may be able to remove the overflow tube and get the screws out for simple replacement.  If not have a new assembly ready for replacement.