text:
Q: Camera Intent returns no file path I have a problem with my camera Intent. It saves the pictures to the storage, but it doesn't return the file path to my activity. When i remove the EXTRA_OUTPUT it returns the file path, but then the images have just a very small size. Is there any solution to get the pictures with original size without using EXTRA_OUTPUT?
Here is my code:
   public void onClick(View arg0) {
    switch (arg0.getId()) {
     case R.id.btnImageCapture:
       preinsertedUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, preinsertedUri);
         startActivityForResult(intent, OPEN_CAMERA);
       break;
       }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     switch(requestCode){
     case OPEN_CAMERA:
         if (resultCode == RESULT_OK && data != null) {
                  Uri imageUri = null;
                  imageUri = data.getData();
                 if(imageUri == null && preinsertedUri != null){
                  imageUri = preinsertedUri;
                 }
                  String[] filePathColumn = { MediaStore.Images.Media.DATA };
                  Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
                  int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                  cursor.moveToFirst();
                  filePath = cursor.getString(columnIndex);
                try {
                 Bitmap photo = (Bitmap) data.getExtras().get("data");
                 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                 photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
                         File f = new File(filePath);
                         f.createNewFile();
                         FileOutputStream fo = new FileOutputStream(f);
                         fo.write(bytes.toByteArray());
                         fo.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                 break;
          }
       }
    }

A: Try this it might help you.
When I capture the photo from camera so I implement a logic using Cursor and iterate the cursor and get the last photo path which is capture from camera.
It give the path of last capture photo from camera.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);

Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
    do {
        uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
        photoPath = uri.toString();
    }while(cursor.moveToNext());
    cursor.close();
}


text:
Q: Amend autosuspension of deleted accounts to include recreation for Sockpuppet deletions?
Related: Automatically suspend accounts recreated after a moderator deleted the original

Recently downstream on Ask Ubuntu, an account was deleted for being a sockpuppet of another account.
Within an hour afterwards, they were able to create a new Ask Ubuntu user account with the exact same StackExchange Network account but did not get suspended or autodeleted.
This seems to be a flaw in the 'automatically suspend' function, as technically deletion as a sockpuppet should be considered the same as 'no longer welcome' (note that I deleted this specific case's second account as "no longer welcome" with the description of the sockpuppetry in the delete reason).
Can said auto-suspension function be amended to include Sockpuppet deletions of user accounts as well?

EDIT: Noticed that the deletes for "This user was created to circumvent system or moderator imposed restrictions and continues to contribute poorly" are also not included.  I think the autosuspend system needs to be included here as well because this is essentially the same as "no longer welcome"...

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find width of (1D discrete) Gaussian Kernel for a certain sigma? Is there a rule of thumb or mathematical equation that tells me how wide my (1D discrete) Gaussian Kernel should be for a certain sigma?
Lets say, I choose a sigma of 1.87, should my kernel be 5 values/steps/pixels wide, 7 oder rather 25 in order to perform standardized image smoothing? Thank you.

A: Pick a threshold that you consider ignorable, like T = 0.01. Then solve exp(-x^2/(2s^2)) / sqrt(2pi s^2) < T:
|x| < s sqrt(-2 ln(sqrt(2pi s^2) T))
The right hand side gives you the width. For s = 1.87 and T = 0.01, this gives you a width of 4 pixels.


text:
Q: Game Center Outcome Posting I'm doing a turn based game... the only information transferred is the score of the player and whether a turn has been sent.
When the next player receives the turn.  The data gets stored into "scoreToBeat"  and turnSent=1.  The player then takes their turn.  Afterward the game ended gets called because turnSent=1.  I used the turn based tutorial by Ray Wenderlich at http://www.raywenderlich.com/5480/beginning-turn-based-gaming-with-ios-5-part-1.
In his case the game ends and is a tie. Like this...   I can't seem to get it to show the person that lost.
   for (GKTurnBasedParticipant *part in currentMatch.participants) {
          part.matchOutcome = GKTurnBasedMatchOutcomeTied;
           }

I can't seem to get it to show the person that lost it always shows a win.  This is my latest attempt of many...  Exactly 2 players in the match btw...  Any ideas would be greatly appreciated.
    for (GKTurnBasedParticipant *part in currentMatch.participants) {
           if(part==currentMatch.currentParticipant)
           {
               if(points>scoreToBeat)
               {
                   part.matchOutcome=GKTurnBasedMatchOutcomeWon;
               }
               else {
                   part.matchOutcome=GKTurnBasedMatchOutcomeLost;
               }
           }
           else {
               if(points>scoreToBeat)
               {
                   part.matchOutcome=GKTurnBasedMatchOutcomeLost;
               }
               else {
                   part.matchOutcome=GKTurnBasedMatchOutcomeWon;
               }

           }

A: points is the local points scored on the device right? if so, I would do the following:
  if([part.playerID isEqualToString [GKLocalPlayer localPlayer].playerID]]) {

 if(points>scoreToBeat) {

part.matchOutcome = GKTurnBasedMatchOutComeWon;

} else {

part.matchOutcome = GKTurnBasedMatchOutComeLost;

}

} else {
    if(points>scoreToBeat) {
               part.matchOutcome=GKTurnBasedMatchOutcomeLost;
           } else {
               part.matchOutcome=GKTurnBasedMatchOutcomeWon;
           }

       }
}

Also, remember to use a NSLog to see if score to beat is actually transferred. One mistake you can do to keep on using currentTurnBasedMatch.matchData, you should set the currentTurnBasedMatch to GKTurnBasedMatch that is returned in delegate methods.
EDIT: A code snipped I use looks like this
if([participant.playerID isEqualToString:[GKLocalPlayer localPlayer].playerID]){
        NSLog(@"we are the last player in the game -end the game");
        for (GKTurnBasedParticipant *part in match.participants) {

            part.matchOutcome = GKTurnBasedMatchOutcomeTied;
        }
       [match endMatchInTurnWithMatchData:match.matchData completionHandler:^(NSError *error) {
           if ([AppDelegate mainMenuController].multiGameMenu.turnBasedMenu !=nil) {

               [[AppDelegate mainMenuController].multiGameMenu.turnBasedMenu reloadTableView];
           }

       } ];
}

A: This is an excerpt from my latest project, good for a 2 player game. It's called during the sendTurn process, when the game is decided to be ending. This is more correct than the previous answer (first code block), in my opinion, because you must set the matchOutcome for all participants before ending the game.
If you had more than 2 players, then you'd have to loop through all participants and set the matchOutcome accordingly.
   GKTurnBasedParticipant *curr = currentMatch.currentParticipant;
    NSUInteger currentIndex = [currentMatch.participants indexOfObject:currentMatch.currentParticipant];
    NSUInteger nextIndex = (currentIndex + 1) % [currentMatch.participants count];
    GKTurnBasedParticipant *next = [currentMatch.participants objectAtIndex:nextIndex];

    if (currScore < otherScore)
    {
        // Curr player lost
        curr.matchOutcome = GKTurnBasedMatchOutcomeLost;
        next.matchOutcome = GKTurnBasedMatchOutcomeWon;
    }
    else if (currScore == otherScore)
    {
        // Tied
        curr.matchOutcome = GKTurnBasedMatchOutcomeTied;
        next.matchOutcome = GKTurnBasedMatchOutcomeTied;
    }
    else
    {
        // Won
        curr.matchOutcome = GKTurnBasedMatchOutcomeWon;
        next.matchOutcome = GKTurnBasedMatchOutcomeLost;
    }

Note that you will see "Won" on both devices by design.
One will say "Me" with "Won" underneath, and the other will say "(Winners Name)" with "Won" underneath.


text:
Q: Making nested Function calls within Haskell Working on converting over some scheme code to haskell for some practice and I have a bit of an issue with creating a custom Binary Search Tree.
node x l r returns a lambda that gets you the corresponding value of that tree. However, when creating let t1 = node 5 (node 3 0 0) (node 8 (node 7 0 0) 0) I get the following errors:
[1 of 1] Compiling Main             ( binTree.hs, binTree.o )

binTree.hs:29:18: error:
    • No instance for (Eq ((a1 -> a0 -> t0) -> a1 -> a0 -> t0))
        arising from a use of 'node'
        (maybe you haven't applied a function to enough arguments?)
    • In the expression: node 5 (node 3 0 0) (node 8 (node 7 0 0) 0)
      In an equation for 't1':
          t1 = node 5 (node 3 0 0) (node 8 (node 7 0 0) 0)
      In the expression:
        do { let t1 = node 5 (node 3 0 0) (node 8 (node 7 0 0) 0);
             print $ size t1 }

binTree.hs:29:23: error:
    • No instance for (Num (a1 -> a0 -> t0))
        arising from the literal '5'
        (maybe you haven't applied a function to enough arguments?)
    • In the first argument of 'node', namely '5'
      In the expression: node 5 (node 3 0 0) (node 8 (node 7 0 0) 0)
      In an equation for 't1':
          t1 = node 5 (node 3 0 0) (node 8 (node 7 0 0) 0)

binTree.hs:29:26: error:
    • Ambiguous type variable 'a1' arising from a use of 'node'
      prevents the constraint '(Eq a1)' from being solved.
      Relevant bindings include
        t1 :: ((a1 -> a0 -> t0) -> a1 -> a0 -> t0) -> a1 -> a0 -> t0
          (bound at binTree.hs:29:13)
      Probable fix: use a type annotation to specify what 'a1' should be.
      These potential instances exist:
        instance Eq Ordering -- Defined in 'GHC.Classes'
        instance Eq Integer
          -- Defined in 'integer-gmp-1.0.0.1:GHC.Integer.Type'
        instance Eq a => Eq (Maybe a) -- Defined in 'GHC.Base'
        ...plus 22 others
        ...plus three instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the second argument of 'node', namely '(node 3 0 0)'
      In the expression: node 5 (node 3 0 0) (node 8 (node 7 0 0) 0)
      In an equation for 't1':
          t1 = node 5 (node 3 0 0) (node 8 (node 7 0 0) 0)

binTree.hs:29:31: error:
    • No instance for (Num (a0 -> t0)) arising from the literal '3'
        (maybe you haven't applied a function to enough arguments?)
    • In the first argument of 'node', namely '3'
      In the second argument of 'node', namely '(node 3 0 0)'
      In the expression: node 5 (node 3 0 0) (node 8 (node 7 0 0) 0)

binTree.hs:29:47: error:
    • Ambiguous type variable 'a0' arising from a use of 'node'
      prevents the constraint '(Eq a0)' from being solved.
      Relevant bindings include
        t1 :: ((a1 -> a0 -> t0) -> a1 -> a0 -> t0) -> a1 -> a0 -> t0
          (bound at binTree.hs:29:13)
      Probable fix: use a type annotation to specify what 'a0' should be.
      These potential instances exist:
        instance Eq Ordering -- Defined in 'GHC.Classes'
        instance Eq Integer
          -- Defined in 'integer-gmp-1.0.0.1:GHC.Integer.Type'
        instance Eq a => Eq (Maybe a) -- Defined in 'GHC.Base'
        ...plus 22 others
        ...plus three instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the second argument of 'node', namely '(node 7 0 0)'
      In the third argument of 'node', namely '(node 8 (node 7 0 0) 0)'
      In the expression: node 5 (node 3 0 0) (node 8 (node 7 0 0) 0)

binTree.hs:29:52: error:
    • Ambiguous type variable 't0' arising from the literal '7'
      prevents the constraint '(Num t0)' from being solved.
      Relevant bindings include
        t1 :: ((a1 -> a0 -> t0) -> a1 -> a0 -> t0) -> a1 -> a0 -> t0
          (bound at binTree.hs:29:13)
      Probable fix: use a type annotation to specify what 't0' should be.
      These potential instances exist:
        instance Num Integer -- Defined in 'GHC.Num'
        instance Num Double -- Defined in 'GHC.Float'
        instance Num Float -- Defined in 'GHC.Float'
        ...plus two others
        (use -fprint-potential-instances to see them all)
    • In the first argument of 'node', namely '7'
      In the second argument of 'node', namely '(node 7 0 0)'
      In the third argument of 'node', namely '(node 8 (node 7 0 0) 0)'

binTree.hs:30:17: error:
    • No instance for (Num ((a1 -> a0 -> t0) -> a1 -> a0 -> t0))
        arising from a use of 'size'
        (maybe you haven't applied a function to enough arguments?)
    • In the second argument of '($)', namely 'size t1'
      In a stmt of a 'do' block: print $ size t1
      In the expression:
        do { let t1 = node 5 (node 3 0 0) (node 8 (node 7 0 0) 0);
             print $ size t1 }

{-# LANGUAGE FlexibleContexts #-}
node x l r = \s ->
        if s == 0
            then x
        else if s == 1
            then l
        else if s == 2
            then r
        else error "invalid value"

--search x t = do
--  not (null t) && ((x == (datr t)) || ((x < (datr t)) && (search x (left t))) || ((x > (datr t)) && (search x (right t))))

multiply tree = do
    if tree == 0
        then 1
    else ($ datr tree) * (multiply ($ left tree)) * (multiply ($ right tree))

datr t = t 0
left t = t 1
right t = t 2
size t = do
    if t == 0
        then 0
    else 1 + (size ($ left t)) + (size ($ right t))

main :: IO ()
main = do
    let t1 = node 5 (node 3 0 0) (node 8 (node 7 0 0) 0)
    print $ size t1

Original working scheme code:
(define (node x l r)   ; x is data, l is left, r is right
  (lambda (s)
    (cond  ((= s 0) x)
           ((= s 1) l)
           ((= s 2) r)
           (#t 'error))))

(define (search x t)   ; assuming a binary search tree
  (and (not (null? t))
       (or (= x (data t))
           (and (< x (data t)) (search x (left t)))
       (and (> x (data t)) (search x (right t))))))

(define (multiply tree)
  (if (null? tree) 1 (* (data tree) (multiply (left tree)) (multiply (right tree)))))
;----------------------------------------------------------------------------------------;
(define (howmany tree expr)
  (if (null? tree) 0
  (if (expr (data tree)) (+ 1 (howmany (left tree) expr) (howmany (right tree) expr))
  (+ (howmany (left tree) expr) (howmany (right tree) expr)))))
;----------------------------------------------------------------------------------------;
(define (data t) (t 0))
(define (left t) (t 1))
(define (right t) (t 2))
(define (size t) (if (null? t) 0 (+ 1 (size (left t)) (size (right t)))))
(define t1 (node 5 (node 3 '() '()) (node 8 (node 7 '() '()) '())))
(display (multiply t1))
(display "\n")

A: Notice that in the scheme the symbol node represents a constructor of a node of a binary tree where the first value is the nodes data, then the left sub tree, then the right.  Similarly, datr, left, and right are projection functions that allow you to access fields of the tree.
Haskell has syntax for data declarations.  In the case of such a Tree it would look like so:
data Tree
    = Node { datr :: Integer, left :: Tree, right :: Tree }
    | Empty

From here you can define multiply by pattern matching against either a node of a tree (Node) or the empty tree (Empty):
multiply :: Tree -> Integer
multiply Empty = 1
multiply (Node x l r) = x * (multiply l) * (multiply r)

The first line is a type signature.  Haskell is statically typed and you are encouraged to explicitly provide the type.  Not doing so makes the code and any error messages harder to read.
The second line matches against the case when the tree is empty, much like the Scheme null? test case.  Then in the third line we get to the recursive calls for the sub-trees.
What's shown with multiple is idiomatic Haskell code.  A more direct translation would be:
multiply t =
    if t == Empty
        then 1
        else datr t * left t * right t

While functional, this sort of code is discouraged - equality tests carry more restrictions and machinery than pattern matching.  The functions of datr, left, and right are partial so if they are applied to a value such as Empty they will fail (i.e. if the preceding logic doesn't hold the invariants you intended); pattern matches have no such failure case.
I'll leave the remaining functions as an exercise.


text:
Q: Applying a timeout to UDP call receive_from in ASIO I have the following bit of ASIO code, that synchronously reads UDP packets. The problem is if no data packets of the given size have arrived in a given time frame  (30 seconds) I'd like the recieve_from function to return with some kind of error to specif icy timeout.
for (;;)
{
  boost::array<char, 1000> recv_buf;
  udp::endpoint remote_endpoint;
  asio::error_code error;

  socket.receive_from(asio::buffer(recv_buf),   // <-- require timeout
      remote_endpoint, 0, error);

  if (error && error != asio::error::message_size)
    throw asio::system_error(error);

  std::string message = make_daytime_string();

  asio::error_code ignored_error;
  socket.send_to(asio::buffer(message),
      remote_endpoint, 0, ignored_error);
}

Looking at the documentation non of the UDP oriented calls support a time-out mechanism.
What is the correct way (also portable if possible) for having a time-out with syncronous UDP calls in ASIO?

A: As far as I know, this is not possible. By running a synchronous receive_from you've blocked code execution by a syscall recvmsg from #include <sys/socket.h>.
As portability goes, I cannot speak for Windows but a linux/bsd C-flavoured solution would look like this:
void SignalHandler(int signal) {
  // do what you need to do, possibly informing about timeout and calling exit()
}

...
struct sigaction signal_action;
signal_action.sa_flags = 0;
sigemptyset(&signal_action.sa_mask);
signal_action.sa_handler = SignalHandler;
if (sigaction(SIGALRM, &signal_action, NULL) == -1) {
  // handle error
}
...
int timeout_in_seconds = 5;
alarm(timeout_in_seconds);
...
socket.receive_from(asio::buffer(recv_buf), remote_endpoint, 0, error);
...
alarm(0);

If this is not at all feasible, I would recommend going full async and run it in a boost::asio::io_service.


text:
Q: Why is my GridView objects not seen in code? why cant I use GridVew?
<LoggedInTemplate>
                <asp:GridView ID="GridView1" runat="server" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000" AutoGenerateColumns="false" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" RowStyle-BackColor="#A1DCF2">
                    <Columns>
                        <asp:BoundField DataField="Name" HeaderText="File Name" />
                        <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                            <ItemTemplate>
                                <asp:LinkButton ID="lnkDownload" runat="server" CommandArgument='<%# Eval("Id") %>' OnClick="DownloadFile" Text="Download"></asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
                <asp:FileUpload ID="FileUpload1" runat="server" />
                <asp:Button ID="btnUpload" runat="server" OnClick="Upload" Text="Upload" />
            </LoggedInTemplate>

using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "select Id, Name from tblFiles";
                    cmd.Connection = con;
                    con.Open();
                    //GridView1.DataSource = cmd.ExecuteReader();
                    //GridView1.DataBind();
                    con.Close();
                    LoginView3.DataSource = cmd.ExecuteReader();
                    GridView1.DataBind();
                    LoginView3.GridView1.DataSource = cmd.ExecuteReader();
                }

Here is screenshot.
https://www.dropbox.com/s/81186zjwkp482ms/Zrzut%20ekranu%202014-09-15%2009.10.48.png?dl=0

A: Your gridview is inside the template control, LoggedInTemplate in this case. So it is not accessible a control directly, which is inside a template of another control.
You need to find the control using the code something like below
GridView gridView = yourMainControl.FindControl("GridView1") as GridView;

Then you can use the control further.


text:
Q: Runtime progress status (like statusbar) in python I'm trying to create simple progress status label for my Pyqt5 Python code and update it after every iteration of a loop in which a function does a bunch of stuff. The label I want to be updated is "status_label_counter". The below code only shows the part for creating labels and the exact place where I want to use the functionality I've mentioned.
    #initialisation code, etc...

    self.status_label_counter = QLabel()
    self.status_label_from = QLabel(' from: ')
    self.status_label_total = QLabel()
    status_hbox = QHBoxLayout()
    status_hbox.addStretch()
    status_hbox.addWidget(self.status_label_counter)
    status_hbox.addWidget(self.status_label_from)
    status_hbox.addWidget(self.status_label_total)
    status_hbox.addStretch()

    #bunch of other code...

    def create_ics(self):
        counter = 0
        self.status_label_total.setText(str(len(self.groups)))
        for group in self.groups:
            #does a bunch of stuff inside
            group_manager.create_calendar_for(self.rows, group, self.term)
            counter += 1
            #for console output
            print('iteration: ', counter)
            #trying to update status counter
            self.status_label_counter.setText(str(counter))

The problem is that I only see the update of both labels when the loop is done with the nested function. When I click a button that calls for "create_ics" function window becomes inactive for about 5 seconds, I see logs on console with count of iterations, but nothing happens in view.

A: The view (Qt) is locked in your main thread and never gets its chance to process its event loop and thus redraw itself. If you really want to do it this way, call:
self.status_label_counter.repaint()

After you set the text (and if you have some complex layout measuring call QApplication.processEvents() instead).
However, much better option would be to run your create_ics() function in a separate thread leaving your main thread to deal with the view and Qt's event processing. You can do it either through standard Python's threading module, or using Qt's own QThread: https://nikolak.com/pyqt-threading-tutorial/ .


text:
Q: WPF: Is there a performance and/or memory benefit to setting properties versus using Styles? Without having time to fully test this myself, I am hoping someone else may already know if there is any performance and/or memory benefit to defining a control's appearance using the control's properties versus a style (or vice versa).
Option #1:
<Border Background="White" BorderBrush="Black" BorderThickness="2" CornerRadius="20">
    ...
</Border>

Option #2:
<Style x:Key="BorderStyle" TargetType="Border">
    <Setter Property="Background" Value="White"/>
    <Setter Property="BorderBrush" Value="Black"/>
    <Setter Property="BorderThickness" Value="2"/>
    <Setter Property="CornerRadius" Value="20"/>
</Style>

<Border Style="{StaticResource BorderStyle}">
    ...
</Border>

Please note that I am not asking about reusability as I understand those benefits.  I am specifically wondering about "one off" styles that are specific to a given control and not reused.
Another example would be the case where I have a second Border with a margin.  Would it be more performant and require less memory to have that Border use the same style as above and directly set the Margin property or should I create a second Style resource based on the first with the new setter?

A: I knew that the list of precedence in on it, but not as many as I wrote in a commentary. Here's what the note says about this list of precedence in Matthew MacDonald book [Chapter 4. Dependency Property]:

So, when you setting the values locally, the memory is allocated for the value. When you setting these values in Style, and other controls that Style is used, the memory is allocated only once, by storing the values of Style.
I think, if the controls are not a lot of (the concept of fuzzy, can be 1, 2 or 3), the speed is practically no difference, but if the control is set, in this case, the difference in speed and memory storage will be.

A: If you use the Style syntax for a collection of properties you use in only one place, you gain no memory efficiency, but you do get code readability; your main XAML code will be a little less cluttered. I've never perceived an execution speed difference between using resource dictionary styles and locally defined dependency properties.
To your second question, again, no perceptible speed difference, but you can override any resource dictionary property by specifying a local property. There is a very small amount of memory efficiency involved in using styles that way.


text:
Q: Python Reading in Tick Data Pandas I got some data that looks like this:
    Symbol              Timestamp      bid      ask
0  EUR/USD  20140101 21:55:34.378  1.37622  1.37693
1  EUR/USD  20140101 21:55:40.410  1.37624  1.37698
2  EUR/USD  20140101 21:55:47.210  1.37619  1.37696
3  EUR/USD  20140101 21:55:57.963  1.37616  1.37696
4  EUR/USD  20140101 21:56:03.117  1.37616  1.37694

I am trying to convert it to pandas, but am stuck on the microsecond part....below is what I am i've got so far...
Read in data
sec = pd.read_csv('EURUSD.csv',header=None,parse_dates = 1)
sec.columns = ['Symbol', 'Timestamp', 'bid', 'ask']

Get the timestamp column to convert
sec['Timestamp'] = sec['Timestamp'].apply(lambda x: dt.datetime.strptime(x, '%Y%m%d %H%M%S'))

'%Y%m%d %H%M%S' In the above command, the part after %S should be wad? Should it be '%Y%m%d %H%M%S%f'? but that doesnt seem to work. The period in the time messes things up...any ideas?

A: Just apply to_datetime:
In [11]: df
Out[11]:
    Symbol              Timestamp      bid      ask
0  EUR/USD  20140101 21:55:34.378  1.37622  1.37693
1  EUR/USD  20140101 21:55:40.410  1.37624  1.37698
2  EUR/USD  20140101 21:55:47.210  1.37619  1.37696
3  EUR/USD  20140101 21:55:57.963  1.37616  1.37696
4  EUR/USD  20140101 21:56:03.117  1.37616  1.37694

In [12]: pd.to_datetime(df.Timestamp)
Out[12]:
0   2014-01-01 21:55:34.378000
1   2014-01-01 21:55:40.410000
2   2014-01-01 21:55:47.210000
3   2014-01-01 21:55:57.963000
4   2014-01-01 21:56:03.117000
Name: Timestamp, dtype: datetime64[ns]

If you must pass a format, missing piece is %f:
In [12]: df['Timestamp'].apply(lambda x: dt.datetime.strptime(x, '%Y%m%d %H:%M:%S.%f'))
Out[12]:
0   2014-01-01 21:55:34.378000
1   2014-01-01 21:55:40.410000
2   2014-01-01 21:55:47.210000
3   2014-01-01 21:55:57.963000
4   2014-01-01 21:56:03.117000
Name: Timestamp, dtype: datetime64[ns]


text:
Q: Has anyone succeeded in uploading an image (not a url) via Facebook's SDK? I am looking all over the place for an end to end *working example of using the Android Facebook SDK to upload an image to a user's wall.  I've succeeded in doing this with a link to a web accessible image, but they say it's possible to just submit a byte array, however, when I try this, I just get an empty post on the wall (it even omits the title and description).
I've tried using photo and image as the hash keys for the byte array... my byte array is a perfectly valid Bitmap... So... I'm stumped.  Is this just another buggy Facebook API that doesn't work?  I'd love to know if anyone has used it successfully and maybe take a look at the code you used to see how mine is different.
Here's mine...
ByteArrayOutputStream stream = new ByteArrayOutputStream();
comboBitmap.compress(Bitmap.CompressFormat.JPEG, 60, stream);
Log.d(Constants.TAG, "filled stream");

byte[] bitmapdata = stream.toByteArray();

Bundle b = new Bundle();
//b.putString("picture","http://myinkpic.com/images/inkIcon.png");

b.putString("caption", "Stash Title");
b.putString("description", "Stash Caption");
b.putByteArray("photo", bitmapdata);
myApp.facebook.request("me/feed", b, "POST");

And here's a link to the dev page where they mention the byte[]
[Facebook api]1
Notice how they say this:
"Make sure the Bundle value for the photo parameter is a byte array."
That's what gave me the idea to use "photo" as the key.  It may in fact totally wrong, but I can't seem to find the docs now for where they define the keys.

A: Well, after much painful searching and testing it would appear that so long as the request method is "me/feed", posting a byte[] is simply not possible.  What *does work is posting to me/photos.  This has a very similar effect, in that the image does get to the user's gallery and ends up on their wall, but if you post multiple images they all go side by side, rather than in a list.
Hopefull Facebook will release an update sometime in the near term fixing this bug.


text:
Q: How many steps and big-O complexity def percentBases(dnaStrand):
    cytosine = dnaStrand.count('C')
    guanine= dnaStrand.count('G')
    adenine= dnaStrand.count('A')
    thymine= dnaStrand.count('T')

    percentC = round(cytosine/len(dnaStrand)*100,2)
    percentG =  round(guanine/len(dnaStrand)*100,2)
    percentA = round(adenine/len(dnaStrand)*100,2)
    percentT = round(thymine/len(dnaStrand)*100,2)

    return(percentC, percentG, percentA, percentT)

I have written this simple code and have been asked to record an approximate time complexity using big-O notation. I don't have a clue about big-O notation but after reading I would have a guess at:
T(n) = 8
O(8)
Please correct me if I'm wrong and try to explain to me. Thanks

A: To understand big-O time complexity of a function, you need to look at what will take more time to compute as the size of the input changes. Your input dnaStrand is a string, and you do two operations count and len that could potentially take more time as the length of the input increases. len for a string is constant (source), but count is linear, since you have to loop over the entire string to count occurrences of different substrings. So, your function is 4*O(n), or just O(n).

A: Your function performs 8 operations and all of them take constant time.
So, T(n) = 8
In terms of big-o, you can write it as
T(n) = O(1) or O(c)


text:
Q: how can I import a file vuejs component into index.html? I'm using a CDN for VUEjs because I don't want to use webpack or render from the server.
index.html and test-component.vue are in the same folder
my index.html:
<!DOCTYPE html>

<meta charset="utf-8">
<title>VUE</title>

  <comp></comp>

my test-component.vue file:
<template>

im a component

</template>

A: obviously .vue files are not natively supported by the browser
there are 2 possible solutions:

*

*use a javascript bundler (like webpack or parcel)

*use http-vue-loader


text:
Q: I'm getting syntax error when trying to send password in form I'm very new at php. I get these errors when I write these codes.

A: You are using the method POST in the form and getting the variables with GET
Either Try method : GET or try $_POST["islem"];

A: check to see if islem was passed in before trying to access it
if (isset($_POST['islem']) {
 // your code here
}

Otherwise you won't be able to load the page up initially in order to submit the form.  Also notice that I used _POST here, this is because you used the POST method in your form.


text:
Q: Monitoring multiple processes using zookeeper I'm utilizing Zookeeper to track the state of multiple processes running in many servers. I have modelled each of the processes belonging to different categories in a tree like structure. Each process is the leaf znode marked as ephemeral.
The doubt i have is :
=> Can i maintain a single static instance of zookeeper connection and utilize this connection for multiple processes to register themselves as a Znode or is it ok, if a zookeeper session is created for every process.
I've read quite a bit on Zookeeper but still couldn't get a clear idea of the Zookeeper sessions. Please can you help me with this


text:
Q: Indent values in a ComboBox In my Excel spreadsheet I use the below VBA codes to get a UserForm with a ComboBox using the values from Sheet1:
List for ComboBox1 on spreadsheet:
         A               B             C
1    Q1
2      January
3      February
4      March
5    Q2
6      April
7      May
8      June

VBA code to call UserForm1 (connected to a button on the spreadsheet):
Sub Test()
Call UserForm1.Show(vbModeless)
End Sub

VBA code of UserForm1:
Private Sub UserForm_Activate()
ComboBox1.List = Sheet1.Range("A1:A8").Value
End Sub

In the end the UserForm1 looks like this:

All this works fine so far.

As you can see in my original list in the spreadsheet the month below the quarters are indented.  Is it possible to also indent the values in the ComboBox1 of the UserForm1?

A: You can solve the issue by putting a space before the values in the sheet and then go with one of the following VBA options:

Option 1:
VBA for ComboBox:
Private Sub UserForm_Activate()
ComboBox1.List = Sheet1.Range("A1:A8").Value
End Sub

VBA to insert the selected values without the space into the spreadsheet:
(In order to use them further in the spreadsheet)
Sub ComboBox1_Insert_Value()
Sheet1.Range("E1").Value = Trim(ComboBox1.Value)
End Sub

Option 2:
VBA for ComboBox:
Loop through the ranges and check if the horizontal orientation is set to right. If so then you could add a space in front of the value of the cell.
Private Sub UserForm_Activate()
For Each cell In Range("A1:A8")
    If cell.HorizontalAlignment = xlRight Then
        ComboBox1.AddItem "  " & cell.Value
    Else
        ComboBox1.AddItem cell.Value
    End If
    Next cell
End Sub

VBA to insert the selected values without the space into the spreadsheet:
(In order to use them further in the spreadsheet)
Sub ComboBox1_Insert_Value()
Sheet1.Range("E1").Value = Trim(ComboBox1.Value)
End Sub

A: As per my comment you could use multiple columns in your combobox and adjust the column widths as desired. e.g.
Private Sub ComboBox1_Click()
    Debug.Print ComboBox1.Value
    With ComboBox1
        If .Value <> vbNullString Then
            .Text = Split(.Value, "-")(1)
        End If
    End With
End Sub
Private Sub UserForm_Initialize()
    Dim rng As Range
    Dim Quarter As String
    Dim c

    With Sheet1
        Set rng = .Range(.Cells(1, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
    End With

    With ComboBox1
        .ColumnCount = 3
        .ColumnWidths = "0;20;40"
        For Each c In rng
            If c.HorizontalAlignment = xlRight Or c.IndentLevel > 0 Or Len(c.Value2) > Len(LTrim(c.Value2)) Then
                .AddItem Quarter & "-" & c.Value2
                .Column(2, .ListCount - 1) = c.Value2
            Else
                Quarter = c.Value2
                .AddItem vbNullString
                .Column(1, .ListCount - 1) = Quarter
            End If
        Next c
    End With
End Sub

This works using three columns all together. The first one is hidden from the end user and is used as line ID value (combination of Quarter and month), the second column holds the Quarter value and the third holds the month value
Produces:


text:
Q: Cleaning up temp files in Mac OS X My 4 months old Mac partition volume is losing space slowly and gradually. I am pretty sure there are a lot of orphaned temporary files laying around in the volume.
I know where to find the obsoleted temp files in my Windows partition, how about in Mac OS X?

A: Mac OS X temporary files are stored in /tmp and /private/var/folders. Your specific Cache and Temporary folders can be found by running the command echo $TMPDIR and/or usr/bin/getconf DARWIN_USER_CACHE_DIR
These locations should be automatically cleared out regularly either through the daily, weekly and monthly "cron" scripts and/or a restart so you shouldn't have to worry about it. You can use tools such as Onyx, Cocktail, Leopard Cache Cleaner, etc. to run these scripts and/or clear your caches and temp files.
The one big exception is Safari's Thumbnail cache does not delete and can be found in your DARWIN_USER_CACHE_DIR under com.apple.Safari.
To find out where most of your disk space is going (and if temporary files are even a culprit) I suggest using a program such as OmniDiskSweeper or GrandPerspective to tell you where all the large files are.

A: When a backup volume is not mounted, Time Machine has saved hourly snapshots to /Volumes/MobileBackups/ on laptops since 10.7. They are deleted automatically when you start running out of disk space though.
/private/var/folders/ can contain partially downloaded files or files for applications that have been removed. du -sm /private/var/folders/*/*/*/*/ | sort -rn sorts the folders by size.
~/Library/Autosave Information/ can contain old unsaved documents.
~/Library/Caches/com.apple.Safari/Webpage Previews/ was about 700 GB on my installation of 10.7. defaults write com.apple.Safari DebugSnapshotsUpdatePolicy -int 2 disables saving the thumbnails.
Safari saves the contents of websites and plain text files to ~/Library/Caches/Metadata/Safari/History/.
If hibernatemode is 3, /var/vm/sleepimage takes up the same amount of disk space as the amount of RAM you have.
/Library/Developer/ wasn't removed when I installed Xcode 4.3. It contained about 2GB of old docset files.
A good way to find large files is to sort files by size in list view after checking calculate all sizes in the view options. You can show hidden files with defaults write com.apple.finder AppleShowAllFiles -bool true; killall Finder.

A: Another couple of possible set of options for checking what is occupying disk space:
Baseline -- unique among disk scanners in that it has a brilliant snapshot function. So it scans your disk and shows you what is occupying space, but it will save this snapshot. A couple of weeks later, run it again and compare to your last snapshot - it will tell you every file that has changed. This is unique and very very useful, especially  before/after installing large software suites.

Daisy Disk -- This is visually the most beautiful of the OS X disk scanners, I always prefer the pie maps visualisation...

A: Not sure if this helps but i would try Onyx and Appdelete to get rid of applications, seems to do a decent job of getting rid of extra system files, etc.

A: I use Disk Inventory X to find what actually eats my space. then reveal that files in finder and delete them if they are not in use anymore

A: I got a bundled copy of AppZapper with a MacHeist - recommended.
JDiskreport - Free Java Utility will show you where all your space has gone - also recommended

A: Most of what I could say is covered above, with a couple exceptions that may or may not apply to your specific case:
If you use Adobe Bridge, the cache folder can get quite amazingly big. I cleaned mine out the other day and ended up removing 8gb of extra space. Also I'm using CS4, and I noticed that my CS3 cache folder was still around even though I got rid of CS3 a while ago. Another 2+ gigs there.
I also use Parallels 4 and it has a nasty tendency to use up all of the free space given enough time, but a computer reboot handles that. This could be just me though. If you do have Parallels or Fusion and have regular snapshots made, that could also be a factor.
I use Whatsize to check what's taking up space, but I got my copy before they started charging. I like it better than the other ones I've seen.

A: Reboot your computer. If it suddenly has lots more free space, this is due to the ever-expanding swap files. They are reclaimed (deleted) upon reboot and will eventually get re-created as you use your Mac. This is completely normal.
There's no need for their existence to turn you into a reboot-obsessed user, however. It's a good thing when your Mac swaps unused memory out to disk.

A: I also cleaned lots of junk files or unneeded files from my system as its getting slower and slower,Tweak and Tuneup helped me in getting back Gb's of space in my mac. I`ll stick with it, as this is the 100% best cleaning app in the market love to have it.


text:
Q: One to one correspondence between transcendental and uncomputable numbers I know that both sets are uncountable infinite but the transcendentals are not a subset of the uncomputables. I don't know if there exist uncomputable numbers that are not transcendental. But my question is whether the two sets have the same cardinality.

A: Here
https://en.wikipedia.org/wiki/Computable_number
under "properties" it is stated the the set of computable numbers is countable.
Hence, the set of uncountable numbers must be uncountable infinite and hence have the same cardinality as the set of transcendental numbers which is uncountable infinite as well.


text:
Q: Understanding why we use methods on strings in Python I've just started learning Python and I've got to a point where I'm a little confused on why we use .upper() in, for example, print("Hello, World!".upper()). I've read through some answers provided on similar stackoverflow questions, any they all the general theme, "you use the notation .upper() for methods".
From my understanding, methods are just special cases of functions that belong to classes. If this is the case, why do we use things like .upper(), .title(), .isalhpa() etc. on simple strings like "Hello, World!" when they don't belong to a class?

A: As other people have pointed out this happens because in python strings, as all of the other types I am aware of, are objects. Strings specifically are objects of the str class. You may look here for more on this.
Also methods usually refer to functions bound to objects. This excellent  post about how methods work on python may interest you.

A: A good thing to get comfortable with is checking types and methods of different objects. E.g.
>>> stringy = 'Hello world!'
>>> type(stringy)
str

Then to get information on string-type objects:
>>> help(str)
class str(object)
# <A description of the class will be here>

Methods defined here:
# <various methods>
upper(...)
    S.upper() -> str

    Return a copy of S converted to uppercase.

So what we were actually doing in our first line is creating an object of the str() class:
stringy = str('Hello world!')

Hope that makes sense :-)


text:
Q: People picker field in sharepoint, CommaSeparatedAccounts as domain\\user I have a people pickerfield in sharepoint. I expect to return its CommaSeparatedAccounts as domain\user.
But it returns CommaSeparatedAccounts' value as "i:0#.w|domain\user"
Find the code sample.
<%@ Register TagPrefix="spuc" Namespace="Microsoft.SharePoint.WebControls"
             Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<spuc:PeopleEditor ID="PeopleEditor1" runat="server"
                   AllowEmpty="true" MultiSelect="false" SelectionSet="User"  />

A: It will give you the login name in the same format.
But you can decode this in your code behind.
Use the following code to decode the username :
string userName = null;
SPClaimProviderManager mgr = SPClaimProviderManager.Local;
if (mgr != null)
{
    userName = mgr.DecodeClaim(SPContext.Current.Web.CurrentUser.LoginName).Value;
}


text:
Q: Clarification needed on async and await I read many articles on async and await(mostly from msdn - which is good actually). There is still one question that bothers me and I could not find the answer.
If there is an await statement on a task then the control is returned to its caller until it is awaited again in the caller. In that case is this time consuming task getting executed in a separate thread? If not then how is it getting executed parallel to the main thread.
async Task<string> GetContentsAsync()
{
    int sample = 0;
    HttpClient client = new HttpClient();
    Task<string> contents = client.GetStringAsync("http://www.microsoft.com");

    string data = await contents;
    return data;
}

I hope my question is clear.

A:
In that case is this time consuming task getting executed in a separate thread?

There are two kinds of tasks. Some Tasks have code to execute, and they run on some thread. Other Tasks do not execute code; they just represent some future event.
The "event tasks" are used a lot by async, particularly in I/O scenarios. In your example, you're executing an HTTP GET. GetStringAsync will send the HTTP request and then return an "event task" that completes when the response is received. While the HTTP request is in flight and being processed by the server, there's no code for the client to execute for that request. So there's no thread required, and none is used.
Also see my answer here.

A: It depends on how the task is created, but no, tasks are not inherently executed on a separate thread automatically. Some helper methods, like Task.Run for example, can help you make sure a task is put on a separate thread (the thread pool in this case).
Remember that a GUI application, let's say WinForms specifically, runs a so-called event loop. In WinForms this happens behind your back, in the Application.Run call. This event loop receives events like clicks and invokes your handlers. The thread that this loop executes on is referred to as "the GUI thread". In WinForms, it's the thread that creates all the controls, and hence also the only thread allowed to touch those controls.
When you create a task using the async modifier on a method, that code is also scheduled to execute via this event loop. It's just queued up. Just like the good old Invoke calls. So once your event handler returns, eventually the event loop gets to that queued up task, executes it, and then executes the rest of the method that followed the await. No parallelism here.
However, there are other ways to create tasks; calling an async method is just one way. Task.Run creates tasks that are put on separate threads. GetStringAsync you show in your example will actually run in parallel with whichever thread invoked the task.


text:
Q: Remove items from a collection if one date is greater than another I'm trying to use linq to remove items from a collection where one date is greater than another. I know I need to use DateTime.Compare() but I'm a bit unsure how to go about it.
If this were allowed, my code would look like the following:
ciLibrary.RemoveAll(x => x.LastSyncToWebsite >= x.Modified);

Since this doesn't work with DATETIME values how do I properly represent this statement?

A: DateTime values can be compared using >=. What you need is a Where:
clLibrary.Where(x => !(x.LastSyncToWebsite >= x.Modified))

or equivalently:
clLibrary.Where(x => x.LastSyncToWebsite < x.Modified)

This generates a new IEnumerable, leaving clLibrary unchanged. If clLibrary is of type List<T>, you can:
clLibrary = clLibrary.Where(x => x.LastSyncToWebsite < x.Modified).ToList();

If clLibrary is of type T[], you can:
clLibrary = clLibrary.Where(x => x.LastSyncToWebsite < x.Modified).ToArray();


text:
Q: Node Permission Comparison in two AEM Environmenrs I wanted to write a Jenkins python job to compare the difference in Node permissions in two different AEM environments. In the Jenkins UI I should be able to configure which environments to compare and which path to compare. I need the output to be in such a way that it should have environment-1 and environment-2, the path that is being compared and the permissions they have.  For Example in the Dev environment, for the path /content/dam/test we have only read permissions and for the same path we have read and write permissions in Stage Environment then the output should be
                  **Environment-1**       **Environment-2**

Content/dam/test       Read                Read & Write
The real question here is how do I retrieve the node permission from the two aem environments and how to compare and filter only the node paths that has difference in permissions?

A: Take a look at the PageInfo servlet. Example call: http://localhost:4502/libs/wcm/core/content/pageinfo.json?path=/content/we-retail/us/en
You will get a permissions node like this:
  "permissions": {
    "modify": true,
    "replicate": true,
    "read": true,
    "create": true,
    "delete": true,
    "acl_read": true,
    "acl_edit": true
  },

See: https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/pageinfo.html for more information.


text:
Q: LDAP error : Cannot find a partition Am using Apache Directory Studio to build LDAP with Spring Security application.
LDIF file:
version: 1

dn: o=mojo
objectClass: organization
objectClass: top
o: mojo

dn: ou=users,o=mojo
objectClass: organizationalUnit
objectClass: top
ou: users

dn: ou=groups,o=mojo
objectClass: organizationalUnit
objectClass: top
ou: groups

dn: cn=Ramesh Kotha,ou=users,o=mojo
objectClass: organizationalPerson
objectClass: person
objectClass: inetOrgPerson
objectClass: top
cn: Ramesh Kotha
sn: Kotha
uid: ramesh
userPassword:: cmFtZXNo

dn: cn=USER,ou=groups,o=mojo
objectClass: groupOfUniqueNames
objectClass: top
cn: USER
uniqueMember: cn=Ramesh Kotha,ou=users,o=mojo

dn: cn=ADMIN,ou=groups,o=mojo
objectClass: groupOfUniqueNames
objectClass: top
cn: ADMIN
uniqueMember: cn=Ramesh Kotha,ou=users,o=mojo

And my Test class is :
import java.util.List;

import javax.naming.NamingException;
import javax.naming.directory.Attributes;

import org.apache.log4j.Logger;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.filter.EqualsFilter;

public class LdapTest {

    static Logger logger = Logger.getLogger("LdapTest");

    public static void main(String[] args) throws Exception {
        LdapContextSource ctxSrc = new LdapContextSource();
        ctxSrc.setUrl("ldap://localhost:10389/o=mojo");
        ctxSrc.setBase("o=mojo");
        ctxSrc.setUserDn("uid=admin,ou=system");
        ctxSrc.setPassword("secret");

        ctxSrc.afterPropertiesSet();

        LdapTemplate tmpl = new LdapTemplate(ctxSrc);

        PersonDao dao = new PersonDao(tmpl);
        dao.getAllPersonNames();

    }

    public static class PersonDao {

        private LdapTemplate ldapTemplate;

        public PersonDao(LdapTemplate ldapTemplate) {
            this.ldapTemplate = ldapTemplate;
        }

        public void setLdapTemplate(LdapTemplate ldapTemplate) {
            this.ldapTemplate = ldapTemplate;
        }

        public List getAllPersonNames() throws Exception {
            logger.info("getAllPersonNames called : ");
            EqualsFilter filter = new EqualsFilter("objectclass", "person");
            return ldapTemplate.search(DistinguishedName.EMPTY_PATH,
                    filter.encode(),
                    new AttributesMapper() {

                        public Object mapFromAttributes(Attributes attrs) throws NamingException {
                            return attrs.get("cn").get();
                        }
                    });
        }
    }
}

ERROR
Exception in thread "main" org.springframework.ldap.NameNotFoundException: [LDAP: error code 32 - NO_SUCH_OBJECT: failed for     SearchRequest
        baseDn : '2.5.4.10=mojo/o=mojo'
        filter : '(2.5.4.0=person)'
        scope : whole subtree
        typesOnly : false
        Size Limit : no limit
        Time Limit : no limit
        Deref Aliases : deref Always
        attributes :
:  Cannot find a partition for 2.5.4.10=mojo/o=mojo]; nested exception is javax.naming.NameNotFoundException: [LDAP: error code 32 - NO_SUCH_OBJECT: failed for     SearchRequest
        baseDn : '2.5.4.10=mojo/o=mojo'
        filter : '(2.5.4.0=person)'
        scope : whole subtree
        typesOnly : false
        Size Limit : no limit
        Time Limit : no limit
        Deref Aliases : deref Always
        attributes :
:  Cannot find a partition for 2.5.4.10=mojo/o=mojo]; remaining name '/'
    at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:174)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:306)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:237)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:588)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:546)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:401)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:421)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:441)
    at com.onlineexam.util.LdapTest$PersonDao.getAllPersonNames(LdapTest.java:49)
    at com.onlineexam.util.LdapTest.main(LdapTest.java:30)
Caused by: javax.naming.NameNotFoundException: [LDAP: error code 32 - NO_SUCH_OBJECT: failed for     SearchRequest
        baseDn : '2.5.4.10=mojo/o=mojo'
        filter : '(2.5.4.0=person)'
        scope : whole subtree
        typesOnly : false
        Size Limit : no limit
        Time Limit : no limit
        Deref Aliases : deref Always
        attributes :
:  Cannot find a partition for 2.5.4.10=mojo/o=mojo]; remaining name '/'
    at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3030)
    at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2951)
    at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2758)
    at com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1812)
    at com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1735)
    at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(ComponentDirContext.java:368)
    at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:338)
    at javax.naming.directory.InitialDirContext.search(InitialDirContext.java:257)
    at org.springframework.ldap.core.LdapTemplate$3.executeSearch(LdapTemplate.java:231)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:293)
    ... 8 more

A: Just changed the URL to ctxSrc.setUrl("ldap://localhost:10389"); it is working fine.


text:
Q: how to make tkinter identify a defined object? The code:
from tkinter import *

def show (A, B, C, D):

    if A == "Large":

        Label1 = Label(root, text=A).pack()

    if B == "Medium":

        Label1 = Label(root, text=B).pack()

    if C == "Small":

        Label1 = Label(root, text=C).pack()

    if D == "Infinitesimal":

        Label1 = Label(root, text=D).pack()

def clear ():
    Label1.destroy()

root = Tk()
root.geometry("500x500+200+200")

var1 = StringVar()
var2 = StringVar()
var3 = StringVar()
var4 = StringVar()

a =Checkbutton(root, text="Large?", variable=var1, onvalue="Large")
a.deselect()
a.pack()

b =Checkbutton(root, text="Medium?", variable=var2, onvalue="Medium")
b.deselect()
b.pack()

c =Checkbutton(root, text="Small?", variable=var3, onvalue="Small")
c.deselect()
c.pack()

d =Checkbutton(root, text="Infinitesimal?", variable=var4, onvalue="Infinitesimal")
d.deselect()
d.pack()

W = Button(root, text="Submit", command=lambda: show(var1.get(), var2.get(), var3.get(), var4.get(), )).pack()

x = Button(root, text="Clear", command=clear).pack()

root.mainloop()

The initial checked list of items will post, but, then, suppose one wants to clear the screen using the clear button.  That's when I run into the following error.
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "<ipython-input-55-b81bc2ffe1d0>", line 22, in clear
    Label1.destroy()
NameError: name 'Label1' is not defined

My concern isnt so much in just fixing this one script, but I am interested in understanding what I did wrong and how to handle this type of error.
why is not the computer identifying 'Label1' as defined?

A: In the show() function, at the very start of it, add global Label1.
Also, if you want: What are Global and Local variables in Python?


text:
Q: If $p=pc$, does this imply $c=1$ in ring $R$? Let $R$ be a ring, where $p=pc$ for $p,c\in R$. Does $c$ have to be equal to $1$? $R$ may not be an integral domain.
Note that $p,c\neq 0$.
Thanks!

A: In $\;R=\Bbb Z_8:=\Bbb Z/8\Bbb Z\;$ ,we have that
$$6=6\cdot 5$$
but certainly $\;6\neq 1\pmod 8\;$ ...

A: Hint $\ \Bbb Z[p,c]/(p-pc)$ $\phantom{......................}$

A: Nontrivial idempotents give counterexamples. The simplest one that comes to mind is
$$
\begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}
$$
in $M_2(\mathbb{Z})$, for instance.

A: An integral domain is defined to be a ring with the cancellation property. So cancellation does not work in general in a ring that is not an integral domain. Zero divisors, which exist in any ring that is not an integral domain, will provide counterexamples. Consider $R^2$ as a direct product of any unital ring $R$ with itself. Addition and multiplication are defined component-wise as in $R$. Take  $p=(a,0)$, for any nonzero a $   \epsilon $ $R$. Then take $c=(1,b)$ for any b $\epsilon$ $R$. Then $pc=(a,0)(1,b)=(a,0)=p$. So no, it does not hold. It does most certainly hold in integral domains, however.


text:
Q: How to use SQL MERGE to remove duplicates, and update data? I am doing some house-keeping on duplicate data. I have different tables like Recipes, Ingredients, and RecipeIngredients.
In the Ingredients table, users have previously added multiple ingredients with the same name/title, e.g., "chicken" will appear many times instead of just one. I want to remove the duplicates but still keep a reference to the recipe.
I am trying to use SQL MERGE but it is deleting the wrong data, and I have starred myself blind on it. What am I doing wrong / it's probably just some quick fix??
When I run the code below, I get this table relation:
Chicken Recipe
Chicken

Burger Recipe
Salt, Pepper, Patty

But what I really want is:
Chicken Recipe
Chicken, Salt

Burger Recipe
Salt, Pepper, Patty

The MERGE statement deletes the "Salt" from RecipeIngredient instead of removing the duplicate. What am I doing wrong?
-- create table structure
CREATE TABLE #Recipes (
    Id int,
    Title nvarchar(50)
)

CREATE TABLE #Ingredients (
    Id int,
    Title nvarchar(50)
)

CREATE TABLE #RecipeIngredients (
    Id int,
    Recipe_id int,
    Ingredient_id int
)

-- load data
INSERT INTO #Recipes (Id,Title) VALUES (1,'Chicken Recipe');
INSERT INTO #Recipes (Id,Title) VALUES (2,'Burger Recipe');

INSERT INTO #Ingredients (Id,Title) VALUES (1,'Chicken');
INSERT INTO #Ingredients (Id,Title) VALUES (2,'Chicken'); -- duplicate ingredient
INSERT INTO #Ingredients (Id,Title) VALUES (3,'Salt');
INSERT INTO #Ingredients (Id,Title) VALUES (4,'Pepper');
INSERT INTO #Ingredients (Id,Title) VALUES (5,'Patty');

INSERT INTO #RecipeIngredients (Id,Recipe_id,Ingredient_id) VALUES (1,1,2); -- chicken has chicken
INSERT INTO #RecipeIngredients (Id,Recipe_id,Ingredient_id) VALUES (2,1,3); -- chicken has salt

INSERT INTO #RecipeIngredients (Id,Recipe_id,Ingredient_id) VALUES (3,2,3); -- burger has salt
INSERT INTO #RecipeIngredients (Id,Recipe_id,Ingredient_id) VALUES (4,2,4); -- burger has pepper
INSERT INTO #RecipeIngredients (Id,Recipe_id,Ingredient_id) VALUES (5,2,5); -- burger has patty

-- try to clean up
MERGE #RecipeIngredients
USING
(
    SELECT MAX(id) as MyId
    FROM #Ingredients
    GROUP BY Title
) NewIngredients ON #RecipeIngredients.Id = NewIngredients.MyId
WHEN MATCHED THEN
    UPDATE SET #RecipeIngredients.Ingredient_id = NewIngredients.MyId
WHEN NOT MATCHED BY SOURCE THEN DELETE;
GO

-- delete duplicate ingredients, i.e., that no longer has a value in table #RecipeIngredients
DELETE FROM #Ingredients WHERE Id NOT IN (SELECT Ingredient_Id FROM #RecipeIngredients)

 -- clean up
DROP TABLE #Recipes
DROP TABLE #Ingredients
DROP TABLE #RecipeIngredients

A: You should first update all the duplicate IDs to the single ID and then do the cleanup.
I've changed the winning ID determination from MAX to MIN since it will leave and have the same value in case there was an insert inbetween (hopefully you increment IDs as identity). Or you may use SNAPSHOT isolation level to enforce the max (or SERIALIZABLE to stop producing more new duplicates during this transaction). Also the cleanup of #Ingredients table should not use in filter, because as of design it is ok to have unused ingredients and users do not want to lose their data. So I've deleted the duplicates in the same way with MIN(id).
This is updated MERGE statement which sets Ingredient_ID to the single value
MERGE #RecipeIngredients as t
USING
(
    SELECT id, min(id) over(partition by title) as MaxId
    FROM #Ingredients
) as NewIngredients
  ON t.Ingredient_Id = NewIngredients.Id
WHEN MATCHED THEN
  UPDATE SET t.Ingredient_id = NewIngredients.MaxId;

Then I remove the duplicates from the #RecipeIngredients:
/*Cleanup duplicates from RecipeIngredients*/
delete t from (
  select
    row_number() over(
      partition by
        Recipe_id,
        Ingredient_id

      order by
        id asc
    ) as rn
  from #RecipeIngredients
) as t
where rn > 1

And finally cleanup the deduplicated records in #Ingredients table:
delete t from (
  select
    id,
    min(id) over(partition by title) as minid
  from #Ingredients
) as t
where id <> minid

And all the code in the db<>fiddle is here

UPD
I've added the more robust way to do a cleanup:

*

*remove duplicates from #Ingredients table first

*capture the deleted records

*then update Ingredient_Id for that deleted IDs in the #RecipeIngredients table, purging the duplicates in it (that can be created after unification, I do not know if it is the case) with MERGE statement.

Here's the new code and db<>fiddle for it. Also I've added anothed duplicated ingredient in #Ingredients table and another ingredient with different Ingredient_Id in #RecipeIngredients table (to show the MERGE's deletion part).
/*Declare the table for unified ingredients*/
declare @deletedIngredients table (
  id int,
  unifiedId int
);

/*Cleanup of duplicate ingredients and
  catch the deleted records with the corresponding unified Id
*/
with i_del as (
  /*Leave only the first (by ID) record with the same name*/
  select id, min(id) over(partition by title) as unifiedId
  from #Ingredients
)
delete from i
  /*Catch the deleted records and corresponding unified Ids*/
  output
    deleted.id,
    i_del.unifiedId

  into @deletedIngredients

from #Ingredients as i
  join i_del
    on i.id = i_del.id
/*Remove only duplicates where Id is not equal to the master record Id*/
where i.id <> i_del.unifiedId
;

/*Then do an update of IDs on the RecipeIngredients
  and delete the duplicates from it (that can be created during the unification of Ingredients_Id)
*/
merge into #RecipeIngredients as t
using (
  select
    ri.id,
    i.unifiedid,
    /*Number the rows per Receipe_Id and new Ingredient_Id*/
    row_number() over(
      partition by
        ri.Recipe_Id,
        i.unifiedId

      order by ri.id asc
    ) as rn
  from #RecipeIngredients as ri
    join @deletedIngredients as i
      on ri.Ingredient_Id = i.id
) as s
  on t.id = s.id
/*The first record should have the new unified id*/
when matched and s.rn = 1 then
  update set ingredient_id = s.unifiedId
/*And unintentionally created duplicate should be removed*/
when matched and s.rn > 1 then delete
;

commit;


text:
Q: VGA and Audio assigned to VFIO but not USB and Serial Controller of RTX 2080 Summary
I'm trying to set-up GPU-passthrough on a linux host with KVM so that I might run a Windows guest for gaming. I've been having a problem where some IOMMU entries (all belonging to the GPU I wish to passthrough) are being assigned to the vfio bus, while others are assigned to the nvidia-gpu drivers.
Hardware
CPU
- Threadripper 1950X
GPU
- Sapphire RX 480 (AMD, meant for host graphics)
- MSI Duke RTX 2080 (nVidia, meant for guest graphics)
MoBo
- MSI Carbon Gaming Pro AC x399
Problem
When I try to passthrough my nVidia GPU, I get the error Please ensure all devices within the iommu_group are bound to their vfio bus driver. (see images below).

*

*The setup in virt-manager: https://i.imgur.com/Tw0CiBu.png

*The error I get: https://i.imgur.com/lqgHViw.png
When I run lspci -k, I find the following records:
0b:00.0 VGA compatible controller [0300]: NVIDIA Corporation GV104 [GeForce GTX 1180] [10de:1e87] (rev a1)
    Subsystem: Micro-Star International Co., Ltd. [MSI] Device [1462:3721]
    Kernel driver in use: vfio-pci
    Kernel modules: nvidiafb, nouveau
0b:00.1 Audio device [0403]: NVIDIA Corporation Device [10de:10f8] (rev a1)
    Subsystem: Micro-Star International Co., Ltd. [MSI] Device [1462:3721]
    Kernel driver in use: vfio-pci
    Kernel modules: snd_hda_intel
0b:00.2 USB controller [0c03]: NVIDIA Corporation Device [10de:1ad8] (rev a1)
    Subsystem: Micro-Star International Co., Ltd. [MSI] Device [1462:3721]
    Kernel driver in use: xhci_hcd
0b:00.3 Serial bus controller [0c80]: NVIDIA Corporation Device [10de:1ad9] (rev a1)
    Subsystem: Micro-Star International Co., Ltd. [MSI] Device [1462:3721]
    Kernel driver in use: nvidia-gpu
    Kernel modules: i2c_nvidia_gpu
41:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] Ellesmere [Radeon RX 470/480/570/570X/580/580X] [1002:67df] (rev c7)
    Subsystem: PC Partner Limited / Sapphire Technology Radeon RX 470/480 [174b:e347]
    Kernel driver in use: amdgpu
    Kernel modules: amdgpu
41:00.1 Audio device [0403]: Advanced Micro Devices, Inc. [AMD/ATI] Ellesmere [Radeon RX 580] [1002:aaf0]
    Subsystem: PC Partner Limited / Sapphire Technology Ellesmere [Radeon RX 580] [174b:aaf0]
    Kernel driver in use: snd_hda_intel
    Kernel modules: snd_hda_intel

Which reports that the RTX 2080 is being used by vfio-pci on 0b:00.0, and 0b:00.1, but 0b:00.2 and 0b.00.3 (which all belong to the RTX 2080) are being used by xhci_hcd and nvidia-gpu.
My understanding is that this is the issue.
What I've done
I mostly referred a Level1 thread and a blog post by Jack Ford:
Blacklisted Nouveau
in file /etc/modprobe.d/blacklist-nouveau.conf
blacklist nouveau
options nouveau modeset=0

Updated GRUB
In /etc/default/grub:
GRUB_DEFAULT=0
GRUB_TIMEOUT_STYLE=hidden
GRUB_TIMEOUT=0
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash amd_iommu=on vfio-pci.ids=10de:1e87,10de:10f8,10de:1ad8,10de:1ad9"
GRUB_CMDLINE_LINUX=""

Added kernel modules
In /etc/modules:
vfio
vfio_iommu_type1
vfio_pci
vfio_virqfd

In /etc/modprobe.d/vfio.conf:
options vfio-pci ids=10de:1e87,10de:10f8,10de:1ad8,10de:1ad9

In /etc/modules-load.d/vfio-pci.conf:
vfio-pci

Confirmed IOMMU/VFIO is enabled
$ dmesg | grep -E "DMAR|IOMMU"
[    0.946794] AMD-Vi: IOMMU performance counters supported
[    0.946855] AMD-Vi: IOMMU performance counters supported
[    0.976135] AMD-Vi: Found IOMMU at 0000:00:00.2 cap 0x40
[    0.976139] AMD-Vi: Found IOMMU at 0000:40:00.2 cap 0x40
[    0.977856] perf/amd_iommu: Detected AMD IOMMU #0 (2 banks, 4 counters/bank).
[    0.977873] perf/amd_iommu: Detected AMD IOMMU #1 (2 banks, 4 counters/bank).
[    1.367168] AMD-Vi: AMD IOMMUv2 driver by Joerg Roedel <jroedel@suse.de>
$ dmesg | grep -i vfio
[    0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-5.0.0-37-generic root=UUID=27ff4f46-db04-4ca0-8981-191a45c365ad ro quiet splash amd_iommu=on vfio-pci.ids=10de:1e87,10de:10f8,10de:1ad8,10de:1ad9 vt.handoff=1
[    0.000000] Kernel command line: BOOT_IMAGE=/boot/vmlinuz-5.0.0-37-generic root=UUID=27ff4f46-db04-4ca0-8981-191a45c365ad ro quiet splash amd_iommu=on vfio-pci.ids=10de:1e87,10de:10f8,10de:1ad8,10de:1ad9 vt.handoff=1
[    2.667765] VFIO - User Level meta-driver version: 0.3
[    2.675583] vfio-pci 0000:0b:00.0: vgaarb: changed VGA decodes: olddecodes=io+mem,decodes=io+mem:owns=none
[    2.692215] vfio_pci: add [10de:1e87[ffffffff:ffffffff]] class 0x000000/00000000
[    2.712193] vfio_pci: add [10de:10f8[ffffffff:ffffffff]] class 0x000000/00000000
[    2.712199] vfio_pci: add [10de:1ad8[ffffffff:ffffffff]] class 0x000000/00000000
[    2.712204] vfio_pci: add [10de:1ad9[ffffffff:ffffffff]] class 0x000000/00000000
[    4.960496] vfio-pci 0000:0b:00.0: vgaarb: changed VGA decodes: olddecodes=io+mem,decodes=io+mem:owns=none

Conclusion
Thanks so much for helping out... I don't know what those two other entries are in the nVidia IOMMU group, but they all appear to belong to the nVidia device. I'm guessing if I could disable the USB and Serial controller, things might work?

A: Recently facing the same issue. The main objective is to have wifi use vfio, but  need to move a USB and a RAM also, as they are in the same IOMMU group.
I did all the steps stated in questions, got RAM and WIFI device on vfio, but not USB.
Finally found out that the xhci_hcd is compiled into the kernel, not as module. So  putting the USB controller id in GRUB_CMDLINE_LINUX_DEFAULT, the USB controller will still bind with xhci_hcd, as it is already inside the kernel. To confirm if your kernel compile xhci_hcd within:
modprobe -D xhci_hcd

If your output is:
builtin xhci_hcd

Then your kernel contain xhci_hcd.
I end up with a script to do the manual driver unbind and bind:
#!/bin/sh
PCI_HID=
echo -n "$PCI_HID" > /sys/bus/pci/drivers/xhci_hcd/unbind
echo -n "$PCI_HID" > /sys/bus/pci/drivers/vfio-pci/bind

For the question. Following should work:
#!/bin/sh
PCI_HID="0000:0b:00.2"
echo -n "$PCI_HID" > /sys/bus/pci/drivers/xhci_hcd/unbind
echo -n "$PCI_HID" > /sys/bus/pci/drivers/vfio-pci/bind
PCI_HID="0000:0b:00.3"
echo -n "$PCI_HID" > /sys/bus/pci/drivers/nvidia-gpu/unbind
echo -n "$PCI_HID" > /sys/bus/pci/drivers/vfio-pci/bind

PS: Though we are manually binding and unbinding drivers, the GRUB_CMDLINE_LINUX_DEFAULT and module config steps are still necessary, else vfio will not bind to the USB controller.

A: I know I am a bit late to the party but I hope the following can help people facing similar issues.
Please note I have only tested this on discrete USB controllers.
xhci_hcd is indeed built in the kernel so it claims the USB controller and unless a workaround is found such as a script to bind/unbind vfio-pci is not assigned as the kernel in use.
Another way to solve this issue is to use the following command:
sudo driverctl -v set-override 0000:0X:00 vfio-pci

Where 0000:0X:00 is your pci id.
Upon reboot the driver assigned will be automatically be vfio-pci.


text:
Q: Networkx add_weighted_edges_from return strange result I'm trying to init a Networkx.MultiDiGraph with weight for all edges.
I have a dictionary as follow:
edges = {(Node1, Node2, 1.0): <some_object>,
         (Node1, Node3, 2.0): <some_object>,
         ...}

I'm running the following code:
nx_graph: nx.MultiDiGraph = nx.MultiDiGraph()
nx_graph.add_nodes_from(nodes.values())           # This works fine.
nx_graph.add_weighted_edges_from(edges.keys())
nx.set_edge_attributes(nx_graph, edges, 'edge')

but for some unknown reason, nx_graph contain the following edges:
print(nx_graph.edges)
>>>[(Node1, Node2, 0), (Node1, Node3, 0), ...]

and the edges doesn't have any attributes at all.
Does someone know why this is happening and how to fix it?
Thanks.

A: I know, it's annoying for me too, but nx just has too many intertwining methods to access data of edges. You just used an incorrect way. G.edges lists all the edges, nothing more. (I use G as nx_graph for simplicity)
In order to list edges together with attributes use G.edges.data() or G.edges(data=True).
Remark: in order to list edges with specific attribute attached, use G.edges.data(<attr>) (as tuples with corresponding attributes attached to the last item) or nx.get_edge_attributes(G, weight') (as dictionary that maps edges to attributes).

A: The guy above me was right, i did print the edges wrong.
But that wasn't the problem, that was a symptom of my main problem: Networkx.add_weighted_edges() doesn't defined well for nx.MultiDiGraph.
i'll explain: while using Networkx.add_weighted_edges(), the ebunch parameter (see documentation here)
using the triplet (source, target, weight) for adding an edge with weight.
Meanwhile, in nx.MultiDiGraph, every edge defined with (source, target, unique_key).
So, Networkx.add_weighted_edges() doesn't reference the unique_key parameter in the edge, and that was the cause to my problem.
To solve this, i use the following code:
First, i changed edges.keys() so it will contain the keys of every edge:
edges = {(Node1, Node2, key1): <some_object>,
         (Node1, Node3, key2): <some_object>,
         ...}

Then, i used the following code:
edges_weights = {(Node1, Node2, key1): 1.0,
                 (Node1, Node3, key2): 2.0,
                 ...}

nx_graph: nx.MultiDiGraph = nx.MultiDiGraph()
nx_graph.add_nodes_from(nodes.values())
nx_graph.add_edges_from(edges.keys())
nx.set_edge_attributes(nx_graph, edges_weights, 'weight')
nx.set_edge_attributes(nx_graph, edges, '<attribute_name>')

And that works fine for me.


text:
Q: i want background image displaying loading in ie, as it is displaying the image after loading fully am facing this problem in IE in all versions. Rest browsers it is fine
once i hit this url in IE http://projects.marswebsolutions.com/kidzntoyz6/ , the page seems to be loading normally but the body background the loading part of the image is not displaying. The whole image comes only after it has finished loading. The main problem that am facing is that, i have used a jpeg image for edges nd it is displaying which shuld not be displaying as it looks very ugly..
Please find me a solution, Thanks in advance

A: according to my knowledge on html5 you can use this line...
.
<meta charset="utf-8" />

 <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
    Remove this if you use the .htaccess -->

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

add this in your design page.

A: Just some quick thoughts. Put the X-UA-Compatible tag to the top of the head.
do you have the url to the background image? I don't see any background image in any browser right now and I do not see anything used in the CSS to point to a background image.
Also move the script references to the bottom of your page, and combine the scripts into a single file. I would also minify, gzip and set a futures expires header on the scripts. These are some web performance best practice. You site is nice and fast, but these things can make it faster. I am just a performance geek and I am always checking for these things ;)


text:
Q: Mysql2::Error: Out of sort memory, consider increasing server sort buffer size using docker-compose.yml Hi I'm building a rails app and I imported lots of data and inserted into the database. Some tables are okay and some tables have some errors that says out of sort memory.
SQL ERROR
Mysql2::Error: Out of sort memory, consider increasing server sort buffer size

How do you increase server sort buffer size using the docker-compose.yml command?
I've tried this one:
version: '3'
services:
  db:
    image: mysql:latest
    command:
      - --default-authentication-plugin=mysql_native_password
      - --innodb-buffer-pool-size=402653184

I did add this command:
--innodb-buffer-pool-size=402653184

but I'm still getting the same error that it is out of memory. Is there any way to increase the buffer size using the docker-compose.yml

A: Turns out when I've tested this, this resolves my error in the mysql container in docker.
Add this command in docker-compose.yml under your db services to increase your memory.
--sort_buffer_size=1073741824

To remove the error when your application is running on docker.
Error "1038 Out of sort memory, consider increasing server sort buffer size

Note that 1073741824 is equal to bytes and will result to 1GB memory allocation.

A: First thing, 402653184 (byte) which is around 400 MB, if you are not sure about this memory limit then increase a bit more
    command:
      - --default-authentication-plugin=mysql_native_password
      - --innodb-buffer-pool-size=1G

And then verify the changes inside your container.
SELECT @@innodb_buffer_pool_size/1024/1024/1024;
#it should return 1GB

Also, there is a possibility that something else causing the issue, you can check CPU, memory and slow query logs
SHOW ENGINE INNODB STATUS

you can then analyse the output base on current buffer pool size
BUFFER POOL AND MEMORY
----------------------
BUFFER POOL AND MEMORY
----------------------
Total large memory allocated 412090368
Dictionary memory allocated 380237
Buffer pool size   24576
Free buffers       23618
Database pages     954
Old database pages 372
Modified db pages  0
Pending reads      0

MySQL optimization


text:
Q: How to set up sshd so that it never asks for a password for a specific user? I have a dedicated system account named "git" that is managed by gitlab/gitolite. Users connecting to this account always use SSH keys, "git" user doesn't have a password. If users connect without a SSH key or with a mis-configured key, they get confused by being asked for a password. I'm looking for a way how to set up the server so that in such a case it doesn't ask for a password and instead it displays some kind of user-friendly message ("Your key is missing or invalid" etc.) and drops the connection. Is it possible, either in sshd configuration, or in some other way (PAM perhaps)?
Note that I'm not asking how to set up public/private password-less connections. Just how to prevent the server asking for a password for a single specific user.
(I understand that such setup reveals to a potential attacker that user "git" exists in the system. But since "git" has no password and an attacker can easily determine its existence anyway, I consider it only a low risk.)

A: You can disable password logins for that specific user. You can't provide a specific message, but at least they won't be prompted for a password. Add the following in /etc/ssh/sshd_config:
Match user git
    PasswordAuthentication no
    ChallengeResponseAuthentication no


text:
Q: LU decomposition; do permutation matrices commute? I have an assignment for my Numerical Methods class to write a function that finds the PA=LU
decomposition for a given matrix A and returns P, L, and U.
Nevermind the coding problems for a moment; there is a major mathematical problem I'm having that my professor seems incapable of addressing, and after searching for hours (perhaps inefficiently) I could find no accounting of it. How do we extricate the permutation matrices from the row elimination matrices?
Essentially the idea, if I understand it correctly, is that we perform a series of transformations on a matrix $A$ by applying successive lower triangular matrices that eliminate single elements, thus $L_nL_{n-1}...L_2L_1A = U$. In my understanding, this is computationally useful because lower triangular atomic matrices can be inverted by changing the sign of the off-diagonal element, so $A = L_1^{-1}L_2^{-1}...U$.
That's all fine (assuming I'm correct), but the introduction of pivot matrices between each $L_j$ seems to make the problem intractable. In every accounting I've seen some sorcery occurs that looks like this:
$$L_nP_nL_{n-1}...P_3L_2P_2L_1P_1A = U \Rightarrow P_nP_{n-1}...P_2P_1L_nL_{n-1}...L_2L_1A = U$$
And no one bothers to explain how this happens or in fact even states it explicitly.
If possible I would like to know
a) Is this operationally acceptable?
b) What properties of these respective classes of matrices make this kind of willy-nilly commutation legal?
c) Is my understanding of the method and its advantages accurate?

A: No, in general permutation matrices do not commute.
It seems like you are using the Doolittle algorithm, so I am going to assume that indeed you are.
Let $U_i$ be the $i$:th step in your LU decomposition of $A$, so
$$\begin{align}
U_0 &= A \\
U_1 &= L_1P_1U_0 \\
\vdots \\
U_n &= L_nP_nU_{n-1}
\end{align}$$
This corresponds well to how one would do LU-decomposition by hand; get the largest element as the leading element on the row you are at (i.e. multiply with $P_k$), then eliminate that column on the following rows (i.e. multply with $L_k$).
As you remark, the $L_i$ will be atomic lower triangular matrices, the non-zero elements all being in column $i$. The inverse of $L_i$ can be constructed by negating all off-diagonal elements, see Wikipedia.
The permutation matrix $P_j$ will be a permutation matrix switching row $j$ with a row $k \geq j$, if multiplied on the left of the matrix you want to transform. The inverse to $P_j$ is $P_j$ itself (since $P_j$  switches row $j$ with row $k$, you can undo this by doing the same thing).
Consider the product $P_jL_i$ for $i < j$. $P_j$ will switch two rows of $L_i$, row $j$ and $k \geq j > i$. We switch elements in $L_i$ as follows:
$$\begin{align}
L_{j,i} &\leftrightarrow L_{k,i}  \\
L_{j,j} &\leftrightarrow L_{k,j}
\end{align}$$
Let $L_k'$ be the matrix produced by switching just the off-diagonal elements (the first switch above). Note that this is still an atomic lower triangular matrix. We can then produce $P_jL_i$ by just switching column $j$ with column $k$ in $L_k'$, which is multiplying by $P_j$ on the right. Here it is important that $i < j, k$, so column $i$ in $L_i'$ is not changed! In other words:
$$P_j L_i = L_i' P_j$$
Thus, you can from your equation
$$L_nP_nL_{n-1}...P_3L_2P_2L_1P_1A = U$$
produce
$$L_n^S L_{n-1}^S \cdots L_1^S P_n P_{n-1} \cdots P_1A = U$$
which can be transformed to (note that $L_i^S$ is still atomic lower triangular):
$$PA = LU$$
taking
$$P = P_nP_{n-1} \cdots P_1$$
and
$$L = (L_n^S L_{n-1}^S \cdots L_1^S)^{-1}.$$
Here, $L_i^S$ is the matrix made by taking $L_i$ and applying all $P_j$ (on the left) for $j > i$ on the off-diagonal elements.
You do this by doing the following, starting with
$$L_nP_nL_{n-1}...P_3L_2P_2L_1P_1A = U$$
move the $P_2$ matrix to the right using $P_2L_1 = L_1' P_2$, producing:
$$L_nP_nL_{n-1}...P_3L_2L_1'P_2P_1A = U$$
then do the same for the matrix $P_3$, but this matrix you have to move to the right twice, using $P_3L_2 = L_2'P_3$ and $P_3L_1' = L_1''P_3$:
$$L_nP_nL_{n-1}...L_2'L_1''P_3P_2P_1A = U$$
and so on for every $P_j$.
As an example of $P_j L_i = L_i' P_j$ consider
$$P = \begin{pmatrix} 1 & 0 & 0 \\ 0 & 0 & 1 \\ 0 & 1 & 0 \end{pmatrix}$$
$$L = \begin{pmatrix} 1 & 0 & 0 \\ 2 & 1 & 0 \\ 3 & 0 & 1 \end{pmatrix}$$
$$L' = \begin{pmatrix} 1 & 0 & 0 \\ 3 & 1 & 0 \\ 2 & 0 & 1 \end{pmatrix}$$
$$PL = \begin{pmatrix} 1 & 0 & 0 \\ 3 & 0 & 1 \\ 2 & 1 & 0 \end{pmatrix}$$
$$L'P = \begin{pmatrix}1 & 0 & 0 \\ 3 & 0 & 1 \\ 2 & 1 & 0 \end{pmatrix}$$
So, to summarize: These special matrices almost commute, only small changes are needed to swap the matrices. However, all important properties of the matrices are preserved are when swapping them.

A: I found an answer based on matrix algebra rather than components here. Here's my attempt to reproduce it with some more detail.
Starting from
$$L_3 P_3 L_2 P_2 L_1 P_1 A = U$$
Define
$$\Lambda_1 = P_3 P_2 L_1 P_2^{-1} P_3^{-1}$$
$$\Lambda_2 = P_3 L_2 P_3^{-1}$$
$$\Lambda_3 = L_3$$
Calculating
$$\Lambda_3 \Lambda_2 \Lambda_1 P_3 P_2 P_1 = (L_3)(P_3 L_2 P_3^{-1})(P_3 P_2 L_1 P_2^{-1} P_3^{-1}) P_3 P_2 P_1 = L_3 P_3 L_2 P_2 L_1 P_1$$
We can swap this into our starting formula to get
$$\Lambda_3 \Lambda_2 \Lambda_1 P_3 P_2 P_1 A = U$$
And letting $\Lambda = \Lambda_1^{-1} \Lambda_2^{-1} \Lambda_3^{-1}$ and $P = P_3 P_2 P_1$ we have
$P A = \Lambda U$.
Now it remains to show that the $\Lambda_i$ are lower triangular and to answer your question about commuting head on. Notice that the $P_i$ only affect rows $i$ and below because the elimination algorithm has completed its work with the rows above $i$. The inverses of the $P_i$ will therefore also only need to affect those rows to unscramble things. Examining $\Lambda_1 = P_3 P_2 L_1 P_2^{-1} P_3^{-1}$ we see that $\Lambda_1$ swaps around rows 2 and below, applies $L_1$ to add multiples of the first row to those lower rows, then unswaps the rows. This is equivalent to adding appropriate multiples of $L_1$ to the original, unswapped rows, which we know is an operation described by a lower triangular matrix. Therefore the matrix $\Lambda_1$ which represents the aggregate operation $P_3 P_2 L_1 P_2^{-1} P_3^{-1}$ must be lower triangular.
In summary, the matrices don't commute as you had asked in your original question, but we can change an $L_i$ into a related vector $\Lambda_i$ by left- and right-multiplying by some permutation matrices. Because the commuting fails, our formula for $\Lambda$ isn't particularly pretty:
$$\Lambda = P_3 P_2 L_1^{-1} P_2^{-1} L_2^{-1} P_3^{-1} L_3^{-1}$$
However, we can get a neater conclusion if we return to
$$L_3 P_3 L_2 P_2 L_1 P_1 A = U$$
and let
$$M = L_3 P_3 L_2 P_2 L_1 P_1$$
so that $M A = U$. Then because $P A = \Lambda U$ we must have $P = \Lambda M$ or $\Lambda = P M^{-1}$. So we can calculate $\Lambda$ from our original $M$ just by applying the composition of our permutations to $M^{-1}$, which isn't quite as good as commuting but isn't half bad either.

A: $\require{color}$
I found @Calle explanation interesting but have a hard time following the arguments.
@kuzooroo explanation fits better my way of thinking but the arguments are too dense. I decided to start a new answer since my arguments will not fit in a comment slot.
Following @Calle:
Note that, since each $P_i$ is a one-cycle permutation
(one interchange),
$P_i^{-1}=P_i$ since doing an interchange twice bring the matrix to the same original form. We now should prove
that $\Lambda$ is a lower triangular matrix with ones in
the diagonal.
$\Lambda_3$ is, of course, a lower triangular with 1 in the diagonal. To prove that $\Lambda_2$ is lower triangular
with ones in the diagonal we take into account the fact that $L_2$ is atomic. That is,
\begin{eqnarray*}
  L_2 =
  \begin{pmatrix}
    1 & 0 & \cdots & 0 & \cdots & \cdots &\cdots & \cdots & 0  \\
    0 & 1 & \cdots & 0 & \cdots & \cdots &\cdots & \cdots & 0  \\
    \vdots & l_{32} & \ddots & \vdots & \vdots  &\vdots & \vdots & \vdots & \vdots\\
    \vdots & \vdots & \cdots & 1  & 0 &  \cdots &\cdots& \cdots & \vdots \\
    \vdots  & l_{i2} & \cdots & 0  & 1 & 0 &\cdots & \cdots & \vdots \\
    \vdots  & \vdots & \cdots & \vdots & \ddots &  \ddots & \ddots & \cdots & \vdots \\
    \vdots & l_{k2} & \vdots & \vdots & \vdots & 0 & 1  & 0 &  \vdots \\
    \vdots & \vdots & \vdots & \vdots & \vdots & \vdots &\ddots & \vdots &  0 \\
    0 &  0 & \cdots & 0 & \cdots & \cdots &\cdots & 0 &  1
  \end{pmatrix} \nonumber.
\end{eqnarray*}
Let us assume that $P_3$ interchanges rows $i$ with $k$.
(note that both $i$ and $k$ are larger than 2).
We have that
\begin{eqnarray*}
  P_3 L_2 =
  \begin{pmatrix}
    1 & 0 & \cdots & 0 & \cdots & \cdots &\cdots & \cdots & 0  \\
    0 & 1 & \cdots & 0 & \cdots & \cdots &\cdots & \cdots & 0  \\
    \vdots & l_{32} & \ddots & \vdots & \vdots  &\vdots & \vdots & \vdots & \vdots\\
    \vdots & \vdots & \cdots & 1  & 0 &  \cdots &\cdots& \cdots & \vdots \\
    \vdots & \boxed{l_{k2}} & \vdots & \vdots & \textcolor{green}{0} & 0 & \textcolor{blue}{1}  & 0 &  \vdots \\
    \vdots  & \vdots & \cdots & \vdots & \ddots &  \ddots & \ddots & \cdots & \vdots \\
    \vdots  & \boxed{l_{i2}} & \cdots & 0  & \textcolor{green}{1} & 0 & \textcolor{blue}{0} & \cdots & \vdots \\
    \vdots & \vdots & \vdots & \vdots & \vdots & \vdots &\ddots & \vdots &  0 \\
    0 &  0 & \cdots & 0 & \cdots & \cdots &\cdots & 0 &  1
  \end{pmatrix} \nonumber.
\end{eqnarray*}
Finally $P_3 L_2 P_3^{-1}= P_3 L_2 P_3$ ineterchanges
columns $i$ (green) with $k$ (blue) on $P_3 L_2$.
The $1$ in column $k$ (blue) takes the place of the 0
in column $i$ (green) . In the same way the $1$ in green in row $k$ takes the position of the blue $0$ on the same row.
That is
\begin{eqnarray*}
  P_3 L_2 P_3^{-1} =
  \begin{pmatrix}
    1 & 0 & \cdots & 0 & \cdots & \cdots &\cdots & \cdots & 0  \\
    0 & 1 & \cdots & 0 & \cdots & \cdots &\cdots & \cdots & 0  \\
    \vdots & l_{32} & \ddots & \vdots & \vdots  &\vdots & \vdots & \vdots & \vdots\\
    \vdots & \vdots & \cdots & 1  & 0 &  \cdots &\cdots& \cdots & \vdots \\
    \vdots & \boxed{l_{k2}} & \vdots & \vdots & \textcolor{green}{1} & 0 & \textcolor{blue}{0}  & 0 &  \vdots \\
    \vdots  & \vdots & \cdots & \vdots & \ddots &  \ddots & \ddots & \cdots & \vdots \\
    \vdots  & \boxed{l_{i2}} & \cdots & 0  & \textcolor{green}{0} & 0 & \textcolor{blue}{1} & \cdots & \vdots \\
    \vdots & \vdots & \vdots & \vdots & \vdots & \vdots &\ddots & \vdots &  0 \\
    0 &  0 & \cdots & 0 & \cdots & \cdots &\cdots & 0 &  1 .
  \end{pmatrix} \nonumber.
\end{eqnarray*}e
This is, again, an atomic matrix with the entries
$l_{i2}$ and $l_{k2}$ interchanged.
In the same way, $P_2 L_1 P_2^{-1}$ is atomic and so it is
$\Lambda_1 =  P_3 P_2 L_1 P_2^{-1} P_3^{-1}$,
In general for
\begin{eqnarray*}
  U= L_{n-1} P_{n-1} L_{n-2} P_{n-2} \cdots   P_2 L_1 P_1 A,
\end{eqnarray*}
we define
\begin{eqnarray*}
  \Lambda_i =     P_{n-1} \cdots P_{i+2} P_{i+1} L_i P_{i+1}^{-1} P_{i+2}^{-1}
   \cdots P_{n-1}^{-1}.
\end{eqnarray*}
where we assume $P_0=I$.
The same procedure shown above guarantee that $\Lambda_i$
is atomic and so $\Lambda=\prod \Lambda_i$ is lower triangular with ones in the diagonal.
Hence this completes what is needed to verify that
$PA=LU$.


text:
Q: Deselect all other select elements (Bootstrap) (jQuery) I posted a similar question a few days ago, but it seems that the reference solution did not work as there seemed to be a bootstrap conflict, where the jQuery was affecting the select element instead of the additional divs generated by bootstrap
For reference, I have a 2 <select> elements which look like the following:
<select class="selectpicker form-control alternate-linked-select-box" id="input-room">
  <option>...</option>

</select>

The intended, functionality I am trying to achieve, is to completely deselect the other element when the current <select> element has been changed.
The previously proposed solution with jQuery was this. I'll also include it here for reference:
var sels = $(".alternate-linked-select-box").on("change", e =>
  sels.not(e.target).find("option:selected").prop("selected", false)
);

However, this does not work with bootstrap as the select elements do not seem to be affected.
Since then, I've also tried disabling everything to see if it had any affect, but to no avail.
$('.alternate-linked-select-box').selectpicker('val', '');

I presume I am doing something very wrong, as I have never really used bootstrap before. Any help is appreciated!

A: For example you have 2 selections with id input-room1 and input-room2, apply below code to reset room2 selection when room1 selection is changed.
$(document).ready(function(){
  //init
  $("#input-room1").prop("selectedIndex", -1);
  $("#input-room2").prop("selectedIndex", -1);
})
$('#input-room1').on('change',function(){
  $("#input-room2").prop("selectedIndex", -1);
})


text:
Q: How can I make a submenu I have the next database:

I have the below function:
<?php

$connection = mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("database1", $connection) or die(mysql_error());

function loop_array($array = array(), $parent_id = 0)

{
  if (!empty($array[$parent_id])) {
      echo '
';
      foreach ($array[$parent_id] as $items) {
          echo '
';
          echo ''.$items['title'].'';
          loop_array($array, $items['id']);
          echo '
';
      }
  }
}

function displays_menus_revised()

{
  $sql = "SELECT * FROM pages";
  $query = mysql_query($sql) or die(mysql_error());
  $array = array();
  if (mysql_num_rows($query)) {
    while ($rows = mysql_fetch_array($query)) {
      $array[$rows['parent_id']][] = $rows;
    }
    loop_array($array);
  }
}

 ?>

My problem is the funtion show the records like in the left picture. I want the function to show the records like in the right picture. Can you tell me where is the problem? What i must change that the function show records like in the right picture? Thanks.

A: So nice code, with such a small slip.  Only the closing 'ul' is missing.
function loop_array($array = array(), $parent_id = 0)
{
  if (!empty($array[$parent_id])) {
      echo '
';
      foreach ($array[$parent_id] as $items) {
          echo '
';
          echo ''.$items['title'].'';
          loop_array($array, $items['id']);
          echo '
';
      }
      echo '
';
  }
}


text:
Q: what is the correct way to wait for all the volumes to get attached to instances I am using fog library to create instances in AWS, while creating the instances I am also attaching EBS volumes to the instances like this:
server = conn.servers.new(:image_id => 'ami-XXXXX',
                          :flavor_id => 'm1.medium',
                          :keyname => 'secret123',
                          :groups => 'gourp123',
                          :block_device_mapping => [
                            {
                              "DeviceName"=>"sdi",
                              "Ebs.VolumeSize"=>10,
                              "Ebs.DeleteOnTermination"=>false
                            },
                            {
                              "DeviceName"=>"sdj",
                              "Ebs.VolumeSize"=>10,
                              "Ebs.DeleteOnTermination"=>false
                            }
                          ])

Now, I have to format the volumes that are being attached using net-ssh, I noticed that using server.wait_for { ready? } does not help as it waits until the server gets into running state and returns back. Which is not a reliable method to format the partitions as the volumes might not have been mounted yet!
So I found another option which is to wait for the console output of the instance to get back using:
server.wait_for { console_output.body['output'] =~ /^cloud-init boot finished/ }
and then format the volumes, which is getting the job done for now. But the console_output takes a very long time to come back.
Is there any better/reliable way of making sure the volumes are mounted and ready for partitioning?


text:
Q: Passing Error from HttpModule to MVC Application I have a custom HttpModule for authentication. In the AuthenticateRequest event handler of the module I check if a custom SSO ticket is available and in that case perform some authentication logic.
If the SSO ticket is available, but incorrect, I would like to show a friendly error message to the user. I would prefer to be able to somehow set HTTP Status 401 (Unauthorized, used when authentication fails) and pass on a meaningful error message from the http module.
I would then like the MVC application to somehow get this information and use it to render a custom 401 error page which includes the meaningful error message from the module.
What's the best way to raise the error in the http module and what's the best way to have it display the error using the MVC application (to get the error message in the MVC application's layout)?

A: You could create a custom controllerfactory, and in your:
protected override IController GetControllerInstance(RequestContext context, Type controllerType)

You will have access to the HttpContext and RouteData through your context object.
If user is not authenticated you can manipulate your routedata to targed your desired controller/action with desired routeconstraints/parameters (for instance a http status message)


text:
Q: How can I update a CloudFormation stack with masked parameters using Ansible? I have a CloudFormation stack that was created using the Ansible cloudformation module, and then I have some masked parameters that was updated manually by a separate operations team.
Now I would like to update the stack to perform a version upgrade, and while this is easily done in the AWS Console and through the AWS CLI, I can't seem to find a way to do this through the Ansible module.
Based on another post here, it was noted that upgrades are not possible, and the only way was to simply not use Ansible.
I have tried using the Ansible cloudformation_facts module to try and fetch the parameters to no avail. Is there any other method to fetch this data from CloudFormation, or will I have to accept that I cannot use Ansible?
Thank you in advance.

A: You can fetch all the parameters from cloudformation using Ansbile with something like the below:
---
- name: Get CloudFormation stats
  cloudformation_facts:
    stack_name: "{{ stack_name }}"
    region: "{{ region }}"
  register: my_stack

If you had a parameter called "subnet-id", you could view what the return would like look like this:
---
- name: Get CloudFormation stats
  cloudformation_facts:
    stack_name: "{{ stack_name }}"
    region: "{{ region }}"
  register: my_stack

- debug: msg="{{ my_stack.ansible_facts.cloudformation[stack_name].stack_parameters.subnet-id }}"

The return would look like this:
ok: [localhost] => {
    "msg": "subnet12345"
}

If values are hashed out however, you won't be able to see what their value was - so the answer is that in that case, you shouldn't be updating cloudformation directly if you're trying to move over to Ansbile. Rather have the values updated in an encrypted file on your source control, and build from there with Ansible.