问:
Best way to programmatically detect iPad/iPhone hardware
The reason I need to find out is that on an iPad, a UIPickerView has the same height in landscape orientation as it does in portrait. On an iPhone it is different. The iPad programming guide introduces an "idiom" value to UIDevice:

```<code>    UIDevice* thisDevice = [UIDevice currentDevice];
    if(thisDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad)
    {
        // iPad
    }
    else
    {
        // iPhone
    }
</code>```

which works OK while you're in iPad (3.2) but not iPhone (3.1.3) - so it looks like there also needs to be an ifdef to conditionally compile that check, like:

```<code>#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 30200
        UIDevice* thisDevice = [UIDevice currentDevice];
        if(thisDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad)
        {
            // etc.
        }
#endif
</code>```

To me that's starting to look very clumsy. What's a better way?

答:
In Swift use userInterfaceIdiom instance property as- </p>

```<code>if UIDevice.current.userInterfaceIdiom == .phone {
     print("iPhone")
 }
</code>```

<p>& For other devices - </p>

```<code>  switch UIDevice.current.userInterfaceIdiom {
    case .pad:
        print("iPad")
    case .phone:
        print("iPhone")
    case .tv:
        print("TV")
    case .carPlay:
        print("carPlay")
    default: break;
  }
</code>```

Body:
The reason I need to find out is that on an iPad, a UIPickerView has the same height in landscape orientation as it does in portrait. On an iPhone it is different. The iPad programming guide introduces an "idiom" value to UIDevice:

    UIDevice* thisDevice = [UIDevice currentDevice];
    if(thisDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad)
    {
        // iPad
    }
    else
    {
        // iPhone
    }

which works OK while you're in iPad (3.2) but not iPhone (3.1.3) - so it looks like there also needs to be an ifdef to conditionally compile that check, like:

#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 30200
        UIDevice* thisDevice = [UIDevice currentDevice];
        if(thisDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad)
        {
            // etc.
        }
#endif

To me that's starting to look very clumsy. What's a better way?

Body:
In Swift use userInterfaceIdiom instance property as-

if UIDevice.current.userInterfaceIdiom == .phone {
     print("iPhone")
 }

& For other devices -

  switch UIDevice.current.userInterfaceIdiom {
    case .pad:
        print("iPad")
    case .phone:
        print("iPhone")
    case .tv:
        print("TV")
    case .carPlay:
        print("carPlay")
    default: break;
  }


来源: stackexchange

问:
How to make Interactive program in BST ? C Lang
I need to to open and read multiple text files which will be stored similar to binary search tree construction.

NOTE: They all need to be opened and their content stored before user enters his input.

I really do need some advice, because I do not see my errors any more.

However, what I really don't get, is how to make it interactive ?

When I press 'A', it needs to read text from the left node and opposite.

Structure of output:

------------------\n

  \n

  Title\n

  file1 // file present - 'A'

  file2 // file empty/not empty - 'B'\n

  Text\n

  \n

  Your choice (A/B):\n

This is how the programs output should look at the beginning:
terminal

Elements of struct

```<code>typedef struct _Elements_
{
  char* title_;
  struct _Elements_* left;
  struct _Elements_* right;
  char* text_;
} Elements;
</code>```

//Forward initialization is present

```<code>int main (int argc, char* argv[])
{
  char returned_value;
  Elements element;

  if (argc != 2)
  {
    printf("Usage: ./ass2 [file-name]\n");
    return 1;
  }

  returned_value = openFile(&element, argv[1]);

  while(returned_value != ('A' || 'B'))
  {
    repeatEntry(returned_value); // Function to scan the value
  }

  // Tricky part! Read from left ???
  if(returned_value == 'A')
  {
    printf("%s",element.left->text_);
  }
  else
  {
    printf("%s",element.right->text_);
  }

  return 0;
}
</code>```

//Here i wanna initialize node elements

// For every malloc, I have to make sure that it succeeded

```<code>Elements* newNode(Elements* element)
{
  Elements* newNode = (Elements*)malloc(sizeof(Elements));
  if(newNode == NULL)
  {
    printf("[ERR] Out of memory.\n");
     return (void*)2; // void* - to avoid warning of different type?
  }
  newNode->title_ = NULL;
  newNode->left = NULL;
  newNode->right = NULL;
  newNode->text_ = NULL;

  return newNode;
}
</code>```

//Function that opens the files

```<code>char openFile(Elements* element, char* input)
{
  // Create new memory if tree is empty
  if(element == NULL)
  {
    return newNode(element);
  }
  FILE* file_open = fopen(input, "r");
  if (file_open == NULL)
  {
    printf("[ERR] Could not read file %s.\n", input);
    return 3;
  }

  // Local variables to handle the parsing file ?
  char line[80];
  int lenght_of_the_line; // Was just for me
  int line_number = 0; // this also

  // Do i really need local variables beside struct ?
  char* title_local = NULL;
  char* first_file = NULL;
  char* second_file = NULL;
  char* text_local = NULL;

  while(fgets(line, 80, file_open))
  {
    lenght_of_the_line = strlen(line);
    //printf("%d ", lenght_of_the_line);
    //printf("%s ", line);

    // Get title
    if((line[lenght_of_the_line - 1] == '\n') && (line_number == 0))
    {

      title_local = (char*)malloc(lenght_of_the_line * (sizeof(char)) + 1);
      if(title_local == NULL)
      {
        printf("[ERR] Out of memory.\n");
        return 2;
      }
      strcpy(title_local, line);
      printf("%s ", element->title_ = title_local);
      printf("\n");
    }

    // Get 1st file name
    else if( (line[lenght_of_the_line - 1] == '\n') && (line_number == 1) )
    {
      if( (line[lenght_of_the_line - 5] == '.') &&
          (line[lenght_of_the_line - 4] == 't') &&
          (line[lenght_of_the_line - 3] == 'x') &&
          (line[lenght_of_the_line - 2] == 't') )
      {
        // Allocate enough memory for first file name
        first_file = (char*)malloc(lenght_of_the_line * (sizeof(char)) + 1);
        if(first_file == NULL)
        {
          printf("[ERR] Out of memory.\n");
          return 2;
        }
        strcpy(first_file, line);

         //name of file to open and store to left node
         //Seems to work, since I got no error
        openFile(element->left, first_file);
      }
    }

    // Get 2nd file name
    else if( (line[lenght_of_the_line - 1] == '\n') && (line_number == 2) )
    {
      if( (line[lenght_of_the_line - 5] == '.') &&
          (line[lenght_of_the_line - 4] == 't') &&
          (line[lenght_of_the_line - 3] == 'x') &&
          (line[lenght_of_the_line - 2] == 't') )
      {
        second_file = (char*)malloc(lenght_of_the_line * (sizeof(char)) + 1);
        if(second_file == NULL)
        {
          printf("[ERR] Out of memory.\n");
          return 2;
        }
        strcpy(second_file, line);
        openFile(element->right, second_file);
      }
    }
    else
    {
      text_local = (char*)malloc(lenght_of_the_line * (sizeof(char)) + 1);
      if(text_local == NULL)
        {
          printf("[ERR] Out of memory.\n");
          return 2;
        }
      strcpy(text_local, line);
      element->text_ = text_local;
      printf("%s", element->text_);
    }

    // Increase line number for 1
    line_number++;
  }
  //free(line);

  fclose(file_open);
  printf("\n");
  printf("Your choice (A/B)? ");
  char user_input;
  scanf("%c", &user_input);

  // DONT FORGET TO FREE THE MEMORY !

  return user_input;
}
</code>```

答:
This

```<code>while(returned_value != ('A' || 'B'))
</code>```

does not do what you probably expect. It compares the returned value to whatever value your compiler uses to represent true.

Currently your loop is hence likely to seem an endless loop, while waiting for returned_value to be identical to true.

You need

```<code>while((returned_value != 'A') && (returned_value != 'B'))
</code>```

This will leave the loop when returned_value is identical to either 'A' or 'B'.

That way the endless loop problem is solved, which is likely the core problem preventing your file BST from being interactive.

By the way, for users convenience I recommend to also accept 'a' or 'b'.

For avoiding a "try again" after each input, use

```<code>scanf(" %c", &user_input);
</code>```

with a space at the start, for ignoring leading white space, including the newline/return after each entered 'A' or 'B'.

ContentLicense: CC BY-SA 3.0

Body:
I need to to open and read multiple text files which will be stored similar to binary search tree construction.

NOTE: They all need to be opened and their content stored before user enters his input.

I really do need some advice, because I do not see my errors any more.

However, what I really don't get, is how to make it interactive ?

When I press 'A', it needs to read text from the left node and opposite.

Structure of output:

------------------\n

  \n

  Title\n

  file1 // file present - 'A'

  file2 // file empty/not empty - 'B'\n

  Text\n

  \n

  Your choice (A/B):\n

This is how the programs output should look at the beginning:
terminal

Elements of struct

typedef struct _Elements_
{
  char* title_;
  struct _Elements_* left;
  struct _Elements_* right;
  char* text_;
} Elements;

//Forward initialization is present

int main (int argc, char* argv[])
{
  char returned_value;
  Elements element;

  if (argc != 2)
  {
    printf("Usage: ./ass2 [file-name]\n");
    return 1;
  }

  returned_value = openFile(&element, argv[1]);

  while(returned_value != ('A' || 'B'))
  {
    repeatEntry(returned_value); // Function to scan the value
  }

  // Tricky part! Read from left ???
  if(returned_value == 'A')
  {
    printf("%s",element.left->text_);
  }
  else
  {
    printf("%s",element.right->text_);
  }

  return 0;
}

//Here i wanna initialize node elements

// For every malloc, I have to make sure that it succeeded

Elements* newNode(Elements* element)
{
  Elements* newNode = (Elements*)malloc(sizeof(Elements));
  if(newNode == NULL)
  {
    printf("[ERR] Out of memory.\n");
     return (void*)2; // void* - to avoid warning of different type?
  }
  newNode->title_ = NULL;
  newNode->left = NULL;
  newNode->right = NULL;
  newNode->text_ = NULL;

  return newNode;
}

//Function that opens the files

char openFile(Elements* element, char* input)
{
  // Create new memory if tree is empty
  if(element == NULL)
  {
    return newNode(element);
  }
  FILE* file_open = fopen(input, "r");
  if (file_open == NULL)
  {
    printf("[ERR] Could not read file %s.\n", input);
    return 3;
  }

  // Local variables to handle the parsing file ?
  char line[80];
  int lenght_of_the_line; // Was just for me
  int line_number = 0; // this also

  // Do i really need local variables beside struct ?
  char* title_local = NULL;
  char* first_file = NULL;
  char* second_file = NULL;
  char* text_local = NULL;

  while(fgets(line, 80, file_open))
  {
    lenght_of_the_line = strlen(line);
    //printf("%d ", lenght_of_the_line);
    //printf("%s ", line);

    // Get title
    if((line[lenght_of_the_line - 1] == '\n') && (line_number == 0))
    {

      title_local = (char*)malloc(lenght_of_the_line * (sizeof(char)) + 1);
      if(title_local == NULL)
      {
        printf("[ERR] Out of memory.\n");
        return 2;
      }
      strcpy(title_local, line);
      printf("%s ", element->title_ = title_local);
      printf("\n");
    }

    // Get 1st file name
    else if( (line[lenght_of_the_line - 1] == '\n') && (line_number == 1) )
    {
      if( (line[lenght_of_the_line - 5] == '.') &&
          (line[lenght_of_the_line - 4] == 't') &&
          (line[lenght_of_the_line - 3] == 'x') &&
          (line[lenght_of_the_line - 2] == 't') )
      {
        // Allocate enough memory for first file name
        first_file = (char*)malloc(lenght_of_the_line * (sizeof(char)) + 1);
        if(first_file == NULL)
        {
          printf("[ERR] Out of memory.\n");
          return 2;
        }
        strcpy(first_file, line);

         //name of file to open and store to left node
         //Seems to work, since I got no error
        openFile(element->left, first_file);
      }
    }

    // Get 2nd file name
    else if( (line[lenght_of_the_line - 1] == '\n') && (line_number == 2) )
    {
      if( (line[lenght_of_the_line - 5] == '.') &&
          (line[lenght_of_the_line - 4] == 't') &&
          (line[lenght_of_the_line - 3] == 'x') &&
          (line[lenght_of_the_line - 2] == 't') )
      {
        second_file = (char*)malloc(lenght_of_the_line * (sizeof(char)) + 1);
        if(second_file == NULL)
        {
          printf("[ERR] Out of memory.\n");
          return 2;
        }
        strcpy(second_file, line);
        openFile(element->right, second_file);
      }
    }
    else
    {
      text_local = (char*)malloc(lenght_of_the_line * (sizeof(char)) + 1);
      if(text_local == NULL)
        {
          printf("[ERR] Out of memory.\n");
          return 2;
        }
      strcpy(text_local, line);
      element->text_ = text_local;
      printf("%s", element->text_);
    }

    // Increase line number for 1
    line_number++;
  }
  //free(line);

  fclose(file_open);
  printf("\n");
  printf("Your choice (A/B)? ");
  char user_input;
  scanf("%c", &user_input);

  // DONT FORGET TO FREE THE MEMORY !

  return user_input;
}

Body:
This

while(returned_value != ('A' || 'B'))

does not do what you probably expect. It compares the returned value to whatever value your compiler uses to represent true.

Currently your loop is hence likely to seem an endless loop, while waiting for returned_value to be identical to true.

You need

while((returned_value != 'A') && (returned_value != 'B'))

This will leave the loop when returned_value is identical to either 'A' or 'B'.

That way the endless loop problem is solved, which is likely the core problem preventing your file BST from being interactive.

By the way, for users convenience I recommend to also accept 'a' or 'b'.

For avoiding a "try again" after each input, use

scanf(" %c", &user_input);

with a space at the start, for ignoring leading white space, including the newline/return after each entered 'A' or 'B'.


问:
Hide to show and hide keyboard in DialogFragment
In my dialog fragment, I am able to show the keyboard using

```<code>getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT STATE_VISIBLE);
</code>```

but I am not able to hide it on dismiss.

I've tried

```<code>getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
</code>```

and

```<code>getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
</code>```

neither of which work.

I've also tried showing and hiding the keyboard using

```<code>InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(0, 0);
</code>```

and

```<code>InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
</code>```

but these are not able to show or hide the keyboard.

```<code> public static class MyDialogFragment extends DialogFragment
    {
        @Nullable @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            return inflater.inflate(R.layout.my_input_dialog, container, false);
        }

        @Override
        public void onViewCreated(View v, Bundle savedInstanceState)
        {
            super.onViewCreated(v, savedInstanceState);

            final EditText editText = (EditText)v.findViewById(R.id.input);
            // this line below is able to show the keyboard
            getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            Button add = (Button)v.findViewById(R.id.add_btn);
            add.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    // other code not shown
                    dismiss();
                }
            });
            Button cancel = (Button)v.findViewById(R.id.cancel_btn);
            cancelButton.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    dismiss();
                }
            });
        }

        @Override
        public void onDismiss(DialogInterface dialog)
        {
            //this line below does NOT work, it does not hide the keyboard
            getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            super.onDismiss(dialog);
        }
    }
</code>```

Note: I have read these stackoverflow posts and have tried the proposed solutions to no avail:

How to hide the onscreen keyboard when a DialogFragment is canceled by the setCanceledOnTouchOutside event

Close/hide the Android Soft Keyboard

答:
Hide it in DialogFragment onDestroyView() method:

```<code> View view = getActivity().getCurrentFocus();
        if (view == null) view = new View(activity);
        InputMethodManager imm = (InputMethodManager)     getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
</code>```

maybe work.

Body:
In my dialog fragment, I am able to show the keyboard using

getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT STATE_VISIBLE);

but I am not able to hide it on dismiss.

I've tried

getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

and

getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

neither of which work.

I've also tried showing and hiding the keyboard using

InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(0, 0);

and

InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);

but these are not able to show or hide the keyboard.

 public static class MyDialogFragment extends DialogFragment
    {
        @Nullable @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            return inflater.inflate(R.layout.my_input_dialog, container, false);
        }

        @Override
        public void onViewCreated(View v, Bundle savedInstanceState)
        {
            super.onViewCreated(v, savedInstanceState);

            final EditText editText = (EditText)v.findViewById(R.id.input);
            // this line below is able to show the keyboard
            getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            Button add = (Button)v.findViewById(R.id.add_btn);
            add.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    // other code not shown
                    dismiss();
                }
            });
            Button cancel = (Button)v.findViewById(R.id.cancel_btn);
            cancelButton.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    dismiss();
                }
            });
        }

        @Override
        public void onDismiss(DialogInterface dialog)
        {
            //this line below does NOT work, it does not hide the keyboard
            getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            super.onDismiss(dialog);
        }
    }

Note: I have read these stackoverflow posts and have tried the proposed solutions to no avail:

How to hide the onscreen keyboard when a DialogFragment is canceled by the setCanceledOnTouchOutside event

Close/hide the Android Soft Keyboard

Body:
Hide it in DialogFragment onDestroyView() method:

 View view = getActivity().getCurrentFocus();
        if (view == null) view = new View(activity);
        InputMethodManager imm = (InputMethodManager)     getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

maybe work.


问:
framework with view controller and storyboard
Is it possible to create a cocoa touch framework in swift which contain storyboard and viewControllers?

If yes can you give me a reference to a guide or something to get started? all the examples i see of creating frameworks are very simple classes which don't involve ui

I want to create a framework which involve UI

答:
Yes, that is possible.

All you have to do is to create a cocoa framework as you normally do from File > New > iOS - Cocoa Framework..

Since this involves UI, Click on the project and right click > New > iOS - Storyboard. And after that it is just as simple as you do it in a normal app. Once your stuff is over in the framework side, you gotta create a new project to test your framework with UI (make sure that the class created in fw is a public class ).

To load the storyboard of your framework instead of your sample project's storyboard, do the full in ViewWillAppear method.

Create an object for storyboard along with the bundle (of your framework - normally it will be your VC's name)

instantiateInitialViewController

And present them

And you'll have your framework's storyboard in your sample project.


问:
With Netty 4, how do I handle reference counted objects when an exception is thrown inside a handler?
Suppose I have an inbound channel handler like this:

```<code>public class Handler extends ChannelInboundHandlerAdapter {

    @Override
    protected void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // msg is actually a reference counted object
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // Handle exception here, can't release msg since it's not passed.
    }
}
</code>```

Since exceptionCaught does not receive the inbound message in its signature, it seems like there is no way to ensure that the reference counted object is released. It appears that I am forced to wrap the entire contents of channelRead in a try/catch block in order to make sure I can recover for any exceptions properly without terminating the entire process. Is this true?

答:
You should release your reference counted objects inside the a try-finally, as shown by the Netty quick start tutorial.

This can be done as follows:

```<code>public class Handler extends ChannelInboundHandlerAdapter {

    @Override
    protected void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            // msg is actually a reference counted object
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // Handle exception here, can't release msg since it's not passed.
    }
}
</code>```

Notice that I have called ReferenceCountUtil.release(msg); instead of just msg.release(), this is because the fact that calling the first automatically checks if the object in question can be released, while for the latter you need to cast the object to a different type, before you can call the release method.

Body:
Suppose I have an inbound channel handler like this:

public class Handler extends ChannelInboundHandlerAdapter {

    @Override
    protected void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // msg is actually a reference counted object
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // Handle exception here, can't release msg since it's not passed.
    }
}

Since exceptionCaught does not receive the inbound message in its signature, it seems like there is no way to ensure that the reference counted object is released. It appears that I am forced to wrap the entire contents of channelRead in a try/catch block in order to make sure I can recover for any exceptions properly without terminating the entire process. Is this true?

Body:
You should release your reference counted objects inside the a try-finally, as shown by the Netty quick start tutorial.

This can be done as follows:

public class Handler extends ChannelInboundHandlerAdapter {

    @Override
    protected void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            // msg is actually a reference counted object
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // Handle exception here, can't release msg since it's not passed.
    }
}

Notice that I have called ReferenceCountUtil.release(msg); instead of just msg.release(), this is because the fact that calling the first automatically checks if the object in question can be released, while for the latter you need to cast the object to a different type, before you can call the release method.


问:
Is there a way to have a default when a sequence contains no elements when using .first with LINQ?
I am using the following code:

```<code>public class BtnCountViews
{
    public int btnCount { get; set; }
    public int views { get; set; }
}

var btns = "(BTNACOUNT + BTNBCOUNT) AS BtnCount, VIEWS As Views";
Counts.btnCountViewsToday =
   db2.Query<BtnCountViews>("SELECT " + btns + " FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).First();
</code>```

When there is no record returned for the day yymmdd then this errors out with a message saying sequence contains no elements.

I do understand why this is happening but would like some suggestions on how I could stop it throwing an exception.

What I would like to do if there are no elements is for Counts.btnCountViewsToday to contain an object populated with a 0 in the btnCount and the views fields.

答:
Try to use FirstOrDefault

```<code> var btnCountViewsToday =
   db2.Query<BtnCountViews>("SELECT " + btns +
    " FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).FirstOrDefault();
</code>```

If you want to create a default object for possible null response you can use DefaultIfEmpty like this;

```<code>var btnCountViewsToday =
   db2.Query<BtnCountViews>("SELECT " + btns +
   " FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).
   DefaultIfEmpty(new BtnCountViews()).FirstOrDefault();
</code>```

Body:
I am using the following code:

public class BtnCountViews
{
    public int btnCount { get; set; }
    public int views { get; set; }
}

var btns = "(BTNACOUNT + BTNBCOUNT) AS BtnCount, VIEWS As Views";
Counts.btnCountViewsToday =
   db2.Query<BtnCountViews>("SELECT " + btns + " FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).First();

When there is no record returned for the day yymmdd then this errors out with a message saying sequence contains no elements.

I do understand why this is happening but would like some suggestions on how I could stop it throwing an exception.

What I would like to do if there are no elements is for Counts.btnCountViewsToday to contain an object populated with a 0 in the btnCount and the views fields.

Body:
Try to use FirstOrDefault

 var btnCountViewsToday =
   db2.Query<BtnCountViews>("SELECT " + btns +
    " FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).FirstOrDefault();

If you want to create a default object for possible null response you can use DefaultIfEmpty like this;

var btnCountViewsToday =
   db2.Query<BtnCountViews>("SELECT " + btns +
   " FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).
   DefaultIfEmpty(new BtnCountViews()).FirstOrDefault();


问:
Difference between object oriented and object based programming language
What's the difference between object based and object oriented programming language?</p>

答: Object oriented programming languages follow all concepts belonging to OOP. Object-based language doesn't support all the features of OOPs like Polymorphism and Inheritance Object-based language has in-built object like JavaScript has window object. Object-based languages are JavaScript.</p>


问:
css-grids, max-height on Chrome not working?
I want to build a Website Applikation with a fixed Size.

Only a content div should be scrollable.

On FireFox my App worked correctly, but on Chrome i get a strange behaviour and i cannot figure out why?

I extract the problem in a small example as follows.

```<code><!DOCTYPE html>
<html>
<head>
    <title>App</title>
    <style>
        html, body
        {
            left: 0;
            top: 0;
            margin: 0;
            width: 100vw;
            height: 100vh;
        }

        .app
        {
            height : 100vh;
            width : 100vw;
            /*overflow: hidden;*/
            display: grid;
            grid-template-rows: 100px auto;
        }

        .content
        {
            display: grid;
            grid-template-columns: 500px auto;
            height: 100%;
            max-height: 100%;
        }

        .scrollable
        {
            overflow: auto;
            max-height: 100%;
        }

        .red
        {
            background-color: red;
        }

        .yellow
        {
            background-color: yellow;
        }

        .blue
        {
          background-color: blue;
        }
    </style>
</head>

<body>
  <div class="app">
    <div class="yellow"></div>
    <div class="content">
      <div class="red scrollable">
        some content <br />
        some content <br />
        .
        .
        .
        some content <br />
        some content <br />
      </div>

      <div class="blue scrollable"></div>
    </div>
  </div>
</body>

</html>
</code>```

in firefox just the red div got a scrollbar, but in chrome the whole page get one. Why they behave differently and how can i fix this in chrome?

答: Remove height:100%, width:100% from the body also remove min-height:100% from app. Hope this should work both browser same.

Body:
I want to build a Website Applikation with a fixed Size.

Only a content div should be scrollable.

On FireFox my App worked correctly, but on Chrome i get a strange behaviour and i cannot figure out why?

I extract the problem in a small example as follows.

<!DOCTYPE html>

    <title>App</title>

        some content

        some content

        .
        .
        .
        some content

        some content

in firefox just the red div got a scrollbar, but in chrome the whole page get one. Why they behave differently and how can i fix this in chrome?


问:
How to integrate codeigniter and PHPExcel?
always display an error message on my browser:

```<code>An Error Was Encountered
Non-existent class: IOFactory
</code>```

all classes PHPExcel, i extract on library.

Here it is my controller code

```<code><?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Report extends CI_Controller
{
     public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url'));
    }

    public function index()
    {

        $this->load->library('phpexcel');
        $this->load->library('PHPExcel/IOFactory.php');
        $objPHPexcel = PHPExcel_IOFactory::load('tandaterima.xlsx');
        $objWorksheet = $objPHPexcel->getActiveSheet();
        //Daftar barang (4item)
        $objWorksheet->getCell('B16')->setValue('UTP');
        $objWorksheet->getCell('B17')->setValue('Cross');
        $objWorksheet->getCell('B18')->setValue('');
        $objWorksheet->getCell('B19')->setValue('');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPexcel, 'Excel5');
        $objWriter->save('write5.xls');
    }
}
</code>```

please help me.

答:
Codeiginiter 3 supports Composer to use PHPExcel:

In application/config/config.php, set $config['composer_autoload'] to TRUE.

Then you can use Composer to install PHPExcel in Codeiginiter :

```<code>composer require phpoffice/phpexcel
</code>```

Further, You could try PHPExcel Helper to easier handle PHPExcel:

```<code>composer require yidas/phpexcel-helper
</code>```

https://github.com/yidas/phpexcel-helper

Body:
always display an error message on my browser:

An Error Was Encountered
Non-existent class: IOFactory

all classes PHPExcel, i extract on library.

Here it is my controller code

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Report extends CI_Controller
{
     public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url'));
    }

    public function index()
    {

        $this->load->library('phpexcel');
        $this->load->library('PHPExcel/IOFactory.php');
        $objPHPexcel = PHPExcel_IOFactory::load('tandaterima.xlsx');
        $objWorksheet = $objPHPexcel->getActiveSheet();
        //Daftar barang (4item)
        $objWorksheet->getCell('B16')->setValue('UTP');
        $objWorksheet->getCell('B17')->setValue('Cross');
        $objWorksheet->getCell('B18')->setValue('');
        $objWorksheet->getCell('B19')->setValue('');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPexcel, 'Excel5');
        $objWriter->save('write5.xls');
    }
}

please help me.

Body:
Codeiginiter 3 supports Composer to use PHPExcel:

In application/config/config.php, set $config['composer_autoload'] to TRUE.

Then you can use Composer to install PHPExcel in Codeiginiter :

composer require phpoffice/phpexcel

Further, You could try PHPExcel Helper to easier handle PHPExcel:

composer require yidas/phpexcel-helper

https://github.com/yidas/phpexcel-helper


问:
nested scrollview + recyclerview, strange autoscroll behaviour
In a view pager I have several fragments, one of them uses a nested scrollview with a header and a recyclerview :

```<code><android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.m360.android.fragment.Members.MemberDetailsFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingTop="20dp">

        <header/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clipToPadding="false"
            android:paddingTop="0dp" />

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>
</code>```

The tag "header" represents a complex layout that I didn't want to post here as it stretches out the code a lot.

when I switch between the tabs, it scrolls strait to the recycler view. The header is hidden, I have to scroll up to see it.

Any ideas on what causes that ? I don't wanna use a type in my adapter if I can avoid it.

答: setandroid:focusableInTouchMode="true" for child Layout( may be LinearLayout ) of NestedScrollView

Body:
In a view pager I have several fragments, one of them uses a nested scrollview with a header and a recyclerview :

<android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.m360.android.fragment.Members.MemberDetailsFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingTop="20dp">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clipToPadding="false"
            android:paddingTop="0dp" />

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

The tag "header" represents a complex layout that I didn't want to post here as it stretches out the code a lot.

when I switch between the tabs, it scrolls strait to the recycler view. The header is hidden, I have to scroll up to see it.

Any ideas on what causes that ? I don't wanna use a type in my adapter if I can avoid it.

ContentLicense: CC BY-SA 4.0


问:
Display specific length of div element pagination
I would like to know how to display specific length of an item by pagination.
with the element code below shows 20 items of div elements.

```<code><div class="group-of-element">
<div class="items">item1</div>
<div class="items">item2</div>
<div class="items">item3</div>
<div class="items">item4</div>
<div class="items">item5</div>
<div class="items">item6</div>
<div class="items">item7</div>
<div class="items">item8</div>
<div class="items">item9</div>
<div class="items">item10</div>
<div class="items">item12</div>
<div class="items">item13</div>
<div class="items">item14</div>
<div class="items">item15</div>
<div class="items">item16</div>
<div class="items">item17</div>
<div class="items">item18</div>
<div class="items">item19</div>
<div class="items">item20</div>
</div>
</code>```

As a result It would be something like this

The first 9 of div items would be displayed and when the button "Display Next 9 items" would be clicked it would display the next set of 9 items. And also when the "Display all items" would be clicked, all results should be displayed.

*Updated Also all the old items would need to hide when the "next 9 items" should be clicked

Any help would be greatly appreciated

答:
You need to keep a track of the shown items, follow this approach

```<code>document.querySelector( "#next" ).addEventListener( "click", function(){
   $( ".group-of-element .items" ).hide().filter( i => i >= lastValue && i <= lastValue + numberOfItems - 1 ).show();
   lastValue = lastValue + numberOfItems > totalItems ? totalItems - 1 :  lastValue + numberOfItems;
});

document.querySelector( "#prev" ).addEventListener( "click", function(){
   console.log(lastValue);
   $( ".group-of-element .items" ).hide().filter( i => i <= lastValue && i >= lastValue - numberOfItems + 1 ).show();
   lastValue = lastValue - numberOfItems < 0 ? 0 :  lastValue - numberOfItems;
});
</code>```

Demo

var numberOfItems = 9;
var lastValue = 8;
var totalItems = $( ".group-of-element .items" ).length;

$( ".group-of-element .items" ).filter( i => i >= numberOfItems ).hide();

document.querySelector( "#next" ).addEventListener( "click", function(){
   $( ".group-of-element .items" ).hide().filter( i => i >= lastValue && i <= lastValue + numberOfItems - 1 ).show();
   lastValue = lastValue + numberOfItems > totalItems ? totalItems - 1 :  lastValue + numberOfItems;
});

document.querySelector( "#prev" ).addEventListener( "click", function(){
   console.log(lastValue);
   $( ".group-of-element .items" ).hide().filter( i => i <= lastValue && i >= lastValue - numberOfItems + 1 ).show();
   lastValue = lastValue - numberOfItems < 0 ? 0 :  lastValue - numberOfItems;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.items {
  background-color: #0cf;
  width: 32%;
  padding: 20px 0px;
  border: 1px solid #000;
  display: inline-block;
  text-align: center;
  vertical-align: middle;
}</code>```

item1

item2

item3

item4

item5

item6

item7

item8

item9

item10

item12

item13

item14

item15

item16

item17

item18

item19

item20

<button id="next">Next</button><button id="prev">prev</button>```

Body:
I would like to know how to display specific length of an item by pagination.
with the element code below shows 20 items of div elements.

item1

item2

item3

item4

item5

item6

item7

item8

item9

item10

item12

item13

item14

item15

item16

item17

item18

item19

item20

As a result It would be something like this

The first 9 of div items would be displayed and when the button "Display Next 9 items" would be clicked it would display the next set of 9 items. And also when the "Display all items" would be clicked, all results should be displayed.

*Updated Also all the old items would need to hide when the "next 9 items" should be clicked

Any help would be greatly appreciated

Body:
You need to keep a track of the shown items, follow this approach

document.querySelector( "#next" ).addEventListener( "click", function(){
   $( ".group-of-element .items" ).hide().filter( i => i >= lastValue && i <= lastValue + numberOfItems - 1 ).show();
   lastValue = lastValue + numberOfItems > totalItems ? totalItems - 1 :  lastValue + numberOfItems;
});

document.querySelector( "#prev" ).addEventListener( "click", function(){
   console.log(lastValue);
   $( ".group-of-element .items" ).hide().filter( i => i <= lastValue && i >= lastValue - numberOfItems + 1 ).show();
   lastValue = lastValue - numberOfItems < 0 ? 0 :  lastValue - numberOfItems;
});

Demo

var numberOfItems = 9;
var lastValue = 8;
var totalItems = $( ".group-of-element .items" ).length;

$( ".group-of-element .items" ).filter( i => i >= numberOfItems ).hide();

document.querySelector( "#next" ).addEventListener( "click", function(){
   $( ".group-of-element .items" ).hide().filter( i => i >= lastValue && i <= lastValue + numberOfItems - 1 ).show();
   lastValue = lastValue + numberOfItems > totalItems ? totalItems - 1 :  lastValue + numberOfItems;
});

document.querySelector( "#prev" ).addEventListener( "click", function(){
   console.log(lastValue);
   $( ".group-of-element .items" ).hide().filter( i => i <= lastValue && i >= lastValue - numberOfItems + 1 ).show();
   lastValue = lastValue - numberOfItems < 0 ? 0 :  lastValue - numberOfItems;
});

.items {
  background-color: #0cf;
  width: 32%;
  padding: 20px 0px;
  border: 1px solid #000;
  display: inline-block;
  text-align: center;
  vertical-align: middle;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="group-of-element">
  <div class="items">item1</div>
  <div class="items">item2</div>
  <div class="items">item3</div>
  <div class="items">item4</div>
  <div class="items">item5</div>
  <div class="items">item6</div>
  <div class="items">item7</div>
  <div class="items">item8</div>
  <div class="items">item9</div>
  <div class="items">item10</div>
  <div class="items">item12</div>
  <div class="items">item13</div>
  <div class="items">item14</div>
  <div class="items">item15</div>
  <div class="items">item16</div>
  <div class="items">item17</div>
  <div class="items">item18</div>
  <div class="items">item19</div>
  <div class="items">item20</div>
</div>
<button id="next">Next</button><button id="prev">prev</button>


问:
Add placeholder text inside UITextView in Swift?
How can I add a placeholder in a UITextView, similar to the one you can set for UITextField, in Swift?

答:
Swift 3.2

```<code>extension EditProfileVC:UITextViewDelegate{

    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.textColor == UIColor.lightGray {
            textView.text = nil
            textView.textColor = UIColor.black
       }
    }
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.isEmpty {
            textView.text = "Placeholder"
            textView.textColor = UIColor.lightGray
        }
    }
}
</code>```

First when user start editing textViewDidBeginEditing call and then check the if colour of text grey means user didn't write anything then set as textview nil and change the colour to black for user texting.

When user end editing  textViewDidEndEditing is call and check if user doesn't write anything in textview then text set as grey colour with text "PlaceHolder"

Body:
Swift 3.2

extension EditProfileVC:UITextViewDelegate{

    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.textColor == UIColor.lightGray {
            textView.text = nil
            textView.textColor = UIColor.black
       }
    }
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.isEmpty {
            textView.text = "Placeholder"
            textView.textColor = UIColor.lightGray
        }
    }
}

First when user start editing textViewDidBeginEditing call and then check the if colour of text grey means user didn't write anything then set as textview nil and change the colour to black for user texting.

When user end editing  textViewDidEndEditing is call and check if user doesn't write anything in textview then text set as grey colour with text "PlaceHolder"


答:
yes you can make use of FistOrDefault function , but it will return you null in this case when you make use of it.

```<code>Counts.btnCountViewsToday =
   db2.Query<BtnCountViews>("SELECT " + btns + "
       FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).FirstOrDefault();
if( Counts.btnCountViewsToday != null)
{
}
else
  //here i am assuming that its object type
   Counts.btnCountViewsToday =  new ViewTodayObject();
</code>```

so suggest you perform null check once you do FirstOrDefault(). if you type is value type than you need to do like this

```<code>   var count = db2.Query<BtnCountViews>("SELECT " + btns + "
           FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).FirstOrDefault();
    if( count != null)
    {}
</code>```

as you are sayin it int type than do like this

```<code>   int? count = db2.Query<BtnCountViews>("SELECT " + btns + "
           FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).FirstOrDefault();
    if( count.HasValue)
    {
          Counts.btnCountViewsToday = count.Value;
    }
    else
        Counts.btnCountViewsToday = 0;
</code>```

Title: Is there a way to have a default when a sequence contains no elements when using .first with LINQ?

Body:
yes you can make use of FistOrDefault function , but it will return you null in this case when you make use of it.

Counts.btnCountViewsToday =
   db2.Query<BtnCountViews>("SELECT " + btns + "
       FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).FirstOrDefault();
if( Counts.btnCountViewsToday != null)
{
}
else
  //here i am assuming that its object type
   Counts.btnCountViewsToday =  new ViewTodayObject();

so suggest you perform null check once you do FirstOrDefault(). if you type is value type than you need to do like this

   var count = db2.Query<BtnCountViews>("SELECT " + btns + "
           FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).FirstOrDefault();
    if( count != null)
    {}

as you are sayin it int type than do like this

   int? count = db2.Query<BtnCountViews>("SELECT " + btns + "
           FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).FirstOrDefault();
    if( count.HasValue)
    {
          Counts.btnCountViewsToday = count.Value;
    }
    else
        Counts.btnCountViewsToday = 0;


答:
You should consider using FirstOrDefault Method

```<code>   var btnCountViewsToday =
   db2.Query<BtnCountViews>("SELECT " + btns + " FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).FirstOrDefault();
</code>```

You should also consider formatting your query to avoid parameter sniffing.

When to use .First and when to use .FirstOrDefault with LINQ?

Returns the first element of a sequence, or a default value if no
  element is found.

MSDN

Body:
You should consider using FirstOrDefault Method

   var btnCountViewsToday =
   db2.Query<BtnCountViews>("SELECT " + btns + " FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd).FirstOrDefault();

You should also consider formatting your query to avoid parameter sniffing.

When to use .First and when to use .FirstOrDefault with LINQ?

Returns the first element of a sequence, or a default value if no
  element is found.

MSDN


问:
How to write this PHP regex?
I have a string of numbers surrounded by parenthesis:

```<code>(2)(56)(9)(12)(2)
</code>```

I was given the following regex by someone to split the numbers out of their parentheses:

```<code><?php

$string = '(2)(56)(9)(12)(2)';

$pattern = "/\\)\\(|\\(|\\)?/";

$numbers = preg_split($pattern, $string);

foreach ($numbers as $number) {
    echo $number.'<br />';
}

?>
</code>```

This outputs:

```<code><br />
<br />
2<br />
<br />
5<br />
6<br />
<br />
9<br />
<br />
1<br />
2<br />
<br />
2<br />
<br />
<br />
</code>```

When I really need it to output:

```<code>2<br />
56<br />
9<br />
12<br />
2<br />
</code>```

How can the regex be altered to make it work?

p.s. each number in between the parenthesis can be of an unlimited length.

答:
I would not use preg_split in the first place. If that's really your source string, then look just for numbers:</p>

```<code>preg_match_all("/\d+/", $string, $numbers);
print_r($numbers[0]);
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to write this PHP regex?

Body:
I have a string of numbers surrounded by parenthesis:

(2)(56)(9)(12)(2)

I was given the following regex by someone to split the numbers out of their parentheses:

<?php

$string = '(2)(56)(9)(12)(2)';

$pattern = "/\\)\\(|\\(|\\)?/";

$numbers = preg_split($pattern, $string);

foreach ($numbers as $number) {
    echo $number.'
';
}

?>

This outputs:

2

5

6

9

1

2

2

When I really need it to output:

2

56

9

12

2

How can the regex be altered to make it work?

p.s. each number in between the parenthesis can be of an unlimited length.

Body:
I would not use preg_split in the first place. If that's really your source string, then look just for numbers:

preg_match_all("/\d+/", $string, $numbers);
print_r($numbers[0]);


问:
ngram text to be as separate column in R

I got list of several text got from ngram, and want to add to original datatable as columns.

```<code>> prep_test
                                                                                prep_test
 1:                      Women Athletic,Athletic Apparel,Apparel Pants,Pants Tights,Tights Leggings
 2:                                                                       Beauty Makeup,Makeup Face
 3:                                                                       Beauty Makeup,Makeup Face
 4:     Electronics Cell,Cell Phones,Phones Accessories,Accessories Cases,Cases Covers,Covers Skins
 5:                                                                         Women Shoes,Shoes Boots
 6:                                                   Men Men,Men s,s Accessories,Accessories Belts
 7: Electronics Cell,Cell Phones,Phones Accessories,Accessories Cell,Cell Phones,Phones Smartphones
 8:                                                           Women Tops,Tops Blouses,Blouses Other
 9:                      Women Athletic,Athletic Apparel,Apparel Pants,Pants Tights,Tights Leggings
10:                                                Home Home,Home DÃ,DÃ cor,cor Home,Home Fragrance

str(prep_test)
Classes ‘data.table’ and 'data.frame':  10 obs. of  1 variable:
 $ prep_test:List of 10
  ..$ : chr  "Women Athletic" "Athletic Apparel" "Apparel Pants" "Pants Tights" ...
  ..$ : chr  "Beauty Makeup" "Makeup Face"
  ..$ : chr  "Beauty Makeup" "Makeup Face"
  ..$ : chr  "Electronics Cell" "Cell Phones" "Phones Accessories" "Accessories Cases" ...
  ..$ : chr  "Women Shoes" "Shoes Boots"
  ..$ : chr  "Men Men" "Men s" "s Accessories" "Accessories Belts"
  ..$ : chr  "Electronics Cell" "Cell Phones" "Phones Accessories" "Accessories Cell" ...
  ..$ : chr  "Women Tops" "Tops Blouses" "Blouses Other"
  ..$ : chr  "Women Athletic" "Athletic Apparel" "Apparel Pants" "Pants Tights" ...
  ..$ : chr  "Home Home" "Home DÃ" "DÃ cor" "cor Home" ...
 - attr(*, ".internal.selfref")=<externalptr>
</code>```

current code to generate n-gram for a column

```<code>bigram_fun <- function(y){
  y <- gsub("[[:punct:][:blank:]]+", " ", y)
  y <- ngram_asweka(y, min=2, max=2)
  #y <- str_split_fixed(y, ",", n=Inf)
  #y <- unlist(y)
  return(y)
}

prep_test <- all[1:10, 9]
prep_test <- apply(prep_test, 1, bigram_fun)
prep_test <- data.table(prep_test)
prep_test
</code>```

dput here

```<code>> dput(prep_test)
list(c("Women Athletic", "Athletic Apparel", "Apparel Pants",
"Pants Tights", "Tights Leggings"), c("Beauty Makeup", "Makeup Face"
), c("Beauty Makeup", "Makeup Face"), c("Electronics Cell", "Cell Phones",
"Phones Accessories", "Accessories Cases", "Cases Covers", "Covers Skins"
), c("Women Shoes", "Shoes Boots"), c("Men Men", "Men s", "s Accessories",
"Accessories Belts"), c("Electronics Cell", "Cell Phones", "Phones Accessories",
"Accessories Cell", "Cell Phones", "Phones Smartphones"), c("Women Tops",
"Tops Blouses", "Blouses Other"), c("Women Athletic", "Athletic Apparel",
"Apparel Pants", "Pants Tights", "Tights Leggings"), c("Home Home",
"Home DÃ", "DÃ cor", "cor Home", "Home Fragrance"))
</code>```

desired outcome

```<code>Bigram 1           Bigram 2           Bigram 3              Bigram 4     ...
"Women Athletic"   "Athletic Apparel" "Apparel Pants"      "Pants Tights"...
"Beauty Makeup"    "Makeup Face"      NA                    NA           ...
"Beauty Makeup"    "Makeup Face"      NA                    NA           ...
"Electronics Cell" "Cell Phones"      "Phones Accessories" "Accessories Cases"
"Women Shoes"      "Shoes Boots"      NA                    NA
</code>```

Appreciate any answers, and sorry for poor questions here as a newbie here

答:
This should work:

```<code>library(plyr)
df = rbind.fill(lapply(mylist,function(x) {as.data.frame(t(x))}))
colnames(df) = sapply(seq(1:ncol(df)),function(x) {paste0("Bigram ",x)})
</code>```

Output:

```<code>           Bigram 1         Bigram 2           Bigram 3          Bigram 4        Bigram 5           Bigram 6
1    Women Athletic Athletic Apparel      Apparel Pants      Pants Tights Tights Leggings               <NA>
2     Beauty Makeup      Makeup Face               <NA>              <NA>            <NA>               <NA>
3     Beauty Makeup      Makeup Face               <NA>              <NA>            <NA>               <NA>
4  Electronics Cell      Cell Phones Phones Accessories Accessories Cases    Cases Covers       Covers Skins
5       Women Shoes      Shoes Boots               <NA>              <NA>            <NA>               <NA>
6           Men Men            Men s      s Accessories Accessories Belts            <NA>               <NA>
7  Electronics Cell      Cell Phones Phones Accessories  Accessories Cell     Cell Phones Phones Smartphones
8        Women Tops     Tops Blouses      Blouses Other              <NA>            <NA>               <NA>
9    Women Athletic Athletic Apparel      Apparel Pants      Pants Tights Tights Leggings               <NA>
10        Home Home          Home DÃ             DÃ cor          cor Home  Home Fragrance               <NA>
</code>```

Hope this helps!

Body:
I got list of several text got from ngram, and want to add to original datatable as columns.

> prep_test
                                                                                prep_test
 1:                      Women Athletic,Athletic Apparel,Apparel Pants,Pants Tights,Tights Leggings
 2:                                                                       Beauty Makeup,Makeup Face
 3:                                                                       Beauty Makeup,Makeup Face
 4:     Electronics Cell,Cell Phones,Phones Accessories,Accessories Cases,Cases Covers,Covers Skins
 5:                                                                         Women Shoes,Shoes Boots
 6:                                                   Men Men,Men s,s Accessories,Accessories Belts
 7: Electronics Cell,Cell Phones,Phones Accessories,Accessories Cell,Cell Phones,Phones Smartphones
 8:                                                           Women Tops,Tops Blouses,Blouses Other
 9:                      Women Athletic,Athletic Apparel,Apparel Pants,Pants Tights,Tights Leggings
10:                                                Home Home,Home DÃ,DÃ cor,cor Home,Home Fragrance

str(prep_test)
Classes ‘data.table’ and 'data.frame':  10 obs. of  1 variable:
 $ prep_test:List of 10
  ..$ : chr  "Women Athletic" "Athletic Apparel" "Apparel Pants" "Pants Tights" ...
  ..$ : chr  "Beauty Makeup" "Makeup Face"
  ..$ : chr  "Beauty Makeup" "Makeup Face"
  ..$ : chr  "Electronics Cell" "Cell Phones" "Phones Accessories" "Accessories Cases" ...
  ..$ : chr  "Women Shoes" "Shoes Boots"
  ..$ : chr  "Men Men" "Men s" "s Accessories" "Accessories Belts"
  ..$ : chr  "Electronics Cell" "Cell Phones" "Phones Accessories" "Accessories Cell" ...
  ..$ : chr  "Women Tops" "Tops Blouses" "Blouses Other"
  ..$ : chr  "Women Athletic" "Athletic Apparel" "Apparel Pants" "Pants Tights" ...
  ..$ : chr  "Home Home" "Home DÃ" "DÃ cor" "cor Home" ...
 - attr(*, ".internal.selfref")=<externalptr>

current code to generate n-gram for a column

bigram_fun <- function(y){
  y <- gsub("[[:punct:][:blank:]]+", " ", y)
  y <- ngram_asweka(y, min=2, max=2)
  #y <- str_split_fixed(y, ",", n=Inf)
  #y <- unlist(y)
  return(y)
}

prep_test <- all[1:10, 9]
prep_test <- apply(prep_test, 1, bigram_fun)
prep_test <- data.table(prep_test)
prep_test

dput here

> dput(prep_test)
list(c("Women Athletic", "Athletic Apparel", "Apparel Pants",
"Pants Tights", "Tights Leggings"), c("Beauty Makeup", "Makeup Face"
), c("Beauty Makeup", "Makeup Face"), c("Electronics Cell", "Cell Phones",
"Phones Accessories", "Accessories Cases", "Cases Covers", "Covers Skins"
), c("Women Shoes", "Shoes Boots"), c("Men Men", "Men s", "s Accessories",
"Accessories Belts"), c("Electronics Cell", "Cell Phones", "Phones Accessories",
"Accessories Cell", "Cell Phones", "Phones Smartphones"), c("Women Tops",
"Tops Blouses", "Blouses Other"), c("Women Athletic", "Athletic Apparel",
"Apparel Pants", "Pants Tights", "Tights Leggings"), c("Home Home",
"Home DÃ", "DÃ cor", "cor Home", "Home Fragrance"))

desired outcome

Bigram 1           Bigram 2           Bigram 3              Bigram 4     ...
"Women Athletic"   "Athletic Apparel" "Apparel Pants"      "Pants Tights"...
"Beauty Makeup"    "Makeup Face"      NA                    NA           ...
"Beauty Makeup"    "Makeup Face"      NA                    NA           ...
"Electronics Cell" "Cell Phones"      "Phones Accessories" "Accessories Cases"
"Women Shoes"      "Shoes Boots"      NA                    NA

Appreciate any answers, and sorry for poor questions here as a newbie here

Body:
This should work:

library(plyr)
df = rbind.fill(lapply(mylist,function(x) {as.data.frame(t(x))}))
colnames(df) = sapply(seq(1:ncol(df)),function(x) {paste0("Bigram ",x)})

Output:

           Bigram 1         Bigram 2           Bigram 3          Bigram 4        Bigram 5           Bigram 6
1    Women Athletic Athletic Apparel      Apparel Pants      Pants Tights Tights Leggings               <NA>
2     Beauty Makeup      Makeup Face               <NA>              <NA>            <NA>               <NA>
3     Beauty Makeup      Makeup Face               <NA>              <NA>            <NA>               <NA>
4  Electronics Cell      Cell Phones Phones Accessories Accessories Cases    Cases Covers       Covers Skins
5       Women Shoes      Shoes Boots               <NA>              <NA>            <NA>               <NA>
6           Men Men            Men s      s Accessories Accessories Belts            <NA>               <NA>
7  Electronics Cell      Cell Phones Phones Accessories  Accessories Cell     Cell Phones Phones Smartphones
8        Women Tops     Tops Blouses      Blouses Other              <NA>            <NA>               <NA>
9    Women Athletic Athletic Apparel      Apparel Pants      Pants Tights Tights Leggings               <NA>
10        Home Home          Home DÃ             DÃ cor          cor Home  Home Fragrance               <NA>

Hope this helps!


问:
start docker toolbox from windows .bat file
I have installed Docker Toolbox on my Windows machine.

so when I need to start some Docker containers I:

I start the Docker terminal (which starts the Docker virtual machine

I use cd to command to go to the dir where I have some specific docker-compose.yml file

I start the container using docker-compose up -d

can I have all of this in a .bat file so I just click and don't lose time typing the same everytime I need to start the container?

答:
I tried to create a batch file starting the start.sh with full path, but that didn't work.

This worked for me: Given that Docker toolbox installed in C:\Program Files\Docker Toolbox, try the below procedure:

Put all these commands in a file called "Docker.cmd" on your desktop and run it as administrator.

```<code>cd\
cd "Program Files"
cd "Docker Toolbox"
start.sh
</code>```

Body:
I tried to create a batch file starting the start.sh with full path, but that didn't work.

This worked for me: Given that Docker toolbox installed in C:\Program Files\Docker Toolbox, try the below procedure:

Put all these commands in a file called "Docker.cmd" on your desktop and run it as administrator.

cd\
cd "Program Files"
cd "Docker Toolbox"
start.sh


问:
two different csv file data manipulation using pandas
I have two data frame df1 and df2

df1 has following data (N Rows)

```<code>  Time(s)   sv-01 sv-02 sv-03  Val1  val2  val3
   1339.4   1     4      12     1.6   0.6   1.3
   1340.4   1     12     4     -0.5  0.5   1.4
   1341.4   1     6      8      0.4   5     1.6
   1342.4   2     5     14      1.2   3.9    11
   ......           .....      ....   ...    ..
</code>```

df2 has following data which has more rows than df1

```<code>Time(msec)   channel  svid    value-1   value-2 valu-03
1000          1       2       0          5       1
1000          2       5       1          4       2
1000          3       2       3          4       7
.....         .....................................
1339400      1        1       1.6        0.4     5.3
1339400      2        12      0.5       1.8      -4.4
1339400      3        4       -0.20     1.6      -7.9
1340400      1        1      0.3       0.3      1.5
1340400      2        6      2.3      -4.3      1.0
1340400      3        4      2.0       1.1      -0.45
1341400      1       1       2         2.1      0
1341400      2       8       3.4      -0.3       1
1341400      3       6       0         4.1      2.3
....       ....      ..      ...        ...      ...
</code>```

What I am trying to achieve is

1.first multiplying Time(s) column by 1000 so that it matches with df2
millisecond column.

2.In df1 sv 01,02 and 03 are in independent column but those sv are
present in same column under svid.

So goal is when time of df1(after changing) is matching with time
of df2 copy next three consecutive lines i.e copy all matched
lines of that time instant.

Basically I want to iterate the time of df1 in df2 time column
and if there is a match copy three next rows and copy to a new df.

I have seen examples using pandas merge function but in my case both have
different header.

Thanks.

Body:
I have two data frame df1 and df2

df1 has following data (N Rows)

  Time(s)   sv-01 sv-02 sv-03  Val1  val2  val3
   1339.4   1     4      12     1.6   0.6   1.3
   1340.4   1     12     4     -0.5  0.5   1.4
   1341.4   1     6      8      0.4   5     1.6
   1342.4   2     5     14      1.2   3.9    11
   ......           .....      ....   ...    ..

df2 has following data which has more rows than df1

Time(msec)   channel  svid    value-1   value-2 valu-03
1000          1       2       0          5       1
1000          2       5       1          4       2
1000          3       2       3          4       7
.....         .....................................
1339400      1        1       1.6        0.4     5.3
1339400      2        12      0.5       1.8      -4.4
1339400      3        4       -0.20     1.6      -7.9
1340400      1        1      0.3       0.3      1.5
1340400      2        6      2.3      -4.3      1.0
1340400      3        4      2.0       1.1      -0.45
1341400      1       1       2         2.1      0
1341400      2       8       3.4      -0.3       1
1341400      3       6       0         4.1      2.3
....       ....      ..      ...        ...      ...

What I am trying to achieve is

1.first multiplying Time(s) column by 1000 so that it matches with df2
millisecond column.

2.In df1 sv 01,02 and 03 are in independent column but those sv are
present in same column under svid.

So goal is when time of df1(after changing) is matching with time
of df2 copy next three consecutive lines i.e copy all matched
lines of that time instant.

Basically I want to iterate the time of df1 in df2 time column
and if there is a match copy three next rows and copy to a new df.

I have seen examples using pandas merge function but in my case both have
different header.

Thanks.

Body:
I think you need double boolean indexing - first df2 with isin, for multiple is used mul:

And then count values per groups by cumcount and filter first 3:

df = df2[df2['Time(msec)'].isin(df1['Time(s)'].mul(1000))]
df = df[df.groupby('Time(msec)').cumcount() < 3]
print (df)
    Time(msec)  channel  svid  value-1  value-2  valu-03
3      1339400        1     1      1.6      0.4     5.30
4      1339400        2    12      0.5      1.8    -4.40
5      1339400        3     4     -0.2      1.6    -7.90
6      1340400        1     1      0.3      0.3     1.50
7      1340400        2     6      2.3     -4.3     1.00
8      1340400        3     4      2.0      1.1    -0.45
9      1341400        1     1      2.0      2.1     0.00
10     1341400        2     8      3.4     -0.3     1.00
11     1341400        3     6      0.0      4.1     2.30

Detail:

print (df.groupby('Time(msec)').cumcount())
3     0
4     1
5     2
6     0
7     1
8     2
9     0
10    1
11    2
dtype: int64


问:
In AngularJS, why isn't a $scope variable accessible from a simple function?
My code is as shown below:

```<code>angular.module('xyz', [])
    .controller('listController', ['$scope',
        function($scope) {
            $scope.deliveryOptions = 0;
            var vm = this;

            function doTransaction() {
                console.log('delivery options is ' + vm.$scope.deliveryOptions);
            }
        }
    ]);
</code>```

Here inside console.log(delivery options), it gives me error that it is Unable to get property 'deliveryOptions' of undefined or null reference. So how can I access that variable?

答:
Use either $scope or controller as, not both

The primary issue is you're mixing original AngularJS 1.x $scope usage, with the controller as design pattern that uses vm (meaning "view model"), which started with Angular 1.5.

You need to pick one or the other, and then your code will work just fine.

If you go with the cleaner and less error-prone vm and controller as design pattern, you simply use vm rather than $scope:

```<code>angular.module('xyz', [])
    .controller('listController', function() {
        var vm = this
        vm.deliveryOptions = 0
        vm.doTransaction = function() {
            console.log('delivery options is ' + vm.deliveryOptions)
        }
     })
</code>```

And then in your view, you use vm.doTransaction() to call your function and display your variable.

Body:
My code is as shown below:

angular.module('xyz', [])
    .controller('listController', ['$scope',
        function($scope) {
            $scope.deliveryOptions = 0;
            var vm = this;

            function doTransaction() {
                console.log('delivery options is ' + vm.$scope.deliveryOptions);
            }
        }
    ]);

Here inside console.log(delivery options), it gives me error that it is Unable to get property 'deliveryOptions' of undefined or null reference. So how can I access that variable?

Body:
Use either $scope or controller as, not both

The primary issue is you're mixing original AngularJS 1.x $scope usage, with the controller as design pattern that uses vm (meaning "view model"), which started with Angular 1.5.

You need to pick one or the other, and then your code will work just fine.

If you go with the cleaner and less error-prone vm and controller as design pattern, you simply use vm rather than $scope:

angular.module('xyz', [])
    .controller('listController', function() {
        var vm = this
        vm.deliveryOptions = 0
        vm.doTransaction = function() {
            console.log('delivery options is ' + vm.deliveryOptions)
        }
     })

And then in your view, you use vm.doTransaction() to call your function and display your variable.


问:
Navigation bar with UIImage for title
I want to customize my app's look by using a logo image as the navigation bar's title, instead of plain text. When I use this code

```<code>let logo = UIImage(named: "logo.png")
self.navigationItem.titleView = logo;
</code>```

I get the error "UIImage is not convertible to UIView". How can I do this correctly?

答:
For swift 4 and you can adjust imageView size </p>

```<code> let logoContainer = UIView(frame: CGRect(x: 0, y: 0, width: 270, height: 30))

 let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 270, height: 30))
 imageView.contentMode = .scaleAspectFit
 let image = UIImage(named: "your_image")
 imageView.image = image
 logoContainer.addSubview(imageView)
 navigationItem.titleView = logoContainer
</code>```

Title: Navigation bar with UIImage for title

Body:
I want to customize my app's look by using a logo image as the navigation bar's title, instead of plain text. When I use this code

let logo = UIImage(named: "logo.png")
self.navigationItem.titleView = logo;

I get the error "UIImage is not convertible to UIView". How can I do this correctly?

Body:
For swift 4 and you can adjust imageView size

 let logoContainer = UIView(frame: CGRect(x: 0, y: 0, width: 270, height: 30))

 let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 270, height: 30))
 imageView.contentMode = .scaleAspectFit
 let image = UIImage(named: "your_image")
 imageView.image = image
 logoContainer.addSubview(imageView)
 navigationItem.titleView = logoContainer


问:
How can i get values from $stateChanges
Please Helpme How can i get values from $statechangeStart and $stateChaneSuccess

MyApp.js

```<code>app.run(function ($rootScope) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
          $scope.IsLoading = true;

    })
    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams, options) {
           $scope.IsLoading = False;
    })
})
</code>```

Home.js

///Here How can i use IsLoading

答:
Because you are adding this logic in the run function, you'll want to set the isLoading property on the $rootScope object, not the $scope object, which does not exist in this context:

```<code>app.run(function ($rootScope) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
        $rootScope.isLoading = true;

    });
    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams, options) {
        $rootScope.isLoading = false;
    });
});
</code>```

Then, in your template that has access to $rootScope, you can show a loading screen by using ngIf, which conditionally adds elements to the DOM:

```<code><div ng-if="isLoading" class="loading-screen">
    Loading...
</div>
</code>```

Title: How can i get values from $stateChanges

Body:
Please Helpme How can i get values from $statechangeStart and $stateChaneSuccess

MyApp.js

app.run(function ($rootScope) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
          $scope.IsLoading = true;

    })
    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams, options) {
           $scope.IsLoading = False;
    })
})

Home.js

///Here How can i use IsLoading

Body:
Because you are adding this logic in the run function, you'll want to set the isLoading property on the $rootScope object, not the $scope object, which does not exist in this context:

app.run(function ($rootScope) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
        $rootScope.isLoading = true;

    });
    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams, options) {
        $rootScope.isLoading = false;
    });
});

Then, in your template that has access to $rootScope, you can show a loading screen by using ngIf, which conditionally adds elements to the DOM:

<div ng-if="isLoading" class="loading-screen">
    Loading...
</div>


问:
Instant App, What's the actual minimum sdk
As per the android developers site, minimum sdk for Instant app is 21, ie 5.0.
link

The site clearly  states : Android Instant Apps are available on the majority of devices running Android 5.0 (API level 21) and higher.

But when we create a new project as per the guideline given in this link
which states that we need to have minimum sdk of 23, to get instant app support.

And does not allow me to create a support for 5.0.

as shown in below image which I tried :

答:
That requirement exists only in the setup wizard, and it is a bug. If you change the value to something lower after creating the project, you'll see that it builds fine and can run on API 21 and 22 devices.

The documentation is correct about supported Android versions, but note that even that doesn't dictate any particular minSdkVersion. You can build an instant app with a minSdkVersion lower than 21. It just won't run on anything before 21, since the Instant Apps Runtime itself is restricted to 21+.

For that reason, this check was always a bug, even when we didn't support devices before 23. I was told it was fixed in 3.0,  though I didn't verify. I checked tonight and confirmed that the check is still present in 3.0. Could be fixed in a more recent version. But if not, we need to fix that. I'll follow up.


问:
Can we Integrate Gulp or Grunt with Magento 1.13.1.0? Trying to Optimize css, js and images
Can we Integrate Gulp or Grunt with Magento 1.13.1.0? Trying to Optimize css, js and images. There is no plugin in Magento 1.13.1.0 version but could there be any other ways to integrate it.

Appreciate your help and suggestions!

答:
If you need to build a theme from scratch with grunt capabilities, then you can easily build it using a yeoman through npm. Yeoman is a web scaffolding tool so you don't have to do the hard work of installing all details.

Step 1:

install node js see link

Step 2:

```<code>npm install -g yo
</code>```

Step 3:

```<code>npm install -g generator-grunt-magento
</code>```

Step 4:

```<code>yo grunt-magento
</code>```

More Details from here.

Another possible solution is to create the grunt structure on an existing theme. This is something that we cannot generalize so it really depends on the theme you have and how you wan't it to be implemented.

Body:
If you need to build a theme from scratch with grunt capabilities, then you can easily build it using a yeoman through npm. Yeoman is a web scaffolding tool so you don't have to do the hard work of installing all details.

Step 1:

install node js see link

Step 2:

npm install -g yo

Step 3:

npm install -g generator-grunt-magento

Step 4:

yo grunt-magento

More Details from here.

Another possible solution is to create the grunt structure on an existing theme. This is something that we cannot generalize so it really depends on the theme you have and how you wan't it to be implemented.


问:
Zooming in / out in Neatbeans?
Is there a way to zoom in / out while in debug mode?
I know about alt+scroll option but this does not work when debugging for the lower console where you actually get to see what is happening (i think its called variables tab).
Thanks

答:
The short answer is no, it is not possible. Unlike windows containing pure text, dynamically zooming in/out in debugging windows such as Variables and Watches is not supported in NetBeans. The same is true in Eclipse.

Presumably this is because those windows are interactive, and contain more than just text (tree structures, icons, input fields, etc.).

That said, you can specify the font size for the entire IDE itself when starting NetBeans, and that would increase/decrease the font size in the Variables window accordingly. For example, to set the IDE's font size to 16, just add the parameter --fontsize 16 to your call to run NetBeans. (I realize that you specifically want to be able to zoom in/out freely, but thought it worth mentioning just in case you were desperate to modify the font size in the Variables window. See http://wiki.netbeans.org/FaqFontSize for details.)

Title: Zooming in / out in Neatbeans?


问:
Issues playing a video with MonoTouch
I'm having a few issues playing a video in MonoTouch. From what I can find there are two different approaches to take. Both result in the audio being played but no video. I'm betting I'm missing something simple so any help would be great.

Attempt one - taken from MT documentation

```<code>moviePlayer = new MPMoviePlayerController(new NSUrl("test.mp4"));
moviePlayer.Play();
</code>```

Attempt two

```<code>moviePlayer = new MPMoviePlayerViewController(new NSUrl("test.mp4"));
this.PresentMoviePlayerViewController(moviePlayer);
</code>```

Thanks

答:
From looking at the documentation, you need to add the MPMoviePlayerController to a view, otherwise the video will no know where to play.

Your second attempt looks a little better, are you calling the play method on the moviePlayer (note this is a MPMoviePlayerViewController) MPMoviePlayerController (named MoviePlayer)?

For what it's worth, I can get;

```<code>moviePlayerController = new MPMoviePlayerViewController(new NSUrl("test.mp4"));
this.PresentMoviePlayerViewController(moviePlayerController);
</code>```

working with no issues on a sample iPad app. Are you sure your test.mp4 is...

Encoded correctly

Included in the project

Video's build action is set to content

Documentation for MPMoviePlayerController: http://developer.apple.com/library/ios/#documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/MPMoviePlayerController/MPMoviePlayerController.html

Documentation for MPMoviewPlayerViewController:
http://developer.apple.com/library/ios/#documentation/MediaPlayer/Reference/MPMoviePlayerViewController_class/Reference/Reference.html#//apple_ref/occ/cl/MPMoviePlayerViewController

Title: Issues playing a video with MonoTouch

Body:
I'm having a few issues playing a video in MonoTouch. From what I can find there are two different approaches to take. Both result in the audio being played but no video. I'm betting I'm missing something simple so any help would be great.

Attempt one - taken from MT documentation

moviePlayer = new MPMoviePlayerController(new NSUrl("test.mp4"));
moviePlayer.Play();

Attempt two

moviePlayer = new MPMoviePlayerViewController(new NSUrl("test.mp4"));
this.PresentMoviePlayerViewController(moviePlayer);

Thanks

Body:
From looking at the documentation, you need to add the MPMoviePlayerController to a view, otherwise the video will no know where to play.

Your second attempt looks a little better, are you calling the play method on the moviePlayer (note this is a MPMoviePlayerViewController) MPMoviePlayerController (named MoviePlayer)?

For what it's worth, I can get;

moviePlayerController = new MPMoviePlayerViewController(new NSUrl("test.mp4"));
this.PresentMoviePlayerViewController(moviePlayerController);

working with no issues on a sample iPad app. Are you sure your test.mp4 is...

Encoded correctly

Included in the project

Video's build action is set to content

Documentation for MPMoviePlayerController: http://developer.apple.com/library/ios/#documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/MPMoviePlayerController/MPMoviePlayerController.html

Documentation for MPMoviewPlayerViewController:
http://developer.apple.com/library/ios/#documentation/MediaPlayer/Reference/MPMoviePlayerViewController_class/Reference/Reference.html#//apple_ref/occ/cl/MPMoviePlayerViewController


问:
PyQt5: create multiple views with designer and connect them in one app
I have completed a simple app in PyQt5, where I did design the UI in QT designer, converted in py code with pyuic5and ran it via python interpreter.

Now I would like to add another UI view, although I am not familiar with PyQt5, and most of the tutorial I found are only mentioning one view.
If I was using Visual Studio for example, I could create a new form, and use show and hide methods to display them, when I press a button for example, but I am not sure how to do the same with PyQt5.

Converted code from pyuic5 include also the if __name__ == "__main__" function, which create the instance and run the app, so is it enough to just take anything above it, to get the UI data only? And how do I create a view from that, so I can show and hide it as needed? Thanks.

EDIT:
Got a bit further, since I found a different way to load UI files. Seems that PyQt has a method that is able to load a UI file directly, instead of convert it in python code. This means that I can create a class that is a subclass of the type of window that I am using (example: QApplication, QMainWindow, QWidget and so on), and I can access that object as if it was a form in Visual Studio.

```<code>from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow
from PyQt5.uic import loadUI

class UIObject(QMainWindow):

    def __init__(self):
        super(UIObject, self).__init__()
        loadUI('mainapp.ui', self)
        self.mybutton1.clicked.connect(self.printhello)

    def printhello():
        print("hello")

app = QApplication(sys.argv)
mainview = UIObject()
mainview.show()
sys.exit(app.exec_())
</code>```

This will load the UI file and show it on screen; I assume that I can use the same construct to load multiple ui files and show then or hide them as I do in Visual studio? Seems straightforward but not knowing much about QT or PyQT, I am not sure why this way to handle ui files is not more commonly advertised in tutorials; I found it by chance while reading the docs.

答:
Found the solution, mixing up various answers and posts from different forums.

You create a first class as QMainWindow, in the __init__ you use loadUi to load the QT designer file. Then you create a second class, which is the one that hold your second form/view, and in the __init__ you pass as parameter the parent view (your first class, or whatever other you may need); so you can hide the main view and show the second view when clicking a button. When you close the secondary view, the previous view will show up again.

You can add as many different windows you want; the trick is to always pass the parent on each of them and remember to show/hide them accordingly. Much more complex than Visual Studio forms, but it is doable.

```<code>class FirstForm(QMainWindow):

    def __init__(self):
        super(FirstForm, self).__init__()
        loadUi('firstform.ui', self)
        self.button1.clicked.connect(self.openOtherForm)

    def openOtherForm(self):
        self.hide()
        otherview = SecondForm(self)
        otherview.show()

class SecondForm(QDialog):

    def __init__(self, parent=None):
        super(SecondForm, self).__init__(parent)
        loadUi('secondform.ui', self)
        self.button2.clicked.connect(self.goBackToOtherForm)

    def openOtherForm(self):
        self.parent().show()
        self.close()

app = QApplication(sys.argv)
main = FirstForm()
main.show()
sys.exit(app.exec_())
</code>```

Body:
I have completed a simple app in PyQt5, where I did design the UI in QT designer, converted in py code with pyuic5and ran it via python interpreter.

Now I would like to add another UI view, although I am not familiar with PyQt5, and most of the tutorial I found are only mentioning one view.
If I was using Visual Studio for example, I could create a new form, and use show and hide methods to display them, when I press a button for example, but I am not sure how to do the same with PyQt5.

Converted code from pyuic5 include also the if __name__ == "__main__" function, which create the instance and run the app, so is it enough to just take anything above it, to get the UI data only? And how do I create a view from that, so I can show and hide it as needed? Thanks.

EDIT:
Got a bit further, since I found a different way to load UI files. Seems that PyQt has a method that is able to load a UI file directly, instead of convert it in python code. This means that I can create a class that is a subclass of the type of window that I am using (example: QApplication, QMainWindow, QWidget and so on), and I can access that object as if it was a form in Visual Studio.

from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow
from PyQt5.uic import loadUI

class UIObject(QMainWindow):

    def __init__(self):
        super(UIObject, self).__init__()
        loadUI('mainapp.ui', self)
        self.mybutton1.clicked.connect(self.printhello)

    def printhello():
        print("hello")

app = QApplication(sys.argv)
mainview = UIObject()
mainview.show()
sys.exit(app.exec_())

This will load the UI file and show it on screen; I assume that I can use the same construct to load multiple ui files and show then or hide them as I do in Visual studio? Seems straightforward but not knowing much about QT or PyQT, I am not sure why this way to handle ui files is not more commonly advertised in tutorials; I found it by chance while reading the docs.

Body:
Found the solution, mixing up various answers and posts from different forums.

You create a first class as QMainWindow, in the __init__ you use loadUi to load the QT designer file. Then you create a second class, which is the one that hold your second form/view, and in the __init__ you pass as parameter the parent view (your first class, or whatever other you may need); so you can hide the main view and show the second view when clicking a button. When you close the secondary view, the previous view will show up again.

You can add as many different windows you want; the trick is to always pass the parent on each of them and remember to show/hide them accordingly. Much more complex than Visual Studio forms, but it is doable.

class FirstForm(QMainWindow):

    def __init__(self):
        super(FirstForm, self).__init__()
        loadUi('firstform.ui', self)
        self.button1.clicked.connect(self.openOtherForm)

    def openOtherForm(self):
        self.hide()
        otherview = SecondForm(self)
        otherview.show()

class SecondForm(QDialog):

    def __init__(self, parent=None):
        super(SecondForm, self).__init__(parent)
        loadUi('secondform.ui', self)
        self.button2.clicked.connect(self.goBackToOtherForm)

    def openOtherForm(self):
        self.parent().show()
        self.close()

app = QApplication(sys.argv)
main = FirstForm()
main.show()
sys.exit(app.exec_())


问:
Recursively find ".sh" file and then execute my .sh file on that path
I have a folder which contains sub sub folders and some folders contains .sh file. I want to execute my .sh file in that path where I see a .sh file. I tried

```<code>find . -name '*.sh'
./folder 1/folder 2/run.sh
./folder3/run.sh
./folder 4/run.sh
./folder5/run.sh
</code>```

This find function is working correctly. Now I have another .sh file which I want to execute on .sh file path. I tried

```<code>find . -name '*.sh' /home/cool/Desktop/followup.sh {} ;
</code>```

where followup.sh is my file. The command is getting executed at current directory . but it is not getting executed on run.sh file path.

I am new to bash scripting. What command or commands would I issue? Note that there are spaces in Folder name.

答:
```<code>find <parent-directory where all sub-folders with run.sh are located> -name '*.sh' -execdir /home/cool/Desktop/followup.sh {} \;
</code>```

Body:
I have a folder which contains sub sub folders and some folders contains .sh file. I want to execute my .sh file in that path where I see a .sh file. I tried

find . -name '*.sh'
./folder 1/folder 2/run.sh
./folder3/run.sh
./folder 4/run.sh
./folder5/run.sh

This find function is working correctly. Now I have another .sh file which I want to execute on .sh file path. I tried

find . -name '*.sh' /home/cool/Desktop/followup.sh {} ;

where followup.sh is my file. The command is getting executed at current directory . but it is not getting executed on run.sh file path.

I am new to bash scripting. What command or commands would I issue? Note that there are spaces in Folder name.


问:
MongoDB documents combination
I have the collection with document structure like this:

```<code>{
"_id" : "Host CPU Utilization (%)",
"count" : 1,
"avg" : NumberDecimal("20.2397439956"),
"flaga" : 4
},
{
"_id" : "Active Sessions Using CPU",
"count" : 1,
"avg" : NumberDecimal("4.0580000000"),
"flaga" : 4
},
 {
"_id" : "Wait Time (%)",
"count" : 1,
"avg" : NumberDecimal("1795.2150000000"),
"flaga" : 999
}
</code>```

Is that possible to use pymongo changing data like:

```<code>{
"_id" : 4,
"Host CPU Utilization (%)" : NumberDecimal("20.2397439956"),
"Active Sessions Using CPU" : NumberDecimal("4.0580000000")
},
{
"_id" : 999,
"Wait Time (%)" : NumberDecimal("1795.2150000000"),
}
</code>```

I have tried to use update commend  rename but can't do it dynamically and can't combine two documents into one. If I use aggregation framework, I don't know how to $put documents with variable field name.

答:
Since version 3.4 we have $arrayToObject operator which might be helpful. You can try grouping by flaga field and then using mentioned operator.

```<code>db.myCollection.aggregate([
    {
        $group: {
            "_id": "$flaga",
            "values": {
                "$push": {
                    "k": "$_id",
                    "v": "$avg"
                }
            }
        }
    },
    {
        $project: {
            "_id": 1,
            "values": { $arrayToObject: "$values" }
        }
    }
])
</code>```

This will give you results like:

```<code>{
   "_id":4,
   "values":{
      "Host CPU Utilization (%)":NumberDecimal("20.2397439956"),
      "Active Sessions Using CPU":NumberDecimal("4.0580000000")
   }
}
</code>```

You can add next pipeline stage with $replaceRoot to get rid of this nesting but unfortunately you'll loose _id field and I bet it's not what you're looking for, so probably you should perform this post-processing in your business logic code.

Title: MongoDB documents combination

Body:
I have the collection with document structure like this:

{
"_id" : "Host CPU Utilization (%)",
"count" : 1,
"avg" : NumberDecimal("20.2397439956"),
"flaga" : 4
},
{
"_id" : "Active Sessions Using CPU",
"count" : 1,
"avg" : NumberDecimal("4.0580000000"),
"flaga" : 4
},
 {
"_id" : "Wait Time (%)",
"count" : 1,
"avg" : NumberDecimal("1795.2150000000"),
"flaga" : 999
}

Is that possible to use pymongo changing data like:

{
"_id" : 4,
"Host CPU Utilization (%)" : NumberDecimal("20.2397439956"),
"Active Sessions Using CPU" : NumberDecimal("4.0580000000")
},
{
"_id" : 999,
"Wait Time (%)" : NumberDecimal("1795.2150000000"),
}

I have tried to use update commend  rename but can't do it dynamically and can't combine two documents into one. If I use aggregation framework, I don't know how to $put documents with variable field name.

Body:
Since version 3.4 we have $arrayToObject operator which might be helpful. You can try grouping by flaga field and then using mentioned operator.

db.myCollection.aggregate([
    {
        $group: {
            "_id": "$flaga",
            "values": {
                "$push": {
                    "k": "$_id",
                    "v": "$avg"
                }
            }
        }
    },
    {
        $project: {
            "_id": 1,
            "values": { $arrayToObject: "$values" }
        }
    }
])

This will give you results like:

{
   "_id":4,
   "values":{
      "Host CPU Utilization (%)":NumberDecimal("20.2397439956"),
      "Active Sessions Using CPU":NumberDecimal("4.0580000000")
   }
}

You can add next pipeline stage with $replaceRoot to get rid of this nesting but unfortunately you'll loose _id field and I bet it's not what you're looking for, so probably you should perform this post-processing in your business logic code.


问:
How to pass an argument in href?
I want to pass the query string value in href as an argument while I render the page.I tried:
<button type="button" class="btn btn-primary btn-xs">Add</button>

I use a tornado framework and the python script is:

```<code>class Room(tornado.web.RequestHandler):
    def get(self):
        nw=Test
        self.render("Room.html",nw=nw)
</code>```

But the query string does not take the value "Test" it gives "/room?nw=" as the URL.i.e. without the value Test.Any help would be appreciated.

答:
Please try with {{}},

```<code><a href="/room?nw={{nw}}"><button type="button" class="btn btn-primary btn-xs">Add</button></a>
</code>```

http://www.tornadoweb.org/en/stable/guide/templates.html

Title: How to pass an argument in href?

Body:
I want to pass the query string value in href as an argument while I render the page.I tried:
<button type="button" class="btn btn-primary btn-xs">Add</button>

I use a tornado framework and the python script is:

class Room(tornado.web.RequestHandler):
    def get(self):
        nw=Test
        self.render("Room.html",nw=nw)

But the query string does not take the value "Test" it gives "/room?nw=" as the URL.i.e. without the value Test.Any help would be appreciated.

Body:
Please try with {{}},

<a href="/room?nw={{nw}}"><button type="button" class="btn btn-primary btn-xs">Add</button></a>

http://www.tornadoweb.org/en/stable/guide/templates.html


问:
How to take a screenshot of specific part of webpage just like Firefox screenshot not using HTML canvas?
I need to have a cursor to drag and take screenshot of dragged area on HTML webpage. I tried using HTML canvas but it takes screenshot of specific div not the selected region on HTML webpage.

答:
The new html2canvas version 1 has width, height, x and y options.

You can make use of these options to achieve a cropping feature the Firefox's Screenshot's way.

document.onmousedown = startDrag;
document.onmouseup = endDrag;
document.onmousemove = expandDrag;

var dragging = false,
  dragStart = {
    x: 0,
    y: 0
  },
  dragEnd = {
    x: 0,
    y: 0
  };

function updateDragger() {
  dragger.classList.add('visible');
  var s = dragger.style;
  s.top = Math.min(dragStart.y, dragEnd.y) + 'px';
  s.left = Math.min(dragStart.x, dragEnd.x) + 'px';
  s.height = Math.abs(dragStart.y - dragEnd.y) + 'px';
  s.width = Math.abs(dragStart.x - dragEnd.x) + 'px';
}

function startDrag(evt) {
  evt.preventDefault();
  dragging = true;
  dragStart.x = dragEnd.x = evt.clientX;
  dragStart.y = dragEnd.y = evt.clientY;
  updateDragger();
}

function expandDrag(evt) {
  if (!dragging) return;
  dragEnd.x = evt.clientX;
  dragEnd.y = evt.clientY;
  updateDragger();
}

function endDrag(evt) {
  dragging = false;
  dragger.classList.remove('visible');
  // here is the important part
  html2canvas(document.body, {
      width: Math.abs(dragStart.x - dragEnd.x),
      height: Math.abs(dragStart.y - dragEnd.y),
      x: Math.min(dragStart.x, dragEnd.x),
      y: Math.min(dragStart.y, dragEnd.y)
    })
    .then(function(c) {
      document.body.appendChild(c);
    });
  dragStart.x = dragStart.y = dragEnd.x = dragEnd.y = 0;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  user-select: none;
}

#dragger {
  position: fixed;
  background: rgba(0, 0, 0, .5);
  border: 1px dashed white;
  pointer-events: none;
  display: none;
}

#dragger.visible {
  display: block;
}

canvas {
  border: 1px solid;
}</code>```

 Drag to take a screenshot ...

```

Body:
The new html2canvas version 1 has width, height, x and y options.

You can make use of these options to achieve a cropping feature the Firefox's Screenshot's way.

document.onmousedown = startDrag;
document.onmouseup = endDrag;
document.onmousemove = expandDrag;

var dragging = false,
  dragStart = {
    x: 0,
    y: 0
  },
  dragEnd = {
    x: 0,
    y: 0
  };

function updateDragger() {
  dragger.classList.add('visible');
  var s = dragger.style;
  s.top = Math.min(dragStart.y, dragEnd.y) + 'px';
  s.left = Math.min(dragStart.x, dragEnd.x) + 'px';
  s.height = Math.abs(dragStart.y - dragEnd.y) + 'px';
  s.width = Math.abs(dragStart.x - dragEnd.x) + 'px';
}

function startDrag(evt) {
  evt.preventDefault();
  dragging = true;
  dragStart.x = dragEnd.x = evt.clientX;
  dragStart.y = dragEnd.y = evt.clientY;
  updateDragger();
}

function expandDrag(evt) {
  if (!dragging) return;
  dragEnd.x = evt.clientX;
  dragEnd.y = evt.clientY;
  updateDragger();
}

function endDrag(evt) {
  dragging = false;
  dragger.classList.remove('visible');
  // here is the important part
  html2canvas(document.body, {
      width: Math.abs(dragStart.x - dragEnd.x),
      height: Math.abs(dragStart.y - dragEnd.y),
      x: Math.min(dragStart.x, dragEnd.x),
      y: Math.min(dragStart.y, dragEnd.y)
    })
    .then(function(c) {
      document.body.appendChild(c);
    });
  dragStart.x = dragStart.y = dragEnd.x = dragEnd.y = 0;
}

* {
  user-select: none;
}

#dragger {
  position: fixed;
  background: rgba(0, 0, 0, .5);
  border: 1px dashed white;
  pointer-events: none;
  display: none;
}

#dragger.visible {
  display: block;
}

canvas {
  border: 1px solid;
}

<script src="https://github.com/niklasvh/html2canvas/releases/download/v1.0.0-alpha.1/html2canvas.js"></script>
<div id="wrapper">
  <p> Drag to take a screenshot ...</p>
  <img crossOrigin src="https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png" width="120" height="120">
</div>

<div id="dragger" tabindex></div>