text:
Q: How to get past wave 10 in the pumpkin moon? I need to beat the pumpkin moon to get the bat scepter and horseman's blade. i get stuck on mourning woods mostly. pumpkings are easy.

*

*Armor: Beetle armor with the shell variant

*Accessories:

*

*Obsidian sheild(Warding)

*Fire gauntlet (Wild)

*Warrior emblem (Violent)

*Hover board (Warding)

*Destroyer Emblem (Wild)

*star veil (Warding)

*Weapons:

*

*legendary terra blade

*superior vampire knives

My arena has 172 spiky ball traps 32 flame traps 23 spear traps and a heart lantern and campfire. All rigged to a one second timer. Any suggestions?

A: Hmmm.
Terra Blade is actually not that good on the pumpkin moon. Too many enemies. Instead, use something that can get like 10-20 at once like the Shadowbeam Staff (if your arena has a roof).
Get an Ankh Shield, those are really good.
Use Cholorophyte arrows, they bounce and do bad stuff to all the enemies.


text:
Q: Changing org.eclipse.swt.widgets background color in Windows Right now I am trying to change the background color of a org.eclipse.swt.widgets.Button with the following code:

    Button sceneButton = new Button(border, SWT.TOGGLE | SWT.FLAT);
    sceneButton.setBackground(Color.RED);

This works fine when I run the program in Solaris, but does nothing when I run the code in Windows. Is this possible? If not, is there some kind of workaround that would allow me to change the background color (even if the "color" is an image) while still displaying text in the button? Thanks!

A: You can't. In the documentation of method Control.setBackground(), it is mentioned:
For example, on Windows the background of a Button cannot be changed.

A: The background of a button in Windows is set from outside of SWT.
Right-click your desktop, click Properties.
Go to the "Appearance" tab.
Click "Advanced".
I believe "3D objects" determines the button background.  This is determined by each user's theme.

One great thing about SWT is it uses the underlying system widgets and themes.  A frustrating thing about SWT is it uses the underlying system widgets and themes.

A: You can simulate a button using CLabel. Add a mouselistener to change the background on mouse down and mouse up, and in the mouse up event dispatch a selection listener event so that it behaves the same as a button. For example:
Color bg = ...
Color shadow = ...
CLabel simulatedButton = new CLabel(parent, SWT.PUSH);
simulatedButton.setBackground(bg);
simulatedButton.addMouseListener(new MouseAdapter() {

  @Override
  public void mouseUp(MouseEvent e) {
    simulatedButton.setBackground(bg);
    notifyListeners(SWT.Selection, new Event());
  }

  @Override
  public void mouseDown(MouseEvent e) {
    simulatedButton.setBackground(shadow);
  }
});

This briefly changes the background of the button while you are pressing the mouse to give the effect of clicking a button. CLabel can also be extended, unlike other SWT widgets, so you can create a subclass if you need to do this often.

A: On windows operating systems button.setBackGround doesn't work directly. A small snippet of code can help. Override the paint event of button as shown below:-
-----obj is button name in below snippet------------
obj.addPaintListener(new PaintListener() {
@Override
    public void paintControl(PaintEvent arg0) {
    // TODO Auto-generated method stub
    obj.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
    org.eclipse.swt.graphics.Pattern pattern;
    pattern = new org.eclipse.swt.graphics.Pattern(arg0.gc.getDevice(), 0,0,0,100, arg0.gc.getDevice().getSystemColor(SWT.COLOR_GRAY),230, arg0.gc.getDevice().getSystemColor(SWT.COLOR_BLACK),230);
    arg0.gc.setBackgroundPattern(pattern);
    arg0.gc.fillGradientRectangle(0, 0, obj.getBounds().width, obj.getBounds().height, true);
    }
});

A: No You cannot change the Background of a Button is SWT. You can find this information in Eclipse SWT documentation.
Eclipse SWT Documentation Button
public void setBackground(Color color)

Sets the receiver's background color to the color specified by the argument, or to the default system color for the control if the argument is null.
Note: This operation is a hint and may be overridden by the platform. For example, on Windows the background of a Button cannot be changed.

A: Could it be that the last change in SWT for Windows has changed this? I left the RED background in the code and I have changed the SWT library to the latest and now the background color is changing.

A: btnNewButton.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLUE));

You can change the background color for a button in SWT for windows with the above code.
Few prerequisites should be to:

*

*Use these two SWT jars :org.eclipse.swt.win32.win32.x86_64_3.109.0.v20181204-1801.jar and org.eclipse.swt_3.109.0.v20181204-1801.jar. (109 version)

*Import org.eclipse.wb.swt.SWTResourceManager
You can also try latest versions of jars but it worked for me with this.
Usually, you can go to advanced properties panel in windows builder to set background but it does not reflect color at runtime.With this, that problem should go away.

redpajama_set_name: RedPajamaStackExchange


text:
Q: converting c++ class to an equivalent java class Suppose I have a constructor in c++ as:
public class Machine {
public:
 Machine(int boltCount, bool failure=false);
};

How do I convert this to an equivalent class in Java?
Thanks,

A: something like that
public class Machine {
   public Machine(int boltCount) { this(boltCount, false); }
   public Machine(int boltCount, bool failure) { /*body here*/ }
};

A: You would have to use constructor chaining, as Java does not have default values for parameters:
public class Machine {
    Machine(int boltCount) {
        this(boltCount, false);
    }

    Machine(int boltCount, boolean failure) {
        // constructor logic
    }
}


text:
Q: I want to merge 4 pictures together in Java I'm struggling to understand how to merge 4 pictures together in java, I want to copy each image to the merged image with the overlapping 20 pixels blended in a 50% merge. To give the merged image a 20 pixel boundary that is a blend of the appropriate portion of each image.
So a 4 image box with the images blended into each other by 20 pixels.  Not sure how I should use the width and height of the images as it is very confusing.
Something like this.  How to do it?

A: I got all of my info from: AlphaComposite, Compositing Graphics, Concatenating Images.
The following program is improved. It uses two methods: joinHorizontal and joinVertical to join the images. Inside the methods, the following happens

*

*the second image is copied, but only the part that overlaps

*the copied image is set at half alpha (transparency)

*on the canvas of the 'return image', the first image is painted, followed by the second without the overlapping part

*the copied image is painted onto the canvas.

*the image is returned

Why do I only set one image at half alpha and not both?
Picture a clear, glass window:

Paint random points red so that half of the window is covered with red. Now, treat the window with the red dots as your new canvas.

Paint random points blue so that the new "canvas" is half covered with blue. The window won't be completely covered; you will still be able to see through it.

But let's imagine that we first painted the window red, and then painted half of it blue. Now, it will be half blue and half red, but not transparent at all.
public class ImageMerger {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        BufferedImage img1 = //some code here
        BufferedImage img2 = //some code here
        BufferedImage img3 = //some code here
        BufferedImage img4 = //some code here

        int mergeWidth = 20; // pixels to merge.
        BufferedImage merge =  ImageMerger.joinVertical(
                ImageMerger.joinHorizontal(img1, img2, mergeWidth),
                ImageMerger.joinHorizontal(img3, img4, mergeWidth),mergeWidth);

        //do whatever you want with merge. gets here in about 75 milliseconds

    }

    public static BufferedImage joinHorizontal(BufferedImage i1, BufferedImage i2, int mergeWidth){
        if (i1.getHeight() != i2.getHeight()) throw new IllegalArgumentException("Images i1 and i2 are not the same height");

        BufferedImage imgClone = new BufferedImage(mergeWidth, i2.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D cloneG = imgClone.createGraphics();
        cloneG.drawImage(i2, 0, 0, null);
        cloneG.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN, 0.5f));
        cloneG.drawImage(i2, 0, 0, null);

        BufferedImage result = new BufferedImage(i1.getWidth() + i2.getWidth()
                - mergeWidth, i1.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = result.createGraphics();
        g.drawImage(i1, 0, 0, null);
        g.drawImage(i2.getSubimage(mergeWidth, 0, i2.getWidth() - mergeWidth,
                i2.getHeight()), i1.getWidth(), 0, null);
        g.drawImage(imgClone, i1.getWidth() - mergeWidth, 0, null);

        return result;
    }
    public static BufferedImage joinVertical(BufferedImage i1, BufferedImage i2, int mergeWidth){
        if (i1.getWidth() != i2.getWidth()) throw new IllegalArgumentException("Images i1 and i2 are not the same width");

        BufferedImage imgClone = new BufferedImage(i2.getWidth(), mergeWidth, BufferedImage.TYPE_INT_ARGB);
        Graphics2D cloneG = imgClone.createGraphics();
        cloneG.drawImage(i2, 0, 0, null);
        cloneG.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN, 0.5f));
        cloneG.drawImage(i2, 0, 0, null);

        BufferedImage result = new BufferedImage(i1.getWidth(),
                i1.getHeight() + i2.getHeight() - mergeWidth, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = result.createGraphics();
        g.drawImage(i1, 0, 0, null);
        g.drawImage(i2.getSubimage(0, mergeWidth, i2.getWidth(),
                i2.getHeight() - mergeWidth), 0, i1.getHeight(), null);
        g.drawImage(imgClone, 0, i1.getHeight() - mergeWidth, null);

        return result;
    }

}


text:
Q: How to clip image in css3 and html5 I want to clip image from left and right side with some degree of angle. i have used crip css. but in that i am able to clip in 90 degree only
img
{
position:absolute;
clip:rect(0px,60px,200px,0px);
}

is it possible to clip image by 30 degre or more on left and right side.

A: You can use a css mask, with an image of a rectangle, or with some gradient which looks like a rectangle.
But the more performant way would be to use a wrapping Div, and simply rotate the image inside the div using transform while giving overflow:hidden to your div. something like that http://jsfiddle.net/gK3XL/
img {
    -webkit-transform : rotate(45deg);
    margin: -30px;
}
div {
    -webkit-transform : rotate(-45deg);
    width: 100px;
    height: 100px;
    overflow: hidden;
}

A: What about matrix transforms?
HTML:

CSS:
body {
  background: black;
}

.container {
  width: 540px;
  margin: 0 auto;
  overflow: hidden;
  transform: matrix(1, 0, 0.6, 1, 0, 0);
}

.container img {
  transform: matrix(1, 0, -0.6, 1, 0, 0);
}

http://codepen.io/raiden-dev/pen/fnjHb?editors=110


text:
Q: Send a JSON string to a RESTful WS from Classic ASP I am basically a noob in classic ASP and VBScript, so I would like to get some help to achieve the goal I have here. I've built a JSON string and I need to send it to a RESTful web service using VBScript. How do I do that?
I have some code, but I don't think it works:
strJSONToSend = JSONstr 'this is where I use my built JSON string

webserviceurl = "url here"

Set objRequest = Server.createobject("MSXML2.XMLHTTP.3.0")
objRequest.open "POST", webserviceurl, False

objRequest.setRequestHeader "Content-Type", "application/json; charset=UTF-8"
objRequest.setRequestHeader "CharSet", "utf-8"
objRequest.setRequestHeader "SOAPAction", webserviceurl

Set objJSONDoc = Server.createobject("MSXML2.DOMDocument.3.0")
objJSONDoc.loadXml strJSONToSend
objRequest.send objJSONDoc

set objJSONDoc = nothing
set objResult = nothing

A: You don't need to convert the JSON to XML (since it's JSON and not XML and all):
strJSONToSend = JSONstr 'this is where I use my built JSON string

webserviceurl = "url here"

Set objRequest = Server.createobject("MSXML2.XMLHTTP.3.0")
objRequest.open "POST", webserviceurl, False

objRequest.setRequestHeader "Content-Type", "application/json; charset=UTF-8"
objRequest.setRequestHeader "CharSet", "utf-8"
objRequest.setRequestHeader "SOAPAction", webserviceurl

objRequest.send strJSONToSend

set objJSONDoc = nothing
set objResult = nothing


text:
Q: How to centre-align NSTextField after setting its string value There's probably a ridiculously simple solution to this (I'm almost embarrassed to ask).
Relevant code snippet from my view controller:
@IBOutlet weak var textLabel: NSTextField!

@IBAction func getTimeButton(sender: AnyObject) {
    let currentDate = NSDate()
    let dateFormatter = NSDateFormatter()
    dateFormatter.timeStyle = .ShortStyle
    textLabel.stringValue = dateFormatter.stringFromDate(currentDate)
}

Before pressing the "Get Time" button, the "Press Button" label is centred:

After pressing the button, the label gets left-alligned:

Label attributes:

I have set the labels constraints, but the constrains seem to get "reset" when the string value is set.
How can I make the label stay centred after setting the string value?
I've also tried to add this to my controller, but to no avail:
let textAlignment = NSTextAlignment.CenterTextAlignment
textLabel.alignment = textAlignment

A: Try this:
textLabel.alignment = .center
I used this and it worked.


text:
Q: DataGrid is not showing values WPF I have a DataGrid which is showing values only in the first column even though there are  values in the other cells. Here is my code:
XAML:
<Grid ShowGridLines="False">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <DataGrid HorizontalAlignment="Left"
              VirtualizingStackPanel.IsVirtualizing="False"
              GridLinesVisibility="None" IsReadOnly="True"
              Name="AvdrEventsDataGrid" VerticalAlignment="Top"
              Grid.Row="0" ItemsSource="{Binding}"
              Loaded="AvdrEventsDataGrid_Loaded" CanUserSortColumns="False">
        <DataGrid.Resources>
            <Style TargetType="{x:Type DataGridColumnHeader}">
                <!--<Setter Property="Background" Value="Black"/>
                <Setter Property="Foreground" Value="White" />-->
                <!--<Setter Property="FontFamily" Value="Wingdings"/>-->
                <Setter Property="FontSize" Value="12" />
            </Style>
        </DataGrid.Resources>
    </DataGrid>
    <Button Content="Run!" Height="23" HorizontalAlignment="Left"
            Name="btnRun" VerticalAlignment="Top" Margin="20,0,0,0"
            Width="75" Grid.Row="1" Click="btnRun_Click"/>
</Grid>

C#:
DataTable _resulTable=new DataTable();
AvdrEventBuilder avdrEventBuilder=new AvdrEventBuilder();
_resulTable = avdrEventBuilder.GetEventData();
AvdrEventsDataGrid.DataContext = _resulTable;

Also I am changing the color of the first column like this

int i = 0;
foreach (var row in _resulTable.Rows)
{
    var cell = AvdrEventsDataGrid.GetCell(i, 0);
    cell.Background = Brushes.Gray;
    cell.Foreground = Brushes.White;
    i++;
    cell.Width = 100;
}

The issue is I can see values only in the first column even though there are values in other dataset columns. I also tried    AvdrEventsDataGrid.ItemsSource = @object; this using a collection of class objects. It showing the same blank values. Please help.


text:
Q: Query a Table in Salesforce having 4 Million Records with 250 columns using Python/Pyspark I need to pull a table ABC from Salesforce having 4Million records with 250 columns. I'm using python simple-salesforce API to do it, but if is running out of memory as I'm using a 8GB ram machine.

*

*Is there any way to query this much large amount of records in salesforce using Pyspark, if so please suggest.

*If there are any other approach also by using either Python or Pyspark, suggest them as well...

A: Is there a chance you are using query_all from simple_salesforce? If so, you might try query_more or query_all_iter instead so that your script does not attempt to load all into a single Python list.
Simple Salesforce documentation here.


text:
Q: Is there any winJS plugin for jQuery? I like the easy way to use jQuery and would prever to use it also in metro style apps. I would like to have a plugin/wrapper/monkey-patch, that uses the winJS-Functions in jQuery. For example I'am using the following plugin to avoid MSPointer-Problems:
$.fn.msMousedown = function(handler) {
    var eventType = 'mousedown touchstart';
        if (window.navigator.msPointerEnabled)
          eventType = 'MSPointerDown';
    this.bind(eventType,handler);
})( jQuery );

Is there any project that I can use that does this handling for me? Maybe a jQuery-Plugin, that allows to just use jQuery in Windows 8-Projects?
In my opinion winJS is to complicated and would be much easier if it uses the simple jQuery-syntax. So I'am searching for an alternative to winJS

A: Take a look at my jqToDo sample. It has a reusable wrapper script that makes WinJS controls look like jQueryUI widgets.

A: You can use jQuery directly in a WinRT project.  You need to add the jQuery files directly to your project (do not reference from CDN) since files need to be available even when offline.  It also provides a correct security context.  I did a very short, very simple example video here... http://slickthought.net/post/2012/08/01/Windows-8-and-HTML-Part-2-3rd-Party-Frameworks.aspx
Includes a quick example using both jQuery and jsRender.
You can also mix-and-match --- the two frameworks are not mutually exclusive.


text:
Q: Android CursorAdapter with EditText problem In my Appliaction I use a CursorAdapter. This displays a list, which is part of a RelativeLayout. This List includes several elements(TextView, Button, EditText). The EditText does not normally appear on the screen.The problem: I import any data to a EditText and scroll the screen. In this moment I see the imported data in another EditText. OR:
Another case. There are 3 EditText. I use the virtual Keyboard (For example use the second editText). I get in the data to the Edit Text. Push the Back Button. And the data goes to the Edit Text below. (So the data go to the third Edit Text)
  Here is the CursorAdapter Code:
class OOSListadapter extends CursorAdapter{
        OOSListadapter(Cursor c){
            super(OOS.this,c);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            OOSRow newRow = (OOSRow)view.getTag();
            newRow.populateRow(cursor);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            LayoutInflater inflater=getLayoutInflater();
            View row=inflater.inflate(R.layout.oos_row, parent, false);
            OOSRow newRow = new OOSRow(row);

            row.setTag(newRow);

            return (row);
        }
    }

And here is one row from my application list.
class OOSRow {
        private TextView row_Action = null;;
        private TextView row_Must = null;;
        private TextView row_Lack = null;;
        private TextView row_itemName = null;;
        private EditText row_price = null;;
        private Button row_detail = null;
        private View row = null;

        OOSRow (View row){
            this.row = row;

            row_Action = (TextView)row.findViewById(R.id.oos_row_SignalA);
            row_Must = (TextView)row.findViewById(R.id.oos_row_SignalK);
            row_Lack = (TextView)row.findViewById(R.id.oos_row_SignalO);
            row_itemName = (TextView)row.findViewById(R.id.oos_row_itemLabel);
            row_price = (EditText)row.findViewById(R.id.oos_row_EditText);
            row_detail = (Button)row.findViewById(R.id.oos_row_detailButton);
        }

        void populateRow (Cursor c){
            Cursor specCursor = dbLoc.Query("SELECT PRICE, LACK, ORDERED FROM ORDERED WHERE ITEMID='"+ c.getString(1) +"'", null);
            specCursor.moveToFirst();
            row_itemName.setText(c.getString(2));
            row_itemName.setContentDescription(c.getString(1));
            if (specCursor.getString(1).toString().equals("Y")){
                row_itemName.setBackgroundColor(Color.parseColor("#FF0000"));
                row_itemName.setTextColor(Color.parseColor("#FFFFFF"));
            }else{
                row_itemName.setBackgroundColor(Color.parseColor("#000000"));
                row_itemName.setTextColor(Color.parseColor("#FFFFFF"));
            }
            row_itemName.setOnClickListener(SelectedLackItem);

            if (c.getString(5).toString().equals("I")){
                row_Action.setTextColor(Color.parseColor("#000000"));
                row_Action.setBackgroundColor(Color.parseColor("#FF0000"));
            }
            else{
                row_Action.setTextColor(Color.parseColor("#FFFFFF"));
                row_Action.setBackgroundColor(Color.parseColor("#000000"));
            }
            if (c.getString(4).toString().equals("I")){
                row_Must.setTextColor(Color.parseColor("#000000"));
                row_Must.setBackgroundColor(Color.parseColor("#00FF00"));
            }
            else{
                row_Must.setTextColor(Color.parseColor("#FFFFFF"));
                row_Must.setBackgroundColor(Color.parseColor("#000000"));
            }

            specCursor = dbLoc.Query("SELECT LACK FROM LASTORDERED WHERE ITEMID='"+c.getString(1)+"' AND COMPANYID ='"+dbLoc.GetCompanyId()+"'", null);
            if (specCursor.moveToFirst())
            {
                if (specCursor.getString(0).toString().equals("I")){
                    row_Lack.setTextColor(Color.parseColor("#000000"));
                    row_Lack.setBackgroundColor(Color.parseColor("#0000FF"));
                }else{
                    row_Lack.setTextColor(Color.parseColor("#FFFFFF"));
                    row_Lack.setBackgroundColor(Color.parseColor("#000000"));
                }
            }

            row_detail.setOnClickListener(OpenDetailScreenButton);
            row_detail.setContentDescription(c.getString(1));
            row_price.setContentDescription(c.getString(1));
            row_price.setInputType(0);
            /*row_price.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    row_price.setInputType(InputType.TYPE_CLASS_NUMBER);
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            });*/

            specCursor.close();
            specCursor = null;
        }
    }

And some pictures:

After Back Button:

Any Idea?

A: I had a very similar problem. The following solution helped me:
<activity android:name= ".yourActivity" android:windowSoftInputMode="adjustPan"/>


text:
Q: How do I make an unbreaking Diamond Pickaxe that can only break Obsidian in MCPE? I am trying to create a diamond pickaxe with two effects. I would like it to be Unbreaking, and that it can only break Obsidian. The problem is, I'm not sure how to go about it.
Can someone help me with this?

A: For the breaking obsidian part, use this command:
/give @s diamond_pickaxe 1 0 {"can_destroy":{"blocks":["obsidian"]}}

If that doesn't work, try using @p instead of @s.
Unfortunately in PE, giving enchanted items using commands is not possible. You could use this command if you are holding the pickaxe:
/enchant @s unbreaking [level:int]

Again, use @p if @s doesn't work. [level:int] is the level of unbreaking you want the pickaxe to be (from 0 to 2, where 0 is level 1).
See this answer for more information.


text:
Q: Efficient way to set elements to zero where mask is True on scipy sparse matrix I have two scipy_sparse_csr_matrix 'a' and scipy_sparse_csr_matrix(boolean) 'mask', and I want to set elements of 'a' to zero where element of mask is True.
for example
>>>a
<3x3 sparse matrix of type '<type 'numpy.int32'>'
    with 4 stored elements in Compressed Sparse Row format>
>>>a.todense()
matrix([[0, 0, 3],
        [0, 1, 5],
        [7, 0, 0]])

>>>mask
<3x3 sparse matrix of type '<type 'numpy.bool_'>'
    with 4 stored elements in Compressed Sparse Row format>
>>>mask.todense()
matrix([[ True, False,  True],
        [False, False,  True],
        [False,  True, False]], dtype=bool)

Then I want to obtain the following result.
>>>result
<3x3 sparse matrix of type '<type 'numpy.int32'>'
    with 2 stored elements in Compressed Sparse Row format>
>>>result.todense()
matrix([[0, 0, 0],
        [0, 1, 0],
        [7, 0, 0]])

I can do it by operation like
result = a - a.multiply(mask)

or
a -= a.multiply(mask) #I don't care either in-place or copy.

But I think above operations are inefficient. Since actual shape of 'a' and 'mask' are 67,108,864 × 2,000,000, these operations take several seconds on high spec server(64 core Xeon cpu, 512GB memory). For example, 'a' has about 30,000,000 non-zero elements, and 'mask' has about 1,800,000 non-zero(True) elements, then above operation take about 2 seconds.
Is there more efficient way to do this?
Conditions are below.

*

*a.getnnz() != mask.getnnz()

*a.shape = mask.shape

Thanks!
Other way(tried)
a.data*=~np.array(mask[a.astype(np.bool)]).flatten();a.eliminate_zeros() #This takes twice the time longer than above method.

A: My initial impression is that this multiply and subtract approach is a reasonable one.  Quite often sparse code implements operations as some sort of multiplication, even if the dense equivalents use more direct methods.  The sparse sum over rows or columns uses a matrix multiplication with the appropriate row or column matrix of 1s.  Even row or column indexing uses matrix multiplication (at least on the csr format).
Sometimes we can improve on operations by working directly with the matrix attributes (data, indices, indptr).  But that requires a lot more thought and experimentation.
For the dense arrays my first try would be
In [611]: a.A*~(mask.A)
Out[611]:
array([[0, 0, 0],
       [0, 1, 0],
       [7, 0, 0]], dtype=int32)

But there isn't a direct way of doing not to a sparse matrix.  If mask was indeed sparse, ~mask would not be.  In your example mask has 4 True terms, and 5 False, so a dense version would work just as well:
In [612]: nmask=sparse.csr_matrix(~(mask.A))
In [615]: a.multiply(nmask)
Out[615]:
<3x3 sparse matrix of type '<class 'numpy.int32'>'
    with 2 stored elements in Compressed Sparse Row format>

CSR scipy matrix does not update after updating its values explores setting the diagonal of a sparse matrix to 0.  It is possible to set values of the data attribute to 0, and then eliminate_zeros once at the end.
The other dense method is
In [618]: a1=a.A
In [619]: a1[mask.A]=0

This also works in sparse - sort of
In [622]: a2=a.copy()
In [624]: a2[mask]
Out[624]: matrix([[0, 3, 5, 0]], dtype=int32)
In [625]: a2[mask]=0
/usr/local/lib/python3.5/dist-packages/scipy/sparse/compressed.py:730: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.
  SparseEfficiencyWarning)
In [626]: a2
Out[626]:
<3x3 sparse matrix of type '<class 'numpy.int32'>'
    with 6 stored elements in Compressed Sparse Row format>

As noted in the previous question, we need to eliminate the zeros:
In [628]: a2.eliminate_zeros()
In [629]: a2
Out[629]:
<3x3 sparse matrix of type '<class 'numpy.int32'>'
    with 2 stored elements in Compressed Sparse Row format>

Taking a hint from the sparsity warning let's try the lil format
In [638]: al=a.tolil()
In [639]: al[mask]
Out[639]:
<1x4 sparse matrix of type '<class 'numpy.int32'>'
    with 2 stored elements in LInked List format>
In [640]: al[mask]=0
In [641]: al
Out[641]:
<3x3 sparse matrix of type '<class 'numpy.int32'>'
    with 2 stored elements in LInked List format>

It's interesting that al[mask] is still sparse, where as a[mask] is dense.  The 2 formats use different indexing methods.
At some low level of sparsity, it might be worth iterating over the True (nonzero) elements of mask, setting the corresponding terms of a to zero directly.
I'm not going to guess as to the relative speeds of these methods.  That needs to be tested on realistic data.


text:
Q: Canvases in table, weird padding Intro:
I'm making a website and I want to make a
 with <canvas/>es in it.
What I have done:
I made a
 with some <canvas/>es in it so I can draw in them.

        item1
        <canvas></canvas>

        item2
        <canvas></canvas>

        item3
        <canvas></canvas>

CSS:
canvas {
    margin: 0;
    padding: 0;
    height: 50px;
}
table {
    margin: 0;
    padding: 0;
    width: 500px;
    border: 0;
    border-width: 0;
    border-spacing: 0;
}
tr {
    margin: 0;
    padding: 0;
}
td {
    margin: 0;
    padding: 0;
    border: 0;
    border-width: 0;
    border-spacing: 0;
    height: 50px;
}

To make the canvases appear to look like a big box I want them to hit each other.
I made a code example: http://jsfiddle.net/Whb8u/
window.onload = function(){
    if(window.addEventListener){
        var items = document.getElementsByTagName('canvas');
        for(var i = 0; i < items.length; i++){
            drawcanvas(items[i]);
        }
    }
};

function drawcanvas(item){
    var context = item.getContext("2d");
    var canvasWidth = item.parentNode.offsetWidth;
    var canvasHeight = item.height = item.parentNode.offsetHeight;

    context.fillStyle = 'rgb(100,100,100)';
    context.fillRect(0, 0, canvasWidth, canvasHeight);
}

Problem:
The canvases don't touch each other.
I already removed the table border, margin, padding and spacing.
The canvases need to have a fixed height of 50px. (in the code I tried to make them hit first, which is more important than the height)
But even if I change the size in the JavaScript the  around it is always 5px bigger than the <canvas/>.
Does anyone know why this happens and/or how to fix it?
Summary:
The grey boxes don't hit each other.
Does anyone know why this happens and/or how to fix it?
Code Example: http://jsfiddle.net/Whb8u/

A: Per default <canvas/> has it's display property set to inline which means it is drawn like text. The gap you see comes from the fact that some letters like g draw below the baseline. One way would be changing the display property:
canvas {
    display: block;
}

See this demo.

A:
Does anyone know why this happens and/or how to fix it?

Its happening because the <canvas> element has a default vertical-align value of baseline .. if you don't want to change the display value you can just change the vertical-align value to bottom:
http://jsfiddle.net/Whb8u/2/


text:
Q: How to assign Roles to new user in Flask - TypeError: __init__() takes exactly 1 argument (3 given) I want to assign roles to users after they've signed up in Flask (using flask.ext.user).
I define UserRoles and Roles as per: https://pythonhosted.org/Flask-User/roles_required_app.html#create-roles-required-app-py
But when I try to auto-add a role after a user register:
@user_registered.connect_via(app)
def _after_reg_hook(sender, user, **extra):
    new_role = UserRoles(user.id,1)

I get the following error:
TypeError: __init__() takes exactly 1 argument (3 given)

Unfortunately the doco example (linked above) doesn't give a practical way of adding roles after registration, so not sure what is going wrong.

A: SQLAlchemy provides a default constructor which assigns named arguments to corresponding attributes.  You passed in positional arguments.
UserRoles(user_id=user.id, role_id=1)

However, you shouldn't be instantiating an association directly, and in fact the example is somewhat misleading as there's no reason to define a full model for the association in this case, since you're not storing any additional data with the association.
Instead, assign a Role directly to the roles collection on User (or the users collection on Role).  Note that this will not check when creating duplicate roles, you should follow the unique object recipe for that.


text:
Q: I am trying to return an array of User objects but my variable $database->FetchArray() return false My program does not execute the foreach because $database->FetchArray() is false.
However my request is correct and executed ($success is equal to true).
public static function FindBasicRecipients(): array|bool
    {
        $database = new Database('log', 'pwd', 'desc');
        $database->Connect();
        $database->Parse("SELECT
            ID_WORKSPACE_USERS,
            LOGIN_WORKSPACE_USERS
            FROM WORKSPACE_USERS
            WHERE FONCTION_WORKSPACE_USERS IN ('Job 1','Job 2', 'Job 3')
            ORDER BY EMAIL_WORKSPACE_USERS"
        );
        $success = $database->Execute();
        if ($success) {
            $basicRecipients = [];
            foreach ($database->FetchArray() as $row) {
                $basicRecipients[] = new User(
                    $row['ID_WORKSPACE_USERS'],
                    $row['LOGIN_WORKSPACE_USERS']
                );
            }
            $database->FreeStatement();
            $database->Close();
            return $basicRecipients;
        } else {
            $database->FreeStatement();
            $database->Close();
            return false;
        }
    }

Here is my Database class with my FetchArray method :
public function FetchArray($mode = null): array|false
    {
        return oci_fetch_array($this->statement, $mode);
    }

A: oci_fetch_array() just returns one row of results. If it returns anything, You'll loop over the columns of the first row, not all the results. It will return false if there are no results or you've already fetched all the results.
To loop over all the results, you should use
while ($row = $database->FetchArray())


text:
Q: auto indentation on common lisp emacs + slime + sbcl in windows I can't use auto indentation function on emacs + slime + sbcl when I define my function and so on.
My .emacs file configuration is this:
(setq inferior-lisp-program
"D:/emacs/sbcl_1.0.37/sbcl.exe"
      lisp-indent-function 'common-lisp-indent-function
      slime-complete-symbol-function 'slime-fuzzy-complete-symbol
      slime-startup-animation nil
      slime-enable-evaluate-in-emacs t
      slime-log-events t
      slime-outline-mode-in-events-buffer nil
      slime-repl-return-behaviour :send-only-if-after-complete
      slime-autodoc-use-multiline-p t
      slime-highlight-compiler-notes t)

(add-to-list 'load-path
 "d:/emacs/site-lisp/slime")  ; your SLIME directory
(require 'slime)
(slime-setup)

Can someone help me?

A: The slime section in my .emacs:
;;; SLIME
(setq inferior-lisp-program "/usr/bin/sbcl")
(add-to-list 'load-path "/usr/share/emacs/site-lisp/slime/")
(require 'slime)
(require 'slime-autoloads)
(slime-setup '(slime-fancy))
(global-set-key "\C-cs" 'slime-selector)

A: I am using emacs 24.1 with slime and discovered that using
(require 'slime)

with
(require 'slime-autoloads)

would not allow slime setup to work, ie no slime-repl or other slime-fancy features would load.
Once I removed
(require 'slime)

it all worked fine.


text:
Q: step$anova following stepAIC() not subsettable? I'm trying to run a simple backwards stepwise multiple linear regression in R using the stepAIC function from the MASS package. The model runs fine, but I can't seem to get the results. When I run "step$anova" I get
Error in step$anova : object of type 'closure' is not subsettable

I've used this exact code many times and never gotten this error before, but I also see no issues in my data matrix or any difference between this and what I usually do. Any tips on this error would be greatly appreciated.
My code is:
PCBiomass<-lm(y1~x1+x2+x3,data=abioY1)
PCBstep<- stepAIC(PCBiomass, direction="backward")
step$anova

the data are attached and useable (earlier in the code they're used in an RDA)

A: Oops, It should be PCBstep$anova in the final line. You can not subset step, because that is an R's built-in function. (You know the stats::step function, right?) A function is a closure; that is what the error is complaining about.


text:
Q: How can I use pipe in this code C++? I'm getting a big trouble because I dunno how to do this.
I need to create only 2 processes that can comunicate.
This is the code:
/* Wrappers */
this->sock_fd = this->w_socket();
this->w_bind();
this->w_listen();

std::cout << "[info] Server is running..." << std::endl;

while(1)
{
    /*Connection stuff */
    struct sockaddr_in client_addr;
    int client_fd = this->w_accept(&client_addr);
    char client_ip[64];
    int client_port = ntohs(client_addr.sin_port);
    inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, sizeof(client_ip));
    std::cout << "[info] Connection from (" << client_ip
        << ", " << client_port << ")" << std::endl;

    /*Login manager*/
    ...

    /* Crate PID */
    int pid = fork();
    if (pid == 0)
    {
        close(this->sock_fd);
        this->manage(client_fd, client_ip, client_port);
        exit(0);
    }
    /* End connection */
    close(client_fd);
}

Well. When a client is successfully authenticated after the login manager, can send data to the server.
If a client is connected and another one is logged in, the second have to kick the first client with a message "You have been disconnected".
How can I use fork and pipe to do that?
I've tried to read something on this, but I'm a bit confused about that.
Thank you.

A: I am not sure about the specific design of your project but if you are using fork() to create a new client from an existing one and you want to use pipe() to communicate, here is a sample code.
int pfds[2];         //pipe() always return pair of file descriptors(fds).
char buf[30];

pipe(pfds);         //fds will be stored in pfds.

if (!fork()) {
    printf(" CHILD CLIENT: writing to pipe\n");
    write(pfds[1], "New Client", 11);
    printf(" CHILD CLIENT: exiting\n");
    exit(0);
} else {
    printf("PARENT CLIENT: reading from pipe\n");
    read(pfds[0], buf, 11);
    printf("PARENT CLIENT: read \"%s\"\n", buf);
    //Take appropriate Action upon read!!!
    wait(NULL);
}

I personally think there are better options than using pipes for this kind of communication(signals or shared memory).

A: have a look at ZMQ: http://www.zeromq.org/


text:
Q: OpenGL texture coordinates confusion From what i read , texture T coordinate(Y axis) is flipped(top is 1.0 , bot is 0.0) , although i don't quite understand why my current mapping code works since i map my coords like this:
float coords[] =
{
    0,0,
    wratio,0,
    wratio,hratio,
    0,hratio
};

Instead:
float coords[] =
{
    0,0,
    wratio,0,
    wratio,1.0 - hratio,
    0,1.0 - hratio
};

And the most confusing of all , is that both versions work (!????!)
...What's going on here?


text:
Q: Force CMake to execute code generator before anything else I can't seem to figure this out. I'm using catkin/CMake. Basically I want to generate an rqt_configure GUI.
However I want to auto-generate the config and message files for this. So I wrote a generator. Using add_custom_target I managed to get the script called:
add_custom_target(
    generate ALL
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
    BYPRODUCTS cfg/${PROJECT_NAME}.cfg msg/${PROJECT_NAME}.msg launch/${PROJECT_NAME}.launch scripts/callback.py
    COMMAND rosrun my_generator my_generator.pc
)

As soon as I try to use the generated code catkin build fails:
    generate_dynamic_reconfigure_options(
        cfg/${PROJECT_NAME}.cfg
    )

    add_message_files(
        FILES ${PROJECT_NAME}.msg
    )

    generate_messages(
        DEPENDENCIES
    )

It says add_message_files can't find the generated file, and doesn't generate the file, even though add_custom_target comes before.
I just want to ensure add_custom_target is run first.
Everything I read about ensuring order says I should use add_depencies( generate), however I don't know which target to attach to to pre-empt these macros.

A: It looks like add_message_files wants to see the file immediately, at configuration stage, when CMake processes CMakeLists.txt. But add_custom_target executes its COMMAND only at the build stage.
You need to run your generator immediately, using execute_process instead:
execute_process(
    COMMAND rosrun my_generator my_generator.pc
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
)

(It could be useful to pass additional RESULT_VARIABLE option, so it would be possible to check success of the command call).


text:
Q: tkinter - How to get which menu item caused callback? I would like to have a single callback function for my menu.  In order to determine what action to take in the callback, I need to know which menu item generated the callback. I have been unable to figure this out.
I see an option called "variable" in the add call, but when I try to use it I get an error.  I thought perhaps it would allow me to specify a StringVar that the menu text would be stored in.
Would like to know in the hello function who generated the callback.  Is it possible to specify a parameter that can be passed in?
from tkinter import *

root = Tk()

def hello():
    print ("hello!")

# create a toplevel menu
menubar = Menu(root)
menubar.add_command(label="Hello!", command=hello)
menubar.add_command(label="Quit!", command=hello)

# display the menu
root.config(menu=menubar)

mainloop()

A: First of all, avoid star imports. You can import it will other name to make it less typical.
import tkinter as tk

command on menu don't return anything. You can use lambda or make separate functions.

Using lambda:
root = tk.Tk()

# create a toplevel menu
menubar = tk.Menu(root)
menubar.add_command(label="Hello!", command=lambda:print("Hello!"))
menubar.add_command(label="Quit!", command=lambda:print("hello!"))

# display the menu
root.config(menu=menubar)

root.mainloop()

When you press the Hello! menu, it will print Hello! but when you press Quit! then it prints hello!

Using separate functions:
root = tk.Tk()
def hello():   #Hello! menu
    print("hello!")
def Hello():   #Quit! menu
    print("Hello!")
# create a toplevel menu
menubar = tk.Menu(root)
menubar.add_command(label="Hello!", command=hello)
menubar.add_command(label="Quit!", command=Hello)

# display the menu
root.config(menu=menubar)

root.mainloop()

You can make separate functions to identify the menu callback.
Making 3 functions:
You can make 3 functions. One will be the main which you will be calling in the other two functions. It will give you a benefit to identify the menu. Here is an example:
root = tk.Tk()
def _main():
    print("hello!")
def hello():   #Hello! menu
    _main()
def Hello():   #Quit! menu
    _main()

# create a toplevel menu
menubar = tk.Menu(root)
menubar.add_command(label="Hello!", command=hello)
menubar.add_command(label="Quit!", command=Hello)

# display the menu
root.config(menu=menubar)

root.mainloop()

A: The question posted was:

Would like to know in the hello function who generated the callback.
  Is it possible to specify a parameter that can be passed in?

After a bit of research I found out how for my function to know who called it.  It was trickier code than I expected.
The line of code that I use is:
    top_menu.add_command(label=sub_menu_info, command=lambda: Menu.MenuItemChosenCallback(element, sub_menu_info))

I've not used lambda before so they syntax was throwing me.  I have a method in my "Menu" class named MeduItemChosenCallback.  It is declared as this:
def MenuItemChosenCallback(self, item_chosen):
I didn't realize I needed to put the class name on the function in the lambda.  I thought it would have been element.MenuItemChosenCallback as that's variable is a Menu object.  Again, not used lambda before so needed to work through the syntax.
Using the sample code originally posted, determining who made the call to hello was done with a parameter:
from tkinter import *

root = Tk()

def hello(parm):
    print (parm)

# create a toplevel menu
menubar = Menu(root)
menubar.add_command(label="Hello!", command= lambda: hello('1'))
menubar.add_command(label="Quit!", command=lambda: hello('2'))

# display the menu
root.config(menu=menubar)

mainloop()

A: Arguably, the best solution is for each command to call a different function.
menubar.add_command(label="Hello!", command=menu_hello)
menubar.add_command(label="Quit!", command=menu_quit)

If you feel the need to have more than one menu item call the same command, using lambda or functools.partial is typically what is used:
Example:
menubar.add_command(label="Hello!", command=lambda: hello("1"))
menubar.add_command(label="Quit!", command=lambda: hello("2"))


text:
Q: How do I fix a counting algorithm that deletes on a random value? I'm trying to make a counting channel, but my algorithm isn't working: it works until I reach the number 9. When I do get to that number, it starts deleting my message. I'm thinking that this is the root of all my problems: if int(message.content[0]) != self.cum_num + 1. I know that self.cum_num + 1 doesn't change the value of self.cum_num, but I do want to be able to compare the incremented by 1 version of this variable to the number the user sends into the counting channel.
@commands.Cog.listener()
    async def on_message(self, message):
        if message.channel.id == self.count_channel:
            try:
                if int(message.content[0]) != self.cum_num + 1:
                    await message.delete()
                else:
                    self.cum_num += 1
            except ValueError:
                await message.delete()

A: It's because of int(message.content[0]) != self.cum_num + 1. If you type in 10 it will grab the first letter 1 and not 10 so it will compare 1 != 10.
Use this to be able to go above 9:
@commands.Cog.listener()
    async def on_message(self, message):
        if message.channel.id == self.count_channel:
            try:
                if int(message.content) != self.cum_num + 1:
                    await message.delete()
                else:
                    self.cum_num += 1
            except ValueError:
                await message.delete()


text:
Q: How can I abstractify my GSON models? **ClassCastException** I am trying to make a module which should be able to convert data that I get from a GraphQL API to kotlin using GSON.
I have an interface that I want to abstractify, So that it can handle more than one single ModelType as it does right now.
data class Response(val data: Data, val errors: MutableList<GQLError>)
data class GQLError(val message: String)
data class Data(val events: MutableList<Event>)

interface ICache : IObservable {
    val url: String

    var content: MutableList<Event>

    fun cache(query: GQL) {
        println(query)
        GlobalScope.launch(Dispatchers.IO) {
            val response: Response = postStuff(query, url)
            launch(Dispatchers.Main) {
                this@ICache.content = response.data.events
                sendUpdateEvent()
            }
        }
    }
}

So I was thinking to change it so that it will look something like  this:
data class Response<T>(val data: T, val errors: MutableList<GQLError>)
data class GQLError(val message: String)
data class EventList(val events: MutableList<Event>)

interface ICache<T> : IObservable {
    val url: String

    var content: T

    fun cache(query: GQL) {
        println(query)
        GlobalScope.launch(Dispatchers.IO) {
            val response: Response<T> = postStuff(query, url)
            launch(Dispatchers.Main) {
                this@ICache.content = response.data
                sendUpdateEvent()
            }
        }
    }
}

And then when I get concrete I can do than in a class for itself:
object ConcreteEvents : ICache<T> {
    override val url: String = "https://example.com/gql-api"
    override var content = EventList(ArrayList())
    override val observers: ArrayList<IObserver> = ArrayList()
}

That way when I run
ConcreteEvents.cache()

Then my content should be set. But I get an error:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to dtu.android.moroapp.observer.EventList
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: dtu.android.moroapp, PID: 21907
    java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to dtu.android.moroapp.observer.EventList
        at dtu.android.moroapp.observer.ConcreteEvents.setContent(ConcreteEvents.kt:11)
        at dtu.android.moroapp.observer.ICache$cache$1$1.invokeSuspend(ICache.kt:21)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

My postStuff function looks like this:
inline fun <reified T> postStuff(query: Any, url: String): T{
    val req = URL(url)
    val con = req.openConnection() as HttpURLConnection
    con.requestMethod = "POST"
    con.connectTimeout = 30000
    con.doOutput = true
    val json = Gson().toJson(query)
    val data = (json).toByteArray()
    con.setRequestProperty("Content-Type", "application/json")
    val request = DataOutputStream(con.outputStream)
    request.write(data)
    request.flush()
    con.inputStream.bufferedReader().use {
        val response = StringBuffer()
        var inputLine = it.readLine()
        while (inputLine != null) {
            response.append(inputLine)
            inputLine = it.readLine()
        }
        return Gson().fromJson(response.toString(), T::class.java)
    }
}

I tried to do TypeToken instead of T::class.java and I even tried to define the typetoken in the concrete class and pass it through the parameters, but it didnt change anything. I always get the same exception.
When I debug the program, then I can see that Response are converted fine, but the value data in Response is returned as a LinkedTreeMap

Something goes wrong in that conversion.. I have no idea what?. Please help me!
Thank you in advance, and have a nice day :-)

A: So I found out that I had to specifically define the type, 100% concrete for GSON to work properly.
So my solution was to pass the Type into the parameter all the way from ConcreteEvents like this
object :TypeToken<Response<EventList>>(){}.type

And then make all the generics functions receive a type in the parameter.


text:
Q: Adding value to array without using loops I was wondering if it's possible to add a values to an array without using loops.
Yes, I know that technically I can write :
$myArray = array(0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32); //etc...

But as you can see on the example if the line is very long it's smarter to do it with a loop.
Now since I already know that each number will be raised by +2 I was wondering if there is internal php command right of the box so I can do it with a callback or any other magic trick ;)
Not the correct syntax but just so you can get the idea.
$myArray = Array();
$myArray[] = insertArray($valueOf{$x};$x;$x>=100;$x=+2);

Yea, I know that this can also applied as a function/class but I'm asking if I can do that magic RIGHT OF THE BOX :)
Thanks!

A: You can create an array containing a range of elements using range() it supports skip parameter
$a = range(0,10,2);
print_r($a);

Array
(
    [0] => 0
    [1] => 2
    [2] => 4
    [3] => 6
    [4] => 8
    [5] => 10
)

A: Yes, you have something called array_walk. Define a function like this:
function addTwo (&$item, $key)
{
    $item = $item * 2;
}

Then use the function this way:
array_walk ($myArray, 'addTwo');

In your use case, you can either use range() with the skip option or, you can use this way:
array_walk (range (0, $max));

Or, with range():
range (0, $max, 2);

A: You can do this with range() (PHP Manual). To produce your array do:
$array = range(0, 32, 2);

The last variable is the number of steps to make between each entry in the array. It defaults at one but by setting it to 2 each number will increment by 2.
print_r($array);

produces
Array
(
    [0] => 0
    [1] => 2
    [2] => 4
    [3] => 6
    [4] => 8
    [5] => 10
    [6] => 12
    [7] => 14
    [8] => 16
    [9] => 18
    [10] => 20
    [11] => 22
    [12] => 24
    [13] => 26
    [14] => 28
    [15] => 30
    [16] => 32
)


text:
Q: java.sql.SQLException: 'Infinity' is not a valid numeric or approximate numeric value I am using a java function which returns a float
private float getEventScaledX(float eventX, float resX) {
    return (eventX * frameWidth) / resX;
}

While storing it under mysql db it throws exception as
Caused by: java.sql.SQLException: 'Infinity' is not a valid numeric or approximate numeric value

Please suggest a right way to handle it at java side to stop this exception but also to get right expected result.

A: The issue here was (as reported by @c0der and @apomene ) resX coming as zero.
JAVA float data type does not throw any arithmetic exception while division by zero operation, rather returns Infinity / NaN as value. Which MySQL can't store as valid numeric type so the exception.
Checking for ( resX > 0 ) fixed my issue .


text: Q: How to embed text over video using ffmpeg library I am trying to use the FFmpeg library, but not able to  Successfully. If there any example which I can refer please help me. I am facing this problem for last 3 days.thanks in advance.I am trying some command, but it always shows me error " CANNOT LINK EXECUTABLE ffmpeg: has text relocations" .


text:
Q: Declaring hex number: The name 'B9780' does not exist in the current context I don't know why it says this:

The name 'B9780' does not exist in the current context

I have the following code:
class Program
{
    public static int TimerBase = 00DB9780;
}

I expect it to accept that, but it says:

Cannot implicitly  convert type double to int. An explicit conversion exists (are you missing a cast?)

A: 00DB9780 is represented as hexadecimal.  To declare as an int prefix the value with 0x:
public static int TimerBase = 0x00DB9780;
                          //  ^^ add 0x to start of hex numbers

Prefixing with 0x tells the compiler to expect (and parse) a hexadecimal number.

Explanation of error(s)
The reason the compiler is saying cannot convert int to double is the first part of the value 00D is actually one way to declare a double in C#.  See Real literals for more info. So the compiler interprets your intention as:
public static int TimerBase = 0D;  // LHS is int, RHS is double

So you get the error:

cannot implicitly convert type double to int

The compiler expects to see a ; after the double declaration (00D) so it also shows an error for missing semi-colon:

; expected

Next the compiler sees B9780 which it tries to interpret as a variable which is why you get the error:

'B9780' does not exist in the current context


text:
Q: netbeans jboss client connection failure I just started to learn EJB by going thru a tutorial.  I started a JBoss server on localhost.  The server started ok, listening on port 4447, 9999 & 8080.
But I keep getting an error running a client. The error message is:
Could not obtain connection to any of these urls: localhost:1099.
I tried to change the port number to 4447, 9999,8080, but still keep getting the same error message.
JBoss version jboss-as-7.1.0.Final.  NetBeans 7.4. JDK 1.6. I already spent hours on it, but still was not able fix it.  Any help will be appreciated.

A: Your client is using the old jnp-protocol for JNDI-lookup (see jndi.properties or code). This is not supported in jboss7. You need to go along the lines of https://docs.jboss.org/author/display/AS71/EJB+invocations+from+a+remote+client+using+JNDI


text:
Q: Coq: parametric rewriting under binders I have a parametric relation myeq that I would like to rewrite under the predicate P whenever both are used with the same parameter.  It works well if I declare the appropriate morphism:
From Coq Require Import Setoid Morphisms.

Parameter A B : Type.
Parameter myeq : A -> relation B.
Add Parametric Relation (a : A) : B (myeq a) as myeq_rel.

Parameter P : A -> B -> Prop.
Add Parametric Morphism (a : A) : (P a)
    with signature (myeq a) ==> iff as P_morphism.
Admitted.

Lemma test1 b1 b2 :
  (forall a, myeq a b1 b2) ->
  exists a, P a b1.
Proof.
  intro.
  setoid_rewrite H. (* OK *)
Abort.

However it stops working when I try to apply a function, even registered as a morphism for myeq:
Parameter Op : B -> B.
Add Parametric Morphism (a : A) : Op
    with signature (myeq a) ==> (myeq a) as op_morphism.
Admitted.

Lemma test2 b1 b2 :
  (forall a, myeq a b1 b2) ->
  exists a, P a (Op b1).
Proof.
  intro.
  setoid_rewrite H. (* not OK, why? *)
Abort.

Did I forget to declare something?


text:
Q: Confusion in usage of "of" in a sentence I read the below statement today.

"Muhammad Ali was born in the small town of Louisville."
  Here Louisville is described as a small town.

Normally when we use "small town of XXX", are we decribing

*

*XXX as a small town, or

*a small town inside something bigger called XXX(Let's say, a country)

Can someone please explain how does one interpret such statements?
Thanks in advance.

A: Firstly, note the definite article in "the small town of Louisville." While "XXX is a small town of …" has the indefinite article.
Both are valid, each with its distinctive meaning.
In the context, it means "the small town called Louisville".
HTH.


text:
Q: FINDING OF protocol of a device using ipaddress I want to know how to find the protocol(SNMP,TL1,CLI,HTTP) being used by a targed device using its ipaddress
Is there any code to find out...if so pls tell
I will be thankful to your valuable replies

A: Your only option is to try to open a TCP connection to the IP address using the port numbers of each of the protocols you are interested in.  It is called port scanning, and it is likely to get you unpopular if you do it without permission!
P.S.  the value of this answer 2 cents :-)


text:
Q: ColdFusion cfc cfquery fails when encrypting a credit card string I have a form in a .cfm page that uses jquery to validate the form and pass the values on to a ColdFusion cfc via .ajax. That all works.
The following is my component code stripped down to show just the pertinent issue.
<cfcomponent displayName="2014 Registration">
 <cfset this.encryptionKey = generateSecretKey('AES') />

 <cffunction name="confregistration" output="false" access="remote" returnType="string">

 <cfargument name="cc" required="true" type="string"/>
 <cfargument name="cvv" required="true" type="string"/>

<cfquery datasource="#application.datasource#">
       INSERT INTO  table_name(cc,cvv)
         values(<cfqueryparam cfsqltype="cf_sql_varchar" value="#encrypt(arguments.cc, THIS.encryptionKey)#"/>,
        <cfqueryparam cfsqltype="cf_sql_varchar" value="#encrypt(arguments.cvv, this.encryptionKey)#"/>)
     </cfquery>

 <cfset message = 'Thank you ' & #encrypt(arguments.cc, THIS.encryptionKey)# />
 <cfreturn #message# />

 </cffunction>
</cfcomponent>

This makes the insert fail completely. In testing if I remove the encryption line the query does it's job and posts to the db.
If I also remove the query but return a message containing just: encrypt(arguments.cc, THIS.encryptionKey) I can see the encrypted string.
I'm new to coldfusion but have been using it for several months. I've found some quirks with variables and using the #'s around variables. They are required in some cases but not in others?
My form works and the component function passes the arguments.cc value if it is not encrypted. So I'm close but there seems to be some weirdness going on.
Any hints as to what might cause the cfparam with the encrypted value to fail?


text:
Q: What's the correct way to convert this event handler registration from C# to VB.net? I'm trying to port some code over from C# to VB.net and I am having trouble with a simple event handler.
C#:
hook.KeyPressed += new EventHandler<KeyPressedEventArgs>(hook_KeyPressed);

I've written it as such in VB.net:
AddHandler hook.KeyPressed, AddressOf hook_KeyPressed

But my conversion is missing any reference to KeyPressedEventArgs in the C# code and i'm not sure if I'm doing this right.  Any help would be appreciated.

A: Remember, that an event is a delegate.  To subscribe to the event, the signature of the event handler must be the same as the delegate.  As long as your method has the proper signature, you have done it right.  Just ensure your event handler's EventArgs parameter is of the KeyPressedEventArgs type.
C#:
hook.KeyPressed += new EventHandler<KeyPressedEventArgs>(hook_KeyPressed);

New C# Syntax:
hook.KeyPressed += hook_KeyPressed;

VB.net
AddHandler hook.KeyPressed, AddressOf hook_KeyPressed

Handler in VB.net:
Sub hook_KeyPressed(ByVal sender As Object, ByVal e As KeyPressedEventArgs)
    'code here
End Sub


text:
Q: Select columns with one of the strings in a list in their name? I have a dataframe with columns that follow certain naming convention. I want to keep only those that have 'out' and 'agg' as prefixes in the header.
I've drafted the following code to achieve this. I created a list so that I can make this a small function and call it for any combination of col prefixes that I want to extract.
prefix = ['out', 'agg']
cols = []
for pref in prefix:
    cols = cols + [col for col in df.columns if pref in col]
df = df[cols].dropna(how='all', axis=0)

Is there a shorter/faster way to do this? I liked the solutions here:Drop columns whose name contains a specific string from pandas DataFrame but couldn't make them  work for a list of strings.
thanks

A: Use DataFrame.filter with regex for match columns names by strings joined by | for regex or:
df = pd.DataFrame({
        'A_out':list('abcdef'),
         'B_out':[4,5,4,5,5,4],
         'C_agg':[7,8,9,4,2,3],
         'agg_D':[1,3,5,7,1,0],
         'out_E':[5,3,6,9,2,4],
         'F_agg':list('aaabbb')
})

prefix = ['out', 'agg']

If need match values for any positions in columns names:
df0 = df.filter(regex='|'.join(prefix)).dropna(how='all')
print (df0)
  A_out  B_out  C_agg  agg_D  out_E F_agg
0     a      4      7      1      5     a
1     b      5      8      3      3     a
2     c      4      9      5      6     a
3     d      5      4      7      9     b
4     e      5      2      1      2     b
5     f      4      3      0      4     b

If need only suffixes add $ for match end of strings:
df1 = df.filter(regex='|'.join(f'{x}$' for x in prefix)).dropna(how='all')
print (df1)
  A_out  B_out  C_agg F_agg
0     a      4      7     a
1     b      5      8     a
2     c      4      9     a
3     d      5      4     b
4     e      5      2     b
5     f      4      3     b

If need only prefixes add ^ for match start of strings:
df2 = df.filter(regex='|'.join(f'^{x}' for x in prefix)).dropna(how='all')
print (df2)
   agg_D  out_E
0      1      5
1      3      3
2      5      6
3      7      9
4      1      2
5      0      4


text:
Q: how to make full css container I wish the container can expand and no have any space on top, left and right
This is my code.
.container{
    width: 100%;
    height: 400px;
    background:red;
}

body{
background:black;

}

A: Most likely it's doing this because of the padding and margin on the html and body tags.
Add
html,body{
   margin: 0px;
   padding: 0px;
}

this to the top of your css. This will remove all the extra padding and margin.

A: Try this:
body {margin:0px;background:#000;}
.container{
    width: 100%;
    min-height: 400px;
    background:red;padding:0px;
}

Demo: http://jsfiddle.net/KUuPr/


text:
Q: Points in a sphere Hey all,
               I am working on a algorithm regarding the surface area. I am using perl as coding language.
I am facing a problem in adding random points in a sphere. Given x, y, z coordinates for points. I want to construct a sphere around those points for a given radius r. My motive is to fill those spheres with random points in oder to occupy that space in 3d.
Kindly guide me through this one. I have no idea how to go about this one.

A: I suggest that you use the Monte Carlo method
Suppose you have a sphere centred at (X0, Y0, Z0), and radius R
To fill that sphere with random points, generate a stream of random coordinates within a cube that exactly contains the sphere, and reject any point that falls outside the sphere
rand(v) is a function that returns a suitably random floating-point value between 0 and v

*

*Generate a point—a set of coordinates relative to the sphere's centre
dx = rand(2R) - R
dy = rand(2R) - R
dz = rand(2R) - R

*

*Check whether it's inside the sphere
dx2 + dy2 + dz2

≤

R2

*

*Add the absolute coordinates to a list if they're valid
save [X0 + dx, Y0 + dy, Z0 + dz]

*

*Keep generating points until you have as many as you need

I hope this helps


text:
Q: Using Twilio VoiceBase Add-On, VoiceBase API Key Needed? I am recording a phone call in my app. AFTER the call is done the user can choose to have the recording transcribed by clicking a button. Then we send the transcription request to VoiceBase.
I've tried the VoiceBase API ruby gem and the documentation from this post on Twilio's blog and VoiceBase's page dedicated to the Twilio integration.
It's pretty easy to send the curl request to reference the recording hosted by Twilio, but my requests are not accepted because I do not have an API key for VoiceBase. Where do I get the API key?

A: Twilio developer evangelist here.
If you are making the request to VoiceBase conditionally after the call has been made then it is not handled by the Twilio intergration and you will need your own VoiceBase API key and billing account.
If you want all calls transcribed automatically by the VoiceBase Add-on to Twilio, then the billing is handled through Twilio and you don't need to make any other accounts, you just need to enable the Add-on in your Twilio console.
Let me know if that helps at all.


text:
Q: Pasar un string a función javascript desde php Tengo este código php:
$enlace = "".$gasto["comentarios"]."";

Me tira un error y no me esta pasando la cadena ya he hecho miles de intentos y no tengo exito, como podría solucionar esto??
Gracias a la ayuda que estoy recibiendo por parte de @phpMyGuel ahora el código ha quedado así:
$enlace = ''.$gasto["comentarios"].'';

El problema ahora viene en lo siguiente, necesito pasar a la función javascript el valor de una variable string y he puesto el código así pero marca error:
$enlace = ''.$gasto["comentarios"].'';

A: En PHP el caracter de escape es /. En tu cadena, podemos usarlo para usar comillas simples sin que estas rompan la concatenación:
PHP
$gasto["comentarios"]  = 'PRUEBA';

$enlace = '' . $gasto["comentarios"] . '';

print $enlace;

SALIDA:
PRUEBA

EDIT
Lo más sencillo para hacer que la función onClick reciba correctamente el valor de una variable sería separar la concatenación, como en el caso de lo que se muestra dentro del enlace:
 $enlace = '' . $gasto["comentarios"] . '';


text:
Q: Use jq to recursively select key names of an object I have a JSON document that looks like:
simple: 42

normal:
  description: "NORMAL"

combo:
  one:
    description: "ONE"
  two:
    description: "TWO"
  arbitrary:
    foo: 42

I want to use a jq expression to generate the following:
["normal", "one", "two"]

The condition to select the key is that its corresponding value is an object type that has a key description. In this case, keys simple and arbitrary don't qualify.
I'm having a hard time to craft the filter. Looked into with_entries and recurse/2 but can't solve it myself.
TIA.

A: It's not clear to me whether the YAML that you gave is just a "view" of your JSON or whether you actually want to start with YAML. If your document really is YAML, then one approach would be to use a tool
(such as yaml2json or yq) to convert the yaml to JSON, and then run jq
as shown below; another would be to use jq as a text-processor,
but in that case you could just as well use awk.
yaml2json input.yaml |
  jq -c '[.. | objects | to_entries[]
          | select(.value | has("description")?) | .key]'

Output
["normal","one","two"]

Streaming parser
This type of problem is also well-suited to jq's streaming parser, which is especially handy when dealing with very large JSON texts.  Using jq --stream, a suitable jq filter would be:
[select(length==2) | .[0] | select(.[-1] == "description") | .[-2]]

The ordering of the results will depend on the ordering of the keys produced by the YAML-to-JSON conversion tool.


text:
Q: The output of a shallow multilayer network, with linear activation function in each of the neurons, is linear in the weights -> FALSE? Can anyone prove to me why the above sentence is FALSE?
I have the feeling that being all linear units I can always write W(Linear) = Y for any W, but the teacher says it's False and quoted a student that said:

The output y of said shallow network is y=sum(v)* sum(wTx +b), so we have the product of the weights v and w inside the output. So the output is non linear in respect to the weights

Could anyone be more precise/analytical?

A: Consider the following neural network:
x1 --  h1
   \/     \ y
   /\     /
x2 --  h2

Corresponding to the following equations:
h1 = w11 x1 + w12 x2
h2 = w21 x1 + w22 x2
y = v1 h1 + v2 h2

Here the weights are w11, w12, w21, w22, v1, v2.
Combining the three equations, we get:
y = v1 w11 x1 + v1 w12 x2 + v2 w21 x1 + v2 w22 x2

Hence we can say that y is a bilinear function of (w11, w12, w21, w22) and (v1, v2), but we cannot say that y is a linear function of (w11, w12, w21, w22, v1, v2).


text:
Q: Destroying a shared std::vector in another process I'm trying to transfer a std::vector<std::string> to a newly forked process via Boost.Interprocess, so that the child process takes ownership of it and destroy it. Retrieving and reading the vector works, however I'm getting an access violation upon destroying it. I gather that the allocator embarks some state with pointers which point into the parent's address space and are meaningless in the child's one.
How am I supposed to create that vector in the parent and destroy in the child correctly ?
Parent process code:
namespace ip = boost::interprocess;

template <class T>
using ip_allocator = ip::allocator<T, ip::managed_shared_memory::segment_manager>;

template <class T>
using ip_vector = std::vector<T, ip_allocator<T>>;

int CALLBACK WinMain(
    _In_ HINSTANCE,
    _In_ HINSTANCE,
    _In_ LPSTR,
    _In_ int
) {
    ip::shared_memory_object::remove("MyTestShm");
    ip::managed_shared_memory mshm{ ip::open_or_create, "MyTestShm", 1024 * 1024 };

    ip_allocator<int> intAlloc{ mshm.get_segment_manager() };

    mshm.construct<ip_vector<int>>("ForkData")(
        ip_vector<int>{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, intAlloc}
    );

    boost::process::spawn(L"Executor.exe", L"ForkData");
}

Child process (Executor.exe) code:
int wmain(int argc, wchar_t **argv) try {
    namespace ip = boost::interprocess;

    // Kludge to attach the debugger and force continuation
    bool volatile coin = true;
    while (coin)
        ::Sleep(1000);

    ip::managed_shared_memory mshm{ ip::open_only, "MyTestShm" };
    auto const * const fd = mshm.find<ip_vector<int>>("ForkData").first;

    if(!fd)
        return 1;

    for (int i : *fd)
        std::cout << i << ' ';
    std::cout << '\n';

    mshm.destroy_ptr(fd); // Crashing line
}
catch (std::exception const &exc) {
    std::cerr
        << "Unhandled " << boost::typeindex::type_id_runtime(exc).pretty_name() << ":\n"
        << exc.what() << '\n';
    return 1;
}

Error and callstack:

Exception thrown: read access violation.
_Pnext was 0x21FE21200B0. occurred

Executor.exe!std::_Container_base12::_Orphan_all() Line 221
Executor.exe!std::_Vector_alloc<std::_Vec_base_types<int,boost::interprocess::allocator<int,boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index> > > >::_Orphan_all() Line 536
Executor.exe!std::vector<int,boost::interprocess::allocator<int,boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index> > >::_Tidy() Line 1913
Executor.exe!std::vector<int,boost::interprocess::allocator<int,boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index> > >::~vector<int,boost::interprocess::allocator<int,boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index> > >() Line 894
Executor.exe!std::vector<int,boost::interprocess::allocator<int,boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index> > >::`scalar deleting destructor'(unsigned int)   Executor.exe!boost::interprocess::ipcdetail::placement_destroy<std::vector<int,boost::interprocess::allocator<int,boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index> > > >::destroy_n(void * mem, unsigned __int64 num, unsigned __int64 & destroyed) Line 61
Executor.exe!boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index>::priv_generic_named_destroy<char>(const char * name, boost::interprocess::iset_index<boost::interprocess::ipcdetail::index_config<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0> > > & index, boost::interprocess::ipcdetail::in_place_interface & table, boost::interprocess::ipcdetail::bool_<1> is_intrusive_index) Line 976
Executor.exe!boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index>::priv_generic_named_destroy<char>(boost::interprocess::ipcdetail::block_header<unsigned __int64> * block_header, boost::interprocess::iset_index<boost::interprocess::ipcdetail::index_config<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0> > > & index, boost::interprocess::ipcdetail::in_place_interface & table, boost::interprocess::ipcdetail::bool_<0> is_node_index) Line 929
Executor.exe!boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index>::priv_destroy_ptr(const void * ptr, boost::interprocess::ipcdetail::in_place_interface & dtor) Line 777
Executor.exe!boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index>::destroy_ptr<std::vector<int,boost::interprocess::allocator<int,boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index> > > >(const std::vector<int,boost::interprocess::allocator<int,boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index> > > * p) Line 550
Executor.exe!boost::interprocess::ipcdetail::basic_managed_memory_impl<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index,8>::destroy_ptr<std::vector<int,boost::interprocess::allocator<int,boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index> > > >(const std::vector<int,boost::interprocess::allocator<int,boost::interprocess::segment_manager<char,boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family,boost::interprocess::offset_ptr<void,__int64,unsigned __int64,0>,0>,boost::interprocess::iset_index> > > * ptr) Line 608
Executor.exe!wmain(int argc, wchar_t * * argv) Line 31
Executor.exe!invoke_main() Line 91
Executor.exe!__scrt_common_main_seh() Line 288
Executor.exe!__scrt_common_main() Line 331
Executor.exe!wmainCRTStartup() Line 17
kernel32.dll!BaseThreadInitThunk()
ntdll.dll!RtlUserThreadStart()

A: Thanks to Passer By who prompted me to go through the Boost.Interprocess documentation again, I stumbled upon this example, which luckily is exactly what I'm trying to do. After confirming that it works on my end (it does), I started gradually morphing it into a copy of my own program, and found the issue.
The difference was the choice of either std::vector or boost::interprocess::vector (also known as boost::container::vector). std::vector is supposed to work fine with a custom allocator, but the issue lies in Microsoft's implementation: _Orphan_all, the function where the access violation happens, is part of the Debug Iterators functionality. That system keeps track of which iterator belongs to which container, but does so by storing raw pointers, which become stale as the vector changes address spaces and end up causing the crash when the vector tries to update the bookkeeping data upon destruction.
Indeed, compiling in Release mode (where _ITERATOR_DEBUG_LEVEL == 0 and debug iterators are deactivated) or using Boost's vector implementation both work flawlessly.


text:
Q: How do I customise themes in Carbon Design System? I am trying to create a custom theme by changing the default colors on carbon.
I have imported the carbon components scss files and I set the variable $carbon-theme as recommended but it is not working. I have imported them in my main index.scss file. I would eventually like to change the color variables and create a customized theme.
This is my index.scss file
@import 'carbon-components/scss/globals/scss/styles.scss';
@import '@carbon/themes/scss/themes';
@include carbon--theme($carbon--theme--g100);

body {
  background-color: $ui-02;
}

This is the mixin I am trying to create.
@mixin custom-color {
  $focus: green;
}

The above does not work. The theme does not change to the expected dark gray background. How do I do this? Also, how would I create the mixin to set other colors?

A: @import '@carbon/themes/scss/themes';
// Use the gray 100 theme
$carbon--theme: $carbon--theme--g100;
@include carbon--theme();

@import 'carbon-components/scss/globals/scss/styles.scss';

body {
  background-color: $ui-02;
}

And not put it into index.scss, put it into App.scss and import it in App.js
works for me, hope this work.


text:
Q: CountDiv (task from codility.com) I have problem understanding the following question: https://codility.com/programmers/task/count_div/ .
Here is the correct answer with a good result:
static int solution(int A, int B, int K) {
    int b = B/K;
    int a = A > 0 ? (A - 1)/K : 0;
    if(A == 0){
        b++;
    }
    return b - a;
    }

I found this answer on Stackoverflow but I cannot understand it. Why b = B/K? a = (A-1)/K in the result we make b - a. Is there is special formula for this?
My own solution was using a loop, but it wasn't fast.

A: The main idea is that you compute the number of integers divisible by K in the range [0, B] and then you do the same for [0, A].
Apply a simple substraction among the two results to find out the number of elements divisible by K in [A, B].
In general, to find the number of integers divisible by K from 0 to X, simply divide X by K. Storing that result in an int will cause it to be automatically truncated down to the nearest integer.


text:
Q: Windows Games Explorer Play/Support Tasks I'm trying to get a game I'm working on to integrate with the Windows Games Explorer.  So far I have embedded a Game Definition Format XML file as a resource in my binary (my actual executable) and I've been able to register the game inside the Games Explorer.
However, In Vista, the play tasks and support tasks that I have defined in my GDF don't display.  The only valid link that shows up in Vista's context menu is a link to the 'Saved Games' folder for my game.  In Windows 7, it all works fine.
What do I need to do to get play tasks and support tasks to display correctly in Windows Vista?

A: IIRC, you have to create the actual shortcut ( %APPDATA%\Microsoft\Windows\GameExplorer\{yourguid}\PlayTasks\0\Play.lnk ) And you probably want to get the GameExplorer path with a known folder id


text:
Q: function continuous ae but not borel measurable It is easy to prove that if $f$ is a function continuous almost everywhere, then $f$ is Lebesgue-measurable by using the property that $\mathcal L$ (the Lebesgue-measure) is complete.
Though I've been wondering if the statement "every function continuous ae is Borel-measurable" is true. I feel like it's not but I have a hard time finding a counterexample. So does such a function (continuous ae and not Borel-measurable) exist?

A: Your assertion is false.  Let $E$ be a non-Borel subset of the Cantor set $C$.  [There are only $\mathfrak c$ Borel subsets of $C$, but $2^{\mathfrak c}$ subsets of $C$, so at least one subset is not Borel.] Then the characteristic function $f$ of $E$ is continuous (at least) on the complement of the Cantor set, since $C$ is a closed set.  Thus $f$ is continuous a.e.  But $\{x: f(x)>0\} = E$ is not Borel.  So $f$ is not Borel measurable.


text:
Q: Error 1054 - Service did not respond in Timely Fashion - C# Application Im having a problem installing my service application. When I'm running my debug mode it all works correctly and all the logical stuff works. I've written service applications before and comparing the two there is little difference between this one and a working one. Thanks in advance for any help on my code:
 class MainClass : ServiceBase
{
    ABCSQLCon _SQLCon = new ABCSQLCon();
    private int cycleTime = 0;

    private delegate void processError(String errorMessage);

    static void Main(string[] args)
    {
        #if(!DEBUG)
            ServiceBase.Run(new MainClass());
        #else
            MainClass service = new MainClass();
            service.OnStart(new string[0]);
        #endif
    }

    protected override void OnStart(string[] args)
    {
        addToLog("Testing SQL Connection...", "Log");
        cycleTime = _SQLCon.sleepTime;
        addToLog("Sleep Time has been set...", "Log");
        if (_SQLCon.testSQLConnection())
        {
            addToLog("Connection to SQL Database succeeded", "Log");
           // queryThread();

            //not neccessary to make applicated multithreaded yet.
            addToLog("Starting Query Thread...", "Log");
            ThreadStart queryCycle = new ThreadStart(queryThread);
            Thread qThread = new Thread(queryCycle);
            qThread.Start();
        }
    }

    private void startProgram()
    {
    }

    protected override void OnStop()
    {
        base.OnStop();
    }

    public MainClass()
    {
        this.ServiceName = "ABCSQL Engine";
    }

Ah I found the problem now, the sql connection test was just a quick open and close job but what I didn't see or realise was where I was initializing that _SQLCON object.
I've moved that to my method and works fine now. Happy days, thanks for the answers as it helped me look in the place I wasnt looking. x

A: It is a best practise to call to methods on a different thread then the service thread to avoid the blocking of the service thread
public void MyMethod()
{
        addToLog("Testing SQL Connection...", "Log");
        cycleTime = _SQLCon.sleepTime;
        addToLog("Sleep Time has been set...", "Log");
        if (_SQLCon.testSQLConnection())
        {
            addToLog("Connection to SQL Database succeeded", "Log");
           // queryThread();

            //not neccessary to make applicated multithreaded yet.
            addToLog("Starting Query Thread...", "Log");
            ThreadStart queryCycle = new ThreadStart(queryThread);
            Thread qThread = new Thread(queryCycle);
            qThread.Start();
        }

}

 private Thread _myThread;
 protected override void OnStart(string[] args)
{
        ThreadStart threadStart = MyMethod;
         _myThread = new Thread(threadStart);
         _myThread.Start();
}

A: The problem is that you are making the database connection in the initialisation of the service itself.
It work in debug because you're not actually starting it as a service:
    #if(!DEBUG)
        ServiceBase.Run(new MainClass());
    #else
        MainClass service = new MainClass();
        service.OnStart(new string[0]);
    #endif

I suspect that the start method is taking a long time because of this line:
    if (_SQLCon.testSQLConnection())

You need to make sure that the start method of the service returns in a timely manner and any potentially long running process is done in a thread. If you move this test into a thread then you should find it working OK.


text:
Q: How to configure Azure CDN now? Few years ago, when i first saw Azure, i found good feature for me: CDN.
How to configure CDN now? (In past, we needed to go previous potal and configure cdn on it).
Thanks.

A: This feature is currently under closed preview and only available to customers who have already used in the past and have active CDN nodes condigured.
My believe is that this feature will soon be available to all Windows Azure customers.
So, as of today (05th of March 2014) Azure CDN is not available to all the customers. More information can be found here. Note that text explicitly mentions "Existing CDN customers".


text:
Q: Polynomial Functor is ω-Continuous Suppose $P:Set\rightarrow Set$ is given by $X \mapsto \sum_{i=0}^{n} C_{i}\times X^{i}$. I want to prove that $P$ is ω-continuous. Three questions: 1). Is my following argument correct? 2). Is there an explicit construction using the product and disjoint union operations? 3). What can be said if $Set$ is replaced by an arbitrary category $C$, say one that is not Cartesian Closed?
edit: I cheated and found a proof of a more general result in CWM that takes care of this. But won't the following argument work for $Set$?
1). Constant endofunctors of Set are ω-continuous.
2). The diagonal functor $\Delta :Set\rightarrow Set\times Set\cdots \times Set$ is left adjoint to the corresponding product functor and so preserves colimits. Since the objects in $Set\times Set\cdots \times Set$  are the categorical products in $Set$, this says if $X_{i}\rightarrow X$ then $X_{i}^{n}\rightarrow X^{n}$.
3). The composition of ω-continuous functors is  ω-continuous.
4). The coproduct $+ : Set\times Set → Set$ is left adjoint to $X\mapsto  (X, X)$.
Thanks in advance for taking the time to review this very basic stuff.
The following was my attempt to show item 2). from scratch.
I show that if $X_{i} \mapsto X$, then $(X_{i}\times X_{i})  \mapsto (X \times X)$. I am having trouble with the last step. Any help would be greatly appreciated. Here's what I have so far:
Let $\left \langle X_{i},\alpha _{i} \right \rangle$ be a colimit cone for $\Delta :\omega \rightarrow Set$. We then have maps $f_{ij}:X_{i}\rightarrow X{j}$ s.t $\alpha _{j}\cdot f_{ij}=\alpha _{i}$
Consider the diagram $:\omega ^{2}\rightarrow Set$ given by $(i,j) \mapsto X_{i}\times X_{j}$. Then we get the commuting squares:
\begin{matrix}X_{i}\times X_{j} &\xrightarrow{(id,f_{j,j+1})}& X_{i}\times X_{j+1} \\ \ \ \downarrow (f_{i,i+1},id) & & \ \ \downarrow (f_{i,i+1},id) \\ X_{i+1}\times X_{j} &\xrightarrow{(id,f_{j,j+1})}& X_{i+1}\times X_{j+1} \end{matrix}
Next, I proved that
$X_{m}\times X_{k} \mapsto X\times X_{k}$ for each $k$. This gives us a new diagram $\omega \rightarrow Set$ which is of course $X\times X_{k}$. This diagram has colimit $X\times X$.
In proving the above, I just observed that, for fixed $k$, if $\beta_{m}: X_{m} \times X_{k}\rightarrow Z$ are arrows making the diagram commute, the we get arrows $\overline{\beta_{m}}:X_{m}\rightarrow Z$ making the original diagram commute, which then give us a unique morphism $\overline{\phi}:X\rightarrow Z$, satisfying $\overline{\phi}\cdot \alpha _{k}=\overline{\beta_{k}}$. This then gives us the unique $\phi:X\times X_{k}\rightarrow Z$. (Or we could just say the functors we get for each $k$, namely, $-\times X_{k}$, peserve colimits, being left adjoints).
A similar argument works for the second colimit.
Now, I want to say that $X\times X$ is the limit of the diagonal diagram $X_{i}\times X_{i}$. So, suppose $\beta_{i,i}:X_{i}\times X_{i}\rightarrow Z$, is a cocone for the diagonal diagram. The fact that all the squares commute induces a cocone $\beta_{j,k}:X_{j}\times X_{k}\rightarrow Z$ over the whole diagram, and in particular if we fix $k$, we obtain unique $\phi_{k}:X\times X_{k}\rightarrow Z$ s.t. $\phi_{k}\cdot \left \langle \alpha _{j},id_{k} \right \rangle=\beta_{j,k}$
I want to use this to give me the required arrow $:X_{i}\times X_{i}\rightarrow Z$, but I do not see how.


text:
Q: Microsoft Outlook what Mailbox is this email in? When I search my emails, and click on a result (or see an email in the list of results), how can I find out what Mailbox that email is currently inside of?
Just in the website email client.

A:
how can I find out what Mailbox that email is currently inside of?

This can be done. I am using Outlook 2016 (365).
Open Outlook, search for the email you want, Find it and open the "found" email.
Press Ctrl-Shift-S and the then Advanced Find dialogue opens and shows you the folder (mailbox) containing the "found" email.
See the screen shot below to illustrate this. The email I found for this test is located in the Folder called Software and that is correct.
If you are using Web Outlook, the Search box is at the top left-hand corner of the Outlook Web App window.
NOTE:  If you have an advanced need to search (I use Search frequently), you may wish to download Outlook.com mail to Outlook Desktop (keep it in Outlook.com) and use Outlook Desktop for searching. I have Outlook.com and it is not anywhere near as good as Outlook Desktop.

A: What exactly does the "what Mailbox" you mentioned here mean? Outlook email folders or different mailbox like shared mailbox?
As I know, in the results displayed on the search list, the email folder will be displayed in the lower right corner of the line of the mail.


text:
Q: Can you extend a sumifs formula dependent on an if statement? I'm wondering if it is possible to extend a SUMIFS formula dependent on an IF statement.
In the example below, what I want is if $O$5 = 0, to extend the SUMIFS formula so that the ">0" becomes criteria1 and then a new criteria_range2 is created, with "<10" as criteria2.
Looking at 'evaluate formula', I'm not sure if the issue is that it won't read the extended bit because it isn't possible to do this, or if the CHAR(34) aren't showing up as I hoped.

=SUMIFS('Revenue'!$G$1:$G$100,'Revenue'!$H$1:$H$100,IF($O$5=0,CHAR(34)&">0"&CHAR(34)&","&"'Revenue'!$H$1:$H$100"&","&CHAR(34)&"<10"&CHAR(34),$O$5))

Any help would be much appreciated! Thanks!

A: If you'd like to use SUMIFs, it should be something like this:
way №1
=SUMIFS(Revenue!$G$1:$G$100,Revenue!$H$1:$H$100,IF($O$5=0,">0",$O$5),
                            Revenue!$H$1:$H$100,IF($O$5=0,"<10",$O$5)
 )

If O5=0, formula evaluates to:
=SUMIFS(Revenue!$G$1:$G$100,Revenue!$H$1:$H$100,">0",
                            Revenue!$H$1:$H$100,"<10"
 )

If O5<>0, formula evaluates to:
=SUMIFS(Revenue!$G$1:$G$100,Revenue!$H$1:$H$100,$O$5,
                            Revenue!$H$1:$H$100,$O$5
 )

which is actually gives you the same result as
=SUMIFS(Revenue!$G$1:$G$100,Revenue!$H$1:$H$100,$O$5)

way №2
=IF($O$5=0,
  SUMIFs(Revenue!$G$1:$G$100,Revenue!$H$1:$H$100,">0",
                             Revenue!$H$1:$H$100,"<10"),
  SUMIFs(Revenue!$G$1:$G$100,Revenue!$H$1:$H$100,$O$5)
 )

If O5=0, formula evaluates to:
=SUMIFS(Revenue!$G$1:$G$100,Revenue!$H$1:$H$100,">0",
                            Revenue!$H$1:$H$100,"<10"
 )

If O5<>0, formula evaluates to:
=SUMIFS(Revenue!$G$1:$G$100,Revenue!$H$1:$H$100,$O$5)

way №3
Or you can use sumproduct as well:
=SUMPRODUCT((Revenue!$G$1:$G$100)*
            IF($O$5=0,(Revenue!$H$1:$H$100>0)*(Revenue!$H$1:$H$100<10),
                      (Revenue!$H$1:$H$100=$O$5)
            )
 )

This is an array formula, so type the formula then press CTRL+SHIFT+ENTER. Curly brackets will automatically appear at the start and end of the formula.
If O5=0, formula evaluates to:
=SUMPRODUCT((Revenue!$G$1:$G$100)*(Revenue!$H$1:$H$100>0)*
                                  (Revenue!$H$1:$H$100<10)
 )

If O5<>0, formula evaluates to:
=SUMPRODUCT((Revenue!$G$1:$G$100)*(Revenue!$H$1:$H$100=$O$5))


text:
Q: Download Search Results I have a search page that allows users to search for documents refined by certain metadata properties.  The documents are scattered across multiple libraries in multiple site collections, but have the same content type.  Is there a way to download the documents from the search results?

A: You can make a custom anchor tag in the Item Template of the search results and for each document set the URL of anchor tag to
http://spsite/_layouts/download.aspx?SourceUrl=http://spsite/Documents/sample.docx

This will download the file from the SharePoint directly.
Source LINK