text:
Q: Winforms MVP with multiple views and one presenter I am trying to develop a Project Management System in my application following the Model View Presenter (MVP) pattern. My question is this, I have seen numerous examples of MVP but I haven't seen one with one Presenter and multiple Views. For example when a user opens a project the same project data can be viewed by a treeview, a datagrid and a chart. How do I cope with that?

A: For making the code decoupled and easy to maintain I would suggest you to have one presenter for each View even if they look like very similar: so that each view will have its own presentation logic.
If you got the same data that needs to be showed on more than one view you could share the View-model between the presenters but again I would suggest you to use different view model for each presenter(even if they are very similar)

A: The way you would do it, is to abstract your view by placing it behind an interface and then wire up the presenter with the concrete implementation of your view.
That said, I'm not sure you would ever want to do it in the real world. The differences between dealing with a tree view compared to a chart would mean that you end up over generalizing things in your view interface and writing a lot of messy code in your view to fulfil the contract.
I would suggest keeping your presenter to view ratio at 1:1. If you want multiple views over the same data then it is your model that you should share across the presenters, so you are displaying the same data in different ways.

A: You should almost always have one presenter instance per view instance.
Say you open a CustomerView, and its CustomerViewPresenter. That's one instance of each.
The you open another CustomerView, and another CustomerViewPresenter instance. That's two instances of each.
That doesn't mean that a given presenter always has to use the same view, in fact it should not. The presenter should talk to one view interface. You should be able to swap a real view for a mock view for testing.

A:
This question might be old but I just want to post my answer for future use.

If you have a view that could be used on multiple views, inheritance is the key.
Example:
using System;

// declaring an interface
public interface A {

    // declare a treeview;
    void treeView();
    // declare a datagrid;
    void datagrid();
    // declare a chart;
    void chart();
}

// The views of interface A
// is inherited into interface B
public interface B : A {
    // declare a label or string
    string mystring  { get; set; }
}

C# allows the user to inherit one interface into another interface. When a class implements the inherited interface then it must provide the implementation of all the members that are defined within the interface inheritance chain.
public partial class Form1 : Form, B
{
    private Presenter presenter;

    public Form1()
    {
        InitializeComponent();
    }

    public string mystring
    {
        get
        {
            return textBox1.Text;
        }
        set
        {
            textBox1.Text = value;
        }
    }

    public void treeView()
    {
        presenter = new Presenter(this);
        presenter.GenerateTreeView();
    }

    public void datagrid()
    {
        presenter = new Presenter(this);
        presenter.GenerateDatagrid();
    }

    public void chart()
    {
        presenter = new Presenter(this);
        presenter.GenerateChart();
    }
}

And your presenter may look like this:
public class Presenter
{
    public B viewB;
    public DomainLogic model;

    public Presenter(B view)
    {
        viewB = view;
    }

    public void GenerateTreeView()
    {
        model = new DomainLogic();
        model.CreateTreeView();
    }

    public void GenerateDatagrid()
    {
        model = new DomainLogic();
        model.CreateDatagrid();
    }

    public void GenerateChart()
    {
        model = new DomainLogic();
        model.CreateChart();
    }

    public void GenerateString()
    {
        model = new DomainLogic();
        viewB.mystring = model.createString();
    }

}

In this case you may have 2 views in one presenter. Not literally 2 views. but inheritance can avoid duplication of codes to your Views.


text:
Q: Animate a div when focus an input I need to animate a div when focus an input. I tried this but is not working.
$("input").focus(function() {
    $("div").animate({
        marginLeft: "0"
    }, 500);
});

The initial position is  margin-left: -500px. The jQuery is installed correctly. When I try to do the same but with a div instead of a input It works.
$(".a_div").click(function() {
$("div").animate({
    marginLeft: "0"
}, 500);
});

But I changed to an input and no longer works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jackson does not support ISO date format Writing a web service which supports both Xml and JSON media types. Following ISO standard to support date format yyyy-MM-dd'T'HH:mm:ss.SSSXXX.
To support this format in xml I have written a DateAdapter class which takes carecof marshaling and un-marshaling of date fields.
There is a CustomSerialization and Deserialization class for Json formats. It's implementation is almost similar to Adapter class. But it throws exception.
@Override
    public void serialize(Date aDate, JsonGenerator aJsonGenerator, SerializerProvider aSerializerProvider)
            throws IOException, JsonProcessingException {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        String dateString = dateFormat.format(aDate);
        aJsonGenerator.writeString(dateString);
    }

Exception:
Illegal pattern character 'X'
    at java.text.SimpleDateFormat.compile(SimpleDateFormat.java:768)

Using jackson v2.2.1
  Working Adapter implementation is exactly same.

private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

    @Override
    public String marshal(final Date v) throws Exception {
        System.out.println(v);
        return dateFormat.format(v);
    }

    @Override
    public Date unmarshal(final String v) throws Exception {
        System.out.println(v);
        return dateFormat.parse(v);
    }

A: The SimpleDateFormat pattern letter X was added in Java 7. You must be using a lower version JRE.
Javadoc 6 versus Javadoc 7.

A: You can create a Deserializer and use it as an @Annotation
public class TemporalDeserializerLocalDateTime extends JsonDeserializer {
@Override
public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationCtx)
        throws IOException, JsonProcessingException {
        ObjectCodec oc = jsonParser.getCodec();
        String content = oc.readValue(jsonParser, String.class);
        return LocalDateTime.parse(content);
    }
}

public class PaymentResource {
@JsonDeserialize(using = TemporalDeserializerLocalDateTime.class)
    private LocalDateTime paymentDate;
}

A: Joop Eggen's comment fixed the issue. Simple Date Format from SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); to SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); fixed the issue.


text:
Q: Design a component responsiveness on all the view ports Component:
my-profile.html

Hilda Isable Sanchez

186579

hilda.sanchez.gmail.com

800.457.5687

my-profile.scss
my-profile {
    .presentation {
        position: relative;
        display: inline-block;
        width: 100%;
        height: 100%;
        overflow: hidden;
        img {
            width: 30%;
            height: 30%;
        }
        .margin-left-150{
          margin-left: 150px;
        }
    }
}

Page:
settings.html
<ion-content class="content">
  <ion-grid no-padding>
    <ion-row class="header">
      <ion-col col-6>
        <my-profile></my-profile>
      </ion-col>
    </ion-row>
    <ion-row class="details">
      <ion-col col-12>

      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

settings.scss
page-settings {
    .content {
        ion-grid {
            height: 100%;
        }
        .header {
            flex: 1;
            background-color: color($colors, secondary);
        }
        .details {
            flex: 2;
        }
    }
}

It looks good on a mobile device like below:

But Horrible on iPad:

Can you please help me to design this correctly on all the viewports of the devices? In other words nicely centered my-profile.html component on all the device sizes (responsiveness).
Note: I know this was happened due to margin-left-150.But how can I center it properly?

A: Seem like you want a perfect centering. Just use flexbox:

.parent {
  width: 100%;
  display: flex;
  justify-content: center;
}

.child {
  margin: auto;
  border: solid 1px #123;
}

Profile info

 Text Text Text

 An other text An other text

Apply to your code:
<ion-col col-12 class="parent">
    <my-profile class="child"></my-profile>
</ion-col>

A: To center an inline-block element horizontally, you set its parent to text-align: center
I also removed width: 100% from presenation or else it won't center being full width of its parent
my-profile.html

Hilda Isable Sanchez

186579

hilda.sanchez.gmail.com

800.457.5687

my-profile.scss
my-profile {
    text-align: center;
    .presentation {
        position: relative;
        display: inline-block;
        height: 100%;
        overflow: hidden;
        text-align: left;            /*  reset to left align  */
        img {
            width: 30%;
            height: 30%;
        }
    }
}

Another option is of course Flexbox. With this you can also drop the height: 100% as flex items in a row direction by default fill their parent's height (align-items: stretch).
my-profile.html

Hilda Isable Sanchez

186579

hilda.sanchez.gmail.com

800.457.5687

my-profile.scss
my-profile {
    display: flex;
    justify-content: center;
    .presentation {
        position: relative;
        overflow: hidden;
        img {
            width: 30%;
            height: 30%;
        }
    }
}


text:
Q: CircularImageView stretching picture in API 10 I am using circularimageView to display the picture of a person. Here's the class.
public class CircularImageView extends ImageView {
private int borderWidth = 4;
private int viewWidth;
private int viewHeight;
private Bitmap image;
private Paint paint;
private Paint paintBorder;
private BitmapShader shader;

public CircularImageView(Context context) {
    super(context);
    setup();
}

public CircularImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setup();
}

public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    setup();
}

private void setup() {
    // init paint
    paint = new Paint();
    paintBorder = new Paint();

    paint.setAntiAlias(true);

    setBorderColor(Color.WHITE);
    paintBorder.setAntiAlias(true);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {

        this.setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);

    }

    else
    {

    }
    paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
}

public void setBorderWidth(int borderWidth) {
    this.borderWidth = borderWidth;
    this.invalidate();
}

public void setBorderColor(int borderColor) {
    if (paintBorder != null)
        paintBorder.setColor(borderColor);

    this.invalidate();
}

private void loadBitmap() {
    BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable();

    if (bitmapDrawable != null)
        image = bitmapDrawable.getBitmap();
}

@SuppressLint("DrawAllocation")
@Override
public void onDraw(Canvas canvas) {
    // load the bitmap
    loadBitmap();

    // init shader
    if (image != null) {
        shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        paint.setShader(shader);
        int circleCenter = viewWidth / 2;

        // circleCenter is the x or y of the view's center
        // radius is the radius in pixels of the cirle to be drawn
        // paint contains the shader that will texture the shape
        canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter + borderWidth - 4.0f, paintBorder);
        canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter - 4.0f, paint);
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = measureWidth(widthMeasureSpec);
    int height = measureHeight(heightMeasureSpec, widthMeasureSpec);

    viewWidth = width - (borderWidth * 2);
    viewHeight = height - (borderWidth * 2);

    setMeasuredDimension(width, height);
}

private int measureWidth(int measureSpec) {
    int result = 0;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);

    if (specMode == MeasureSpec.EXACTLY) {
        // We were told how big to be
        result = specSize;
    } else {
        // Measure the text
        result = viewWidth;
    }

    return result;
}

private int measureHeight(int measureSpecHeight, int measureSpecWidth) {
    int result = 0;
    int specMode = MeasureSpec.getMode(measureSpecHeight);
    int specSize = MeasureSpec.getSize(measureSpecHeight);

    if (specMode == MeasureSpec.EXACTLY) {
        // We were told how big to be
        result = specSize;
    } else {
            // Measure the text (beware: ascent is a negative number)
            result = viewHeight;
        }

        return (result + 2);
    }
}

It works fine in anything > API 10 but in other cases the image gets stretched out and only the top left part of the image is visible and is pixelated. I tried Resizing the bitmap of the picture but it did not help.
Here is the bitmap initialization
PackageManager m = getActivity().getPackageManager();
        String s = getActivity().getPackageName();
        PackageInfo p = null;
        try {
            p = m.getPackageInfo(s, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        s = p.applicationInfo.dataDir;
        //String root = Environment.getExternalStorageDirectory().toString();
        s += "/player_photos/" + player.getPlayerId() + ".png";
        Bitmap bMap = BitmapFactory.decodeFile(s);
        Resources res = getResources();
        BitmapDrawable icon = new BitmapDrawable(res, bMap);

            playerDP.setImageDrawable(icon);

        }


text:
Q: System.Web.Hosting.IIS7WorkerRequest:ReadEntityCoreSync, What is it? I'm not a developer, so please excuse me ignorance in this case. We have an ASP.net webforms application written in C#. The application is served from IIS 8 on Win Server 2012 VM, with 8-core CPU and plenty of RAM.
Some of application users are complaining about some page stalls.
We have an Application Performance Monitoring system, it is telling me that the below method is taking 30 seconds to execute somtimes.
Name: System.Web.Hosting.IIS7WorkerRequest:ReadEntityCoreSync
Type: .NET Class / Method
Class: System.Web.Hosting.IIS7WorkerRequest
Method: ReadEntityCoreSync
I have been trying to look around trying to figure out what is this method all about with no luck, could anyone please tell me what is this method doing, and what could cause it to run for extended period of time?


text:
Q: Complex Numbers - Equation manipulation Please see link, I'm wondering how you end with RHS of equation on second line of image. Please can explain the step and algebra manipulation used
Thanks

A: You have the expression
$$\frac{(z-ia)^2e^{imz}}{(a^2+z^2)^2}$$
First we note that the roots of $a^2+z^2$ are $z = \pm ia$ so we have
$$\frac{(z-ia)^2}{(a^2+z^2)^2} = \frac{(z-ia)^2}{\left((z-ia)(z+ia)\right)^2}$$
$$= \frac{(z-ia)^2}{(z-ia)^2(z+ia)^2} = \frac{1}{(z+ia)^2}$$
Now what's left to do is to first compute
$$\frac{d}{dz}\left(\frac{e^{imz}}{(z+ia)^2} \right)$$
using the quotient rule $(u/v)'= (u'v - uv')/v^2 $ , we have
$$\frac{d}{dz}\left(\frac{e^{imz}}{(z+ia)^2} \right) = \frac{ime^{imz}\cdot(z+ia)^2 - e^{imz}\cdot 2(z+ia)}{(z+ia)^4} = e^{imz} \frac{im(z+ia)^2 - 2(z+ia)}{(z+ia)^4}$$
That's enough to set $z = ia$ now, so we have
$$e^{im(ia)} \frac{im(2ia)^2 -2(2ia)}{(2ia)^4} = e^{-ma} \frac{-im\cdot 4a^2- 4ia}{16a^4} = ie^{-ma} \frac{-ma-1}{4a^3} = -ie^{-ma}\frac{(1+ma)}{4a^3}$$
I guess you must have made a mistake during the simplifcation.

A: Perhaps they did directly
$$\lim_{z\to ai}\left[\frac{(z-ai)^2e^{imz}}{(z-ai)^2(z+ai)^2}\right]'=\lim_{z\to ai}\frac{ime^{imz}(z+ai)-2e^{imz}}{(z+ai)^3}=\frac{-me^{-ma}2a-2e^{-ma}}{-8a^3i}$$
$$=\frac{e^{-ma}(ma+1)}{4a^3i}=-\frac{ie^{-ma}}{4a^3}(ma+1)$$


text:
Q: Query and table optimization `
SELECT DISTINCT ECS.UserId,,PFR.EntityId,PFR.CreatedBy
FROM EventConsentStatus ECS
INNER JOIN @Institutions I ON ECS.InstitutionId=I.InstitutionId
LEFT JOIN ParentFormResponses PFR ON  PFR.EntityTypeId = 1
          AND PFR.EntityId=@ActivityId AND ECS.EventId=PFR.EntityId
WHERE ECS.EventId = @ActivityId

A table called ParentFormResponses mentioned in the above query is having more than 3lacs records. Table is not having any identity column instead I have created clustered primary index on group of some columns based on uniqueness. But still it is taking more than 16 minutes to execute a simple select statement i.e. select * from ParentFormResponses.
If I am removing column names of ParentFormResponses table from above mentioned select statement then it is showing result in 2 3 seconds but for above query it is taking too much time.
If I create non clustered index on entityid and entitytypeid then also it is not giving optimized result.
Please suggest me how can I improve table structure and query performance.
Detail information:
Table Stucture:
`CREATE TABLE [dbo].[ParentFormResponses](
[EntityId] [int] NOT NULL,
[FormId] [int] NOT NULL,
[StudentId] [nvarchar](50) NOT NULL,
[CreatedBy] [nvarchar](50) NOT NULL,
[CreatedOn] [datetime] NOT NULL,
[EntityTypeId] [int] NOT NULL,
[FormVersion] [decimal](18, 1) NOT NULL,
[DigitallySigned] [bit] NULL,
[HasResponseChanged] [bit] NULL,

CONSTRAINT [PK_ParentFormResponses] PRIMARY KEY CLUSTERED
(
    [EntityId] ASC,
    [FormId] ASC,
    [StudentId] ASC,
    [EntityTypeId] ASC,
    [FormVersion] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]`
=> I dropped primary key index and created below non clustered index
CREATE NONCLUSTERED INDEX [IX_ParentFormResponses_sakshi_EntityId] ON [dbo].[ParentFormResponses_sakshi]
(
    [EntityId] ASC,
    [EntityTypeId] ASC,
    [FormId] ASC,
    [FormVersion] ASC
)
INCLUDE (   [StudentId],
    [CreatedBy]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

=> Result of all three tables based on sp_spaceused are-

* name-                      rows,   reserved,   data,       index_size, unused

* ParentFormResponses    -        309961,    64704 KB,   63592 KB,   936 KB,     176 KB

* ParentFormResponses_sakshi-    309893, 117696 KB,  60472 KB,   56944 KB,   280 KB

* EventConsentStatus -        673796,    380920 KB,  109240 KB,  271512 KB,  168 KB
Note: Number of records are not 30k but more than 3 lacs. By mistake I wrote wrongly.

A: The combination of distinct and left join is suspicious from a performance perspective.  First, check the following query:
SELECT ECS.UserId, ECS.EntityId
FROM EventConsentStatus ECS INNER JOIN
     @Institutions I
     ON ECS.InstitutionId = I.InstitutionId
WHERE ECS.EventId = @ActivityId;

You can optimize this with an index on EventConsentStatus(EventId, UserId).  Assuming this has good performance, it will produce the right set of rows.  If not, then you may be getting duplicates from @Institions.  If this is the case, then consider removing it (no columns are used from that table, it is only for filtering).  Or:
SELECT ECS.UserId, ECS.EntityId
FROM EventConsentStatus ECS
WHERE ECS.EventId = @ActivityId AND
      EXISTS (SELECT 1 FROM  @Institutions I WHERE ECS.InstitutionId = I.InstitutionId)

To get the right values, let's get the additional data using outer apply:
SELECT ECS.UserId, PFR.EntityId, PFR.CreatedBy
FROM EventConsentStatus ECS INNER JOIN
     @Institutions I
     ON ECS.InstitutionId = I.InstitutionId OUTER APPLY
     (SELECT TOP 1 PFR.EntityId, PFR.CreatedBy
      FROM ParentFormResponses pfr
      WHERE ECS.EventId = PFR.EntityId  AND
            PFR.EntityTypeId = 1 AND
            PFR.EntityId = @ActivityId
     ) pfr
WHERE ECS.EventId = @ActivityId;

For this, you want an index on ParentFormResponses(EntityId, EntityTypeID, CreatedBy).


text:
Q: Intuition on what to perform (structural) induction on or clues when one's stuck while conducting a proof by induction Suppose we're working with Peano representation of natural numbers so as to have structural inductive approach and suppose we have an inductive definition for parity of natural numbers as follows:
$ev \in \mathbb{N} \rightarrow EvenParity\\
zero :\ \ ev\ 0 \\
more : \forall n \in \mathbb{N}, ev\ n \rightarrow ev\ (S\ (S\ n))$
So either zero is even, or, given an even $n \in \mathbb{N}$, then application of successor two times $S\ (S\ n))$ also forms an even number.
To finish the definition, suppose these are the only ways to construct an even number.
Now we want to prove the following:
$\forall n\ m \in \mathbb{N}, ev\ (n + m) \rightarrow ev\ n \rightarrow ev\ m$
Let us name our hypotheses as follows:
$ev\ (n + m)\ is\ H$
$ev\ n\ \ \ \ \ \ \ \ \ \ \ \ \ is\ H'$
Now there are several ways to continue the proof. We can perform induction on $n$, $m$, $H$ or $H'$.
The proof is rather trivial if one performs induction on $H'$, that is $ev\ n$.
First we need to show $ev\ m$ under the assumption that $n = 0$ (considering the equation $zero$), hence $ev\ (0 + m)$, this reduces to $ev\ m$ which is what we wanted to prove.
Now we need to show $ev\ m$ under the assumption that the number has been built from $more$, that is $n = S\ (S\ n))$. Using the inductive hypothesis $ev\ (n + m) \rightarrow ev\ m$, we see $ev\ m$ follows from $ev\ (n + m)$. From $ev\ (S\ (S\ n) + m))$ we can get $ev\ (S\ (S\ (n + m)))$, from which $ev\ (n + m)$ and we're done.
However, if I try to conduct a similar proof by induction using any of the other possibilities, I get stuck very quickly in the $more$ case.
For example, consider we try induction on $m$ (over the Z | S n structure).
First, $m = 0$, hence we need to show $ev\ 0$. This follows from definition.
However, now we need to show $ev\ (S\ m)$. Here we only know $ev\ (n + S\ m)$, $ev\ n$ and our inductive hypothesis $ev\ (n + m) \rightarrow ev\ m$. The proof gets messy at this point, could perhaps be done by showing that even parity of successor of n follows from uneven, but I am not sure - still, it gets comparatively complicated very quickly.
How does one know what to perform induction on and what are some common clues that a proof leads just about nowhere - for example in the induction over $m$ case, I can see that my hypotheses are close to useless, as I need to show $ev\ (S\ m)$ from $ev\ (n + S\ m)$, $ev\ n$ and $ev\ (n + m) \rightarrow ev\ m$.


text:
Q: Infinite sum + integral I have the following sum + integral to solve:
$\int_0^{\infty}dt\,   t^{\frac{m-3}{2}} e^{-t(a^2+b^2)} \sum_{n=-\infty}^{\infty} e^{-t(c^2 n^2 +2bcn)}$
My try:
Refine[
Integrate[t^{(m - 3)/2} Exp[-t (a^2 + b^2)] Sum[
Exp[-t (c^2 n^2 + 2 b c n)], {n, -Infinity, Infinity}], {t,0,Infinity}],
{Element[{a, b, c}, Reals], Element[m, Integers], m > 0}]

where $a,b,c\in\mathrm{R}$, $m\in\mathrm{N^+_0}$.
So far, this input gives an output with an integral (and an EllipticTheta function):
$\text{Integrate}\left[\frac{\sqrt{\pi } t^{\frac{m-3}{2}-\frac{1}{2}} e^{b^2 t-t \left(a^2+b^2\right)} \vartheta _3\left(\frac{b \pi }{c},e^{-\frac{\pi ^2}{c^2 t}}\right)}{\left| c\right| },\{t,0,\infty \},\text{Assumptions}\to m\in \mathbb{Z}\land (a|b|c)\in \mathbb{R}\land m>0\right]$
Is it possible to do the sum & integration to receive a closed form, at least for some particular values of $m$, like $m=0,1,2,3$? How to change the input in order to achieve that?
I'll welcome any comments on how to improve this question (and its title).

A: Making unsubstantiated use of Fubini's theorem or whatever its discrete equivalent is, let's interchange the sum and the integral:
$\sum_{n=-\infty}^{\infty} \int_0^{\infty}dt\, t^{\frac{m-3}{2}}e^{-t(a^2+b^2)}e^{-t(c^2n^2+2bcn)}$
First doing the integration:
Assuming[Element[a | b | c, Reals] && Element[m | n, Integers],
  Integrate[t^((m - 3)/2) Exp[-t (a^2 + b^2)] Exp[-t (c^2 n^2 + 2 b c n)],
    {t, 0, ∞}] // FullSimplify]

ConditionalExpression[(a^2 + (b + c n)^2)^((1 - m)/2) Gamma[1/2 (-1 + m)], m > 1]

Then we do the sum for a specific value of $m\ge2$:
With[{m = 2}, Sum[(a^2 + (b + c n)^2)^((1 - m)/2) Gamma[1/2 (-1 + m)], {n, -∞, ∞}]]

Sum doesn't converge.

With[{m = 3}, Sum[(a^2 + (b + c n)^2)^((1 - m)/2) Gamma[1/2 (-1 + m)], {n, -∞, ∞}]]

$\frac{\pi  \left(\left\lfloor \frac{2 \arg (a-i b)-2 \arg (c)+\pi }{4 \pi }\right\rfloor
   +\left\lfloor \frac{-2 \arg (a-i b)+2 \arg (c)+\pi }{4 \pi }\right\rfloor \right)}{a
   c}+\frac{\pi  \coth \left(\frac{\pi  a-i \pi  b}{c}\right)}{2 a c}+\frac{\pi  \coth
   \left(\frac{\pi  a+i \pi  b}{c}\right)}{2 a c}$
With[{m = 4}, Sum[(a^2 + (b + c n)^2)^((1 - m)/2) Gamma[1/2 (-1 + m)], {n, -∞, ∞}]]

(no closed form)

With[{m = 5}, Sum[(a^2 + (b + c n)^2)^((1 - m)/2) Gamma[1/2 (-1 + m)], {n, -∞, ∞}]]

$\frac{\pi  \left\lfloor \frac{2 \arg (a-i b)-2 \arg (c)+\pi }{4 \pi }\right\rfloor }{2
   a^3 c}+\frac{\pi  \left\lfloor \frac{-2 \arg (a-i b)+2 \arg (c)+\pi }{4 \pi
   }\right\rfloor }{2 a^3 c}+\frac{\pi  \coth \left(\frac{\pi  a-i \pi  b}{c}\right)}{4
   a^3 c}+\frac{\pi  \coth \left(\frac{\pi  a+i \pi  b}{c}\right)}{4 a^3 c}+\frac{\pi ^2
   \text{csch}^2\left(\frac{\pi  a-i \pi  b}{c}\right)}{4 a^2 c^2}+\frac{\pi ^2
   \text{csch}^2\left(\frac{\pi  a+i \pi  b}{c}\right)}{4 a^2 c^2}$
etc. It seems that this method gives closed-form solutions for odd $m\ge3$.


text:
Q: Trigger action values not updating in Database I am new to salesforce and trying to play around with triggers. I have tried the trailhead exercise for triggers to set shippingPostCode from BillingPostalCode. Below is my code
trigger AccountAddressTrigger on Account (before insert, before update) {

    if(Trigger.isInsert || Trigger.isUpdate){
        for (Account a : [SELECT Match_Billing_Address__c,BillingPostalCode,shippingPostalCode  FROM Account WHERE Id IN :Trigger.New]){
            if(a.Match_Billing_Address__c){
                a.shippingPostalCode = a.BillingPostalCode;
                System.debug('a.shippingPostalCode'+a.shippingPostalCode);
            }
        }
    }

}

It prints the shippingPostCode in the log whereas I couldn't see the same when I query the Account object, its still shows null. Not sure why it's not updating on the backend. Can you please help?

A: In before trigger you can modify the instance of records from Trigger.new without a dml, while to update records you got via SOQL you must perform a dml, no matter if they have the same Id: they are different instance.
In your scenario I think you don't need the SOQL, you could just loop over records in Trigger.new, check Match_Billing_Address__c then update shippingPostalCode.
trigger AccountAddressTrigger on Account (before insert, before update) {

    for (Account a : Trigger.new) {
        if(a.Match_Billing_Address__c){
            a.shippingPostalCode = a.BillingPostalCode;
            System.debug('a.shippingPostalCode'+a.shippingPostalCode);
        }
    }

}

Moreover in before insert you don't have the record Id, so the SOQL would return an empty list.
Anyway, in before update you can get the updatable instance from Trigger.newMap.


text:
Q: Android application: calc function does not work after changing to DrawerLayout I changed the layout in my app from RelativLayout to RelativLayout as a child of DrawerLayout. Everything works fine, except the everything inside onClick() in MainActivity.java. After pressing the button button1 the result of the calculation is NaN which was working before. It has to do something with the change of the layout. I don't have a clue what causes this issue.
Maybe someone can help me out?
GitHub: https://github.com/ephlox/GradesCalculator2
MainActivity.java
package com.lob.gradescalculator;

import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import android.view.MenuInflater;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    DrawerLayout drawerLayoutgesamt;
    ActionBarDrawerToggle drawerToggle;

    int sum = 0;
    int ects = 0;
    float mark = 0;
    NumberFormat numberFormat = new DecimalFormat("0.00");
    Button button1;
    TextView textView1;
    EditText editText1;
    EditText editText2;
    EditText editText3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar1);
        setSupportActionBar(toolbar);

        drawerLayoutgesamt = (DrawerLayout) findViewById(R.id.drawerlayoutgesamt);
        drawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayoutgesamt, R.string.auf, R.string.zu);
        drawerLayoutgesamt.setDrawerListener(drawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        drawerToggle.syncState();

        button1 = (Button)findViewById(R.id.button1);
        textView1 = (TextView)findViewById(R.id.textView1);
        editText1 = (EditText)findViewById(R.id.editTextGDI);
        editText2 = (EditText)findViewById(R.id.editTextGDW);
        editText3 = (EditText)findViewById(R.id.editTextProgrammieren1);
        loadSavedPreferences();

        button1.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v){

                        ViewGroup group = (ViewGroup)findViewById(R.id.activity_main);
                        for (int i = 0, count = group.getChildCount(); i < count; ++i) {
                            View view = group.getChildAt(i);
                            if (view instanceof EditText) {
                                if(view.equals(editText1) && !(editText1.getText().toString().matches(""))){ //GDI
                                    System.out.println("edittext1");
                                    ects += 5;
                                    try{ sum += Integer.parseInt(editText1.getText().toString()) *5; } catch(NumberFormatException n){}
                                }
                                else if(view.equals(editText2)&& !(editText2.getText().toString().matches(""))){ //GDW
                                    System.out.println("edittext2");
                                    ects += 5;
                                    try{ sum += Integer.parseInt(editText2.getText().toString()) *5; } catch(NumberFormatException n){}
                                }
                                else if(view.equals(editText3)&& !(editText3.getText().toString().matches(""))){
                                    System.out.println("edittext3");
                                    ects += 7;
                                    try{ sum += Integer.parseInt(editText3.getText().toString()) *7; } catch(NumberFormatException n){}
                                }
                            }
                        }

                        mark = (float)sum / (float)ects;
                        textView1.setText(String.valueOf(numberFormat.format(mark)));
                        savePreferences("editText1", editText1.getText().toString());
                        savePreferences("editText2", editText2.getText().toString());
                        savePreferences("editText3", editText3.getText().toString());

                        sum = 0;
                        ects = 0;
                        mark = 0;
                    }
                }
        );
    }

    private void loadSavedPreferences() {
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        editText1.setText(sharedPreferences.getString("editText1", ""));
        editText2.setText(sharedPreferences.getString("editText2", ""));
        editText3.setText(sharedPreferences.getString("editText3", ""));
    }

    private void savePreferences(String key, String value) {
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        int id = item.getItemId();

        if(id == R.id.action_settings){
           return true;
        }
        if(drawerToggle.onOptionsItemSelected(item)){
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(new Configuration());
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.lob.gradescalculator.MainActivity">

    <android.support.v4.widget.DrawerLayout
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:id="@+id/drawerlayoutgesamt"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

        <!--  Activity Layout für Hauptbereich -->
        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/activitylayout"
            >

            <android.support.v7.widget.Toolbar
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/toolbar1"
                android:background="#c6d9ff"
                android:fitsSystemWindows="true"
                >
            </android.support.v7.widget.Toolbar>

            <!-- TextViews -->
            <TextView
                android:id="@+id/WIF_Title"
                android:text="Wirtschaftsinformatik B.Sc."
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="25dp"
                android:layout_x="23dp"
                android:layout_y="200dp"
                android:layout_below="@+id/toolbar1"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"/>

            <TextView
                android:id="@+id/textViewGDW"
                android:text="Grundlagen der Wirtschaftsinformatik"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="@style/TextAppearance.AppCompat.Body1"
                android:textStyle="normal|bold"
                android:textAlignment="textStart"
                android:layout_below="@+id/textViewGDI"
                android:layout_marginTop="30dp"
                android:layout_x="45dp"
                android:layout_y="344dp"
                android:layout_alignStart="@+id/textViewGDI" />
            <TextView
                android:id="@+id/TextViewProgrammieren1"
                android:text="Programmieren 1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="@style/TextAppearance.AppCompat.Body1"
                android:textStyle="normal|bold"
                android:textAlignment="textStart"
                android:layout_below="@+id/textViewGDW"
                android:layout_marginTop="32dp"
                android:layout_x="113dp"
                android:layout_y="238dp"
                android:layout_alignStart="@+id/textViewGDW" />

            <!-- EditTexts -->

            <!-- Buttons -->

            <EditText
                android:id="@+id/editTextGDI"
                android:layout_width="50dp"
                android:layout_height="wrap_content"
                android:layout_below="@+id/WIF_Title"
                android:layout_alignParentEnd="true"
                android:layout_marginTop="10dp"
                android:layout_marginEnd="10dp"
                android:inputType="number"
                android:textColorHint="@drawable/selector"
                android:background="@drawable/roundedborders"
                android:digits="12345"
                android:maxLength="1"

                />

            <TextView
                android:id="@+id/textViewGDI"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:text="Grundlagen der Informatik"
                android:textAppearance="@style/TextAppearance.AppCompat.Body1"
                android:textStyle="normal|bold"
                android:textAlignment="center"
                android:layout_x="125dp"
                android:layout_y="184dp"
                android:layout_below="@+id/WIF_Title"
                android:layout_alignParentStart="true"
                android:layout_marginStart="3dp"
                android:layout_marginTop="15dp"/>

            <EditText
                android:id="@+id/editTextGDW"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:textColorHint="@drawable/selector"
                android:background="@drawable/roundedborders"
                android:ems="10"
                android:layout_x="69dp"
                android:layout_y="91dp"
                android:layout_alignBaseline="@+id/textViewGDW"
                android:layout_alignBottom="@+id/textViewGDW"
                android:layout_alignStart="@+id/editTextGDI"
                android:layout_alignEnd="@+id/editTextGDI" />

            <EditText
                android:id="@+id/editTextProgrammieren1"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:textColorHint="@drawable/selector"
                android:background="@drawable/roundedborders"
                android:ems="10"
                android:layout_x="78dp"
                android:layout_y="264dp"
                android:layout_width="50dp"
                android:layout_alignBaseline="@+id/TextViewProgrammieren1"
                android:layout_alignBottom="@+id/TextViewProgrammieren1"
                android:layout_alignStart="@+id/editTextGDW"
                android:layout_alignEnd="@+id/editTextGDW" />

            <TextView
                android:id="@+id/textView1"
                android:text="..."
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="71dp"
                android:layout_x="23dp"
                android:layout_y="200dp"
                android:layout_above="@+id/button1"
                android:layout_centerHorizontal="true" />

            <Button
                android:id="@+id/button1"
                android:text="Berechne"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="75dp"
                android:layout_x="128dp"
                android:layout_y="442dp"
                android:layout_alignParentBottom="true"
                android:layout_alignEnd="@+id/textViewGDW" />

        </RelativeLayout>

        <!-- Drawerlayout für links -->
        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/drayerlayoutsingle"
            android:layout_gravity="start"
            android:background="#fff">

        </RelativeLayout>

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

</RelativeLayout>

A: Solved it. I had to change ViewGroup group = (ViewGroup)findViewById(R.id.activity_main); to ViewGroup group = (ViewGroup)findViewById(R.id.activitylayout);.


text:
Q: Data mining, curse of dimensionality Let's say I have a dataset represented as a matrix X, of dimensions n x m, with m high. I would like to quickly reduce the dimension m such that the objects in each row in X preserve distances to each other. One way to accomplish this would be to:
create a mapping matrix A by initializing it with all 0's and then randomly choosing 1/6 of its values to be +1 and 1/6 of its values to be -1, and then multiply X by A.
Am I right or wrong?

A: If you are preserving the distances, then you are also preserving the curse of dimensionality. The distances will still all be too similar to be useful...


text:
Q: Turn on/off NEST using REST API I am looking into options to make rest client to turn on/off nest thermostat from the using web service.
I found API to read the device info, but didn't get API to change settings or turn on and off the device.
Is there any REST/SOAP Api to turn on and off NEST Devices?

A: There is a REST api for the NEST. The documentation can be seen here
For a thermostat you might not be able to turn it off directly, however setting temperature low enough should emulate off. For example by setting:
{ target_temperature_c : 1.0 }

A: can you format your payload and the response you're getting in the text so its easier to see?
You should PUT to:
https://developer-api.nest.com/devices/thermostats/<thermostatID>?auth=<token>
and your payload should be:
{"target_temperature_f":78}

Or if you want to turn the system off your payload should be:
{"hvac_mode":"off"}


text:
Q: Dynamic bash associative array keys I've been wrestling with this problem for a long time and can't seem to find a working solution.
Suppose I have declared two associative arrays.
declare -A FOO_ARRAY=(
  [a]="first"
  [b]="second"
  [c]="third"
)

declare -A BAR_ARRAY=(
  [a]="first"
  [b]="second"
  [c]="third"
)

I can get a list of keys like so:
$ echo ${!FOO_ARRAY[@]}
c b a
$ echo ${!BAR_ARRAY[@]}
c b a

I can also dynamically deference a key from the array by doing something like this:
for KEY in FOO BAR
do
  temp="${KEY}_ARRAY[a]"
  echo ${!temp}
done

However, if you notice that the operator for dynamically referencing variables is also the same to get the list of keys from an associative array, how could I make something like this possible in order to dynamically list the keys in an associative array?
A naive example like this results in an invalid variable name error.
$ export NAME=foo
$ export temp="\!${NAME^^}_ARRAY[@]"
$ echo ${!temp}
bash: \!FOO_ARRAY[@]: invalid variable name

What I'm searching for is a way to dynamically return the list of keys from an associative array as if the above code sample returned:
c b a

A: You can use a nameref:
declare -rgA FOO_ARRAY=(
  [a]="first"
  [b]="second"
  [c]="third"
)

name="foo"
declare -n array="${name^^}_ARRAY"
echo "The keys are: " "${!array[@]}"

A: Use declare -n. From help declare:
-n  make NAME a reference to the variable named by its value

Example:
declare -A foo_array=(
  [a]="first"
  [b]="second"
  [c]="third"
)
declare -n temp="foo_array"
echo "${!temp[@]}"  # -> a b c

For more details, see info bash under the "Bash Builtins" section.

A: This Will Work
NAME=foo
temp="${NAME^^}_ARRAY[@]"
echo ${!temp}

Explanation: here temp will store " FOO_ARRAY[@] " as string only and when echo it in reference way it does print the value.
Example
declare -rgA FOO_ARRAY=(
  [a]="first"
  [b]="second"
  [c]="third"
)

declare -rgA BAR_ARRAY=(
  [a]="first"
  [b]="second"
  [c]="third"
)

echo ${!FOO_ARRAY[@]}
echo ${!BAR_ARRAY[@]}

for KEY in FOO BAR
do
  temp="${KEY}_ARRAY[a]"
  echo ${!temp}
done

NAME=foo
temp="${NAME^^}_ARRAY[@]"
echo ${!temp}

Run:
a b c
a b c
first
first
first second third


text:
Q: munmap_chunk() error in when i free an allocated memory i have a char* path that is global, later i call a function that allocates memory and returns it, and path points to it, when i free it i get this error
the only way is to not free the pointer
void free_memory() {

    if(path!=NULL)
        free(path);//problem

}

char* ExtractPath(char*str)
{
    char*temp=(char*)malloc(sizeof(char)*(strlen(str))+1);
    bzero(temp,strlen(temp));
    char ch ='/';

    if( checkUrl(str)==1) {
        if(strncasecmp(str,"http://",7)==0)
            str+=7;

        if(strstr(str,"/")!=NULL)
        {
            strcpy(temp,str);
            temp=strchr(temp,ch);
            strtok(temp,"\t");
        }
        else
            strcpy(temp,"/");
    }
    return temp;
}
path=ExtractPath(Users_input);//here the pointer points to the allocated memory that returned from the function the char*path is a global value

A: As I see, the problem is with
 bzero(temp,strlen(temp));

The content of temp is indeterminate, passing that to strlen() would invoke undefined behaviour.
Quoting C11, chapter §7.22.3.4

The malloc function allocates space for an object whose size is specified by size and
  whose value is indeterminate.

That said, regarding the error for free() part, you have to supply the exact pointer which was returned by malloc() or family.
Quoting chapter §7.22.3.3

[...] Otherwise, if
  the argument does not match a pointer earlier returned by a memory management
  function, or if the space has been deallocated by a call to free or realloc, the
  behavior is undefined.

In your code, you actually modify the original pointer stored in temp by saying
        temp=strchr(temp,ch);
        strtok(temp,"\t");

and return the "modified" temp.
Passing that temp to free() will lead to undefined behaviour, once again.

A: Since ExtractPath does not return the value returned from malloc, there is no way to free the returned string. It is only legal to pass to free precisely the value you got back from malloc.
Once you do temp=strchr(temp,ch);, the original value returned from malloc is lost. Calling free on the value returned from strchr is not legal.
Here's one way to fix it:
char* ExtractPath(char*str)
{
    char* temp=(char*)malloc(sizeof(char)*(strlen(str))+1);
    char* orig = temp; /* save the value we got back from malloc */
    char* ret;
    char ch ='/';

    if( checkUrl(str)==1) {
        if(strncasecmp(str,"http://",7)==0)
            str+=7;

        if(strstr(str,"/")!=NULL)
        {
            strcpy(temp,str);
            temp=strchr(temp,ch);
            strtok(temp,"\t");
        }
        else
            strcpy(temp,"/");
    }
    ret = malloc (strlen(temp) + 1);
    strcpy(ret, temp); /* make a new copy to return */
    free(orig); /* pass what malloc returned to free */
    return ret; /* caller can free this since we got it back from malloc */
}


text:
Q: Eclipse JDT ListRewrite inserts new node at wrong places I'm trying to add an annotation to some selected fields using Eclipse JDT infrastructure. However, this is not run as a plugin. I added all the required dependencies to a separate project so this can be run in batch mode. However I found out that, the ListRewrite is not inserting my annotation at the right place. I have given the code below. I initially get all the field declarations in a map using a visitor and then add them one by one using the code below.
FieldDeclaration fld = lVrblDet.listStringVarMap.get(propName);
final MarkerAnnotation autoWiredAnnotate = ast.newMarkerAnnotation();                           autoWiredAnnotate.setTypeName(ast.newName("MyAnnot"));
lrw = rewriter.getListRewrite(fld, FieldDeclaration.MODIFIERS2_PROPERTY);
lrw.insertLast(autoWiredAnnotate, null);
Document document = new Document(cu.toString());
try {
    TextEdit edits = rewriter.rewriteAST(document, null);
    edits.apply(document);
} catch (MalformedTreeException | IllegalArgumentException | BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
}

However the expected output is sometimes offset by 1 character.The input and output classes have been given below.
Input Class:
@SuppressWarnings("unchecked")
public class SampleClassA {

    public SampleClassB classB;

    public SampleClassB getClassB() {
        return classB;
    }

    public void setClassB(SampleClassB classB) {
        this.classB = classB;
    }

    @Deprecated
    public void printNameFromSmapleClassB() {
        System.out.println(this.classB.name);
    }

}

Output Class:
@SuppressWarnings("unchecked") public class SampleClassA {
  p @MyAnnot
ublic SampleClassB classB;
  public SampleClassB getClassB(){
    return classB;
  }
  public void setClassB(  SampleClassB classB){
    this.classB=classB;
  }
  @Deprecated public void printNameFromSmapleClassB(){
    System.out.println(this.classB.name);
  }
}

As you can see in the code above, the Annotation messed with the modifier. I have tried multiple combinations of insertFirst,insertLast.Examples on the net are incomplete. Can somebody point me the mistake/the right resource ?

A: I just couldn't get it to work with ListRewrite. I don't know what I was doing wrong. So I wrote a visitor to store all the FieldDeclarations in a map.
@Override
public boolean visit(FieldDeclaration node) {
    for (Object obj : node.fragments()) {
        listStringVarMap.put(((VariableDeclarationFragment) obj).getName().toString(), node);
    }
    return false;
}

I looped through the map and inserted the annotation nodes as a modifiers, for the declarations that met my criteria. Please do remember to turn on recormodifications for the compilation unit you are modifying.
CompilationUnit cu = jFileAst.getEquivCompilUnit();
cu.recordModifications();
FieldDeclaration fldDecl = lVrblDet.listStringVarMap.get(propName);
importVo = (JavaAnnotImportVo) javaAstNodeCreator
            .createASTNode(SpringAnnotationEnum.AutowireAnnotation, ast);
cu.imports().add(importVo.getImpDecl());
fldDecl.modifiers().add(0, importVo.getAnnotNode());

Finally write to file on disk/save back. Formatting(optional) before saving is a good idea, because the node insertions mess up with the code formatting.


text:
Q: Specify system property on launch of application I need to specify a System Property when launching my android application from Android Studio / gradle.
I cant figure out ho to do that.
Background is that my app needs to know the URL of the server it talks to. The default needs to be overridden during testing and development. I have code in the app that merges system properties on top of application properties read from a property file under assets folder. Now all I need is the ability to launch the app specifying a system property somehow.
TIA for your help.

A: You can always keep the URL in your SharedPreference. Whenever you are using it in development/testing you can take input from user and change it accordingly and save it again in SharedPreference. So your app will always know which server it's communicating to. If the user doesn't give any input then it'll take your default from asset folder else from SharedPreference.

A: You can accomplish this via build variants.
Add something like the following to your build.gradle:
android {
   //...

   productFlavors {
        local {
            applicationId "com.example.myapp.local"
            versionName "1.0-local"
        }
        staging {
            applicationId "com.example.myapp.staging"
            versionName "1.0-staging"
        }
        prod {
            applicationId "com.example.myapp.prod"
            versionName "1.0-prod"
        }
    }

and then create the following resource files
app/src
     |
     + local/res/values/strings.xml
     |
     + staging/res/values/strings.xml
     |
     + prod/res/values/strings.xml

Where each strings.xml has the appropriate endpoint:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="api_endpoint">http://10.0.2.2:3000</string>
</resources>

Then, before running the app, select the build variant you want to run from the build variants tool window (e.g. localDebug or stagingRelease), and it'll have the intended string value that you can access as a resource.


text:
Q: Scheduling nodejs script as SQL Server Agent job Is there is a way to schedule a nodejs script to run through the SQL Server Agent job system? Currently I have a Powershell script that executes my .js file. Running the .ps1 file works fine manually and in Windows Task Scheduler. When I try to run the file through the agent, I get the following error:

The job script encountered the following errors. These errors did not stop the script:  A job step received an error at line 1 in a PowerShell script. The corresponding line is 'Powershell -file "C:\Program Files\nodejs\scripts\script.ps1"'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'node : The term 'node' is not recognized as the name of a cmdlet function script file or operable program.

The reason I want to add it to the SQL Server Agent is for consistency with other jobs I am running on the server. It would be ideal to have them all in a single place. If it isn't possible to get SQL to recognize the "node" command, then I can just use Task Scheduler.


text:
Q: Why setTimeout() function runs only once? I am making a javascript bookmarklet that resizes all images, periodically.
javascript: function x(){
    for(i=0;i<=document.getElementsByTagName('img').length;i++)
        document.getElementsByTagName('img')[i].width+=1;
};
t = window.setTimeout("x()",100);
void(0);

But it runs only once. What is the problem here??

A: Are you looking for setInterval() instead of setTimeout() by any chance?
t = window.setInterval("x()",100);

A: Here is the same code properly indented for clarity
function x() {
    for(i=0;i<=document.getElementsByTagName('img').length;++)
        document.getElementsByTagName('img')[i].width+=1;
};
t = window.setTimeout("x()",100);
void(0);

window.setTimout() executes the passed code only once because it is meant to. If you want to execute code more often, use window.setInterval().

A: Shouldn't it be i++ at the end of your for loop?

A: Also there is a syntax error.
for(i=0;i<=document.getElementsByTagName('img').length;i++)

A: You need to put the...
t = window.setTimeout("x()",100);

inside the function x() brackets {  } and it works with SetTimeout()
function x() {
    for(i=0;i<=document.getElementsByTagName('img').length;i++)
        document.getElementsByTagName('img')[i].width+=1;

t = window.setTimeout("x()",100);
};

    x();

void(0);

You can only call x() after all the images have been loaded on the page or there is an error.

A: It might be window.setTimeOut("x",100)
Edit : correct the answer to this window.setTimeout(x,100).
PS: thats what happens if you simply work with a IDEs.


text:
Q: how is the code for displaying dropdown items in button event? hi all i have implemented code for displaying drapdown items when click on the custom button
but it is not working ios5 give the solution for displaying dropdown items it is too urgent for me in iphone.
 units = [[NSMutableArray alloc] initWithObjects:@"Metric(metres)",@"Imperial(feets)",nil];
    dropDownView = [[DropDownView alloc] initWithArrayData:units cellHeight:30 heightTableView:60 paddingTop:-8 paddingLeft:-5 paddingRight:-10 refView:dropdownButton animation:BLENDIN openAnimationDuration:0 closeAnimationDuration:0];
    dropDownView.delegate = self;
    [dropdownButton setTitle:@"Metric(metres)" forState:UIControlStateNormal];
    [self.view addSubview:dropDownView.view];
}
-(void)dropDownCellSelected:(NSInteger)returnIndex{

    [dropdownButton setTitle:[units objectAtIndex:returnIndex] forState:UIControlStateNormal];
    //[self calculatebuttonaction];
}

#pragma mark -
#pragma mark Class methods

-(IBAction)DropdownButtonClick{
    [dropDownView openAnimation];

}

A: What about simply to create another UITableView (or UITableViewController) and use it with push/pop functions to display the items of dropdown list with expanding of nothing?


text:
Q: How to work with repetitive bootstrap css code I am frequently using this code to center some content

  ..

  ..

Is there a way to reuse / inherit this code, so that I can use it like below, where my-centered-container-vertical just adds flex-column to my-centered-container (no code duplication)?

</div

</div

A: You shouldn't write in CSS anyway. Use SASS or LESS instead. See other answers for how to integrate bootstrap into your project. Also see bootstrap#importing. As for your specific question, you can re-use like this.
.my-center {
    @extend .d-flex;
    @extend .align-items-center;
    @extend .justify-content-center ;
    @extend .h-100;
}


text:
Q: Python inserting in an empty list at specific index doesn't work I have a list of object, each object contains a unique ID. The current list is like so:
[{"id": 3}, {"id": 5}, {"id": 8}]

I want to change the indexes a bit - instead of the dictionary with id = 3 to be on index 0, I want the dictionary with id = 3 to be on index 3.
I have tried:
list = []
for item in items:
    list[item["id"]] = item

but that gives me indexing error. Then I tried to do the following:
list = []
for item in items:
    list.insert(item["id"], item)

which just acts like a regular append (does not insert at specified index).
I have a last ditch attempt to do this on the front end when I am getting the response from the API but that defeats the whole purpose of reducing the amount of looping I do on the client side. The reason being is that the server can knock out these loops in like 50 milliseconds and on the client side it takes up to 300 milliseconds since it runs in the browser.

A: There is no problem in your code it all happens because your list has zero element
items = [{"id": 3}, {"id": 5}, {"id": 8}]
list_ = []
for item in items:
    while item['id'] > len(list_):
        list.append(None)
    list_.insert(item["id"], item)
print(list_)

OUTPUT:
You can see here your elements are inserted inside the list.
[None, None, None, {'id': 3}, None, {'id': 5}, None, None, {'id': 8}, None]

The above code works perfectly if the dictionary inside the list is in increasing order, But if the dictionary is in random order then first you need to first change the list to increasing order.

items = [{"id": 3}, {"id": 5}, {"id": 8},{'id':2}]
items = (sorted(items,key=lambda e:e['id'])) # sort the list
list_ = []
for item in items:
    while item['id'] > len(list_):
        list.append(None)
    list_.append(item)
print(list)

INPUT/OUTPUT
IN:items = [{"id": 3}, {"id": 5}, {"id": 8},{'id':2}]

OUTPUT FROM FIRST ANSWER:[None, None, {'id': 2}, None, {'id': 3}, None, {'id': 5}, None, None, {'id': 8}]

OUTPUT FROM SECOND ANSWER:[None, None, {'id': 2}, {'id': 3}, None, {'id': 5}, None, None, {'id': 8}]

A: I think the general solution for this will be
a= [{"id": 3}, {"id": 5}, {"id": 8}]
l = [None for _ in range(max(a,key=lambda x: x["id"])["id"]+1)]
for item in a:
    l[item["id"]]= item
print(l)

Also insert and item assignment is creating error because it expects that index to be exist beforehand so in that case you need to initialize your list with empty labels

A: You can't insert into an empty list at index 3. The first element you add to a list will always be at index 0. More general, you can't insert at an index that's higher than the list is long. If you want a quick way to look up items with a specific index, use another dict instead of a list as the container:
>>> lst = [{"id": 3}, {"id": 5}, {"id": 8}]
>>> d = {x["id"]: x for x in lst}
>>> d
{3: {'id': 3}, 5: {'id': 5}, 8: {'id': 8}}
>>> d[3]
{'id': 3}

This way, each element can be looked up in O(1) using its ID as the index. And this will also work if the IDs are very large numbers (when its impractical to create a mostly empty list with that many indices) or even non-numeric, e.g. strings.

A: You can do below steps;
x = [{"id": 3}, {"id": 5}, {"id": 8}]

x.insert(3, x[0])
del x[0]

A: Create an empty list with needed indexes first like
data = [{"id": 3}, {"id": 5}, {"id": 8}]
mod_list = [None]*max(x.get("id") for x in data)

Now fill the indexes with needed data
[mod_list.insert(x.get("id"),x) for x in data]

You get a list like this
[None, None, None, {'id': 3}, None, {'id': 5}, None, None, {'id': 8}, None, None]

The None indexes can be ignored in processing.


text:
Q: Puppet: conditional file source I would like to use a different squid.conf file depending on a condition. Something like:
    file { '/etc/squid/squid.conf':
    ensure => file,
    if condition = true then
        source => 'puppet:///modules/1/squid.conf_1',
    else
        source => 'puppet:///modules/1/squid.conf_2',
    fi
    }

Is there a way to do this?

A: You need a selector, which will let you have a conditional inside the resource - or set a variable up outside of it.
Here's the selector:
file { '/etc/squid/squid.conf':
  ensure => file,
  source => $fact ? {
    "foo"   => 'puppet:///modules/1/squid.conf_1',
    "bar"   => 'puppet:///modules/1/squid.conf_2',
    default => 'puppet:///modules/1/squid.conf_default',
  },
}

Or set a variable and use that instead:
if $fact == "foo" {
  $squidconf = 'puppet:///modules/1/squid.conf_1'
} else {
  $squidconf = 'puppet:///modules/1/squid.conf_2'
}

file { '/etc/squid/squid.conf':
  ensure => file,
  source => $squidconf,
}

There are other variations of course, have a look at the language guide linked above and the Learning Puppet tutorial section on variables.


text:
Q: Compare instances of Option[T] avoiding None == None Yesterday I was suddenly enlighted and understood how and why people use 'map' method with Option to compare values. Yes, I'm a bit slow, sorry :)
I revised these very nice links and came to the question I would like to ask.
http://twitter.github.com/effectivescala
http://blog.tmorris.net/posts/scalaoption-cheat-sheet
In my Lift webapp I have some Option[User] and Option[Server] variables. I'm trying to find out if this User is admin of this Server by the following check
if(user.map(_.id) == server.map(_.adminId))

But I noticed that in case of 'user' is None and 'server' is also None this check succeeds which is not good for me (if any of them is None I'd like this check to fail). I could add user.isDefined condition but I feel there is more correct way to do it. Could you tell how to accomplish it in Scala way?

A: you can use a for comprehension
def isAdmin(server: Option[Server])(user: Option[User]): Boolean = (for {
    s <- server
    u <- user
  } yield (u.id == s.adminId)
).getOrElse(false)

The comprehension results in a Option[Boolean] from which you get the value or false if there's no value (the case where any of the options is None, as you requested)
Why curried?
I made the method curried, so you can define you function for a specific server, and then reuse that to check many users
def isMyServerAdmin = isAdmin(Some(myServer)) _

isMyServerAdmin(Some(user1)) = true
isMyServerAdmin(Some(user2)) = false
isMyServerAdmin(None) = false

A: You could do it with pattern matching (which in this case is probably the clearest way):
(user, server) match {
  case (Some(user), Some(server)) if user.id == server.adminId =>
    // both ids are matching, handle this case here
  case _ =>
    // no match, handle this case here
}

You could also try as a one-liner but here I don't advise it as it's pretty obfuscated:
if ( user.flatMap{ user => server.map(_.adminId == user.id) }.getOrElse( false ) ) {
  // both ids are matching, handle this case here
}
else {
  // no match, handle this case here
}

Finally, if you only have to handle the case where the ids match (and would just do nothing if there is not), using a for comprehension is not too bad of an option (no pun intended):
for ( user <- user; server <- server if user.id == server.adminId ) {
  // both ids are matching, handle this case here
}

A: I got used to the combination of exists / contains for this purpose.
When comparing two options of the same type:
o1.exists(o2.contains)

In your case this can be applied using map:
user.map(_.id).exists(server.map(_.adminId).contains)

A: We can make use of Option#zip to work with an Option of the tuple user/server:
user zip server exists { case (user, server) => user.id == server.adminId }

where the behavior of Option#zip is:
Some(User(id = "hello")) zip Some(Server(adminId = "world"))
// Some((User("hello"), Server("world")))
Some(User(id = "hello")) zip None        // None
None zip Some(Server(adminId = "world")) // None
None zip None                            // None

and where Option#exists applies a predicate on the optional tuple produced by zip.


text:
Q: SharePoint and use of AD's wWWHomePage attribute While looking at the wWWHomePage attribute in Active Directory, a web search found some questions on lousier Q&A sites, that indicate that SharePoint will populate the wWWHomePage attribute on a user in AD with their SharePoint site.
The specific question I found was how to turn this off?  There was no answer there, so I would be curious to know how to turn it off.
But more importantly, what affect would there be to SharePoint if we turned this off?
We actually are planning on syncing in other data from another source into that attribute.  How would that affect SharePoint, if at all?
Should the answer be that it matters, I will later ask a question if the attribute has any funny syntax requirements as I was informed that in the past the people I am working with have had problems with some values in the field, even though the schema def seems to say it is just a 2K long single valued Unicode string.

A: While not entirely the complete answer, it is useful to know that while wWWHomePage is a single valued attribute, extra values are meant to overflow into url which is multivalued.
(We have an Identity Management project where single valued phone info in the source directory and LDAP accessible directory are mapped to the primary single valued phone attribute, and the rest overflow into the otherXXXX attributes.  (Thus there is pager and the overflow attribute otherPager and so on for the various phone attributes).)
So we will overflow multiple values from our source directory into url and leave one value in wWWHomePage which should obviate any Sharepoint potential issues.


text:
Q: EOFException initializing an ObjectInputStream I am new and I only know a little of english. Well my problem is that I have to do a Multithreading server and a Client class to communicate a lot of clients to one server. I am saving my clients in a hashmap and after adding to the hashmap I am using a method to write into a file (HashMap is serializable and I am using singleton pattern to make the hashmap global). The problem is when I try to read from my file, then Java throws me an EOFException and I don't know why.
This is my code:
import java.io.*;
import java.util.*;

public class MapaClients implements java.io.Serializable  {

private static MapaClients mapa= new MapaClients();

private Map<String,Client> clients= new HashMap<String,Client>();

private MapaClients(){}

public static MapaClients getInstance(){
    return mapa;
}

public void afegirMapa(String correu, Client client){
    clients.put(correu, client);
}

public Client existeix(String correu){
    if(clients.containsKey(correu)){
        return(clients.get(correu));
    }else{
        return(null);
    }
}

public void serializableGuardar(){
    try {
         FileOutputStream fileOut =new FileOutputStream("client.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(mapa);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in client.ser");
      } catch (IOException i) {
         i.printStackTrace();
      }
}

public void desserializableCarregar(){
    ObjectInputStream in;
      try {
         FileInputStream fileIn = new FileInputStream("client.ser");
         in = new ObjectInputStream(fileIn);
         boolean check=true;
         while (check) {
            try{
                mapa = (MapaClients) in.readObject();
            } catch(EOFException ex){
                in.close();
                check=false;
            }
         }
         in.close();
         fileIn.close();
      } catch (IOException i) {
         i.printStackTrace();
      } catch (ClassNotFoundException c) {
         c.printStackTrace();
      }
}

public void actualizar(Client client){
    clients.replace(client.getCorreu(), client);
}
}

The problem is here:
in = new ObjectInputStream(fileIn);

This is the exception:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Proves.MapaClients.desserializableCarregar(MapaClients.java:46)

I hope u can help me and sorry for my english :)

A: You are trying to initialize the ObjectInputStream from an empty file.


text:
Q: How can I solve the following issue in python AttributeError: 'list' object has no attribute 'to_dict'? I am facing issue in the below code in pandas python. When I run the following cell, I did not face any issue but when I run the next cell The error shows up:
def build_anonymized_dataset(df, partitions, feature_columns, sensitive_column, max_partitions=None):
    aggregations = {}
    for column in feature_columns:
        if column in categorical:
            aggregations[column] = agg_categorical_column
        else:
            aggregations[column] = agg_numerical_column
    rows = []
    for i, partition in enumerate(partitions):
        if i % 100 == 1:
            print("Finished {} partitions...".format(i))
        if max_partitions is not None and i > max_partitions:
            break
        grouped_columns = df.loc[partition].agg(aggregations, squeeze=False)
        sensitive_counts = df.loc[partition].groupby(sensitive_column).agg({sensitive_column : 'count'})
        values = grouped_columns.iloc[0].to_dict().items()
        for sensitive_value, count in sensitive_counts[sensitive_column].items():
            if count == 0:
                continue
            values.update({
                sensitive_column : sensitive_value,
                'count' : count,

            })
            rows.append(values.copy())
    return pd.DataFrame(rows)

But when I run the following cell, I am facing error related to the previous cell. I do not understand what is this error and how can solve it.
dfn = build_anonymized_dataset(df, finished_partitions, feature_columns, sensitive_column)

the following  error appear:
  14 grouped_columns = df.loc[partition].agg(aggregations, squeeze=False)
     15 sensitive_counts = df.loc[partition].groupby(sensitive_column).agg({sensitive_column : 'count'})
---> 16 values = grouped_columns.iloc[0].to_dict().items()
     17 for sensitive_value, count in sensitive_counts[sensitive_column].items():
     18     if count == 0:

AttributeError: 'list' object has no attribute 'to_dict'


text:
Q: Why is the UV absorption band for molecules not a sudden transition? From what I have read, when a molecule in solution or gas is excited, it does so from ground state, but may gain the energy for vibrational transitions as well. This would lead me to expect that there would be a sudden change in absorption with a long band of absorption (with some variation there in). However, what I find is that the transition is not sudden, but sloped. I am particularly interested in the slope of nitrate in water. Why is this? Are there molecule-molecule interactions? Are the molecules starting at an excited state?

A: When a photon interacts with an atom (or molecule in this case) three things can happen:

*

*elastic scattering, when the photon keeps its energy and phase, and changes angle

*inelastic scattering, when the photon gives part of its energy to the atomic or molecular system, and changes angle

*absorption, when the photon gives all of its energy to the atomic or molecular system
In the case of photo electricity, or at higher energies, it is number 3 that happens, but number 2 can happen too.
Now 1. usually happens on the surface (like in the case of a mirror).
In your case, for UV, at higher energies, that happens deeper inside the material. In this case, usually 2. and 3. can happen, and some molecules get excited.
In this case, the photon's energy gets partially (2.) or fully (3.) transformed into the vibrational energies of the molecules.
Now you are asking, why not all molecules get excited at the same level, that is, all of them would need to move from their ground state to the same excited energy level. That is what you call a sudden transition. But instead, you find a sloped transition.
The reason for that is:

*

*some photons transfer their energy only partially (inelastic scattering), some fully (absorption) to the molecule's vibrational energy. In the case of partial excitation (inelastic scattering), the photon's energy only partially gets transformed into the molecule's vibrational energy. Now each molecule will get a different level of that partial energy. That is why all molecules will move up to a different energy level.

*In the case of absorption, you would expect that all molecules get excited to the same energy level, considering that all photons are the same energy level. But that would mean too, that all molecules were at the same ground level, and there is no connection between the molecules' vibrational energyies (temperature) in the lattice. But in reality, the molecules have different ground levels, and as they absorb the photons' energies, the vibration energies tend to equalize through the lattice, in a way that molecules with higher energy levels will transfer part of their energy level to other molecules' vibrational energies. That is how temperature will try to equalize out through the lattice.

*There are not only single photon absorptions, but multi (two) photon absorptions too. In this case, one single molecule can absorb more then one photon. In this case the molecule will have a different energy level too.

*There is something called multi molecule (two) excitation, when a photon excites more then one molecule. In this case the molecules will have different energy levels too.
It is important to understand too, that you are asking whether molecules are starting at excited states. In the case of UV higher energies, we are talking about vibrational energies of the molecules, that is their temperature. Obviously, not all molecules will have the same vibrational energy levels in the lattice.
You are asking too, whether there are molecule-molecule interactions. Yes, since we are talking about vibrational energies, and temperature, these energy levels naturally try to equalize out through the lattice, that is, molecules with higher energy levels will transfer some of their energies to other neighboring molecules that have lower energy levels until they will equal out.


text:
Q: label with url in Vue.js Here's my code:
<v-checkbox
    :label="I agree with the Privacy Policy"
    v-model="agree2"
></v-checkbox>

and I want to have an action when I click Privacy Policy. I know I can put an url there, but I would rather show model with Vue. How can I do that?

A: Use the slot with name 'label' and put into whatever any you wont:
<v-checkbox ...>

I agree with the <myLinkComponent>...</...>

</v-checkbox>

You can see that from documentation: https://vuetifyjs.com/en/components/checkboxes/#label-slot


text:
Q: querying all sensor values for a machine I have a simulator with 5 custom measurements sent every 5 minutes. I would like to get the results of these custom measurements based on the name of the simulator, can you please assist me on how to achieve that?

A: You cannot directly query measurements by the device name (only with the device ID) so you have to do two queries:
Step 1:
Query for the device based on the name to get the ID:
/inventory/managedObjects?fragmentType=c8y_IsDevice&text={device_name}

Step 2:
Query for measurements based on source ID
/measurement/measurements?source={device ID}&dateFrom={...}&dateTo={...}&revert=true&pageSize=5

I added a couple more query parameters. I guess dateFrom/dateTo is clear. The revert parameter will give you the latest measurements first and the pageSize limits the results to 5. So the query should give you the latest 5 measurements for the device which should result in one for each of you 5 measurements


text:
Q: Compile error with boost asio.hpp When I include boost/asio.hpp to my source file and compile, I get this error:
In file included from /usr/include/boost/type_traits/is_complex.hpp:12,
             from /usr/include/boost/type_traits.hpp:81,
             from /usr/include/boost/asio/detail/wrapped_handler.hpp:21,
             from /usr/include/boost/asio/io_service.hpp:39,
             from /usr/include/boost/asio/basic_io_object.hpp:20,
             from /usr/include/boost/asio/basic_socket.hpp:24,
             from /usr/include/boost/asio/basic_datagram_socket.hpp:25,
             from /usr/include/boost/asio.hpp:20,
             from Source.cpp:166:
/usr/local/lib/gcc/x86_64-suse-linux/4.3.2/include/c++/complex: In function '_Tp std::__complex_abs(const std::complex<T>&)':
/usr/local/lib/gcc/x86_64-suse-linux/4.3.2/include/c++/complex:558: error: expected unqualified-id before '(' token

As can be seen, I'm compiling under Suse Linux 2.6.31.14-0.8 with gcc 4.3.2. I tried

*

*Line 558 in complex has "... = std::max(abs(__x), abs(__y));". Hence I tried adding #undef max and #undef abs to see if it will help. It did not help

*I tried conditional inclusion of BOOST_ALL_NO_LIB and it did not help.

Any pointers to fix this issue is appreciated.
Here is the complete function in complex which is giving the error:
  // 26.2.7/3 abs(__z):  Returns the magnitude of __z.

template<typename _Tp>
    inline _Tp
    __complex_abs(const complex<_Tp>& __z)
    {
      _Tp __x = __z.real();
      _Tp __y = __z.imag();
      const _Tp __s = std::max(abs(__x), abs(__y));
      if (__s == _Tp())  // well ...
        return __s;
      __x /= __s;
      __y /= __s;
      return __s * sqrt(__x * __x + __y * __y);
    }


text:
Q: If $a
Given two numbers $a,b\in (0, \infty)\subset\mathbb{R}$ and two other numbers $c,d\in (0, \infty)\subset\mathbb{R}$ is it sufficient to show that
  $$
\dfrac{c}{a} < \dfrac{d}{b}
$$
  in order to prove that $c<d$?
This seems to pass my intuition check of that if you divide by a larger quantity and find that the ratio is larger, the numerator should be larger
My attempt:
$$
a < b \implies \dfrac{a}{b} < 1
$$
Since
$$
\dfrac{c}{a} < \dfrac{d}{b} \implies c < \dfrac{ad}{b} < 1 \cdot d \therefore c<d
$$
Does this seem correct or is there an edge case I am missing or logical error?

A: With $a<b$ as a condition, this is correct indeed. If we don't have this condition, $6/3<4/1$ is a counterexample.


text:
Q: object openqa is not a member of package I try to run my Scala project from Terminal using this command:
/Users/dave/scala-2.11.7/bin/scala myPath.scala

And got this error:

error: object openqa is not a member of package org import
  org.openqa.selenium.support.ui.{WebDriverWait, ExpectedConditions}

This project works fine via Intellij.

A: use the -classpath parameter. e.g. scala -classpath {path to your selenium jars here} myPath.scala
For example for some of my project which I run from IntelliJ and where I use selenium the following works for me:
d:\Projects\IMDBAverage\src\main\scala-2.11>scala -classpath "D:\Projects\IMDBAverage\target\scala-2.11\classes;D:\Enreach\MTV3\Automation\Automation\lib\selenium-java-2.38.0.jar;D:\Enreach\MTV3\Automation\Automation\lib\selenium-server-standalone-2.38.0.jar" IMDBAverageCalculator.scala
Notice here that I run scala from the sources directory, the same as you try to do in your example. In the classpath I add 2 selenium jars which are in completely other folder + also I add to the classpath other compiled classes from the project. Probably in your case it is not needed, but if except from the main class there are other classes in dependencies then you should do this.
Even better would be to run from the compiled classes folder, then the classpath gets shorter (notice . as a current directory there):
d:\Projects\IMDBAverage\target\scala-2.11\classes>scala -classpath ".;D:\Enreach\MTV3\Automation\Automation\lib\selenium-java-2.38.0.jar;D:\Enreach\MTV3\Automation\Automation\lib\selenium-server-standalone-2.38.0.jar" IMDBAverageCalculator


text:
Q: Licensed API for twitter Right now I'm using a free API called tweepy in python to download tweets from twitter with a particular hashtag within a timeframe.
Mainly two problems I'm facing in tweepy:

*

*It doesn't download an media files and just provides a link for it within that tweet

*It doesn't download tweets that doesn't have text in them. (except the hashtag)

So, I was wondering if I use a licensed API (please recommend if any in mind) then will it download each and every tweet with that hashtag and within that timeline.

A: Tweepy is a Python library that provides an interface to the Twitter API. Twitter has an API itself; Tweepy is a Python way of talking to the Twitter API.
The Twitter API only provides links to images and media. It is down to your own code to download the actual content. Tweepy doesn't make any difference here. You will need to adapt your code to grab any media content from any URL in the Tweet object.

It doesn't download tweets that doesn't have text in them. (except the hashtag)

I do not know what this means. You have not provided a code sample (see how to ask) so it is impossible to understand what you need. Tweepy as a library does not download anything at all. It requests information from the Twitter API. You need to write code to download anything you want to keep.


text:
Q: Get and then remove random object from Knockout ObservableArray I'm trying to grab a random object from an observable array and then remove the object from the array so that it isn't grabbed again. However, it seems like all of the objects are being removed too quickly and incorrectly so I run out of objects.
https://jsfiddle.net/vwfp9L7s/
HTML:

Javascript:
function PersonVM() {
  this.people = ko.observableArray([{
      name: "bob",
      age: 22
    },
    {
      name: "bill",
      age: 23
    },
    {
      name: "sue",
      age: 24
    },
  ])
  this.getPerson = function() {
    var random = Math.floor(Math.random() * this.people().length);
    var randomPerson = this.people()[random];
    this.people.remove(randomPerson);
    console.log(this.people().length);
    return randomPerson;
  }
}
ko.applyBindings(PersonVM, document.getElementById("personList"));

This is only ouputting 2 person li's and leaving the third blank. If you look at the console log, the arrays length goes 2, 0, 0.
Why is .remove removing all of my objects and not the used one?

A: As @Matt said you're triggering getPerson to re-evalute. Here's why:
You have a vm that has an observableArray and you bind that to your view. There are 3 bindings to the getPerson in your view. As the view is rendered it calls the getPerson function, but on each call it mutates the people observableArray. That mutation triggers the view to re-render because there is a change in the vm.
You're using a function that returns a random person from a list so there is no reason for the people array to be observable. You only need observable properties when you want to drive a view update on change. In this case its not only unnecessary but its also causing an unintended side-effect.
Solution 1:
A simple fix would be for the people property to be a plain array:
function PersonVM() {
  this.people = [{
      name: "bob",
      age: 22
    },
    {
      name: "bill",
      age: 23
    },
    {
      name: "sue",
      age: 24
    },
  ]
  this.getPerson = function() {
    var random = Math.floor(Math.random() * this.people.length);
    var randomPerson = this.people[random];
    this.people.splice(random, 1);
    console.log(this.people.length);
    return randomPerson;
  }
}

You'll need to use splice since JS Arrays don't have a remove method.
Solution 2:
As an alternative you could keep the observableArray and fill it in random order from a plain JS array. Then you can have a simpler view binding


text:
Q: Getting all users with a Role in Liferay I'm new to Liferay development in general, so feel free to point out if I'm going about stuff totally the wrong way.
I'm trying to get a DynamicQuery object of all users within a certain group (I'll use this object to further filter another query I'll do against the message board). The User interface seems to have a roleIds property that I might be able to use, since I already know the roleId I'm interested in. But I can't find the proper way to query if roleIds contains a certain value.
Any ideas on what I want to do?
PS: I would have the exact SQL query I could ask directly, but I'd rather use Liferay's own connection pool, without needing to do some weird ext project thingy.

A: You don't need a DynamicQuery. These are the methods you are looking for in the classes that Dirk points out:
long[] UserServiceUtil.getRoleUserIds(long roleId)

or
long[] UserLocalServiceUtil.getRoleUserIds(long roleId)
List<User> UserLocalServiceUtil.getRoleUsers(long roleId)

Remember that the methods in the classes XXXLocalServiceUtil are not checking the permissions of the current user.
EDIT: If you are looking for all users with a given role within a given community:
long companyId= _X_; //Perhaps CompanyThreadLocal.getCompanyId() if you don't have it anywhere else?
Role role=RoleLocalServiceUtil.getRole(companyId, "Example Role");
Group group=GroupLocalServiceUtil.getGroup(companyId, "Example Community");
List<UserGroupRole> userGroupRoles = UserGroupRoleLocalServiceUtil.
                       getUserGroupRolesByGroupAndRole(groupId, role.getRoleId());
for(UserGroupRole userGroupRole:userGroupRoles){
    User oneUser=userGroupRole.getUser();
}

A: The easiest way to access liferays own objects is by using the XXXServiceUtil classes (e.g. RoleServiceUtil.getUserRoles(userId)). Thus you rarely have to deal with any SQL directly. Either the RoleServiceUtil or UserServiceUtil might have what you need.

A: The roles of an Organizations are stored in the table UserGroupRole, so if you want to get the owner of an Organization you must use the following code:
boolean isOrgOwner =
    UserGroupRoleLocalServiceUtil.hasUserGroupRole(
        usr.getUserId(),
        this.currentOrganization.getGroupId(),
        RoleConstants.ORGANIZATION_OWNER);

If you want to retrieve all the Organization Owners of an organization:
List<User> administrators = new LinkedList<>();

List<UserGroupRole> allOrganizationAdministrators =
    UserGroupRoleLocalServiceUtil.getUserGroupRolesByGroupAndRole(
        this.currentOrganization.getGroupId(), roleId);

for (UserGroupRole userGroupRoleTemp : allOrganizationAdministrators) {
    administrators.add(userGroupRoleTemp.getUser());
}

Cheers!


text:
Q: How can I get start date and end date of each period in sql? I have table rows like this.

status     start      end
32         1/1/2017   1/2/2017
32         1/2/2017   4/2/2017
1          4/2/2017   6/3/2017
1          6/3/2017   9/5/2017
32         9/5/2017   19/5/2017
32         19/5/2017  22/6/2017

And I wanna group rows to

status     start      end
32         1/1/2017   4/2/2017
1          4/2/2017   9/5/2017
32         9/5/2017   22/6/2017

How can I do using SQL?
thank you for all help.

A: I don't think you can easily do this one in one step. Maybe if you resort to some ugly recursive CTE or a very long chain of CTEs or nested sub-queries. Basically you need to reconfigure your dataset so you can tell the beginning and end of a period.
Assumptions:

*

*Any gap means a period is ending and a new period is beginning

*There are no overlapping periods. (i.e. 1 (1/7 - 1/12), 1 (1/10 - 1/20) )

I'm going to go with SQL-Server syntax because it's what I'm most comfortable with, but these operations should be something you could do in most sql environments with a little modification. (I'm using a temp table and CTE's, but you could use sub-queries)
create table dbo.[Status] (
    [status] int,
    [start] date,
    [end] date
)

insert into dbo.[Status] ([status], [start], [end])
values
    (32,    '20170101', '20170201'),
    (32,    '20170201', '20170204'),
    (1,     '20170204', '20170306'),
    (1,     '20170306', '20170509'),
    (32,    '20170509', '20170519'),
    (32,    '20170519', '20170622')

create table dbo.Result (
    PeriodID int identity, -- to make grouping and self-referential joins easier
    Status int,
    start date,
    next_start date null,
    [end] date null
)

select * from dbo.[Status]
-- This will get you all the periods and their start dates
;with cteExcludeTheseRows(status, start) as (
    -- These are the records where the Start date matches an end date for the same status group. As a result these aren't real periods, just extensions.
    select S.status, S.start
        from [Status] S
        join [Status] Prior on S.Status = Prior.status and S.start = Prior.[end]
)
insert into dbo.Result (status, start)
    select
        S.status,
        S.start
    from [Status] S
        left join cteExcludetheserows Exclude on S.status = Exclude.status and S.start = Exclude.start
    where Exclude.status is null

-- Reference the temp table to get the next start period for your status groups, that way you know that the end date for that period has to be less then that date
;with cteNextStart (PeriodID, next_start) as (
    select
        R.PeriodID,
        next_start = min(next.start)
        from dbo.Result R
        join dbo.Result next on R.status = next.status and r.start < next.start
        group by R.PeriodID
)
update R
    set R.next_start = next.next_start
    from dbo.Result R
    join cteNextStart next on R.PeriodID = next.PeriodID

-- Now get the end date for each period by looking back at your main status table
;with cteEnd (PeriodID, [end]) as (
    select
        R.PeriodID,
        [end] = max(s.[end])
        from dbo.Result R
        join [Status] S on R.status = s.status and S.[end] between R.start and isnull(R.next_start, '99991231')
        group by R.PeriodID
)
update R
    set R.[end] = [end].[end]
    from dbo.Result R
    join cteEnd [end] on R.PeriodID = [end].PeriodID

-- And finally, here you have your result set
select
    status,
    start,
    [end]
    from dbo.Result
    order by start, status

drop table dbo.[Status]
drop table dbo.Result

A: see  also
demo
SELECT  * FROM aaa a
where a.sstatus != (select top 1 b.sstatus from aaa b
                                where b.start_date < a.start_date
                                order by b.start_date desc);

A:    you may try this:

   CREATE TABLE #STATUS
    (
        [STATUS] INT,
        [START] DATE,
        [END] DATE
    )

    INSERT INTO #STATUS
     (
      [STATUS], [START], [END]
     )
    VALUES
        (32,    '20170101', '20170201'),
        (32,    '20170201', '20170204'),
        (1,     '20170204', '20170306'),
        (1,     '20170306', '20170509'),
        (32,    '20170509', '20170519'),
        (32,    '20170519', '20170622')

    SELECT
      A.STATUS
     ,A.[START]
     ,B.[END]
    FROM #STATUS A
    LEFT JOIN #STATUS B
    ON A.[STATUS]=B.[STATUS]
    AND A.[END]=B.[START]
    WHERE B.STATUS IS NOT NULL


text:
Q: how to access the $query variable inside taxonomy-xxx.php template file? In my custom template files, I create query in the following way:
<?php $query = new WP_Query(array('post_type' => 'aya-bi-aya','author' => $current_user->ID,'paged' => $paged, 'post_status' => array('publish') ) ); ?>

And to perform pagination, I call pagination function after loop like:
<?php my_pagination($query->max_num_pages);?>

But in my taxonomy-xxx.php, when I call pagination the same way, I get the warning:
Notice: Undefined variable: query in C:\xampp\htdocs\balagha-to-alquran\production\wp-content\themes\twentyten\taxonomy-dawahir-balaghia.php on line 186

Notice: Trying to get property of non-object in C:\xampp\htdocs\balagha-to-alquran\production\wp-content\themes\twentyten\taxonomy-dawahir-balaghia.php on line 186

Can you please help me resolve this issue? your help is appreciated.
Edit and solution:
My pagination function:
function my_pagination($pages = '', $range = 2)
{
     $showitems = ($range * 2)+1;

     global $paged;
     if(empty($paged)) $paged = 1;

     if($pages == '')
     {
         global $wp_query;
         $pages = $wp_query->max_num_pages;
         if(!$pages)
         {
             $pages = 1;
         }
     }

     if(1 != $pages)
     {
         echo "
";

         if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "«";
         if($paged > 1 && $showitems < $pages) echo "‹";

         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? "".$i."":"".$i."";
             }
         }

         if ($paged < $pages && $showitems < $pages) echo "›";
         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "»";
         echo "
\n";
     }
}

I resolved the issue by removing the argument from the function call($query->max-num-pages) in my taxonomy-xx.php since the argument is not mandatory. As you can see, there is an if statement inside the function that deals with the absence of argument by calling the global $wp_query.
Thank you.

A: Is the my_pagination() call within the same file as your $query declaration?
If not, you need to put global $query; at the top of your template file where my_pagination() is being called.
If this doesn't solve it, please give some more information/code examples.


text:
Q: DAML finance library usage About DAML finance library, I have found some docs.
But I still can not understand what's the key usage of this library, and what is the difference/benefits between "normal" smart contract and using Finlib of digital asset creation/transfer/redeem?

A: The FinLib contains an asset model that can be used as a common representation for assets across different use cases / applications. The benefit of using a shared model is that your applications become inherently interoperable. For example, let's say you have an issuance app and a trading app. If both use the same asset model, the assets issued from one app can be used as is for trading in the other app, without any need for translation.
The FinLib library provides a ready implementation of the most important aspects of an asset model:

*

*How asset ownership is represented

*How accounts are represented

*How signatories are defined for your assets

*How to split and merge fungible assets

*How to transfer ownership of assets

*How to do atomic swaps and settlement

The library doesn't actually prescribe how you represent the definition of what a particular asset actually is, or what the rules and workflows around it are. An asset in this model is represented by an abstract identifier (the asset id), which you can use to link it to a description or to workflows. This type of loose coupling allows for the dynamic evolution of facts and rules around your assets, without having to touch the contracts representing the ownership.


text:
Q: Transforming Observables in RxJava and RxScala I have an Observable that emits a List of entries as below:
val obsList: Observable[List[MyEntry] = Observable.from(getListEntry)

// getListEntry would give me a List[MyEntry]

How could I now get the contents piped into another Observable that takes in a MyEntry? I mean, for each entry in the original Observable, I would need to pipe them to another Observable that has a type signature of:
Observable[MyEntry]

A: I figured out how to do this! I'm using the Monifu library!
So, I would be doing:
Observable.fromIterable(listOfEntry)


text: Q: Where to use Redux and sessionStorage? I am developing an application in that i am using sessionStorage, I was reading an article and found that redux . After reading more about redux, I found that it is also used for state management ( currently i am managing my application state using sessionStorage) . Now I am confused where to use sessionStorage and redux.


text:
Q: Retain UINavigationBar height as 64points when UIStatusBar hides I'm using a UINavigationController, which has a UINavigationBar.
When I call and hide the UIStatusBar, the navigationBar reduces in size to 44pts. I don't want this to happen, I want it to retain the size of 64pts.
Is this even Possible? Could I do some workaround to hard code that size?