text:
Q: I have a UICollectionView and i want to show an image in a Cell, that goes to a normal ViewController. How do i do that? I have a UICollectionViewController (with a navigation controller) and i want to show an image in a Cell that 'pushes' to a normal ViewController (different by every image). How do i do that?

A: Seem you want to build photo gallery by UICollectionView.
If use storyBoard, use segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showDetail"])
    {
        NSIndexPath *selectedIndexPath = [[self.collectionView indexPathsForSelectedItems] objectAtIndex:0];

        // load the image, to prevent it from being cached we use 'initWithContentsOfFile'
        NSString *imageNameToLoad = [NSString stringWithFormat:@"%d_full", selectedIndexPath.row];
        NSString *pathToImage = [[NSBundle mainBundle] pathForResource:imageNameToLoad ofType:@"JPG"];
        UIImage *image = [[UIImage alloc] initWithContentsOfFile:pathToImage];

        DetailViewController *detailViewController = [segue destinationViewController];
        detailViewController.image = image;
    }
}

If use nib: inside didSelectItemAtIndexPath, use self.navigationController push.
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *imageNameToLoad = [NSString stringWithFormat:@"%d_full", indexPath.row];
    NSString *pathToImage = [[NSBundle mainBundle] pathForResource:imageNameToLoad ofType:@"JPG"];
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:pathToImage];
    DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    detailViewController.image = image;
    [self.navigationController pushViewController:detailViewController animated:YES];
}

Sample code from Apple:
https://developer.apple.com/library/ios/#samplecode/CollectionView-Simple/Introduction/Intro.html
CollecionView tutorial: http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12


text:
Q: Failed to install metrics-server on minikube I am trying to install metrics-server on my Kubernetes cluster. But it is not going to READY mode.
I am was installed metrics-server in this method
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

After installing i was tried some of those commands, kubectl top pods, kubectl top nodes. But i got an error
Error from server (ServiceUnavailable): the server is currently unable to handle the request (get pods.metrics.k8s.io)
Metrics server is failed to start

A: Enable metrics-server addon in minikube cluster.
Try the following commend.
minikube addons enable metrics-server

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting user input and chopping it up into a struct to be passe back for execvp So what I am trying to do essentially is get user input. The user types a command maybe something like command arg1 arg2 arg3. So I made a struct to hold the base command command and an arguments pointer to a pointer of a char to hold the argument arg1 arg2 arg3 as well as a count to hold the arg count.
In main I get user input with fgets which I then take in and pass to my splitCommand function. The splitCommand function takes the char* which is the full command with args. It then uses strtok to chop it up and stores it into a struct, passing the struct back to main.
The problem I have is that when i run it, and if i type command arg1 arg2 it prints out command arg1 (null). So I can't tell if I am just confused and referencing the arguments part of the struct wrong, or if I am not copying the arguments properly into the struct.
Any help or point in the right direction as to what I am doing wrong would be greatly appreciated.
Thank you in advanced.
struct Command
{
  char *base;
  char **arguments; //array of pointers
  int count;
};

//Takes a commands string and splits by spaces, returning a string array, including command
struct Command splitCommand(char *cmd)
{
  char *cmdArgs[MAXARGS];

  char *cmd_token = strtok(cmd, " "); //set pointer to first space
  cmd_token = strtok(NULL, " ");      //Chop off first command
  char *cmdFirst = strtok(cmd, " ");  //First command
  int totalArgs = 0;                  //argument counter
  struct Command retCommand;          //command struct
  retCommand.base = cmdFirst;

  //Loop through and get all args
  for (int i = 0; i < MAXARGS; i++)
  {
    if (cmd_token != NULL)
    {
      totalArgs++;
      cmdArgs[i] = cmd_token;
      cmd_token = strtok(NULL, " ");
    }
  }

  retCommand.arguments = cmdArgs;
  retCommand.count = totalArgs;
  return retCommand;
}

//MAIN
int main(int argc, char const *argv[])
{
  //String Array and memory allocation
  char *userCommands[MAXCMDS];
  for (int i = 0; i < MAXCMDS; i++)
  {
    userCommands[i] = malloc(MAXIN);
  }

  //Command 1
  printf("Welcome to MASH!\nmash-1>");
  fgets(userCommands[0], MAXIN, stdin);
  struct Command cmd1 = splitCommand(userCommands[0]);
  printf("%s ", cmd1.base);
  printf("%s ", cmd1.arguments[0]);
  printf("%s ", cmd1.arguments[1]);
  return 0;
}

A: You're using strtok in an unintended manner. You must call it exactly once with cmdString for its first parameter to get the first token, then all successive calls with NULL to get the rest.
Additionally, your code does not compile. When posting to SO, you should always provide code that at least compiles with no errors.
Here is your code hacked up to work as (I think) you intended.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXARGS 256
#define MAXIN 4096

struct Command {
  char *cmdLine; // copy of command line; base and arguments point here
  char *base;
  char **arguments;
  int argCount;
};

struct Command parseCommand(char *cmdLine)
{
  char *cmdArgs[MAXARGS];
  struct Command cmd;
  cmd.cmdLine = strdup(cmdLine);
  cmd.base = strtok(cmd.cmdLine, " ");
  cmd.argCount = 0;
  for (char *arg = strtok(NULL, " "); arg; arg = strtok(NULL, " "))
    cmdArgs[cmd.argCount++] = arg;
  cmd.arguments = malloc(cmd.argCount * sizeof *cmd.arguments);
  memcpy(cmd.arguments, cmdArgs, cmd.argCount * sizeof *cmd.arguments);
  return cmd;
}

int main(int argc, char const *argv[])
{
  char buf[MAXIN];
  printf("Welcome to MASH!\nmash-1>");
  fgets(buf, MAXIN, stdin);
  struct Command cmd = parseCommand(buf);
  printf("Command (%d args): %s", cmd.argCount, cmd.base);
  for (int i = 0; i < cmd.argCount; ++i) printf(" %s", cmd.arguments[i]);
  printf("\n");
  return 0;
}


text:
Q: Maximize $ax + by + c$ Working on a problem of comparative advantage of the economist David Ricardo, I've gone into solving a more general case of that study in which I stumbled over this question : how do we maximize the quantity $P = ax + by + c$, given that $a, b$ and $c$ are all known and $x, y$ are variables confined to the interval $[ 0,T] $.

In short, my query is : Determine $(x,y) \in [0,T]^2$ such that $(ax + by + c)$ is maximal, with $(a,b,c) \in \mathbb{R}^3$, all of which are known.
Thank you !

A: Assuming $a, b \neq 0$, use these four statements to get the maximum:
If $a$ is negative, $x=0$.
If $a$ is positive, $x=T$.
If $b$ is negative, $y=0$.
If $b$ is positive, $y=T$.
"Do. Or do not. There is no try."  ~Yoda


text:
Q: $F_N(t)=\int_{-1/N}^0\overline{f}(t+h)dh$ implies $\|F_N\|_{L^2((0,T); X)}\leq\|f\|_{L^2((0,T); X)}$? Let $f\in L^2((0,T); X)$ where $X$ is a Banach space and $0<T<\infty$. Define $F_N: \mathbb{R}\to X$ by $$F_N(t)=\int_{-1/N}^0\overline{f}(t+h)dh$$
where $\overline{f}$ is the extension by $0$ of $f$ outside $(0,T)$. How can I prove that $$\|F_N\|_{L^2((0,T); X)}\leq\|f\|_{L^2((0,T); X)}$$
Remark: The integral above is the Bochner integral and $$\|u\|_{L^2((0,T); X)}=\left(\int_0^T\|u(t)\|_X^2\right)^{1/2}$$
Remark 1: By aaplying some simple inequalities, I was able to reach in the following inequality $$\int_0^T\|F_N(t)\|_X^2\leq N\int_0^T\int_{-1/N}^0\|\overline{f}(t+h)\|_X^2dhdt$$
Can I conclude something from it?
Thank You.

A: I think I got it, please verify if it is correct. Note that
\begin{eqnarray}
 \|F_N\|_{L^2((0,T),X)} &\leq& N\int_0^T\int_{-1/N}^0\|\overline{f}(t+h)\|^2_X dhdt      \nonumber \\
   &=& N\int_{-1/N}^0\left(\int_{0}^T\|\overline{f}(t+h)\|^2_X dt\right)dh \nonumber \\
   &=& N\int_{-1/N}^0\|\overline{f}(\cdot+h)\|^2_{L^2((0,T),X)}dh \\
   &\leq & \sup_{-1/N\leq h\leq 0}\|\overline{f}(\cdot+h)\|^2_{L^2((0,T),X)} \\
   &\leq & \|f\|^2_{L^2((0,T),X)}
 \end{eqnarray}
In the last inequality, I have made a change of variables.


text:
Q: Increase PDF height to show in one page I have an HTML used Apex page which has renderas PDF tag for PDF conversion. But the content is too long and coming in two pages. I need to keep it in one Page. Can someone suggest a solution?
Apex Page
<apex:page showHeader="false" standardStylesheets="false" sidebar="false"
    standardController="Sample_Order_Form_abv__c" extensions="SaveAsPdfExtension"
    contentType="{! renderedContentType }" renderAs="PDF">

       {!SOF.Form_ID_abv__c}

 The form is uniquely coded

 And valid for 1 time use only
  A new form is required for each subsequent order.

   ATTENTION PRACTITIONER : PLEASE FILL IN ALL BLANK FIELDS TO ENSURE SAMPLE DELIVERY

   Deliver To :

   {!SOF.Account_abv__r.Name} ,

 {!SOF.Address_Line_1_abv__c}

  {!SOF.Address_Line_2_abv__c}

 {!SOF.City_State_Zip_abv__c}

  Phone: {!SOF.Account_abv__r.Phone}    Fax: {!SOF.Account_abv__r.Fax}

  State License #: {!SOF.Address_abv__r.License_vod__c }

  Rep. Territory#: {!SOF.Territory_abv__c}

Deliveries can be received on (circle)      Tue   Wed   Thu   Fri

 You    will    receive    the    following    prescription    sample(s)

 {!SOF.Proprietary_Name_abv__c}    {!SOF.Established_Name_abv__c}    {!SOF.Dosage_Strength_abv__c}   {!SOF.NDC_abv__c}    Qty: {!SOF.Quantity_abv__c}

     For questions, please call your HUMIRA Sales Representatives or the J.Knipper and Company Hotline at 1-800-250-1774.

Please refer to the provided full Prescribing Information (PI)                EXPIRES     {!ExpDate}

or visit http://www.rxabbvie.com/pdf/humira.pdf for full PI.

 Full Prescribing Information is also available by calling

1-800-633-9110.

       {!SOF.Form_ID_abv__c}

</apex:page>

Please find how the pdf page splits in system.

A: Try setting the page size in the


text:
Q: How to remove unsafe inline and unsafe eval from content security policy? Can anyone know how to remove unsafe inline and unsafe eval from content security policy using nonce,
anyone have any resource how to implement nonce as i am unable to implement it properly i think i am getting errors in node.js application.
I have tried the helmet, meta tags, set Headers nothing worked.

A: You can't remove 'unsafe-eval' with nonces, you'll need to rewrite or replace the code.
Nonces are hard. You will need to insert the nonce in the CSP and in code dynamically. It also needs to change with every pageload to be secure. Frameworks don't always permit this. Also remember that inline event handlers aren't nonceable and need to be rewritten. I would suggest to try to rewrite all static script and style into separate files and then see if you still need nonces for the rest or if you can handle it in other ways.

A: https://github.com/wyday/mod_cspnonce is an apache module that can be used to implement nonce in place of unsafe-inline.


text:
Q: How to set WebDrivers(chrome, Firefox,etc.) path in build.gradle rather than setting it in code I would like to set the WebDrivers path in build.gradle rather than setting the absolute path of the driver. This would help me from not checking-in the .exe into the repo.
I am setting the driver as
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); in code.
Instead of the specifying the "/path/to/chromedriver" in code, I would like it to be picked/set by gradle whenever the test runs.
Tried below in build.gradle
test {systemProperty "webdriver.chrome.driver",
         classpath.find {
             it.name.contains("selenium-chrome-driver")
         }
     println "Getting system properties"
     println System.getProperty("webdriver.chrome.driver")
    }

But each I run the test, I get null
Thanks in advance.

A: You could also use WebDriverManager( https://github.com/bonigarcia/webdrivermanager ) to manage your drivers.
https://github.com/bonigarcia/webdrivermanager#basic-usage shows the simple way to add via gradle
dependencies {
    testImplementation("io.github.bonigarcia:webdrivermanager:4.3.1")
}

and code usage:
@BeforeClass
public static void setupClass() {
    WebDriverManager.chromedriver().setup();
}

@Before
public void setupTest() {
    driver = new ChromeDriver();
}


text:
Q: Python Regex match so long as there's no character I am having some trouble with another regular expression. For this one, my code is supposed to look for the pattern:
re.compile(r"kill(?:ed|ing|s)\D*(\d+).*?(?:men|women|children|people)?")

However, it is matching too aggressively. It happens to match a sentence which has the word 'killing' in it. But the pattern continues to collect until it reaches a digit further down in the text. In particular, it is matching:
killed in an apparent u.s. drone attack on a car in yemen on sunday, tribal sources and local officials said.the men's car was driving through the south-eastern province of maareb, a mostly desert region where militants have taken refuge after being driven from southern strongholds.yemen, where al qaeda militants exploited a security vacuum during last year's uprising that ousted president ali abdullah saleh, has seen an in10

This is not the behavior I'm after. I would like this pattern to fail if it cannot be found inside a single sentence.
The solution I'm trying implement in pseudo code is:
find instance of 'kill'
if what follows contains a period (\.) before a digit, do not match.

My failed implementation looks like this:
re.compile(r"kill(?:ed|ing|s)\D*(?!:\..*?)(\d+).*?(?:men|women|children|people)?")

I've tried a 'look-behind', but I have to specify a width. What I'm trying to do with the above is match any ending of 'kill', followed by any non-digit, but NOT match a period, and anything else is free to follow before the digit I'm after.
Sadly, this code behaves the exact same in my test. Any help would be appreciated.

A: A small modification:
r"kill(?:ed|ing|s)[^\d.]*(\d+)[^.]*?(?:men|women|children|people)?"

Basically, I prevent full stop . from being matched between kill and men/women/etc. following after.


text:
Q: Given a list of user ids, how can I get these users profiles? All I've been able to find is the method UserInfo.getProfileId() which will only get the logged in user's profile ID. I need to get the profile of a list of users.

A: You can loop through the list and add the profile Ids to a set like this:
public static Set<Id> getProfilesFromUser(List<User> userList>){
   Set<Id> setProfileIds= new Set<Id>();
   for(User u : userList){
       setProfileIds.add(u.ProfileId);
   }
   return setProfileIds;
}

you should now have a set of all profile Ids for all the users in the initial list


text:
Q: Always present password field on Windows login instead of fingerprint I've recently enabled the fingerprint reader on my laptop running Windows 8.1 and now use it for login as a supplement to my password. When I login using my fingerprint, the default login method is changed to fingerprints, and Windows displays this when I turn on the computer:

However, when I'm at home and my laptop is plugged into my docking station, I can't access the fingerprint reader underneath the laptop lid. Thus, I have to click Sign-in options and then the password icon before being able to type my password:

When the password field is shown, I can still login using my fingerprint, and thus, having the password field shown always would be ideal, so as to save clicks each time I log in a home. Is this possible?

A: This has been fixed in Windows 10. The sing-in screen now always shows the password field, even if I last signed in with my fingerprint.


text:
Q: Present a complex number in rectangular form. I did the right thing? $ \left({\frac{(\sqrt 2 - i\sqrt2)(1-\sqrt3)}{4}}\right)^{28}$ 1)
$$\left({\frac{(\sqrt 2 - i\sqrt2)(1-\sqrt3)}{4}}\right)^{28} = \left(\frac{(\sqrt2 -\sqrt6)+i(-\sqrt6-\sqrt2)}{4}\right)^{28} = \left(\frac{\sqrt2-\sqrt6}{4}+\frac{i(-\sqrt6-\sqrt2)}{4}\right)^{28} $$
2) Continue using the formula Moivre
$$ z^n = |z|^n(\cos{(n\phi)}+i\sin{(n\phi)}) $$
$$|z| = \sqrt{\left(\frac{\sqrt2-\sqrt6}{4}\right)^2 + \left(\frac{-\sqrt6-\sqrt2}{4}\right)^2 } \\= \sqrt{\frac{2-2\sqrt{12}+6}{16}+\frac{6+2\sqrt{12}+2}{16}} \\= \sqrt{\frac{2-2\sqrt{12}+6+6+2\sqrt{12}+2}{16}} = \sqrt{\frac{16}{16}} = 1 $$
3)
$$\tan(\phi) = \frac{-\sqrt6-\sqrt2}{\sqrt2-\sqrt6} = \frac{(-\sqrt6-\sqrt2)(\sqrt2+\sqrt6)}{2-6} = \frac{-(\sqrt2+\sqrt6)(\sqrt2+\sqrt6)}{-4} = \frac{-(2+2\sqrt{12}+6)}{-4} = \frac{-8-2\sqrt{12}}{-4}= \frac{-4(2+\sqrt3)}{-4} = 2 +\sqrt3$$
$$ \phi = \arctan{(2+\sqrt3)} $$
Result:
$$ z = 1^{28} \cdot (\cos(28\arctan(2+\sqrt3) + i\sin(28\arctan(2+\sqrt3))$$

A: I guess that a factor $i$ is missing in front of $\sqrt{3}$.
We use the exponential notation (or just read $e^{it}$ as $\cos(t)+i\sin(t)$ if you are going to use De Moivre Formula) and we split the work in two:
$$(\sqrt 2 - i\sqrt2)^{28}=(2e^{-i\pi/4})^{28}=2^{28}e^{-7i\pi}=-2^{28}$$
and
$$(1 - i\sqrt3)^{28}=(2e^{-i\pi/3})^{28}=2^{28}e^{-28i\pi/3}=2^{28}e^{-4i\pi/3}.$$
Hence
$$\left({\frac{(\sqrt 2 - i\sqrt2)(1-i\sqrt3)}{4}}\right)^{28}=
\frac{-2^{28}\cdot2^{28}e^{-4i\pi/3}}{4^{28}}=-e^{-4i\pi/3}=e^{-i\pi/3}=\frac{1-i\sqrt{3}}{2}.
$$


text:
Q: This coder requires that replaced objects be returned from initWithCoder:' I'm testing my app on simulator 3.1.3 release, it runs fine. When it come to simulator 3.2 or 4.0, it crashes right from the beginning:
2010-09-28 18:36:39.957 Angeloni[23268:207] *** Terminating app due to uncaught exception 'NSGenericException', reason: 'This coder requires that replaced objects be returned from initWithCoder:'

*** Call stack at first throw:
(
    0   CoreFoundation                      0x0268cb99 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x027dc40e objc_exception_throw + 47
    2   CoreFoundation                      0x02645238 +[NSException raise:format:arguments:] + 136
    3   CoreFoundation                      0x026451aa +[NSException raise:format:] + 58
    4   UIKit                               0x005d03fa UINibDecoderDecodeObjectForValue + 2384
    5   UIKit                               0x005d1179 -[UINibDecoder decodeObjectForKey:] + 398
    6   UIKit                               0x004f6d77 -[UIRuntimeConnection initWithCoder:] + 212
    7   UIKit                               0x005d04ca UINibDecoderDecodeObjectForValue + 2592
    8   UIKit                               0x005cfdc2 UINibDecoderDecodeObjectForValue + 792
    9   UIKit                               0x005d1179 -[UINibDecoder decodeObjectForKey:] + 398
    10  UIKit                               0x004f6034 -[UINib instantiateWithOwner:options:] + 804
    11  UIKit                               0x004f7eb5 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 168
    12  UIKit                               0x003ad95f -[UIViewController _loadViewFromNibNamed:bundle:] + 70
    13  UIKit                               0x003ab675 -[UIViewController loadView] + 120
    14  UIKit                               0x003ab54f -[UIViewController view] + 56
    15  Angeloni                            0x000045ba -[MenuPrincipalViewController gotoOfertas:] + 109
    16  UIKit                               0x003017f8 -[UIApplication sendAction:to:from:forEvent:] + 119
    17  UIKit                               0x0038cde0 -[UIControl sendAction:to:forEvent:] + 67
    18  UIKit                               0x0038f262 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
    19  UIKit                               0x0038de0f -[UIControl touchesEnded:withEvent:] + 458
    20  UIKit                               0x003253d0 -[UIWindow _sendTouchesForEvent:] + 567
    21  UIKit                               0x00306cb4 -[UIApplication sendEvent:] + 447
    22  UIKit                               0x0030b9bf _UIApplicationHandleEvent + 7672
    23  GraphicsServices                    0x02f04822 PurpleEventCallback + 1550
    24  CoreFoundation                      0x0266dff4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
    25  CoreFoundation                      0x025ce807 __CFRunLoopDoSource1 + 215
    26  CoreFoundation                      0x025cba93 __CFRunLoopRun + 979
    27  CoreFoundation                      0x025cb350 CFRunLoopRunSpecific + 208
    28  CoreFoundation                      0x025cb271 CFRunLoopRunInMode + 97
    29  GraphicsServices                    0x02f0300c GSEventRunModal + 217
    30  GraphicsServices                    0x02f030d1 GSEventRun + 115
    31  UIKit                               0x0030faf2 UIApplicationMain + 1160
    32  Angeloni                            0x00002342 main + 84
    33  Angeloni                            0x000022e5 start + 53
)

terminate called after throwing an instance of 'NSException'

Anyone ever had this problem? I read in some forum that this is a of IB problem.
If anyone can help.

A: Had this problem on a project where I did not use any Storyboards.
What I had to do:

*

*go to my project's Info.plist file

*remove the Main storyboard file base name entry there.


text:
Q: can't free qutoa using gcloud and Google Compete engine failed.
[INFO] ERROR: (gcloud.app.deploy) INVALID_ARGUMENT: The following quotas were exceeded: BACKEND_SERVICES (quota: 5, used: 5 + needed: 1).
[ERROR] Error: gcloud app command with exit code : 1
[INFO] --

i keep getting the above error when i try to deploy..I cannot delete my backend_services?
i assume its gcloud app instances list
and simply delete the instances, however when I delete they just keep reinitialize. how can i free up the 5 instances using gcloud or the console.
i tried going to : https://console.cloud.google.com/compute/instances?project=playchat-98e58 , but its not showing any instances?
$ gcloud.cmd app instances list
SERVICE  VERSION          ID                                VM_STATUS  DEBUG_MODE
default  20170317t203143  aef-default-20170317t203143-4ctc  RUNNING
default  20170317t203143  aef-default-20170317t203143-b4wr  RUNNING
default  20170317t203143  aef-default-20170317t203143-tpnt  RUNNING
default  20170317t205434  aef-default-20170317t205434-5fm7  RUNNING
default  20170317t205434  aef-default-20170317t205434-6rkt  RUNNING
default  20170317t205434  aef-default-20170317t205434-9nkq  RUNNING
default  20170317t212530  aef-default-20170317t212530-f869  RUNNING
default  20170317t212530  aef-default-20170317t212530-k6cn  RUNNING
default  20170317t212530  aef-default-20170317t212530-lszv  RUNNING
default  20170317t213906  aef-default-20170317t213906-5x7c  RUNNING
default  20170317t213906  aef-default-20170317t213906-8qg1  RUNNING
default  20170317t213906  aef-default-20170317t213906-qglb  RUNNING
default  20170318t002735  aef-default-20170318t002735-b60s  RUNNING
default  20170318t002735  aef-default-20170318t002735-hr4c  RUNNING
default  20170318t002735  aef-default-20170318t002735-wh80  RUNNING

twoen@DESKTOP-9R5VHUK MINGW64 ~/AppData/Local/Google/Cloud SDK/google-cloud-sdk/bin
$ gcloud.cmd compute backend-services list
Listed 0 items.

A: Backend services are resource that can exist independently from your deployed apps. You can try listing and deleting them:
gcloud compute backend-services list
gcloud compute backend-services delete $BACKEND_SERVICE_NAME


text:
Q: Get all the users count according to type in one query instead of multiple query in mysql I am trying to write a MySQL query where I want to get data from one table only. Where structure looks like this:
+--------------------+------------------+------+-----+----------+----------------+
| Field              | Type             | Null | Key | Default  | Extra          |
+--------------------+------------------+------+-----+----------+----------------+
| id                 | int(10) unsigned | NO   | PRI | NULL     | auto_increment |
| name               | varchar(255)     | NO   |     | NULL     |                |
| lastname           | varchar(255)     | NO   |     | NULL     |                |
| slug               | text             | NO   |     | NULL     |                |
| gender             | varchar(225)     | YES  |     | NULL     |                |
| balance            | double(50,6)     | YES  |     | NULL     |                |
| email              | varchar(255)     | NO   |     | NULL     |                |
| password           | varchar(255)     | NO   |     | NULL     |                |
| city               | varchar(255)     | NO   |     | NULL     |                |
| country            | varchar(255)     | NO   |     | NULL     |                |
| statename          | varchar(255)     | NO   |     | NULL     |                |
| countryname        | varchar(255)     | NO   |     | NULL     |                |
| dob                | date             | YES  |     | NULL     |                |
| membership         | varchar(255)     | YES  |     | standard |                |
| status             | varchar(255)     | NO   |     | NULL     |                |
| marital_status     | varchar(255)     | NO   |     | NULL     |                |
| description        | text             | NO   |     | NULL     |                |
| user_id            | int(10) unsigned | YES  | MUL | NULL     |                |
| active             | smallint(6)      | NO   |     | 1        |                |
| registertype       | varchar(255)     | NO   |     | unpaid   |                |
| created_at         | timestamp        | YES  |     | NULL     |                |
| updated_at         | timestamp        | YES  |     | NULL     |
+--------------------+------------------+------+-----+----------+----------------+

Now I want to select data like this with below columns:
1) created_at (will be a date)
2) total_registrations (will be total count)
3) paid_member (count of total member where registertype=paid on a specific date)
4) unpaid_member (count of total member where registertype=unpaid on a specific date wise)

So far I am successful to get the results like this with below query:
select DATE(`created_at`) as created_at, count(*) as total_registrations
from en_customers
where DATE(`created_at`)  between date_sub(CURDATE(), interval 7 day) AND CURDATE()
    AND registertype="paid"
group by DATE(`created_at`);

From this query I get this result:
+------------+-----------+
| created_at | total_reg |
+------------+-----------+
| 2018-07-04 |         7 |
| 2018-07-05 |         7 |
| 2018-07-06 |         5 |
| 2018-07-07 |         4 |
| 2018-07-08 |         8 |
| 2018-07-09 |        13 |
| 2018-07-10 |        15 |
| 2018-07-11 |        14 |
+------------+-----------+

But I am not not able to take the records with columns I just show.
Thank you (in advance)!

A: Do it like this:
select DATE(`created_at`) as created_at, count(*) as total_registrations
    ,sum(case when registertype='paid' then 1 else 0 end) as paid_member
    ,sum(case when registertype='unpaid' then 1 else 0 end) as unpaid_member
from en_customers
where DATE(`created_at`)  between date_sub(CURDATE(), interval 7 day) AND CURDATE()
group by DATE(`created_at`);

The technique is called "Conditional Aggregation".
Note I removed the registertype="paid" condition from the WHERE clause.

A: use CASE WHEN in COUNT function.
select DATE(`created_at`) as created_at,
       count(*) as total_registrations,
       COUNT(CASE WHEN registertype='paid' THEN 1 END) as paid_member,
       COUNT(CASE WHEN registertype='unpaid' THEN 1 END) as unpaid_member
from en_customers
where DATE(`created_at`)  between date_sub(CURDATE(), interval 7 day) AND CURDATE()
group by DATE(`created_at`);

A: you could use sum on filtered  values
select DATE(`created_at`) as created_at
      , count(*) as total_registrations
      , sum(case when registertype='paid' then 1 else 0 end) paid_member
      , sum(case when registertype='unpaid' then 1 else 0 end) unpaid_member
from en_customers
where DATE(`created_at`)  between date_sub(CURDATE(), interval 7 day) AND CURDATE()

group by DATE(`created_at`);


text:
Q: Prevent word from being broken in TextView How do I prevent a word in a TextViewfrom breaking in half when it doesn't fit on the current line and instead move to the next line.
|android goo|
|gle kitkat |

should instead be
|android    |
|google     |
|kitkat     |

The TextView is currently added to a RelativeLayout using this code:
TextView tv = new TextView(this);
RelativeLayout.LayoutParams layoutParams = new  RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (16*scale + 0.5f);
tv.setPadding(dpAsPixels, 0, dpAsPixels, 0);

tv.setLayoutParams(layoutParams);

String fullString = "" + user + ": " + text;
fullString = fullString.replaceAll("\n", "
");
fullString = fullString.replaceAll(" ", "&#160");
tv.setText(Html.fromHtml(fullString));
tv.setTextSize(32f);
tv.setTextColor(getResources().getColor(R.color.text));

layout.addView(tv);

A: the problem is in following line

fullString = fullString.replaceAll(" ", "&#160");

remove it and it will work as you need, you don't need to replace space with html code, fromHtml will do it for you

A: The problem with your code is this line:
fullString = fullString.replaceAll(" ", "&#160");

By doing this, you replace all "normal" spaces with non-breakable spaces (&nbsp). Since these spaces are non-breakable, they prevent a line break.
Just remove this line and the words won't break in half anymore.

A: Add
android:scrollHorizontally="false"

to your TextView entry in your XML or call
setHorizontallyScrolling(false);

Docs here.

A: We can use Webview in some cases and justify the text help of html/css and then set the Text.


text:
Q: clear OS Block all outgoing traffic unless out to VPN In clear OS I can block all outgoing traffic. Using Block Mode "Block all outgoing traffic".
This is exactly what I want. However with this mode on I cannot connect to SQL Server via a VPN. I can ping the server by host name, URL, and IP and it responds. But I cannot connect using SSMS until I turned block mode off.
Any thoughts on allowing the SQL server to talk back to VPN clients.
               |Internet|
[Me] -> (VPN)--|--------|--> [ClearOS (VPN)] -> [SQL Server]

More info:
Clear OS 5.2
PPTP VPN


text:
Q: Webpack puplicate ending in generated file Example on github
The problem is in duplicate file ending in generated by webpack files.
Webpack adds extra closing brackets and brakes file.
Example:
|- build/
|- app.js
|- one.js
|- test.js

app.js contains webpack config:
var webpack = require("webpack");
var compiler = webpack({
  entry: {
    generated: ['./test.js']
  },
  output: {
    path: "build",
    filename: "[name].js"
  }
}, function(err) {
  if(err) console.error(err);
});

compiler.watch('', function (err) {
  if(err) console.error(err);
});

test.js - webpack source
require('./one.js');

one.js - code source
console.log('hello from one');

After exacution I expect to get valid generated.js with ending like:
/***/ }
/******/ ]);

but I get:
/***/ }
/******/ ]);le');

/***/ }

/******/ });

I can suggest that  le' it's a part of cannot resolve module or cannot find module.
That take place with different configs and different files and brakes everething. I need your help.
Update:
For unknown reason extra ending not appears if webpack creates folder by itself.

A: You need to clean build directory before start building generated.js.
/******/ ]);le');

It is output from previous build.


text:
Q: I have json object but I am unable to access 'name' element in this? This is the json data
{
    "0": {
        "restaurant": "Bayleaf",
        "order": "HIHUN10",
        "delivery at": "04:43 PM 2016-06-22",
        "type": "Home Delivery",
        "name": "dEEPAK rAI",
        "address": "12356,Lucknow,226010",
        "phone": "9120276440",
        "total": "Rs 831.60",
        "pay by": "Cash On Delivery",
        "picked by": "By Administrator",
        "date": "06\/22\/2016",
        "status": "Waiting",
        "action": "pending"
    },
    "1": {
        "restaurant": "Jungliee",
        "order": "HIHUN9",
        "delivery at": "03:40 PM 2016-06-21",
        "type": "Home Delivery",
        "name": "dEEPAK rAI",
        "address": "12356,Lucknow,226010",
        "phone": "9120276440",
        "total": "Rs 465.00",
        "pay by": "Cash On Delivery",
        "picked by": "Dummy",
        "date": "06\/21\/2016",
        "status": {
            "Accepted": 1,
            "Processing": 2,
            "Delivered": 3,
            "Completed": 4,
            "Failed": 5
        },
        "action": "view"
    },
    "2": {
        "restaurant": "Naushijaan",
        "order": "HIHUN8",
        "delivery at": "11:10 AM 2016-06-18",
        "type": "Home Delivery",
        "name": "dEEPAK rAI",
        "address": "12356,Lucknow,226010",
        "phone": "9120276440",
        "total": "Rs 545.00",
        "pay by": "Cash On Delivery",
        "picked by": "By Administrator",
        "date": "06\/18\/2016",
        "status": {
            "Processing": 2,
            "Delivered": 3,
            "Completed": 4,
            "Failed": 5
        },
        "action": "view"
    },
    "3": {
        "restaurant": "Aahaar",
        "order": "HIHUN7",
        "delivery at": "11:32 AM 2016-06-12",
        "type": "Home Delivery",
        "name": "sk mishra",
        "address": "520viram khand,Lucknow,226010",
        "phone": "9198979962",
        "total": "Rs 450.00",
        "pay by": "Cash On Delivery",
        "picked by": "Dummy",
        "date": "06\/12\/2016",
        "status": {
            "Completed": 4,
            "Failed": 5
        },
        "action": "view"
    },
    "4": {
        "restaurant": "Bayleaf",
        "order": "HIHUN6",
        "delivery at": "08:29 PM 2016-06-11",
        "type": "Home Delivery",
        "name": "Dharmraj",
        "address": "D-242Office G 19 Sector 63,Lucknow,201003",
        "phone": "7428069025",
        "total": "Rs 606.60",
        "pay by": "Cash On Delivery",
        "picked by": "By Administrator",
        "date": "06\/11\/2016",
        "status": {
            "Completed": 4,
            "Failed": 5
        },
        "action": "view"
    },
    "5": {
        "restaurant": "Bayleaf",
        "order": "HIHUN5",
        "delivery at": "08:17 PM 2016-06-11",
        "type": "Home Delivery",
        "name": "Dharmraj",
        "address": "D-242Office G 19 Sector 63,Lucknow,201003",
        "phone": "7428069025",
        "total": "Rs 606.60",
        "pay by": "Cash On Delivery",
        "picked by": "By Administrator",
        "date": "06\/11\/2016",
        "status": {
            "Completed": 4,
            "Failed": 5
        },
        "action": "view"
    }
}

A: This is how you can access the name field.

var yourJson = {"0":{"restaurant":"Bayleaf","order":"HIHUN10","delivery at":"04:43 PM 2016-06-22","type":"Home Delivery","name":"dEEPAK rAI","address":"12356,Lucknow,226010","phone":"9120276440","total":"Rs 831.60","pay by":"Cash On Delivery","picked by":"By Administrator","date":"06\/22\/2016","status":"Waiting","action":"pending"},"1":{"restaurant":"Jungliee","order":"HIHUN9","delivery at":"03:40 PM 2016-06-21","type":"Home Delivery","name":"dEEPAK rAI","address":"12356,Lucknow,226010","phone":"9120276440","total":"Rs 465.00","pay by":"Cash On Delivery","picked by":"Dummy","date":"06\/21\/2016","status":{"Accepted":1,"Processing":2,"Delivered":3,"Completed":4,"Failed":5},"action":"view"},"2":{"restaurant":"Naushijaan","order":"HIHUN8","delivery at":"11:10 AM 2016-06-18","type":"Home Delivery","name":"dEEPAK rAI","address":"12356,Lucknow,226010","phone":"9120276440","total":"Rs 545.00","pay by":"Cash On Delivery","picked by":"By Administrator","date":"06\/18\/2016","status":{"Processing":2,"Delivered":3,"Completed":4,"Failed":5},"action":"view"},"3":{"restaurant":"Aahaar","order":"HIHUN7","delivery at":"11:32 AM 2016-06-12","type":"Home Delivery","name":"sk mishra","address":"520viram khand,Lucknow,226010","phone":"9198979962","total":"Rs 450.00","pay by":"Cash On Delivery","picked by":"Dummy","date":"06\/12\/2016","status":{"Completed":4,"Failed":5},"action":"view"},"4":{"restaurant":"Bayleaf","order":"HIHUN6","delivery at":"08:29 PM 2016-06-11","type":"Home Delivery","name":"Dharmraj","address":"D-242Office G 19 Sector 63,Lucknow,201003","phone":"7428069025","total":"Rs 606.60","pay by":"Cash On Delivery","picked by":"By Administrator","date":"06\/11\/2016","status":{"Completed":4,"Failed":5},"action":"view"},"5":{"restaurant":"Bayleaf","order":"HIHUN5","delivery at":"08:17 PM 2016-06-11","type":"Home Delivery","name":"Dharmraj","address":"D-242Office G 19 Sector 63,Lucknow,201003","phone":"7428069025","total":"Rs 606.60","pay by":"Cash On Delivery","picked by":"By Administrator","date":"06\/11\/2016","status":{"Completed":4,"Failed":5},"action":"view"}}
console.log(yourJson["0"].name);
console.log(yourJson["1"].name);  //etc.

A: If it's already an object from json, just access it:
var data = {"0":{"restaurant":"Bayleaf","order":"HIHUN10","delivery at":"04:43 PM 2016-06-22","type":"Home Delivery","name":"dEEPAK rAI","address":"12356,Lucknow,226010","phone":"9120276440","total":"Rs 831.60","pay by":"Cash On Delivery","picked by":"By Administrator","date":"06\/22\/2016","status":"Waiting","action":"pending"},"1":{"restaurant":"Jungliee","order":"HIHUN9","delivery at":"03:40 PM 2016-06-21","type":"Home Delivery","name":"dEEPAK rAI","address":"12356,Lucknow,226010","phone":"9120276440","total":"Rs 465.00","pay by":"Cash On Delivery","picked by":"Dummy","date":"06\/21\/2016","status":{"Accepted":1,"Processing":2,"Delivered":3,"Completed":4,"Failed":5},"action":"view"},"2":{"restaurant":"Naushijaan","order":"HIHUN8","delivery at":"11:10 AM 2016-06-18","type":"Home Delivery","name":"dEEPAK rAI","address":"12356,Lucknow,226010","phone":"9120276440","total":"Rs 545.00","pay by":"Cash On Delivery","picked by":"By Administrator","date":"06\/18\/2016","status":{"Processing":2,"Delivered":3,"Completed":4,"Failed":5},"action":"view"},"3":{"restaurant":"Aahaar","order":"HIHUN7","delivery at":"11:32 AM 2016-06-12","type":"Home Delivery","name":"sk mishra","address":"520viram khand,Lucknow,226010","phone":"9198979962","total":"Rs 450.00","pay by":"Cash On Delivery","picked by":"Dummy","date":"06\/12\/2016","status":{"Completed":4,"Failed":5},"action":"view"},"4":{"restaurant":"Bayleaf","order":"HIHUN6","delivery at":"08:29 PM 2016-06-11","type":"Home Delivery","name":"Dharmraj","address":"D-242Office G 19 Sector 63,Lucknow,201003","phone":"7428069025","total":"Rs 606.60","pay by":"Cash On Delivery","picked by":"By Administrator","date":"06\/11\/2016","status":{"Completed":4,"Failed":5},"action":"view"},"5":{"restaurant":"Bayleaf","order":"HIHUN5","delivery at":"08:17 PM 2016-06-11","type":"Home Delivery","name":"Dharmraj","address":"D-242Office G 19 Sector 63,Lucknow,201003","phone":"7428069025","total":"Rs 606.60","pay by":"Cash On Delivery","picked by":"By Administrator","date":"06\/11\/2016","status":{"Completed":4,"Failed":5},"action":"view"}};

// as single, hardcoded entry
var nameAt0 = data[0].name;
var nameAt1 = data[1].name;
...

// as loop
for( var i in data )
    if( data.hasOwnProperty(i) )
        var name = data[i].name;

A: Your json is an object, to access name you must iterate through properties :
$.each(data, function(i, e) {
  alert(e.name);
});

https://jsfiddle.net/kj0azubb/

var data = {
  "0": {
    "restaurant": "Bayleaf",
    "order": "HIHUN10",
    "delivery at": "04:43 PM 2016-06-22",
    "type": "Home Delivery",
    "name": "dEEPAK rAI",
    "address": "12356,Lucknow,226010",
    "phone": "9120276440",
    "total": "Rs 831.60",
    "pay by": "Cash On Delivery",
    "picked by": "By Administrator",
    "date": "06\/22\/2016",
    "status": "Waiting",
    "action": "pending"
  },
  "1": {
    "restaurant": "Jungliee",
    "order": "HIHUN9",
    "delivery at": "03:40 PM 2016-06-21",
    "type": "Home Delivery",
    "name": "dEEPAK rAI",
    "address": "12356,Lucknow,226010",
    "phone": "9120276440",
    "total": "Rs 465.00",
    "pay by": "Cash On Delivery",
    "picked by": "Dummy",
    "date": "06\/21\/2016",
    "status": {
      "Accepted": 1,
      "Processing": 2,
      "Delivered": 3,
      "Completed": 4,
      "Failed": 5
    },
    "action": "view"
  },
  "2": {
    "restaurant": "Naushijaan",
    "order": "HIHUN8",
    "delivery at": "11:10 AM 2016-06-18",
    "type": "Home Delivery",
    "name": "dEEPAK rAI",
    "address": "12356,Lucknow,226010",
    "phone": "9120276440",
    "total": "Rs 545.00",
    "pay by": "Cash On Delivery",
    "picked by": "By Administrator",
    "date": "06\/18\/2016",
    "status": {
      "Processing": 2,
      "Delivered": 3,
      "Completed": 4,
      "Failed": 5
    },
    "action": "view"
  },
  "3": {
    "restaurant": "Aahaar",
    "order": "HIHUN7",
    "delivery at": "11:32 AM 2016-06-12",
    "type": "Home Delivery",
    "name": "sk mishra",
    "address": "520viram khand,Lucknow,226010",
    "phone": "9198979962",
    "total": "Rs 450.00",
    "pay by": "Cash On Delivery",
    "picked by": "Dummy",
    "date": "06\/12\/2016",
    "status": {
      "Completed": 4,
      "Failed": 5
    },
    "action": "view"
  },
  "4": {
    "restaurant": "Bayleaf",
    "order": "HIHUN6",
    "delivery at": "08:29 PM 2016-06-11",
    "type": "Home Delivery",
    "name": "Dharmraj",
    "address": "D-242Office G 19 Sector 63,Lucknow,201003",
    "phone": "7428069025",
    "total": "Rs 606.60",
    "pay by": "Cash On Delivery",
    "picked by": "By Administrator",
    "date": "06\/11\/2016",
    "status": {
      "Completed": 4,
      "Failed": 5
    },
    "action": "view"
  },
  "5": {
    "restaurant": "Bayleaf",
    "order": "HIHUN5",
    "delivery at": "08:17 PM 2016-06-11",
    "type": "Home Delivery",
    "name": "Dharmraj",
    "address": "D-242Office G 19 Sector 63,Lucknow,201003",
    "phone": "7428069025",
    "total": "Rs 606.60",
    "pay by": "Cash On Delivery",
    "picked by": "By Administrator",
    "date": "06\/11\/2016",
    "status": {
      "Completed": 4,
      "Failed": 5
    },
    "action": "view"
  }
};

$.each(data, function(i, e) {
  $("#content").append(e.name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
</div>

A:

var jsonData = {
  "0": {
    "restaurant": "Bayleaf",
    "order": "HIHUN10",
    "delivery at": "04:43 PM 2016-06-22",
    "type": "Home Delivery",
    "name": "dEEPAK rAI",
    "address": "12356,Lucknow,226010",
    "phone": "9120276440",
    "total": "Rs 831.60",
    "pay by": "Cash On Delivery",
    "picked by": "By Administrator",
    "date": "06\/22\/2016",
    "status": "Waiting",
    "action": "pending"
  },
  "1": {
    "restaurant": "Jungliee",
    "order": "HIHUN9",
    "delivery at": "03:40 PM 2016-06-21",
    "type": "Home Delivery",
    "name": "dEEPAK rAI",
    "address": "12356,Lucknow,226010",
    "phone": "9120276440",
    "total": "Rs 465.00",
    "pay by": "Cash On Delivery",
    "picked by": "Dummy",
    "date": "06\/21\/2016",
    "status": {
      "Accepted": 1,
      "Processing": 2,
      "Delivered": 3,
      "Completed": 4,
      "Failed": 5
    },
    "action": "view"
  },
  "2": {
    "restaurant": "Naushijaan",
    "order": "HIHUN8",
    "delivery at": "11:10 AM 2016-06-18",
    "type": "Home Delivery",
    "name": "dEEPAK rAI",
    "address": "12356,Lucknow,226010",
    "phone": "9120276440",
    "total": "Rs 545.00",
    "pay by": "Cash On Delivery",
    "picked by": "By Administrator",
    "date": "06\/18\/2016",
    "status": {
      "Processing": 2,
      "Delivered": 3,
      "Completed": 4,
      "Failed": 5
    },
    "action": "view"
  },
  "3": {
    "restaurant": "Aahaar",
    "order": "HIHUN7",
    "delivery at": "11:32 AM 2016-06-12",
    "type": "Home Delivery",
    "name": "sk mishra",
    "address": "520viram khand,Lucknow,226010",
    "phone": "9198979962",
    "total": "Rs 450.00",
    "pay by": "Cash On Delivery",
    "picked by": "Dummy",
    "date": "06\/12\/2016",
    "status": {
      "Completed": 4,
      "Failed": 5
    },
    "action": "view"
  },
  "4": {
    "restaurant": "Bayleaf",
    "order": "HIHUN6",
    "delivery at": "08:29 PM 2016-06-11",
    "type": "Home Delivery",
    "name": "Dharmraj",
    "address": "D-242Office G 19 Sector 63,Lucknow,201003",
    "phone": "7428069025",
    "total": "Rs 606.60",
    "pay by": "Cash On Delivery",
    "picked by": "By Administrator",
    "date": "06\/11\/2016",
    "status": {
      "Completed": 4,
      "Failed": 5
    },
    "action": "view"
  },
  "5": {
    "restaurant": "Bayleaf",
    "order": "HIHUN5",
    "delivery at": "08:17 PM 2016-06-11",
    "type": "Home Delivery",
    "name": "Dharmraj",
    "address": "D-242Office G 19 Sector 63,Lucknow,201003",
    "phone": "7428069025",
    "total": "Rs 606.60",
    "pay by": "Cash On Delivery",
    "picked by": "By Administrator",
    "date": "06\/11\/2016",
    "status": {
      "Completed": 4,
      "Failed": 5
    },
    "action": "view"
  }
};
$.each(jsonData, function(index, value) {
  console.log(JSON.stringify(value.name));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A: Its working fine now every answer is correct.I am missing

 dataType: 'json'
   ,

'dataType:json' in side ajax block.

A: First, you have a very non standar JSON structure, but, you can't access as a JSON Array, so, you have to parse the JSON to an objet that you can read more easly.
    var MyJSONArray = [];
    $.each(YourJSON,function(index,e){
        MyJSONArray[] = e;
    ]

And then you can use it AS
    var restarant_1 = MyJSONArray[0].restaurant;

And this is it!
Enjoy


text:
Q: Why is my game delay happening before I want it to? I'm creating a game in pygame and I wanted to display "Level Complete" text at the end of the level. I wanted to create a delay after the text is blitted so it will be displayed for a few seconds. However, the delay keeps occurring before my text is displayed, despite the line of code being after the text is blitted. Here is the link to my game:
Swamp_Game
I tried using the pygame.time.delay() function, but it kept making the pause happen before my text.
# lines 101-107 on main.py

screen.blit(field, field_rect)
core_text(screen, "Level Complete!", 100, 150, 200, BLACK)
pygame.time.delay(2000)
screen.blit(swamp, swamp_rect)
level_2() # function to initiate level 2
clock.tick(20)
pygame.display.flip()

I wanted the pause to occur after the text is shown, but it keeps happening before it. As a result, my text is only displayed for a fraction of a second before it moves onto the next level and is barely visible.

A:
but it kept making the pause happen before my text.

The text is drawn before delay, but it is not visible on the display.
Of course, you've to update the display by either pygame.display.flip() or pygame.display.update(), before pygame.time.delay().
Further you should handle the events (e.g. pygame.event.pump()) - some systems need event handling for display update.
pygame.display.flip()
pygame.event.pump()
pygame.time.delay(2000)
pygame.event.pump()


text:
Q: Limesurvey images over radio buttons? As you can see above in this Limesurvey question, there are custom images over the radio-buttons in what I assume is the 5 point choice question option. I am trying to reproduce this in one of my own surveys. How can I achieve this? Is this done programatically or is it done through the GUI interface somewhere?
Thanks!

A: Hi surely a Array question type. With answer like this:
  Very unhappy

  Unhappy

  .....

You can use HTML in answer part (and sub question part too).


text:
Q: How to get REST Api in Ember JS? I work with an Ember boilerplate that works with REST Api.
The data should be recieved from Laravel backend and rendered in an Ember template. I will be grateful for any help.
Here is response of index (/) route:
{
    "responce":[
        {
            "id":0,
            "title":"main",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Vitae, aliquam."
        },
        {
            "id":1,
            "name":"about",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident, obcaecati? Accusantium ex dolorum voluptate deleniti?"
        },
        {
            "id":2,
            "name":"contacts",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates voluptatibus exercitationem molestias rem."
        }
    ]
}

I suppose that there should be some kind of a loop that processes the received data and renders it. The result should be something like this:

main

Lorem ipsum dolor sit amet consectetur adipisicing elit. Vitae, aliquam.

about

Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident, obcaecati? Accusantium ex dolorum voluptate deleniti?

contacts

Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates voluptatibus exercitationem molestias rem.

Thanks in advance!

A: There are a lot of pieces to put together here, but let me try and layout the general path. Your Laravel API provides structured data that needs to be read by your ember application. Start by setting up your ember routes model hook to read that data. You'll want to check the guide for a lot more information, but I would start with this in your index route as the first step:
import Route from '@ember/routing/route';
import fetch from 'fetch';

export default Route.extend({
  model() {
    //this is where your ember app gets data from your API
    return fetch('YOUR-LARAVAL-API.com/index').then(response => {
      console.log(data);
      const data = response.json();
      return data.responce;
    });
  }
});

This should make the data available in your index.hbh template so you can access it as model like:

{{#each this.model as |post|}}

{{post.title}}

{{post.content}}

{{/each}}


text:
Q: Is there a way to split and copy rows where there is a carriage return? I have a spread sheet with a lot of columns and rows. Within those columns there are cells where data has been combined using a carriage return,
The top screenshots the data, the first row has 2 carriage returns in and back up name has 1 Row 2 has a carriage return in the code column
I want this to change to the table below it

The below code, splits the cells and pastes them on the end. I then move the original data + 1 column into a new workbook. Paste the split out value back into correct column. Then paste this into a new workbook.
Repeat until the additional columns are gone
    Sub SplitCarriageReturnsCostCodes()

    Sheets("Booking Details").Select

'This will cells where there is a carriage return

    Dim splitVals As Variant
    Dim totalVals As Long
    Dim CellstoSplit As Range
    Dim LastRow As Long          'Makes the last row check the last cell with data in'

    LastRow = Worksheets("Booking Details").Cells(Rows.Count, 5).End(xlUp).Row

    'Set range to split:
    Set CellstoSplit = Range("AG2", "AG2" & LastRow)

    For Each cell In CellstoSplit
    cell.Activate
    splitVals = Split(ActiveCell.Value, Chr(10))
    totalVals = UBound(splitVals)
    Range(Cells(ActiveCell.Row, ActiveCell.Column + 17), Cells(ActiveCell.Row, ActiveCell.Column + 17 + totalVals)).Value = splitVals
    'Pastes them on the end, from range of cell selected plus a number of cells count
    Next cell

End Sub

Sub CreateTabCostCodes()

    ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)   'Adding sheet after all tabs
    ActiveWorkbook.Sheets(Worksheets.Count).Name = "Temp Sheet 1"     'Gives new sheet a name

    ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)   'Adding sheet after all tabs
    ActiveWorkbook.Sheets(Worksheets.Count).Name = "Booking Details New"     'Gives new sheet a name

End Sub

Sub CopyandPasteCostCodes()
'
        'Dim I As Integer                            'Set I name as a variable
        'I = 1                                       'I = 1
        'Do While I <= 100

        Dim ColCount As Integer                     'Sets column count as an integer
        Dim I As Integer                            'Set I as interget
        intCol = ThisWorkbook.Sheets("Booking Details").UsedRange.Columns.Count
                                                    'counts column in my range I just created
        ColCount = intCol - 49                      'column count minus the pre existing columns
        Do While I <= ColCount                      'do while I is equal to or less than column count

        Dim LastRow As Long                     'Makes the last row check the last cell with data in'
        LastRow = Sheet1.Cells(Rows.Count, 5).End(xlUp).Row ' last row in column E = 5, count columns as per a Vlookup'

        Sheets("Booking Details").Select
        Range("A2", "AX2" & LastRow).Select
        Selection.Copy
        Sheets("Temp Sheet 1").Select
        Range("A1").Select
        ActiveSheet.Paste
        Range("AX1", "AX1" & LastRow).Select
        Application.CutCopyMode = False
        Selection.Cut
        Range("AG1").Select
        ActiveSheet.Paste
        Range("A1", "AW1" & LastRow).Select
        Selection.Cut
        Sheets("Booking Details New").Select
        Range("A100000").Select              'Find empty cell at bottom
        Selection.End(xlUp).Select          'Goes from bottom till it find data, xlup = go up'
        ActiveCell.Offset(1, 0).Select      'In this 1,0 then 1 is rows to offset, pastes below the copied data'.
                                            '0 is columns.
        ActiveSheet.Paste

    'Deletes column AW and moves the data along so I can pick it up again

        Sheets("Booking Details").Select
        'Columns("AW:AW").Select               'Before I fixed notes column
        Columns("AX:AX").Select
        Selection.Delete Shift:=xlToLeft

        I = I + 1                   'Add 1 to I up to my number above
    Loop

    Sheets("Booking Details New").Select
    Range("Z2").Select
    Selection.Copy
    Columns("AG:Ag").Select
    Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
    Application.CutCopyMode = False

End Sub

Sub Copy_HeadersCostCodes()
'
' Copies headers from booking details to new tab

    Sheets("Booking Details").Select
    Rows("1:1").Select
    Range("AP1").Activate
    Selection.Copy
    Sheets("Booking Details New").Select
    Rows("1:1").Select
    ActiveSheet.Paste

    'Fixes a header that formats badly

    Sheets("Booking Details New").Select
    Range("Z1").Select
    Selection.Copy
    Range("AG1").Select
    Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
    Application.CutCopyMode = False

End Sub

Public Sub DeleteBlankRowsCostCodes()

'This deletes any row where there is a blank in column AA in the Bookings new tab'

    Dim lLRow As Long
    With Worksheets("Booking Details New") 'Select temp sheet tab'
     lLRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'Looks from top to end of data in first column, hence rows.count, 1'
    .Range("AG:AG").AutoFilter Field:=1, Criteria1:=""
    .Range("AG2:AG" & lLRow).SpecialCells(xlCellTypeVisible).EntireRow.Delete xlShiftUp
     .AutoFilterMode = False
     End With

End Sub

It works but it feels heavy handed. Still new to VBA, learning on the go


text:
Q: How to create dynamic links based on an API request I am completely new to both vue.js and Javascript.  How do I dynamically create nav links from an Axios request?
I am wanting to follow what's being done in the item section which is currently static information, but i want to dynamically return links based on whats returned in the json request.
import * as types from '../../mutation-types'
import lazyLoading from './lazyLoading'
import charts from './charts'

// gathering items from API
const url = 'http://localhost:8080/items/'
data: {
  items: []
},
mounted() {
  axios.get(url).then(response => {
    this.results = items.data
  })
}

// Sidebar links are statically created here

const state = {
  items: [
    {
      name: 'Dashboard',
      path: '/dashboard',
      meta: {
        icon: 'fa-tachometer',
        link: 'dashboard/index.vue'
      },
      component: lazyLoading('dashboard', true)
    },
    {
      name: 'Axios',
      path: '/axiosDemo',
      meta: {
        auth: true,
        icon: 'fa-rocket',
        link: 'axios/index.vue'
      },
      component: lazyLoading('axios', true)
    },

    charts,

  ]
}

const mutations = {
  [types.EXPAND_MENU] (state, menuItem) {
    if (menuItem.index > -1) {
      if (state.items[menuItem.index] && state.items[menuItem.index].meta) {
        state.items[menuItem.index].meta.expanded = menuItem.expanded
      }
    } else if (menuItem.item && 'expanded' in menuItem.item.meta) {
      menuItem.item.meta.expanded = menuItem.expanded
    }
  }
}

export default {
  state,
  mutations
}

I think what I am wanting to do is something like this (python example):
items:
    for i in items_payload:
        {
          name: i.name,
          path: i.url,
          meta: {
              icon: 'fa-tachometer',
              link: i.name+'/index.vue'
                },
        },

How do I best accomplish this in vue.js? Any help would be appreciated. Thanks.

A: If you are making the api request from a component, you can create a list of links like follows:
// for demo purposes, let's say links are returned as an array of objects
[
  {
    href: '/path/to/page1',
    linkText: 'Page 1'
  },
  {
    href: '/path/to/page2',
    linkText: 'Page 2'
  }
]

// MyComponent.vue
<template>

        {{ item.linkText }}

</template>

export default {
  data () {
    return {
      links: []
    }
  },
  mounted() {
    axios.get(url).then(response => {
      this.links = items.data
    })
  }
}


text:
Q: Make use of tablet camera within website I am trying to make a website for tablets.
In this application i would like to make use of the camera that is in the tablet.
After a few hours i finally got it to work. So now it is possible to hit the button and the camera will start. After that the image will be written to a html5 canvas.
The problem that i have been having now is that i would like to repeat this process 4 times. So there have to be 4 upload buttons and 4 canvas. Each upload should be made to its own canvas. and be saved in the local storage. I have been trying real hard and tried multiple things but i just can't figure it out.
The problem should be in these 2 functions
    function readURL(input) {
        var canvas = document.getElementById('maincanvas');
        var context = canvas.getContext('2d');
        var imageObj = new Image();

        if (input.files && input.files[0]) {

            var reader = new FileReader();

            reader.onload = function (e) {
                imageObj.src = e.target.result;

                var newWidth = imageObj.width * 0.5;
                var newHeight = imageObj.height * 0.5;

                canvas.width = newWidth;
                canvas.height = newHeight;

                context.drawImage(imageObj, 0, 0, newWidth, newHeight);

                var data = canvas.toDataURL("image/jpeg", 1.0);

                localStorage.setItem("image", data);

                document.getElementById('preview').src = data;

            }

            reader.readAsDataURL(input.files[0]);
        }

    }

    $("#uploader").change(function(){
        readURL(this);
    });

Here is the fiddle: http://jsfiddle.net/bagmaendene/8Locnjp2/
Would be really great if soembody could help me do it.
Thanks in advance


text:
Q: Understanding sed expression 's/^\.\///g' I'm studying Bash programming and I find this example but I don't understand what it means:
filtered_files=`echo "$files" | sed -e 's/^\.\///g'`

In particular the argument passed to sed after '-e'.

A: It's a bad example; you shouldn't follow it.

First, understanding the sed expression at hand.
s/pattern/replacement/flags is the a sed command, described in detail in man sed. In this case, pattern is a regular expression; replacement is what that pattern gets replaced with when/where found; and flags describe details about how that replacement should be done.
In this case, the s/^\.\///g breaks down as follows:

*

*s is the sed command being run.

*/ is the sigil used to separate the sections of this command. (Any character can be used as a sigil, and the person who chose to use / for this expression was, to be charitable, not thinking about what they were doing very hard).

*^\.\/ is the pattern to be replaced. The ^ means that this replaces anything only at the beginning; \. matches only a period, vs . (which is regex for matching any character); and \/ matches only a / (vs /, which would go on to the next section of this sed command, being the selected sigil).

*The next section is an empty string, which is why there's no content between the two following sigils.

*g in the flags section indicates that more than one replacement can happen each line. In conjunction with ^, this has no meaning, since there can only be one beginning-of-the-line per line; further evidence that the person who wrote your example wasn't thinking much.

Using the same data structures, doing it better:
All of the below are buggy when handling arbitrary filenames, because storing arbitrary filenames in scalar variables is buggy in general.

*

*Still using sed:
# Use printf instead of echo to avoid bugginess if your "files" string is "-n" or "-e"
# Use "@" as your sigil to avoid needing to backslash-escape all the "\"s
filtered_files=$(printf '%s\n' "$files" | sed -e 's@^[.]/@@g'`)

*Replacing sed with a bash builtin:
# This is much faster than shelling out to any external tool
filtered_files=${files//.\//}

Using better data structures
Instead of running
files=$(find .)

...instead:
files=( )
while IFS= read -r -d '' filename; do
  files+=( "$filename" )
done < <(find . -print0)

That stores files in an array; it looks complex, but it's far safer -- works correctly even with filenames containing spaces, quote characters, newline literals, etc.
Also, this means you can do the following:
# Remove the leading ./ from each name; don't remove ./ at any other position in a name
filtered_files=( "${files[@]#./}" )

This means that a file named
./foo/this directory name (which has spaces) ends with a period./bar

will correctly be transformed to
foo/this directory name (which has spaces) ends with a period./bar

rather than
foo/this directory name (which has spaces) ends with a periodbar

...which would have happened with the original approach.

A: man sed.  In particular:
-e script, --expression=script
    add the script to the commands to be executed

And:
   s/regexp/replacement/
          Attempt  to match regexp against the pattern space.  If success-
          ful,  replace  that  portion  matched  with  replacement.    The
          replacement may contain the special character & to refer to that
          portion of the pattern space  which  matched,  and  the  special
          escapes  \1  through  \9  to refer to the corresponding matching
          sub-expressions in the regexp.

In this case, it replaces any occurence of ./ at the beginning of a line with the empty string, in other words removing it.


text:
Q: Looping through pandas data frame while changing row values using regex
-EDIT-
As Daniel Kasatchkow (below) suggested, I have attempted the following:
df._links.str.findall('qwer://abc\\\.x-data\\\.orc/v1/i/\d+/users')

But I get the following output:
0    NaN
1    NaN
2    NaN
3    NaN
4    NaN
5    NaN
...

UPDATE - Still unable  to find a solution

A: Try something like this
import pandas as pd

df = pd.DataFrame(["{u'users': {u'href': u'qwer://abc\.x-data\.orc/v1/i/32/users'}, u'self': {u'href': ...","{u'users': {u'href': u'qwer://abc\.x-data\.orc/v1/i/87/users'}, u'self': {u'href': ..."], columns=['_links'])

df._links.str.findall('qwer://abc\\\.x-data\\\.orc/v1/i/\d+/users')

When using regex I find it helpful to trial out the regex on http://pythex.org/
If the data is in a dictionary format, it would be best to convert it over to a DataFrame using pandas.DataFrame.from_dict


text:
Q: show that the function is analytic at the origin $$f(z)=\begin{cases}\frac{\sin z}{z}&z \neq 0\\1&z=0\end{cases} $$
(a).Using the maclaurin expansion for $\sin z$, show that for all $z$,
$f(z)=1-\frac{z^2}{3!}+\frac{z^4}{5!}+\dots$
Attempt:
How would I go about showing this? Could I just claim that this function agrees with dividing the series $\sin z$ by $z$ and adding the fact that $f(0)=1$ corrects for the removable discontinuity which is present at $z=0$ for $\frac{\sin z}{z}$?
I do not know how to go about showing this. Also why would $f$ be analytic at the origin, is it because we have a taylor series representation for the function there?

A: Just write down the expansion of $\sin z$ and divide by $z$ when $z \neq 0$. For $z=0$ verify the equation directly. Analyticity of $f$ follows from the fact that it has a convergent power series expansion.
(For (a) there is no need to prove analyticity of $f$).

A: There's not a whole lot to show. Assuming you know that the definition of an analytic function is it has a convergent power series, you can produce the power series that you did. Just show it converges using, say, the ratio test.


text:
Q: Split Method is not usable on FileReader.result I just wanted to read the last line of my text file. I followed the answer on this TypeScript (Angular) - read text file line by line but the error appear and it says 'split' does not exist on type 'string | ArrayBuffer'
fileChanged(e) {
    this.file = e.target.files[0];
    if(this.file){
        let fileReader = new FileReader();
        fileReader.onload = (e) => {
            console.log(fileReader.result);
            var contents=fileReader.result;
            for (const line of contents.split(/[\r\n]+/)){
            console.log(line);
                }
        }
        fileReader.readAsText(this.file);
}

A: The result you are getting is in string | ArrayBuffer type, not string type. In order to use split method cast the result into string.
const line of (contents as string).split(/[\r\n]+/)


text:
Q: How to prevent Spotipy from adding incorrect song to playlist? Working through Angela Yu's 100 days of code and am on a project where the user inputs a YYYY-MM-DD to search for a list of 100 songs from billboard top 100 for that date. Those songs are webscraped and added to a playlist via Spotipy. However, I noticed that songs from unwanted years get added. For example, if I entered 1996-11-15, a Bruno Mars song would appear on my playlist, which isn't from 1996.
To prevent this, I added more conditionals in the for loop to search for exact song name and artist name, then I added an empty list called "duplicate_check" where I would add a song name for  a song that's already been added to the playlist list. The problem with this is I get less than 100 songs now.
How do I get 100 songs that are exactly from the billboards top 100 for the requested date?
# Asks user to input YYYY-MM-DD.
time_period = input("What year would you like to travel to in YYYY-MM-DD format? ")
year = time_period.split("-")[0]

url = f"https://www.billboard.com/charts/hot-100/{time_period}/"

# Initialize BS to parse url above.
response = requests.get(url)
webpage = response.text
soup = BeautifulSoup(webpage, "html.parser")

# Scrapes Billboard page to find song titles
song_titles = soup.select(selector="ul li h3")
song_artists = soup.select(selector="li ul li span")
artist_list = [artist.getText().strip() for artist in song_artists[0:700:7]]
song_list = [title.getText().strip() for title in song_titles[0:100:1]]

song_uri_list = []
# The purpose of this list is to prevent duplication by adding the song name to this list, once the uri is added.
duplicate_check = []

# Using params and header, creates a POST request to create new playlist on my account.
params = {
    "name": f"{time_period} Billboard 100",
    "public": False,
    "collaborative": False,
}

# Gets Access Token from .cache file generated after initializing spotipy API.
with open(".cache", "r") as file:
    data = file.read().split()
    token = data[1].strip(',"')

header = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json",
}

# Initializes Spotipy API.
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope="playlist-modify-private",
                                               client_id=SPOTIFY_CLIENT_ID,
                                               client_secret=SPOTIFY_CLIENT_SECRET,
                                               redirect_uri=SPOTIPY_REDIRECT_URI,
                                               cache_path=".cache"
                                               ))

# Creates a playlist on my account.
response = requests.post(url=f"{SPOTIFY_ENDPOINT}/users/{SPOTIFY_USER_ID}/playlists", json=params, headers=header)
playlist_uri = json.loads(response.text)["uri"]

# Searches Spotify for each song scraped from url via a unique URI and adds it to a list.
for song, artist in zip(song_list, artist_list):
    results = sp.search(q=f"track: {song} artist: {artist} year: {year}", type="track")
    for dict in results["tracks"]["items"]:
        if dict["name"] == song and dict["artists"][0]["name"] == artist and song not in duplicate_check:
            try:
                song_uri_list.append(dict["uri"])
                duplicate_check.append(song)
            except IndexError:
                print("no song found")
                pass

# Adds list of songs to playlist.
sp.playlist_add_items(
    playlist_id=playlist_uri,
    items=song_uri_list,
    position=None
)

A: Fetch more initially, 120 should suffice,
artist_list = [artist.getText().strip() for artist in song_artists[0:840:7]]
song_list = [title.getText().strip() for title in song_titles[0:120:1]]

and then take only 100 unique songs:
# Searches Spotify for each song scraped from url via a unique URI and adds it to a list.
for song, artist in zip(song_list, artist_list):
    # take only 100 songs
    if len(duplicate_check >= 100):
        break
    results = sp.search(q=f"track: {song} artist: {artist} year: {year}", type="track")
    ...


text:
Q: raise ValueError("name for name_scope must be a string." I have defined doubled conv layers in Keras, to use it as a reference in the Unet architecture, like this:
class ConvBlock(keras.Model):
  def __init__(self,in_channels):
    super(ConvBlock,self).__init__()
    self.in_channels = in_channels
    self.conv = keras.Sequential(
        layers.Conv2D(filters=self.in_channels,kernel_size=(3,3),strides=(1,1),padding="same",use_bias=False),
#       layers.BatchNormalization(),
#       layers.ReLU(),
        layers.Conv2D(filters=self.in_channels,kernel_size=(3,3),strides=(1,1),padding="same", use_bias=False),
#       layers.BatchNormalization()
#       layers.ReLU(),
    )

  def call(self,input_tensor):
    return self.conv(input_tensor)

During the unit test, i got this error: ValueError: name for name_scope must be a string.
Here is my code test, a very simple one ..
model = ConvBlock(64)
y = tf.random.uniform((2,32,32,3))
print(model(y).shape)

A: tf.keras.keras.Sequential takes list of layers, please try the following:
    self.conv = keras.Sequential([
        layers.Conv2D(filters=self.in_channels,kernel_size=(3,3),strides=(1,1),padding="same",use_bias=False),
        layers.Conv2D(filters=self.in_channels,kernel_size=(3,3),strides=(1,1),padding="same", use_bias=False),
        ]
    )


text:
Q: python-ldap to get data from server 2003 when I test the following command in Centos
ldapsearch -v -d5 ldaps://192.168.0.254 -D "cn=xuqifeng" -w 'xuqifeng'

sys tell me:
ldap_initialize( <DEFAULT> )
ldap_create
ldap_sasl_bind
ldap_send_initial_request
ldap_new_connection 1 1 0
ldap_int_open_connection
ldap_connect_to_host: TCP localhost:389
ldap_new_socket: 3
ldap_prepare_socket: 3
ldap_connect_to_host: Trying ::1 389
ldap_pvt_connect: fd: 3 tm: -1 async: 0
ldap_close_socket: 3
ldap_new_socket: 3
ldap_prepare_socket: 3
ldap_connect_to_host: Trying 127.0.0.1:389
ldap_pvt_connect: fd: 3 tm: -1 async: 0
ldap_close_socket: 3
ldap_err2string
ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1)

OMG,Help.ps:System which host ip is 192.168.0.254 is Microsoft Server 2003.

A: You are not providing correct host parameter to ldapsearch.
Use -H  to achieve that
ldapsearch -v -d5 -H ldaps://192.168.0.254 -D "cn=xuqifeng" -w 'xuqifeng'
But this has nothing to do with python


text:
Q: Delay in parallel computing I'm using parallel.for to launch in many threads a external program. But despite the fact that these are separate threads I need implement sth like delay. E.g. 2 threads want to launch this external program at the same moment - then one of them should wait and start e.g. 10 sec after second thread.
Is it possible?

A: It's possible, but given the information you've provided it seems pointless... you're enforcing single-threaded execution of the external program, so you might as well have a single thread executing it. If Thread 2 has to wait for Thread 1 in order to start the "external program," then just let Thread 1 do all the work since it already knows when it started the "external program."
The only benefit you will get from a multi-threaded approach is if you have a bunch of processing that you need to do prior to executing the "external program" and that processing has to be a good candidate for concurrent execution.
Update
OK, there are a couple of ways to do this with only one extra thread in order to keep your Main/GUI thread responsive. The first approach is a simple lock around the external resource which you're interacting with:
public class ExternalResourceHandler
{
    private readonly ExternalResource _resource;
    private readonly object _sync = new object();

    // constructors
    // ...
    // other methods

    public void PerformExternalOperation()
    {
        lock(_sync)
        {

            Result result = _resource.Execute();

            // do soemthing with the result
        }
    }
}

Here are 3 multi-threaded version for executing the code:

*

*Using a Parallel.For method: recommended if the external program takes a short amount of time to execute- I'd suggest for things under 25 seconds (although this is not necessarily a "correct" number).

*Using a ThreadPool: again, I'd recommend for things that take less than 25 seconds (with the same reservation as above).

*Using a Thread: this would be recommended if the operation runs longer (i.e. more than 25 seconds, but it would do just as good if it's under 25 seconds).

Here are some examples (not necessarily functional, mostly meant to give you an idea of the different approaches):
public class Program
{
    public static ExternalResourceHandler _erh = new ExternalResourceHandler();

    static int Main()
    {
        Console.WriteLine("Type 'exit' to stop; 'parallel', 'pool' or 'thread' for the corresponding execution version.");
        string input = Console.ReadLine();
        while(input != "exit")
        {
            switch(input)
            {
            case "parallel":
                // Run the Parallel.For version
                ParallelForVersion();
                break;
            caase "pool":
                // Run the threadpool version
                ThreadPoolVersion();
                break;
            case "thread":
                // Run the thread version
                ThreadVersion();
                break;
            default:
                break;
            }
            input = Console.ReadLine();
        }
        return 0;
    }

    public static void ParallelForVersion()
    {
        Parallel.For(0, 1, i =>
        {
            _erh.PerformExternalOperation();
        });
    }

    public static void ThreadPoolVersion()
    {
        ThreadPool.QueueUserWorkItem(o=>
        {
            _erh.PerformExternalOperation();
        });
    }

    public static void ThreadVersion()
    {
        Thread t = new Thread(()=>
        {
            _erh.PerformExternalOperation();
        });
        t.IsBackground = true;
        t.Start();

    }
}

The other option is to employ the Producer/Consumer design pattern where your ExternalResourceHandler is the consumer and it processes requests to the external resource from a thread-safe queue. Your main thread just places requests on the queue and immediately returns back to work.  Here is an example:
public class ExternalResourceHandler
{
    private volatile boolean _running;
    private readonly ExternalResource _resource;
    private readonly BlockingQueue<Request> _requestQueue;

    public ExternalResourceHandler( BlockingQueue<Request> requestQueue)
    {
        _requestQueue =  requestQueue;
        _running = false;
    }

    public void QueueRequest(Request request)
    {
        _requestQueue.Enqueue(request);
    }

    public void Run()
    {
        _running = true;
        while(_running)
        {
            Request request = null;
            if(_requestQueue.TryDequeue(ref request) && request!=null)
            {
                _resource.Execute(request);
            }
        }
    }

    // methods to stop the handler (i.e. set the _running flag to false)
}

Your main would look like this:
public class Program
{
    public static ExternalResourceHandler _erh = new ExternalResourceHandler();

    static int Main()
    {
        Thread erhThread = new Thread(()=>{_erh.Run();});
        erhThread.IsBackground = true;
        erhThread.Start();

        Console.WriteLine("Type 'exit' to stop or press enter to enqueue another request.");
        string input = Console.ReadLine();
        while(input != "exit")
        {
            _erh.EnqeueRequest(new Request());
            input = Console.ReadLine();
        }

        // Stops the erh by setting the running flag to false
        _erh.Stop();

        // You may also need to interrupt the thread in order to
        // get it out of a blocking state prior to calling Join()
        erhThread.Join();
        return 0;
    }
}

As you see: in both cases all the work for the external handler is forced on a single thread yet your main thread still remains responsive.

A: Look at producer-consumer pattern. The first thread produces the information "external progam launched" the second thread consumes it, waits 10 second and then launches the external program.


text:
Q: Read from internal storage in Windows Phone 8? Is there a way to access the internal file storage in Windows Phone 8? I noticed that there is a way to read files from the SD card http://msdn.microsoft.com/en-us/library/windowsphone/develop/microsoft.phone.storage(v=vs.105).aspx but what about the phones that don't have an SD card slot, like the Nokia Lumia 920?

A: I am not sure where specifically you mean by internal storage, but there are a few locations you can access on the device.
Application Data (Formerly Isolated Storage)
This is the bread and butter location for an app to access. It is your own private location to store settings or files that you may have.
It can be accessed with:
StorageFolder localRoot = ApplicationData.Current.LocalFolder:

There is more documentation here with examples as well.
Libraries
These are common locations where apps are able to store and access media data. Accessing these requires declaring the capability for the area you are accessing and the file associations for the files you would like to see.
For example getting the camera roll folder would require the following:
In WMAppManifest:
<Capability Name="ID_CAP_MEDIALIB_PHOTO" />

The C#
StorageFolder cameraRoll = KnownFolders.CameraRoll;

There is more documentation of the different capabilities in the designer in Visual Studio. (The summaries there are easier to get a brief understanding with than the full MSDN articles.)
KnownFolders has access to all of the different locations that you can get at internally using it. Careful though, some of the locations are Windows or Phone specific, but they are all documented so you know which.


text:
Q: Android TV Gridview dpad composed items I'm sorry if this question has been answered before. Honestly, I have searched this issue a lot and although there are similar cases, none of them helped me.
I am developing an Android Application for a TV. I have created a GridView because I want to show some thumbnails of pictures and videos. Each item in the gridview has a picture and a text info below.
The problem is that I can't get the dpad to work properly. If I set android:focusable="true" in the items, I can navigate through the GridView, but I can't display the image/video after pressing enter or using the mouse (no call to "onItemClick()"). If I do not set android:focusable="true", I can't navigate through the GridView (maybe cuz I do not see it) and also I can't press enter and see the image/video, but I do can click with the mouse the item and see the image/video.
What can I do to make the dpad work properly?
Thank you very much in advance. I have been struggling with this since a big while, I would sincerely appreciate your help.

A: I faced the exact same problem yesterday. What you need to do is add an onKeyListener to the GridView and inside the onKey function handle the key presses. I'll share what I did with it so that you can build on it.
gridView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
                Toast.makeText(getActivity(), "CENTER", Toast.LENGTH_SHORT).show();
                if(gridView.getSelectedItemPosition() == -1){
                    if(gridView.getCount() > 0)
                        gridView.setSelection(0);
                    else
                        return false;
                }
                CURRENT_VIDEO_NUM = gridView.getSelectedItemPosition();
            }
            else{
                switch(keyCode){
                    case KeyEvent.KEYCODE_DPAD_RIGHT:
                        Toast.makeText(getActivity(), "RIGHT", Toast.LENGTH_SHORT).show();
                        if(event.getAction() == 0){
                            try {
                                if (gridView.getSelectedItemPosition() < gridViewAdapter.getCount() - 1) {
                                    gridView.setSelection(gridView.getSelectedItemPosition() + 1);
                                    return true;
                                }
                            } catch (Exception e) {
                                gridView.setSelection(gridViewAdapter.getCount() - 1);
                                return true;
                            }
                        }
                        break;
                    case KeyEvent.KEYCODE_DPAD_LEFT:
                        Toast.makeText(getActivity(), "LEFT", Toast.LENGTH_SHORT).show();
                        if(event.getAction() == 0){
                            try {
                                if (gridView.getSelectedItemPosition() > 0) {
                                    gridView.setSelection(gridView.getSelectedItemPosition() - 1);
                                    return true;
                                }
                            } catch (Exception e) {
                                gridView.setSelection(0);
                                return true;
                            }
                        }
                        break;
                    case KeyEvent.KEYCODE_DPAD_UP:
                        Toast.makeText(getActivity(), "UP", Toast.LENGTH_SHORT).show();
                        break;
                    case KeyEvent.KEYCODE_DPAD_DOWN:
                        Toast.makeText(getActivity(), "DOWN", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        Toast.makeText(getActivity(), "ELSE" + keyCode, Toast.LENGTH_SHORT).show();
                        break;

                }
            }
            return false;
        }
    });

Now let me explain whats happening here.
1) I check if the center button is pressed, if thats the case, I'll perform the action that is to be performed when an item is clicked.
2) If RIGHT button is pressed, the selection is moved to right and the same for the left one.
3) UP and DOWN are a little less trivial. Since I was just building a demo, I didn't spend time on it. Won't be a problem though, just increment/decrement the total number of columns of the grid view keeping in mind the max/min of the items.
Try building on it and if you face any issue, do let me know.


text:
Q: Derived template override return type of member function C++ I am writing matrix classes. Take a look at this definition:
template <typename T, unsigned int dimension_x, unsigned int dimension_y>
class generic_matrix
{
  ...
  generic_matrix<T, dimension_x - 1, dimension_y - 1>
  minor(unsigned int x, unsigned int y) const
  { ... }
  ...
}

template <typename T, unsigned int dimension>
class generic_square_matrix : public generic_matrix<T, dimension, dimension>
{
  ...
  generic_square_matrix(const generic_matrix<T, dimension, dimension>& other)
  { ... }
  ...
  void foo();
}

The generic_square_matrix class provides additional functions like matrix multiplication.
Doing this is no problem:
generic_square_matrix<T, 4> m = generic_matrix<T, 4, 4>();

It is possible to assign any square matrix to M, even though the type is not generic_square_matrix, due to the constructor. This is possible because the data does not change across children, only the supported functions. This is also possible:
generic_square_matrix<T, 4> m = generic_square_matrix<T, 5>().minor(1,1);

Same conversion applies here. But now comes the problem:
generic_square_matrix<T, 4>().minor(1,1).foo(); //problem, foo is not in generic_matrix<T, 3, 3>

To solve this I would like generic_square_matrix::minor to return a generic_square_matrix instead of a generic_matrix. The only possible way to do this, I think is to use template specialisation. But since a specialisation is basically treated like a separate class, I have to redefine all functions. I cannot call the function of the non-specialised class as you would do with a derived class, so I have to copy the entire function.
This is not a very nice generic-programming solution, and a lot of work.
C++ almost has a solution for my problem: a virtual function of a derived class, can return a pointer or reference to a different class than the base class returns, if this class is derived from the class that the base class returns. generic_square_matrix is derived from generic_matrix, but the function does not return a pointer nor reference, so this doesn't apply here.
Is there a solution to this problem (possibly involving an entirely other structure; my only requirements are that the dimensions are a template parameter and that square matrices can have additional functionality).
Thanks in advance,
Ruud

A: You could just implement the function in the derived class without making it virtual.  This will "hide" the base class implementation and may be desirable for your use despite the general aversion to hiding member functions.
A better method might be to just use a different name, although that may upset the "purity" of your interface.
Finally- could minor() be implemented as a free function instead of a member function?  Then you could provide overloads as appropriate, and the correct function would be called at compile time.  This is the closest to the method hiding case I opened with, but I suspect it would be more generally accepted as "good practice."

A: There is no need for complicating the design if you can simply make minor() a free function:
template<typename T, unsigned int X, unsigned int Y>
generic_matrix<T, X-1, Y-1>
minor(const generic_matrix<T, X, Y>& m, unsigned int x, unsigned int y);

... then you can add alternative versions as much as you want.

A: If you don't use these types polymorphically, you could just override the base class method in the derived class non-virtually so that it returns a derived class object. It would hide the base class version, which usually isn't wanted, but in your case it seems it is.
Or you make these member functions free function templates, if necessary with overloads for different types of matrices. (Although templatization might take care of that automatically.)

A: Template specialization will work.  What you do is take the shared code and put it in a base class and then just inherit from both.  Protect the destructor in the base so that nobody can break your concept by casting to the base and trying to delete it.
Something like so:
namespace detail_
{
  template < typename T >
  struct my_templates_common_functionality
  {
    void f1() {}
    void f2() {}
  protected:
    ~my_templates_common_functionality() {}
  };
}

template < typename T >
struct my_template : detail_::my_templates_common_functionality<T>
{
  int f3() { return 5 }
};

template < >
struct my_template<double> : detail_::my_templates_common_functionality<double>
{
  char* f3() { return nullptr; }
};

There are other ways, but that's one of the easiest.


text:
Q: How to print items from a tkinter window onto an external file? I'm trying to transfer the content of a window onto an external file but when I do, it shows incomplete amount of items. How do I make it so that the rec_content shows everything?
Code:
 get_content = listbox2.get(0, END) # Get the items selected by user
            bb = Label(receipt_window, text="Bert's Burgers")
            line1 = Label(receipt_window, text='----------------------------------------------------------------')
            bb.pack()
            line1.pack()
            for con_item in get_content: # Split the item into two variables to format text
                con1, con2 = con_item.split('PHP')
                rec_content = f'{con1:<30}costs PHP{con2:<8}'
                receipt = Label(receipt_window, text=rec_content)
                receipt.pack()

 item_list = [str(rec_content), "Cost" + str(cost), "Cash Paid" + payment.get(), "Change" + str(change_formula)]
                    with open("receipt.txt", "w") as f:
                        for line in item_list:
                            f.write(line)
                            f.write("\n")

Window Content:

Result:

Desired Result:

A: A very easy and convenient way to format text is to use a triple quote string.
This enables you to quickly organise or modify your receipt.
Here is a demonstration.
con1 = 1
con2 = 130
con3 = 2
con4 = 100
con5 = 3
con6 = 75

cost = con2 + con4 + con6
payment = 310
change = payment - cost

receipt = f"""
                       Bert's Burgers
        {con1} pc(s) Vegan Burger     costs PHP {con2}
        {con3} pc(s) Big Fries        costs PHP {con4}
        {con5} pc(s) French Fries     costs PHP {con6}
----------------------------------------------------------------
                     Total Cost: PHP {cost}
                  Cash Tendered: PHP {payment}
                         Change: PHP {change}
"""

with open("receipt.txt", "wt") as f:
    f.write(receipt)

with open("receipt.txt", "rt") as f:
    receipt = f.read()

print(receipt)

A: You have the similar issue as in your last question: You have used same variable rec_content in the for loop, then add this variable into item_list outside the for loop.  So item_list will have the last item in the for loop.
You need to append rec_content into item_list in the for loop:
    item_list = []
    for con_item in get_content:
        con1, con2 = con_item.split('PHP')
        rec_content = f'{con1:<30}costs PHP{con2:<8}'
        receipt = Label(receipt_window, text=rec_content)
        receipt.pack()
        item_list.append(rec_content)

    item_list += [f'Cost {cost}',
                  f'Cash Paid {payment.get()}',
                  f'Change {change_formula}']

    with open('receipt.txt', 'w') as f:
        f.write('\n'.join(item_list))


text:
Q: MongoDB Filter with Interval I have a database query that selects all documents having a timestamp field (tmp) falling in a certain range, like so
{ tmp: { '$gte': 1411929000000, '$lte': 1419010200000 } }

This query returns a large number of records, say 10000.
Objective:
To fetch documents in the same interval range, but separated by say (1 hour timestamp) interval in between hence reduce the number of records that is fetched.
Is there a way of doing this entirely using MongoDB query system?
Any comments would be very helpful. Thanks.
EDITED:
Please see the comment below for more info:
MongoDB Filter with Interval


text:
Q: Redefine \or form within a nested if statement? It's apparently a bad idea to redefine \or so that it renders as \lor in mathmode. However, while trying anyhow, I faced two issues that I would like to understand better.
I followed the approach 1, 2
\let\@oldor\or
\def\or{\ifmmode\lor\else\expandafter\@oldor\fi}

However, after moving that into another if statement (checking the package option overwrite \or) it stopped working. Instead,  I got the ! Extra \or. error.
By chance, I discovered that I get the same error when I'm trying to use \verb|\or| in a footnote (overleaf).
Any chance how I can rewrite the \def without the expandafter, so that it works anywhere, no matter how many if statements are nested?

A: TL;DR
You can't redefine \or.
Longer answer
Consider this plain TeX example:
\let\originalor\or
\def\or{\ifmmode\lor\else\expandafter\originalor\fi}

$a\or b$ (works)

\ifcase1
  0\or
  1\or
  2\else
  BUMMER\fi

\let\or\originalor

\ifcase1
  0\or
  1\or
  2\else
  BUMMER\fi

\bye

Guess what you get from the two \ifcase statements. Yes, the first one yields "BUMMER", while the other one, with \or restored to its primitive meaning, yields the expected 1.
Why is that? In order to skip the cases, TeX needs to see the primitive \or (a control sequence let to the primitive \or would do as well). So if you redefine \or, no macro based on \ifcase will work as expected.
Well, they will work, but only when the tested integer is 0, because in this case TeX will expand the redefined \or, finding \originalor and so skipping up to the matching \fi. In the "BUMMER" case, the whole 0\or 1\or 2 counts as the text for the 0 case (because there is no primitive \or in it).
This is essentially the same as redefining \fi or any other conditional.

A: Just want to point out something that may be obvious (and in your case you've surely considered already), but is often ignored: if your desire is simply that you'd like to type \or in your personal .tex file or in formulas, and have it treated as if you'd typed \lor, then you can do this by processing the input (specifically, the parts entered manually by you or the user) externally, rather than via a TeX macro.
(For simplicity of illustration let's assume you want \or treated as \lor everywhere in your input file, not just in math mode. The example below shows that redefining \or only in math mode can also cause issues, so there's not much to gain by treating math mode specially anyway.)
Concretely, consider the following input file:
\documentclass{article}
\usepackage{amsmath}
\begin{document}

\makeatletter
\let\@oldor\or
\def\or{\ifmmode\lor\else\expandafter\@oldor\fi}
\makeatother

\begin{equation}
(x < 0) \or (x = 0) \or (x > 0)
\end{equation}

\begin{align}
\allowdisplaybreaks[1]
a &= b \\
c &= d
\end{align}
\end{document}

It fails with a hard-to-debug error on reaching the \end{align} line, because \allowdisplaybreaks uses \or internally. See the following from amsmath.sty:
\interdisplaylinepenalty\@M
\newcommand{\allowdisplaybreaks}[1][4]{%
  \interdisplaylinepenalty\getdsp@pen{#1}\relax
}
\def\getdsp@pen#1{%
  \ifcase #1\@M \or 9999 \or 6999 \or 2999 \or \z@\fi
}

Instead of redefinining \or in TeX, we can get rid of the redefinition (the part inside \makeatletter … \makeatother above), and simply replace every occurrence of \or with \lor with an external script. (E.g. something like sed 's/\\or\([^a-zA-Z]\)/\\lor\1/g' on your file will do.)
With LuaTeX (if our setup allows using that, which in your Mediawiki-texvc case probably not) we can do this inside the file itself if we want:
\documentclass{article}
\usepackage{luacode}
\usepackage{amsmath}
\begin{document}

\begin{luacode*}

luatexbase.add_to_callback('process_input_buffer',
                           function(line)
                              return line:gsub([[\or([^a-zA-Z])]], [[\lor%1]])
                           end,
                           [[Replaces each \or in the input with \lor]])

\end{luacode*}

\begin{equation}
(x < 0) \or (x = 0) \or (x > 0)
\end{equation}

\begin{align}
\allowdisplaybreaks[1]
a &= b \\
c &= d
\end{align}
\end{document}

Unlike the earlier version, this doesn't cause any issues from uses of \or in macros that were defined earlier.


text:
Q: HERE Maps: change visibility of a cluster layer Once a cluster is created and added to a map with this:
let layer = new H.map.layer.ObjectLayer(clusteredDataProvider);
map.addLayer(layer);

How can one change the layer visibility (show/hide) ?

A: You can use the removeLayer() method for that. For example:

var handleClusterLayer = function(cb)
{
  if(cb.checked)
  map.addLayer( clusterOverlayLayer );
  else
  map.removeLayer( clusterOverlayLayer );
};