text:
Q: CMake use flags for specific configuration in external project I'm using ExternalProject_Add to build an external make-based project. I'd like to propagate flags according to the current build-configuration.
I basically have to following command:
ExternalProject_Add(
        ...
        BUILD_COMMAND make CFLAGS=${CMAKE_C_FLAGS_???}
        ...
        )

and I want to use CMAKE_C_FLAGS_DEBUG when the project is built in Debug, or whatever the current configuration is. How can that be done? I've tried this, but it doesn't parse:
ExternalProject_Add(
        ...
        BUILD_COMMAND make CFLAGS=${CMAKE_C_FLAGS_$<CONFIG>}
        ...
        )

A: I haven't found a proper solution, but a reasonable compromise. Since the most important thing for us was to use the correct flags in the release build, I'm now checking specifically for that, using this rather convoluted workaround for the lack of if-then-else in generator expressions prior to 3.8:
set(default_flags "${CMAKE_C_FLAGS} -g -O2")
set(release_flags "${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_RELEASE}")
set(flags $<$<CONFIG:Release>:${release_flags}>$<$<NOT:$<CONFIG:Release>>:${default_flags}>)

ExternalProject_Add(
    ...
    BUILD_COMMAND make CFLAGS=${flags}
    ...
    )


text:
Q: Unknown C# Error Hi I don't know why C# is having a parsing error on my last Curly Bracket, sorry if it is very simple im new to C# here is the code.
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour
{
    public string IP = "192.168.0.8";
    public int Port = "25001";

    void OnGUI()
    {
        if(Network.peerType == NetworkPeerType.Disconnected)
        {
            if (GUI.Button(new Rect(100,100,100,25),"Join Existing Server"))
            {
                Network.Connect(Ip,Port);
            }

            if (GUI.Button(new Rect(100,125,100,25),"Create New Server"))
            {
                Network.InitializeServer(10,Port);
                //First Number Above next to port in perenthisies is number of allowed clients / 1x Server (# of players allowed to join game.)
            }
            else
            {
                if(Network.peerType == NetworkPeerType.Client)
                {
                    GUI.Label(new Rect(100,100,100,25),"Client");
                    if(GUI.Button (new Rect(100,125,100,25),"Disconnect"))
                    {
                        Network.Disconnect(250);
                    }
                }
                if(Network.peerType == NetworkPeerType.Server)
                {
                    GUI.Label(new Rect(100,100,100,25),"Server");
                    GUI.Label(new Rect(100,125,100,25),"Connections: " + Network.connections.Length);

                    if(GUI.Button (new Rect(100,125,100,25),"Disconnect"))
                    {
                        Network.Disconnect(250);

                }
            }
        }
    }
}

The last "}" is coming up red any help would be appreciated thanks!
Just so people don;t get confused it is supposed to be a server and client for an on-line video game but it won't let me run the game with the error. I have tried to improve the formatting and remove blank space but none seemed to work, I have also made sure that there are the right amount of closing bracket at the end of the code so I have no Idea what is wrong.

A: Add a closing bracket after:
if(GUI.Button (new Rect(100,125,100,25),"Disconnect"))
{

    Network.Disconnect(250);

It's missing.

A: After formatting your code, I can see you're missing one final closing brace.
Add a closing brace } at the very end of your code snippet above.

A: I appreciate the question is not to do with this, but just to help, the error regarding:

cannot implicitly convert type string to int

can be solved by changing your code to the following:
public class NewBehaviourScript : MonoBehaviour {

    public string IP = "192.168.0.8";
    public string Port = "25001";

or
public class NewBehaviourScript : MonoBehaviour {

    public string IP = "192.168.0.8";
    public int Port = 25001;

A: This is your code with correction. Be careful about the brackets.
using UnityEngine;

using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

public string IP = "192.168.0.8";
    public int Port = "25001";

    void OnGUI()
    {

        if(Network.peerType == NetworkPeerType.Disconnected)
        {

            if (GUI.Button(new Rect(100,100,100,25),"Join Existing Server"))
            {

            Network.Connect(Ip,Port);

            }

            if (GUI.Button(new Rect(100,125,100,25),"Create New Server"))
            {

            Network.InitializeServer(10,Port);
                //First Number Above next to port in perenthisies is number of allowed clients / 1x Server (# of players allowed to join game.)

            }

            else
            {

            if(Network.peerType == NetworkPeerType.Client)
                {

                    GUI.Label(new Rect(100,100,100,25),"Client");
                    if(GUI.Button (new Rect(100,125,100,25),"Disconnect"))
                    {

                        Network.Disconnect(250);

                    }

                }
                if(Network.peerType == NetworkPeerType.Server)
                {

                    GUI.Label(new Rect(100,100,100,25),"Server");
                    GUI.Label(new Rect(100,125,100,25),"Connections: " + Network.connections.Length);

                    if(GUI.Button (new Rect(100,125,100,25),"Disconnect"))
                    {

                        Network.Disconnect(250);

                    }
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the difference between the assignments to pointers in C? //C - code
int num
int *pi = # //1
printf(" *pi=%d  and  pi=%d \n ", *pi, pi);  // p1
pi = #      //2
printf(" *pi=%d  and  pi=%d \n ", *pi, pi);  // p2

As for comment 2, I understand that we are assigning a valid address to the pointer pi but I don't understand what is happening in the line of comment 1 because because both the printf() statements p1 and  p2 are doing the same job.
And in case of dynamic memory management with malloc(sizeof(datatype)) function, why the following is an invalid approach?
int *pi;
*pi = (int*)malloc(sizeof(int)); // terminates the program

while the following:
int *ri = (int*)malloc(sizeof(int));

and
int *qi;
qi = (int*)malloc(sizeof(int));

works fine.
Please explain.
EDIT : The question marked as duplicate to this question doesn't talk about pointers  and problems that we face during dynamic memory management.

A: You are getting confused between the use of * in the declaration of a pointer and the use of * as the dereferencing operator.
To understand better, while declaring, you can write int *p as (int*) p.
This means, that p is of type 'pointer to an int'.
However, * is also the dereferencing operator, or the 'value at' operator.
So, *pi = value at pi, i.e., the value stored at the location of num, i.e., the value of num.
int *pi;
*pi = (int*)malloc(sizeof(int));

crashes becuse you try to assign the result of (int*)malloc(sizeof(int)) to the location where pi is pointing. but as pi is not pointing anywhere (it is uninitialized), hence, it doesn't work.
On the other hand,
int *ri = (int*)malloc(sizeof(int));

works because you are making ri point to the location where the result of (int*)malloc(sizeof(int));  is stored.
int *qi;
qi = (int*)malloc(sizeof(int));

also works because you are making qi point to the location where (int*)malloc(sizeof(int)); is stored.

A: You should understand what is a pointer.
A pointer should hold a valid memory address.
int *p;

Here p is a pointer which holds the memory address and *p is called dereferencing a pointer. In other words *p gives the value stored in the location p.
So during dynamic memory allocation
int *p = malloc(sizeof(int) );

Here pointer p is assigned the address returned by malloc().
int *p;

p = malloc(sizeof(int));

Again pointer is being assinged the value returned by malloc(). Note that I am not using *p because still memory is not allocated for my pointer p
int num;
int *p = #

Assignment is proper but before intializing the variable if you deference then you get erroneous results.
int num = 10;
int *p = #

Now *p gives 10.

A: int *pi;
*pi = (int*)malloc(sizeof(int)); // terminates the program

So you define a pointer variable without initializing it. It now contains an unspecified address. You then try and write to that unspecified address. That's undefined behavior according to the standard, and your run-time is kind enough to crash, so you'd know there's a problem.
int *qi;
qi = (int*)malloc(sizeof(int));

You again define a pointer variable, which again holds an unspecified address. But in the very next line, you assign to the variable some (probably valid) address. So all is well (so far).
So you you see, the two cases are different. In the first, you de-reference the pointer and assign to that (unspecified address), and in the second you assign to the pointer.

A: The last time I programmed in C was more than 10 years ago, but AFIK, your first example crashes, because you assign the result of the malloc() to *pi (you try to assign the result of malloc to the address pi currently points to. Since *pi was not initialized, this crashes your program).


text:
Q: Is it possible to lookup for a value from another sheet in the same workbook? I have a workbook with multiple spreadsheets. One of the sheets is called "Master Filtered" and the other is called "MTL OR TOR"
I want to fill in the column K of the "Master filtered" sheet with a lookup value from the "MTL or TOR" sheet in the second column. I wrote this piece of code but it is not working.
Sub MTL_OR_TOR()
    Dim AcctNb As String
    Dim result As String

    Worksheets("Master Filtered").Activate
    Dim lastrow As Long
    lastrow = Cells(Rows.Count, 1).End(xlUp).Row

    For G = 4 To lastrow

    AcctNb = Cells(G, 3).Value

    Set myrange = Worksheets("MTL OR TOR").Range("AA4:AB685") 'Range in which the table MTL or TOR should be entered
    result = Application.WorksheetFunction.VLookup(AcctNb, myrange, 2, False)

    Range("K" & G).Value = result
    Next

End Sub

Do you have any idea why is this code not working and how to fix it?
I was thinking maybe my error is in the line starting with Set myrange= Worksheets("MTL OR TOR") but couldn't figure it out.

A: Sub MTL_OR_TOR()
    ' Name your variables in a meaningful way and indicate their type
    Dim strAcctNb As String
    Dim strResult As String
    Dim lngLastRow As Long
    Dim lngLoop As Long
    Dim rngLookup As Range

    'Set your range and variables before you execute the code for readability
    Set rngLookup = Worksheets("MTL OR TOR").Range("AA4:AB685") 'Range in which the table MTL or TOR should be entered

    'Do not Activate or Select unless you really have to
    'Worksheets("Master Filtered").Activate

    With Worksheets("Master Filtered")

        lngLastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

        For lngLoop = 4 To lngLastRow
            strAcctNb = .Cells(lngLoop, 3).Value
            strResult = Application.WorksheetFunction.VLookup(strAcctNb, rngLookup, 2, False)
            .Range("K" & lngLoop).Value = strResult
        Next

    End With

End Sub


text:
Q: How to disable internationalization for all bundle's all routes when using JMSI18nRoutingBundle? I use Symfony2's JMSI18nRoutingBundle to allow automatic internationalization of my routes. Individual route internationalization can be disabled in routing.yml as follows
index:
  pattern: /
  defaults: { _controller: AcmeBaseBundle:Welcome:indexRedirector }
  options:
    i18n: false

However, I normally annotate routes in the controllers and define just a prefix in routing.yml:
AcmeApiBundle:
  resource: "@AcmeApiBundle/Controller/"
  type:     annotation
  prefix:   /api
  options:
    i18n: false

In this case, disabling internationalization does not work properly and routes get matched only by adding the locale as a prefix for the URLs.
How to disable the internationalization for the all URLs in the bundle?

A: Specify the option in the annotations. Something like:
/**
 * @Route("/", options={"i18n" = false})
 */


text:
Q: Como voltar para a página anterior com botão físico do smartphone - Ionic Como permito que o botão físico voltar do celular realize uma determinada função no Ionic 3? (No caso, uma função que faz o aplicativo abrir a página inicial)

A: Boa tarde Teiji, você pode utilizar o serviço Platform, com ele você pode registrar a ação do botão com uma função, por exemplo:
export class AnyPage{

  constructor(private navCtrl: NavController,
              private platform: Platform) {
    this.platform.registerBackButtonAction(() => {
      this.navCtrl.pop();
    });
  }
}

A partir desse momento, sempre que você apertar o botão físico do celular, ele executará o this.navCtrl.pop(), mas não sei se usando o Native Transitions a ação do NavController será útil.


text:
Q: Finding the modular of a Square Root of a product of many numbers I am working on Quadratic Sieve and at some stage I need to find
$$
\sqrt{\prod_{k=1}^n y_k} \pmod{N}
$$
Now the Product (inside square root) getting bigger and bigger (up to few hundred numbers) and I can't apply mod before square root operation. My question is, can I apply some sort of modulus inside square root to keep the product term down. Ultimately the result will be between 0 to N-1.
What I'm doing now, dividing the product by some $p^2$ and letting $p$ out of square root and applying the mod outside root when possible.
For an example,
$$
\begin{split}
s &= \sqrt{625 \cdot 117649\cdot 529\cdot 707281\cdot 2565726409\cdot 2809}
     \pmod{1113911}\\
  &= 25 \sqrt{117649\cdot 529\cdot 707281\cdot 2565726409\cdot 2809}
     \pmod{1113911} \quad \text{as } 625 = 25^2 \\
  &= 25\cdot 343 \sqrt{529\cdot 707281\cdot 2565726409\cdot 2809}
     \pmod{1113911} \quad \text{as } 117649 = 343^2 \\
  &= 25\cdot 343 \cdot 23 \sqrt{707281\cdot 2565726409\cdot 2809}
     \pmod{1113911} \quad \text{as } 529 = 23^2 \\
  &= 25\cdot 343 \cdot 23 \cdot 841 \sqrt{2565726409\cdot 2809}
     \pmod{1113911} \quad \text{as } 707281 = 841^2 \\
  &= 165866225 \sqrt{2565726409\cdot 2809} \pmod{1113911} \\
  &= 1007397 \sqrt{2565726409\cdot 2809} \pmod{1113911}, \\
\end{split}
$$
the last step being so since $165866225 \pmod{1113911} \equiv 1007397$, and so on.
Is there any better way to do this?
Thank you.


text:
Q: MediaCapture gives poor quality of QR code image captured(Windows Phone 8.1 universal app) MediaCapture gives poor quality of QR code image captured, because of which QR code decoder(Zxing) is not able to decode the QR code(Windows Phone 8.1 universal app)
The problem comes only if QR code becomes more complex, i.e. generated out of long string(more then 180 characters), for QR codes generated out of small strings(less then 180) it works fine.
If I feed image directly to Zxing decoder(copy qr image to solution and provide uri) it works fine. But if I capture image using mediacapture api await captureManager.CapturePhotoToStorageFileAsync(imgFormat, file);
and feed it to decoder it does not work,

A: Have a look at the CameraResolution SDK sample on the Microsoft Windows Universal Samples GitHub repo. You should be looking into using the GetAvailableMediaStreamProperties method, pick the resolution you want to use, and set it on the MediaStreamType of your choosing (Video, Photo, Preview) by using the SetMediaStreamPropertiesAsync method.
Do read through the full sample, though. There are some details (like the number of MediaStreamTypes supported by the camera, see VideoDeviceCharacteristic) that you should understand to build a robust camera app.

A: By looking at the image you posted in the comments for the other answer in conjunction to the code snippets you're using for focus, I would guess that you're calling the focus API at the wrong time. Make sure to use the FocusControl (and other "auto" controls such as WhiteBalance and Exposure) after starting the preview.
Also, focus takes some time to converge, so make sure you're waiting for the operation to finish before capturing a photo.


text:
Q: Failed to create nested elements in XML using XLST I have a flat XML which looks like this:
<objectDataList>
<objectData>
    <equipment>
        <name>Chassis-One</name>
        <type>Chassis</type>
    </equipment>
</objectData>
<objectData>
    <equipment>
        <name>Shelf-One</name>
        <type>Shelf</type>
    </equipment>
</objectData>
<objectData>
    <equipment>
        <name>Shelf-Two</name>
        <type>Shelf</type>
    </equipment>
</objectData>
<objectData>
    <equipment>
        <name>Slot-One</name>
        <type>Slot</type>
    </equipment>
</objectData>

How can I create an XSL that will transform my XML into another XML that looks like this:
<equipments>
<object>
    <name>Chassis-One</name>
        <object>
            <name>Shelf-One</name>
            <object>
                <name>Slot-One</name>
            </object>
        </object>

</object>

It's like in a chassis, there are 2 shelves, and in Shelf One, there is Slot -One..
I tried halfway, but I couldn't think how to make the element nested:
<xsl:template match="/response">
    <equipments>
            <object>
                <xsl:apply-templates select="objectData"/>
            </object>
    </equipments>

<xsl:template match="objectData/equipment[type='Chassis']">
    <name><xsl:value-of select="equipment/name"/></name>
        <!-- Now I want to find the shelf according to the chassis name -->
        <xsl:call-template name="find-shelf-according-to-chasis-name">
            <xsl:with-param name="chassisName" select="equipment/name"/>
        </xsl:call-template>
</xsl:template>

I hope someone could shed some light
Thank you in advance

A: The following script will do what you want, it is a bit lengthy due to the fact that the Chassis - Shelf - Slot structure has to be represented in the script. If your xml would contain id and parent-id attributes the script could be smaller and the naming convention could be removed or loosened.
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml"/>

  <xsl:template match="/">
    <equipments>
    <xsl:apply-templates select="//equipment[type='Chassis']" />
    </equipments>
  </xsl:template>

  <xsl:template match="equipment[type='Chassis']">
    <xsl:variable name="suffix" select="substring-after(name, '-')" />
    <object>
        <xsl:copy-of select="name" />
        <xsl:apply-templates select="//equipment[type='Shelf'][substring-after(name, '-')=$suffix]" />
    </object>
  </xsl:template>

  <xsl:template match="equipment[type='Shelf']">
    <xsl:variable name="suffix" select="substring-after(name, '-')" />
    <object>
        <xsl:copy-of select="name"/>
        <xsl:apply-templates select="//equipment[type='Slot'][substring-after(name, '-')=$suffix]" />
    </object>
  </xsl:template>

  <xsl:template match="equipment[type='Slot']">
    <object>
        <xsl:copy-of select="name"/>
    </object>
  </xsl:template>

</xsl:stylesheet>

The part you were asking for uses the substring-after function to determine the name suffix and uses that in the subsequent selection.

A: There's a fairly simple (although a little verbose) solution:
<xsl:template match="objectDataList">
  <equipments>
    <xsl:apply-templates select="objectData[equipment/type='Chassis']"/>
  </equipments>
</xsl:template>

<xsl:template match="objectData[equipment/type='Chassis']">
  <xsl:variable name="index" select="substring-after(equipment/name,'-')" />
  <object>
    <xsl:copy-of select="equipment/name" />
    <xsl:apply-templates select="following-sibling::objectData[equipment/type='Shelf' and substring-after(equipment/name,'-') = $index]" />
  </object>
</xsl:template>

<xsl:template match="objectData[equipment/type='Shelf']">
  <xsl:variable name="index" select="substring-after(equipment/name,'-')" />
  <object>
    <xsl:copy-of select="equipment/name" />
    <xsl:apply-templates select="following-sibling::objectData[equipment/type='Slot' and substring-after(equipment/name,'-') = $index]" />
  </object>
</xsl:template>

<xsl:template match="objectData[equipment/type='Slot']">
  <xsl:variable name="index" select="substring-after(equipment/name,'-')" />
  <object>
    <xsl:copy-of select="equipment/name" />
  </object>
</xsl:template>

It's a bit repetitive though, the last three templates are almost identical. But then, depending on your specific requirements, it might be helpful that they're handled by different templates.
If you can guarantee that a shelf will always follow the related chassis etc, then you can change the <xsl:apply-templates in the second template to:
<xsl:apply-templates select="following-sibling::*[1]">
If there might not be one, then you can do:
<xsl:apply-templates select="following-sibling::*[1][equipment/type='Shelf']">


text:
Q: results.pandas().xyxy[0] in only outputting data for one image rather than four I am trying to get the output stored in a variable so that it can be used later on for more processing.
But to get to that stage I am facing a challenge with this code
######INFERENCE ON P6 MODELS*****************************************************************************
import torch
import glob
from natsort import natsorted
import cv2
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
import pandas as pd
import os

model = torch.hub.load('/Users/yolov5', 'custom', path='/User/yolov5/runs/train/exp11/weights/best.pt', source='local', force_reload=True)  # custom trained model
model.conf = 0.25  # NMS confidence threshold

Path = 'User/yolov5/data/images/'

imgs = [cv2.imread(file) for file in natsorted(glob.glob(Path+"/*.jpg"))]

# Inference
results = model(imgs,size=640)

# Results:

#results.save() # or .print() .show(), .save(), .crop(), .pandas(), etc.
results.pandas()
#print(results.print())
#print(results.pandas().xyxy[:])
# results.show()
#results.pandas().xyxy[0]

#print(results)
#print(results.pandas().xyxy[0])
# dfm = pd.DataFrame(results.pandas().xyxy[0])#, columns = ['Loss','Accuracy']
# # #dfm['Classes'] = classes.tolist()
# predict_labs = 'pred_yolo_individual.csv'
# with open(predict_labs, mode='w') as fd:
#      dfm.to_csv(fd)

#results.print()  # or .show(), .save(), .crop(), .pandas(), etc.
#results.render()
results.xyxy[0]  # im predictions (tensor)
results.pandas().xyxy[0]
results.print()
# pred = results.pandas().xyxy[0]
# for index, row in pred.iterrows():
#     print(row['class'], row['confidence'], row['name'])

As you can see I am trying loads of stuff to get this going but some major details I am missing that is not getting the right output as desired.
I would like to get the output like this format below for the folder of images that I have.
# Results
results.print()  # or .show(), .save(), .crop(), .pandas(), etc.

results.xyxy[0]  # im predictions (tensor)
results.pandas().xyxy[0]  # im predictions (pandas)
#      xmin    ymin    xmax   ymax  confidence  class    name
# 0  749.50   43.50  1148.0  704.5    0.874023      0  person
# 2  114.75  195.75  1095.0  708.0    0.624512      0  person
# 3  986.00  304.00  1028.0  420.0    0.286865     27     tie

*** THE ISSUE IS***
When I use the same code I am only getting one output!!!!!?!?!?!
If I do a
print(results.pandas().xyxy[0:])

I am seeing the output as demonstrated below but not in the structured format as above:
YOLOv5  v7.0-72-g064365d Python-3.10.6 torch-1.13.1 CPU

Fusing layers...
Model summary: 212 layers, 20856975 parameters, 0 gradients, 47.9 GFLOPs
Adding AutoShape...
[         xmin       ymin        xmax        ymax  confidence  class      name
0  539.859314  119.92907  602.884216  245.533752    0.353711      1  Stabbing, Empty DataFrame
Columns: [xmin, ymin, xmax, ymax, confidence, class, name]
Index: [], Empty DataFrame
Columns: [xmin, ymin, xmax, ymax, confidence, class, name]
Index: [],          xmin       ymin         xmax        ymax  confidence  class      name
0  709.833496  66.843300  1025.770752  800.782593    0.771696      1  Stabbing
1   84.628845   4.153772   461.863617  833.189636    0.632551      1  Stabbing]

Please assist, and thank you in advance for acknowledging my issues.

A: I would suggest using the following code to get the desired output:
# Inference
results = model(imgs, size=640)

# Results:

preds = results.pandas().xyxy[0]  # im predictions (pandas)
# print(preds)

# Create dataframe and write to file
dfm = pd.DataFrame(preds)
dfm.columns = ['xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name']
predict_labs = 'pred_yolo_individual.csv'
dfm.to_csv(predict_labs, index=False)

This will create a CSV file containing all the predictions in the desired format.


text:
Q: wrap attributes under custom key active model serializer I have serializer like
class UserSeriazer < ActiveModel::Serializer
  attributes :name, :email
end

and the json produced as below
{
  name: 'james'
  email: 'j@sample.com'
}

how can i wrap the above json item, under custom key say customer
{
  customer:
    {
      name: 'james'
      email: 'j@sample.com'
    }

}

I tries something like attribute :name, :email, key: :customer, but didn't work. thanks in advance.

A: You can try to add root key to your serializer file. in UserSerializer, add this
attributes :name, :email, root: 'customer'

I'm not sure of how this would work. You can go with following if this doesn't work.
The best method would be to create a new serializer called CustomerSerializer. That would inherit from UserSerializer. In the derived serializer, you can specify the required attributes. Wherever you user UserSerializer should be modified to use CustomerSerializer.
class CustomerSerializer < UserSerializer
  attributes :name , :email
end

Please comment which works!


text:
Q: Drupal Chaos Tool Suit Custom Ruleset error I am using Drupal core 6.14 and Chaos Tool Suit 6.x-1.12 and in the ctool custom access rulesets page I am getting error when loading the ctools modal dialog.
The POST request url in my local machine is http://localhost/drupal/?q=ctools/context/ajax/add/ctools_export_ui-ctools_access_ruleset/requiredcontext/%3A%3Aadd/node.
Response status is 200 and the statusText is "parsererror". It's giving the error alert,
An error occurred at http://localhost/drupal/?q=ctools/context/ajax/add/ctools_export_ui-ctools_access_ruleset/requiredcontext/%3A%3Aadd/node.

Error Description: "[ { "command": "settings", "argument": { "basePath": "/drupal/", "cron": { "basePath": "/drupal/?q=poormanscron", "runNext": 1362598387 } } }, { "command": "css_files", "argument": [ { "file": "/drupal/sites/all/modules/activities/activities.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/alert/alert.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/complaint/complaint.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/employeeform/employeeform.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/evvodashboard/evvodashboard.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/evvodashboard/js/jquery.ui.core.js?0", "media": "all" }, { "file": "/drupal/sites/all/modules/evvodashboard/js/jquery.ui.widget.js?0", "media": "all" }, { "file": "/drupal/sites/all/modules/evvodashboard/js/jquery.ui.mouse.js?0", "media": "all" }, { "file": "/drupal/sites/all/modules/evvodashboard/js/jquery.ui.sortable.js?0", "media": "all" }, { "file": "/drupal/sites/all/modules/hblogin/hblogin.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/management/css/management.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/ownerregisterform/ownerregisterform.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/phonebook/phonebook.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/propertyform/propertyform.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/propertymanagement/propertymanagement.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/tenentregisterform/tenentregisterform.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/cck/theme/content-module.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/ctools/css/ctools.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/filefield/filefield.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/panels/css/panels.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/cck/modules/fieldgroup/fieldgroup.css?0", "media": "all" }, { "file": "/drupal/sites/all/modules/views/css/views.css?0", "media": "all" }, { "file": "/drupal/sites/all/files/css/custom-theme/jquery-ui-1.8.13.custom.css?0", "media": "all" }, { "file": "/drupal/sites/all/themes/rubik/fullcalendar/fullcalendar.css?0", "media": "all" } ] }, { "command": "scripts", "argument": [ "/drupal/misc/jquery.js", "/drupal/misc/drupal.js", "/drupal/sites/all/modules/activities/activities.js", "/drupal/sites/all/modules/alert/alert.js", "/drupal/sites/all/modules/alert/alert_1.js", "/drupal/sites/all/modules/complaint/complaint.js", "/drupal/sites/all/modules/emergency/emergency.js", "/drupal/sites/all/modules/employeeform/employeeform.js", "/drupal/sites/all/modules/evvodashboard/evvodashboard.js", "/drupal/sites/all/modules/facilityform/facilityform.js", "/drupal/sites/all/modules/gtrans/gtranslate.js", "/drupal/sites/all/modules/insurance/insurance.js", "/drupal/sites/all/modules/maintenance/maintenance.js", "/drupal/sites/all/modules/mycalendar/calendar.js", "/drupal/sites/all/modules/ownerregisterform/ownerregisterform.js", "/drupal/sites/all/modules/phonebook/phonebook.js", "/drupal/sites/all/modules/privatemsg/privatemsg.js", "/drupal/sites/all/modules/profile_edit/profile_edit.js", "/drupal/sites/all/modules/propertyform/propertyform.js", "/drupal/sites/all/modules/propertymanagement/propertymanagement.js", "/drupal/sites/all/modules/tenentregisterform/tenentregisterform.js", "/drupal/sites/all/modules/vendors/vendors.js", "/drupal/sites/default/files/jstimer/timer.js", "/drupal/sites/all/modules/panels/js/panels.js", "/drupal/sites/all/modules/poormanscron/poormanscron.js", "/drupal/sites/all/modules/webfm/modules/webfm_mp3/mp3player/audio-player.js", "/drupal/sites/all/files/js/jquery-1.5.1.min.js", "/drupal/sites/all/files/js/jquery-ui-1.8.13.custom.min.js", "/drupal/sites/all/files/js/jquery_alphanumeric.js", "/drupal/sites/all/files/js/accode.js", "/drupal/sites/all/files/development-bundle/ui/ui.progressbar.js", "/drupal/sites/all/themes/rubik/fullcalendar/fullcalendar.min.js" ] }, { "command": "modal_display", "title": "Add required context \"Node\"", "output": "\x3cform action=\"/drupal/?q=ctools/context/ajax/add/ctools_export_ui-ctools_access_ruleset/requiredcontext/%3A%3Aadd/node\"  accept-charset=\"UTF-8\" method=\"post\" id=\"ctools-edit-requiredcontext-form\"\x3e\n\x3cdiv\x3e\x3cdiv class=\"modal-form clear-block\"\x3e\x3cdiv class=\"description\"\x3eA node object.\x3c/div\x3e\x3cinput type=\"hidden\" name=\"requiredcontext[name]\" id=\"edit-requiredcontext-name\" value=\"node\"  /\x3e\n\x3cinput type=\"hidden\" name=\"requiredcontext[id]\" id=\"edit-requiredcontext-id\" value=\"1\"  /\x3e\n\x3cdiv  class=\"form-item form-item-labeled\" id=\"edit-requiredcontext-identifier-wrapper\"\x3e\r\n      \x3clabel  for=\"edit-requiredcontext-identifier\"\x3eIdentifier: \x3c/label\x3e\r\n    \x3cinput type=\"text\" maxlength=\"128\" name=\"requiredcontext[identifier]\" id=\"edit-requiredcontext-identifier\" value=\"Node\" class=\"form-text fluid\" /\x3e      \x3cdiv class=\'description\'\x3eEnter a name to identify this required context on administrative screens.\x3c/div\x3e\r\n  \x3c/div\x3e\r\n\x3cdiv  class=\"form-item form-item-labeled\" id=\"edit-requiredcontext-keyword-wrapper\"\x3e\r\n      \x3clabel  for=\"edit-requiredcontext-keyword\"\x3eKeyword: \x3c/label\x3e\r\n    \x3cinput type=\"text\" maxlength=\"128\" name=\"requiredcontext[keyword]\" id=\"edit-requiredcontext-keyword\" value=\"node\" class=\"form-text fluid\" /\x3e      \x3cdiv class=\'description\'\x3eEnter a keyword to use for substitution in titles.\x3c/div\x3e\r\n  \x3c/div\x3e\r\n\x3c/div\x3e\x3cinput type=\"submit\" name=\"op\" id=\"edit-next\" value=\"Save\"  class=\"form-submit\" /\x3e\n\x3cinput type=\"hidden\" name=\"form_build_id\" id=\"form-fec71d3cab0e5c35520c4ffc4dd5632f\" value=\"form-fec71d3cab0e5c35520c4ffc4dd5632f\"  /\x3e\n\x3cinput type=\"hidden\" name=\"form_token\" id=\"edit-ctools-edit-requiredcontext-form-form-token\" value=\"cf83cbf84d13b7631f47c02ddec33b01\"  /\x3e\n\x3cinput type=\"hidden\" name=\"form_id\" id=\"edit-ctools-edit-requiredcontext-form\" value=\"ctools_edit_requiredcontext_form\"  /\x3e\n\n\x3c/div\x3e\x3c/form\x3e\n" } ]"

I don't have any JavaScript errors in firebug console and php error in php error log.


text:
Q: Avoiding modal panel to open if error in AngularJS I have the following method in a controller:
 $scope.showProductDetails = function (size,product) {

$scope.showLoader('Loading the details of the product. Please wait...');

    var modalInstance = $modal.open({
          templateUrl: 'productDetail.html',
          controller: 'ProductDetailController',
          size: size,
          resolve:{
            productDetails: function (){return productsFactoryHelper.ProductDetail.query({productid:product.id},function()
            {
            $scope.hideLoader();
            },function(error)
            {
                    commonFactory.Pop('error','This product is not available at this moment. Please try again later. If the problem persists contact a system administrator');
                    $scope.hideLoader();
            });}
          }

        });

};

As you can see, I'm opening a modal panel, and using 'resolve' to pass an object that I retrieve from the server.
This call to the server can launch an exception, so I manage this case in the callback function for error, but I cannot avoid the modal panel to open if an error happens. I would like to know if there is a way to do that without changing the structure of the code. I mean I could achieve that just doing the call out of the resolve, before opening the modal panel, and depending if the call is successful or not , open the modal panel, but I would like to know if there is a way to do it inside the resolve, without changing the structure of the method.
Thanks

A: Inside error callback function, return error again. You need to return a promise, so, if the returned promise is an error, it shouldn't open.
  resolve:{
            productDetails: function (){return productsFactoryHelper.ProductDetail.query({productid:product.id},function()
            {
            $scope.hideLoader();
            },function(error)
            {
                    commonFactory.Pop('error','This product is not available at this moment. Please try again later. If the problem persists contact a system administrator');
                    $scope.hideLoader();
                    return error
            });}
          }

A: I think your idea of doing the call before opening the modal makes most sense in this case.  In other words, only open the modal when it has the data.
Your other option is to display an error in the modal and change the contents/buttons accordingly.


text:
Q: How to show the degree $[\Bbb Q(\alpha _n+\frac{1}{\alpha_n}) : \Bbb Q]$ is $\phi(n)/2$, where $\alpha_n$ is a primitive $n$-th root of unity?
How to show the degree $[\Bbb Q(\alpha _n+\frac{1}{\alpha_n}) : \Bbb Q]$ is $\phi(n)/2$, where $\alpha_n$ is a primitive $n$-th root of unity?

I already know that $[\Bbb Q(\alpha _n ):\Bbb Q]$ is Euler-phi function $\phi(n)$.  But, I have no clue what to do next? Is it possible to find the irreducible polynomial for $\alpha _n +\frac{1}{\alpha_n}$ over $\Bbb Q$?

A: For any $k,\gcd(n,k)=1$ :
$$ \mathbb{Q}(\zeta_n)= \mathbb{Q}(\cos(2\pi k/n))(i\sin(2\pi k/n))$$
$i \sin(2\pi k/n)$ is a root of $x^2+1-\cos^2(2\pi k/n)$ a polynomial of degree $2$ over $\mathbb{Q}(\cos(2\pi k/n))$ and so $$[ \mathbb{Q}(\zeta_n): \mathbb{Q}(\cos(2\pi k/n))] \le 2$$
Since it is real $\mathbb{Q}(\cos(2\pi k/n)) \ne \mathbb{Q}(\zeta_n)$ and : $$[ \mathbb{Q}(\zeta_n): \mathbb{Q}(\cos(2\pi k/n))] = 2, \qquad \phi(n) = [ \mathbb{Q}(\zeta_n): \mathbb{Q}] = [ \mathbb{Q}(\zeta_n): \mathbb{Q}(\cos(2 \pi k/n))][ \mathbb{Q}(\cos(2\pi k/n)): \mathbb{Q}]$$
$$[ \mathbb{Q}(\cos(2\pi k/n)): \mathbb{Q}] = \phi(n)/2$$

A: If you let $\beta_n=\alpha_n+\frac{1}{\alpha_n}$. Then, clearly $\mathbb Q(\beta_n)\subseteq \mathbb Q(\alpha_n)$, since $\beta_n=\mathbb Q(\alpha_n)$.
You first have to show it is a strict subfield - that $\mathbb Q(\alpha_n)\neq \mathbb Q(\beta_n)$. That can be seen by noting that $\beta_n$ is real, and $\alpha_n$ is not, for $n>2$.
An alternative approach is to show that the automorphism of $\mathbb Q(\alpha_n)$ sending $\alpha_n$ to $\alpha_n^{-1}$ fixes $\beta_n$ and thus all of $\mathbb Q(\beta_n)$, but does not fix $\alpha_n$ unless $n=2$.
But if $\alpha_n+\frac{1}{\alpha_n}=\beta_n$ then $x^2-\beta_nx +1$ has $\alpha_n$ as a root, so $\alpha_n$ is at most degree $2$ over $\mathbb Q(\beta_n)$.
So we get $$\phi(n)=[\mathbb Q(\alpha_n):\mathbb Q]=[\mathbb Q(\alpha_n):\mathbb Q(\beta_n)][\mathbb Q(\beta_n):\mathbb Q]=2[\mathbb Q(\beta_n):\mathbb Q]$$
The minimal polynomial for $\beta_n$ can be computed in terms of Chebyshev polynomials, but you have to deal with repeated roots and the like.


text:
Q: Projecting an object into a scene based on world coordinates only I want to place a 3D image into a scene base on world/global coordinates.  I have an image of a scene.  The image was captures at some global coordinate (x1, y1, z1).  I am given an object that needs to be placed into this scene based on its global coordinate (x2, y2, y3).  This object needs to be projected into the scene accurately similarly to perspective projection.
An example may help to make this clear.  Imagine there is a parking lot with some set of global coordinates.  A picture is taken of a portion of the parking lot.  The coordinates from the spot where the image was taken is recorded.  The goal is to place a virtual vehicle into this image using the global coordinates for that vehicle.  Because the global cooridnates for the vehicle may not be in the fov of the global coordinates for the image I am assuming that I will need the image coordinates, angle and possibly fov.
3D graphics is not my area so I have been looking at http://en.wikipedia.org/wiki/Perspective_projection#Perspective_projection. I have also been looking at Matrix3DProjection which seems to possibly be what I am looking for but it only works in Silverlight and I am trying to do this in WPF. In my mind it appears I need to determine the (X,Y,Z) coordinates that are in the fov of the image, determine the world coordinate to pixel conversion and then accurately project the vehicle into the image giving it the correct perspective such that is looks 3D i.e smaller the further away bigger closer
Is there a function within WPF that can help with this or will I need to re-learn matrices and do this by hand?

A: I'm not sure I understand why this is difficult.  If I'm understanding you right, all you need to do is set the transforms on your Model3D objects.  I assume you are alreay have Model3D objects for your car model (either Model3DGroup or GeometryModel3D).  Here is how you would combine this with your scene image:

*

*Use whatever coordinates are convenient on the Model3D representing your car model, then add a Transform3DGroup consisting of a ScaleTransform3D, a RotateTransform3D, and a TranslateTransform3D to size and position your car model to global coordinates

*Create a GeometryModel3D for the scene, using an ImageBrush for the material, a simple rectangular Geometry3D, and a Transform3DGroup consisting of a ScaleTransform3D, a TranslateTransform3D, a RotateTransform3D and a TranslateTransform3D to size and position the scene (see code comments below for details)

*Construct a Viewport3DVisual using a PerspectiveCamera and containing a Model3DVisual containing a Model3DGroup that contains an AmbientLight plus the models created in steps 1 and 2
So the XAML would be something like this:
...
<Viewport3DVisual>

  <!-- the camera -->
  <Viewport3DVisual.Camera>
    <PerspectiveCamera ... camera parameters ... />
  </Viewport3DVisual.Camera>

  <ModelVisual3D>
    <ModelVisual3D.Content>
      <Model3DGroup>

        <!-- the light -->
        <AmbientLight ... light parameters ... />

        <!-- the car model -->
        <Model3DGroup>
          <Model3DGroup.Transform>
            <Transform3DGroup>
              <ScaleTransform3D    ... scale car to proper size ... />
              <RotateTransform3D   ... face car in proper direction ... />
              <TranslateTranform3D ... move car to proper global coordinates ... />
            </Transform3DGroup>
          </Model3DGroup.Transform>

          ... GeometryModel3D or Model3DGroup for the car model goes here ...

        </Model3DGroup>

        <!-- the scene image -->
        <GeometryModel3D>

          <GeometryModel3D.Material>
            <ImageBrush ImageSource=... scene image ... />
          </GeometryModel3D.Material>

          <GeometryModel3D.Geometry>
            <MeshGeometry3D Positions="0,0,0 1,0,0 1,1,0 0,1,0" Indices="0,1,2 2,3,0" />
          </GeometryModel3D.Geometry>

          <GeometryModel3D.Transform>
            <Transform3DGroup>
              <ScaleTransform3D     ... scale scene to apparent size ... />
              <TranslateTransform3D ... translate scene along Z axis to apparent distance from camera ... />
              <RotateTransform3D    ... rotate distanced scene to original camera orientation ... />
              <TranslateTransform3D ... move to global coordinates of original camera location ... />
            </Transform3DGroup>
          </GeometryModel3D.Transform>

        </GeometryModel3D>

      </Model3DGroup>
    </ModelVisual3D.Content>
  </ModelVisual3D>
</Viewport3DVisual>

Note that your scene image is set using an apparent size and distance rather than field of view.  Select a large apparent distance for the scene image so it will always be behind the car model.  Compute the apparent size like this:
var verticalFieldOfView = 60.0;    // Degrees
var horizontalFieldOfView = 60.0;  // Degrees
SceneApparentDistance = 1000.0;    // In global coordinate units

SceneApparentHeight = image.Height * SceneApparentDistance * Math.Tan(verticalFieldOfView * Math.Pi/180));
SceneApparentWidth = image.Width * SceneApparentDistance * Math.Tan(horizontalFieldOfView * Math.Pi/180));


text:
Q: iOS - How to parse Json array in xcode and save results are strings Hi I am trying to parse a Json string as an NSArray and save certain results as strings to set permissions for different users in my app. My current code is:
NSError *jsonParsingError1 = nil;
        accountData = [NSJSONSerialization JSONObjectWithData:jsonAccount
                                                   options:NSJSONReadingMutableContainers error:&jsonParsingError1];

accountData is an NSMutableArray created in the .h file.
jsonAccount is NSData created by converted an NSString
The NSLog out put for the array is;
  {
    account = "XXXX";
    companyName = XXXXX;
    id = XXXXX;
    websites =         (
                    {
            account = "XXXXX";
            accountId = XXXXX;
            anonymiseIP = 0;
            companyName = XXXXX;
            XXXX = 0;
            domains =                 (
                "XXXXX"
            );
            features =                 {
                advancedSegmentation = 1;
                attentionHeatmaps = 1;
                domains = 0;
                dotHeatmaps = 1;
                goalConversionTracking = 1;
                interactionHeatmaps = 1;
                leadInfo = 0;
                scrollHeatmaps = 1;
                timeHeatmaps = 1;
                users = 0;
                valueHeatmaps = 1;
                visitorPlayback = 1;
                visitorScoring = 1;
                visitors = 1;
            };
            fixedElementSelector = "";
            flagClicksReceived = 0;
            flagDataReceived = 0;
            flagGoalsReceived = 0;
            flagInteractionsReceived = 0;
            flagScrollsReceived = 0;
            id = XXXXX;
            interactionSelector = "";
            name = "XXXX";
            permissions =                 (
                segments,
                heatmaps,
                visitors,
                campaigns,
                support,
                globalSettings,
                websiteSettings
            );
            setCookies = 1;
            status = 1;
            statusMessage = "";
            statusString = OK;
            trialling = 1;
        }
    );
},

When I try and create a sting from one of the results and display it in the log I get this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray:]: unrecognized selector sent to instance 0x6a950f0'

How can I save different keys as strings?

A: Looks like that your JSON is a Dictionary, not an Array.

A: Your JSON is not array you should parse it like NSDictionary

A: After parsing the JSON, you should test what kind of object it returned. E.g.:
if ([accountData isKindOfClass:[NSArray class]]) {
   // handle like an array
} else if ([accountData isKindOfClass:[NSDictionary class]]) {
   // handle like a dictionary
}

A: Your JSON is a dictionary with four keys: account, companyName, id, and websites.
The key "websites" will give you an array.
You can iterate through the "websites" array, and each element is a dictionary.
Each of the dictionaries in the "websites" array has lots of keys like account, accountId, anonymiseIP and so on. Some of these keys have values that are dictionaries or arrays.
In the NSLog statement, (a, b, c) would be an array, while { a = x; b = y; c = z; } would be a dictionary.

A: Your server response is a dictionary so change accountData to dictionary
Write NSLog for below and you will get information in it
[accountData objectForKey:@"account"];
[accountData objectForKey:@"companyName"];
[accountData objectForKey:@"id"];
[[accountData objectForKey:@"websites"] count];//array
[[[accountData objectForKey:@"websites"] objectAtIndex:0]objectForKey:@"account"];
[[[accountData objectForKey:@"websites"] objectAtIndex:0]objectForKey:@"domains"];
[[[[accountData objectForKey:@"websites"] objectAtIndex:0]objectForKey:@"domains"]count]; //array
[[[[accountData objectForKey:@"websites"] objectAtIndex:0]objectForKey:@"domains"]objectAtIndex:0];


text:
Q: Regex expression to match strings after example codes Hello I'm trying to make regex expression to match text after code example of regex that I have at the moment with sample text.
(?<=H\d\d\d)([.*\w\W\n]+)(?=End word)

https://regex101.com/r/9SBnH9/2
Sample text
Sample text
Sample text
H319 asdkjczixuqweoiurqoiweqwrjasdkjfqwe qweiouqwroiu kjasdkj czkjxklqjwekjiouasdiiaosudou
oiuasodiucxzlkjqweoiu oqiwur H320 asdkqjwe askjdq xzc
H325 asjdhasjd zxcjh
H331+H341+H341 askdjvkjzx qweqrqwoe
End word
Sample text
Sample text

This is the sample text and I want expression to start searching for matches after find H** code and get the text only when find again H** code ignore it and take the text and have example with H**+H**+H** or H**+H**, but same deal skip H codes and get the text only. And search until it finds End word. I'm to the point where it start from first H code, but then it get all the string and end's on end word you can see that in regex site which I send.
I should get this as result:

asdkjczixuqweoiurqoiweqwrjasdkjfqwe qweiouqwroiu kjasdkj
czkjxklqjwekjiouasdiiaosudou oiuasodiucxzlkjqweoiu oqiwur.asdkqjwe
askjdq xzc.asjdhasjd zxcjh.askdjvkjzx qweqrqwoe

A: You can match all chars in between that are not directly followed by H and 3 digits and assert End word at the right at the start of the string.
(?<=H\d{3}\b)(?:(?!\+?H\d{3}\b)[\S\s])+(?=[\s\S]*\r?\nEnd word\b)

The pattern in parts matches:

*

*(?<=H\d{3}\b) Positive lookbehind, assert H and 3 digits directly to the left. The word boundary \b prevents a partial match

*(?: Non capture group

*

*(?!\+?H\d{3}\b)[\S\s] Match 1+ times any char (including newlines) that are not directly followed by an optional + then H and 3 digits

*)+  Close non capture group and repeat 1+ times

*(?= Positive lookahead, assert to the right

*

*[\s\S]*\r?\nEnd word\b Match End word at the start of the string (or leave out the ^ if it is not at the start)

*) Close lookahead

Regex demo
If you also don't want to cross matching End word, you can add that to the negative lookahead:
(?<=H\d{3}\b)(?:(?!\+?H\d{3}\b|^End word\b)[\S\s])+(?=[\s\S]*\r?\nEnd word\b)

Regex demo

A: I would use this regex:
(?<=H\d{3}\b)(?!\+H\d{3})\s*([\w\W]+?)\s*(?=H\d{3}\b|End word)

See a demo here
Notice that [.*\w\W\n] is redundant w.r.t. just [\w\W], because the latter matches any character that is or not a word character (therefore, any character), so it already includes periods, stars and newlines.


text:
Q: Outputting text to multiple terminals in Python (I am using Python and ArchLinux)
I am writing a simple AI in Python as a school project. Because it is a school project, and I would like to visibly demonstrate what it is doing, my intention is to have a different terminal window displaying printed output from each subprocess- one terminal showing how sentences are being parsed, one showing what pyDatalog is doing, one for the actual input-output chat, etc, possibly on two monitors.
From what I know, which is not much, a couple of feasible ways to go about this are threading each subprocess and figuring out display from there, or writing/using a library which allows me to make and configure my own windows.
My question is, then, are those the best ways, or is there an easy way to output to multiple terminals simultaneously. Also, if making my own windows (and I'm sorry if my terminology is wrong when I say 'making my own windows'. I mean building my own output areas in Python) is the best option, I'm looking for which library I should use for that.

A: So you could go in multiple directions with this. You could create a Tkinter (or GUI library of your choice) output text box and write to that. This option would give you the most control over how to display your data.
Another option is to access multiple terminals via named pipes. This involves spawning an xterm with a pipe and pumping output to it to be written on screen. See this question for and example:
Using Python's Subprocess to Display Output in New Xterm Window

A: I like @ebarr's answer, but a quick and dirty way to do it is to write to several files. You can then open multiple terminals and tail the files.


text:
Q: Building MSI through NAnt Build I'm assigned the task of getting our MSI's building through NAnt. I will use NAntContrib or WiX if I "have" to, but the time given to me for this ticket doesn't afford me the luxury of researching new build techniques. This is my first time working with NAnt.
The current Solution we have is 80 projects, 6ish services (with their own MSI install projects), and a handful of websites.
The build script builds the solution first, then starts copying all the built libraries, files, zips, configs to their specific locations so deployment is straight forward. The only problem is it does not build any MSI files.
The Build box has Visual Studio installed on it. From quickly looking around the net I saw that if you have VS installed, then running deven.com can build the MSI files...
The Solution being built contains the Install projects for the services, but no MSI's are getting created. Is there a specific setting / command line argument I must pass in to get this done?
The XML that is building the solution is as follows.
$builtype is "/build"
<target name="BuildOnly" depends="ConfigureBuild">
  <if test="${property::exists('Distribution') and Distribution == 'True'}" >
    <call target="ConfigureBuild.Release"/>
 </if>

 <call target="StopServices"/>
 <call target="CleanSUOFiles"/>
 <!--<call target="BuildEnterpriseLibrary" />-->
 <property name="build.dir" value="${directory::get-current-directory()}"/>

 <echo message="######### ${buildtype} ${StandardProjectTarget}"/>

 <exec program="${deven.com}" workingdir="${build.dir}" failonerror="true"  commandline=""BC_HM.sln" ${buildtype} ${StandardProjectTarget}"/>

 <call target="BuildSchematronFiles"/>
</target>

Thanks.

A: NAnt is a build tool, it's not related in any way with installation packages. It builds projects, it doesn't generate files on its own. So you need a project which generates an MSI package.
This can be created in multiple ways:

*

*use a Visual Studio setup project

*use a free setup authoring tool like WiX

*use a commercial setup authoring tool which supports NAnt

Please note that creating installation packages is not an easy task. So analyze all setup authoring tools before choosing one.


text:
Q: jq to filter inner array elements but return the whole JSON TL;DR
How can I return the whole JSON after filtering inner array elements of a top-level key?
Detailed explanation
I have a JSON describing the COCO image database and it is formatted as follows (irrelevant elements truncated as ...).
{
  "info": {
    "description": "COCO 2017 Dataset",
    ...
  },
  "licenses": [
    {
      "url": "http://creativecommons.org/licenses/by-nc-sa/2.0/",
      ...
    },
    ...
  ],
  "images": [
    {
      "license": 4,
      ...
    },
  "annotations": [
    {
      "segmentation": [
        [
          510.66,
          ...
        ]
      ],
      "area": 702.1057499999998,
      "iscrowd": 0,
      "image_id": 289343,
      "bbox": [
        473.07,
        395.93,
        38.65,
        28.67
      ],
      "category_id": 18,
      "id": 1768
    },
  "categories": [
    {
      "supercategory": "person",
      ...
    },
  ]
}

I need to filter annotations where category_id has one of several values, for example 1, 2.
I can successfully filter such category_ids with
jq -C ' .annotations[] | select( .category_id == 1 or .category_id == 2 ) ' instances_val2017.json | less -R

However, what is returned are only the annotations element of the total JSON as below.
{
  "segmentation": [
    [
      162.72,
      ...
    ]
  ],
  "area": 426.9120499999995,
  "iscrowd": 0,
  "image_id": 45596,
  "bbox": [
    161.52,
    507.18,
    46.45,
    19.16
  ],
  "category_id": 2,
  "id": 124742
}
{
...
{

I know it's possible to return these elements as an array by wrapping the expression in [] but how can I return the entire original JSON after filtering the specified category ids?

A: Okay I spent 3 hours trying to solve this yesterday then this morning I posted this question and subsequently figured it out!
Here is the solution which uses the |= operator which modifies an element in place.
jq '.annotations |= map(select(.category_id | contains(1,2)))' instances_val2017.json

As per the suggestion of @peak, here is the command with == instead of contains.
jq '.annotations |= map(select(.category_id == (1,2)))' instances_val2017.json


text:
Q: Global Timer i.e. A Timer which works on multiple forms. - C# I was wondering if it would be possible to create a timer which isnt bound to a single form. Basically im making a quiz and i want the user to only have 2 minutes to answer all questions. Once the 2 minutes are up the current form will close and an endscreen will appear. The time must also be visible at all times. Any help would be great.

A: You can use a static timer. The timer can be accessed from all forms. Just update the time based on the static timer on each form.

A: Yes you can use a static class with a static dispatch timer.
public static class StaticTimer`
{
   public static DispatcherTimer timer { get; set; }
}

In Form Use:
StaticClass.timer = new DispatcherTimer();
StaticClass.timer.Interval = new TimeSpan(0, 0, 0, 0, 100);
StaticClass.timer.Tick += timer_Tick;
StaticClass.timer.Start();

 public void timer_Tick(object sender, EventArgs e)
 {
     logic....

 }


text:
Q: Getting current office id for user In my project once the user logs in they are assigned to an office and based on their office they only get information within that office. I want to get the current id of the user after logging in but i am not sure how to go about that or where to look. Any help or suggestions would be great.
asp.net mvc project.

A: Regardless of your data store, you could use a similar approach to @Omar's answer in this question I asked some time ago.
The basic idea is to define a parent/base Controller class from which all your relevant controllers inherit. Then, upon initializing that controller:
protected override void Initialize(RequestContext requestContext) { }

You would setup the data based within the office. I can't describe this much further, because you haven't provided a lot of specifics, but within Controller.Initialize you would access this information via AD, your database, etc.
Finally, you could incorporate the retrieved data (via Repositories, etc) into your view models, or pass to the view using ViewData or ViewBag. Though, I recommend the former over the latter in the interest of code cleanliness.


text:
Q: how to parse string into json i have difficulty when i try to parse the following string into json can anybody gauide me or suggest me proper way of parsing following json string
'[{"club_id":"19","club_name":"Al Lawrence","club_desc":"We welcome anyone who enjoys the camaraderie of competition at any level.   Al currently coaches many Houston area runners ranging from elite to back-of-the-packers.  Today the club still has a number of members who receive professional independent coaching from Al, but that certainly is not a requirement for membership in the Al Lawrence Running Club.","club_latitude":"29.770042","club_longitude":"-95.37","club_zip":"77001","club_member_size":"93","club_size":"s","club_type":"training","club_url":"http:\/\/www.alrcus.org\/","club_img":"1390975493.jpg","is_published":"1"},{"club_id":"20","club_name":"Bay Area Fit","club_desc":"Welcome to Houston FIT! We are a group of training partners and friends preparing together for a full or half marathon in 2013\/2014. Even if you\u2019ve never run a step before, training with our group will help you conquer mental and physical barriers you never thought possible.","club_latitude":"29.564405","club_longitude":"-95.091113","club_zip":"77058","club_member_size":"302","club_size":"l","club_type":"training","club_url":"http:\/\/www.houstonfit.com\/","club_img":"1390975687.jpg","is_published":"1"},{"club_id":"22","club_name":"Bay Area Running Club","club_desc":"Order now before the next HARRA race!  Password texas.  Color, size and logo location options available plus you can add BARC on the back for just $5 more.  Flat shipping rate of $4.95 if you buy one or two singlets and no tax!  Orders are shipped out 24-48 hours after purchase. ","club_latitude":"29.583945","club_longitude":"-95.033832","club_zip":"77586","club_member_size":"450","club_size":"l","club_type":"non-training","club_url":"http:\/\/www.barchouston.com\/","club_img":"1390989179.jpg","is_published":"1"},{"club_id":"29","club_name":"Houston Harriors","club_desc":"The 1st race of the HARRA 2014 Spring Series\r\nSaturday, February 22nd, 2014 Houston, Texas\r\nSponsored by the Houston Harriers","club_latitude":"29.733042110628393","club_longitude":"-95.33655524253845","club_zip":"77001","club_member_size":"0","club_size":"","club_type":"tranning","club_url":"http:\/\/www.houstonharriers.com\/","club_img":"1391078677.jpg","is_published":"1"}]'

i have tried by eval() and JSON.parse method but error arise
Uncaught SyntaxError: Unexpected token

A: You cannot have control characters inside a JSON string.
Your JavaScript string literal includes:
"The 1st race of the HARRA 2014 Spring Series\r\nSaturday, February 22nd, 2014 Houston, Texas\r\nSponsored by the Houston Harriers"

This gets converted to this fragment of JSON:
"The 1st race of the HARRA 2014 Spring Series
Saturday, February 22nd, 2014 Houston, Texas
Sponsored by the Houston Harriers"

The literal new lines are forbidden. If you want them in the data, then you'll have to escape the escape characters in the JavaScript:
"The 1st race of the HARRA 2014 Spring Series\\r\\nSaturday, February 22nd, 2014 Houston, Texas\\r\\nSponsored by the Houston Harriers"

In general, however, assuming the JSON is from a trusted source, you shouldn't be embedded a string literal of JSON in JavaScript in the first place. Just take away the ' from the start and end and you'll have a JavaScript object literal that doesn't need parsing inside the JS.

A: The problem is arising from the escape characters in the JSON. For example: http:\/\/ and \n.
If you double-escape them (http:\\/\\/ and \\n), the parse will work:
Demo

A: Your problem is in the data itself where you have \r\n this is because you cannot have contorl chars in a json string.
If you remove them it all works correctly see the fiddle below
http://jsfiddle.net/DwXnb/


text:
Q: How to find index of an array which has maximum value in dataframe using python? I have a dataframe which has array of elements, i would like to get the index value of the maximum number in the array using python,
Desired output:
Elements    Max Value Index

[3,4,5]              2

[2,0,1]              0

I tried using:
df['Max Value Index'] = df["Elements"].apply(lambda x:max(x))

It gives me the maximum value,
, I just need the index number, i tried many ways but not able to get that, can anybody please help?

A: Try idxmax(x)
df['Max Value Index'] = df["Elements"].apply(lambda x:idxmax(x))

A: You could use numpy.argmax:
df['Max Value Index'] = df['Elements'].apply(lambda l:np.argmax(l))

Or in straight python:
df['Max Value Index'] = df["Elements"].apply(lambda l:l.index(max(l)))

Output:
    Elements  Max Value Index
0  [3, 4, 5]                2
1  [2, 0, 1]                0


text:
Q: Trigger.IO - Rewriting files on prebuild - index.html missing I am using a node script to rewrite some files including the index.html in the prebuild section of a forge build in Trigger.IO.
I have tested the script directly and it works fine. Once I use it in the prebuild I get the following error:
Missing index.html in source directory, index.html is required by Forge.

Anyone got any tips on what I should be doing or why this might be erroring?
This is the script I'm using:
var fs = require('fs-sync')
  , fs2 = require('fs')
  , path = require('path');

replaceFiles = function(dirPath, sourcePath) {
  try { var files = fs2.readdirSync(dirPath); }
  catch(e) { return; }
  if (files.length > 0)
    for (var i = 0; i < files.length; i++) {
      var filePath = dirPath + '/' + files[i];
      var fileparts = files[i].split('.');
      if(!fs2.statSync(filePath).isFile() && files[i] == 'lib'){
        fs.delete(filePath);
        console.log('deleted lib directory');
      } else if (fs2.statSync(filePath).isFile() && (fileparts[1] == 'jpg' || fileparts[1] == 'png' || fileparts[1] == 'html')){
        fs.delete(filePath);
        console.log('deleted ' + filePath);
      }
    }
    fs.copy(sourcePath, dirPath, {});
    console.log('copy done!');
};

var target = process.argv[2];
console.log(target);

replaceFiles('.', './' + target);

Trigger.IO runs the following command:
node hook.js android

A: Trigger apps require an index.html in the root of the src folder, if that file is not there when the app is run then you will see that error message.
It looks like your code deletes all html files before copying the files in ./android to ./, my guess is you have no index.html in the android folder, so no index.html exists in your built app.
You can see what files actually make it into your built app by looking in the development/android/assets/src folder in your app's folder.


text:
Q: Does anyone have any luck with running multiple crate.io nodes on virtualized environment? I'm using crate.io to test replication between nodes. I've two instances running on two separate Ubuntu machines running on VirtualBox on the same local network. The instance is not able to recognize additional nodes - seems like each one is running on its own. Does anyone have any experience in configuring multiple nodes?

A: By default crate nodes are discovering themselves using multicast which seems not to work at your network setup. Switching to unicast should solve this:

discovery.zen.ping.multicast.enabled: false
  discovery.zen.ping.unicast.hosts:
   - crate1.example.com:4300
   - crate2.example.com:4300
   - crate3.example.com:4300

This blog post describes it well: https://crate.io/blog/using-crate-in-multinode-setup.


text:
Q: how to test conditional if with jasmine and angular i have a problem with testing jasmine, i cant test conditional if. when i run in sonarqube, just that conditional cant detect.
this is my code:
login() {
    this.submitted = true;
    this.isLoading = true;

        if (this.loginForm.valid) {
          this.authenticationService
            .login(this.f.username.value, this.f.password.value)
            .pipe(finalize(() => {
              this.loginForm.markAsPristine();
              this.isLoading = false;
            }))
            .subscribe(credentials => {
              this.router.navigate(['/'], { replaceUrl: true });
            }, error => {
              this.error = error;
            });
          this.isLoading = false;
        }
      }

this is my testing code:
test('testing conditional if', () => {
    component.loginForm.controls['username'].setValue('admin');
    component.loginForm.controls['password'].setValue('12345678');
    expect(component.loginForm.valid).toBeTruthy();
    spyOn(authenticationService, 'login').and
      .returnValue(component.loginForm.markAsPristine());
    expect(component.login().loginForm.isLoading).toBeFalsy();
    component.login();
  });

help me guys to solve my problem, i search in every website but cant solve this problem. thank you for your attention and your solution.

A: Think the issue is spyOn(authenticationService, 'login').and
      .returnValue(component.loginForm.markAsPristine()); If you spy on it and return a value, you are effectively mocking it. Hence the function will be stubbed and will just return the result of component.loginForm.markAsPristine()
From the jasmine docs:

Jasmine has test double functions called spies. A spy can stub any function and tracks calls to it and all arguments.

As you want the function to executed for SonarCube, but still spy for the purpose of tracking calls, you should be using callThrough
spyOn(authenticationService, 'login').and.callThrough();
From Docs:

By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation.

Now this should register with the sonar cube as the code will be executed and if you set this.loginForm.valid to true, the if will execute, and when set to false, the else part of the block will execute


text:
Q: Throw exception and getting e null I throw a exception with some message like:
public static ILSResponseEmailLookUPBO getILSUserAccounts(Resources res,
        String email) throws TripLoggerCustomException,
        TripLoggerUnexpectedErrorException {
    String resp = null;

    String lookupURL;
    try {
        lookupURL = TripLoggerConstants.ServerConstants.ILS_LOOKUP_URL
                + URLEncoder.encode(email, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        throw new TripLoggerCustomException(
                res.getString(R.string.error_try_again));
    }
    try {
        resp = ConnectionManager.getInstance().httpRequest(lookupURL,
                TripLoggerConstants.RequestMethods.GET);
    } catch (IOException e) {
        if (e.getMessage().equals(
                res.getString(R.string.network_unreachable))
                || e.getMessage().equals(
                        res.getString(R.string.host_unresolved))) {
            throw new TripLoggerCustomException(
                    res.getString(R.string.network_not_reachable));
        } else {
            throw new TripLoggerCustomException(
                    res.getString(R.string.email_notfound_ils));
        }
    }

here my else part execute.
And my exception class is:
 public class TripLoggerCustomException extends Exception {

    private String customMessage;
    private static final long serialVersionUID = 1L;

    public TripLoggerCustomException() {
        super();
    }

    public TripLoggerCustomException(String message) {
        super(message);
        this.customMessage = (message == null ? "" : message);
    }

    public String getCustomMessage() {
        return this.customMessage;
    }

    public void setCustomMessage(String customMessage) {
        this.customMessage = customMessage;
    }
     }

And here i catch this exception:
  private void manageLookUpActions(final String emailID) {

    new Thread() {
        public void run() {

            try {
                listILSAccounts = ILSLookupEmailBL.getILSUserAccounts(
                        getResources(), emailID);
            } catch (TripLoggerCustomException e) {
                dismissProgressBar();
                handleException(e.getMessage());
                return;
            } catch (TripLoggerUnexpectedErrorException e) {
                dismissProgressBar();
                handleException(e.getMessage());
                return;
            }
}
    }.start();

}

but here in catch of TripLoggerCustomException e is null.why?Can anyone help me?

A: After looking into multiple reports on StackOverflow, it seems like this is not an actual issue. Multiple people have been saying that it is a problem in the combination of the Eclipse debugger and the Android Emulator. That is why you don't get a NullPointerException, which you would definitely get if e was null.
So this is probably not an issue you have to worry about.


text:
Q: How come "tales" can get 'taller' as in "his tales are getting taller"?
"You are merely repeating the names of those who were acquitted of being Death Eaters thirteen years ago!" said Fudge angrily. "You could have found those names in old reports of the trials! For heavens sake, Dumbledore - the boy was full of some crackpot story at the end of last year too - his tales are getting taller, and you're still swallowing them - the boy can talk to snakes. Dumbledore, and you still think he's trustworthy?"
Harry Potter and the Goblet of Fire

I'm just wondering how come 'tales' can get 'taller'? It seems to me that tales are getting longer makes more sense. How should we understand it here?

A: A tall tale is an exaggerated, fantastic story (Wiktionary)


text:
Q: Migration of hard drive from one raid array to another I would like to remove a working drive in a raid-1 array, replacing with a new drive, in order to hopefully build a "test system" where I can experiment with OS upgrades and migration of an old "point-of-sale" enterprise software for which we have no original installation disks. I have also been unable to upgrade drivers on current system and would like to upgrade to a current, stable CentOS that our software will run on.
Origin system is Dell PowerEdge 410 running CentOS 5.11 and raid card is Serial-Attached SCSI SAS 6/iR. "Test" system is a Dell Optiplex 360 with a Dell PERC 6i card.
Can I create a "duplicate" raid array this way if I rebuild using removed disk and bypass initialization? If so, I will also duplicate our BackupEdge set-up with a NAS device (all of this on a separate LAN and WAN, of course) so I can then "experiment away", as I fully expect to create a few Linux "pieces that I can keep" during the learning process! (newb/determined hobbyist/family store I.T. guy)
My first posted question and I appreciate any help!
PS - Next question will be regarding how, if at all poss to re-install the pieces and resolve the dependencies of our old P.O.S. program to an OS that is NOT End of Life...

A: Your idea of "breaking" the RAID to build another one is an interesting one, if anything. But, it's likely to be fraught with horrors.
The simple thing to do here is to use a cloning program on a boot disc(CloneZilla, Acronis, etc.) and clone the existing volume to a single hard drive. Then insert the cloned drive in to your test server. There is no reason to have a second RAID array for simple testing.
If for some reason you need to build another RAID array, take the cloned hard drive and your cloning software boot disc, and clone the drive onto another healthy RAID volume. So, two clones: Old RAID -> Single HD -> New RAID.
Good luck! Make sure you have backups of everything. I don't want to see your next post be how to recover a corrupt RAID volume with an obsolete OS and archaic PoS system. :)


text:
Q: How to use pivot table/consolidation for excel file in vb.net? The Following Code:
 xlWorkSheet.Range("H1").Select().Consolidate(Sources:="'C:\mido\     [b.xlsx]Sheet1'!R1C1:R13C5", _
    Function:=xlCount, TopRow:=True, LeftColumn:=True, CreateLinks:=False)

gets an error message stating that xlCount is not defined. I thought this came predifined with Excel but I could not find any helpful links that would help me solve this problem.

A: Replace xlCount with its numerical value -4112 when running this from VB.NET, otherwise you will need to fully qualify this xlCount enumeration.


text:
Q: Rails 5 - Onmi Auth Devise Im working on an App, I  would not like the user to register with facebook, but once the account is created I would like the user to have the option to connect to facebook to be able to grab their profile picture and some basic info if permitted.
Will omni-auth be my best option to do this? or is there a better tool out there? I've never used omni auth or created anything like this.
Thanks in advance.


text:
Q: Access forbidden: You don't have permission to access the requested directory I'm running an ubuntu server on oracle virtualbox from windows.
I have installed a symfony2 website(lets say that it's called pepper.com) on the server under var\www,
but no matter how I configure my xampp\apache\conf\extra\httpd-vhosts.conf file, I always get Access forbidden, Error 403 when I'm trying to access www.pepper.com on the browser.
I've been searching for quite some time but I couldn't resolve this problem.
My httpd.conf file:
    ...
    ...
    Listen 127.0.0.1:80
    ...
    # Virtual hosts
    Include conf/extra/httpd-vhosts.conf

My httpd-vhosts.conf:
    NameVirtualHost *:80

    <VirtualHost *:80>
         ServerAdmin stefanos@myserver.pepper.com
         DocumentRoot "var/www/pepper.com/web"
         ServerName www.pepper.com
         ServerAlias www.myserver.pepper.com
        <Directory var/www/>
             Require all granted
        </Directory>
    </VirtualHost>

My hosts file:
    127.0.0.1       www.pepper.com

A: Your var/www/ should be /var/www/ otherwise it will take var/www relatively from the directory that Apache runs out of.


text:
Q: Manage dotfiles/configuration and ~/bin/-scripts for sets of servers I have a few git repositories containing my config files and scripts that I use.
Of course I don't use all scripts on all machines that I have access to, e.g. no music related scripts and configs on computers that I access at my company.
Since I don't use them I also don't want them to appear in these places. So I have separated all script and config repositories so far that I can clone only these to the target machines.
This way it is getting more and more complex and given that I don't want to reinvent the wheel I'm asking you – is there a tool which can do all this?
I was thinking about something like an apt-get system: Have meta packages for my sets of servers (work|home|desktop|programming computers) and just run apt-get install work|home|... / upgrade on a machine to install it / get changes. Is there a wheel or is it yet to be invented? Of course it should be as portable as possible :-]
Thank you, best regards

A: Could you perhaps use git submodules?  The git book tutorial is pretty good.


text:
Q: Facebook doesn't redirect to redirecturi after login stays in the same facebook login page I am following the code from:
https://developers.facebook.com/docs/php/howto/example_facebook_login
require_once 'config.php';
error_reporting(-1);
if(!session_id()) {
    session_start();
}
    require_once('includes/Facebook/autoload.php');

    $facebook= new Facebook\Facebook([
        'app_id'                => $setting['facebook_appid'],
        'app_secret'            => $setting['facebook_secret'],
        'default_graph_version' =>'v2.5',

    ]);
    $helper = $facebook->getRedirectLoginHelper();
    $redirect_uri = 'http://mysuite.com/facebook_auth.php';
    $permissions = ['email', 'user_likes'];
    $loginUrl = $helper->getLoginUrl($redirect_uri,$permissions);
    echo "";

It works but it doesn't redirect to my redirect page after login. it is not coming to facebook_auth.php.
After facebook login it stays in the same facebook login page.


text:
Q: UITableView editing is set to NO after reloading table In iOS 8, when I call [tableView reloadData] after deleting/moving rows, it seems the property editing of my tableView will be set back to NO (I set my tableview's editing = YES before) all the time. It is really annoyed I have to set editing property to YES after reloading my tableview. Is it a bug of iOS 8?  I would be appreciate if anyone has a work around to keep the editing property unchanged.
Updated:
Even I set editing to YES again, my tableView can not be edited anymore.

A: I am facing the same issue. The following method of UITableViewCell does give editing as "YES"
(void) setEditing:(BOOL)editing animated:(BOOL)animated

I have a check inside this method:
if ([NSStringFromClass([view class]) rangeOfString: @"Reorder"].location != NSNotFound)

which seems to be working when the table is created for the first time. However, it does not work when table gets reloaded.


text:
Q: PHP can I do this loop? I have a loop (based on an array - which could grow but NOT too much - max 6 keys) e.g.: array('12','34','56',48').  What I would like to do is loop through the array and THEN loop again to find the "previous" array val.
For example, key[0] = 12, key[1] = 34 then key[0] = 12, key[2] = 56 then key[1] = 34 etc.
The values of the array are ID's from a DB and I need (hopefully) to run a query based on the "current key" and the previous key.
Any ideas - can it be done?

A: $num_elem = count($array);
for ($i = 0; $i < $num_elem; $i++)
{
   $curr_val = $array[$i];
   $prev_val = ( 0 == $i) ? null: $array[$i-1];
}

A: Unlike the other solutions, I would recommend against using an index based accessor.
In php, the keys are not necessarily in order.  For example, if you call natsort on your array, the key=>value relationships stay the same but the array itself is actually reordered, leading to counterintuitive results.  (See Why isn't natsort (or natcasesort) working here?)
I would use something like:
<?php
  $ids = array('12','34','56','48');
  $previous = false;
  foreach($ids as $id)
  {
    echo "current: $id\n";
    echo "previous: $previous\n";
    $previous = $id;
  }
?>

A: I don't think multiple loops are really needed here.  I would use the internal pointer of the array with next(), prev(), and current() functions.

A: If I've understood correctly you want to do this.
for($i=1; $i < count($array); $i++) {
  $currentValue = $array[$i];
  $previousValue = $array[$i-1];

  // Here you can run a query based on the current and the previous value
}

For example, taking $array as array(12,34,56,48) you would have 3 iterations where the $currentValue and $previousValue would have the following values:

*

*First iteration: $currentValue = 34, $previousValue = 12

*Second iteration: $currentValue = 56, $previousValue = 34

*Third iteration: $currentValue = 48, $previousValue = 56

A: <?
$val = 56;
$data = array(12, 34, 12, 56, 34);
for($i = 0; $i < count($data); $i++) {
  if($data[$i] == $val) {
    if($i == 0) die("No previous");
    $previous = $data[$i-1];
  }
}

echo "Previous to $val was $previous";

or better yet use array_search()
to find index for given $val


text:
Q: Span Wallpaper Across Displays in Lockscreen In the Appearance tool, we have the option to span a wallpaper across multiple displays.
On the Desktop it works fine:

However, on the lock screen I see the same image repeated three times:

How do I span the wallpaper across displays on the lock screen? I don't see any option to do so in the appearance menu.

A: At this time this is not possible due to bug #1291359.
This issue is still present up to Ubuntu 16.04.
The most common thing to do at this moment is to show the default login screen/color.
You can do this by installing dconf Editor.
Open a terminal with Ctrl+Alt+T and type:
sudo apt install dconf-editor

or click dconf Editor  to auto-open Software Center and click Install to install it.
Now we must grant LightDM permissions to access dconf Editor.

*

*Gain root access, type your password (no visual feedback),and Enter.
sudo -i

*Allow user to create a connection to the X server for lightdm
xhost +SI:localuser:lightdm

*Switch to user lightdm
su lightdm -s /bin/bash

*Start dconf Editor
dconf-editor
On dconf Editor, navigate to com > canonical > unity-greeter in the left pane.

*

*Disable (untick) the value for 'draw-user-backgrounds' on the right pane.

*While at it, you may want to disable 'draw-grid' (it disables the dotted grid layer).

Reboot to confirm changes.
sudo reboot

Note: from now on LightDM has permission to access the X server, so every time you open dconf Editor, LightDM already has access.
To revoke this access, issue the command xhost -SI:localuser:lightdm as root.

A: Hm. To save you some poking around, I've tried Variety, dconf-editor, nitrogen, and CompizConfig with no luck. The closest I could get was setting a particular wallpaper for just the lock screen with dconf-editor.
Strangely, if you install gnome-tweak-tool there is a setting under Desktop that allows you to choose a separate mode and image for the Background and Lock Screen - but while the Background settings here affect my desktop, my tests with the Lock Screen settings don't make any change. It may be a lead, however, if you want to try and finagle Unity into submitting to Gnome (assuming the tweak options haven't just been broken from the start).


text:
Q: Django slow at creating objects? How long should this take to run?
 query = Contact.objects.filter(contact_owner=batch.user, subscribed=True)
 objs = [
        Message(
            recipient_number=e.mobile,
            content=content,
            sender=e.contact_owner,
            billee=user,
            sender_name=sender,
        )
        for e in query

Just this code nothing else (not saving to db I'm only running above i.e. create the objects). It takes 15 mins for 5000 messages objects to be created in the query. Is this right? Why is Django so slow?
This is the model it creates, again I'm not saving here. I think there ahs to be an issue in the model when an object is created, that or Django is just too slow for my needs.
Model message
from django.db import models
from django.contrib.contenttypes import generic
from django.utils.translation import ugettext as _
from django.conf import settings
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver

import uuidfield.fields
import picklefield
import jsonfield

if 'timezones' in settings.INSTALLED_APPS:
    from timezones.utils import adjust_datetime_to_timezone
else:
    def adjust_datetime_to_timezone(a, b, c):
        return a

from gateway import Gateway

class MessageManager(models.Manager):
    def get_matching_message(self, datadict):
        for gateway in Gateway.objects.all():
            try:
                return Message.objects.get(
                    gateway_message_id=datadict.get(gateway.status_msg_id),
                    gateway=gateway,
                )
            except Message.DoesNotExist:
                pass

    def get_original_for_reply(self, datadict):
        for gateway in Gateway.objects.all():
            try:
                return Message.objects.get(
                    uuid=datadict.get(gateway.uuid_keyword),
                    gateway=gateway
                )
            except Message.DoesNotExist:
                pass
        # This may have been a message sent from another phone, but
        # there may be a reply-code that was added in.
        return self.custom_reply_matcher(datadict)

    def custom_reply_matcher(self, datadict):
        # Designed to be overridden.
        return None

    def get_last_rate_for(self, recipient_number):
        m = Message.objects.filter(recipient_number=recipient_number).exclude(
            gateway_charge=None).order_by('-send_date')[0]
        return m.gateway_charge / m.length

    def get_message(self, gateway_message_id):
        try:

            return Message.objects.get(gateway_message_id=gateway_message_id,)

        except Message.DoesNotExist:
            pass

    MESSAGE_STATUSES = (
        ('Unsent', 'Unsent'),
        ('Sent', 'Sent'),
        ('Delivered', 'Delivered'),
        ('Failed', 'Failed'),
    )
    class Message(models.Model):
        """
        A Message.

        We have a uuid, which is our reference. We also have a gateway_message_id,
        which is their reference.  This is required by some systems so we can
        pass in a unique value that will allow us to match up replies to original
        messages.
        """

        content = models.TextField(help_text=_(u'The body of the message.'))
        recipient_number = models.CharField(max_length=32,
            help_text=_(u'The international number of the recipient'
                         ', without the leading +'))

        sender = models.ForeignKey('auth.User', related_name='sent_sms_messages')

        sender_name = models.CharField(max_length=11)

        send_date = models.DateTimeField(null=True, blank=True, editable=False)
        delivery_date = models.DateTimeField(null=True, blank=True, editable=False,
                                             help_text="The date the message was sent.")
        uuid = uuidfield.fields.UUIDField(auto=True,
            help_text=_(u'Used for associating replies.'))

        status = models.CharField(max_length=16, choices=MESSAGE_STATUSES,
            default="Unsent",
        )
        status_message = models.CharField(max_length=128, null=True, blank=True)
        billed = models.BooleanField(default=False)

        content_type = models.ForeignKey('contenttypes.ContentType')
        object_id = models.PositiveIntegerField()
        billee = generic.GenericForeignKey()

        gateway = models.ForeignKey('sms.Gateway',
            null=True, blank=True, editable=False)
        gateway_message_id = models.CharField(max_length=128,
            blank=True, null=True, editable=False)

        reply_callback = picklefield.PickledObjectField(null=True, blank=True)

        gateway_charge = models.DecimalField(max_digits=10, decimal_places=5,
            null=True, blank=True)

        charge = models.DecimalField(max_digits=10, decimal_places=5,
                                             null=True, blank=True)

        objects = MessageManager()

        class Meta:
            app_label = 'sms'
            permissions = (
                ('view_message', 'Can view message'),
            )
            ordering = ('send_date',)

        def send(self, gateway):
            gateway.send(self)

        @property
        def length(self):
            """Unicode messages are limited to 70 chars/message segment."""
            # try:
            #     return len(str(self.content)) / 160 + 1
            # except UnicodeEncodeError:
            #     return len(self.content) / 70 + 1
            return len(self.content) / 160 + 1

        @property
        def local_send_time(self):
            # TODO: Get this from UserProfile?
            if getattr(self.billee, 'timezone', None):
                return adjust_datetime_to_timezone(
                    self.send_date,
                    settings.TIME_ZONE,
                    self.billee.timezone
                )
            return self.send_date

        @property
        def local_send_date(self):
            return self.local_send_time.date()

        def __unicode__(self):
            return "[%s] Sent to %s by %s at %s [%i]" % (
                self.status,
                self.recipient_number,
                self.sender,
                self.send_date,
                self.length
            )

    @receiver(pre_save, sender=Message)
    def my_handler(sender, **kwargs):
        instance = kwargs['instance']
        if not instance.charge:
            instance.charge = instance.length
            # No need to save, as we're slipping the value in
            # before we hit the database.

contact model
import os
import datetime
from uuid import uuid4
from datetime import date
from django.db import models
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django.utils import timezone
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver

from adaptor.fields import *
from adaptor.model import CsvModel

def path_and_rename(path):
    """
   Callable function for renaming the file being uploaded.

    """
    def wrapper(instance, filename):
        ext = filename.split('.')[-1]
        # get filename
        if instance.pk:
            filename = '{}.{}'.format(instance.pk, ext)
        else:
            # set filename as random string
            filename = '{}.{}'.format(uuid4().hex, ext)
            # return the whole path to the file
        return os.path.join(path, filename)

    return wrapper

class GroupManager(models.Manager):
    def for_user(self, user):
        return self.get_query_set().filter(user=user, )

class Group(models.Model):
    """
     Stores all groups.
    """
    name = models.CharField(max_length=60)
    modified = models.DateTimeField(null=True, auto_now=True, help_text="Shows when object was modified.")
    created = models.DateTimeField(auto_now_add=True, help_text="Shows when object was created.")

    #FK
    user = models.ForeignKey(User, related_name="user")

    objects = GroupManager()

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('contacts.views.group', args=[str(self.id)])

    def get_delete_url(self):
        return reverse('contacts.views.group_delete_confirm', args=[str(self.id)])

class ContactManager(models.Manager):
    """
    Custom Manager for keyword.
    """
    def unsorted_contacts(self, user):
        """
        Manager that will list all records for a user where group is 'None'.
        """
        return self.get_query_set().filter(contact_owner=user, group=None)

    def for_user_and_group(self, user, group):
        """
        Manager that will list all records for a user where group is 'group'.
        """
        return self.get_query_set().filter(contact_owner=user, group=group)

    def for_user(self, user):
        """
        Manager that will list all records for a user they own.
        """
        return self.get_query_set().filter(contact_owner=user)

class Contact(models.Model):
    """
    Stores all contacts.
    """
    first_name = models.CharField(max_length=60, blank=True)
    last_name = models.CharField(max_length=60, blank=True)
    company = models.CharField(max_length=100, blank=True)
    mobile = models.CharField(max_length=15)
    email = models.EmailField(max_length=100, blank=True)
    subscribed = models.NullBooleanField(default=1, help_text="Shows if contact is unsubscribed to SMS/Email.")
    modified = models.DateTimeField(null=True, auto_now=True, help_text="Shows when object was modified.")
    created = models.DateTimeField(auto_now_add=True, help_text="Shows when object was created.")

    objects = ContactManager()

    #FK
    group = models.ForeignKey(Group, related_name='contacts', blank=True, null=True)
    contact_owner = models.ForeignKey(User)

    def __unicode__(self):
        return self.first_name

    def full_name(self):
        return "%s %s" % (self.first_name, self.last_name)

    def get_delete_url(self):
        return reverse('contacts.views.contact_delete', args=[str(self.id), str(self.group_id)])

    def get_group_absolute_url(self):
        return reverse('contacts.views.group', args=[str(self.group_id)])

    @property
    def user(self):
        return self.contact_owner

@receiver(pre_delete, sender=Contact)
def contact_cleanup(sender, instance, **kwargs):
    """
    Do a bit of tidying up when deleting a Contact.
    Sent at the beginning of a model's delete() method and a queryset's delete() method.
    """
    # Remove any FK's not done by cascade delete like generic relationships.
    from unsubscribe.models import Unsubscribe
    unsubscribe_list = Unsubscribe.objects.filter(object_id=instance.id, content_type__model='contact')
    unsubscribe_list.delete()

class Upload(models.Model):
    """
    Stores jobs and status uploads of file uploads for CSV import.
    """
    filepath = models.FileField(upload_to=path_and_rename('uploadsCSV'),
                                help_text="It can take several minutes for contacts to appear.")
    # Upload audit information
    uploaded_by = models.ForeignKey(User)
    date_uploaded = models.DateTimeField(auto_now_add=True)

    # Processing audit information
    PENDING, PROCESSED, FAILED = 'Pending', 'Processed', 'Failed'
    STATUSES = (
        (PENDING, _(PENDING)),
        (PROCESSED, _(PROCESSED)),
        (FAILED, _(FAILED)),
    )

    status = models.CharField(max_length=64, choices=STATUSES, default=PENDING)
    processing_description = models.TextField(blank=True, null=True)
    num_records = models.PositiveIntegerField()
    num_columns = models.PositiveIntegerField()
    date_start_processing = models.DateTimeField(null=True)
    date_end_processing = models.DateTimeField(null=True)

    #FKs
    group = models.ForeignKey(Group)

    def get_configurator_url(self):
        return reverse('contacts.views.upload_configurator', args=[str(self.id)])

    def process(self, cleaned_data):
        self.date_start_processing = timezone.now()
        try:

            group_position = self.num_columns + 1
            upload_id_position = self.num_columns + 1

            # Try and import CSV
            import_this(data=self.filepath, extra_fields=[
                {'value': self.group_id, 'position': group_position},
                {'value': self.uploaded_by.id, 'position': upload_id_position}], cleaned_data=cleaned_data)

            self._mark_processed(self.num_records)

        except Exception as e:
            self._mark_failed(unicode(e))

    def was_processing_successful(self):
        return self.status == self.PROCESSED

    def was_processing_successful(self):
        return self.status == self.PROCESSED

    def _mark_processed(self, num_records, description=None):
        self.status = self.PROCESSED
        self.date_end_processing = date.today()
        self.num_records = num_records
        self.processing_description = description
        self.save()

    def _mark_failed(self, description):
        self.status = self.FAILED
        self.processing_description = description
        self.save()

def import_this(cleaned_data, *args, **kw):
    # make custom ContactCSVModel
    class ContactCSVModel(CsvModel):
        for k, v in cleaned_data.items():

            if not v == '':
                # print("---------------------------------")
                # print(str(v))
                # print("---")
                # print(k[3:])
                # print("---------------------------------")
                setattr(CsvModel, v, CharField(row_num=k[3:]))

        group = DjangoModelField(Group, row_num="5")
        contact_owner = DjangoModelField(User, row_num="6")

        class Meta:
            delimiter = ","
            dbModel = Contact
            update = {'keys': ["mobile", "group"]}

    return ContactCSVModel.import_data(*args, **kw)

A: If you install Django debugtoolbar you could actually see the queries being fired, and the code responsible on firing them.
This slowness is mainly because django fires a new db query every time you do e.mobile and e.contact_owner, in the loop.
To prevent these queries, prefetch the data using select_related like below
query = Contact.objects.select_related('mobile', 'contact_owner').filter(contact_owner=batch.user, subscribed=True)

If your relations are many to many, then use prefetch_related rather than select_related.