text:
Q: Can I use C-style casts when calling C functions from C++? I have read, both on this site and elsewhere, that the recommended programming style for C++ is to avoid using C-style casts, and prefer the C++-style static_cast, dynamic_cast, reinterpret_cast, and const_cast. The reasons for this recommendation generally boil down to (1) the C++ casts are safer because they are more specific and limited in meaning, and (2) they are intentionally verbose and ugly because you should not be using them often in good C++ code. However, this reasoning doesn't make as much sense when it comes to calling C functions from my C++ code.
In my C++ projects I am often forced to call OS-level libraries that only have a C interface, such as the POSIX sockets library for network operations. These C functions often expect the caller to make several pointer casts, and if I stick to only C++-style casts my code becomes clunky and verbose. For example, my networking code is littered with function calls like this:
std::size_t message_size;
ssize_t bytes_read = recv(fd, reinterpret_cast<char*>(&message_size), sizeof(message_size), MSG_WAITALL);

I'm not gaining any safety from using C++ casts (since reinterpret_cast doesn't really add any more compile-time checks than a C-style cast), and the ugliness of the code isn't alerting me to a problem - there's no way to use socket functions without casting.
In light of the interface mismatch between C and C++, would it be reasonable to use C-style casts when calling C functions that require casting? Or are C-style casts always bad practice, and I should just accept the extra code bloat when I need to call C functions?

A: It's easy to prevent the verbosity of calling C functions from cluttering your code: wrap them. In the case of recv, for example, you can simply do this:
template <typename T>
ssize_t recv(int fd, T& data) {
  return ::recv(fd, reinterpret_cast<char*>(&data), sizeof(data), MSG_WAITALL);
}

You can improve on this by e.g. static_asserting that T is trivially copyable or has some other desired properties.
Now if you use this function instead of the C recv all over the code, you have reduced clutter and improved safety (you can't accidentally mismatch the data type and its size).
At the same time, you're still using C++-style casts, which prevents you from accidentally casting away constness.

A: The standard explains how the C style cast works (N4296):

5.4/4: The conversions performed by

*

*a const_cast,

*a static_cast,

*a static_cast followed by a const_cast,

*a reinterpret_cast , or

*a reinterpret_cast followed by a const_cast,

  can be performed using the cast notation of explicit type conversion.
  (...)

Without entering into the details, the rest of the paragraph also explains that the C cast relaxes some constraints that would apply to static_cast in presence of pointers to derived classes.  This relaxed attitude is one of the reasons why it is advised not to use it in C++ code.
In your case, using  (char*)&message_size would result in reinterpret_cast<char*>(&message_size) to be generated by the compiler.  So you wouldn't lose anything by using reinterpret_cast directly.
Bjarne Stroustrup gives a couple of other reasons, why the C++ casting should be preferred in his book "The design and evolution of C++":

To sum up, old-style cast:

*

*Are a problem for understanding: they provide a single notation for several weakly related operations

*Are error-prone: almost every type combination [i.e. source type and target type] has a legal interpretation

*Are hard to spot in code and hard to find with simple tools

*Complicate the C and C++ grammars

  The new cast operators represent a classification of the old's cast
  functionality.

Of course, in your special case, point 1, 2 and 4 are not a real issue.  Nevertheless using the new style would bring you the benefit of point 3, and would get you used to the greater precision that is commonly used in C++ casting.
On the other side, IMHO, it would not be shocking to still use the C syntax if you restrict its use to the sole highlight in the code the interoperability with the C libraries.


text:
Q: Finding a Substring in a Dataframe from a Numpy Array? How do I find a list of substrings in a dataframe against an array and use the array values to create a new column? For example, I started off using str.contains and typing out the actual string value(see below).
import pandas as pd
import numpy as np

#Filepath directory
csv_report = filepath

#Creates dataframe of CSV report
csv_df = pd.read_csv(csv_report)

csv_df['animal'] = np.where(csv_df.item_name.str.contains('Condor'), "Condor",
                   np.where(csv_df.item_name.str.contains('Marmot'), "Marmot",
                   np.where(csv_df.item_name.str.contains('Bear'),"Bear",
                   np.where(csv_df.item_name.str.contains('Pika'),"Pika",
                   np.where(csv_df.item_name.str.contains('Rat'),"Rat",
                   np.where(csv_df.item_name.str.contains('Racoon'),"Racoon",
                   np.where(csv_df.item_name.str.contains('Opossum'),"Opossum")))))))

How would I go about achieving the above code if the string values are in an array instead? Sample below:
import pandas as pd
import numpy as np

#Filepath directory
csv_report = filepath

#Creates dataframe of CSV report
csv_df = pd.read_csv(csv_report)

animal_list = np.array(['Condor', 'Marmot','Bear','Pika','Rat','Racoon','Opossum'])

A: I think there's a cleaner way to write this, but it does what you want. If you are worried about case-sensitive, or full word matching, you'll have to modify this to your needs. Also, you don't need a np.array, just a list.
import io
import pandas as pd

data = '''item_name
Condor
Marmot
Bear
Condor a
Marmotb
Bearxyz
'''
df = pd.read_csv(io.StringIO(data), sep=' \s+', engine='python')
df

animal_list = ['Condor', 'Marmot','Bear','Pika','Rat','Racoon','Opossum']

def find_matches(x):
    for animal in animal_list:
        if animal in x['item_name']:
            return animal

df.apply(lambda x: find_matches(x), axis=1)

0    Condor
1    Marmot
2      Bear
3    Condor
4    Marmot
5      Bear
dtype: object

A: There is a better way than using apply or several np.where. Have a look at np.select.
Here as on the other answer we are assuming that each row can have only one match
Data
Stolen from @Jonathan Leon
import pandas as pd
import numpy as np
data = ['Condor',
        'Marmot',
        'Bear',
        'Condor a',
        'Marmotb',
        'Bearxyz']

df = pd.DataFrame(data, columns=["item_name"])

animal_list = ['Condor',
               'Marmot',
               'Bear',
               'Pika',
               'Rat',
               'Racoon',
               'Opossum']

Define conditions for numpy select
cond_list = [df["item_name"].str.contains(animal)
             for animal in animal_list]

df["animal"] = np.select(cond_list, animal_list)

output

  item_name  animal
0    Condor  Condor
1    Marmot  Marmot
2      Bear    Bear
3  Condor a  Condor
4   Marmotb  Marmot
5   Bearxyz    Bear

Case insensitive
Here you should change the last two lines with
cond_list = [df["item_name"].str.lower()\
             .str.contains(animal.lower())
             for animal in animal_list]

df["animal"] = np.select(cond_list, animal_list)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to fix the position of Buttons I am trying to change the places of the buttons from left to right at the top.
Here is the code below:
import wx

class Example(wx.Frame):

    def __init__(self, parent, title):
      super(Example, self).__init__(parent, title = title, size = (200,300))

      self.InitUI()
      self.Centre()
      self.Show()

    def InitUI(self):
      p = wx.Panel(self)
      vbox = wx.BoxSizer(wx.VERTICAL)

      for label in range(8):
         b2 = wx.Button(p, label =str(label))
         vbox.Add(b2,0,wx.VERTICAL)
         hbox = wx.BoxSizer(wx.HORIZONTAL)

      for label in range(8):
         b3 = wx.Button(p, label = "Btn3")
         vbox.Add(b3,0,wx.RIGHT)
         hbox = wx.BoxSizer(wx.HORIZONTAL)

      p.SetSizer(vbox)

app = wx.App()
Example(None, title = 'BoxSizer demo')
app.MainLoop()

The output is showing like this:

But I want the btn3 to the right side like this

*

*1 btn3

*2 btn3

*3 btn3

*4 btn3

Here (1,2,3,4) are buttons with btn3 (buttons).
Thanks for advance.

A: I assume that you want the btn3 buttons in a vertical line to the right of the other buttons.
There are various options, GridSizer and FlexGridSizer spring to mind but in your code you have already introduced a horizontal BoxSizer but not used it, so this code below will use that.
Load the vertical boxsizers and then load those into the horizontal sizer.
import wx

class Example(wx.Frame):

    def __init__(self, parent, title):
      super(Example, self).__init__(parent, title = title, size = (200,300))

      self.InitUI()
      self.Centre()
      self.Show()

    def InitUI(self):
      p = wx.Panel(self)
      vbox1 = wx.BoxSizer(wx.VERTICAL)
      vbox2 = wx.BoxSizer(wx.VERTICAL)
      hbox = wx.BoxSizer(wx.HORIZONTAL)

      for label in range(8):
         b2 = wx.Button(p, label =str(label))
         vbox1.Add(b2,0,0)

      for label in range(8):
         b3 = wx.Button(p, label = "Btn3")
         vbox2.Add(b3,0,0)

      hbox.Add(vbox1)
      hbox.Add(vbox2)

      p.SetSizer(hbox)

app = wx.App()
Example(None, title = 'BoxSizer demo')
app.MainLoop()


text:
Q: Cocoa/Objective C (OSX NOT IOS) accessing parent Object from child i am new in STackOverflow and new to ObjectiveC. I did a lot of research and already found some answers like: Accessing objects of parent class in cocoa
Still, i have some problems in understanding it and i hope the community may help to understand:
I have a ViewController, inside this controller i create an instance of a custom NSObject Class. I'd like to access the ViewController's (parent) properties and methods from the object instance.
MYCustomViewController.h
@interface MYCustomViewController : NSViewController

// Vars
@property BOOL testBool;

@end

MYCustomViewController.m
@implementation MYCustomViewController

- (void) someMethod
{
    self.testBool = true;
    _importController = [[MYCustomObject alloc] init];
    [_importController test];
}

@end

MYCustomObject.h
@interface MYCustomObject : NSObject
- (void)test;
@end

MyCustomObject.m
@implementation MYCustomObject

- (void)test
{
    // HOW CAN I ACHIEVE THIS?
    myParent.testBool; // --> true

    // AND THIS?
    [myParent someMethod];
}

@end

I am still learning, so any (not too short) explanation would be great.
Idea was: send "self" on object instantination, but how?
Targeting OSX 10.10, Xcode 8, OSX 10.12
EDIT: Got it to work using protocol on MYCustomObject. Is there any other possibility with the above mentioned idea?

A: Objective-C (and Swift) have no language concept of "parent object" being the object that created an object. (There is a parent/child relationship in classes.) If your model requires a parent connection then you simply pass the creating parent to an init method.
For example, given class MustHaveParent the following might be defined:
@implementation MustHaveParent
{
   id myParent; // reference to my parent
}

- (instancetype) initWithParent:(id)parent
{
   self = [super init];
   if(self)
      myParent = parent;
   return self;
}

and an instance of this class might be created using:
// myChild is a *local* variable, see below
MustHaveParent *myChild = [[MustHaveParent alloc] initWithParent:self];

If your model does require such a reference you should be careful not to create a reference cycle, where the parent references the child and the child references the parent. This is why the example above uses a local variable, if the reference had been stored in an instance variable of the creator there would be a cycle. While not always bad cycles often cause memory leaks. If you need to know more about this look up "reference cycles", "strong references", "weak references" etc.
HTH


text:
Q: MFC ctrls and duplicate messages I have two CListCtrl objects in my form.  I want selected list in both of them be same.
How I can do it.
I want duplicate the message that sent to a ClistCtrl and send to other one.
How I can do it?
if this is a good way?
thanks herzl

A: So, essentially what you're saying is that you want the lists to be synchronized.
You can easily achieve that by adding an event handler to catch the user's selection inside you list control, by adding: ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST1, OnItemChangedList1) to your dialog/window's message-map.
Inside OnItemChangedList1(), get the index of the currently selected item by calling GetFirstSelectedItemPosition(), and set that as the current index in your second list by calling SetSelectionMark().
This way, whenever the user will click on the 2nd item, for example, in List_A, the 2nd item in List_B will be selected as well.
There ought to be a function that brings that row into view, if it's not in view already, but I can't find it.
I hope that raps it up, ListView's have changed a lot since I've used them, but feel free to ask more if anything is unclear.


text:
Q: Show all posts under a custom taxonomy even if those posts belong to other categories as well I have custom post type 'tribe_events' and custom taxonomy 'tribe_events_cat' and i want to get all posts under a specific category but the only problem here is I only get those posts which have only that category . for example if 1 post is attached to 2 categories then it will not show in the my requested category even though it has that category quick help would be appreciated and here is my code
    query_posts(
                             array( 'post_type' => 'tribe_events',
                             'posts_per_page' => -1,

                             'tax_query' => array(

                                array(
                                    'taxonomy' => 'tribe_events_cat',
                                    'field'    => 'term_id',
                                    'terms'    => $cat,

                                ),
                            ),

                             ));

A:     $terms = get_terms( array(
       'taxonomy' => 'tribe_events_cat',
       'hide_empty' => false,
    ) );

    $cat = array();

    foreach ($terms as $term) {
       $cat[] = $term->term_id;
    }

query_posts(
  array( 'post_type' => 'tribe_events',
   'posts_per_page' => -1,

   'tax_query' => array(

      array(
        'taxonomy' => 'tribe_events_cat',
        'field'    => 'term_id',
        'terms'    => $cat,
     ),

));

Can you try this code? Hope it works

A: Sorry for taking up all your time the problem was the date of events . Past events just filtered out of loop and thats why they wont show no matter what . Stupid me :|


text:
Q: Mount success but property of device mapper that dmsetup create is lost I tried to create device mapper with dmsetup as followed:
dmsetup create error_disk
0 20000 linear /dev/loop0 0
20000 1 error
20001 20959 linear /dev/loop0 20001

Then I check with command below:
dd if=/dev/mapper/error_disk of=/dev/null bs=1k count=10000  => Result OK
dd if=/dev/mapper/error_disk of=/dev/null bs=1k count=10001  => Result IO error

So the result is right as I expected.
But then I mount as follow:
mke2fs /dev/mapper/error_disk
mount /dev/mapper/error_disk  /mnt/

I mounted successful. But when I copy the file with size is 20Mb to /mnt/ and copy successful. But I think the coping must to fail because this error disk is error at sector 20000 (10Mb).
So how can I do to this coping is fail.


text:
Q: trying to get json data from api .... I'm on localhost I am trying to get json data from http://gulf-shade.com/test/asd.php and it always says  No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
here is my code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://gulf-shade.com/test/asd.php", true);
xhr.responseType = 'json';
xhr.onreadystatechange = function () {
    if (xhr.readyState != 4 || xhr.status != 200) return;
    result = xhr.response.data;
         cosnole.log(result);
    }
};
xhr.send();

A: It appears that the site your are trying to access has CORS enabled which disallow any requests coming from JavaScript from another domain, in your case (localhost).
You can't make Ajax request to this service unless it allowed localhsot as an origin and if you can't do that, then at least you can create your localhost API which calls the http://gulf-shade.com/test/asd.php URL, retrieves the data and return it to your Ajax request.


text: Q: Remove lock screen blue icon Removing the blue icon on an Android that created when using multiple users I've tried to use build prop however it doesn't remove the actual user blue icon unless I remove the user. I want to keep using multiple users however, remove the blue icon entirely


text:
Q: An identity regarding linear operators and their adjoint between Hilbert spaces I came upon a trivial-seeming claim that I can't prove myself: Let $H_1$, $H_2$ and $H_3$ be finite-dimensional Hilbert spaces, let $A:H_1\rightarrow H_2$ and $B,C:H_3\rightarrow H_1$ be linear operators between these Hilbert spaces. Then $A^*AB = A^*AC$ if and only if $AB=AC$ (where $A^*$ denotes the adjoint of $A$).
The "if" part is obvious: If $AB=AC$, then $A^*AB = A^*AC$, no matter what $A^*$ is. As for the "only if" part, I tried the following among others:
$$A^*AB = A^*AC\ \Leftrightarrow\ A^*(AB-AC)=0\ \Rightarrow\ \langle A^*(AB-AC)w,u\rangle=0\ \forall u\in H_1,w\in H_3\ \Leftrightarrow\ \langle(AB-AC)w,Au\rangle = 0\quad \forall u\in H_1,w\in H_3\ \Leftrightarrow\  \mathrm{im}(AB-AC)=(\mathrm{im}\ A)^\bot = \mathrm{ker}\ A^*$$
and I'm stuck. I'm sure one has to exploit the definition and properties of adjoints in some way. I feel the answer is far from complicated yet I failed so far. Any help would be appreciated.

A: Let $x \in \ker(A^*A)$, then
$$ 0 = \left<A^*Ax,x\right> = \left<Ax,Ax\right> = \|Ax\|^2 $$
so $x \in \ker A$. This proves $\ker(A^*A) = \ker(A)$. Hence if $A^*(AB - AC) = 0$ then $\mathrm{im}\, (B-C) \subseteq \ker(A^*A) = \ker(A)$, hence we have $AB - AC = 0$.


text:
Q: ULTRA X3 D0409 1000W PSU and high 3.3v rail voltage I just got ULTRA X3 D0409 1000W PSU for a rig which I'm building and before putting it in, as always, I have it checked with PSU tester and came up that 3.3V rail voltage is going high (up to 4.1) but it will fluctuate after that between 3.7 and 4.0
I think going above 3.8V it should to trigger over-voltage protection in the PSU but it didn't.
Any thoughts on that? Is this can be adjusted by a resistor or something else?

A: Most likely it's not user adjustable.
Besides most power supplies need at least some load to keep it happily regulated.


text:
Q: load content from other page with ajax I have a WordPress site, which is based on posts, but I want to filter my post with ajax.
The tricky part is that, if I want to filter from lets say "cases" to "photography" I have two different templates for this.
I can manage this with a little php and change the_template_part, but that makes the page reload which I don't want to do.
I've been trying to do a ajax request to complete the filter function.
My .js
   $('a[rel="filter"]').click(function() {

        var filter = $(this).attr('id');

        $('.checked').removeClass('checked');
        $(this).parent().addClass('checked');

        $.ajax({
            url: '/wp-admin/admin-ajax.php',
            data: window.location = '#?filter=' + filter,
            success: function() {
                $('#content').children().fadeOut(549);
                $('#content').html(data).fadeIn(549);
            }
        });

        console.log('Filter ' + $(this).attr('id') + ' clicked');
    });

And this is the php to change the template_part in my Index.php
    $type = ($_GET['filter'] == '') ? 'projects' : $_GET['filter'];
    <?php
       get_template_part($type);
    ?>

Can I achieve this or do I need to think this over?
This just return the actual address in plain text
    $('a[rel="filter"]').click(function() {

        var filter = $(this).attr('href');

        $('.checked').removeClass('checked');
        $(this).parent().addClass('checked');

        $.ajax({
            url: 'wp-admin/admin-ajax.php',
            //url: 'url' + filter,
            data: {
                filter: filter
            },
            success: function(html) {
                $('#content').children().fadeOut(549);
                $('#content').html(filter).fadeIn(549);
                console.log(filter);
                console.log("Success");
            },
            error: function() {
                console.log('No can do')
            }
        });

        console.log('Filter ' + filter + ' clicked');
        return false;
    });

If I have 3 pages with different queries and templates which represent (Case, photography and motion), which on the frontpage I want to make filterable. I'm working on a one page site.

A: Add return false at the end of click function.


text:
Q: Django : how to delete file record after user close his page? I'm making a simple file resizer with Django, there are 3 fields, email, size, image.
After the user arrives to a the last view where he can download what he resized, I'd like Django to erase the image of the ImageField to save space on my Django project whenever an user close his window with the final view page.
I do want to keep the email and the size as it is,  so these are the only things that shouldn't be deleted.
I have no idea where to search, I looked into StackOverflows posts and in Django google groups articles but I could not find something to help me, any suggestion on how this can be done ?

A: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onunload - you can try using this method to handle browser close tab with js and send request to django.
But in your place I would prefer timeout after which all images resized certain time ago would be removed (it can be done with simple cron script, possibly with some management command).


text:
Q: unable to solve ODE with zdot function I have a problem with plotting RLC circuit with zdot function in Scilab
.
I have worked out the analytical calculation:
Vin = ( VR/(s^2*L*C)+ VR/(s*R*C) + VR )

    // R = 11 Ohm, R = 0.012 F, L = 1.5 H. f - 1e4

I'm trying to solve ODE above before plotting and it led me to
Vin = (s^2*VR + s*VR*(1/R*C) + VR/(L*C)) /s^2

i try to follow the manual in scilab for solving ode with zdot function :
function zdot=RLCsystem(t, y)
z1 = y(1); z2 = y(2);
// Compute input
Vin = A*sin(2*%pi*f*t);    // A = 1, f = 1e4 Hz
zdot(1) = z2; zdot(2) = (Vin - z1/(L*C) - z2/(R*C)) ;
endfunction

--I dont know where the s^2 stand in this code / equation
any suggestion would help.

A: This is properly a question about a mathematical formalism. What you call solution and equation is formulated in the Laplace space. Roughly, s stands for the differentiation operator, 1/s for the integration operator. In a proper calculation there are also initial values involved.
Thus the ODE written in derivative notation is
VR'' + VR'/(R*C) + VR/(L*C) = Vin''

If the state vector y contains the function value and derivatives in increasing order, then the action of s is a shift in that vector, or the selection of the component corresponding to the power of s. Which is apparently done in the code.
Note that the code does not respect the second derivative of Vin. Correctly this would have to be
function zdot=RLCsystem(t, y)
z1 = y(1); z2 = y(2);
  // Compute input
  w = 2*%pi*f
  Vin = A*sin(w*t);    // A = 1, f = 1e4 Hz
  D2Vin = -A*w^2*sin(w*t)
  zdot(1) = z2; zdot(2) = (D2Vin - z1/(L*C) - z2/(R*C)) ;
endfunction

Other eliminations in the following confirmation calculation might result in first order systems that do not contain derivatives of the input voltage.
element laws:
  C*VC'=IC, VR = R*IR = VL = L*IL',
cell laws:
  IC = IL+IR, Vin = VC + VR
eliminate flows
  L*IC' = VR + L*IR'
  L*C*(Vin-VR)'' = VR + L/R*VR'


text:
Q: How to properly manage changes to Android source? Let's say I'm building Android or CyanogenMod from source and want to make changes to its source. Also, let's assume I don't want to submit these changes (since they are incomplete or are changes that have already been rejected, for example).
What is the best way to manage that? How can I have proper source control of my "personal" changes, but at the same time be able to use repo sync so that I have the latest changes?
Can I have local branches (for each project I make changes) and simply merge from the master branch to my local branches after every repo sync?

A: When you run "repo sync" what actually happens is that each git repository is rebased on a new upstream. If you don't have any local patches in a specific git repository, it's a simple fast-forward. If you do have some patches and upstream does as well(your branch and upstream branch have diverged), repo will attempt an automatic rebase.
So lets say you have a patch on top of upstream code, and upstream has had some new comits since you applied that patch. When you run repo sync, repo will try to rebase your code on top of upstream. If the automatic rebase fails, repo will throw an error message letting you know that you should fix the patch manually.
To sum it up: You can create a branch in each project you want to modify, store your commits on that branch. Repo sync will automatically rebase your patches(unless it fails and then you'd have to apply them manually).

A: You will need to use repo start command to create a topic branch that tracks the remote repo branch. Or you need to use --track option of the git branch command to manually create a local branch with a remote tracking branch. Use the --set-upstream option of the git branch command to add a tracking branch to an existing local branch.
Once you have setup the tracking branch correctly, the repo sync command will fast forward and reapply your local patches as Anton Cherkashyn has described in his answer.

A: Use gerrit in conjunction with repo and git.

A: This seems to work for me.
First mentioning some setup
# cd to root of source tree
repo start MyBranch       # Create working branch for all projects
repo checkout MyBranch    # switches all projects to use MyBranch

Time passes, fabulous edits made and committed (in MyBranch), working branch is clean. Now want upstream changes ...
# Current active branch is "MyBranch"
# The following sync -d as per repo docs:
#     -d: switch specified projects back to the manifest revision.
#      Helpful if the project is currently on a topic branch,
#      but the manifest revision is temporarily needed.
# In other words, it automatically syncs default manifest's upstream
repo sync -d -j12

# Active branch may be "MyBranch" or possibly a detached head or whatever.
# So, if necessary, switch back to MyBranch
# - I usually do this just to make sure all projects are in MyBranch
# - NOTE: If a new project appears it won't have MyBranch
repo checkout MyBranch

# Now we're in MyBranch. Its "upstream" is our local master so sync it.
# - This is usually rather quick
repo sync

The "repo sync -d" may not be necessary but hasn't caused any problems as far as I have seen. Plus it pulls the master codeline locally to keep it in sync for handy diffs and such.
Perhaps "repo sync" from within MyBranch does that too. But I don't seem to get any updates when I omit the "repo sync -d" step and just do "repo sync" when MyBranch is checked out. (Although maybe my local setup is messed up somehow)
To summarize:
Option A: Might work
cd RootOfRepoSourceTree   # wherever you have it
repo checkout MyBranch
repo sync

Option B: Works consistently for me
cd RootOfRepoSourceTree   # wherever you have it
repo sync -d -j12
repo checkout MyBranch
repo sync


text:
Q: Sharing data between classes I am building an iphone application that tries to fetch data using web services.The user on clicking the button is navigated to a new view.
The code for login action is
- (IBAction)btnLoginAction:(id)sender
{

 [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
 activityIndicator=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(50.0, 50.0, 50, 50)];
 [activityIndicator setCenter:CGPointMake(156, 208)];
 [activityIndicator startAnimating];

 [self.view addSubview:activityIndicator];
 soapMessenger=[[SoapMessenger alloc] init];
 parser=[[XML_Parsing alloc] init];
 [soapMessenger buildSoap:@"CURRENT"];
 [soapMessenger setConnection];

where soapMessenger and xml_parsing are classes for creating connections and parsing data ....I am able to parse the xml.But the problem is passing that data to a new view controller....How can I pass the result data to a new class?

A: If you want to pass data from one class to another you need to create property of the datatype you want to pass in the class in which the data is passed.
Example
FirstVC - Your Class from which you want to pass the value to next View Controller.
SecondVC - Your Second Class to which you want to pass the value.
@interface FirstVC : UIViewController{
NSInteger *testInteger;
}

@implementation FirstVC{

- (IBAction)btnLoginAction:(id)sender
{
SecondVC *second = [[SecondVC alloc] initWithNibName:@"SecondVC" buddle:[NSBundle mainbundle]];
second.receivingInteger=testInteger;
[second release];
}

}

@interface SecondVC{
NSInteger receivingInteger;
}
@property(nonatomic) NSInteger receivingInteger;

A: This is a Model View Controller question. MVC. Your data classes should store the data in your model, and then the relevant part of the model can be passed to the new class - normally by Synthesizing an property of the correct type in the new class, and then alloc/init the new class, and set the property.

A: You need to define a model class which holds the data parsed from the XML which you then pass to the new view controller via a property.

A: I have figured it out.....I used protocols to implement it.


text:
Q: Display Nokogiri children nodes as raw HTML instead of >tag< I am changing an XML table into an HTML table, and have to do some rearranging of nodes.
To accomplish the transformation, I scrape the XML, put it into a two-dimensional array, and then build the new HTML to output.
But some of the cells have HTML tags in them, and after my conversion <su> becomes >su<.
The XML data is:

<BOXHD>
  <CHED H="1">Disc diameter, inches (cm)</CHED>
  <CHED H="1">One-half or more of disc covered</CHED>
  <CHED H="2">Number <SU>1</SU>
  </CHED>
  <CHED H="2">Exhaust foot <SU>3</SU>/min.</CHED>
  <CHED H="1">Disc not covered</CHED>
  <CHED H="2">Number <SU>1</SU>
  </CHED>
  <CHED H="2">Exhaust foot<SU>3</SU>/min.</CHED>
</BOXHD>

The steps I'm taking to convert this to an HTML table are:
class TableCell

  attr_accessor :text, :rowspan, :colspan

  def initialize(text='')
      @text = text
      @rowspan = 1
      @colspan = 1
  end
end

@frag = Nokogiri::HTML(xml)

# make a 2d array to store how the cells should be arranged
column = 0
prev_row = -1
@frag.xpath("boxhd/ched").each do |ched|
  row = ched.xpath("@h").first.value.to_i - 1
  if row <= prev_row
    column +=1
  end
  prev_row = row
  @data[row][column] = TableCell.new(ched.inner_html)
end

# methods to find colspan and rowspan, put them in @data
# ... snip ...

# now build an html table
doc = Nokogiri::HTML::DocumentFragment.parse ""
Nokogiri::HTML::Builder.with(doc) do |html|
  html.table {
    @data.each do |tr|
      html.tr {
        tr.each do |th|
          next if th.nil?
          html.th(:rowspan => th.rowspan, :colspan => th.colspan).table_header th.text
        end
      }
    end
  }
end

This gives the following HTML (notice the superscripts are escaped):

        Disc diameter, inches (cm)
        One-half or more of disc covered
        Disc not covered

        Number <su>1</su>
        Exhaust foot <su>3</su>/min.
        Number <su>1</su>
        Exhaust foot<su>3</su>/min.

How do I get the raw HTML instead of the entities?
I've tried these with no success
@data[row][column] = TableCell.new(ched.children)
@data[row][column] = TableCell.new(ched.children.to_s)
@data[row][column] = TableCell.new(ched.to_s)

A: This might help you understand what's happening:
require 'nokogiri'

doc = Nokogiri::XML('<root><foo></foo></root>')

doc.at('foo').content = 'bar'
doc.to_xml # => "<?xml version=\"1.0\"?>\n<root>\n  <foo><html><body>bar</body></html></foo>\n</root>\n"

doc.at('foo').children = 'bar'
doc.to_xml # => "<?xml version=\"1.0\"?>\n<root>\n  <foo>\n    \n      bar\n    \n  </foo>\n</root>\n"

doc.at('foo').children = Nokogiri::XML::Document.new.create_cdata 'bar'
doc.to_xml # => "<?xml version=\"1.0\"?>\n<root>\n  <foo><![CDATA[bar]]></foo>\n</root>\n"

A: I abandoned the builder, and simply built the HTML:
headers = html_headers()

def html_headers()

  rows = Array.new
  @data.each do |row|
      cells = Array.new
      row.each do |cell|
          next if cell.nil?
          cells << "%s	" %
                      [cell.rowspan,
                      cell.colspan,
                      cell.text]
      end
      rows << "
%s
" % cells.join
  end
  rows.join

end

def replace_nodes(headers)

  # ... snip ...

  @frag.xpath("boxhd").each do |old|
      puts "replacing boxhd..."
      old.replace headers
  end

  # ... snip ...

end

I don't understand why, but it appears that the text I replaced the <BOXHD> tags with are parsed and searchable, as I was able to change tag names from data in cell.text.


text:
Q: Escape characters are not working when passing program arguments from shell script to jar When I tried to pass some program arguments from shell script to java program, the escape characters are not working.
Here is the code and command I tried to use.
Shell Script:
#!/usr/bin/bash
filename="DX.jar"
uid="111,110"

onCallName1="Tom"
onCallName2="Jerry"
onCallName3="Brun"

text="These are people who are on call: @$onCallName1, @$onCallName2 and @$onCallName3. \\n'
Please focus on the cases of online problems. \\n'
Safe cases monitor: https://a.b.com/page/992645614 \\n'
Old cases log: https://a.b.com/page/1012464399 \\n'
Cases feedback: https://a.b.com/page/1041338613"

# run!
java -jar $filename -uid $uid -text $text

The argument text should be parsed in the Java program and output itself like follows:

These are people who are on call: @$onCallName1, @$onCallName2 and @$onCallName3.
Please focus on the cases of online problems.
Safe cases monitor: https://km.sankuai.com/page/992645614
Old cases log: https://km.sankuai.com/page/1012464399
Cases feedback: https://km.sankuai.com/page/1041338613

But when I run this shell script like bash a.sh, it only outputs these:

These

Could anyone help me and give me some advice?
Thanks in advances.

A: Try rewriting your script as follow and please tell if it works or not for you too:
#!/usr/bin/bash
filename="DX.jar"
uid="111,110"

onCallName1="Tom"
onCallName2="Jerry"
onCallName3="Brun"

text="These are people who are on call: @$onCallName1, @$onCallName2 and @$onCallName3. \n'
Please focus on the cases of online problems. \n'
Safe cases monitor: https://a.b.com/page/992645614 \n'
Old cases log: https://a.b.com/page/1012464399 \n'
Cases feedback: https://a.b.com/page/1041338613"

# run!
java -jar "$filename" -uid "$uid" -text "$text"

In other words:

*

*Leave carriage returns unescaped.

*Put java command line arguments inside double quotes.


text:
Q: Oracle SQL: Anyone can help me with Error(2,32): PLS-00049: bad bind variable 'WORKED_HOURS' Anyone can help me with Error(2,32): PLS-00049: bad bind variable 'WORKED_HOURS'
    CREATE OR REPLACE TRIGGER uprava_prac_casu
    BEFORE
    UPDATE OF worked_hours
    ON Attendance_of_employee
    FOR EACH ROW
    BEGIN
    IF (:new.worked_hours>15) THEN :worked_hours:=15; END IF;

    IF (:new.worked_hours<3) THEN :worked_hours:=3; END IF;
    END;
    /

Trigger UPRAVA_PRAC_CASU compiled

Errors: check compiler log

From compiler log: Error(2,32): PLS-00049: bad bind variable 'WORKED_HOURS'
Then I have tried this:
CREATE OR REPLACE TRIGGER uprava_prac_casu
    BEFORE
    UPDATE OF worked_hours
    ON Attendance_of_employee
    FOR EACH ROW
    BEGIN
    IF (:new.worked_hours>15) THEN :old.worked_hours:=15; END IF;

    IF (:new.worked_hours<3) THEN :old.worked_hours:=3; END IF;
    END;
    /

> Error report -
>     ORA-04085: nemožno zmeniť hodnotu referenčnej premennej OLD
>     04085. 00000 -  "cannot change the value of an OLD reference variable"
>     *Cause:    Old values can only be read and not changed.
>     *Action:   Do not attempt to change an old variable.

A: You may just have your "old"s and "new"s set up backward.  Or, you may want to adjust the "new" values.  I am guessing the latter:
CREATE OR REPLACE TRIGGER uprava_prac_casu
BEFORE UPDATE OF worked_hours
ON Attendance_of_employee
FOR EACH ROW
BEGIN
    IF (:new.worked_hours > 15) THEN :new.worked_hours := 15; END IF;
    IF (:new.worked_hours < 3) THEN :new.worked_hours := 3; END IF;
END;

You are getting the error because you can only update the new value in the trigger, not the old value.

A: AS it clearly says you cannot modify :old.worked_hours.

You cannot change the field values of the OLD structure; attempting to
  do so will raise the ORA-04085 error. You can modify the field values
  of the NEW structure.


text:
Q: AWS Instance Storage Usage I created an EC2 instance which is dedicated to a small WordPress site. I have stopped the instance because I am basically just parking the site for now. The instance has an EBS volume, which is 10 gigabytes. I am sure the instance mustn't actually use that much. Is there a way I can safely reduce the size of the EBS volume so I don't have to pay extra?

A: Take a snapshot and store in s3 glacier, and get rid of the EBS volume. When you are ready to use, hydrate it from glacier and you should be good to go.

A: What about just create a snapshot and then from this snapshot create a new instance but on the storage step dedicate less space. What is the total amount of space your WordPress occupies?


text:
Q: Kendo Autocomplete search multiple columns i have used kendo Auto Complete in my KendoGrid,
It is working fine for now, but it only search or get data from across one column only,
i want it to search across multiple columns.
Here is my code of Autocomplete in KendoGrid.
 $(function(){
    $("#EmployeeGrid").kendoGrid({
        dataSource:{
            serverPaging: true,
            serverFiltering: true,
            pageSize: 5,
            transport: {
                read: "<?php echo base_url() ?>index.php/hr_management/manage_hr/list_view"
            },
            schema:{
                data: "data",
                total: "total"
            }
        },
        toolbar: kendo.template($("#toolbarTemplate").html()),
        pageable: {
            input:true,
            numeric:false
        },
        columns: [
            {
                field: "EmployeeID",
                hidden:true
            },
            {
              field: "FileNo",
              title: "File Number"
            },
            {
                template:"#= FirstName # #= LastName #",
                title: "Full Name"
            },
            {
                field:"City",
                title:"City"
            },
            {
                field:"AddressLine1",
                title:"Address 1"
            },

            {
                field:"WorkPhone",
                title:"WorkPhone"
            },
            {
                field:"MobileNo",
                title:"Mobile No"
            },
            {command: { text: "View", click: showDetails }, title: " ", width: "140px"},
            {command: { text: "Edit", click: EditUserDetails }, title: " ", width: "140px"}
        ]
    });

});
var autoCompleteUsers = $("#employees").kendoAutoComplete({
    minLength: 3,
    dataTextField: "FileNo",
    dataSource: {
        serverFiltering: true,
        transport: {
            read: {
                type: "GET",
                dataType: "json",
                contentType:'application/json; charset=utf-8',
                url: "<?php echo base_url() ?>index.php/hr_management/manage_hr/search_employee/",
                data: function (arg){
                    return {FileNo : autoCompleteUsers.data("kendoAutoComplete").value()};
                }
            }
        }
    },
    change: onChangeAutoComplete
});
function onChangeAutoComplete(){
    var value = this.value();
    var grid = $('#EmployeeGrid');
    if (value) {
        grid.data("kendoGrid").dataSource.filter({ field: "FileNo", operator: "Contains", value: value });
    } else {
        grid.data("kendoGrid").dataSource.filter({});
    }
}

function showDetails(e) {
    e.preventDefault();
    $('.action_button').html('');
    var row = $(e.target).closest("tr");
    var item = $("#EmployeeGrid").data("kendoGrid").dataItem(row);
    $.ajax({
        type: "POST",
        url: "<?php echo base_url().'index.php/hr_management/manage_hr/view_employee_profile/'?>"+JSON.parse(item.EmployeeID),
        success: function(output_string){
            var data = output_string.split("MyMark_Employee");
            $('.second_column_content_container').html(data[0]);
            $('.action_button').html(data[1]);

            $("#createEmployee").hide();
        },
        error: function(data){
            alert("error");
        }
    });

}

function EditUserDetails(e) {
    e.preventDefault();
    $('.action_button').html('');
    var row = $(e.target).closest("tr");
    var item = $("#EmployeeGrid").data("kendoGrid").dataItem(row);
    $.ajax({
        type: "POST",
        url: "<?php echo base_url().'index.php/hr_management/manage_hr/edit_employee_details/'?>"+JSON.parse(item.EmployeeID),
        success: function(output_string){
            var data = output_string.split("MyMark_Employee");
            $('.second_column_content_container').html(data[0]);
            if(data[1]!= " ")
            {
                $('.action_button').html(data[1]);
            }

        },
        error: function(data){
            alert("error");
        }
    });

}

What to do?
Do i need to define multiple dataTextField:?
Need Suggestions.

A: Good question. I wondered the same thing.
After looking at the Kendo code (kendo.web.min.js), it does not look like it is possible to define multiple fields for the property dataTextField. It looks like only one field is allowed.
A workaround is to add a field in your model that includes (in string form) all the fields that you want to search. Then set dataTextField to that field. It's not an ideal solution, but it works.


text:
Q: Всплывающие блоки Здравствуйте.Делаю сайт и появилась необходимость сделать удобную для пользователя функцию добавления различных записей. Вот пример. Там на главной странице в самом верху есть блок для добавления заказа. Суть в том, что там заполняются только основные поля (заголовок, описание и город заказа). А уже после нажатия на кнопку добавления, всплывает блок, где нужно ввести более подробную информацию по заказу. Хочу так же сделать у себя. Подскажите, как лучше все это дело реализовать? Лучше писать самому или есть готовые плагины для таких вещей??
A: Я бы написал сам... Лишняя практика не помешает :)
Но если других дел много сроки ограничены или в JS вы "не специалист" лучше использовать готовые библиотеки, например плагин JQuery Window
A: Лучше всего - начать уже реализовывать. Если вИдения еще нет - оно появится в процессе работы. Хотите двойную форму - делайте двойную.
Собственно, вооружайтесь Fibebug'ом и изучайте код страницы.
A: Ну это обычный плагин к jquery вроде fancybox. Такой можно написать вручную или использовать готовый, зависит от ваших возможностей и свободного времени.


text:
Q: Object not creating using module pattern of JavaScript in CRM 2011 I have devised the JavaScript logic as per module pattern for my CRM 2011 form. At the time of form load sometimes i get the alert as 'Crm object undefined' but upon refreshes (single or multiple) this error disappears (work smoothly).
After quite struggling I am still not able to understand that why this happens. Has it anything to do with module pattern? because onLoad function is fired just fine but the thing that is bothering me is that why sometimes Crm object is not created.
var Crm = (function (FSX) {
    var xrm = {
        date: {
            setDate: function (sourceAttribute, targetAttribute) {
                // ... date setting logic ...
            }
        }
    }
    return xrm.date;
}(FSX));

function onLoad() {
    if (typeof Crm === 'undefined') {
        alert('Crm object undefined');
        return;
    }
    Crm.setDate("fsx_source", "fsx_target");
}

A: I think the problem lies with the FSX object.
Where is this loaded?
If it has not been loaded before the script defining your module executes, the code will error out and Crm will be undefined.
There is a nicely written article here about loading dependant libraries for a CRM form.
It proposes are a number of solutions:
1) Use RequireJs or HeadJs to dynamically load your dependant scripts.
2) Loading Libraries by including them in Ribbon commands.


text:
Q: sendSynchronousRequest blocked app? This method used to perform well, but today it's strange where app is blocked. I can't check its status or sth. Any suggestion? Thanks in advance.

A: That's the idea with synchronous requests. If you want a non blocking operation either use an asynchronous request or a synchronous in another thread (not your main thread). If you need further clarification feel free to ask.

A: whenevery you use a synchronous request or core data opertaion. remember to run it in background thread because it will halt your UI
[self performSelectorInBackground:@selector(updateData) withObject:nil];

A: You Should send an Asynchronous request... It won't affect the UI and will run in the background. For Example:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

This request runs in the background and the data can be received and processed using the delegate methods mentioned below.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection

Since the UI works on the Main thread, so the UI will not be blocked.


text:
Q: Sakurai's explanation of degenerate electron gas I am having some questions with the following equation of Sakurai's explanation electron gas.
Sakurai is trying to compute the ground state energy of the degenerate electron gas using perturbation theory. First he computes the Hamiltonian:
Then he tries to compute the unperturbed Energy (for $H_0$) as follows:

What I don't get is the first line marked. First where is this weird $V/(2\pi)^3$ coming form? Thanks in advance!

A:
What I don't get is the two lines marked. First where is this weird
$V/(2π)^3$ coming form?

It's a typical result in density of states calculations in momentum (k) space. The momentum space states, when applying boundary conditions, are given by e.g. $k_x = \frac{2\pi}{L}$. In 3D, it's $(2\pi)^3/L^3$, where $L^3$ is the volume $V$.

And secondly why is that when we take the sum over λ, we don't
multiply the expression by 2 because of spin up and down?

You do.
The integral $\int_0^{k_F} \mathrm{d}^3k$ is the volume integral of a sphere of radius $k_F$, so it gives you $4\pi k_F^3/3$. Multiply by $2$ for spin degeneracy (the $\lambda$ sum), $8\pi k_F^3/3$.
The LHS pre-factor is $V/(2\pi)^3$, times the factor we just got, gives you $\frac{V}{3\pi^2}k_F^3$ as per the RHS.


text:
Q: Component-Wise 3D Vector Projection I want to define the projection of a vector $\mathbf{v} \in \mathbb{R}^3$ onto the line $\mathbf{r} \in \mathbb{R}^3$ in terms of the components of $\mathbf{v} = (v_x, v_y, v_z)$. In 2D, this looks like the following:

2D component-wise vector projection
The magnitude of the component-wise projection of the velocity vector $\mathbf{v}$ onto $\mathbf{r}$ is the radial velocity $v_r$, and (in 2D) can be expressed as the following:
$$
v_r = \text{comp}_{\mathbf{r}} \mathbf{v}_x + \text{comp}_{\mathbf{r}} \mathbf{v}_y = v_x \cos \theta + v_y \sin \theta
$$
or in vector form,
$$
v_r = \begin{bmatrix} \cos \theta & \sin \theta \end{bmatrix} \begin{bmatrix} v_x \\ v_y \end{bmatrix}
$$
The 3D case becomes a bit more complicated, and this is where I haven't been able to understand the geometry of the component-wise projection. In the 3D case, we have the vector $\mathbf{r}$ expressed in a form of polar coordinates where the azimuth angle $\theta$ is defined in the x-y plane relative to the positive y-axis, and the elevation angle $\phi$ is defined in the w-z plane relative to the positive w-axis, where the direction of the w-axis is defined by the direction of the projection of $\mathbf{r}$ onto the x-y plane.

3D geometry
The 3D vector $\mathbf{v}$ is defined with its origin at the point $(x,y,x)$ and has components $(v_x, v_y, v_z)$. The magnitude of the component-wise projection of $\mathbf{v}$ onto $\mathbf{r}$ will be a function of both the azimuth ($\theta$) and elevation ($\phi$) angles of the form:
$$
v_r = \begin{bmatrix} f_1(\theta, \phi) & f_2(\theta, \phi) & f_3(\theta, \phi) \end{bmatrix} \begin{bmatrix} v_x \\ v_y \\v_z \end{bmatrix}
$$

A: We want to create vectors along the vector $\vec r$ with components being that of the $x, y, z$ projections of the vector $\vec v = (v_x, v_y, v_z)$.
To create a vector in some direction with some magnitude, we multiply the unit vector along a direction with the magnitude we wish for. So, for example, to create the projection of the $x$ value along the direction by $\vec r$, we will:

*

*Create a unit vector $\hat r = \vec r / |r|$, which is the unit vector in the direction along $\vec r$

*Make the new vector $\vec r_x =  v_x \hat r$, where $v_x$ is the x-component of the vector $v$.

Similarly, for $y$, we can create a vector $\vec r_y = v_y \hat r$. And for $z$, we can create $\vec z = v_z \hat r$.
Since we have the vector $\vec r$ in spherical coordinates, we can write the unit vector along the direction $\vec r$ in cartesian coordinates as:
$\hat r = (\cos \phi \sin \theta, \cos \phi \cos \theta, \sin \phi)$.
So the vectors will be:

*

*$\vec r_x = v_x \hat r =  (v_x\cos \phi \sin \theta, v_x \cos \phi \cos \theta,v_x \sin \phi)$

*$\vec r_y = v_y \hat r =  (v_y\cos \phi \sin \theta, v_y \cos \phi \cos \theta,v_y \sin \phi)$

*$\vec r_z = v_z \hat r =  (v_z\cos \phi \sin \theta, v_z \cos \phi \cos \theta,v_z \sin \phi)$
If I completely misunderstood the question, please do tell me!

A: In $\mathbb R^n$ in any number of dimensions, with the usual distance function, if you have a line through the origin in the direction of a vector $\mathbf r,$ as you have in your first figure,
and any other vector $\mathbf v,$ the length of the projected vector you get by projecting
$\mathbf v$ onto the line of $\mathbf r$ is just the inner product (aka dot product)
$$ v_r =  \left(\frac1{\lVert\mathbf r\rVert}\mathbf r\right) \cdot v. $$
In general, the vector $\frac1{\lVert\mathbf r\rVert}\mathbf r$ is simply a unit vector in the same direction as $\mathbf r.$
In two dimensions, with a vector $\mathbf r$ at an angle $\theta$ from the $x$ axis, it happens that the vector on the left side of that inner product is
$$ \frac1{\lVert\mathbf r\rVert} \mathbf r=
\begin{bmatrix}
\cos\theta \\
\sin\theta
 \end{bmatrix},$$
and therefore the inner product is given by the matrix multiplication you showed.
In your three-dimensional case, you can set
$$\frac1{\lVert\mathbf r\rVert} \mathbf r=
 \begin{bmatrix} f_1(\theta, \phi) \\
 f_2(\theta, \phi) \\
 f_3(\theta, \phi) \end{bmatrix},$$
that is, simply set $f_1(\theta, \phi),$ $f_2(\theta, \phi),$ and
$f_3(\theta, \phi)$ to the three coordinates of the unit vector in the direction $\theta,\phi.$ You can read these coordinates off your diagram.
(They are combinations of trigonometric functions of $\theta$ and $\phi$ which you've already written; just don't multiply by $R$.)


text:
Q: NVIDIA device doesn't exist! I posted this question a few days ago.
I tried to reinstall the driver by downloading it from official NVIDIA website and also reinstalling it from Additional Driver app or ubuntu-driver autoinstall command but none of them solved the problem. I can install them without any error but after reboot I face some problems (whem PRIME profile is on-demand). Now nvidia-smi doesn't work:
┌──(rootubuntu)-[~]
└─$ nvidia-smi
NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.

nvidia-persistenced.service has beed failed to start and I get this message:
Failed to query NVIDIA devices. Please ensure that the NVIDIA device files (/dev/nvidia*) exist, and that user 127 has read and write permissions for those files.

And there is no nvidia in /dev/:
┌──(rootubuntu)-[~]
└─# ls /dev
acpi_thermal_rel  cuse         hidraw0    i2c-6    loop12  loop9         nvme0      pts       snd        tty11  tty21  tty31  tty41  tty51  tty61      ttyS12  ttyS22  ttyS4    v4l    vcsa3  vfio
autofs            disk         hidraw1    i2c-7    loop13  loop-control  nvme0n1    random    spidev0.0  tty12  tty22  tty32  tty42  tty52  tty62      ttyS13  ttyS23  ttyS5    vcs    vcsa4  vga_arbiter
block             dma_heap     hpet       initctl  loop14  mapper        nvme0n1p1  rfkill    stderr     tty13  tty23  tty33  tty43  tty53  tty63      ttyS14  ttyS24  ttyS6    vcs1   vcsa5  vhci
bsg               dri          hugepages  input    loop15  mcelog        nvme0n1p2  rtc       stdin      tty14  tty24  tty34  tty44  tty54  tty7       ttyS15  ttyS25  ttyS7    vcs2   vcsa6  vhost-net
btrfs-control     drm_dp_aux0  hwrng      kmsg     loop2   media0        nvme0n1p4  rtc0      stdout     tty15  tty25  tty35  tty45  tty55  tty8       ttyS16  ttyS26  ttyS8    vcs3   vcsu   vhost-vsock
bus               ecryptfs     i2c-0      kvm      loop3   mei0          nvme0n1p5  sda       tpm0       tty16  tty26  tty36  tty46  tty56  tty9       ttyS17  ttyS27  ttyS9    vcs4   vcsu1  video0
char              fb0          i2c-1      log      loop4   mem           nvram      sda1      tpmrm0     tty17  tty27  tty37  tty47  tty57  ttyprintk  ttyS18  ttyS28  udmabuf  vcs5   vcsu2  video1
console           fd           i2c-2      loop0    loop5   mqueue        port       sda3      tty        tty18  tty28  tty38  tty48  tty58  ttyS0      ttyS19  ttyS29  uhid     vcs6   vcsu3  zero
core              full         i2c-3      loop1    loop6   net           ppp        sg0       tty0       tty19  tty29  tty39  tty49  tty59  ttyS1      ttyS2   ttyS3   uinput   vcsa   vcsu4  zfs
cpu               fuse         i2c-4      loop10   loop7   ng0n1         psaux      shm       tty1       tty2   tty3   tty4   tty5   tty6   ttyS10     ttyS20  ttyS30  urandom  vcsa1  vcsu5
cpu_dma_latency   gpiochip0    i2c-5      loop11   loop8   null          ptmx       snapshot  tty10      tty20  tty30  tty40  tty50  tty60  ttyS11     ttyS21  ttyS31  userio   vcsa2  vcsu6

please help if you can.


text:
Q: I need to recursively check a dynamic Tree Structure in Javascript I need your help. So the goal this time is that i want to recursively check my tree structure.
Basically this is what i need it to do:

On the on side i have a so called treeNode (example: 'Article.Artnr') and on the other a so called contextEntry (which has an 'Article').
I need to check if the name in treeNode exists in contextEntry, if it exists i need to check the type of it and than go on. Now the tricky Part: The next name in the namesSplit is 'Artnr' which i need to check if it is an property from 'Article' in the contextEntry. Again if it is i need to check it's type and go on. I don't know beforehand how deep my structure will be so i really would appreciate your help on this one.
let namesSplit = treeNode.name.split('.');

let key = namesSplit[0];

let contextEntry = exprData.contextEntry.find(_x => _x.name === key);

I have implemented my Recursive check like so:
function recursive(names, contextEntry) {
        for (let i = 0; i < names.length; i++) {
            if (names[i] === contextEntry.name) {
                // getType(contextEntry.value);
                console.log('Name found in Context: ' + names[i]);
                continue;
            }
            if (names[i] == Object.keys(contextEntry.value)) {
                console.log(getType(contextEntry.value));
                console.log('Child Name found in Context: ' + names[i]);
                // console.log(Object.values(contextEntry.value));
            }
        }
    }
    recursive(namesSplit, contextEntry);

I also have to check the type of every value from the Context.
There are 4 possible datatypes: Primitive, Array of Primitive,
Object, Array of Objects
if the value in the context is either Primitive or an Array of Primitives it will throw an error, if it is an Object i need to just extract the value of it and if it is an Array of Objects i need to find the right object and than extract the value from it
VariableType is an enum.
My Check Function is implemented like so:
function getType(contextEntry.value) {
        if (Array.isArray(contextEntry.value)) {
            for (let i of contextEntry.value) {
                if (isPrimitive(i)) {
                    return VariableType.ARRAY_OF_PRIMITIVES;
                }
            }
            if (contextEntry.value.some(val => typeof val === 'object')) {
                return VariableType.ARRAY_OF_OBJECTS;
            }
        }
        if (typeof contextEntry.value === 'object' && contextEntry.value !== null) {
            return VariableType.OBJECT;
        }
        if (isPrimitive(contextEntry.value)) {
            return VariableType.PRIMITIVE;
        }
    }


text:
Q: Using TF Estimator with TFRecord generator I am trying to create a simple NN that reads in a folder of tfrecords. Each record has a 1024-value 'mean_rgb' vector, and a category label. I am trying to create a simple feed-forward NN that learns the categories based on this feature vector.
def generate(dir, shuffle, batch_size):
    def parse(serialized):
        features = {
            'mean_rgb': tf.FixedLenFeature([1024], tf.float32),
            'category': tf.FixedLenFeature([], tf.int64)
        }
        parsed_example = tf.parse_single_example(serialized=serialized, features=features)
        vrv = parsed_example['mean_rgb']
        label = parsed_example['category']
        d = dict(zip(['mean_rgb'], [vrv])), label
        return d

    dataset = tf.data.TFRecordDataset(dir).repeat(1)
    dataset = dataset.map(parse)
    if shuffle:
        dataset = dataset.shuffle(8000)
    dataset = dataset.batch(batch_size)
    iterator = dataset.make_one_shot_iterator()
    next = iterator.get_next()
    print(next)
    return next

def batch_generator(dir, shuffle=False, batch_size=64):
    sess = K.get_session()
    while True:
        yield sess.run(generate(dir, shuffle, batch_size))

num_classes = 29
batch_size = 64

yt8m_train = [os.path.join(yt8m_dir_train, x) for x in read_all_file_names(yt8m_dir_train) if '.tfrecord' in x]

yt8m_test = [os.path.join(yt8m_dir_test, x) for x in read_all_file_names(yt8m_dir_test) if '.tfrecord' in x]

feature_columns = [tf.feature_column.numeric_column(k) for k in ['mean_rgb']]

#batch_generator(yt8m_test).__next__()

classifier = tf.estimator.DNNClassifier(
    feature_columns=feature_columns,
    hidden_units=[1024, 1024],
    n_classes=num_classes,
    model_dir=model_dir)

classifier.train(
    input_fn=lambda: generate(yt8m_train, True, batch_size))

However, I get the following error:

InvalidArgumentError (see above for traceback): Input to reshape is a
  tensor with 65536 values, but the requested shape has 64

I am not sure why it sees the input as a 64x1024=65536 vector instead of a (64, 1024) vector. When I print the next item in the generator, I get
({'mean_rgb': <tf.Tensor: id=23, shape=(64, 1024), dtype=float32, numpy=
array([[ 0.9243997 ,  0.28990048, -0.4130672 , ..., -0.096692  ,
         0.27225342,  0.13346168],
       [ 0.5853526 ,  0.67050666, -0.24683481, ..., -0.6999033 ,
        -0.4100128 , -0.00349384],
       [ 0.49572858,  0.5231492 , -0.53445834, ...,  0.0449002 ,
         0.10582132, -0.37333965],
       ...,
       [ 0.5776026 , -0.07128889, -0.61762846, ...,  0.22194198,
         0.61441416, -0.27355513],
       [-0.01848815,  0.20132884,  1.1023484 , ...,  0.06496283,
         0.29560333,  0.09157721],
       [-0.25877073, -1.9552246 ,  0.10309827, ...,  0.22032814,
        -0.6812989 , -0.23649289]], dtype=float32)>}

which has the correct (64, 1024) shape

A: the problem is at how the features_columns works, for example, I had a similar problem and I solved by doing a reshape here is part of my code that will help you understand:
defining the features_column:
feature_columns = {
        'images': tf.feature_column.numeric_column('images', self.shape),
    }

then to create the input for the model:
        with tf.name_scope('input'):
            feature_columns = list(self._features_columns().values())
            input_layer = tf.feature_column.input_layer(
                features=features, feature_columns=feature_columns)

            input_layer = tf.reshape(
                input_layer,
                shape=(-1, self.parameters.size, self.parameters.size,
                       self.parameters.channels))

if pay attention to the last part I had to reshape the tensor, the -1 is to let Tensorflow figure out the batch size

A: I believe the issue was that feature_columns = [tf.feature_column.numeric_column(k) for k in ['mean_rgb']] assumes that the column is a scalar - when actually it is a 1024 vector. I had to add shape=1024 to the numeric_column call. Also had to remove existing checkpoint saved model.


text:
Q: K nearest neighbour search with weights on dimensions I have a floor on which various sensors are placed at different location on the floor. For every transmitting device, sensors may detect its readings. It is possible to have 6-7 sensors on a floor, and it is possible that a particular reading may not be detected by some sensors, but are detected by some other sensors.
For every reading I get, I would like to identify the location of that reading on the floor. We divide floor logically into TILEs (5x5 feet area) and find what ideally the reading at each TILE should be as detected by each sensor device (based on some transmission pathloss equation).
I am using the precomputed readings from 'N' sensor device at each TILE as a point in N-dimensional space. When I get a real life reading, I find the nearest neighbours of this reading, and assign this reading to that location.
I would like to know if there is a variant of K nearest neighbours, where a dimension could be REMOVED from consideration. This will especially be useful, when a particular sensor is not reporting any reading. I understand that putting weightage on a dimension will be impossible with algorithms like kd-tree or R trees. However, I would like to know if it would be possible to discard a dimension when computing nearest neighbours. Is there any such algorithm?
EDIT:
What I want to know is if the same R/kd tree could be used for k nearest search with different queries, where each query has different dimension weightage? I don't want to construct another kd-tree for every different weightage on dimensions.
EDIT 2:
Is there any library in python, which allows you to specify the custom distance function, and search for k nearest neighbours? Essentially, I would want to use different custom distance functions for different queries.

A: Both for R-trees and kd-trees, using weighted Minkowski norms is straightforward. Just put the weights into your distance equations!
Putting weights into Eulidean point-to-rectangle minimum distance is trivial, just look at the regular formula and plug in the weight as desired.
Distances are not used at tree construction time, so you can vary the weights as desired at query time.

A: After going through a lot of questions on stackoverflow, and finally going into details of scipy kd tree source code, I realised the answer by "celion" in following link is correct:
KD-Trees and missing values (vector comparison)
Excerpt:

"I think the best solution involves getting your hands dirty in the code that you're working with. Presumably the nearest-neighbor search computes the distance between the point in the tree leaf and the query vector; you should be able to modify this to handle the case where the point and the query vector are different sizes. E.g. if the points in the tree are given in 3D, but your query vector is only length 2, then the "distance" between the point (p0, p1, p2) and the query vector (x0, x1) would be
sqrt( (p0-x0)^2 + (p1-x1)^2 )
I didn't dig into the java code that you linked to, but I can try to find exactly where the change would need to go if you need help.
-Chris
PS - you might not need the sqrt in the equation above, since distance squared is usually equivalent."


text:
Q: Spring Security ACL - Allow Users to 'read' one field from the Domain class I'm very new to the Spring Security Framework and I have a little problem here to solve.
I've already managed to use the @PreAuthorized("hasPermission('#person', Permission) annotation for service and controller methods.
This works fine for me, but this only works for the whole Domain class.
In my case there are some fields which should be shown to users despite they haven't the permission to read this Person.
A quick example:

*

*A user logs in.

*He'd like to visit the profile page from Jon Doe.

*But the user did not have the right to read Jon Doe.

*The System should notice the user that he hasn't the rights and shows the
Name like: You doesn't have the permission to read the profile from Jon Doe."

This is a very simple example, there are more fields a user could see.
Hopefully you'll understand what I'm asking for.
(I´m sorry my english is not that good.)
EDIT
PersonController
 @RequestMapping("/{id}")
 public String get(@PathVariable("id") Long personId, Model model,HttpSession session) {

    Person person = personService.findById(personId);

    /* DO STUFF HERE */

    return "person.show";
}

PersonService
@PreAuthorize("hasPermission('#personId', <domainClass>, 'read')")
public Person findById(Long personId) {
    return personRepository.findOne(personId);
}

A: You could do it explicitely by no using @PreAuthorized("hasPermission('#person', Permission) annotation at all and instead doing it by hand in your code ... but that would partially defect the interest of using Spring Security framework !
I would suggest :

*

*use the @PreAuthorized("hasPermission('#person', Permission) annotation in service class layer => it should throw an AccessDeniedException is user is not allowed to read that profile

*add a handler for AccessDeniedException in the calling controller. As exception will be thrown during the execution of a method of the controller, that handler will be given a chance to process it. Call a non protected method from the relevant service class that will only return public fields and forward to a view indicating You doesn't have the permission to read the profile from Jon Doe
In that configuration, the exception handler should take parameters equivalent to original controller method to have access to :

*

*the Principal executing the request

*the id for the requested profile

But this should not be a problem since an exception handler can accept almost the same parameters that a @RequestMapping method does in addition to the exception itself.
Per your edit, you get the personId from a path variable, which would be hard to get from the exception handler. So you should save it as a request attribute before calling the protected service method to get it in the exception handler :
 @RequestMapping("/{id}")
 public String get(@PathVariable("id") Long personId, Model model,HttpSession session, HttpServletRequest request) {

    request.setAttribute("personId", personId);
    Person person = personService.findById(personId);

    /* DO STUFF HERE */

    return "person.show";
}

@ExceptionHandler(AccessDeniedException.class)
 public ModelAndView accessDeniedHandler(HttpServletRequest request) {
    ModelAndView mav = new ModelAndView("accessDeniedView");
    Long personId = request.getAttribute("personId");
    // populate your model
    return mav;
}


text:
Q: Is there a way to adjust a web pages height with PHP to adjust with a browser? Is there a way that you can use PHP to automatically fit a web page into the size of the browsers window?

A: Not with PHP, but with Javascript or CSS you can.
PHP is server-side technology.
JavaScript and CSS are client-side technologies.

A: Even with javascript it's often buggy. It's very difficult to take thinks like horizontal taskbars into account. Javascript may find the window to be 500px in height and with the stuff that the user is running it's only 300 or so. Additionally, if someone has Javascript or css turned off, it ruins everything. Best bet is to design in a way that all browsers can deal with it. Make clean compliant designs and let users mess with it if they want to.

A: Using PHP or server-code more or less to change HTML/CSS elements wouldn't be optimal.  You would want to use HTML and CSS directly.  If that doesn't work, your absolute last option might be JavaScript but that's not best practice.


text:
Q: Does serializing of simultaneous global memory accesses to one address happen when there are L1 and L2 cache levels? Based on what I know, when threads of a warp access the same address in global memory, requests get serialized so it's better to use constant memory. Does serializing of simultaneous global memory accesses happen when GPU is equipped with L1 and L2 cache levels (in Fermi and Kepler architecture)? In other words, when threads of a warp access the same global memory address, do 31 threads of a warp benefit from cache existence because 1 thread has already requested that address? What happens when the access is a read and also when access is a write?

A: Simultaneous global accesses to the same address by threads in the same warp in Fermi and Kepler do not get serialized.  The warp read has a broadcast mechanism which satisfies all such reads from a single cacheline read with no performance impact.  The performance is the same as if it were a fully coalesced read.  This is true regardless of cache specifics, for example it is true even if L1 caching is disabled.
The performance of simultaneous writes is not specified (AFAIK) but behaviorally,  simultaneous writes always get serialized, and the order is undefined.
EDIT responding to additional questions below:

*

*Even if all threads in the warp write the same value into the same address, does it get serialized? Isn't there a write broadcast mechanism that recognizes such situation?

There is not a write broadcast mechanism that looks at all the simultaneous writes to see if they are all the same, and then take some action based on that.  The correct answer is that the writes happen in unspecified order, and the performance characteristics are undefined.  Obviously, if all the values being written are the same, you can be assured that the value that ends up in the location will be that value.  But if you're asking whether the write activity is collapsed to a single cycle or requires multiple cycles to complete, that actual behavior is undefined (undocumented) and in fact may vary from one architecture to the next (for example, cc1.x may serialize in such all way that all the writes are performed, whereas cc2.x may "serialize" in such a way that one write "wins" and all the others are discarded, not consuming actual cycles.)  Again, the performance is undocumented/unspecified, but the program-observable behavior is defined.

2 With this broadcast mechanism you explained, the only difference between constant memory broadcast access and global memory broadcast access is that the first one may route the access all the way to the global memory but the latter has a dedicated hardware and is faster, right?

__constant__ memory uses the constant cache, which is a dedicated piece of hardware that is available on a per-SM basis, and caches a particular section of global memory in a read-only fashion.  This HW cache is physically and logically separate from L1 cache (if it exists and is enabled) and L2 cache.  For Fermi and beyond, both mechanisms support broadcast on read, and for constant cache, this is the preferred access pattern, because the constant cache can only service one read access per cycle (i.e. does not support a whole cacheline read by a warp.)  Either mechanism may "hit" in the cache (if present) or "miss" and trigger a global read.  On the first read of a given location (or cacheline), niether cache will have the requested data, and it will therefore "miss" and trigger a global memory read, to service the access.  Thereafter, in either case, subsequent reads will be serviced out of the cache, assuming the relevant data is not evicted in the interim.  For early cc1.x devices, the constant memory cache was pretty valuable since those early devices did not have a L1 cache.  For Fermi and beyond the principal reason to use the constant cache would be if identifiable data(i.e. read-only) and access patterns (same address per warp) are available, then using the constant cache will prevent those reads from travelling through L1 and possibly evicting other data.  In effect you are increasing the cacheable footprint somewhat, over just what the L1 can support alone.


text:
Q: React Hooks (Functional) Lifecycle: Component rendered before useEffect() code I'm using React Functional Components. I'm familiar with the class lifecycle, but not with the functional lifecycle. My problem is that this component is rendered before the initialization performed in useEffect().. is complete. In my return() I check whether a state variable is true or not.

*

*I see my non-Error layout first (TopNav & Main)

*In 2-3 sec. the screen changes to the Error layout

What is the order in which functional components are processed? I can't present then non-Error layout until the error condition has been evaluated.
function App() {

    const [error, setError] = useState({});
    const [userInfo, setUserInfo] = useState({});

    const fetchUserInfo = async () => {
       const url = 'http://myapp.com/fetchUserInfo';
       try {
          const response = await axios.get(url);
          setUserInfo(response.data);
       }
       catch (error) {
          setError(error);
       }
    }

    // On initialization, fetch UserInfo
    useEffect(() => {
        fetchUserInfo();
    }, []);

    return (

            <Router>

                {error.message
                    ?
                        <Error error={error} />
                    :

                            <TopNav userInfo={userInfo} />

                }

            </Router>

  );
}

A: useEffect callback function is called after the render cycle and so once your render is complete, your fetchUserInfo call is made which is again an async operation.
What you should instead have is a loading state to let the UI wait will the API has provided as response to show an appropriate UI
function App() {
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState({});
    const [userInfo, setUserInfo] = useState({});

    const fetchUserInfo = async () => {
       const url = 'http://myapp.com/fetchUserInfo';
       setIsLoading(true);
       try {
          const response = await axios.get(url);
          setUserInfo(response.data);
       }
       catch (error) {
          setError(error);
       }
       finally {
           setIsLoading(false);
       }
    }

    // On initialization, fetch UserInfo
    useEffect(() => {
        fetchUserInfo();
    }, []);

    return (

            <Router>

                {isLoading? <Loader />: error.message
                    ?
                        <Error error={error} />
                    :

                            <TopNav userInfo={userInfo} />

                }

            </Router>

  );
}

A: Looking at your code, you will only get an error/data state after the async function fetchUserInfo is resolved/rejected. You can try adding a third state loading to signify that component has mounted but data fetching is in progress.
function App() {

  const [error, setError] = useState({});
  const [userInfo, setUserInfo] = useState({});
  const [loading, setLoading] = useState(true)

  const fetchUserInfo = async () => {
    setLoading(true);
    setError({})
    const url = 'http://myapp.com/fetchUserInfo';
    try {
      const response = await axios.get(url);
      setLoading(false);
      setUserInfo(response.data);
    }
    catch (error) {
      setLoading(false)
      setError(error);
    }
  }

  // On initialization, fetch UserInfo
  useEffect(() => {
    fetchUserInfo();
  }, []);

  return (

      <Router>

        {error.message && !loading
          ?
          <Error error={error} />
          :

            <TopNav userInfo={userInfo} />

        }

      </Router>

  );
}

A: Your code will be executed in this order.

*

*Since the error.message is empty for your first render, the TopNav and Main will be rendered.

*Execute the useEffect hook, call the fetchUserInfo function. either the error or the userInfo will be updated.

*Since the state has been changed, will render the page again.
in your case, it will evaluate the error.message and render the corresponding component.


text:
Q: Cannot access to the Ubuntu after upgrade I Downloaded updates and after restarting the computer, a message appeared saying
GNU GRUB Version 2.02~ beta 2-9

Minimal BASH-like line editing is supported. For the first word, TAB
lists possible command completions. Anywhere else TAB lists possible
device or file completions.

grub>_

I've read that you can use the boot repair, but how if I cannot access the operative system, Ubuntu is the only operating system in the computer.

A: Try to do that using a live ubuntu disk while mounting your active partition and then reinstalling grub using the live disk.

A: Simple way: Make a Ubuntu live USB.
Hard way: Try this GRUB command to boot your Ubuntu.
grub> linux  (hd0,1)/boot/vmlinuz-xxx root=/dev/sdax
grub> initrd (hd0,1)/boot/initrd.img-xxx
grub> boot

After booting, you can use Boot Repair to fix GRUB.

A: If you have more partitions on your computer, try doing ls then do ls (hdX,Y) on the things you saw on the ls command. If you see folders like 'boot', 'etc', 'root', that's probably your Ubuntu partition. Now execute the following commands to manually boot:
set root='(hdX,Y)'
linux /boot/vmlinuz-xxx root=/dev/sdXY
initrd /boot/initrd.img-xxx
boot

/dev/sdaXY depends on what (hdX,Y) is. If (hdX,Y) is (hd0,1) then you will have to set it to /dev/sda1, if it's (hd1,2) it will be /dev/sdb2.
After you boot to Ubuntu, login and open a terminal and try typing this:
sudo update-grub

Now you should reboot. If this doesn't fix grub, try re-installing it instead. Also re-install it on the device you already have grub.
sudo grub-install /dev/sdX             #Use what X was in the manual boot
sudo update-grub

Now reboot. This should re-install your grub and should fix your problem.


text:
Q: Rename Site collection after re creating it once after deletion :SP2010 Old Site Collection name = ABC
delete the site collection
Create a new Site COllection with same name = ABC
but on UI the title of site collection shows ABC-2
I have tried updating the title through UI (under site settings, Look and feel) and through powershell too.
Is there any other method?
EDIT
I am able to change the title through UI, just add a space or two in the title. But then when I check the permissions of site, there still the ABC-2 Memebers, ABC-2 Owners shows up.

A: SharePoint adds the number because the name still exists because of the site collection not being completely removed from the content database. If you would try to create a third, it would be called ABC-3 and so on.
Changing the title, the site collection will still be named ABC-2 internally.
When you remove a site collection from the UI, the site collection does still exist but is marked for deletion for 30 days until it is deleted permanently.
The only way to remove the deleted site collection is to through PowerShell.
This step can be avoided by deleting the site collection itself using PowerShell from the first time.
You can type Get-SPDeletedSite to see what site collections that are marked for deletion.
Then you can use Remove-SPDeletedSite to remove the site from the database and thus be able to create a new site collection with the same name.
If you wanna delete all the site collection at the same time you can pipe the 2 cmdlts together: Get-SPDeletedSite | Remove-SPDeletedSite
If you only wanna remove a single site, type Remove-SPDeletedSite -Identity "http://farm/sites/sitecollToRemove"


text:
Q: MySQL use Filter Table on Array of other Table I have two tables: profile and hobbie
Each profile is abled to choose up to hobbie, what will be safed in profile.p_hobbies as array of id's (e.g.: [1,5,7,8,9])
Now i want to get the names of a profile's hobbie.
I thougth it should be something link:
SELECT hobbie.h_name
FROM profile, hobbie
WHERE profile.p_id=37 AND hobbie.h_id IN profile.p_hobbies

The result is a failure #1064
#1064 - Fehler in der SQL-Syntax. Bitte die korrekte Syntax im Handbuch nachschlagen bei 'profile.p_hobbies LIMIT 0, 25' in Zeile 3
I already use the IN method in other SQL-Querys. I guess I can't use it if the Array I want to use is also data from the SQL Database?
Is there anything I can do without using multiple queries?
I'm using MariaDB-9

A: There is no such thing as an array type in MySQL. You have a problem with your data structure. You should have an association/junction table, with one row per user and hobby. Something like this:
create table profileHobbies (
    profileHobbieId int auto_increment primary key,
    profileId int,
    hobbieId int,
    foreign key (profileId) references profiles(profileId),
    foreign key (hobbieId) references hobbies(hobbieId)
);

Rows would looks like this:
profileHobbieId   profileId   HobbieId
       1              1           1
       2              1           3
       3              1           5

Then your query would look like:
SELECT h.h_name
FROM profileHobbies ph JOIN
     hobbie h
     ON ph.hobbie_id = h.hobbie_id
WHERE ph.profile_id = 37 ;

There are many reasons why you don't want to store a list of hobbies as a delimited string. Here are some:

*

*The ids are integers.  Data should be stored using the correct type and integers are not strings.

*Foreign key relationships should be properly declared.

*SQL has lousy string processing capabilities.

*The string functions needed to manage the list prevents the optimizer from using indexes.

*SQL has a really great data structure for storing lists. It is called a table, not a string.

A: Your best choice is to normalize your data. Storing sets of numbers as comma-delimited lists is considered harmful in SQL. Why harmful?

*

*it doesn't scale up well because it can't use indexes to search

*updating the sets of numbers is hard;  consider the problem of removing 2 from 1,2,3,4. That's a mess in SQL.

Some SQL variants have support for the updating function. But the scale-up problem is still there. (Don't be too offended at this advice: most of us have made this database-design mistake at one time  or another.)
You have a many-to-many relationship between profiles and hobbies.  Therefore you need a table, named profile_hobbie with two columns in it, p_id and h_id.
When a profile starts doing a hobby, you insert a row into profile_hobbie with the id of the profile and of the hobby.  If a profile stops doing a hobby, you delete that row.
Then your query would look like this:
  SELECT hobbie.h_name
    FROM profile
    JOIN profile_hobbie ON profile.p_id = profile_hobbie.p_id
    JOIN hobbie ON profile_hobbie.id = hobbie.h_id
   WHERE profile.p_id=37

This will yield a (possibly empty) list of hobbies for the chosen profile.
You could also try using MySQL's FIND_IN_SET() function, but you may run into conversion trouble between integers and strings.
   SELECT hobbie.h_name
     FROM profile
     JOIN hobbie ON (FIND_IN_SET(hobbie.h_id, profile.p_hobbies) > 0)

But, Gordon is right. This uses a lousy string-processing hack.


text:
Q: How can I use sed to generate a list of files to be deleted via rm? I have a compute cluster that takes input files and generates two output files from stdout and stderr and the error file is empty if thing ran correctly. Since we do a lot of runs in parallel, I just want to maintain the inputs and logs when there is an error. This breaks down to the following tasks:

*

*Find all of the empty error logs.

*Find the prefix that corresponds to a given batch.

*Delete all of the files related to that batch.

A batch of files looks like the following:

25584-0.8-0.170-bfa.yml
25584-0.8-0.175-bfa.pbs
25584-0.8-0.175-bfa.pbs.e20693449
25584-0.8-0.175-bfa.pbs.o20693449

So far I've sorted out how to find the files:
find . -name '*.pbs.e*' -size 0

and how to extract the generic prefix that applies to all of the files:
sed 's/\(.*\)\.pbs.e.*/\1.*/'

so piping all of these together I would expect the following to delete all of the files associated with compute jobs that had no errors:
find . -name '*.pbs.e*' -size 0 | sed 's/\(.*\)\.pbs.e.*/\1.*/' | xargs -d '\n' rm

However the output I get for all matching cases is the following:

rm: cannot remove `./25584-0.8-0.170-bfa.*': No such file or directory

Manually typing out the command (e.g., rm 25584-0.8-0.170-bfa.*) works a expected and it appears that sed appends a \n to the output which means the | xargs rm or | xargs -d '\n' rm pipes are generating the error.
How can I format the output from sed (or similar tool) so that the matching files will be deleted?

A: The reason you get
rm: cannot remove './25584-0.8-0.170-bfa.*': No such file or directory

is that this command was executed:
rm "./25584-0.8-0.170-bfa.*"

where the argument is a string containing a star and not a glob expression. A glob needs to be expanded by a shell and given to the command as arguments.

For this directory
-rw-r--r--  1 t users    0 Jul 20 22:10 25584-0.8-0.175-bfa.pbs
-rw-r--r--  1 t users    0 Jul 20 22:10 25584-0.8-0.175-bfa.pbs.e20693449
-rw-r--r--  1 t users    0 Jul 20 22:10 25584-0.8-0.175-bfa.pbs.o20693449
-rw-r--r--  1 t users    0 Jul 20 22:10 25584-0.8-0.176-bfa.pbs
-rw-r--r--  1 t users    0 Jul 20 22:10 25584-0.8-0.176-bfa.pbs.e20693449
-rw-r--r--  1 t users    0 Jul 20 22:10 25584-0.8-0.176-bfa.pbs.o20693449

Here we print two strings:
> find . -name '*.pbs.e*' -size 0 | sed 's/\(.*\)\.pbs.e.*/\1.*/' |\
xargs -I@ echo @

./25584-0.8-0.175-bfa.*
./25584-0.8-0.176-bfa.*

Here we call a shell which is expanding the arguments before giving them to the command:
> find . -name '*.pbs.e*' -size 0 | sed 's/\(.*\)\.pbs.e.*/\1.*/' |\
xargs -I@ bash -c "echo @"

./25584-0.8-0.175-bfa.pbs ./25584-0.8-0.175-bfa.pbs.e20693449 ./25584-0.8-0.175-bfa.pbs.o20693449
./25584-0.8-0.176-bfa.pbs ./25584-0.8-0.176-bfa.pbs.e20693449 ./25584-0.8-0.176-bfa.pbs.o20693449

which is what you need, so your command could be modified to:
find . -name '*.pbs.e*' -size 0 | sed 's/\(.*\)\.pbs.e.*/\1.*/' | xargs -I@ bash -c "rm -- @"

A: I suspect that there is more than one way of doing this, but since a one liner isn't needed the issues with sed can be bypassed by just using a loop:
for item in `find . -name '*.pbs.e*' -size 0 | sed 's/\(.*\)\.pbs.e.*/\1.*/'`; do
  rm $item
done

A: the asterisk * is taken as literal character and not expected filename expansion. you can pass your sed to another find which takes literal * in -name pattern without evaluating it
find . -maxdepth 1 -type f -name '*.pbs.e*' -size 0 | sed 's,^\./\(.*\)\.pbs\.e.*,\1.*,' | xargs -n1 -I{} find . -maxdepth 1 -type f -name '{}' -print -delete

to make the sed a little more safe you can run it on full path, only culprit you must extra escape meta characters in path name
# search dir
dir=.
dir=$(realpath "$dir")

# that should escape meta-characters in non-trivial dir name
# stackoverflow.com/q/15783701
printf -v dirstr '%q' "$dir"

# $dirstr is used for sed but can replaced with $dir for simple dir name
find "$dir" -maxdepth 1 -type f -name '*.pbs.e*' -size 0 | sed "s,^$dirstr/\(.*\)\.pbs\.e.*,\1.*," | xargs -n1 -I{} find "$dir" -maxdepth 1 -type f -name {} -print -delete

should work with whitespace and other non-trivial file names (except for \n)


text:
Q: Reasoning through this probability problem Two men are chosen randomly from a group with $n$ people. Some of those people have have a cat and some don't. Some are men and some are women. It is a given that the probability that $2$ chosen people being both men and having a cat is $\frac{39}{995}$.
Now, there's more information to this problem, but I believe this will suffice. The probability of being a men and owning a cat is $0.2$. What is the value of $n$, that is, how many people are there?
The answer lies in the solution to this equation and here's where I get stuck: $$0.2\cdot \frac{0.2n-1}{n-1}=\frac{39}{995}$$
I know how to solve the equation, I just don't know why it makes sense.

A: Let $m$ be the number of men with cats and let $N$ be the total number of people.
From what you said, we have that probability of a men with a cat being selected is:
$$\frac{m}{N} = 0.2$$
And the probability of selecting (I'm assuming without replacement) two men with cats is:
$$\frac{m(m-1)}{N(N-1)} = \frac{39}{995}$$
Can you solve it from here?


text:
Q: "Index was outside the bounds of the array" in c#. Why? I keep getting an Exception in my for-each loop, and I don't understand why.
The error goes away when I make array[i] equal to i, but what if I want it equal to a different value?
Relevant code:
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array1 = new int[5];

            for (int i = 0; i < 5; i++)
            {
                array1[i] = (i + 1);
            }

            foreach (int value in array1)
            {
                Console.Write(array1[value]);
            }

            Console.ReadKey();

        }
    }
}

A: The problem with your foreach loop is you are using VALUE as the array index, instead of simply printing the value.
Change your code to:
Console.Write(value);

and it should work.

A: foreach (**int** value in array1)
{
    Console.Write(**array1[value]**);
}

do this instead:
foreach (var value in array1)
{
    Console.Write(value);
}

A: you are assigning i+1 to array elment value and trying to access the array using this value.
        int[] array1 = new int[5];

        for (int i = 0; i < 5; i++)
        {
            array1[i] = (i + 1);
        }

in above code
    array1[0]=1
    array1[1]=2
    array1[2]=3
    array1[3]=4
    array1[4]=5

value in   array1[4] is 5
now in foreach loop your are trying to access array at location 5 i.e array1[5] which throws index out of bound exception

A: On this line, you are dimensioning the array with five elements, 0 to 4:
int[] array1 = new int[5]; // elements 0, 1, 2, 3, 4

Then you are looping five times in your first "for" loop and setting every element equal to the index plus one: 1, 2, 3, 4, 5.  In the next "for" loop, you are attempting to access the elements of the same array by their values, but when you reach the last element, whose value is 5, it fails because there is no index 5.  Remember, there are only indexes 0 to 4.


text:
Q: StatefulBuilder VS StatefulWidget in Flutter - performance We can use StatefulBuilder to update a specific element on the UI of a StatelessWidget and in other hand, we can archive similar result moving the StatelessWidget to a StatefulWidget and getting rid of the StatefulBuilder widget.
I prefer StatefulBuilder because it makes the code much easier and cleaner, but what's the best in terms of performance?
A: Wrap everything on a StatefulBuilder using StatelessWidget
B: Use StatefulWidget

A: There is effectively no difference in performance between the two.  Both involve the creation of a State object.
Given that your using global state, there is no real reason to use a StatefulBuilder relating to part of that existing global state.  The StatefulBuilder provides a mechanism to have its own associated State object with state you define and can mutate.  In your case (global data), your state is already in memory, so you might as well just mutate it in your StatefulBuilder builder callback, e.g.
setState(() => myGlobalCounter.increment());

You are likely aware, that one would normally prefer an InheritedWidget based state solution.  While this can be considered equivalent in some ways to just moving global state to a global tree location, it more easily allows for all interested Widgets to be notified of changes to that state.


text:
Q: Finding limits graphically

Determine lim f(x) as x approaches -2

Since there are two y values as x approaches -2 namely a gap at -1(from left and right) and a solid dot at -3, which of the following should be correct?

The limit DNE or the limit exists at y=-1?

Thank you.

A:
The limit of f(x) as x approaches -2 is -1.

The limit is a two-sided limit, i.e., whether the limit f(x) approaches -2 from the left or from the right, the value remains the same and therefore the limit is -1. We say, therefore, that the limit exists.
Note, however, that the 'solid' dot is a defined value which is applicable to problem related to: Determine f(-2) which is -3.


text:
Q: Searching for a particular word in a file in C Good day y'all i have been trying to find if a particular remark or word exist in a file. Don't know why the else part isn't working. How do I do it?
#include <stdio.h>
#include <string.h>

int main()
{
    FILE *fp;
    char *file = "mar";
    char *str1 = "PASS";
    char *str2 = "FAIL";
    char *find,*f;
    char line[20] ;

    fp = fopen(file, "r");

    while( fgets (line, 20, fp)!=NULL )
    {
       if((find = strstr(line,str1)) || (find = strstr(line,str2)))
          {
              printf("ok");
              break;
          }
        else//if(find != strstr(line,str1))// || (find != strstr(line,str2)))
          {
              printf("Still processing");
              break;
          }
    }

    fclose(fp);
    return(0);
}

A: You don't need any condition in the else part. You also don't need to store the pointer returned by strstr since you don't use it.
The problem is probably because of the break statement you have in the else part. Consider what would happen if anyone of lines do not have
either of those words you look for: It would go into the else part and break the loop. Hence, it will not read the file anymore.
Your if-else can be simplified to:
   if( strstr(line,str1) || strstr(line,str2) )
      {
          printf("ok");
          break; // If you want to continue searching the file after
                 // first match, then you should remove this `break;`
      }
    else
      {
          printf("Still processing");
      }

I would avoid hard-coding array size in fgets(). Instead the loop condition can be written as:
   while( fgets (line, sizeof line, fp) ) {
      ...
   }


text:
Q: Importing quandl using python 27 I'm trying to import quandl and have downloaded it from Github and unzipped it to C:\Python27\Lib\site-packages\quandl but whenever I run my file "quandltest.py", I get "ImportError: No module named inflection". I then downloaded inflection from Github and saved it to the site-packages folder but still get the following whenever I run the file. I'm using a Python 27 IDLE to import quandl (I get the same error using Pycharm). Anyone have any idea/the same issue?? Thanks! I also do not have access to my command window as it has been disabled by the admin so I cannot pip install.
Traceback (most recent call last):

File "C:/Python27/quandltest.py", line 1, in <module>
    import quandl

File "C:\Python27\lib\site-packages\quandl\__init__.py", line 7, in <module>
    from .model.database import Database

File "C:\Python27\lib\site-packages\quandl\model\database.py", line 11, in <module>
    from quandl.connection import Connection

File "C:\Python27\lib\site-packages\quandl\connection.py", line 5, in <module>
    from .util import Util

File "C:\Python27\lib\site-packages\quandl\util.py", line 1, in <module>
    from inflection import parameterize

ImportError: No module named inflection


text:
Q: Trace of a Summation of Positive Definite Matrices with a Real Coefficient
Show that $$\mbox{tr} \left( \sum_{i=1}^k (\alpha A_{i} + B_{i})^2 \right) \geqslant 0, \qquad \forall \alpha \in \mathbb{R}$$ given that $A_{i}$ and $B_{i}$ are positive definite $n \times n$ complex matrices $\forall i=1,\dots,k$.

Any hint?

A: Hint: $(\alpha A_i + B_i)^2$ is positive semidefinite.


text:
Q: How can I show base-2 long division? I am writing a report in Latex and need to represent the CRC computation. So basically, I need to show the Paper-n-Pencil Method of Long Division in LaTeX.
Any idea how I can approach this problem ? Any good reference would be highly appreciated.
I plan to write similar thing in LaTeX.

A: Per this article, I ended up doing this:

\newdimen\digitwidth
\settowidth\digitwidth{0}
\def~{\hspace{\digitwidth}}

\def\divrule#1#2{%
\noalign{\moveright#1\digitwidth%
\vbox{\hrule width#2\digitwidth}}}
101\,\begin{tabular}[b]{@{}r@{}}
10010 \\ \hline
\big)\begin{tabular}[t]{@{}l@{}}
1011110 \101 \\ \divrule{0}{7}
~~~111 \~~~101 \\ \divrule{3}{4}
~~~~100
\end{tabular}
\end{tabular}
You have to do the division by hand, then use '~'s for aligning the digits. For the little bars, do \divrule{startPosition}{length}.
Example output:

A: I've never used it myself, but you might try this package. It would likely require modification for binary, though.
There is also this post.