Q:

How to extract Bigquery table for every given length of rows to csv file in Google Storage?

For example, I have a table in bigquery with 10 million rows, I want to extract this table to Google Storage every 100 thousand rows. To make it clear, I want 100 csv files and each one have 100k distinct rows in the bigquery table.
bq extract --noprint_header dataeset.abigtable gs://bucket/output/*.csv

With the code above entered into gcloud shell, the table will be splitted into 10 or so files in google storage. However, I have no control of how many rows in each of the file. How could I control it?

A:

There is no flag which you can use to make your use-case possible. If you think this feature would be helpful, you can file this as a feature request, although a handful of stars is needed to get this feature request to be prioritized by the BigQuery team. To make it more meaningful, there should be a business use-case as to why you need such (e.g why would you need the exported csv file to have 100k rows each?).


Q:

How to assign "var" inside if statement

I need to do this:
var productsLocation = response.blah blah; //with linq query
var item; // even var item = null; //not valid
if(condition){
    item = productsLocation.linq query
} else {
    item = productsLocation.differentquery
}
var group = item.query;

Is this possible? If yes, how?
EDIT: here is my exact code:
var productLocation = response.productLocation.Select(p => ProductLocationStaticClass.DtoToModel(p));
var items;
if (condition)
{
    items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName));
} else {
    items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName) && stocks.Contains(s.Barcode));
}

A:

First of all get your response variable type, then initialize 'item' variable as IEnumarable where T is same as response variable type
var productsLocation = response.productLocation.Select(p => ProductLocationStaticClass.DtoToModel(p));
IEnumerable<ProductClass> item;
if (condition)
{
    items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName));
}
else
{
    items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName) && stocks.Contains(s.Barcode));
}
var group = item.Where(condition);


Q:

R: choose different raw and separate to new ranked set

I have a dataset which looks like:
Interest    Age     Gender  Scored.Probabilities
AL008       18-24   male    0.211
AL024       25-34   male    0.022
AL008       35-44   female  0.102
AL008       25-34   female  0.002
AL024       13-17   male    0.102
AL035       35-44   female  0.027
AL024       35-44   female  0.051
AL024       55-64   male    0.025
AL024       35-44   male    0.016
AL034       45-54   male    0.021
AL036       35-44   male    0.082

I want choose the same name of 'Interest' column and create new dataset which ranked according to 'Scored.Probabilities':
Set         Interest    Age     Gender  Scored.Probabilities    rank
1           AL008       18-24   male    0.211                    1
1           AL008       35-44   female  0.102                    2
1           AL008       25-34   female  0.002                    3
2           AL024       13-17   male    0.102                    1
2           AL024       35-44   female  0.051                    2
2           AL024       55-64   male    0.025                    3
2           AL024       25-34   male    0.022                    4
2           AL024       35-44   male    0.016                    5
3           AL034       45-54   male    0.021                    1
4           AL035       35-44   female  0.027                    1
5           AL036       35-44   male    0.082                    1

A:

You can try
 library(data.table)
 setDT(df1)[order(-Scored.Probabilities), rank:= 1:.N, Interest][
           order(Interest), Set := .GRP, Interest][order(Interest, rank)]
 #     Interest   Age Gender Scored.Probabilities rank Set
 #1:    AL008 18-24   male                0.211    1   1
 #2:    AL008 35-44 female                0.102    2   1
 #3:    AL008 25-34 female                0.002    3   1
 #4:    AL024 13-17   male                0.102    1   2
 #5:    AL024 35-44 female                0.051    2   2
 #6:    AL024 55-64   male                0.025    3   2
 #7:    AL024 25-34   male                0.022    4   2
 #8:    AL024 35-44   male                0.016    5   2
 #9:    AL034 45-54   male                0.021    1   3
#10:    AL035 35-44 female                0.027    1   4
#11:    AL036 35-44   male                0.082    1   5


Q:

CPU vs Memory trade-offs when using instanced drawing w/ many unique primitives

I'm using OpenGL ES 2 on iOS to render a (relatively) huge 2D grid where the squares ("pixels") are disjointed -- spaced, instead of in a checkerboard pattern -- and outlined, and am having the worst time trying to figure out an efficient way to draw it such that each square and outline of that square can be assigned a different color, as this is for a drawing app. The grid must be able to represent up to 1024x1024 "pixels".
Originally, I tried the approach of putting all of my vertex data in a massive buffer and rendering that with a single glDrawArrays call each frame, but, as you might expect, the memory usage was unreasonable and that was only with the outlines (made with GL_LINES) -- no fills. Further research taught me about instanced drawing, which I'm doing now via glDrawArraysInstancedEXT, but, of course, 1024*1024 instanced draw calls are killing the CPU/FPS. I would guess that the solution to this problem lies somewhere between the two approaches -- draw a larger primitive of "grouped" GL_TRIANGLE_STRIPs using degenerate vertices to separate the resulting squares... but then I don't think I can give each square it's own color. Needless to say, I'm still learning; how does one usually draw massive quantities of simple, same, but uniquely-colored polygons??
The relevant code...
static const int numColumns = 1024;
static const int numRows = 1024;
static const GLfloat outlineVertices[] = {
    0.1f, -0.1f,
    0.9f, -0.1f,
    0.1f, -0.9f,
    0.9f, -0.9f
};
static const GLfloat innerVertices[] = {
    0.2f, -0.2f,
    0.8f, -0.2f,
    0.2f, -0.8f,
    0.8f, -0.8f
};

- (void)setupGL
{
    [EAGLContext setCurrentContext:self.context];

    [self loadShaders];

    glDisable(GL_DEPTH_TEST);

    glGenVertexArraysOES(1, &_vertexArray);
    glBindVertexArrayOES(_vertexArray);

    glGenBuffers(1, &_vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(outlineVertices), outlineVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
}

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    glClearColor(0.65f, 0.65f, 0.65f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glBindVertexArrayOES(_vertexArray);

    glUseProgram(_program);
    glUniformMatrix4fv(uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX], 1, 0, _modelViewProjectionMatrix.m);
    glUniform1i(uniforms[NUM_COLUMNS], numColumns);
    glUniform1i(uniforms[NUM_ROWS], numRows);

    glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(outlineVertices), outlineVertices, GL_STATIC_DRAW);
    glUniform1i(uniforms[DRAWING_INNER], 0);
    glDrawArraysInstancedEXT(GL_TRIANGLE_STRIP, 0, 4, numColumns * numRows);

    glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(innerVertices), innerVertices, GL_STATIC_DRAW);
    glUniform1i(uniforms[DRAWING_INNER], 1);
    glDrawArraysInstancedEXT(GL_TRIANGLE_STRIP, 0, 4, numColumns * numRows);
}

vshader:
#extension GL_EXT_draw_instanced : enable

attribute vec4 vertices;

varying lowp vec4 colorVarying;

uniform int numColumns;
uniform int numRows;
uniform mat4 modelViewProjectionMatrix;
uniform int drawingInner;

void main()
{
    if (drawingInner == 0) {
        colorVarying = vec4(1.0, 0.0, 1.0, 1.0);
    } else {
        colorVarying = vec4(0.0, 0.0, 1.0, 1.0);
    }

    float column = mod(float(gl_InstanceIDEXT), float(numColumns));
    float row = -(float(gl_InstanceIDEXT / numColumns));

    gl_Position = vec4(vertices.x + column, vertices.y + row, vertices.zw) * modelViewProjectionMatrix;
}

Any help is appreciated, including tips on best practices. Is there a way to draw this massive grid efficiently without changing the data based on what the user is currently seeing... some sort of manual culling? Thank you!

A:

Best to just do this in the fragment shader.  This way, you can just use plain, ordinary textures, and you can forget about having to render anything more than a single quad.  Here is a shader that draws a grid, with different foreground / background colors for each pixel.  It is written to run inside ShaderToy, so you will have to adapt it for your program.
I put a live demo on ShaderToy (which is a little different from the code below, so it can run on ShaderToy).
Fragment Shader
precision mediump float;

// Texture coordinates, from 0 to 1
varying vec2 TexCoord;
uniform sampler2D FGTex;
uniform sampler2D BGTex;
// Texture size, in pixels.
uniform vec2 TexSize;
// Width of grid lines, from 0 to 1
uniform float GridWidth;

void main() {
    // Get the foreground and background colors
    vec4 fgColor = texture2D(FGTex, TexCoord);
    vec4 bgColor = texture2D(BGTex, TexCoord);
    // Calculate the grid
    vec2 gridPos = fract(TexCoord * TexSize + GridWidth * 0.5);
    vec2 gridFrac = step(GridWidth, gridPos);
    gl_FragColor = mix(bgColor, fgColor, gridFrac.x * gridFrac.y);
}

Results

Note that the grid lines are inconsistent unless you do the math exactly right to get them to line up, but you have to do that anyway.


Q:

code is not working as expected; array doubling; pass by reference

i was working on stacks when i came across a problem where i had to double the array. i used this code which did not work but it should have.
class ArrayDouble
{
public static void main(String []args)
{
    int arr[] = new int[10];
    sizeChange(arr);
    for(int i=0;i<arr.length;i++)
        System.out.print(arr[i]+ " ");
}
public static void sizeChange(int arr[])
{
    arr[0]=1;
    arr = new int[2*arr.length];
    arr[1]=1;
}
}

from what i have seen, any changes that takes place in an array which has been passed as a parameter, the changes reflect back in the actual parameters right? So why doesn't the change in size of the array is reflected in the original parameter?
Also, arr[0] becomes 1 in the original array but arr[1] remains 0. why does that happen?
PS: the problem was solved when i changed the return type of sizeChange to int[] and passed arr of sizeChange and collected it into the Main arr. So i dont need the correction of the code, i just need the answer as to why this is happening.
Thank you in advanced.

A:

Arrays are not a primitive type in Java, but they are not objects either ... "
In Java, the called method can update the contents of the array, and it can update its copy of the array reference, but it can't update the variable in the caller that holds the caller's array reference. Hence ... what Java is providing is NOT pass-by-reference.
Like all Java objects, arrays are passed by value ... but the value is the reference to the array. So, when you assign something to a cell of the array in the called method, you will be assigning to the same array object that the caller sees.
This is NOT pass-by-reference. Real pass-by-reference involves passing the address of a variable. With real pass-by-reference, the called method can assign to its local variable, and this causes the variable in the caller to be updated.
Detailed Explaination :
Arrays are in fact objects, so a reference is passed (the reference itself is passed by value, confused yet?). Quick example:
// assuming you allocated the list
public void addItem(Integer[] list, int item) {
    list[1] = item;
}

You will see the changes to the list from the calling code. However you can't change the reference itself, since it's passed by value:
// assuming you allocated the list
public void changeArray(Integer[] list) {
    list = null;
}

If you pass a non-null list, it won't be null by the time the method returns.


Q:

Is it possible to have Angular @HostListener('window:scroll',) in simple Service not Component or Directive

Is it possible to have Angular @HostListener('window:scroll',) in simple Service not Component or Directive code?
I don't want to polute any of my components, since the awareness of scroll should be injected in several other services... Currently i have following code that compiles, but does not work somehow.
import { Component, OnInit, Injectable, Inject, HostListener } from '@angular/core';
import { SearchService } from './search.service';
import { DOCUMENT } from '@angular/platform-browser';

const scrollStepToReload = 3700;

@Injectable()
export class ScrollWatcherService {

  private maxReachedScroll = 0;
  private lastLoadedAt = 0;

  constructor(private searchService: SearchService, @Inject(DOCUMENT) private document: any) { }

  @HostListener('window:scroll', ['$event'])
  onScroll($event) {

    const scrollOffset = window.pageYOffset || this.document.documentElement.scrollTop || this.document.body.scrollTop || 0;
    console.debug("Scroll Event", scrollOffset);

    if (scrollOffset > this.maxReachedScroll) {
      this.maxReachedScroll = scrollOffset;
    }
    if (this.lastLoadedAt + scrollStepToReload < this.maxReachedScroll) {

      this.lastLoadedAt = this.maxReachedScroll;
      this.searchService.continueSearch();

    }
  }
}

Similar code works i Component as desired.
Any ideas how to get it run in a service? or something similar?

A:

You cannot have a HostListener in a service. Use the classic:
window.addEventListener('scroll', () => {
        console.log('scrolling');
});


Q:

Sort items in a list according to the number in the item

I have a list which looks like this-
answer = ['toy3', 'toy4', 'toy1']

I want to sort it according to the number in the toy(ascending). So the list should look like this-
answer = ['toy1', 'toy3', 'toy4']

A:

Use the key parameter of sorted:
import re

numbers = re.compile('\d+$')

answer= ['toy3','toy4','toy1']

result = sorted(answer, key=lambda x: int(numbers.search(x).group()))
print(result)

Output
['toy1', 'toy3', 'toy4']

The idea is to extract the group of digits at the end and convert to an integer, then use this value as the key for sorting.


Q:

Is it possibly to re-load a JS script file dynamically?

We're looking at using Blockly to enable power-users to design business rules in a non-coding, sandboxed way.
When they edit their diagram to regenerate new JS code, I would like to reload this into the browser. One aspect of this is, if the code is saved as an external JS script, how can I reload it in the browser without refreshing the whole page?

A:

Even though your explanation is extremely messy, I’ll try to stick to the title and provide an example of how you might re-load a specific JS file dynamically (apologies if it is not what you were looking for, but then you’d better re-write your question).
I guess you did not search Google a lot, because in this SO answer you find how to re-load a JS file:
function reloadJs(src) {
    src = $('script[src$="' + src + '"]').attr("src");
    $('script[src$="' + src + '"]').remove();
    $('


Q:

Unique value combinations with summary count

Say I have the following data
x <- (c(1,2,1,1,1,2,2,1,2,1,2))
y <- (c(3,4,4,4,4,3,3,4,4,3,3))
table <- data.frame(x,y)

How would one calculate the frequencies of a unique combinations, ie 1-4
I have looked into summary((table$x)[1] & (table$y)[2])
Does it involve using the the unique and length commands?
Or must I use the plyr package and then use ddply
Thanks in advance !

A:

As Ananda suggets the function table is likely the way to go:
> df <- data.frame(x, y)
> table(df)
   y
x   3 4
  1 2 4
  2 3 2
> table(with(df, paste(x, y, sep="-")))

1-3 1-4 2-3 2-4
  2   4   3   2


Q:

Converting code containing views to stored procedure

I've pieced together this code to create a pivot on a sum of invoice subtotals per a dealership. It works, and produces the correct results. However, when I try to convert it to a stored procedure the infamous squiggly red line appears under "CREATE VIEW Revenues" in SQL Server management studio and the error says:
'CREATE VIEW must be the only statement in the batch' and I don't know enough T-SQL to proceed as I need to be able to execute it from a ASP.NET/C# web app.
I'm trying create an SP by putting:
1)
USE [Sherwood]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROC [dbo].[usp_GetRevenues]

@StartDate AS DateTime = '20120301',
@EndDate AS DateTime = '20120401'
AS
SET NOCOUNT ON;

BEGIN

in front, with an END statement at the end.
2) The parameters are necessary to be able to filter the data for a period of months, but I appear not to be able to pass parameters or use variables with the code as is.
Thanks in advance.
Code as is below - showing where I need to filter with variables. The code works only with dates in the format '1/1/2012' in the where clause, but need to be able to pass variables as shown.
--================================
CREATE VIEW Revenues
AS
SELECT
i.DateOrdered
,LTRIM(STR(DATEPART(MONTH,i.DateOrdered))) AS [Month]
,LTRIM(STR(YEAR(i.Dateordered))) AS [Year]
,c.CustomerCode
,SUM(i.Jobprice) AS Subtotal
FROM Invoices i
JOIN
Customers c
ON i.CustomerID = c.ID
WHERE i.DateOrdered >= @StartDate
AND i.DateOrdered <= @EndDate **<-- and here.**
GROUP BY ROLLUP (YEAR(i.DateOrdered),
MONTH(i.DateOrdered), i.DateOrdered, c.CustomerCode);
GO

IF OBJECT_ID('Revenues2') IS NOT NULL
DROP VIEW Revenues2
GO

CREATE VIEW Revenues2
AS
SELECT
 LTRIM(STR([YEAR])) + '-' + STUFF([Month],1,0, REPLICATE('0', 2 - LEN([Month])))
 AS [Date]
,Subtotal
,CustomerCode
FROM Revenues
WHERE CustomerCode IS NOT NULL
GO

DECLARE @query VARCHAR(4000)
DECLARE @years VARCHAR(2000)
SELECT  @years = STUFF(( SELECT DISTINCT
                    '],[' + [Date]
                    FROM  Revenues2
                    ORDER BY '],[' + [Date]
                    FOR XML PATH('')
                    ), 1, 2, '') + ']'

SET @query =
'SELECT * FROM
(
  SELECT Subtotal,[Date],CustomerCode
   FROM Revenues2
)t
PIVOT (SUM(Subtotal) FOR [Date]
IN ('+ @years +')) AS pvt'

EXECUTE (@query)

--==========================================
Regards
Cliff

A:

I may be wrong, but it seems to me you're not deleting/commenting the "CREATE VIEW" part when you're converting to an SP. This is wrong for you cannot define a view from within a stored procedure's definition - hence the "CREATE VIEW must be(...)" complaint.
Besides, that code of yours is a bit fragile: once you've correctly created the SP, next time it runs it will error with a message of "The SP is already used, you should be using ALTER PROC" or something like that (I'm writing from memory know).
Code like this should solve both problems:
USE [Sherwood]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- It's preferable to set these options before creating an SP,
-- rather than within its execution
SET NOCOUNT ON
GO
IF OBJECT_ID('usp_GetRevenues') IS NOT NULL
    DROP PROC usp_GetRevenues
GO
CREATE PROC [dbo].[usp_GetRevenues]
    @StartDate AS DateTime = '20120301',
    @EndDate AS DateTime = '20120401' AS
-- BEGIN --This is really optional
SELECT
i.DateOrdered
,LTRIM(STR(DATEPART(MONTH,i.DateOrdered))) AS [Month]
,LTRIM(STR(YEAR(i.Dateordered))) AS [Year]
,c.CustomerCode
,SUM(i.Jobprice) AS Subtotal
FROM dbo.Invoices i
JOIN dbo.Customers c
ON i.CustomerID = c.ID
WHERE i.DateOrdered >= @StartDate
AND i.DateOrdered <= @EndDate **<-- and here.**
GROUP BY ROLLUP (YEAR(i.DateOrdered),
MONTH(i.DateOrdered), i.DateOrdered, c.CustomerCode);
GO


Q:

Android ListView does not populate all entries in SQLite DB

I am working on a learning Android application (PersistAlarm, I call it) where I can set an alarm. The application's first activity is a button with ListView where the user can add alarms to the application. The alarm is set in the second activity and it populates the DB in the backend.
Once the alarm is set, it returns to the first activity (PersistAlarm.java) where the list of alarms is populated.
The problem is that till now, I was able to get the list of alarms. Suddenly, only the first entry in the alarms table is now visible. Other entries arent displayed. Strange!
Can anyone tell me where I am going wrong?
Here's the PersistAlarm Activity XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".PersistAlarm" >

<Button
    android:id="@+id/buttonAddAlarm"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add Entry" />

<ListView
    android:id="@+id/alarmListV"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</ListView>

Here's the PersistAlarm.java code
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_persist_alarm);

    final AlarmAdapter alarmAdapt;
    final ListView mainAlarmView;

    final Context context = this;

    Button alarmAdd = (Button) findViewById(R.id.buttonAddAlarm);

    mainAlarmView = (ListView) findViewById(R.id.alarmListV);

    alarmAdd.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent intent = new Intent(context, AddEditAlarm.class);
            startActivity(intent);
        }
    });

    List<PAlarm> alarmList = db.getAllAlarms();
    Log.d("LIST COUNT" , String.valueOf(alarmList.size()));
    alarmAdapt = new AlarmAdapter(PersistAlarm.this, R.id.alarmListV, alarmList);
    mainAlarmView.setAdapter(alarmAdapt);

}

Here's my PAlarm object that acts as the foundation object for the Application:
public class PAlarm {

int _id;
String _eventName;
String _eventDate;
String _eventTime;
String _type;

public PAlarm() {

}

public PAlarm(int id, String eventName, String eventDate, String eventTime, String type) {
    this._id = id;
    this._eventName = eventName;
    this._eventDate = eventDate;
    this._eventTime = eventTime;
    this._type = type;
}

public PAlarm(String eventName, String eventDate, String eventTime, String type) {
    this._eventName = eventName;
    this._eventDate = eventDate;
    this._eventTime = eventTime;
    this._type = type;
}

public int get_id() {
    return _id;
}

public void set_id(int _id) {
    this._id = _id;
}

public String get_eventName() {
    return _eventName;
}

public void set_eventName(String _eventName) {
    this._eventName = _eventName;
}

public String get_eventDate() {
    return _eventDate;
}

public void set_eventDate(String _eventDate) {
    this._eventDate = _eventDate;
}

public String get_eventTime() {
    return _eventTime;
}

public void set_eventTime(String _eventTime) {
    this._eventTime = _eventTime;
}

public String get_type() {
    return _type;
}

public void set_type(String _type) {
    this._type = _type;
}

@Override
public String toString() {
    return this._id + ". " + this._eventName + " - " + this._eventDate + " - " + this._eventTime;
}

This is my custom Adapter to render the ListView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/alarmNameTV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24dip" />
    <TextView
        android:id="@+id/alarmDateTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="9dip" />

</LinearLayout>

Also, my Custom Adapter's java code:
public class AlarmAdapter extends ArrayAdapter<PAlarm> {
private List<PAlarm> alarms;
private Activity activity;

public AlarmAdapter(Activity a, int textViewId, List<PAlarm> alms) {
    super(a, textViewId, alms);
    this.alarms = alms;
    this.activity = a;

}

public static class ViewHolder {
    public TextView alarmView;
    public TextView alarmDateTimeView;

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View v = convertView;
    ViewHolder holder;

    if (v == null) {
        LayoutInflater vi = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.alarm_item, null);
        holder = new ViewHolder();
        holder.alarmView = (TextView) v.findViewById(R.id.alarmNameTV);
        holder.alarmDateTimeView = (TextView) v.findViewById(R.id.alarmDateTime);
        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
        final PAlarm alarm  = alarms.get(position);
        if (alarm != null) {
            holder.alarmView.setText(alarm.get_eventName());
            holder.alarmDateTimeView.setText(alarm.get_eventDate() + " (" + alarm.get_eventTime() + ")" );
        }
    }

    return v;

}

Would appreciate some help here. Thanks

A:

try changing your getView():
public View getView(int position, View convertView, ViewGroup parent) {

    View v = convertView;
    ViewHolder holder;

    if (v == null) {
        LayoutInflater vi = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.alarm_item, null);
        holder = new ViewHolder();
        holder.alarmView = (TextView) v.findViewById(R.id.alarmNameTV);
        holder.alarmDateTimeView = (TextView) v.findViewById(R.id.alarmDateTime);
        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();

        }
   final PAlarm alarm  = alarms.get(position);
   if (alarm != null) {
       holder.alarmView.setText(alarm.get_eventName());
       holder.alarmDateTimeView.setText(alarm.get_eventDate() + " (" + alarm.get_eventTime() + ")" );
    }

    return v;

}

Explaination:
In ListView views are recycled if view coming in getView() is null it means view is not recycled and we have to initialize it; which we do in if condition. if view is not null that means it is recycled and we just have to change the data for that view.
so view is recycled or not we have to set data. so data setting code should be outside if...else


Q:

Modulus division when first number is smaller than second number

I apologize if this is a simple question but I'm having trouble grasping the concept of modulus division when the first number is smaller than the second number. For example when 1 % 4 my book says the remainder is 1. I don't understand how 1 is the remainder of  1  % 4.  1 / 4 is 0.25. Am I thinking about modulus division incorrectly?

A:

First, in Java, % is the remainder (not modulo) operator, which has slightly different semantics.
That said, you need to think in terms of integer-only division, as if there were no fractional values. Think of it as storing items that cannot be divided: you can store zero items of size 4 in a storage of overall capacity one. Your remaining capacity after storing the maximum number of items is one. Similarly, 13%5 is 3, as you can fit 2 complete items of size 5 in a storage of size 13, and the remaining capacity is 13 - 2*5 = 3.

A:

If you divide 1 by 4, you get 0 with a remainder of 1. That's all the modulus is, the remainder after division.

A:

I am going to add a more practical example to what "Jean-Bernard Pellerin" already said.
It is correct that if you divide 1 by 4 you get 0 but, Why when you do 1 % 4 you have 1 as result?
Basically it is because this:
n = a / b (integer), and
m = a % b = a - ( b * n )

So,
 a    b    n = a/b  b * n  m = a%b
 1    4      0        0      1
 2    4      0        0      2
 3    4      0        0      3
 4    4      1        0      0
 5    4      1        4      1

Conclusion: While a < b, the result of a % b will be "a"


Q:

Javascript Regexp: Replace curly braces

Folks,
I'm trying to replace a huge chunk of string with a multiple occurrences of "${country_id}". I need a Regular expression that can replace the ${country_id}. Here is the code I have:
    var iterLiteral  = "\$\{"+literal+"\}"
    var re = new RegExp(iterLiteral,"g")
    var value = value;
    return body.replace(re,value)

I get this error:

Evaluator: org.mozilla.javascript.EcmaError: Invalid quantifier }

How can I fix it?
Edit:
String to be replaced: ${country_id}
literal being passed to the function : country_id.
Trying to use what Anubhava said ( using \\ ), the program tries to search for \$\{country_id\} and it doesn't find one.
Edit 2: Why is this a duplicate? the question that was mentioned doesn't talk about escaping.

A:

If you have a set regular expression, you might find it easier to use the // syntax for defining the RegExp:
'foo: ${country_id}, bar: ${country_id}'.replace(/\$\{country_id\}/g, 'baz')

Alternatively, if the string must be constructed, then you need to double escape the slashes for them to be a part of the regular expression, and not seen as escaping characters for the creation of the string itself:
'foo: ${country_id}, bar: ${country_id}'.replace(new RegExp('\\$\\{' + 'country_id' + '\\}', 'g'), 'baz')

Your function would thus be:
function replaceLiteral(body, literal, value) {
    var iterLiteral = "\\$\\{" + literal + "\\}";
    var re = new RegExp(iterLiteral, "g");
    return body.replace(re, value)
}

var result = replaceLiteral('foo: ${country_id}, bar: ${country_id}', 'country_id', 'baz');
console.log(result);

All of these output the same string:
'foo: baz, bar: baz'


Q:

Examples of other Mills' constants

Mills' constant is the well-known constant A such that the function $\lfloor A^{{3}^{n}} \rfloor$ gives primes for all natural numbers $n$, whose value is ~$1.306377883...$
It is also well-known that there is an infinity of functions $\lfloor A^{{r}^{n}} \rfloor$ that gives primes for all $n$, depending on the value of $r$.
Are there any examples of such $\lfloor A^{{r}^{n}} \rfloor$ where $r \neq 3$? There seems to be very little information available on this subject.

A:

Given a particular value of $r \ge 3$, a high precision calculator and a method of finding the next prime above a number, it is easy to find the initial digits of $A_r$.
For example with $r=4$:

start with the smallest prime $2$
$2^4=16$
the smallest prime above $16$ is $17$
$17^4 = 83521$
the smallest prime above $83521$ is $83537$
etc.

We now want $2 \le A_4^{4^1} \lt 3$ and $17 \le A_4^{4^2} \lt 18$ and $83537 \le A_4^{4^3} \lt 83538$ and so on
This will give $A_4=1.193725\ldots$
Meanwhile, for $r=2$, then if Legendre's conjecture that there is a prime between $n^2$ and $(n+1)^2$ is true,  you have $\lfloor 1.5246999605380943599233635756884211622202236231…^{2^n}\rfloor$ giving primes: see OEIS A059784


Q:

Change the app-name sent by docker's syslog driver

I'm using Papertrail to collect my Docker container's logs.
Do to that, I used the syslog driver when I created the container:
sudo docker run --name my_container --log-driver=syslog  ...

... and added the following line to my /etc/rsyslog.conf
*.* @logsXXX.papertrailapp.com:YYYY

At the end, I get on Papertrail logs like this:
Apr 24 13:41:55 ip-10-1-1-86 docker/3b00635360e6: 10.0.0.5 - - [24/Apr/2015:11:41:57 +0000] "GET /healthcheck HTTP/1.1" 200 0 "-" "" "-"

The problem is that the app-name (see syslog RFC) is docker/container_id
I would rather have the container name (or host). But I don't know how to do.
I tried to set a specific hostname to my container like below, but it didn't work better:
sudo docker run --name my_container -h my_container --log-driver=syslog  ...

A:

You can't do it. Here's a pending PR to add that feature: https://github.com/docker/docker/pull/12668
Hopefully it gets merged in soon. You could always roll your own, I suppose.
Update: Looks like this is slated for Docker 1.8
Update: This is now possible:
docker run --name my_container --log-driver=syslog --log-opt syslog-tag=my_application


Q:

Highcharts: Legend not show

I tried to make a chart using Highcharts 3.0. Have a look at [http://jsfiddle.net/QL2Hn/][1]
The problem is, why the chart legend only perform 2 pieces only? Please help. Thank you.

A:

Well for me it lists all items, see this http://jsfiddle.net/QL2Hn/1/ but you need to set showInLegend:true


Q:

Unity - SetActive not defined

When using a script to hide and unhide specific sprites on the click of a button, I get these two errors.
Assets\Scripts\ButtonLeft.cs(26,5): error CS1061: 'int' does not contain a definition for 'SetActive' and no accessible extension method 'SetActive' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
Assets\Scripts\ButtonLeft.cs(22,8): error CS1061: 'int' does not contain a definition for 'activeSelf' and no accessible extension method 'activeSelf' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
I was assured by previous posts, some only dating back a few weeks, that activeSelf was the correct way to check whether a sprite was already hidden, and I have used SetActive before in this project with no issues. Here's the script I'm trying to run:
using System.Collections.Generic;
using UnityEngine;

public class ButtonLeft : MonoBehaviour
{

    public void Click ()
    {
    if (23.activeSelf)
    {
        23.SetActive (false);
        3.SetActive (true);
        1.SetActive (false);
    }
    if (3.activeSelf)
    {
        23.SetActive (false);
        3.SetActive (false);
        1.SetActive (true);
    }
    if (1.activeSelf)
    {
        23.SetActive (true);
        3.SetActive (false);
        1.SetActive (false);
    }
    }

    // Update is called once per frame
    void Update()
    {

    }
}

Is the syntax wrong in any way? Is activeSelf not the correct way to check whether an object is active or not?
Using Unity 2019.4.5f1 Personal

A:

The reason you're getting those error messages is due to running them on integers instead of sprites. You need to use an instance of a GameObject.
You can acquire a reference to something of that sort in several ways. One would be by making a field that's exposed to the inspector and providing the reference through there.
using UnityEngine;

public class ButtonLeft : MonoBehaviour
{
    [SerializeField]
    private SpriteRenderer sprite1 = null;

    [SerializeField]
    private SpriteRenderer sprite3 = null;

    [SerializeField]
    private SpriteRenderer sprite23 = null;

    public void Click()
    {
        if (sprite23.gameObject.activeSelf)
        {
            sprite23.gameObject.SetActive(false);
            sprite3.gameObject.SetActive(true);
            sprite1.gameObject.SetActive(false);
        }
        if (sprite3.gameObject.activeSelf)
        {
            sprite23.gameObject.SetActive(false);
            sprite3.gameObject.SetActive(false);
            sprite1.gameObject.SetActive(true);
        }
        if (sprite1.gameObject.activeSelf)
        {
            sprite23.gameObject.SetActive(true);
            sprite3.gameObject.SetActive(false);
            sprite1.gameObject.SetActive(false);
        }
    }
}

How things may end up looking in the editor:

If you want to be able to drag in any game object as a reference
using UnityEngine;

public class ButtonLeft : MonoBehaviour
{
    [SerializeField]
    private GameObject sprite1 = null;

    [SerializeField]
    private GameObject sprite3 = null;

    [SerializeField]
    private GameObject sprite23 = null;

    public void Click()
    {
        if (sprite23.activeSelf)
        {
            sprite23.SetActive(false);
            sprite3.SetActive(true);
            sprite1.SetActive(false);
        }
        if (sprite3.activeSelf)
        {
            sprite23.SetActive(false);
            sprite3.SetActive(false);
            sprite1.SetActive(true);
        }
        if (sprite1.activeSelf)
        {
            sprite23.SetActive(true);
            sprite3.SetActive(false);
            sprite1.SetActive(false);
        }
    }
}


Q:

Warning: mysqli_error() expects parameter 1 to be mysqli, null given in

Warning: mysqli_error() expects parameter 1 to be mysqli, null given in error persists when am trying to upload a csv file into the database.
below is my code snippet. I don't where i could be misfiring.
<?php

class UploadFIle
{
   function __construct()
{

}
public function insertFile($filename,$tableName){
    global $db_mysqli_connection;
    $queryTruncate="TRUNCATE table ".$tableName;
    mysqli_query($db_mysqli_connection,$queryTruncate);
    $handle = fopen($filename, "r");
    $query='INSERT INTO '.$tableName.' VALUES ';

     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $limit=sizeof($data);
        $query.='(';
        $counter=0;
        while($limit>0){
            $query.="\"".$data[$counter]."\"".',';
            ++$counter;
            --$limit;
        }

        $query=rtrim($query,',');

        $query.='),';

     }
     $query=rtrim($query,',');
     mysqli_query($db_mysqli_connection,$query) or die(mysqli_error($connection).$query);

        if (mysqli_affected_rows($db_mysqli_connection)<=0) {
           // echo "\nQuery execute failed: ERRNO: (" . $mysqli->errno . ") " . $mysqli->error;
            $csvMessage = "Upload Failed <br/>" . $db_mysqli_connection->error ;
        }else{
            $csvMessage = "Upload Successful";
        }
        return $csvMessage;
        //var_dump($mysqli);
}

}
?>

A:

Look at this line:
mysqli_query($db_mysqli_connection,$query) or die(mysqli_error($connection).$query);

You are using $db_mysqli_connection to connect, but $connection to check for error. You must replace $connection with $db_mysqli_connection.


Q:

is_singular just won't work

I'm working with wp 3.9.1 and plugin Custom Content Type Manager. I'm creating my own theme. I created a custom type called "aggregato". I also use custom taxonomies. I then created a WP_query for my front-page:
$query = new WP_Query( array(
   'post_type' => array ('post', 'aggregato'),
   'cat' => '-1',
   'posts_per_page' => 12,
));

The query works, it returns 12 items of both the "post" and "aggregato" post types. Problem is that I want to format them differently. So when I use:
if ( is_singular('aggregato') ) {
    //my code
}

Nothing happens. It never enters, that condition is never return true. I don't know what to do anymore. I used is_singular(), is_single(), $query->post-type, $post->post-type. Nothing. It just does not work.
Anybody has any idea? Any pointers? Please, help!
EDIT: the point is that using the codex and looking for answetrs on the web I was always sent to that particular function. It got some time to understand that it was not my case. I think that the question I posted was very clear. I was just, very simply, wrong.

A:

I believe you are trying to check post type inside the Loop. To check the post type, try this:
global $post;
if('post' == $post->post_type ){
  // post stuff here
}
else{
  // aggregato stuff here
}

Alternatively, you can also use get_post_type() function to get post type of current post.

A:

You are misunderstanding the is_singular() condition. The first line of it's codex states

This conditional tag checks if a singular post is being displayed

The key word there is displayed. It will only return true if the page that the user is currently looking at, is a single instance of the provided post type.


Q:

Decoding h264 raw stream on Android 2.3.3

I'm trying to decode a raw h264 stream on "older" Android versions.
I've tried MediaPlayer class and does not seem to support the stream format.
I can see the stream on other Cam Viewer apps from the market, so I figure there must be a way to do it, probably using the NDK.
I've read about OpenMAX and Stagefright, but couldn't find a working example about streaming.
Could someone please point me in the right direction?
Also, I'm reading in several places about "frameworks/av/include/media/stagefright/MediaSource.h" and other sources, but they don't seem to be either in the regular SDK or the NDK.
Where is this source located? is there another sdk?
Thanks in advance.
Update: I'm receiving a rtsp connection.

A:

You should use third-party libs like android-h264-decoder which uses JNI for  increasing the performance! Also look at this lib  Intel
Update: Media codec wasn't exposed until API 16 (Android 4.1), so that won't work for a 2.3.3 device.

A:

If you wish to perform only a simple experiment to verify certain functionality, you can consider employing the command line stagefright utility. Please do consider this condition where your streaming input may not be supported.
If you wish to build a more comprehensive player pipeline, you can consider the handling for rtsp as in here or http as in here. Please note that NuCachedSource2 implementation is essential for streaming input as this provides a page cache implementation which acts as a jitter for the streaming data.
Please do note one critical point: Command line stagefright utility doesn't render to the screen. Hence, if you wish to render, you will to implement the complete playback pipeline with rendering.
On a related note, if your input is streaming input, the standard player implementation does have support for streaming inputs as can be observed here. Did you face any issues with the same?
As fadden has already pointed out, your work is made far more simpler with the introduction of MediaCodec in Android 4.x.

A:

Stagefright and OpenMAX IL were (and still are) internal components of Android. You can find the code (including MediaSource.h) at https://android.googlesource.com/platform/frameworks/av/+/master Note that the media framework has moved to a separate "tree" frameworks/av only recently. Before it was part of 'frameworks/base', e.g. https://android.googlesource.com/platform/frameworks/base/+/gingerbread/media/


Q:

Make a desaturated image transparent keeping only shadows & highlights

I've been trying to do this for a few days now and have not gotten the results I need. I'm not sure I'm using the correct terminology in the title, if not, please feel free to correct me, and I'll update it.
I want to go from this:

to this (i've sampled an area of the transparency to show the k value in case that helps). Notice the shadows/highlights are there, but nothing else:

This allows me to place a layer filled with a solid color below the transparent image. The result is a different color shirt, and shadows/highlights are seen:
layer filled with blue placed below the transparent shirt layer

layer filled with black placed below the transparent shirt layer

Does anyone have any ideas on how I might be able to accomplish this? I've been able to get close to the result, but my transparency is either not enough or too much. I lose much of the shadow/highlight detail. The starting image is of filetype JPG.
UPDATE:
I need the final result to be a PNG like this one:

This PNG looks like it has a white background but taking it into Photoshop or GIMP you'll see the shirt is transparent. I need to reverse engineer how this was done so it can be done to other pieces of clothing.
What is interesting about the above PNG is the Shadows, Highlights, and Midtones in the transparent part of the image can all be selected individually. Photoshop: Select->Color Range->Shadows, Highlights or Midtones. Image below to show what I mean:

A:

When assigning white as alpha channel for transparency we will not be able to have opaque highlights, as these per definition will be white, hence fully transparent.
To have an alpha channel sparing both highlighted white areas, and black shadows we better choose a grey color for assigning alpha.

To show the effect more clearly I first made your original image darker, and increased contrast. You will need to both, adjust the source contrast, and choose a grey level which suits your needs best for better results.

Then I assigned an alpha channel to a 'grey' color (rather than white):

Now when we overlay this picture with e.g. a green background we can see, that both highlights, and shadows are maintained.

We can see, that when used on dark colors the white areas of the original image may still be too bright for the desired effect. This can be overcome when we choose a grey rather than a white source for creating our alpha channel template.
Below (top left) I used a grey bucket fill with 20% opacity on the white original. After assigning a transparancy alpha channel to grey (top right) we can overlay a colored background (left black, middle dark red, right ivory white) to achieve the bottom line effects.

A:

For this, you best create separate channels for the shadows and highlights.
The shadows can be directly taken from the white T-Shirt, and be used as a multiplicator (0-100%) for the shirt's color (layer mode: multiply)
As for the highlights, this really depends on the material. Cloth doesn't reflect much light on the surface, so most of its color comes from diffused light (the shirt's color). To extract the specular light, I'd use a high-pass filter (histogram adaption: only the bright colors, and none of the dark colors) on the white shirt's image and use that to brighten the shirt, but only with maybe 20% (low reflection).
Layers:

Resulting images:


Q:

Pass value to an include file in php

How do you pass a parameter into an include file? I tried the following but it doesn't work.
include "myfile.php?var=123";
and in myfile.php, I try to retrieve the parameter using $_GET["var"].
include "myfile.php?var=123"; will not work. PHP searches for a file with this exact name and does not parse the parameter
for that I also did this:
include "http://MyGreatSite.com/myfile.php?var=123";but it does not also work.
Any hints? Thanks.

A:

Wrap the contents of the included file in a function (or functions). That way you can just do
include "myfile.php";
myFileFunction($var1, $var2);

A:

quick and dirty
 $var = 123;
 include "myfile.php";

in myfile just use "$var"
The same but without global variables:
  function use_my_file($param) {
      $var = $param;
      include "myfile.php";
  }

Hold on, are you trying to include the result of myfile.php, not its php code? Consider the following then
  $var = 123;
  readfile("http://MyGreatSite.com/myfile.php?var=$var"); //requires allow_url_fopen=on in php.ini

virtual might also work


Q:

Has the Doctor ever observed himself, without revealing who he was?

Also known as "Has the Doctor ever observed himself, without revealing himself to himself?"
We see that the Doctor isn't afraid to work with himself to solve complex problems, but has there been any moments where the Doctor has observed his past/future self (time travel makes things confusing) without showing off he's the Doctor?

A:

Yes, occasionally

He does this in series 1's "Father's Day", quite directly "observing himself" with Rose:

He makes a big deal of not being seen by their past selves, out of fear of paradoxes; of course Rose goes and screws all that up, but that's neither here nor there.
This is broadly the point of series 8's "Heaven Sent"; the Doctor spends billions of years helping himself without really understanding anything about his situation (not until the last moments, anyway)
This is also, essentially, the plot of series 8's "Time Heist"; the Doctor et. al. are running through a script that had been previously set up by the Doctor himself, which he can't remember (and can't remember being responsible for) thanks to a liberal application of memory worm
Yet another Capaldi example, but series 9's two-parter "Under the Lake"/"Before the Flood" has the Doctor sending himself a message through time:

Doctor: The messages my ghost gave, they weren't for you, they were for me. That list. Everyone after you was random, but you being the next name, that's what made me confront the Fisher King.
Doctor Who Series 9 Episode 4: "Before the Flood"

While it's left deliberately vague, it's possible that he serruptitiously interacts with himself in series 8's "Listen"; Clara remarks that the note left on the chalkboard, alleged (by the Doctor) to have come from his "perfect hiding" companion, is in the Doctor's own handwriting:

Clara: It looks like your handwriting.
Doctor:  Well, I couldn't have written it and forgotten, could I?
Doctor Who Series 8 Episode 4: "Listen"

This one is admittedly debateable especially since, as Clara notes with her next line, it's entirely in-character for the Doctor to have left himself a note which he then forgot about.
We might also consider the Valeyard, from season 23's "Trial of a Time Lord" arc. The Valeyard is revealed (by the Master, not by himself) to be an amalgamation of the Doctor's darker impulses, something of an in-betweeny, timey-wimey, pseudo-future-regeneration...thing:

Doctor: Just a minute! Did you call him the Doctor?
Master: There is some evil in all of us, Doctor, even you. The Valeyard is an amalgamation of the darker sides of your nature, somewhere between your twelfth and final incarnation.
Doctor Who Season 23 Episode 4: "Trial of a Time Lord: The Ultimate Foe"

The Valeyard has previously spent the entire season-long arc acting as prosecutor at the Doctor's trial, without feeling the need to reveal his identity.


Q:

Hiding a row on return value from a form in jquery/ajax

I have some data which are loaded to table via jquery/ajax. Table has a column to do delete action on each row.Actions are also done by ajax call and fadingOut the row to hide it from user.
If the user click on delete icon, a dialogbox should be appear to give the reason of removing from user, submission of form should be done by ajax too, and of course the user can cancel this dialogbox, so the row shouldn't fadeOut.
I am confused with these multiple ajax call. How can I get if the user cancel the form or submitted it to determine the need of hiding row?

A:

You can determine if the user submits or cancels the form by attaching different handlers to the click events of your submit and cancel buttons.
If the cancel button is clicked, the form will not be submitted at all (there will not be an AJAX call) because you won't need to do anything at all.
If you already have code for the dialog box with the form and the AJAX call, post the relevant parts so that we can expand further.


Q:

how to renew expired certificate with fastlane?

My iOS certificate is stored in GitHub and it is expired, the failure message in circleci progress is that ‘Your certificate 'xxxxxxx.cer' is not valid, please check end date and renew it if necessary’.
Do I need to create a new certificate, or download an existing one? I don’t remember how this was originally created, I thought it was done by Fastlane as part of the build.
But I don't know how to modify the Fastlane command, I have tried to add the 'cert', but it fails.

A:

You can use fastlane match development after deleting the development profiles and certificates from your git repo. Alternatively, you can delete everything from git repo and run fastlane match
If you do not care about existing profiles and certificates, just run fastlane match nuke development and fastlane match nuke appstore, then fastlane match development and fastlane match appstore. These commands will first delete everything from your git repo and apple developer portal and the next two commands will create everything on your apple developer portal and push them to your git repo.
Read up this


Q:

How are vectors linearly independent?

So I have these $4$ vectors (they are column vectors, but I can't put them in the right form , somebody please help)
$v_1= (1,1,0,0)$
$v_2=(1,-1,0,0)$
$v_3=(0,2,0,0)$
$v_4=(0,2,1,0)$
The professor said that only $v_1,v_2,$ and $v_4$ are linearly independent.
He remarks by saying that that $v_3 = v_1 − v_2$; since $v_1$ and $v_2$ are clearly
independent and both have $0$ as their third coordinate while $v_4$ has a non-zero third coordinate, a set of three linearly independent vectors is clearly provided by $\{v_1, v_2, v_4\}$.
I did not understand this process. Can somebody please help me understand why only $3$ vectors out of $4$ are linearly independent? Thank you!
I know that vectors are L.I. if they have only the trivial solution , but I'm not sure how to apply this here.
Please explain as simply as you can too, if that is possible.

A:

(*Since you are a new user I shall try to explain. But is best if you show in this forum what you have done so that we can guide you.)
Linear Independence: $v_1,v_2,\cdots,v_n$ are linearly independent if the only solution to the equation $a_1v_1+a_2v_2+\cdots+a_nv_n=0$ is $a_1=a_2=\cdots=a_n=0$.
So here we have $a_1v_1+a_2v_2+\cdots+a_nv_n=0 \implies a_1\begin{bmatrix}1\\1\\0\\0\end{bmatrix}+a_2\begin{bmatrix}1\\-1\\0\\0\end{bmatrix}+a_3\begin{bmatrix}0\\2\\0\\0\end{bmatrix}+a_4\begin{bmatrix}0\\2\\1\\0\end{bmatrix}=\begin{bmatrix}0\\0\\0\\0\end{bmatrix}$ which gives us four equations $$a_1+a_2=0\\a_1-a_2+2a_3+2a_4=0\\a_3=0.$$ Using $a_3=0,a_1=-a_2$ in the second equation gives you $a_3=a_4$. So we have got a non-zero solution $(-a_2,a_2,0,a_2)$ for $a_1v_1+a_2v_2+\cdots+a_4v_4=0 $. Thus the four vectors $\{a_1,a_2,a_3,a_4\}$ are liearly dependent.
You may try to show linear independence or dependence with any set of $3$ vectors from the above $4$ vectors to understand further.


Q:

How to download the Latex file of an article from arXiv.org?

It is a non-mathematical question. Math StackExchange is a not a right place to ask this question, but I don't have any other choice.
How to download the Latex file of an article from arXiv.org?

A:

It is possible, but not in all articles. You have to go to the page where the abstract is shown, click on Download -> Other Formats -> Source -> Download source.  Sometimes the source is compressed and may need unzipping.


Q:

change jqGrid options in Struts 2

Where can i change this options:
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options
in jqGrid Struts 2 plugin + Eclipse.
I need this to change the ignoreCase option.

A:

If it is not supported in tags then you can try to change it in javascript. Get jqGrid object from DOM and apply options to it.
Update
$(document).ready(function() {
  $("#id_of_element").jqGrid({
    // options here
  });
});


Q:

ASP.NET: Update ListView from CodeBehind

So there's a ListView element on my ASP.NET page that I need to be able to update from the code behind. To my understanding, Microsoft has prepared UpdatePanels and DataBindung for exactly such purpose, allowing me to "bind" the ListView's content to a property member in the code behind and promising to take care of updating the browser's view automatically (?) when the property changes.
However, only the initial load of items via GetStuff() works; I can see in the debug console that my timer keeps adding new elements to the List, but those never arrive in the browser's view. What am I missing?
In Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="myLittleProject.Default" %>
<%@ Register Src="~/StuffListItemControl.ascx" TagPrefix="stf" TagName="StuffListItem" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <!-- some irrelevant stuff -->
    </head>
    <bod>
        <form id="form1" runat="server">
            <asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>

            <!-- some irrelevant stuff -->

            <asp:UpdatePanel runat="server" ID="StuffUpdatePanel" UpdateMode="Always">
                <ContentTemplate>
                    <ul>
                        <asp:ListView ID="StuffBoundContent" runat="server">
                            <ItemTemplate>
                                <stf:StuffListItem runat="server" ID="StuffListItemControl" />
                            </ItemTemplate>
                        </asp:ListView>
                    </ul>
                </ContentTemplate>
            </asp:UpdatePanel>

            <!-- some more irrelevant stuff -->
        </form>
    </body>
</html>

And in Default.aspx.cs:
using System.Collections.Generic;
namespace myLittleProject
{
    public partial class Default : System.Web.UI.Page
    {
        public static List<Stuff> StuffContent;

        protected void Page_Load(object sender, EventArgs e)
        {
            StuffContent = Stuff.GetStuff(); // returns a list of three elements from the database

            System.Timers.Timer t = new System.Timers.Timer();
            t.Interval = 3000;
            t.Elapsed += T_Tick;
            t.Enabled = true;
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            StuffBoundContent.DataSource = StuffContent;
            StuffBoundContent.DataBind();
        }

        private void T_Tick(object sender, EventArgs e)
        {
            StuffContent.Add(new Stuff(StuffContent.Count + 1, DateTime.Now.ToShortDateString(), new string[] { "what", "ever" }));
            System.Diagnostics.Debug.WriteLine("[TIMER EVENT] StuffContent.Count = " + StuffContent.Count.ToString());
        }
    }
}

A:

System.Timers.Timer does not work with a webpage. The reason that t is disposed after the page is sent to the client. Use a Timer control if you really want to use one.
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick"></asp:Timer>

And then you can update the ListView in Timer1_Tick.
protected void Timer1_Tick(object sender, EventArgs e)
{
    //update the ListView
}

Place the Timer Control inside the UPdatePanel if you do not want a full postback when the timer is triggered.
Another thing to remember is that although you use an UpdatePanel, a complete page life cycle is triggered. So all other code you use in Page Load (and PrerRender) is executed even when only the ListView update is visible to the user. This could put a huge load on the server when an updatepanel is triggered every few seconds. Maybe better use Ajax.
PS you don't need to use Page_PreRender to bind data.


Q:

Casting smartpointers to base class

If class B derives from class A, can I dynamic_cast a shared_ptr<B> to a shared_ptr<A>, and from shared_ptr<A> to a shared_ptr<B>?
I just ask myself because with a dynamic cast you can do something like instanceof in Java. And I asked myself if this also works for smart_ptr.

A:

For the particular case of casting from a derived class to a base class, there are assignment operators available that do the necessary implicit conversion for you. For the other direction, you can use dynamic_pointer_cast.
#include <memory>

struct A { virtual ~A() = 0; };
struct B: A { };

void example()
{
    // derived to base
    std::shared_ptr<B> b;
    std::shared_ptr<A> a = b;

    // base to derived
    std::shared_ptr<A> a2;
    std::shared_ptr<B> b2 = std::dynamic_pointer_cast<B>(a2);
}

See http://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast for more info on casting operations - there are equivalents for all the usual suspects like reinterpret_pointer_cast, etc.


Q:

Twitter Bootstrap Modal Width issues

My application features many modals, all with different widths. I understand you can set the width of a modal inline by doing something like:
width: 400px
margin-left: -200px;
This works great, however if you compress your window in it'll kick the modal 50% of the screen, so you cannot see half of the modal rendering it useless at these small resolutions. At about the resolution of an iPad you can see this happen.
Now on to the issue, if in the main bootstrap.css file you set the width of the modal, only that one width works perfect. So if I set the width as 400 and margin-left -200, all modals will work at this width. But if I go ahead and do inline CSS on a modal and do for instance:
width: 900px
margin-left: -450px
It'll break at lower resolutions as described above.
What am I doing wrong? Does Twitter Bootstrap only offer the ability to make one modal width work at all resolutions?
I'd include screenshots, however the admins at StackOverflow apparently don't allow me to post these to help you guys.
Here's an example of one of the modals that will break at a lower resolutions because of doing the width inline:

    ×

New Project

    <form action="" id="add_project">
    Name

    <input type="submit" id="submitButton" class="btn submit" value="Create">
    </form>

At about the resolution of an iPad, 50% of the modal is off the screen to the left.

A:

You could use jQuery to select the modal(s) in question and edit their CSS attributes. Using the following would set the modal to 90% of screen width and position it center of the screen:
$('#myModal').modal({
            backdrop: true,
            keyboard: true,
            show: false
        }).css({
            // make width 90% of screen
           'width': function () {
               return ($(document).width() * .9) + 'px';
           },
            // center model
           'margin-left': function () {
               return -($(this).width() / 2);
           }
    });

This would work when the page loads. Resize you browser and refresh the page and the modal should be centered in the screen taking up 90% of screen width.


Q:

How is this an ascending sequence?

When my textbook was proving this lemma...

Under the assumptions of Egoroff's Theorem, for each $\eta>0$ and $\delta>0$, there is a measurable subset A of E and an index N for which $|f_n - f| < \eta$ on A for all $n \geq N$ and $m(E \sim A) < \delta$.

The textbook says that "$|f_k - f|$ is properly defined, sicne f is real-valued, and it is measurable, so that the set $\{x \in E |f(x) - f_k(x)| < \eta\}$ is measurable." And then it says that this is also measurable, $E_n = \{x \in E | |f(x)-f_k(x)|< \eta \text{for all} k \geq n \}$, since "The intersection of a countable collection of measurable sets is measurable." But then it says that the sequence $\{E_n\}^{\infty}_{n=1}$ is an ascending collection of measurable sets. This is what I'm confused about...how is it ascending? We know that as n increases, the difference between f(x) and $f_k(x)$ decreases...so isn't it supposed to be a descending sequence?
Thanks in advance

A:

Saying that a sequence of sets ${\mathbb E_n}$is ascending means that $\mathbb E_n\subset \mathbb E_{n+1}$.
Now, if $x\in \mathbb E_n$, then $|f(x)-f_k(x)|<\eta$ for all $k\geq n$. Hence $|f(x)-f_k(x)|<\eta$ for all $k\geq {n+1}$, namely, $x\in \mathbb E_{n+1}$. So the sequence is indeed ascending.


Q:

Travis cannot pull from github repository using token

I have created a github token in order to auto-deploy using travis-ci.
I'm using this token in my local environment to test it. This is what I do:
mkdir out && cd out
git init
git remote add origin https://$USERNAME:$GITHUB_TOKEN@github.com/$USERNAME/$PROJECT
git pull --all

This works like a charm in my own computer, but, when this is executed in travis the only output I get is the following:
Initialized empty Git repository in /home/travis/build/$USERNAME/$PROJECT/out/.git/
Fetching origin
remote: Not found
fatal: repository 'https://[secure]@github.com/$USERNAME/$PROJECT/' not found
error: Could not fetch origin

What am I missing?

A:

I don't know the reason, but the url must end with .git
Broken URL: https://username:token@github.com/username/project
Fixed URL..: https://username:token@github.com/username/project.git


Q:

Acceptance Testing - Check Email Received

I have some acceptance test allows a Windows service to send an email out via smtp, does anyone know of a good way to check if a email has been received via code, at present being sent to an Exchange Mail Box?
Regards
Iain

A:

Microsoft offers an SDK for Exchange. The following specifies that (in 2010 at least - since you don't mention version) you can get an XML dump of emails: http://msdn.microsoft.com/en-us/library/dd877045%28v=EXCHG.140%29.aspx


Q:

Can you push someone upwards into the air?

I'm wonder about the pushing away keywording and if it's valid to push creatures vertically. As an example lets check the monk ability.

Open Hand Technique
Starting when you choose this tradition at 3rd level, you can
manipulate your enemy's ki when you harness your own. Whenever you hit
a creature with one of the attacks granted by your Flurry of Blows,
you can impose one of the following effects on that target:

It must succeed on a Dexterity saving throw or be knocked prone.

It must make a Strength saving throw. Ir it fails, you can push it up
to 15 feet away from you.

It can't take reactions until the end of your next turn.

Q1: Can you use the second effect to push him away upward diagonal from you? if so, he takes 1d6 when falling to the ground and get prone?.
Q2: If some other mechanics claim push the creature X feet, can you push him those feet vertically? (like an uppercut kind of strike)

A:

away

is the critical word here. In plain language, the direction of motion should be along the line connecting the monk and her target, which is typically going to be horizontal (or near-enough as to not matter).
If you want to take a squat before striking and hope that "pushing away" now lifts the creature, we've got rules for that: lifting (PHB 176). But now we're squarely into rulings territory: a GM might reasonably rule that you must successfully grapple before lifting, as you're trying to impose movement. A GM might reasonably rule that you're making a shove attack, and that shoving someone 5' horizontally is physically akin to shoving them 6" upward (citation: every fight I had with my brothers as a kid). &c. &c. &c.

A:

No, to both. When you're each on the ground that's not “pushing”, that's “throwing”, and the ability to push someone doesn't grant the ability to throw them upwards. An ability that allows throwing will specify so, and give details about height as well as distance, just like the rules covering jumping do.
This agrees with an official rules answer from the designer on the subject of pushing upwards, so you don't just have to take my word for it:

@JeremyECrawford Second question: can the knock back granted by open hands flurry of blows be used to push the target vertically?

Pushing someone away requires the whole move to be away from you. A diagonal push works. Vertical doesn't. #DnD

Note that I said "ground" too: in flight and other 3D movement contexts, pushing naturally includes every direction away from you.

A:

I think it's best to start with the relevant tweet from Jeremy Crawford.

Let's tackle your questions directly.

Q1: Can you use the second effect to push him away upward diagonal from you?
  Q2: If some other mechanics claim push the creature X feet, can you push him those feet vertically? (like an uppercut kind of strike)

These are basically the same question, The answer here is clearly "no". You can't push them "diagonally upward", just "away".
And no, you can't just duck down. Halfling Monks don't get the ability to "uppercut" Medium-sized opponents just because they are shorter.

if so, he takes 1d6 when falling to the ground and get prone?

This is where things get a little complicated.
Let's say that you were on an incline and your opponent was at the top of the hill. You kick them "away" which results in them going "diagonally up". Depending on the angle, this could launch them in the air.
The PHB (183) says:

At the end of a fall, a creature takes 1d6 bludgeoning damage for every 10 feet it fell, to a maximum or 20d6. The creature lands prone, unless it avoids taking damage from the fall.

Note that damage doesn't start until the person falls 10 feet. So if you hit them 8 feet in the air, they land cleanly. For this to work for the monk, you need to be on a 60 degree angle adjacent to your target so that "15 feet away" also means 10+ feet in the air. This could work, but it's also going to be extremely rare.


Q:

MySQL query syntax and trim

I get an error on the MYSQLI query, saying that there's an error with the syntax on line 2. I've addslashed/trimmed all my variables and so commas/dots shouldn't be breaking the command. However, one issue is my file name does contain spaces, so I'm not sure if Trim is a good option since it removes the spaces, that is the second issue.
I have the following php/mysql code:
Its giving me the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO files (f_name, f_type, f_size) VALUES ('ISYF.doc', 'application/mswo' at line 2
the names you see on top are file names/file types
I have tried inputting the mysql command directly into the database, and it works, even when the filename contains spaces.. but on browser, it tells me i have a syntax error...
OK i did more tests, it appears to me the START TRANSACTION;/COMMIT; are the ones causing the issue, i highly suspect the semi-colons which they come with, anyone thinks the same way?
<?php
session_start();
 require 'config.php';
 //I'm using mysqli_ as an example, it should be PDO

$ds = DIRECTORY_SEPARATOR;
$foldername = "updatefiles/";
if (isset($_POST['update']) && isset($_POST['description']) && isset($_POST['expire']) && isset($_POST['groupid'])){
    $title=addslashes(trim($_POST['update']));
    $description=addslashes(trim($_POST['description']));
    $expire=addslashes(trim($_POST['expire']));
    $groupid=addslashes(trim($_POST['groupid']));

    $fileupload = addslashes(trim(basename( $_FILES['file']['name'])));
    $fileType = $_FILES['file']['type'];
    $fileSize = $_FILES['file']['size'];

    $tempFile = $_FILES['file']['tmp_name'];
    $targetPath = dirname( __FILE__ ) . $ds. $foldername . $ds;
    $targetFile =  $targetPath. $fileupload;
    move_uploaded_file($tempFile,$targetFile);

     $uploadsql = mysqli_query($mysqli,"START TRANSACTION;
INSERT INTO files (f_name, f_type, f_size) VALUES ('$fileupload', '$fileType', '$fileSize');
INSERT INTO posts (category, description, posttitle, userid, expire, group_id) VALUES ('updates','$description', '$title','{$_SESSION['userid']}', '$expire','$groupid' );
COMMIT;");

if (!$uploadsql) {
echo mysqli_error($mysqli);

} else {
echo"successandfile";

}

}else {
echo"formnotsubmitted";

}

?>

A:

mysqli_query() can only execute one SQL statement.  Use mysqli_multi_query() instead.
In your case here:
$uploadsql = mysqli_multi_query($mysqli,"START TRANSACTION;
INSERT INTO files (f_name, f_type, f_size) VALUES ('$fileupload', '$fileType', '$fileSize');
INSERT INTO posts (category, description, posttitle, userid, expire, group_id) VALUES ('updates','$description', '$title','{$_SESSION['userid']}', '$expire','$groupid' );
COMMIT;");

Although, I would tend to split this up to catch errors and roll the transaction back.  That is the whole point of transactions.


Q:

How do I write a Capybara assertion that checks for the presence of a button and its enabled or disabled state?

I have an app that enables/disables buttons in response to things that happen in the UI.
I can easily use capybara to detect if a button exists
should have_button 'save'

but I have no idea how to verify the state of the save button.  That is:
How do I write a Capybara assertion that checks for the presence of a button and its enabled or disabled state?
I have hacked together a check for a disabled button; for enabled, I suppose that I could verify that there is a matching button and that there is no matching disabled button.  But this, to say the least, is clunky.
This seems like such a fundamental UI check, that I am sure that I have missed something, but I can't seem to figure out what.

Follow up based on gregates's answer:
As I mentioned in the comment, the Capybara behavior is dependent upon the underlying driver. We are using webkit, and it returns "true"/"false" string results. Apparently, other drivers return true/false.  The folks at Capybara are aware of the issue (github.com/jnicklas/capybara/issues/705), but they feel (probably correctly) that it isn't really their issue to resolve.
Rather than have my tests depend upon the driver I am using, I ended up creating a custom matcher:
RSpec::Matchers.define :be_enabled do
  match do |actual|
    driver_result = actual[:disabled]
    # nil, false, or "false" will all satisfy this matcher
    (driver_result.nil? || driver_result == false || driver_result == "false").should be_true
  end
end

RSpec::Matchers.define :be_disabled do
  match do |actual|
    driver_result = actual[:disabled]
    (driver_result == "disabled" || driver_result == true || driver_result == "true").should be_true
  end
end

Then you can type:
user_license_area.find_button('Save').should be_disabled

A:

It appears that Capybara's handling of disabled elements has changed, so I figured I'd give an update.
To test whether a page has a button and is enabled, use:
expect(page).to have_button('Save')

To test whether a page has a button and is disabled, use:
expect(page).to have_button('Save', disabled: true)

This format works with has_field?, find_field, etc.
You can read more on this update at http://www.elabs.se/tag/capybara
UPDATE
The old link is broken. This is the GitHub issue where the feature was discussed and this is the unfortunately barren documentation for the method.

A:

find_button('save')[:disabled].should eq "disabled"

Note that one line will effectively test for both existence and disabled state.
Edit: for enabled, try
find_button('save')[:disabled].should_not be

(Either of these tests may need to be tweaked depending on precisely how you disable/enable the button.)

A:

There is be_disabled check
it "allows finding elements and checking if they are disabled" do
  expect(string.find('//form/input[@name="bleh"]')).to be_disabled
  expect(string.find('//form/input[@name="meh"]')).not_to be_disabled
end

https://github.com/jnicklas/capybara/blob/2a51b817b355f6c1a5e95a471a87f1a492562e55/spec/basic_node_spec.rb#L108


Q:

Mysql subquery COUNT in same Table returns NULL

I have this MySQL table and I want to update multiple columns ( children, size) using COUNT() and SUM() on same table.
mytable
id  parentid  name      userid   path    children   privatesize    size
=======================================================================
1   0         Test-1    1        NULL      5        20             125
2   0         Test-2    1        NULL      0        15             15
3   1         Test-3    1        /1/       3        25             75
4   1         Test-4    1        /1/       0        30             30
5   3         Test-5    1        /1/3/     0        10             10
6   3         Test-6    1        /1/3/     1        30             40
7   6         Test-7    1        /1/3/6/   0        10             10
8   0         Test-8    2        NULL      0        20             20

Notes:
size = privatesize + children privatesize
NULL = "", just for demonstration
Let's update for now just one column, children column.
Right now I use MySQL stored functions to calculate children:
DELIMITER $$

CREATE DEFINER=`dbuser`@`localhost`
FUNCTION `getchildren`( rowid INT, uid INT ) RETURNS INT(11)

BEGIN

DECLARE children    INT DEFAULT 0;

SELECT COUNT( `mytable`.`id` ) INTO children
FROM `dbname`.`mytable`
WHERE `mytable`.`path` LIKE CONCAT( '%/',rowid ,'/%' ) AND `mytable`.`userid` = uid;

RETURN  children;
END

Test function getchildren:
SELECT dbname.getchildren( 1, 1 );

This returns number 5
To update rows ( Example id 2 and 5 ) I use this query:
UPDATE `dbname`.`mytable`
SET `children` = getchildren( `mytable`.`id` , `mytable`.`userid` )
WHERE `mytable`.`id` IN ( 2, 5 )

And works correctly.
But I don't want to use functions because later I need to update multiple columns (example: size ) and I don't want to call functions for every columns.
For that I have tried this query:
UPDATE `dbname`.`mytable` mt
INNER JOIN  (
        SELECT `mytable`.`path` AS path, COUNT( `mytable`.`id`)  AS countid
        FROM `dbname`.`mytable`
        GROUP BY `mytable`.`userid`
        ) sub ON  `sub`.`path` LIKE CONCAT( "%/", `mt`.`id` , "/%" )
SET `mt`.`children` = `sub`.`countid`
WHERE `mt`.`id` IN ( 2, 5 );

In fact without success, this change the value of children to NULL.
Even the same method (using the same subquery logic) doesn't work in SELECT, returns NULL or returns multiple rows (with correct count for each group) if I change GROUP BY: id or to path.
It looks like COUNT() doesn't work like usual on subquery.
What I'm missing in this query? Can someone explain what really cause this behavior or I'm wrong at all?
Online SELECT Test
Thanks.

A:

After trying many times I'm stuck with a simple "trick" and I will post here. I'm not happy with my solution but at last it works. I'm using User Defined Variables as a way to "return" from User Defined Function multiple variables (INT Variables).
getchildren( rowid, userid) function:
DELIMITER $$

CREATE DEFINER=`dbuser`@`localhost`
FUNCTION `getchildren`( rowid INT, uid INT ) RETURNS INT(11)

BEGIN

DECLARE children    INT DEFAULT 0;
SET @childrensize := 0;

SELECT
    COUNT( `mytable`.`id` ),
    SUM( `mytable`.`privatesize` )
INTO children, @childrensize

FROM `dbname`.`mytable`
WHERE
    `mytable`.`path` LIKE CONCAT( '%/',rowid ,'/%' )
    AND `mytable`.`userid` = uid;

RETURN  children;
END

Test New Function:
SELECT `dbname`.getchildren( 1, 1 ) AS children, @childrensize AS size;

This returns:
Children   size
===============
5          105

Now let's update rows with id 2 and 5 (both children and size)
UPDATE `dbname`.`mytable`
SET
    `children` = getchildren( `mytable`.`id`, `mytable`.`userid` ),
    `size` = `privatesize` + IFNULL( @childrensize, 0 )
WHERE `mytable`.`id` IN ( 2, 5 )

And works correctly!
The logic is simple, each time the function getchildren is called he updates user defined variable @childrensize. If the row has no children the function set @childrensize to NULL, for that IFNULL( @childrensize, 0 ) is necessary.
In this way, the function will called one time for each row and update multiple columns.
UPDATES:
Here is the right solution for this case:
UPDATE `dbname`.`mytable` mt
LEFT JOIN (
    SELECT  `mtc1`.`id`, count(*) numchildren, sum( `mtc2`.`privatesize` ) AS tsize
    FROM `tsdata`.`mytable` mtc1, `tsdata`.`mytable` mtc2
    WHERE `mtc2`.`path` LIKE CONCAT( '%/',mtc1.id,'/%' )
    GROUP by `mtc1`.id)
mtc ON `mtc`.`id` = `mt`.`id`

SET
    `mt`.`children`= IFNULL( `mtc`.numchildren, 0 ),
    `mt`.`size` = `mt`.`privatesize` + IFNULL( `mtc`.tsize, 0 )
WHERE `mt`.`id`  in ( 2, 5 );

The performance is almost 40% higher than using function (On the method above)


Q:

Is this safe across threads?

I have some code that looks like this:
Thread 0:
CMyOtherClass *m_myclass;

CMyClass::SomeFunc(DWORD SomeParam)
{

m_myclass = new CMyOtherClass(SomeParam);

}

Thread 1:
CMyClass::InsideSecondThread()
{

   MySecondThreadFunc(*m_myclass);

}

CMyClass::MySecondThreadFunc(MyOtherClass& myclass)
{

// do something with myclass variable....
// What about thread safety???  Is this not now a shared variable?
// or have we passed a copy and are we safe?
// SomeParam should be the same while in this thread, however it can be changed by Thread 0

}

So my question is, if you are passing this m_myclass variable across threads, is this threadsafe or not?

A:

It is not threadsafe.


Q:

Trying to run Specflow tests but error returned - Unit Test Provider already specified

I've been looking at similar questions on different websites in the hope I could find an answer for it but I've not come across something which has worked for me.
I have a Visual Studio 2019 solution (.Net Framework) which contains Specflow related tests. I can see all my tests in the Test Explorer but when I try to run any of them, I am returned with the error 'Unit test provider already specified'. My test runner was initially Specflow.SpecRun but I have since removed all references to this and am now using Specflow.MsTest - this is to allow me to associate my test cases to one in Azure DevOps. Only after making this change, I am getting these errors.
I have searched across my solution and there are no longer any references to SpecRun; there are no build errors either. The 'Enable SpecflowSingleFileGenerator' setting is set to False, I do have an app.config file but do not have a specflow.json file - I read that that is only needed for .NET Core projects.
Has anyone else come across the above or have any ideas to resolving it as I am a bit stuck.

A:

I was having this problem when I moved from nUnit to MsTest. I want to add few more steps to comments mentioned

Check your feature.cs files and make sure it has onlyMicrosoft.VisualStudio.TestTools.UnitTesting attributes and not nUnit or specrun
Check whether you are using any local.testsettings file in visual studio
Remove nUnit from tools and extensions if you are not using it.
Restart VS, clear temp folder, clean and rebuild


Q:

Mac OSX: MySQL gem install fail (RoR)

I'm running OSX 10.7 (Lion), and recently uninstalled MacPorts because MySQL failed to start. MySQL (64-bit) is now starting, but now I can't install the MySQL gem (Rails). I've tried using the with-mysql-config and the ARCHFLAGS option, neither of which worked. I tried reinstalling Ruby 1.9.3, which also didn't change anything. I'm currently running MySQL 5.1.61 after I thought MySQL 5.0.95 might be causing an issue. Here is the traceback:
Christy$ gem install mysql2
Building native extensions.  This could take a while...
ERROR:  Error installing mysql2:
    ERROR: Failed to build gem native extension.

    /Users/Christy/.rvm/rubies/ruby-1.9.3-p0/bin/ruby extconf.rb
checking for rb_thread_blocking_region()... yes
checking for rb_wait_for_single_fd()... yes
checking for mysql.h... yes
checking for errmsg.h... yes
checking for mysqld_error.h... yes
creating Makefile

make
compiling client.c
client.c: In function ‘rb_raise_mysql2_error’:
client.c:98: warning: ISO C90 forbids mixed declarations and code
client.c: In function ‘rb_mysql_client_socket’:
client.c:590: warning: ISO C90 forbids mixed declarations and code
compiling mysql2_ext.c
compiling result.c
linking shared-object mysql2/mysql2.bundle
ld: file not found: /opt/local/lib/libssl.1.0.0.dylib for architecture x86_64
collect2: ld returned 1 exit status
make: *** [mysql2.bundle] Error 1

I tried reinstalling openssl (thinking that file not found: /opt/local/lib/libssl.1.0.0.dylib might be because of that), but it still doesn't work. I'm kind of new to this, so any help would be much appreciated! Thank you!
EDIT: /opt/local/lib/ does not exist. I don't know why it's looking there for the file. Any ideas on how to point it to the right place (locate libssl points to /usr/lib/libssl.0.9.8.dylib and /usr/local/Cellar/openssl/0.9.8s/lib/libssl.0.9.8.dylib, among other places)?

A:

LD_LIBRARY_PATH has a bad path in it. Can temporarily set it for that shell by running export LD_LIBRARY_PATH=/usr/local/lib:/usr/lib ; gem install mysql2.
However, might suggest adding the definition to your .bashrc (or other appropriate .shellrc file) export LD_LIBRARY_PATH=/usr/local/lib:/usr/lib so all shells get it.


Q:

single slit diffraction numerical simulation

I'm trying to simulate the Fraunhoffer diffraction at slits(single,double,triple) with Mathematica.
In the picture, the red one is analytical result and the green one is numerical result.

The question is, why does it oscilate on the numerical result?
Or does it occurs in reality? If so, what is the mechanism or principle of the occurrence of the oscillation even though the analytic solution is smooth?
The mathematica source file is here.
source file
The slit size is 50um.
I don't think it is the sampling problem, because when I changed the sampling number 500 to 5000, the oscillation was still exist.

A:

I believe that the problem is the Nyquist limit.  You are representing the slit as sampled array of zeros and ones.  The bandwidth of the edge is infinite so at any sample interval you will be undersampled.
To see this effect in one dimension, consider the following code, which models the slit in much the way you have done, then upsamples it to give an impression of the underlying fully-sampled signal.
slit = Table[If[Abs[t] < 10, 1, 0], {t, -100, 99}];
spec = Fourier[slit] // Chop;
upslit = InverseFourier[Join[Take[spec, 100], Table[0, {1400}], Take[spec, -100]]];
ListLinePlot[Re[upslit], PlotRange -> All]

The oscillations shown here may well explain the oscillations seen in your final result.  [Note: the phase of upslit is not right, but I hope it gets the message across]
You might get round the problem by fudging some sort of taper on the edge of the slit.


Q:

Core pressure of sphere of fluid in a vacuum

Suppose that we have some known fluid floating in space with no outside gravitational forces. How would we calculate the pressure of the outside fluid on acting on the "core" of the fluid (in other words, the gravitational force the sphere of fluid is exerting on itself)? (This would also assume that the fluid would not evaporate, boil, or change state in general.)

A:

Assuming the fluid forms a sphere of radius $R$ and is incompressible with constant density $\rho$, we could calculate the pressure it exerts on a smaller sphere of radius $r_1$ by first getting the weight of the fluid above this smaller sphere as follows:
$$W=\int_0^{\pi}\int_0^{2\pi}\int_{r_1}^R\dfrac{G(\rho*\dfrac{4}{3}\pi r^3)}{r^2}\rho r^2\sin(\zeta)dr d\theta d\zeta$$
Where $\dfrac{G(\rho*\dfrac{4}{3}\pi r^3)}{r^2}$ is the strength of the gravitational field at the radius of interest (taking into account the matter inside the sphere of radius of interest). Also, $\rho dV = \rho r^2\sin(\zeta)dr d\theta d\zeta$ in spherical coordinates and constitutes the mass of the portion of mass immediately above the radius of interest.
Solving this integral yields $W=\dfrac{4}{3}\pi ^2 G\rho ^2 (R^4-r_1^4)$ and then the pressure would be the weight divided by the surface area of the sphere of radius $r_1$ $$P=\dfrac{\pi}{3r_1^2} G\rho ^2 (R^4-r_1^4)$$
As you can see, taking the limit when $r_1 \rightarrow 0$, we have $P \rightarrow \infty$ and that is because the area of this sphere becomes infinitely small.


Q:

Save a http request in a variable

I have manage to get an API working for a product I have started to use, I can successfully run the below code and update a record in the api's database (I have removed all the api's soap xml code to make it look cleaner), I am trying to save the output as a variable so i can then process it in php,
I am a beginner to Javascript but I cant find much help on saving the output.
If someone could point me in the right direction I would be forever grateful,
I just need to console.log output in a variable rather than in the console.

var https = require("https");
var xml =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">' +
'<soap:Header>' +
'</soap:Header>' +
'<soap:Body>' +
'</soap:Body>' +
'</soap:Envelope>';
var username = "";
var password = "";

var options = {
    host: "",
    port: 443,
    method: "POST",
    path: "",
    // authentication headers
    headers: {
        'Content-Type': "text/xml; charset=utf-8",
        'Content-Length': Buffer.byteLength(xml),
        'Authorization': "Basic " + new Buffer(username + ":" + password).toString("base64"),
        'SOAPAction': "",
        'Accept': "application/json"
    }
};
//The call
request = https.request(options, function (res) {
    console.log("statusCode:", res.statusCode);

    res.on("data", (d) => {
        process.stdout.write(d);
    });
});

request.on("error", (e) => {
    console.error(e);
});

request.end(xml);

A:

If you want to save the output, then you need to save the data from the variable that contains the output (which you have called d).
console.log("statusCode:", res.statusCode);

var data = "";

res.on("data", (d) => {
    data += d;
});

res.on("end", x => {
    // data is now ready
});

Note that you will probably run into the issue described in this question and you would probably be better off using an HTTP client library that natively supported promises, such as Axios.


Q:

Link error on compiling ghc 7.10.3 on SLES11

I want to compile ghc 7.10.3 on a SLES11 instance since the downloaded binary doesn't work. Now I am getting link errors in the end:
/home/oswald/build/ghc-7.10.3/libraries/ghc-prim/dist-install/build/libHSghc-prim-0.4.0.0-8TmvWUcS1U1IKHT0levwg3-ghc7.10.3.so: undefined reference to `__sync_val_compare_and_swap_2'
/home/oswald/build/ghc-7.10.3/libraries/ghc-prim/dist-install/build/libHSghc-prim-0.4.0.0-8TmvWUcS1U1IKHT0levwg3-ghc7.10.3.so: undefined reference to `__sync_fetch_and_nand_2'

with a lot lines more. These seem to be GCC primitives. The installed gcc version on this machine is 4.3.4, which has primitives, but I did not find the _2 and _1 endings in the documentation (it uses variable arguments list as I understand it).
Any idea on how to solve this?

A:

Ok, so I did install a newer gcc (4.9.3) locally and then the compilation of ghc was successful.


Q:

What is the best word or phrase for expressing that 2 skills are unrelated to each other?

I'm trying to find a word or phrase for describing a situation where learning one skill doesn't help you in another area.
My instinct was to use parallel or perpendicular, but I'm not actually sure which would be right, which indicates to me that neither actually conveys the meaning I want.  I could use "unrelated", but thats not as descriptive as I would like, especially since the skills may be "related" in some way that isn't "how they're learned".
Basically I want to say something like "Software development skills are <???> to engineering management skills.  Learning one doesn't help you learn the other."

A:

When factors are independent, they can be called orthogonal, fancy for a 90-degree relationship (right angled). They don't feed each other, they don't interact, they don't conflict.

Statistically independent:  mental ability may be classified into several orthogonal … factors — O. D. Duncan - Merriam-Webster dictionary online

Use this word abstractly when you want to say "I'm not fighting you. Our opinions differ, that's all. They're orthogonal."

A:

Nontransferable

Software development skills are nontransferable to engineering management skills.

It beats variations on the unrelated word you already rejected by speaking directly to the idea that the knowledge or skills of one are not transferred to or shared by the other.
This word/idea of transfer is common in sports skill training and is applicable here.

A:

You may also use the term "independent".

Independent
[in-di-pen-duh nt]
/adjective

not dependent; not depending or contingent upon something else for existence, operation, etc.

Source: Dictionary.com

This term may be best used when you are talking about how the separate skill sets are each exclusive from the other. You can acquire one, the other, or both. There is no collaborative value that increases either skill set themselves, nor is the cumulative value greater than the sum of each skill sets own value.
Some things are related, but can still be independent. Therefore, the term independent is useful in that it is less focused on the relational similarity of the subject matter and more to do with how they interact.

"Software development skills and engineering management skills are independent of each other..."


Q:

How C compiler interpret this program?

I have following program
struct test
{
int length;
union
{
    struct
    {
        int pid_test;
        int age;
    }_testing1;

    struct
    {
        int pid_test;
        int age;
    }_testing2;
}_un;
};

#define pid_test _un._testing1.pid_test
int main()
{
{
    struct test *pOBJ = (struct test *)malloc( sizeof(struct test) );
    pOBJ->_un._testing2.pid_test = 1;
    free(pOBJ);
}
}

When I run it, it gives me following error
error: ‘struct <anonymous>’ has no member named ‘_un’

When I changed the code in the following way, it works fine.
pOBJ->pid_test = 1;

I don't know how compiler interpret the above mentioned code.
Any help would be highly appreciated

A:

When you have that pid_test macro defined,
pOBJ->_un._testing2.pid_test

expands to
pOBJ->_un._testing2._un._testing1.pid_test

I'm sure you can spot the problem.


Q:

R: How to return the exact form of `...` in `fn(...)` without evaluating `...`?

Consider this code
fn = function(...) {
  # print the content of ... without evaluation?
}

I want the output of fn(a = b) to be "a = b" and fn(a = gn(b), 3~b~a, dd, e = 2 + f, h = hn(jn(cdf))) to be list("a=gn(b)", "3~b~a", "dd", "e=2+f", "h= hn(jn(cdf)))".
I can't seem to find the right NSE function for it. I prefer Base R so I understand the process better. The closest I got was this
fn = function(...) {
   res = rlang::enexprs(...)
   paste0(names(res), ifelse(names(res)=="",names(res) , "=") , sapply(res, capture.output))
}

A:

An alternative to match.call (see here) is the undocumented ...().
fn <- function(...) {
  x <- substitute(...())
  y <- ifelse(nchar(names(x)) > 0, paste(names(x), "=", x), as.character(x))
  as.list(y)
}

fn(a = b)
fn(a = gn(b), 3~b~a, dd, e = 2 + f, h = hn(jn(cdf)))

A:

You can use match.call :
fn = function(...) {
  temp <- as.list(match.call())[-1]
  as.list(sub('^=', '', paste0(names(temp), '=', temp)))
}

fn(a = b)
#[[1]]
#[1] "a=b"

fn(a = gn(b), 3~b~a, dd, e = 2 + f, h = hn(jn(cdf)))
#[[1]]
#[1] "a=gn(b)"

#[[2]]
#[1] "3 ~ b ~ a"

#[[3]]
#[1] "dd"

#[[4]]
#[1] "e=2 + f"

#[[5]]
#[1] "h=hn(jn(cdf))"


Q:

Background update via PHP?

I don't know if it is possible only with PHP but thought will ask here...
I do have a PHP code which updates data every 15 days. my problem is when it updates the entire process taking more than 5 seconds so user must wait until the updates done.
what I am looking is I want to do an background update while user is viewing the content. or after web page is loaded then show updating blinking text on it.
my current code is given below:-
$result = $db->sql_query("SELECT * FROM data1,data2,data3,data4 WHERE person='" .$name. "'");

$row = $db->sql_fetchrow($result);
$day = $row['regtime'];
$days = (strtotime(date("Y-m-d")) - strtotime($row['regtime'])) / (60 * 60 * 24);
if($row > 0 && $days < 15){

$row = ['name'];
$row = ['age'];
$row = ['place'];
$row = ['address'];
$row = ['lat'];
$row = ['long'];
$row = ['geo'];
//etc
}else{ //do update
//insert into database
}

A:

ok mathew,
the assumption here is that you've got an empty div on the page with an id=myStatusDiv. also, it assumes that you've got a url/php file /home/longprocess. add jquery to the page and then at the foot of the page, add the following:
<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            type: 'POST',
            data: "username=" + $("#username").val(),
            url: 'longprocess.php',
            beforeSend: function() {
                // you could also put a spinner img or whatever here too..
                $("#myStatusDiv").html("please wait, page being updated...");
            },
            success: function(result) {
                $("#myStatusDiv").html(result);
            }
        });
    });
</script>

basically, when the dom has loaded, the $.ajax function will silently run in the backgound. on completion, the myStatusDiv div will get populted with whatever status message you have generated from your longprocess method. this could be anything from a simple message to an 'almost' entire section on the page. your php page would only have to search for the named parameters sent via the data object - i.e. in the above example -> $name = $_POST['username'];
there are lots of examples on the net and here in SO.
good luck (hint: search google for 'php ajax jquery $_POST') ;)
jim
[edit] - of course, you'll have to include your $_POST variables in the $,ajax method... I've made an assumption that you've got a textbox input with an id=username. there again are plenty of examples, but here's a quick one i found to get you going: http://www.talkphp.com/vbarticles.php?do=article&articleid=58&title=simple-ajax-with-jquery


Q:

Is there any way to access an element of the resulting array directly after calling explode() function in PHP?

Possible Duplicate:
Interpreting return value of function directly as an array

Is there any way to access an element of the resulting array directly after calling explode() function in PHP?
e.g.:
echo explode('-', 'a-b-c')[1];

would return b

A:

There currently is no support for this in PHP. I believe PHP 5.4 (which is in BETA testing right now) is going to support this though.
for now you would just have to break it in two lines:
$arr = explode('-', 'a-b-c');
$arr[1]


Q:

CameraPreviewImageSource.StartPreviewAsync doesn't work with videoEncodingProperties

I'm using CameraPreviewImageSource.PreviewFrameAvailable event to determine flashes by calculating average luminosity of each frame.
For my purposes I don't need big frames, but with default settings StartPreviewAsync() method generates frames with size 1280*720px.
I tried to use StartPreviewAsync(videoEncodingProperties) but every time I get an exception HRESULT:0x80040155 Interface not registered.
I can set preview frame size through underlying VideoDeviceController object, but it looks overcomplicated a bit, especially concerning that I have to set properties in a magically determined sequence (otherway the camera will be broken after exiting from the app).

await App.CameraPreviewImageSource.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, _previewProperties);
var properties = await App.CameraPreviewImageSource.StartPreviewAsync();
properties.Width = _previewProperties.Width;
properties.Height = _previewProperties.Height;

Am I doing something wrong or StartPreviewAsync(videoEncodingProperties) method in SDK simply doesn't work at all?

A:

Well, "right" sequence of commands solves the problem:

var properties = await App.CameraPreviewImageSource.StartPreviewAsync();
await App.CameraPreviewImageSource.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, _previewProperties);
properties.Width = _previewProperties.Width;
properties.Height = _previewProperties.Height;