Q:

How to give minimum 2 lines of space to overflowing text?

Expected output should be at least 2 lines tall

I want to retain the text-overflow: ellipsis property

    Can we make this upper case? and also remove the word and’? Can we make this upper case? and also remove the word and’? Can we make this upper case? and also remove the word and’? Can we make this upper case? and also remove the word and’? Can we make
    this upper case? and also remove the word and’? Can we make this upper case? and also remove the word and’?

A:

Got the best way using -webkit-line-clamp (doesn't work in IE) from this answer

    Can we make this upper case? and also remove the word and’? Can we make this upper case? and also remove the word and’? Can we make this upper case? and also remove the word and’? Can we make this upper case? and also remove the word and’? Can we make
    this upper case? and also remove the word and’? Can we make this upper case? and also remove the word and’?


Q:

Unable to upload to App Store using XCode 7

-Background
This issue only happened using XCode 7.0 or later but neither before.
The project only has minor changes in sources code but not in assets file as well as the story board.
-Issue
After archived the project successfully and waiting the process to be completed after pressing Upload to App Store.
The following error prompt

Your binary is not optimized for iPhone 5 - New iPhone apps and app updates submitted must support the 4-inch display on iPhone 5 and must include a launch image referenced in the Info.plist under UILaunchImages with a UILaunchImageSize value set to {320,568}. Launch images must be PNG files and located at the top-level of your bundle, or provided within each .Iproj folder if you localized your launch images.

However, launch image has never been set and exists in the project, therefore i find there are no clues and hints for how to fix this problem. It is confirmed the configuration can work on or before XCode 6.4.

Please kindly advise.

A:

LaunchScreen file should be xxx.Storyboard  Actually Main is the main storyboard file where all your views are designed. You should Change it with LaunchScreen.Storyboard or LaunchScreen.xib  ... But if you have image.assets you can click on use asset Catalog and then in launch image fill all the images required with all sizes you need. (if you will use catalogs, don't forget to clear Launch Screen File name (leave it blank))


Q:

Extract string which is separated by dots followed by another string

I need to get the browser version which is followed by browser name and / in my log file. Example
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0.5.7

Here i would like to extract the version which comes after Firefox i.e (17.0.5.7). I have tried the following, but no success. As i am using AIX, i am unable to make use of -O flag.
grep -w 'Firefox\/[^ ,]\+' $line
sed 's/^.*\(Firefox\/[^ ,]*\).*$/\1/' $line

Also i need use the command inside while do loop like below
while read -r line
do
case $line in
*Firefox*) print "<browser Firefox>\"" command_to_be_executed $line "\"</browser>";;
*) print "<browser>\"Unknown\"</browser>";;
esac
done < filename

Thanks in adavance.

A:

Since it's the last field in the line, you can do:
awk -F'[ /]' '$(NF-1)=="Firefox"{print $NF}' file.log

It prints the lines which checks whether the it is "Firefox" and prints the version followed.

Simply do echo on line and get the version.
while read -r line
do
case $line in
*Firefox*) version=$(echo $line | awk -F'[ /]' '{print $NF}' )
print "<browser Firefox>\"" $version "\"</browser>";;
*) print "<browser>\"Unknown\"</browser>";;
esac
done < filename


Q:

How would i go about creating a external url monitor?

How would I go about creating an application that can somehow see URLs I am viewing in most popular browsers?
Can it be done out of process?
In what ways can this be done?
Can it be done without browser plugins?

A:

The simplest answer is use a proxy server.. prevent html access out except from the proxy server so they have to use it, then all url requests go to the proxy server, even if you choose to make it yourself, then you can collect the URLS either from logs or something and off you go.


Q:

Why is the padding not applied on a div with a table inside?

I have this simple html code here. I don't understand why the padding in the second DIV is not showing? If i remove the cellpadding and spacing, i see around 10 pixels in padding, but not the 20px i want.
Why?

                     xxx
                    xxx

A:

There is absolutely no reason.
You just forgot a : after padding

                xxx
                xxx

See jsfiddle


Q:

Python: Calculate the max height of a tree with multiple children

def __init__(self,label=None):
    self.label = label
    self.leftMostChild = None
    self.RightSibling = None

def height(self):
    if self.leftMostChild == None and self.RightSibling == None:
        return 0
    else:
        if self.leftMostChild:
            return self.leftMostChild.height() + 1

        if self.RightSibling:
            return self.RightSibling.height()

Apparently, the height is off by 1. When a tree with height 3 is produced, 2 gets return after calling the function height. I am not sure where did i do wrong in this function.
Any help would be appreciated.

A:

Return causes a function to end immediately. This means that if a node has both a left most child and a right sibling, the right sibling will never be evaluated.  Here is the function with only one return for each if/else branch.
def height(self):
    if self.leftMostChild == None and self.RightSibling == None:
        return 0
    else:
        leftHeight = rightHeight = 0
        if self.leftMostChild:
            leftHeight =  self.leftMostChild.height() + 1

        if self.RightSibling:
            rightHeight = self.RightSibling.height()
        return max(leftHeight, rightHeight)

This can be further simplified to:
def height(self):
    leftHeight = rightHeight = 0
    if self.leftMostChild:
        leftHeight =  self.leftMostChild.height() + 1
    if self.RightSibling:
        rightHeight = self.RightSibling.height()
    return max(leftHeight, rightHeight)


Q:

wrapper issue with the DOM structure using jquery

I have an issue where I have the following jQuery and mark up working although if I move the location of textarea the .click() event doesn't fire.  I haven't seen this $('element', something) before.  What does the $wrapper syntax mean please?  Thanks,
 this.each(function () {
     var $field = $(this);
     var $wrapper = $field.parent();

      $('.myClass', $wrapper)
          .click(function () {
              // do stuff
          });

  <textarea></textarea>

A:

This answer assumes that $(this) refers to the textarea, which isn't clear from your question.
The second parameter in $('.myClass', $wrapper) refers to the context of the first parameter. That is, the first parameter is a descendant of the second parameter.
If $field is your text area, the context of .myClass is the parent of the textarea (as that is how you've defined $wrapper).
If you move the textarea out of the DIV that also contains .myClass, your context changes. Since .myClass is no longer in that context, the event handler is not bound to it.
If you want the click event bound to .myClass irrespective of context, use:
$('.myClass').click(function () {
     // do stuff
});


Q:

Updating state of the app without touching the DOM - Vue.js

I'm going through the Vue.js guide and I came across this paragraph. It says:

Note in the method we simply update the state of our app without touching the DOM

Basically the method simply reverses a string on click of a button. What I'm unable to understand is the concept of Updating the state of app without touching the DOM. What does the state mean here? Can somebody explain this in layman terms?

A:

One of the cornerstones of Vue.js is its simply implemented two-way data binding. This means that when a state or data value is changed within the Vue object/instance, it is also synced and changed in the DOM and vice versa without having to manually update both.
In a pure Javascript situation such as:

function changeData() {
  document.getElementById('data').innerHTML = "Second";
}

  First

<button onclick="changeData()">Change Value</button>

In this, we are directly manipulating the DOM to change the text value of the span element, however, with Vue's two-way data binding, only the instance's state/data must be changed for both to update.


Q:

Wacky UITableViewCellAccessoryCheckmark Behavior

I am setting the UITableViewCellAccessoryCheckmark programmatically as seen in the code below. Sometimes it works perfectly and the cells that contain titles that should be checked are checked and the ones that shouldn't be checked aren't checked. BUT AT OTHER TIMES when a cell receives a check, the tableview will add a random checkmark to another cell that shouldn't be checked. But this occurs only on some lists even though it might contain the same exact data as another list that works fine. The cells are contained in a section that has a max of maybe 6 rows so they all appear on the screen once you scroll to that section. Most of the time the section only has 3 rows. If the checkmarks are screwed up because of reusing cells then I would think the section that has 6 rows would be the ones causing problems, but it's not. The messed up sections are the ones with only 3 rows! As you will see, I've logged just about every line and the debugger gives me what I expect to see but the tableview just goes and adds extra checkmarks that don't show up in the debugger. I just cannot figure out what I'm doing wrong. If anyone can just give me a jumping off point of what else to check, I'm all ears. Right now I'm all tears! Let me know if you need any other bits of code. Thanks in advance!
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

if (indexPath.section == 0 && indexPath.row == 0)
{
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}

if(_book.hasNovellaArray)
{
    NSMutableArray *storyList = [[NSMutableArray alloc] init];
    NSMutableArray *newList = [[NSMutableArray alloc] init];

    for (id title in _book.novellaArray)
    {
        [storyList addObject:title];
        NSLog(@"added title in the collection:%@:",storyList);
    }

    for (id story in _book.novellaRead)
    {
        [newList addObject:story];
        NSLog(@"added story has been read:%@:", newList);
    }

    for (id i in storyList)
    {
        for (id j in newList)
        {
            if ([ i isEqualToString:j])
            {
                NSLog(@"%@ = %@", i, j);
                if ([_detailCell.detailLabel.text isEqualToString:i])
                {
                    _detailCell.accessoryType = UITableViewCellAccessoryCheckmark;
                    NSLog(@"cells have been checked");
                    NSLog(@"title checked: %@", _detailCell.detailLabel.text);
                    NSLog(@"at index path %ld", (long)indexPath.row);
                }
            }
        }
    }
}

}

A:

Cells get reused. When you conditionally set a property of a cell, you must always reset that property for all other conditions.
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    } else {
        [cell setSelectionStyle:UITableViewCellSelectionStyleDefault];
    }

    _detailCell.accessoryType = UITableViewCellAccessoryNone;

    if (_book.hasNovellaArray)
    {
        NSMutableArray *storyList = [[NSMutableArray alloc] init];
        NSMutableArray *newList = [[NSMutableArray alloc] init];

        for (id title in _book.novellaArray)
        {
            [storyList addObject:title];
            NSLog(@"added title in the collection:%@:",storyList);
        }

        for (id story in _book.novellaRead)
        {
            [newList addObject:story];
            NSLog(@"added story has been read:%@:", newList);
        }

        for (id i in storyList)
        {
            for (id j in newList)
            {
                if ([ i isEqualToString:j])
                {
                    NSLog(@"%@ = %@", i, j);
                    if ([_detailCell.detailLabel.text isEqualToString:i])
                    {
                        _detailCell.accessoryType = UITableViewCellAccessoryCheckmark;
                        NSLog(@"cells have been checked");
                        NSLog(@"title checked: %@", _detailCell.detailLabel.text);
                        NSLog(@"at index path %ld", (long)indexPath.row);
                    }
                }
            }
        }
    }
}


Q:

The effects of war on the workforce

It seems to me that a war have two opposite effects on the post-war workforce :

it decreases the active population because of the deaths
it increases the active population by mobilizing women (who stay on the labor market after the war)

Is it correct ? And which of these two effects prevails in the case of the WWI and the WWII please ?

A:

I'm not sure that deaths decrease the active population
Historically speaking there are periods when war is conducted only by professional military (in which case there is no effect on the labor force), and periods where war is conducted by citizen/soldier/militia.  Different sides in the same war may have different participation rates.  Military service in most wars is a very tiny fraction of total population. I believe military service is generally less than 10% of the population - meaning that the change in labor force participation is effectively insignificant.
I'm not sure that women are mobilized in all wars.
I'm not sure that there was a vast surge in female employment during the Napoleonic wars or even during the Vietnam war. I know that modern specialists in women's history question the extent to which women's participation in the labor force actually surged during WWII. Women's participation in the labor force probably shifted between segments, but may not have risen significantly.   (My girlfriend has written several papers on this, but I haven't learned to boil down her thesis into a sound bite that fits neatly on SE).
I'm not sure how you're defining "Active Population"
Inventing your own term here makes it very difficult to provide an answer with references and citations. I think you should probably research employment to population ratio or other standard terms of use.  The interesting question is whether the war pulls people out of the idle class into the working class. Even the unemployment rates only measure the proportion of the population that chooses to seek work - it ignores those who have given up, or choose not to participate (because they're wealthy, because they're handicapped, because they are criminal, etc.)
I think it is safer and more accurate to say that the allocation of the labor force shifts from private enterprise (butter) to mandated production (guns).  The proportion of the GDP that is shifted is probably much more important than the labor force participation.


Q:

72 + 96 = 120, is it possible?

I came across the following riddle:

How is it possible for $72+96=120$ to be correct?

A:

This is the

 side lengths of a right-angled triangle, where the two shorter sides have length 72 and 96; and the longest side has length 120. (Note this is a 3-4-5 Pythagorean triple).

Essentially,

 if you travel north 72 units and then east 96 units, it's equivalent to travelling northeast (not exactly, the heading will be $\tan^{-1}\left(\frac{4}{3}\right)$ radians) by 120 units


Q:

Communication with SD Card with STM32 Processor - SDIO protocol

I am using the board Nucleo F401Re based on micro-controller STM32F401RET6. I connected to the board a Micro SD slot, and interested in writing data to the SD Card and read data from it. I used the software STM32CubeX to generate code and in particular the SD library with built-in functions. I tried to write a simple code which writes an array to a specific array and tries to read the same data afterwords. The code is as follows:
  int main(void)
{
  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART2_UART_Init();
  MX_SDIO_SD_Init();

  char buffer[14] = "Hello, world\n";
  uint32_t to_send[512] ; // Te
  uint32_t to_receive[512];
  uint64_t address = 150;
  HAL_SD_WriteBlocks(&hsd, to_send, address, 512, 1);
  HAL_SD_ReadBlocks(&hsd, to_receive, address, 512, 1);

  while (1)
  {
      HAL_UART_Transmit(&huart2, (uint8_t *)buffer, 14, 1000);
      HAL_UART_Transmit(&huart2, (uint8_t *)to_receive, 512, 1000);

}

The code stopps in the middle of the function HAL_Init() and I'm getting the following message:
The stack pointer for stack 'CSTACK' (currently 0x1FFFFD30) is outside the stack range (0x20000008 to 0x20000408)

This message doesn't appear when I don't use the functions HAL_SD_WriteBlocks(), or HAL_SD_ReadBlocks(). If someone already had this problem and knows how to fix it, some help would save me. If needed I can add the rest of the code.

A:

You're using too much stack space. You can adjust the allocated stack space in the linker script and increase it if needed.
However you can probably avoid that by writing your code differently. In your example above, you're allocating large buffers (4kB) on the stack. Don't do that unless absolutely necessary. I'm referring to this:
int main(void) {
  // ...
  uint32_t to_send[512];
  uint32_t to_receive[512];
  // ...
}

Instead, allocate your buffers like this:
uint32_t to_send[512];
uint32_t to_receive[512];

int main(void) {
  // ...
}


Q:

Typo3 8.7 Indexed Search: exclude images

I am looking for the proper way to exclude images from being indexed. I tried using plugin.tx_indexedsearch.settings.mediaList = 0 (I deduced that number from the mediaTypes select list in the advanced search form) but that only changed the options in the MediaTypes select list.
I found out that one of the hidden fields is tx_indexedsearch_pi2[search][mediaType] and that there is a default setting searchParams.mediaType = -1 in the extbase variable dump. So I tried plugin.tx_indexedsearch.searchParams.mediaType = 0 in the TypoScript settings – but to no effect.
So what I did was to change the value of the above mentioned hidden field in the template file Partials/Form.html from {searchParams.mediaType} to 0. But I reckon that will only keep files from being displayed in the results not from being indexed in the first place.

A:

In my configuration the following TS helped:
plugin.tx_indexedsearch.settings.mediaList =

and I excluded in the extension configuration (basic.ignoreExtensions)
jpg, png, gif, jpeg


Q:

Tracing Che on OpenShift

https://www.eclipse.org/che/docs/che-7/tracing-che/ has a number of  environment variables to set to enable tracing.
Is it possible to set these when working on OpenShift? If so; where would the correct place be; and where will the Jaeger interface be available?
Thanks

A:

Is it possible to set these when working on OpenShift?

Yes, you can configure it for the Che master of your installation.

OpenShift is the Saas Che offering

As a user of che.openshift.io you can't leverage from tracing capabilities of Che at this moment.


Q:

How to add slide in the middle of presentation using python-pptx?

I have a template.pptx , having 10 slides in total. I want to copy a slide/layout of slide 2 and add new slide after 2, between 2 and 3.
what I can do currently is copy and add the slide at the end of presentation.
prs = Presentation('C:\Documents\template.pptx')
slide = prs.slides.add_slide(prs.slide_layouts[1])
prs.save('C:\Documents\template_save.pptx')

Can I do this using java apache-poi?

A:

I have tried the hybrid approach and it works well.

Copy and add slide at the end of presentation with python-pptx
Reorder slides with Apache POI

ppt.setSlideOrder(slides.length-1, 4); // Bring last slide to 5th position


Q:

c programming scanf will not read input twice

I am writing a program in CodeBlocks in C. I want to check if the input is in the right type and if not try to get it again.
My problem is whenever I'm trying to get the input with scanf and the input is incorrect it won't enter scanf again and just keep looping as if the input is always incorrect.
#include <stdio.h>
#include <stdlib.h>

int main()
{
    float a = 0;

    while(scanf(" %f", & a) == 0)
    {
        printf("reenter");
    }

    printf("%f", a);

    return 0;
}

When I tried to enter incorrect value as 'y' the loop will go on:

If I will enter a current value it will get it as it should.

A:

In case of bad input entry, the input buffer is not consumed by scanf(), so you must read it additionaly in the way which guarantee successfull reading - for example as string.
See below:
int main()
{
    float a = 0;

    while (scanf(" %f", & a) == 0)
    {
        scanf("%*s"); // additional "blind" read

        printf("reenter");
    }

    printf("%f", a);

    return 0;
}


Q:

Storing case statement result in a variable SQL SEVER

Is there anyway to store the result of a case statement in a variable so that it has a fixed result that i can return at any point.
e.g.
    CASE
    WHEN MONTH([DATE]) = MONTH(getdate()) AND
    YEAR([DATE]) = YEAR(getdate())
    THEN SUM(Figure)
    OVER (PARTITION BY [Name],
    MONTH([DATE]))
    ELSE 0
    END INTO @MTD

Ideally i want to be able to return a consisted month to date value where the calculation is not affected by where clauses

A:

If you use a variable to store the profit it will only be able to store one row, therefore you should add a where clause to select a specific [Name], [Month] and probably [Year] for which you want to retrieve the overall profit. You  should add [Year] to your partition as well as to the WHERE clause unless you want to sum profits from the same month in different years.
The resulting code would be like this:
declare
    @val int = 0;

select
    @val = CASE
        WHEN MONTH([DATE]) = MONTH(getdate()) AND
        YEAR([DATE]) = YEAR(getdate())
        THEN SUM(PROFIT)
        OVER (PARTITION BY [Name],
            MONTH([DATE]), YEAR([DATE]))
        ELSE 0
        END
FROM table_name
WHERE [Name] = @Name AND
      MONTH([DATE]) = @Month AND
      YEAR([DATE]) = @Year

print @val


Q:

How center text of the column headers in SlickGrid?

there any way to center text in a column header
Any ideas how to do this or what  ccs  must be changed ?

A:

Add the following style in your css:
.slick-header-column {
   text-align: center;
}


Q:

seek any true in a column from a list of data frames in R

I have a list of dataframes containing only boolean (TRUE / FALSE) columns.
I need to know if any of these columns contains any TRUE value (all are expected to be false and in fact, all are FALSE), but I'm getting just nonsense.
mylist <-
  list(df1=data.frame(
    "column11" = c(FALSE, FALSE, FALSE, FALSE),
    "column12" = c(FALSE, FALSE, FALSE, FALSE)
  ),df2=data.frame(
    "column21" = c(FALSE, FALSE, FALSE, FALSE),
    "column22" = c(FALSE, FALSE, FALSE, FALSE)
  ),df3=data.frame(
    "column31" = c(FALSE, FALSE, FALSE, FALSE),
    "column32" = c(FALSE, FALSE, FALSE, TRUE)
      ))

lapply(mylist, function(x) any(TRUE))

$df1
[1] TRUE

$df2
[1] TRUE

$df3
[1] TRUE

A:

One reason the anonymous function doesn't work as expected is because its argument is not being used, instead any() is checking if the value TRUE is TRUE.  It also needs to be passed a logical vector, not a data.frame.
If you want to check if any column in the data.frame has a TRUE value use:
sapply(mylist, function(x) any(unlist(x)))

  df1   df2   df3
FALSE FALSE  TRUE

If you want to check if any particular column has a TRUE value, use:
sapply(mylist, sapply, any)

           df1   df2   df3
column11 FALSE FALSE FALSE
column12 FALSE FALSE  TRUE


Q:

Setting up a Raspberry Pi

I have just started trying to set up my new Raspberry Pi. I have installed NOOBS and it is now asking which operating system I would like to use. It is recommending 'raspbian'. could anybody tell me why raspbian is the best one to use?

A:

Raspbian is perfect for beginners to the raspberry pi.

It is easy to set-up and use
There is lots of support available on-line for it, as most people are using it.
It is based on Debian which is a widley used OS.
It is specifically designed to run on the raspberry pi.

However it all depends on what you want to use your Pi for, raspbian is great for general use. But if you were looking to do something more specific, like set up a media centre you might want to use RaspBMC


Q:

Change of variable for logistic distribution to loglogistic - where do I go wrong?

Similar to what I described in this post I would like to make the following change of variable $$Y := \exp( \eta + \sigma e ), \sigma>0 $$ where $e$ has the standard logistic density $f_E(e) = \exp(e)/(1+\exp(e))^2$. Note that this equation is invariant to a change of $\exp(e)$ by $\exp(-e)$ in denominator and numerator.
Density of $Y$, i.e. $f_Y(y)$, should be log-logistic. To derive this I make a change of variables with $$g(y) = \exp( \eta + \sigma y )$$ so that $$g^{-1}(y) = (\ln(y)-\eta)/\sigma.$$ Furthermore we have $$\frac{d}{dy} g^{-1}(y) = (y\sigma)^{-1}. $$ Then applying $$f_Y(y)=f_E(g^{-1}(y))|\frac{d}{dy}g^{-1}(y)|$$
we find $$f_Y(y)= \frac{\exp( (\ln(y) - \eta)/\sigma )}{(1+\exp( (\ln(y) - \eta)/\sigma ))^2}(y\sigma)^{-1}.$$
Now the density of the log-logistic distribution is given by $$f_Y(y)= \frac{y^{\gamma-1} \lambda^\gamma \gamma}{(1+(y\lambda)^\gamma)^2},$$
if we re-apramerterize $\gamma=\frac{1}{\sigma }$ and $\lambda=\exp{-\eta}$. However, from simulations I find that this is false and I have to use $\lambda=\exp{\eta}$ instead. I paste the code to reproduce this result below. Where do I go wrong?
library(actuar)
# Hard coded random draw from the logistic distribution
qlog = function(p) log(p)-log(1-p)
rlog = function(n){
  u = runif(n)
  qlog(u)
}

# Sample some data
n = 10^6
eta = 2
sig = 1/3
y = exp( eta + sig * rlog(n))

# Make reparametrization
gamma = 1/ sig
lambda1 = exp(-eta) #what I find in my derivation, red curve
lambda2 = exp(eta) # What seems to be correct
#

# Plot densities
plot(density(y, from=0, to = 50), xlim=c(0,50))
curve(dllogis(x, shape = gamma, scale= lambda1 ) , add=T, col=2)
curve(dllogis(x, shape = gamma, scale= lambda2 ) , add=T, col=3)

A:

In the log-logistic density defined by :
$$f_Y(y)=\frac{y^{\gamma−1}\lambda^\gamma\gamma}{{ (1 + (\lambda y)^\gamma)}^2},$$
$\lambda$ corresponds to a rate parameter, whereas in your call of the function:
dllogis(x, shape = gamma, scale= lambda1 )
you pass it as a scale. there is a inverse relation between the two, so you should call dllogis(x, shape = gamma, scale= 1 / lambda1 ). I think your derivation is correct.


Q:

Clearing input within React Component from a parent or grandparent Component

I'm have a filter form within my app that has normal input fields as well as a date range input (AirBnb's react-dates plugin). On submitting the filter form, I'd like the form to clear all fields. However, I haven't been able to find a way to access the fields within the react-dates component, since it is a child component.
So far, I have tried placing a "ref" on the Component as follows:
    <DateRangePickerWrapper ref="daterange"/>

And then selecting the ref through the following function:
filterButton(data,e){

    let refs = this.refs

    for(const key in refs){

      if(!(key === "daterange")){
         refs[key].value = ""
       }else{
         console.log(this.refs["daterange"])

       }
    }
}

However- I receive a "Connect" object upon log instead of the actual Component since I am using Redux.:
Connect {props: {…}, context: {…}, refs: {…}, updater: {…}, version: 15, …}

I tried adding the "forwardRef" option to the Component export, however- I still receive the Connect object...
export default connect(mapStateToProps, { forwardRef: true})(DateRangePickerWrapper);

If there is an easier way to reset the input besides going through the Components, I am more than happy to change to that method instead..
Thanks for your time!

A:

From the react-dates README.md that you linked to in your question:
<DateRangePicker
  startDate={this.state.startDate} // momentPropTypes.momentObj or null,
  endDate={this.state.endDate} // momentPropTypes.momentObj or null,
  // ... more props...
/>

The props startDate and endDate accept null as a value, which has the effect of clearing the selected dates.


Q:

What is the equivalent of blue screen of death in linux?

Will the computer just freeze or will it display a error message like BSoD?

A:

Its called a kernel panic. Linux usually doesn't get kernel panic because it is very good at handling hardware (What led you to ask this question). In some cases Linux might get kernel panics if you have malfunctioning hardware. In such cases your system will cease to work, producing an error similar to below:


Q:

C# Having trouble with a array

Keep In mind I don't have much coding experience...
I'm having problem's accessing an Array.
I'm creating the Array using a function that returns a Array here's an example:
int[] ArrayName = ReturnArray(string);

So now that ArrayName has been created it should be identical to what ReturnArray returned should it not?
Well I set a breakpoint right on :
int[] ArrayName = ReturnArray(string);

I can see that ArrayName was created properly.
Well when I try to access just 1 value of the Array like so:
print(ArrayName[0]);

It should only return the first value in the array right? well It's not!
It returns a MORE THAN ONE VALUE and the value's Don't even match what ReturnArray(string) Returned
Here is the "ReturnArray" function :
    public static int[] ReturnArray(string t)
    {
        int i,ii,;
        string ba;
        string base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        List<int> list = new List<int>();
        for (i = 0; i < t.Length;i++)
        {
            ba = t.Substring(i, 1);
            ii = base64.IndexOf(ba) * 64;
            list.Add(ii);
        }
        return list.ToArray();
    }

Added more code do to response's from comments
    private void outputLoop()
    {
        int i = 0;
            for (i = 0; i < 63; i++)
            {
                int te = lines[i].Length - 128;
                string tes = lines[i].Substring(te, 64);
                int[] ArrayName = ReturnArray(tes);
                _textlayer.DrawString(_font, ArrayName[i].ToString(), new Vector2(1100, i * 15), Color.White);
          }
    }

A:

Here's a working sample. Let's deconstruct.
static void Main( string[] args ) {
    // declare a variable and assign it to the return value of ReturnArray()
    var arr = ReturnArray( "foo" );

    // get the first value in the array
    var first = arr[0];
}

public static int[] ReturnArray( string t ) {
    int i, ii;
    string ba;
    string base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    List<int> list = new List<int>();
    for( i = 0; i < t.Length; i++ ) {
        ba = t.Substring( i, 1 );
        ii = base64.IndexOf( ba ) * 64;
        list.Add( ii );
    }
    return list.ToArray();
}

First, if you are trying to make a base 64 algorithm, it's already been done and in the framework. If you are trying to learn, that's great, but there are examples out there to go on.
ii = base64.IndexOf( ba ) * 64;

Secondly, your code does return what I would expect, i.e. an array of numbers which come from the product of IndexOf() * 64.
This little example yields 1984, 2560, 2560 for "foo" and the value at index 0 is 1984.
"AAA" yields 0, 0, 0, because IndexOf() is 0 * 64.
As you would expect, "BBB" yields 64, 64, 64, because IndexOf() returns 1, and it is multiplied by 64.
More debugging code (based on comments):
int[] arr = ReturnArray( "DADBALAMANAOAAABAYAZAaAbAcAdAeAff/BIBJBKBLBMBNBOBJBKBLBMBNBOBPf/AAABAoApAqArAsAtAuAvf/f/+4+5f/f/f/AAABf/B4B5B6DQAZAaAbAcAdAeAZAa" );

// should print "192"
System.Diagnostics.Debug.WriteLine( arr[0] );


Q:

Define vs prove Euler's formula

Mathematical Analysis by Tom Apostol (section 1.26) defines $e^{ix} \triangleq \cos x + i\sin x$. He then adds an argument for why this definition is reasonable, asserting that this is not a proof.

Why is this not a proof? Wikipedia seems to think that it counts: https://en.wikipedia.org/wiki/Euler's_formula#Using_polar_coordinates
Why define $e^z$ in the first place instead of proving it (e.g. using the standard Taylor series proof)?

Here is the relevant section of the text:

A:

You can decide what to define and what to prove. If you define $e^z$ as Apostol does, then you have to prove that it is given by its Taylor series at every point. If you define it to be given by the Taylor series, then you have to prove Euler's formula. When Apostol says that this is not a proof it is because you do not have a previous definition of the complex exponential and, of course, there is nothing you can prove about it. But you can say that he provides a proof of the fact that there is only one such function satisfying the formal differentiation rules for the exponential. If you had defined the exponential as a function satisfying those formal properties, his argument would be a proof of uniqueness of such an object and a proof of the formula.


Q:

Read logs from one process during run of some command

I have some service which produces logs in the file logs.log.
I have some other command which interacts with this service. Let's say it is some foo.sh.
What I need, is to cut and save logs from logs.log exactly during foo.sh running. In other words I need that part of service's logs when it interacts with my foo.sh (so I don't care about foo.sh's logs).
I would expect that this command will do the trick, but it continues reading the file when foo.sh has already finished:
> foo.sh | tail -f logs.log > foo_part.log

Is any nice way to perform this trick?

A:

This is made rather straightforward by sending your background processes to, well, the background:
foo.sh &
mypid=$!
tail -f /path/to/logs.log > /path/to/partial.log &
tailpid=$!
wait $mypid
kill -TERM $tailpid

$! captures the PID of the last job sent to run in the background, so we can wait on your script to finish, and then kill the tail process when we no longer need it.

A:

This version can do it too (i think):
( tail -f logs.log >foo_part.log &
foo.sh&
wait $! && kill %1 )

Note that %1 will hit the first background process in the subshell


Q:

Issue in making exe file from Visual studio c++ project which uses thrift?

I'm using apache thrift for my project. After I change my project to release and rebuild solution I got following error. What's wrong with it? How can I resolve this issue?
Error   41  error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value 'MD_DynamicRelease' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TTransportException.obj)    Project
Error   44  error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value 'MD_DynamicRelease' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TBufferTransports.obj)  Project
Error   46  error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value 'MD_DynamicRelease' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TSocket.obj)    Project
Error   48  error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value 'MD_DynamicRelease' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(Thrift.obj) Project
Error   50  error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value 'MD_DynamicRelease' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TApplicationException.obj)  Project
Error   52  error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value 'MD_DynamicRelease' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TSimpleServer.obj)  Project
Error   54  error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value 'MD_DynamicRelease' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TServerSocket.obj)  Project
Error   56  error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value 'MD_DynamicRelease' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(GetTimeOfDay.obj)   Project
Error   58  error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value 'MD_DynamicRelease' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TWinsockSingleton.obj)  Project
Error   60  error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value 'MD_DynamicRelease' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(SocketPair.obj) Project
Error   40  error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '2' doesn't match value '0' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TTransportException.obj)    Project
Error   43  error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '2' doesn't match value '0' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TBufferTransports.obj)  Project
Error   45  error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '2' doesn't match value '0' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TSocket.obj)    Project
Error   47  error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '2' doesn't match value '0' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(Thrift.obj) Project
Error   49  error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '2' doesn't match value '0' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TApplicationException.obj)  Project
Error   51  error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '2' doesn't match value '0' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TSimpleServer.obj)  Project
Error   53  error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '2' doesn't match value '0' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TServerSocket.obj)  Project
Error   55  error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '2' doesn't match value '0' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(GetTimeOfDay.obj)   Project
Error   57  error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '2' doesn't match value '0' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(TWinsockSingleton.obj)  Project
Error   59  error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '2' doesn't match value '0' in centralNodeServiceV2_constants.obj   E:\DataCollectionje_connected_4_ex\DataCollection\Project\libthrift.lib(SocketPair.obj) Project
Error   62  error LNK1319: 20 mismatches detected   E:\DataCollectionje_connected_4_ex\DataCollection\Release\Project.exe   Project

A:

The runtime library you used to compile thrift isn't the same as the one you're using to compile your exe.
This issue has been discussed before, take a look at this: Mismatch Detected for 'RuntimeLibrary'
long story short, when you're switching your project to release, you also have to use thrift in release, which doesn't seem to be your case.


Q:

Variable substitution in tcl

I'm running an incarnation of tcl 8.5 that has been embedded into another system.
That system will accept and correctly execute a command such as:
uniformDist  minAndMax  {1 10}

where uniformDist is some object to which I do not have internal visibility.
I want to be able to say something like:
set M 1000
uniformDist  minAndMax  {1 M}

but this does not work.
Nor does
    set M 1000
    uniformDist  minAndMax  {1 $M}
I tried:
u minAndMax {1 [eval $M]}

and
u minAndMax {1 [eval M]}

Neither of those works.
The error message is:

expected a real value: unable to convert from: "$M"Error: expected
  fewer arguments  [Error while parsing pair]

or

expected a real value: unable to convert from: "[eval"Error: expected
  fewer arguments  [Error while parsing pair]

What is the right way that tcl does this?

A:

Variable substitution is expressed using $ and the variable's name (such as $M or ${M}).
This doesn't work:
uniformDist  minAndMax  {1 $M}

because the braces prevent substitution: $M is just the (sub)string 'dollar, upper case m'.
This works:
uniformDist  minAndMax  [list 1 $M]

because the arguments to list will be evaluated before the list {1 1000} is returned and passed to uniformDist.
The form "1 $M" would work too, and the command substitution [set M] can be used instead of the variable substitution above.
Documentation:
Summary of Tcl language syntax


Q:

How to use a single query with a varying WHERE clause

I have a query like:
SELECT *
FROM USERS
WHERE  location1 = true

The users table has 4 columns:
location1
location2
location3
location4

In my stored procedure, I want to pass in a parameter that will tell me to use either location1, or location2 etc.
Is there a way to write my query so that I can handle this without having to re-write the same query 4 times for each where filter?
My SELECT query is a little more complicated but essentially it is the same idea.

A:

You could use some ORs to accomplish that (especially if you don't want to go the dynamic sql route).
SELECT *
FROM USERS
WHERE  ((@myLocationParameter = 'location1' AND location1 = true)
        OR (@myLocationParameter = 'location2' AND location2 = true)
        OR ....)


Q:

PIL shows "broken data stream when reading image file" in virtualenv

My python and PIL installation is from MacPorts on Snow Leopard.
When I try to open a JPG image in the system python with PIL, I don't get any errors.
$ python
>>> import Image
>>> img = Image.open("test.jpg")
>>> img2 = img.resize((1,1))
>>> # no errors!!!

However when I create a virtual environment
$ virtualenv --no-site-packages venv
$ cd venv/
$ source bin/activate
(venv) $ pip install PIL
...
(venv) $ python
>>> import Image
>>> img = Image.open("../test.jpg")
>>> img2 = img.resize((1,1))
...
IOError: broken data stream when reading image file

Here is a whole dump including the whole build of PIL.
Any ideas?

A:

Looks like this is an issue.
Generally people should not be using PIL anymore
Give Pillow a try https://pypi.python.org/pypi/Pillow/2.4.0
I am willing to bet this plays nice in the venv


Q:

How to passing the pointer parameters and return them right?

Here is my code sample:
#include <stdio.h>
#include <stdlib.h>
void foo(int size, int new_size, int * ptr1, double * ptr2) {
    int i;
    new_size = size * 2;
    ptr1 = (int *) calloc(new_size, sizeof(int));
    ptr2 = (double *) calloc(new_size, sizeof(double));

    for (i = 0; i < new_size; i++) {
        ptr1[i] = 1;
        ptr2[i] = 2;
    }
}
int main(){
    int i, size = 4, new_size = 4;
    int *ptr1 = NULL;
    double *ptr2 = NULL;

    foo(size, new_size, ptr1, ptr2);

    for (i = 0; i < new_size; i++) {
        printf("new_size: %d\n", new_size);
        printf("ptr1: %d, ptr2: %f\n", ptr1[i], ptr2[i]);
    }

    free(ptr1);
    free(ptr2);

    return 0;
}

And I have to malloc space and assign data to ptr1 and ptr2 in foo function (because I don't know the new size of them in main functin) and then use them in the main function.Why the code doesn't work? And How to implement the above process I want?

A:

You can pass the address of the pointer to the function like so:
void foo(int size, int new_size, int ** ptr1, double ** ptr2) {
    int i;
    new_size = size * 2;
    *ptr1 = (int *) calloc(new_size, sizeof(int));
    *ptr2 = (double *) calloc(new_size, sizeof(double));

    for (i = 0; i < new_size; i++) {
        (*ptr1)[i] = 1;
        (*ptr2)[i] = 2;
    }
}

and in main
foo(size, new_size, &ptr1, &ptr2);

Your code didn't work because parameter are passed by value. ptr1 and ptr2 while being pointers are still passed by values so any modification to them(compared to modification to what they point to) will not remain after the function.

A:

Pass the addresses of the pointers, modify the pointers in the functions and thats all, other that that I have a few observations on your code

Don't cast the return value of malloc(), it's not necessary in c, and it hurts your code readability.
Always check the return value of malloc() and pretty much any function that returns a value, because normally there is a special value indicating failure, and you don't want your program to misbehave under extraordinary conditions.

This is a version of your own code with the main issue addressed and also the observations above.
#include <stdio.h>
#include <stdlib.h>

int foo(int size, int new_size, int ** ptr1, double ** ptr2) {
    int        i;
    new_size = size * 2;

    *ptr1 = malloc(new_size * sizeof(int));
    *ptr2 = NULL;
    if (*ptr1 == NULL)
        return 1;

    *ptr2 = malloc(new_size * sizeof(double));
    if (*ptr2 == NULL) {
         free(*ptr1);
         return 2;
    }

    for (i = 0; i < new_size; i++) {
        (*ptr1)[i] = 1;
        (*ptr2)[i] = 2;
    }

    return 0;
}

int main() {
    int i, size = 4, new_size = 4;
    int    *ptr1 = NULL;
    double *ptr2 = NULL;

    if (foo(size, new_size, &ptr1, &ptr2) != 0)
        return -1;
    for (i = 0; i < new_size; i++) {
        printf("new_size: %d\n", new_size);
        printf("ptr1: %d, ptr2: %f\n", ptr1[i], ptr2[i]);
    }

    free(ptr1);
    free(ptr2);

    return 0;
}

In c you always pass parameters by value, it might be confusing because you are passing a pointer, but a pointer is just another variable which stores a memory address, that address is changing inside the foo() function but it's only being written into the local pointer ptr1.
Passing the address writes the value to the original pointer in main().


Q:

Can return only be used once in a block of code?

I'm in the process of learning python, and I can't wrap my head around a piece of code in the book:
def find_value(List, value):

    for i in range(len(List)):
        if List[i] == value:
            return i

    return -1

I've tried running the code, and it returns the index if the value is in it, and returns -1 if it isn't, but what I don't understand is since the 'return -1' is outside the for loop, and if statement, should it not be run every time the code is executed?
Or does return only get processed once, the first time it is called?
I just want to make sure I understand this concept before moving on.
Thanks in advance

A:

No, you can have as many return statements in as many places as you like:
def function():
    ... # do something
    return 1
    return
    return [3, 4, 5]
    return next(__import__('os').walk('.'))[-1:-1000000000:-1]

Though the important thing to keep in mind that only the first return that your function encounters will count, and anything else that would've succeeded it is not touched.
In the function above, you'll get 1 as the result and nothing else.
This sort of "flow of control" is why you can even do weird stuff like this -
def foo():
    return True
    whatIsThisIdontEven__somethingWeird.jpg  # would ordinarily throw RuntimeErrors anywhere else

print(foo())
# True

In your case, it entirely depends on your code flow at runtime, but you'll still end up encountering only one return, and consequently returning only once.
Note that one difference is in the case of try-except-finally, where the return in the final clause always wins.
def function():
    try:
        ... # do something
        return 1
    except SomeException:
        ... # do something else
    finally:
        return 2

In the case of normal execution, you'll encounter return 1 in try, but because of the semantics of the finally clause, you'd still end up returning 2. I believe this is the only exception.
Now, yield, on the other hand, is a different matter...


Q:

string interpolation in angular 2 and it's dynamicity

In Angular2, why if i put a property in a simple view, like this:
<span>{{allowServer}}</span>

it change whenever its value change on its .ts file, and if i put it like this:
<button class="btn btn-primary" disabled={{allowServer}} >server</button>

the button doesn't get the new value disabled?
So, what is the rule for which I have to use interpolation instead of binding syntax?
[disabled]=allowServer

A:

[prop]="value"
is for object binding to properties (@Input() of an Angular component or directive or a property of a DOM element).
prop="{{value}}"
binds a value to a property. The value is stringified (aka interpolation)
See lets look at an example:
<button id="button1" disabled={{allowServer}} >server</button>
<button id="button2" [disabled]={{allowServer}} >server</button>

1) allowServer === true
button1.disabled = 'true' // string

button2.disabled = true   // boolean

2) allowServer === false
button1.disabled = 'false' // string so disabled is true

button2.disabled = false// boolean

As you can see button1 will always be disabled


Q:

Merge figures and graphics tags

The tags figures and graphics have the same description on their infotab. Although the tag-info of figures mentions that graphics is a synonym, they are actually not listed as synonyms. So far, I cannot see a real difference between questions tagged with graphics and figures. Therefore, I would suggest to merge the tags figures and graphics.
But I cannot yet suggest tag-synonyms or mergers with my few points.

A:

I don't believe retagging is the way to go here. Not only does it flood the front page, but it hides the problem that figures and graphics are synonyms. I also don't have the required reputation. That said, even if I did, tag synonyms are not really being voted on so nothing is would actually change.


Q:

Why is "while (rs.next())" necessary here?

I want to select the maximum line number from my database "Logs" and store it in a variable m.
Here's my code:
ResultSet rs = stmt.executeQuery("Select max(Line) as L from logs");

while (rs.next()) {          // Why do I need this
    int m = rs.getInt("L");
    System.out.println(m);
}

But it doesn't work unless I use while(rs.next()).

If I understand correctly, rs.next() moves the cursor to the next row, but  here, in this result, I only have one row.
So, can someone explain why the loop is necessary? The only thing I can think of is that the first cursor is set on the column name, am I right?

A:

Why?
The cursor is initially placed before the first element. You need to advance it once to access the first element.
This was obviously done because traversing the results using a loop is very convenient then, as you see. From the official documentation:

Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

Solution
So, while you don't need any loop, you need to advance the cursor once. A single rs.next(); would technically be enough:
rs.next();
// Access the result

However, you probably want to account for the case where there was no match at all, since:

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.

So the code would fail in this case.
Because of that, you should account for the case and use the returned boolean to guard your access:
if (rs.next()) {
    // Access result ...
} else {
    // No match ...
}

A:

From the official documentation (which you should have read btw):

Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

You basically need to move it, in your case moving it once is enough:
 rs.next();
 System.out.println(rs.getInt("L"));

A:

You can convert this to use a simple if statement instead.
if(rs.next()) {
    // other code here
}

You would use while when you have more than one row to bring back.


Q:

Excuir Repositorio GitLab de apenas um Computador

Preciso deletar os arquivos baixados de um repositório de apenas um membro autorizado remotamente, para o mesmo não ter mais acesso ao projeto, é possivel?

A:

Infelizmente, como os dados estão registrados localmente, você só conseguiria excluir tendo acesso ao computador dele.


Q:

How can I use different hrefs in my fancybox call?

I have the following fancybox call:
  $(document).ready(function() {
        $('.fancybox').fancybox({
            'closeClick'  : false,
            'scrolling'   : 'no',
             afterShow: function(){
            //do some stuff
             }
        });
    });

for influence on the following:

what I would like to do is add the href to the fancybox call so that I can simply put a hash tag in the href in the html.
  $(document).ready(function() {
        $('.fancybox').fancybox({
            'closeClick'  : false,
            'scrolling'   : 'no',
                'href'        : 'example_url',
             afterShow: function(){
            //do some stuff
             }
        });
    });

But I need to take it a bit further. Lets say I have three different items to consider:
 //requires url-1
 //requires url-2
 //requires url-3

I know I need to give each one some type of unique identifier. Further, I realize I could just make three different fancybox calls for each one, but I think the better way to do it would be something like this:
  $(document).ready(function() {
        $('.fancybox').fancybox({
                //do some processing here to find out what triggered the fancybox, then set a variable with the proper href based on that input. Could have a switch statement etc
            'closeClick'  : false,
            'scrolling'   : 'no',
                'href'        : //variable holding proper url
             afterShow: function(){
            //do some stuff
             }
        });
    });

But I am having trouble making it actually happen how I envision!

A:

EDIT: I should say that my example is using Fancybox 2, it will probably not work in the earlier versions
You can have the links carry a data-href attribute, which you can use in the fancybox call like this (fiddle: http://jsfiddle.net/xEtZ8/)
URL 1

URL 2

And JS
$(function() {
    $('.fancybox').fancybox({
        type: 'iframe',
        beforeLoad: function() {
            this.href = this.element.data('href');
        }
    });
});


Q:

Plist and Cache path

According Mac App Store rules 2.30:
"Program may write only to allowed locations."
My app (com.SomeApp) contains bundled app with own ID (com.SomeHelper).
This helper app, unfortunately, can write own preferences (~/Library/Preferences/com.SomeHelper.plist) and cache files (~/Library/Caches/com.SomeHelper).
Reviewers rejected entire app! There is no way to discuss about this stupid rule.
Developer can register only one ID for MAS app in iTC, and I can't use the same ID for bundled apps (to prevent conflicts and pass iTC meta-information validation).
Cache file generated by network services (on URL requests).
How to solve this puzzle?
Is there a way to disable plist and cache at all?
Or maybe there is a way to change location for preferences and cache file?
Is there a better solution?

A:

Here is my final solution (partially in pseudocode, sorry):
// in the helper's main.m:
@implementation NSUserDefaults (Forwarder)

-(void)setObject:(id)value forKey:(NSString *)defaultName
{
[[MainAppServer sharedPrefsServer]/* some IPC to parent process*/ setObject:value forKey:defaultName];// I still use distributed objects available before sandboxing rules, next we can use XPC, I hope…
}

@end

int main(int argc,char* argv[])
{
…

NSAutoreleasePool * arp = [NSAutoreleasePool new];
[NSURLCache setSharedURLCache:[[[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:@"/dev/null"] autorelease]];
[[NSUserDefaults standardUserDefaults] addSuiteNamed:@"your.main.app.plist-domain.here"];
[arp drain];
…
return NSApplicationMain(argc,  (const char **) argv);
}

Summary:

We disabled cache
We made user defaults read via suite, and write via forwarding by some IPC way…

I checked - no cache and plist files are producing now.
The puzzle is solved!


Q:

How to replace src attribute name with data attribute name

I have a html document which uses object tag with src attribute. But I need to replace src(attribute name) with "data" (attribute name).
Is it possible to do so using JavaScript?
All I referred shows that we can change the attribute values, but I couldnt find any method to replace attribute node name.
Could someone please help

A:

You will have to get the src attribute value and set that to the data attribute value.
You can use .removeAttribute() if you want to get rid of the src attributes.
Something like this:
var att = element.getAttribute("src");
element.setAttribute("data", att);
element.removeAttribute("src");

jsFiddle example

If you want to do a bunch of elements, just select them and do a for loop. For example going over all divs:
var att, i, elie = document.getElementsByTagName("div");

for (i = 0; i < elie.length; ++i)
{
    att = elie[i].getAttribute("src");
    elie[i].setAttribute("data", att);
    elie[i].removeAttribute("src");
}

jsFiddle example

.getAttribute()
.removeAttribute()
.setAttribute()


Q:

Microservices async operation HTTP response

We're building a microservice app where clients can create projects. The following diagram shows the technical flow of this process:

My question: what HTTP response should the API gateway return to the client (step 1.)?
My initial idea was to give back a 202, but the problem there is that I don't know the Location yet (/projects/{id}), because the id of the project will be created at the Project Management Service.

A:

Considering that the IDs of the newly created project entity is not known at the request time (i.e. it is generated after the insertion into the database) you indeed cannot generate the url to the project resource.
Instead, you could assign an ID (i.e. 1234-abcd-5678-efgh) to the command before sending to the bus and keep track of its execution status on the API gateway itself. Then you can respond to the client with an command execution status endpoint like /commands/1234-abcd-5678-efgh where it can query by polling.
The alternative would be to use another service that would reserve&deliver unique IDs but you must make a blocking call to it and this hurts scalability. Or you can host this service inside the API gateway itself (onto the same node) to minimize latency. Also, there is a risk of loosing some IDs in case of project creation failures but this can be compensated by releasing those IDs in those situations (thus increasing the architecture complexity).
A third solution could be the use of a project surogate ID, like a GUID, assigned as a property of the project, included in the command, having the purpose of an alternate  identity that can be used only in the pre-creation phase of the process. Then, the response to the client could be like this: /projects/by-guid/1234-abcd-5678-efgh and after the project is created a GET to this url would permanently redirect to the final project url.


Q:

Unarchive a file into specific directory

Running the command, I end up with the file being in /home/user/Documents/home/user/Documents/.
tar -xzvf /tmp/file.tar.gz -C /home/user/Documents/

A:

This is happening because you have use absolute paths while creating the archive, and as you are using -C to do chdir(2) before unarchiving, you will get the absolute paths starting from where you have chdir(2)-ed.
Now, you have two options if you want to use -C:

Use relative paths while creating the archive, and then you can use -C like you have used while unarchiving:
tar -xzvf /tmp/file.tar.gz -C /home/user/Documents/

pick the destination carefully to make sure it does not have the possibility of overwriting anything existing.
Change the directory to /, and use the absolute paths while archiving, and again of course choose the chdir(2) path very carefully in this case as this could replace any existing file:
 tar -xzvf /tmp/file.tar.gz -C /

based on your example, this will put the file(s) in /home/user/Documents/.


Q:

What is the equivalent to a Matlab cell array?

I am new to Python and trying to create something equivalent to Matlab's "cell array". Lets say I have 100 customers index 'C001', 'C002' etc. and I have different data for each customer:

Size of premises in square meters [real number]
categorical data showing whether they are 'commercial', 'residential' or 'other'
hourly time series of their electricity consumption in 2014 i.e. datetime-indexed array of 8760 real values

What is the best way to buildsuch a dataset in Python 2.7 that combines single values, categorical data and time-index arrays? I am trying to use pandas for this but no success so far.
Thank you very much in advance

A:

The equivalent of a MATLAB cell array is a numpy object array.  However, these are rarely used because they are rarely what you want in practice.  In most cases where someone would use a Cell in MATLAB, a list or nested list would suffice:
>>> a = [obj1, obj2, obj, obj4]
>>> b = [[obj1, obj2], [obj3, obj4]]

However, that is not what you want to do in your case.  Your question is a classic example of X Y problem.  You are asking how implement a particular solution to your problem, rather than asking how to solve the problem itself.  Python can do a lot of things MATLAB can't, so trying to make Python behave like MATLAB will often result in sub-optimal solutions.
In this case, what you want is a pandas DataFrame.  It is nothing at all like a MATLAB cell array, but fits your data set much better.  You can use a MultiIndex to store the parameters, and columns to store the time series data.  This allows you to index by name, size, category, date, etc.  You can calculate, for example, the mean energy usage for each category of property in the third quarter for properties over 500 square meters in just one line of code.
So here is an example how you could structure such data:
>>> names = ['C001', 'C002', 'C003', 'C004']
>>> sizes = np.abs(np.random.random(4))*1000
>>> category = ['Commerical', 'Residential', 'Residential', 'Other']
>>> ts = np.random.random([100, 4])
>>> timestamps = pd.date_range('1/1/2011', periods=100, freq='W')
>>>
>>> cols = pd.MultiIndex.from_arrays([names, sizes, category])
>>>
>>> df = pd.DataFrame(ts, index=timestamps, columns=cols)
>>> df.columns.names = ['Name', 'Size', 'Category']
>>> df.index.name = 'Time'
>>>
>>> print(df)
Name             C001        C002        C003       C004
Size       36.719201   732.278278  795.755755 551.383120
Category   Commerical Residential Residential      Other
Time
2011-01-02   0.108720    0.018492    0.057233   0.694548
2011-01-09   0.959845    0.968857    0.422210   0.975767
2011-01-16   0.709676    0.119963    0.004481   0.830328
2011-01-23   0.084271    0.535408    0.209943   0.668001
2011-01-30   0.626125    0.052301    0.212636   0.995429
2011-02-06   0.376399    0.199327    0.482884   0.632472
2011-02-13   0.302807    0.353679    0.599427   0.993996
2011-02-20   0.185445    0.005769    0.755981   0.923540
2011-02-27   0.109611    0.994292    0.873782   0.542741
2011-03-06   0.561404    0.778414    0.595238   0.082001
2011-03-13   0.056986    0.869344    0.459753   0.450071
2011-03-20   0.261320    0.675317    0.603043   0.371950
2011-03-27   0.890803    0.061619    0.831677   0.801890
2011-04-03   0.498199    0.846559    0.370336   0.225477
2011-04-10   0.248914    0.693038    0.145255   0.233058
2011-04-17   0.621441    0.683213    0.048944   0.650139
2011-04-24   0.459869    0.055751    0.912097   0.457605
2011-05-01   0.814447    0.780415    0.184241   0.429139
2011-05-08   0.586905    0.209121    0.428080   0.246584
2011-05-15   0.754021    0.909181    0.846984   0.948835
2011-05-22   0.513610    0.203925    0.338072   0.596325
2011-05-29   0.497080    0.557908    0.916812   0.680242
2011-06-05   0.646791    0.641024    0.399427   0.308346
2011-06-12   0.573922    0.539285    0.098703   0.461480
2011-06-19   0.062978    0.939339    0.713087   0.380326
2011-06-26   0.422484    0.109185    0.459734   0.800468
2011-07-03   0.962368    0.632361    0.388565   0.503425
2011-07-10   0.802551    0.261161    0.590494   0.526307
2011-07-17   0.261447    0.686405    0.636970   0.622476
2011-07-24   0.634331    0.630028    0.069925   0.504036
...               ...         ...         ...        ...
2012-05-06   0.185331    0.375717    0.658463   0.697377
2012-05-13   0.273510    0.665318    0.756944   0.083542
2012-05-20   0.895984    0.850881    0.680869   0.987420
2012-05-27   0.450593    0.262195    0.458893   0.199141
2012-06-03   0.696102    0.332312    0.419764   0.338074
2012-06-10   0.113108    0.167605    0.812625   0.329429
2012-06-17   0.527418    0.087454    0.868973   0.744649
2012-06-24   0.977674    0.831538    0.410719   0.598423
2012-07-01   0.577802    0.141307    0.310356   0.276271
2012-07-08   0.772117    0.288240    0.820701   0.548857
2012-07-15   0.699628    0.467952    0.429433   0.304482
2012-07-22   0.782641    0.337854    0.561191   0.572241
2012-07-29   0.010225    0.962770    0.793041   0.166877
2012-08-05   0.895516    0.628526    0.782264   0.908301
2012-08-12   0.787210    0.698185    0.255306   0.741693
2012-08-19   0.042833    0.556469    0.165885   0.408108
2012-08-26   0.942076    0.377714    0.927170   0.119004
2012-09-02   0.567978    0.007891    0.777752   0.869950
2012-09-09   0.120134    0.417996    0.328654   0.484447
2012-09-16   0.833769    0.946456    0.594471   0.569707
2012-09-23   0.515544    0.090017    0.344200   0.498175
2012-09-30   0.419152    0.315412    0.683195   0.498630
2012-10-07   0.879582    0.958591    0.531812   0.051948
2012-10-14   0.488241    0.683242    0.096560   0.197295
2012-10-21   0.425213    0.279539    0.476436   0.492512
2012-10-28   0.238334    0.836782    0.901589   0.132700
2012-11-04   0.030562    0.797666    0.238895   0.550427
2012-11-11   0.875454    0.973046    0.457116   0.154175
2012-11-18   0.557967    0.895320    0.478239   0.448102
2012-11-25   0.075152    0.047344    0.650615   0.293129

[100 rows x 4 columns]


Q:

Printing a Project in NetBeans

I have an exam and I would like to print my Java (in NetBeans project) files as fast as possible. I was wondering is there a way to print an entire project/project in NetBeans with one click? or do you have a better suggestion? (I will be using Windows XP and there is no nice editor like Gedit or Kate installed)

A:

Give that the identical question on the netbeans forum from last year is not answered yet, I would say no.
When I needed to print off my final year Comp Sc project (needed to hand in a full print out + polished install CD, oh the poor trees that died for that one...), I opened every file then went through and did a print & close on each one. :(


Q:

TabControl winform c#

Does anyone know why my tabcontrol will not display on this form? Have a feeling it maybe something simple but at the moment i just get a blank form.
Thanks
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace test_project_3
{
    public partial class TabTest : Form
    {
        public TabTest()
        {
            InitializeComponent();

            WebBrowser WB = new WebBrowser();
            WB.Navigate("www.google.com");

            TabControl tc = new TabControl();
            tc.Dock = DockStyle.Fill;
            tc.Show();

            TabPage tp = new TabPage();
            tp.Text = "test";
            tp.Show();
            tp.Controls.Add(WB);

            tc.TabPages.Add(tp);
        }
    }
}

A:

You need to add the TabControl to the Controls collection:
this.Controls.Add(tc);


Q:

Can't find resource identifiers from AAR in XML

I developed a custom Preference for an application.  It has two custom attributes.  I'm trying to move the Preference to a library project to reuse in other projects.  I moved the Java file along with the corresponding layout and attr XML files.  Here's the attr file in the library project:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="NumberPickerPreference" >
        <attr name="minValue" format="integer" />
        <attr name="maxValue" format="integer" />
    </declare-styleable>
</resources>

Here's the manifest:
<manifest package="com.mydomain.androiduilibrary">
</manifest>

An odd-looking manifest for sure.  When I generated the library project the only thing Android Studio put in the manifest was the SDK info, which then generated a warning about it already being specified in the build.gradle file, so I deleted the entry in the manifest.
I generate the AAR file using the bundleRelease task and get a file named androiduilibrary-release.aar.  I then go to the project that needs to use this Preference and select "New Module | Import .JAR or .AAR Package", navigate to the AAR, and it's now in my project as a module entitled androiduilibrary-release.  I make a module dependency in the Project Structure dialog, and can now reference the Preference in Java code.  So far, so good.
However, when I attempt to reference the Preference in XML, I get the following error on my custom attributes:  "Error:(9) No resource identifier found for attribute 'minValue' in package 'com.mydomain.androiduilibrary'".  Here's the XML:
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:title="@string/location_service_settings_preference_header_title"
    xmlns:custom="http://schemas.android.com/apk/res/com.mydomain.androiduilibrary">

<com.mydomain.androiduilibrary.NumberPickerPreference
    android:title="@string/update_interval_preference_title"
    android:key="@string/update_interval_preference_key"
    android:defaultValue="@integer/update_interval_preference_default"
    android:summary="@string/update_interval_preference_summary"
    custom:minValue="@integer/update_interval_preference_min"
    custom:maxValue="@integer/update_interval_preference_max"
    android:dialogMessage="@string/update_interval_preference_dialog_message"
    android:dialogTitle="@string/update_interval_preference_title" />

I can look inside the AAR and see that the values are populating in R.txt:
int attr maxValue 0x7f010001
int attr minValue 0x7f010000

And that its manifest is being created correctly:
<?xml version="1.0" encoding="UTF-8"?>

<manifest android:versionName="1.0" android:versionCode="1"
    xmlns:android="http://schemas.android.com/apk/res/android" package="com.mydomain.androiduilibrary">

    <uses-sdk android:targetSdkVersion="21" android:minSdkVersion="11"/>

</manifest>

I also get a warning when calling out the custom preference:  "Element com.mydomain.androiduilibrary.NumberPickerPreference is not allowed here" so I'm guessing that will be a problem too.
Is there a step I'm missing that will allow me to reference elements from the AAR in my XML?  I'm using Android Studio 1.0.2.  Thanks in advance.

A:

Solved it from this post, down at the bottom where it talks about external libraries.  Essentially, when referencing AAR elements in code you do so using the package specified in the AAR's manifest, but when referencing AAR elements in XML you cite the namespace of the project (not the AAR).


Q:

Optimizing cohort analysis on Google BigQuery

I'm attempting to perform a cohort analysis on a very large table. I have a test table with ~30M rows (over double in production). The query fails in BigQuery stating "resources exceeded.." and it's a tier 18 query (tier 1 is $5, so it's a $90 query!)
The query:
with cohort_active_user_count as (
  select
    DATE(`BQ_TABLE`.created_at, '-05:00') as created_at,
    count(distinct`BQ_TABLE`.bot_user_id) as count,
    `BQ_TABLE`.bot_id as bot_id
  from `BQ_TABLE`
  group by created_at, bot_id
)

select created_at, period as period,
  active_users, retained_users, retention, bot_id
from (
  select
    DATE(`BQ_TABLE`.created_at, '-05:00') as created_at,
    DATE_DIFF(DATE(future_message.created_at, '-05:00'), DATE(`BQ_TABLE`.created_at, '-05:00'), DAY) as period,
    max(cohort_size.count) as active_users, -- all equal in group
    count(distinct future_message.bot_user_id) as retained_users,
    count(distinct future_message.bot_user_id) / max(cohort_size.count) as retention,
    `BQ_TABLE`.bot_id as bot_id
  from `BQ_TABLE`
  left join `BQ_TABLE` as future_message on
    `BQ_TABLE`.bot_user_id = future_message.bot_user_id
    and `BQ_TABLE`.created_at < future_message.created_at
    and TIMESTAMP_ADD(`BQ_TABLE`.created_at, interval 720 HOUR) >= future_message.created_at
    and `BQ_TABLE`.bot_id = future_message.bot_id
  left join cohort_active_user_count as cohort_size on
    DATE(`BQ_TABLE`.created_at, '-05:00') = cohort_size.created_at
    and `BQ_TABLE`.bot_id = cohort_size.bot_id
  group by 1, 2, bot_id) t
where period is not null
and bot_id = 80
order by created_at, period, bot_id

Here is the desired output:

From my understanding of BigQuery, the joins are causing a major performance hit because each BigQuery node needs to process them. The table is partitioned by day, which I'm not yet making use of in this query, but I know it will still need to be optimized.
How can this query be optimized or exclude the use of joins to allow BigQuery to process more efficiently in parallel?

A:

Step #1

Try below
Moved JOIN'ing on cohort_active_user_count outside the inner SELECT as I think it is one of main reason for query be expensive. And as you see - using JOIN instead LEFT JOIN for this one as LEFT is not needed here
Please test and let us know result
WITH cohort_active_user_count AS (
  SELECT
    DATE(BQ_TABLE.created_at, '-05:00') AS created_at,
    COUNT(DISTINCT BQ_TABLE.bot_user_id) AS COUNT,
    BQ_TABLE.bot_id AS bot_id
  FROM BQ_TABLE
  GROUP BY created_at, bot_id
)
SELECT t.created_at, period AS period,
  cohort_size.count AS active_users, retained_users,
  retained_users / cohort_size.count AS retention, t.bot_id
FROM (
  SELECT
    DATE(BQ_TABLE.created_at, '-05:00') AS created_at,
    DATE_DIFF(DATE(future_message.created_at, '-05:00'), DATE(BQ_TABLE.created_at, '-05:00'), DAY) AS period,
    COUNT(DISTINCT future_message.bot_user_id) AS retained_users,
    BQ_TABLE.bot_id AS bot_id
  FROM BQ_TABLE
  LEFT JOIN BQ_TABLE AS future_message
    ON BQ_TABLE.bot_user_id = future_message.bot_user_id
    AND BQ_TABLE.created_at < future_message.created_at
    AND TIMESTAMP_ADD(BQ_TABLE.created_at, interval 720 HOUR) >= future_message.created_at
    AND BQ_TABLE.bot_id = future_message.bot_id
  GROUP BY 1, 2, bot_id
  HAVING period IS NOT NULL
) t
JOIN cohort_active_user_count AS cohort_size
  ON t.created_at = cohort_size.created_at
  AND t.bot_id = cohort_size.bot_id
WHERE t.bot_id = 80
ORDER BY created_at, period, bot_id

Step # 2

Below "further optimization" is based on assumption that your BQ_TABLE is a raw data with multiple entries for the same user_id/bit_id for the same day - thus increasing a lot expenses of LEFT JOIN in inner SELECT.
I propose first to aggregate this, as it is done below. In addition to drastically reducing size of JOIN - it also eliminates all those conversion from TIMESTAMP to DATE in each join'ed row
WITH BQ_TABLE_AGG AS (
  SELECT bot_id, bot_user_id, DATE(BQ_TABLE.created_at, '-05:00') AS created_at
  FROM BQ_TABLE
  GROUP BY 1, 2, 3
),
cohort_active_user_count AS (
  SELECT
    created_at,
    COUNT(DISTINCT bot_user_id) AS COUNT,
    bot_id AS bot_id
  FROM BQ_TABLE_AGG
  GROUP BY created_at, bot_id
)
SELECT t.created_at, period AS period,
  cohort_size.count AS active_users, retained_users,
  retained_users / cohort_size.count AS retention, t.bot_id
FROM (
  SELECT
    BQ_TABLE_AGG.created_at AS created_at,
    DATE_DIFF(future_message.created_at, BQ_TABLE_AGG.created_at, DAY) AS period,
    COUNT(DISTINCT future_message.bot_user_id) AS retained_users,
    BQ_TABLE_AGG.bot_id AS bot_id
  FROM BQ_TABLE_AGG
  LEFT JOIN BQ_TABLE_AGG AS future_message
    ON BQ_TABLE_AGG.bot_user_id = future_message.bot_user_id
    AND BQ_TABLE_AGG.created_at < future_message.created_at
    AND DATE_ADD(BQ_TABLE_AGG.created_at, INTERVAL 30 DAY) >= future_message.created_at
    AND BQ_TABLE_AGG.bot_id = future_message.bot_id
  GROUP BY 1, 2, bot_id
  HAVING period IS NOT NULL
) t
JOIN cohort_active_user_count AS cohort_size
  ON t.created_at = cohort_size.created_at
  AND t.bot_id = cohort_size.bot_id
WHERE t.bot_id = 80
ORDER BY created_at, period, bot_id


Q:

Find last login datetime for SQL Server login

Is it possible to get a timestamp for the last login for a given ID in SQL Server?
I'm attempting to clean up security on a SQL Server 2000 installation and what I'd like to do is just delete all the non-active logins.

A:

This information is not stored anywhere in SQL Server.  You would have to run a server side trace for the Audit Login/Logout events and then scan the files over time to determine if a login is being used or not.
You could also do this if you have Login auditing for successful logins enabled, but even with auditing enabled you will only be able to go back as far as your SQL errorlogs go. Additionally, you could write a job to write the signed in users to a table.


Q:

how to join the threads with the main function

hey i am able to create threads but its not joining with the main...the program is not executing the third for loop..ie. the thread joining part...any help would be appreciated
here is my code:
for(i=0;i<N/2;i++) {
    pthread_create (&thread[i], NULL, thread_sort, (void *) &data[i]);
}
for(i=0;i<N/2;i++) {
    if( pthread_create (&thread[i], NULL,thread_sort, (void *) &data[i])<0) {
        cout<<"\n Error in creation of threads.....!!!!!!!!";
    }
    else {
        cout<<"Thread "<<i<<"is Created"<<endl;
    }
}

for(i=0;i<N/2;i++) {
    pthread_join(thread[i],NULL);
    if (pthread_join(thread[i],NULL)<0) {
        cout<<"\n Error in joining Threads";
    }
}

A:

for(i=0;i<N/2;i++) {
    pthread_join(thread[i],NULL);
    if (pthread_join(thread[i],NULL)<0) {
        cout<<"\n Error in joining Threads";
    }
}

You are attempting to join the thread twice here, you should take out the first pthread_join, IE:
for(i=0;i<N/2;i++) {
    if (pthread_join(thread[i],NULL)<0) {
        cout<<"\n Error in joining Threads";
    }
}

Also, are error values negative?  The documentation I am finding says "non-zero," so I'm wondering if that should be pthread_join(thread[i],NULL)!=0 instead.
EDIT:  Try taking out your first loop as well, it ends up calling pthread_create twice on the same objects.


Q:

How to create a UITableCell that has multiple subtitles

I came across this design image online and I am really puzzled on how could I make a UITableCell that has multiple subtitles and allows me to customised them in the way shown by the picture.
My understanding is that one can only use 1 subtitle per cell.
Is there a way to create a UITable cell that looks like that? How would you go on to make those 4 subtitles under the cell title???

A:

You could do that easily by having a custom layout for the UITableViewCell. This video should help you in doing this:
http://www.youtube.com/watch?v=d_kO-J3DYvc
Basically you will need to design the UI of the cell in storyboard/NIB file and add multiple labels to your table cell there. Sub-class UITableViewCell and link it to the designed UITableViewCell in storyboard/NIB. Addd IBOulets in that class for the labels and link your labels from the UI to these IBOutlets.


Q:

Chemfig: reaction mechanism problem: arrow position

Hello everybody.
 As you all can see the curved arrow doesn't point to the positive carbon as it should, but it kink of turn around the bond.
How can I solve this?
Thanks in advance for any answer!
\schemestart
\chemfig{@{a2}C^{\oplus}(-[:90]CH_3)(-[:180]CH_3)(-[:270]CH_3)}\chemfig{\+ @{a1}Cl^{\ominus}}\arrow{<=>}\chemfig{C(-[:0]Cl)(-[:90]CH_3)(-[:180]CH_3)(-[:270]CH_3)}
\schemestop
\chemmove{\draw(a1)..  controls +(100:5mm) and +(145:5mm)..  (a2);}

A:

You should write instead
\schemestart
\chemfig{@{a2}C^{\oplus}(-[:90]CH_3)(-[:180]CH_3)(-[:270]CH_3)}\chemfig{\+ @{a1}Cl^{\ominus}}
\arrow{<=>}\chemfig{C(-[:0]Cl)(-[:90]CH_3)(-[:180]CH_3)(-[:270]CH_3)}
\schemestop
\chemmove{\draw(a1)..  controls +(100:5mm) and +(45:5mm)..  (a2);}


Q:

Publishing images on Facebook iOS

I am making and app that you modify images and then you could upload it to Twitter, Facebook, etc... My problem it's with Facebook. also fbDidLogin never called. I Follow allot of tutorials to this and search allot and try allot of solutions and nothing.
Because i don't know if the user will export the photo to Facebook I login it only when its necessary I leave the code. I hope someone can help me.
What I need it's to publish my image that I create into the users wall
//<FBSessionDelegate, FBDialogDelegate, FBRequestDelegate>

- (void)publishFacebook:(UIImage *)img {

    [self loginFacebook];
    NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                        img, @"picture", @"Testing...", @"caption",
                                        nil];
    [_facebook requestWithGraphPath:@"me/photos" andParams:params andHttpMethod:@"POST" andDelegate:self];
    NSLog(@"Image posted");
}

- (void)loginFacebook {

    if (_facebook == nil) {
        _facebook = [[Facebook alloc] initWithAppId:kAppId andDelegate:self];
    }

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"] && [defaults objectForKey:@"FBExpirationDateKey"]) {
        _facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
        _facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
    }

    if (![_facebook isSessionValid]) {
        NSArray *permissions =  [NSArray arrayWithObjects:@"email", @"offline_access", @"publish_stream", nil];
        [_facebook authorize:permissions];
        [defaults synchronize];
    }
}

- (void)fbDidLogin {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[_facebook accessToken] forKey:@"FBAccessTokenKey"];
    [defaults setObject:[_facebook expirationDate] forKey:@"FBExpirationDateKey"];
    [defaults synchronize];

}

And in my app delegate
// Pre 4.2 support
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [[_viewController facebook] handleOpenURL:url];
}

// For 4.2+ support
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [_viewController.facebook handleOpenURL:url];
}

It go to the Facebook app, and it request all the permissions etc.. and IT said in the console "Image Published" but if I stay in Facebook app without accepting or declining, just stay there it execute the upload image...
If in the Facebook App I accept all the permissions it return to my normal app. The app Delegate methods are return normal values a webpage of Facebook with a really long string.
What could I do?
Thanks

A:

Try this code...
    -(void)buttonPressed:(id)sender{ //start the facebook action by clicking any button
    facebook = [[Facebook alloc] initWithAppId:@"YOUR_APP_ID" andDelegate:self];

     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            if ([defaults objectForKey:@"FBAccessTokenKey"] && [defaults objectForKey:@"FBExpirationDateKey"]) {
                facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
                facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
            }
    if (![facebook isSessionValid]) {
        [facebook authorize:nil];
    }else{
    [self postWall];
    }
    // Pre 4.2 support
    - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
        return [facebook handleOpenURL:url];
    }
// after 4.2 support
    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [facebook handleOpenURL:url];
}
    - (void)fbDidLogin {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"];
        [defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"];
        [defaults synchronize];
        [self postWall];
    }
    -(void)postWall{

          NSString *filePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
NSData *imageData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                               @"Test message", @"message", imageData, @"source", nil];
[facebook requestWithGraphPath:@"me/photos" andParams:params andHttpMethod:@"POST" andDelegate:self];

        NSLog(@"Image posted");
    }
-(void)fbDidNotLogin:(BOOL)cancelled{
    if (cancelled) {
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"Could not Login" message:@"Facebook Cannot login for your application" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alertView show];
    }
}

Check out did you put delegate to FBsessionDelegate,FBRequestDelegate in your controller File.Try to run your facebook in your app itself and NOT in SAFARI.To do that check this link. Facebook Implementation within app (without opening in safari or native app)
EDITED:
Changed code with postWall method and added fbDidNotLoginMethod.This is the correct one.


Q:

How to find smoothed estimates of the derivative and second derivative of a signal?

I have a signal sampled at $\Delta t$: $f_i(t_i=i\Delta t)$ where $i = 0,\ldots,n-1$.
I want to find the first and second derivative of the signal: $f'(t)$ and $f''(t)$.
My first thought was to estimate the derivatives by central differences:
\begin{align}
f'(t_{i})&=\frac{f(t_{i+1})-f(t_{i-1})}{2\Delta t}\\
f''(t_{i})&=\frac{f(t_{i+1})-2f(t_{i})+f(t_{i-1})}{(\Delta t)^2}
\end{align}
However the signal may have a lot of high frequency noise that may cause quick fluctuations in $f'$ and $f''$.
What would be the best way to find "smoothed" estimates of $f'$ and $f''$?

A:

It probably depends more on your data. Just know, since differentiation is a linear operation, if you choose any linear filter to smooth f' and f'', it is equivalent to smoothing f using that same filter, then taking its derivatives.
Can you post some pictures or more information about the signal you want to differentiate? Probably what you're looking for is some sort of lowpass filter to smooth the signal. A couple really simple options include a single-pole recursive filter like $y(n) = a \cdot x(n) + (1-a) \cdot y(n-1)$, or a Hann filter, which is just convolving the signal with a Hann window. The Hann filter option is nice because it's linear-phase. If you know the frequency range you care about, you can just design a suitable lowpass filter in the frequency domain.

A:

The Savitzky-Golay filter provides smooth estimates of the signal and first few derivatives.
A MATLAB implementation can be found here.


Q:

Find coordinates of n points uniformly distributed in a rectangle

I have a rectangle R of width W and height H.
I have N points inside this rectangle.
I need to find an algorithm to position my points in the rectangle in the most uniform way possible (no overlaps, max area coverage, uniform density).
So the output of the algorithm should be a list of coordinates.
Here's some examples with different rectangles and points:

Any help?

A:

In the absence of a precise definition of "the most uniform way possible", try this method:

Uniformly generate say $100N$ random points in the rectangle. These
are the density points.
Uniformly generate $N$ random points in the rectangle. These are the
sites.
Compute an approximate Voronoi diagram of the sites based on the
density points. More precisely, assign to each density point the
site closest to it.
Now, move each site to the barycenter of the density points assigned
to it.
Repeat steps 3 and 4 say $30$ times (a version of Lloyd's
algorithm for approximating a centroidal Voronoi tessellation).

The result is a nicely distributed set of $N$ sites in the rectangle.
The images below use $N=100$. Original sites on the left, final sites on the right.