text:
Q: What is the C# alternative for the below powershell code? I am trying to get a list of services from a remote machine using C# but it doesn't work but the same works when I run the PowerShell script under the same user.
 $global:websess = New-PSSession -Computername $webserverNameList.Text -Credential $global:cred -ConfigurationName *JEAconfigname* -Authentication Negotiate

The above code is from the PowerShell script that uses the same domain\username to get a list of services from a remote machine. I tried doing the same from my C# code using ServiceController class and also a combination of ConnectionOption class and ManagementScope but I get access denied error.
        ConnectionOptions connection = new ConnectionOptions();
        connection.Username = "domain\username";
        connection.Password = "password";
        connection.Authority = "";
        connection.EnablePrivileges = true;
        connection.Authentication = AuthenticationLevel.PacketPrivacy;
        connection.Impersonation = ImpersonationLevel.Impersonate;
        ManagementScope scope = new ManagementScope(@"\\" + lstServerNames.SelectedValue.ToString() + @"\root\cimv2");
        scope.Connect(); // Fails here: System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'
        ObjectQuery query = new ObjectQuery(
                "SELECT * FROM Win32_Service WHERE Name like '%Vend%'");

        ManagementObjectSearcher searcher =
              new ManagementObjectSearcher(scope, query);

        foreach (ManagementObject queryObj in searcher.Get())
        {
            cmbServices.Add(queryObj["Name"].ToString());
        }

i have tried this too:
List<ServiceController> serviceList = ServiceController.GetServices(lstServerNames.SelectedValue.ToString()).Where(x => x.ServiceName.ToLower().StartsWith("vend") || x.ServiceName.ToLower().StartsWith("vstsagent")).ToList();
// Fails here: System.InvalidOperationException: 'Cannot open Service Control Manager on computer '*server name*'. This operation might require other privileges.'
        foreach (ServiceController service in serviceList)
        {
            cmbServices.Add(service.ServiceName);
        }

I know the user is now given admin access. The existing PowerShell using Just Enough Administration (JEA) access to run the script.
https://msdn.microsoft.com/en-us/library/dn896648.aspx

A: You're using the wrong ManagementScope constructor.  You're not specifying the options.
Try:
ManagementScope scope = new ManagementScope(@"\\" + lstServerNames.SelectedValue.ToString() + @"\root\cimv2", connection);
scope.Connect();

Read through the example in the linked document above, too.


text:
Q: What is "trunc" in VHDL: numerical example What does it mean ?
integer(trunc(log2(maximum(coeffs))));

I have found it in a filte implementation here. It is given some description:

-- Determine the optimum power of two scaling for filter coefficients
-- to make the fixed point representation with minimum leading zeros

let say, the part log2(maximum(coeffs)) = 4,856  , what will VHDL give as trunc(4,856)?

A: trunc(x)
... round x to the nearest integer not larger in absolute value.
cp.
floor(x)
... return the largest integral value that is not greater than x.

A: It is a IEEE function. It appears to cut off leading and trailing zeroes unless I am misunderstanding something.

https://perso.telecom-paristech.fr/guilley/ENS/20171205/TP/tp_syn/doc/IEEE_VHDL_1076.2-1996.pdf

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using the discriminant to find the equation of tangents to a circle I was working on a geometry question and took a really long winded route to get an answer. A worked solution I found for it used the discriminant but I don't understand how. The question was this:
The circle C has equation $ x^2 + 6x + y^2 -2y = 7 $.
The lines L1 and L2 are tangents to the circle at the points P and Q respectively.
They intersect at the point R $(0,6)$.
Find the equations of lines L1 and L2, giving your answers in the form $ y=mx + b$.
I began by drawing out the diagram, and went down a very long route that involved using Pythagoras several times to find various magnitudes of distances, establishing that the centre of the circle, $(-3,1)$, forms a square with P, Q, and R. From this, I worked out the gradient of the line from the centre to R, found the gradient of the line perpendicular to it, and then finally could workout the co-ordinates of the points P and Q. Only from here was I able to finish it and workout the equations of the tangents at P and Q.
However, this took about 30 minutes, and when I looked at the worked solutions saw the following much more concise method:
The equations of the lines L1 and L2 are both $y = mx + 6$.
Substituting $y = mx + 6$ into the equation of the circle, expanding, and factorising gives:
$(1+m^2)x^2 + (6+10m)x + 17 = 0$
There is one solution, so using the discriminant $b^2 - 4ac = 0$:
$(6+10m)^2 - 4(1+m^2)(17)=0$
Which expands and factorises to give:
$(4m-1)(m+4)=0$
therefore $m = 1/4 $ or $ m = - 4$
I am really not conceptually understanding why we can use the discriminant in this situation, and would really appreciate someone explaining what is actually happening when we say "there is one solution, so using the discriminant..."
Thank you in advance!

A: It comes down to the fact that a tangent line to a circle (or any conic, for that matter), intersects the circle at exactly one point. So, you're looking for lines through $R$ that intersect the circle at exactly one point. Substituting into the equation of the circle gives you a quadratic equation in the $x$-coordinates of the intersection points. We want this equation to have exactly one solution, which means that the quadratic must have a double root, and that happens when its discriminant vanishes.
You need to be a little careful about using this method. If there's only a single solution for $x$, that could also mean that both intersection points have the same $x$-coordinate. That can't happen here, though, because it would mean that the line is vertical, but you can't represent a vertical line with an equation of the form $y=mx+b$.


text:
Q: How to stop ArangoDB? I'm using ArangoDB and I was wondering how to stop it. I tried:
$ sudo arangodb stop
2018/01/31 17:10:55 Failed to shutdown starter: Post
http://127.0.0.1:8528/shutdown: dial tcp 127.0.0.1:8528: getsockopt: connection
refused

I also tried:
$ /etc/init.d/arangod stop
bash: /etc/init.d/arangod: No such file or directory

I am using Linux Mint 18.1.
Update
I think the command maybe:
/etc/init.d/arangodb3 stop

A: The ArangoDB documentation says
/etc/init.d/arangod stop

And it goes on to say

The exact commands depend on your Linux distribution. You may require root privileges to execute these commands.

From comments it is clear that the version of ArangoDB that you are using provides a script with a slightly different name than the above, so
/etc/init.d/arangodb3 stop

is the way to go for you.

A: Run this command to stop the arangodb service:
sudo systemctl stop arangodb


text:
Q: What is the spectral radius of a non-diagonal matrix? This is my first question in Math StackExchange.
Assume that I know the spectral radius of matrix $A$. The matrix $\bar{A}$ is created from $A$ by removing all the $A$'s diagonal entries (i.e., $\bar{a}_{ij} = {a}_{ij}$ if $i \neq j$, $0$ otherwise).  Can I find the value, or at least the upper bound, of spectral radius of $\bar{A}$?
Thank you in advance.

A: An attempt:
An upper bound for the spectral radius of $\overline{A}$.
First note that $\overline{A}=A-D$ where $D=[a_{11},a_{22},\ldots,a_{nn}]$, the diagonal matrix with diagonal entries $a_{ii}$. Therefore  $\text{spectral of radius}(\overline{A})= \text{spectral of radius}(A-D)$.
Therefore we will search for the best upper bound for the spectral radius of $A-D$
Also if $A$ is a  matrix with zero diagonal, then $\text{spectral of radius}(\overline{A})= \text{spectral of radius}(A)+\text{spectral of radius}(D)$, since $\overline{A}=A$ and $D=0$.


text:
Q: Getting the "native size" of an image created with JLabel I am using JLabel to create an image file from a string.
I have to specify an image dimensions (label.setSize(width, height)), otherwise I get an exception:
java.lang.IllegalArgumentException: Width (0) and height (0) cannot be <= 0
    at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1016)
    at java.awt.image.BufferedImage.<init>(BufferedImage.java:338)
    at com.shopsnips.portal.services.ImageCreator.createFromText(ImageCreator.java:31)
    at com.shopsnips.portal.services.ImageCreator.main(ImageCreator.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

I can control the font size using
label.setFont(new Font("Serif", Font.BOLD, 26));

When I use a font or text that is too large to fit the fixed dimentions, the label is truncated and "..." is included instead. Is there a way to identify the optimal/maximal font size that still fits in the dimensions I set?
Or alternatively, how can I find out whether the current settings (font size + dimensions) will cause the text to be truncated?
Here is some source:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ImageCreator {
    private ImageCreator(){}

    private final static String FONT = "Freestyle Script";

    public static void main(String[] args) {
        Path outputFile = Paths.get("c:\\tmp\\img\\test.png");

        createFromText("Hello World - this is a long text", outputFile, 150, 50);
    }

    /**
*
Create an image from text.

*

* https://stackoverflow.com/a/4437998/11236
*/
    public static void createFromText(String text, Path outputFile, int width, int height) {
        JLabel label = new JLabel(text, SwingConstants.CENTER);
        label.setSize(width, height);
        label.setFont(new Font(FONT, Font.BOLD, 24));

        BufferedImage image = new BufferedImage(
                label.getWidth(), label.getHeight(),
                BufferedImage.TYPE_INT_ARGB);

        Graphics g = null;
        try {
            // paint the html to an image
            g = image.getGraphics();
            g.setColor(Color.BLACK);
            label.paint(g);
        } finally {
            if (g != null) {
                g.dispose();
            }
        }

        // get the byte array of the image (as jpeg)
        try {
            ImageIO.write(image, "png", outputFile.toFile());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Please log in to comment.

A: 1) put BuferedImage as Icon to the JLabel,
2) don't setSize let this job for LayoutManager
3) answer by @Jeffrey was too close to the correct answer, BuferedImage if exist can return both dimensions
4) for better help sooner please post a SSCCE, because I/we can't see code on your monitor, nor exceptions generated from your Java classes

A:
label.setFont(new Font("Serif", Font.BOLD, 26)); ..Is there a way to identify the optimal/maximal font size that still fits in the dimensions I set?

For getting the size of text, look to FontMetrics or a GlyphVector.
A 'quick and dirty' way to get the size of text is to drop it into a label & interrogate the label for the preferred size.
Taking these figures, the font size can be adjusted accordingly.

A: I don't like any of the answers given (or there are not detailed enough for me to make use of right now).
Instead, I just used this heuristic to choose a font size:
private static int chooseFontSize(String text) {
    int largeFont = 28;
    int mediumFont = 22;
    int tinyFont = 16;
    if (text.length() > 25) {
        return tinyFont;
    }
    if (text.length() > 15) {
        return mediumFont;
    }
    return largeFont;
}


text:
Q: Find duplicate records with different values I know how to query to find records with duplicate records based on a field or fields e.g.
Select Customer,Count(*) from Table1 group by Customer,Month having count(*)>1

which would give me a list of all customers who ordered more than once in a given month.
However from that select I'd like to:

*

*Refine the group to show only dupes where the product is DIFFERENT. I know if I wanted to do the same I'd simple add to group by ',Product' but in my case it is Product != Product and I'm not sure how to indicate that in the group

*Instead of getting a list of just which Customers ordered more than one product in a given month a list of all those orders. In other words instead of this type of list from the group:
Bob,December
Mary,June
I am trying to return:
Bob,Widget,December
Bob,Pipes,December
Mary,Books,June
Mary,Cars,June

A: If product field is in the same table, then you can use count with distinct on the product field to get the number of distinct products:
Select Customer, Month, Count(distinct product)
from Table1
group by Customer, Month
having count(distinct product)>1

If you want to know what they ordered, then join it back as a subquery to your main table:
select distinct t1.customer, t1.month, t1.product from table1 t1
inner join
    (Select Customer, Month, Count(distinct product)
     from Table1
     group by Customer, Month
     having count(distinct product)>1
    ) t2 on t1.customer=t2.customer and t1.month=t2.month

The distinct in the outer select depends on your exact needs.


text:
Q: Lucene/Solr performance issue with large number of clauses We are using Solr 4.3 (2 shard and 2 replica) for storing data. The query execution takes around 10 sec when there is lots of conditions on a field (around 100000 clauses), including phrase queries and rows=1000. I do return only id's though.
Collection: Documents
Fields: id,Field1, Field2, Field3, Field4, Field5
Query: Field11:(value1 value2 value3..............value100000)
SortField: Field2

During analysis we found that following statement of (IndexSearcher.java class) takes most of the time.
Weight weight = query.createWeight(this);
We don't want any relavance/Scoring. So can we disable this feature Weight/scroting etc to improve the performance? if yes, How can we do this?
Please let me know any further information required on this.

A: As you say that you want to apply ACLs there is, as far as I know, no ready to go solution. Therefore you will need to build your own.
How this is done can be read here Custom Security Filtering in Solr: Based on Access Control Lists.


text:
Q: Gradle build failing due to dependency issues We have declared ojb:db-ojb:1.0.4 which is required for compiling our project , but we are getting the below issue , it is searching for dependency commons-transaction:commons-transaction:1.1 , but we have org.apache.commons.transaction:commons-transaction:1.1 in archiva. Could you check and let us know how we can avoid checking for dependency for commons-transaction or any other solutions to handle this in gradle:
[04:14:17][Gradle failure report] > Could not resolve commons-transaction:commons-transaction:1.1.
[04:14:17][Gradle failure report] Required by:
[04:14:17][Gradle failure report] com.e2open.e2mc:IOMe:8.2 > ojb:db-ojb:1.0.4
[04:14:17][Gradle failure report] > Could not resolve commons-transaction:commons-transaction:1.1.
[04:14:17][Gradle failure report] > inconsistent module metadata found.     Descriptor: org.apache.commons.transaction:commons-transaction:1.1 Errors: bad group: expected='commons-transaction' found='org.apache.commons.transaction'


text:
Q: Question about the example of quantum modular form I'm reading Zagier's paper "Quantum Modular Forms", and there is a part that I can't understand well.
In his paper, the example 1 (which are closely related to Maass wave form) said that the function
$$
f(x)=q^{1/24}(1+\sum_{n\geq 0}(-1)^{n}(q;q)_{n}q^{n+1}),\qquad q=e^{2\pi i x}, x\in \mathbb{Q}
$$
is a quantum modular form of weight 1 with character, i.e.
$$
f(x+1)=\zeta_{24}f(x), \qquad\frac{1}{2x+1}f\left(\frac{x}{2x+1}\right)=\zeta_{24}f(x)+h(x)
$$
where $h$ can be extended smoothly to $\mathbb{R}$ except $x=-1/2$. However, I tried to draw graph by using MATLAB of $h$ and I got slightly different graph from the author's :

Two graphs coincide for $x>-1/2$ but not for $x<-1/2$. (Mine represents imaginary part of $h$.)
Actually, the character $\chi:\Gamma_{0}(2)\to \mathbb{C}^{\times}$ defined by
$$
\chi(T)=\chi\left(\begin{matrix}1&1\\0&1\end{matrix}\right)=\zeta_{24}, \chi(R)=\chi\left(\begin{matrix}1&0\\2&1\end{matrix}\right)=\zeta_{24}
$$
should satisfy $\chi(-I)=\chi((RT^{-1})^{2})=1$. But $f$ has odd weight (weight 1), so it would be natural to have $\chi(-I)=-1$. There might be something I missed. Thanks in advance.


text:
Q: How to get all solutions for an integer program in ortools? I am trying to get all solutions for a Mixed Integer program through ortools. I have two lists x and y of size 4. I want to get all solutions which satisfy sum(x) = 4 * sum(y). I created a function which takes list of past solutions as input and returns next solution. I am able to get only 2 solutions even though there are more. What am I doing wrong here?
I am expecting the following solutions
Solution 1:
xs1 = [0,0,0,0], ys1 = [0,0,0,0]
Solution 2:
xs2 = [4,0,0,0], ys2 = [1,0,0,0]
Solution 3:
xs3 = [0,4,0,0], ys3 = [1,0,0,0]
Solution 4:
xs4 = [0,0,4,0], ys4 = [0,0,1,0]
and soon on
from ortools.linear_solver import pywraplp

def opt(xs, ys):
    solver = pywraplp.Solver.CreateSolver('SCIP')

    infinity = solver.infinity()
    # x and y are integer non-negative variables.

    n = 4
    M = 20

    x = [0]* n
    y = [0]* n

    w = [[0]* n]*len(xs)

    δ = [[0]* n]*len(xs)

    for i in range(0,n):
        x[i] = solver.IntVar(0, 20, 'x'+str(i))
        y[i] = solver.IntVar(0, 20, 'y'+str(i))

        for j in range(len(xs)):
            w[j][i] = solver.IntVar(0, 20, 'zp'+str(j)+ '-' + str(i))
            δ[j][i] = solver.IntVar(0, 1, 'δ'+str(j)+ '-' + str(i))

    for j in (range(len(xs))):
        for i in range(0,n):
            solver.Add((w[j][i] - x[i] + xs[j][i]) >=0)
            solver.Add((w[j][i] - x[i] + xs[j][i]) <= M*(1-δ[j][i]))

            solver.Add((w[j][i] + x[i] - xs[j][i]) >=0)
            solver.Add((w[j][i] + x[i] - xs[j][i]) <= M*δ[j][i])

    for j in range(len(xs)):
        solver.Add(solver.Sum([w[j][i] for i in range(0,n)]) >= 1)

    solver.Add(solver.Sum([x[i] for i in range(0, n)]) - 4 * solver.Sum([y[i] for i in range(0, n)]) == 0)

    solver.Minimize(solver.Sum([x[i] for i in range(0, n)]))

    status = solver.Solve()

    if status == pywraplp.Solver.OPTIMAL:
        solver_x = [0]*n
        solver_y = [0]*n
        for i in range(0,n):
            solver_x[i] = x[i].solution_value()
            solver_y[i] = y[i].solution_value()
        return ([solver_x, solver_y, solver.Objective().Value()])
    else:
        print('No Solution')
        return ([[0], [0]], -1)

psx = [[0,0,0,0], [0,4,0,0]]
psy = [[0,0,0,0], [1,0,0,0]]

ns = opt(psx, psy)
print(ns)

Output:
No Solution
([[0], [0]], -1)

Reference:

*

*Finding multiple solutions to general integer linear programs

*How to write constraints for sum of absolutes

A: If you have a pure integer programming model, you can use the CP-SAT solver which allows you to print all the solutions [See this].


text:
Q: edit a raster using batch file in command line I am trying to write a batch file for windows command line to convert values of 0 to 1. I can change the numbers with ease but am struggling with the batch file process. I want the batch file to search through 3 degrees of folders to find images to process. So far I have...
UPDATE: The problem appears to have been solved. But for reference the batch file didn't seem to be working, no error messages, just no output.
for %%y in (D:\Data\imageA\20*) do (
    cd %%y
    for %%m in (\%%y\*) do (
        cd %%m
        for %%d in (\%%m\*) do (
            cd %%d
            for %%f in (imageA_*_raster) do replacetool %%f %%f_new 0 1
            cd ..
        )
        cd ..
    )
    cd ..
)

A: *

*To enumerate directories rather than files, you need to use for /D.

*Put quotation marks around all paths, like "D:\Data\imageA\20*", for example. Use the ~ modifier of for variable references to avoid double-quotation.

*Remove the cd commands, use absolute paths instead, applying the ~F modifier, like for /D %%m in ("%%~Fy\*") do ( ... ).

*If you insist of using relative paths (in case the replacetool needs such), use pushd "%%~y" instead of cd %%y and popd instead of cd .., and change (\%%y\*) to ("*").

Here is the fixed code, using absolute paths:
for /D %%y in ("D:\Data\imageA\20*") do (
    for /D %%m in ("%%~Fy\*") do (
        for /D %%d in ("%%~Fm\*") do (
            for %%f in ("%%~Fd\imageA_*_raster") do replacetool "%%~Ff" "%%~Ff_new" 0 1
        )
    )
)

Here is the code, using relative paths:
for /D %%y in ("D:\Data\imageA\20*") do (
    pushd "%%~y"
    for /D %%m in ("*") do (
        pushd "%%~m"
        for /D %%d in ("*") do (
            pushd "%%~d"
            for %%f in ("imageA_*_raster") do replacetool "%%~f" "%%~f_new" 0 1
            popd
        )
        popd
    )
    popd
)


text:
Q: How to prevent a circular citation? This is a follow up query of this
I am using : mysql  Ver 15.1 Distrib 10.1.44-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
CREATE TABLE Work(id INT NOT NULL AUTO_INCREMENT,
    title CHAR(20),
    date DATETIME,
    description VARCHAR(1000),
    CONSTRAINT Work_PK PRIMARY KEY (id),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE Work_Citation(id INT NOT NULL AUTO_INCREMENT,
                   work_1 INT NOT NULL,
                   work_2 INT NOT NULL,
                   CONSTRAINT Work_Citation_PK_1 PRIMARY KEY (id),
                   CONSTRAINT Work_Citation_PK_2 UNIQUE (work_1,work_2),
                   CONSTRAINT Work_Citation_FK_1 FOREIGN KEY (work_1) REFERENCES Work(id),
                   CONSTRAINT Work_Citation_FK_2 FOREIGN KEY (work_2) REFERENCES Work(id)) ENGINE=InnoDB DEFAULT  CHARSET=utf8;

-- How to prevent circular citation?
-- Example 1: In the Work_Citation table, if one piece of Work say work_1 = 1 cites another piece of Work say work_2 = 2, then work_1 = 2 cannot cite work_2 = 1, ie the converse is not possible.
-- Example 2 : (work_1 = 1, work_2 = 2), (work_1 = 2, work_2 = 3), (work_1 = 3, work_2 = 1)?


text:
Q: Unknown type name UITableView I am trying to use a library for drop down.When I copied its files in my project , I am getting weird error saying Unknown type name UITableView and also a lot of errors like Expected a type.What is wrong here?
 @protocol kDropDownListViewDelegate;
 @interface DropDownListView : UIView<UITableViewDataSource,UITableViewDelegate>
{

    UITableView *_kTableView;
    NSString *_kTitleText;
    NSArray *_kDropDownOption;
   CGFloat R,G,B,A;
   BOOL isMultipleSelection;
}
 @property(nonatomic,strong)NSMutableArray *arryData;
 @property (nonatomic, assign) id<kDropDownListViewDelegate> delegate;
- (void)fadeOut;
// The options is a NSArray, contain some NSDictionaries, the NSDictionary contain 2 keys, one is "img", another is "text".
- (id)initWithTitle:(NSString *)aTitle options:(NSArray *)aOptions xy:(CGPoint)point size:(CGSize)size isMultiple:(BOOL)isMultiple;
// If animated is YES, PopListView will be appeared with FadeIn effect.
- (void)showInView:(UIView *)aView animated:(BOOL)animated;
-(void)SetBackGroundDropDwon_R:(CGFloat)r G:(CGFloat)g B:(CGFloat)b alpha:(CGFloat)alph;
@end

@protocol kDropDownListViewDelegate <NSObject>
 - (void)DropDownListView:(DropDownListView *)dropdownListView didSelectedIndex:(NSInteger)anIndex;
 - (void)DropDownListView:(DropDownListView *)dropdownListView Datalist:(NSMutableArray*)ArryData;
 - (void)DropDownListViewDidCancel;
 @end

A: You've missed an #import; probably:
#import <UIKit/UIKit.h>

This is normally part of the prefix file (pre-compiled header) so it's possible that is broken in some way.


text:
Q: When an account has expired, trigger set that the account owner made is autimatically removed from triggers? My coworker left our company, so his account will be expired in a few days.
I wondering triggers that he made in a google apps script are removed automatically?
I have an access to edit the scripts he made, but why I cannot delete triggers of the scripts?

A: As said in the comments, when someone's account is disabled (not deleted) their triggers are not executed anymore.


text:
Q: How do I return a TreeSet of the values contained in a TreeMap? I am trying to get a set of all the values for keys in a TreeMap that are greater than some value, key.
Code attempt below:
TreeSet<E> set = (TreeSet<E>)tMap.tailMap(key, false).values();

Is there a way to do this in Java?
Thanks!!

A: values() returns a Collection, so you can always feed that Collection to TreeSet constructor (assuming your E class implements Comparable<E>):
TreeSet<E> set = new TreeSet<E>(tMap.tailMap(key, false).values());

If you wish the TreeSet to use some custom Comparator instead of natural ordering, you can write:
TreeSet<E> set = new TreeSet<E> (yourComparator);
set.addAll(tMap.tailMap(key, false).values());


text:
Q: Set EditText cursor position to right of Hint Text I am writing an application where I need to set cursor position to right of Hint text.
I checked with some of available answer , here and here but all these say with input text instead with only text hint.
Any suggestion if it is possible to have!


text:
Q: Python Dot Separator with Variable Input I'm currently attempting to write a program that takes in a user input of units and magnitude and converts them to a user defines the unit. So basically just a unit converter (still doing beginner projects with Python).
But for the module pint, it uses a dot separator as the way to get the units, like so:
from pint import *

ureg = UnitRegistry()
dist = 8 * ureg.meter
print(dist)
>>> 8 meters

Now 8 is tied to meters. But say I want to let the user define the unit. So have a variable defined by an input attached to ureg like so:
from pint import *

ureg = UnitRegistry()
inp = input()
>>>inp = meter
unit = ureg.inp # this is a variable defined by user
step = 8 * unit
print(step)

>>>AttributeError: 'UnitRegistry' object has no attribute '_inp_'

The problem is python thinks I'm trying to access an attribute called inp from ureg, which doesn't exist. if inp=meters, why won't it work as ureg.meters worked? How can you attach variables to call attributes from a module?

A: You could use getattr(object, name):
ureg = UnitRegistry()

user_value = input()
unit = getattr(ureg, user_value) # this is a variable defined by user
step = 8 * unit
print(step)

A: Or:
ureg = UnitRegistry()
user_value = input()
unit = vars(ureg)[user_value] # this is a variable defined by user
step = 8 * unit
print(step)

Or:
eval('ureg.%s()'%user_value)


text:
Q: Haskell Pattern Matching for consecutive list elements I want to check if the next element in a list is the same as the previous element and increase count using a recursive function and pattern matching in Haskell, how can I do this?
I was thinking of something along the lines of:
mrn [] = 0
mrn [x] = 1
mrn (x:xs)
  |(x == mrn xs) = --what do I increment here?
  otherwise --what here?

If the next element is not the same, I want to reset the count and also store the previous count somewhere else

A: We do not store our data anywhere else but in the function's output, or in its arguments, updating them from one call to another, because the data in Haskell are immutable -- if x = 42, then it is 42. It can't be changed.
This means using an initial value of 0 for the count argument. It will have to be used by an inner "worker" function defined inside our function, so as to not pollute the global space with irrelevant implementational details.
And to match two consecutive  elements we use (x:y:xs) pattern:
countDups :: [a] -> Integer
countDups xs  =  go xs 0
   where
   go []  count = count
   go [x] count = count
   go (x:y:xs) count
      | your test = go (y:xs) (count+1)
      | otherwise = go (y:xs) count

You will need to do the necessary corrections so that it does what you want, changing the tests in the guards appropriately.
The above will count all the duplications in the list. If you wanted something else, namely, to get the list of all consecutive counts, then you will need to have your function create that list:
dupCounts :: [a] -> [Integer]
dupCounts xs  =  go xs 0 False
   where
   go []  count previousIsSame = [count]
   go [x] count previousIsSame = [count]
   go (x:y:xs) count previousIsSame
      | your test = go (y:xs) (count+1) ....
      | otherwise = x : go (y:xs) 0 ....

Completing / changing / the code should be straightforward, hopefully.


text:
Q: Create rounded block without border-radius I create my own website and I can't understand how correctly create rounded block (see red rectangle in the picture here: https://dl.dropboxusercontent.com/u/43315655/planeto-template.jpg)
This block will be display at different screens (from 960 px to HD). I have tried to do with border-radius but it's wrong.
Please, help me with any links, advice or code examples :)

A: The image you posted is an HTML template. If they did it, don'T you think it is possible?
It is, just put a border on bottom left and bottom right. One value is 100% and the other is the height you want the curve to stop :
border-bottom-right-radius : 100% 100px;
border-bottom-left-radius : 100% 100px;

Fiddle : http://jsfiddle.net/yqf9a/1/

A: I'm not quite sure what you don't understand about border-radius, but the W3C Wiki explains the use of the border-radius property pretty good: http://www.w3schools.com/cssref/css3_pr_border-radius.asp
Also try the CSS Border Radius Generator: http://border-radius.com/


text:
Q: Open IE and Interact with Web Form using Excel VBA I'm trying to create an excel spreadsheet with a landing page where I input a specific week number, period number and/or year.
I would then click a button to open an instance of Internet Explorer, navigate to the web form, input the data from the cells in the spreadsheet and then load up the reports selected.
Code for the web form

<title>Performance Reporting</title>

<link href="../../CSS/KPI_Style.css" rel="stylesheet" type="text/css">

<link href="../../CSS/KPI_Style.css" rel="stylesheet" type="text/css">
<link href="../CSS/KPI_Style.css" rel="stylesheet" type="text/css">

<link href="../CSS/PL_Style.css" rel="stylesheet" type="text/css" />

Store Performance

  <title></title>

<link href="../../../Testing/KPI/NewKPI/Digital_KPI/stylesheet.css" rel="stylesheet" type="text/css">

 Reporting Selection

<form name="form1" id="form1" method="post" action="Get_Page_V4.asp">
<input name="store" type="hidden" value="2397" >
<input name="ViewType" type="hidden" value="store" >

Selected Location: 1111

            <input name="RadioGroup1" type="radio" value="1" checked>
              Yesterday

            <input type="radio" name="RadioGroup1" value="2">

<input name="datebox" type="hidden" id="datebox" value="07/10/2018" size="10" maxlength="10">

            <input type="radio" name="RadioGroup1" value="3">
              Week

              Enter Week

<input name="week" type="text" id="week" value="24" size="2" maxlength="2">

              Enter Financial Year

<input name="weekyear" type="text" id="weekyear" value="2019" size="4" maxlength="4">

              <input type="radio" name="RadioGroup1" value="4">

              Period

              Enter Period

<input name="period" type="text" id="period" value="6" size="2" maxlength="2">

              Enter Financial Year

<input name="periodyear" type="text" id="periodyear" value="2019" size="4" maxlength="4">

            <input type="radio" name="RadioGroup1" value="6">
              Year

              Enter Financial Year

<input name="YearYear" type="text" id="YearYear" size="4" maxlength="4" value="2019" >

              <input name="RadioGroup2" type="hidden" class="Style10" value="6"  checked="Checked">

            <input type="submit" name="Submit" value="Display Report">

<input name="page_name" type="hidden" value="Region_Page1_" />
</form>

VBA code
Sub Get_Data()
    Dim i As Long
    Dim IE As Object
    Dim objElement As Object
    Dim objCollection As Object
    Dim HWNDSrc As Long
    Dim dates As Object

    Set IE = CreateObject("InternetExplorer.Application")

    With IE
        .Visible = True
        .navigate "http://INTRANETSITE/Summary_Select.asp"

        Do Until .readyState = 4 And Not .Busy
            DoEvents
        Loop

        .document.all.Item("radioGroup1")(3).Checked = True   'Select the 4th checkbox down on the list
        .document.forms(0).submit                             'Submit the form to generate the result
    End With

    Pause (2)

    With IE
        .navigate "http://INTRANETSITE/ReportDetail2.asp?"

        Do Until .readyState = 4 And Not .Busy
            DoEvents
        Loop
    End With
End Sub

The code above navigates to the web form and does select the 4th radio button which is for period reports, then submits the form and displays the first page.
How do I interact with the text boxes to also amend which week or period I want to select reports for?
Also, when it tries to navigate to ReportDetail2.asp it returns the following error and then crashes the VBA code.

Method 'Navigate' of object 'IWebBrowser2' failed

The long term goal of this is to navigate through 20+ pages of reports, pulling the data from each table into a tab on the spreadsheet, so if it can't navigate between the reports, even before we get to the code to pull the data, then that's a problem.

A: Try something like the following. I am showing the different options you might consider so remember to comment out those you don't want to use.
You need to add a reference to Microsoft Internet Controls via VBE > Tools > References or use late bound call of
Dim ie As New InternetExplorer : Set ie = CreateObject("InternetExplorer.Application")

VBA:
Option Explicit
Public Sub MakeSelections()
    Dim ie As New InternetExplorer
    Const URL As String = "yourURL"
    With ie
        .Visible = True
        .navigate URL

        While .Busy Or .readyState < 4: DoEvents: Wend

        With .document
            .querySelector("[value='1']").Checked = True 'Yesterday. CSS attribute = value selector
            .querySelector("[value='3']").Checked = True 'Week
            .querySelector("[value='4']").Checked = True 'Period
            .querySelector("[value='6']").Checked = True 'Year
            .getElementById("week").Value = 6 'week value
            .getElementById("weekyear").Value = 2018 'financial year value
            .getElementById("period").Value = 6 'period value
            .getElementById("periodyear").Value = 2018 'period financial year value
            .getElementById("yearyear").Value = 2019 'financial year value
            .querySelector("[value='Display Report']").Click 'display report
        End With
        Stop '<== Delete me later
        '.Quit '<== Remember to quit application
    End With
End Sub


text:
Q: XCode 8 failing to compile Swift 3 code that works on Xcode 9 The code in question is a bit that comes from this answer, and checks whether a given index is available or not.
Specifically, only in XCode 8.3 does the following issue who up (the code compiles fine in XCode 9 beta. This code is also decidedly Swift 3, and not 4).

I looked into issues relating to the "missing argument" error, and the typical response is to make sure to include the optional argument. However, in here all 3 are included optional i, which is the type Index.
What am I doing incorrectly with the syntax here?

A: The syntax was changed to this:
public func contains(where predicate: (Element) throws -> Bool) rethrows -> Bool

Now you should use this one
self.indices.contains(where: { (object) -> Bool in
     //make comparison here
})

Or
self.indices.contains(where: {$0 == "equal to something"})

Or you can use something like this:
if self.indices.first(where: {$0 == "equal something"}) != nil {
    return self[i]
}else{
    return nil
}

BTW, Sets are still have a bool value returned after calling "contains". Check this


text:
Q: Integrating a network graph with dc.js/crossfilter.js I'm looking for tips and guidance on integrating a network chart with dc.js/crossfilter.js`.
Let's say I have some data like this:
[
    {
        'name': 'john',
        'sexe': 'male',
        'relative': [
            'susy',
            'mark'
        ]
    },
    {
        'name': 'susy',
        'sexe': 'female',
        'relative': [
            'susy',
            'mark'
        ]
    }
    ...
]

Using plain dc.js I can quite easily display coordinated piecharts showing proportions of males/females, percentages of people with the same name etc..
What I would like is to combine the features of dc.js with a network graph, so I can show who's related to who.
The idea is that ie: when selecting "females" in a piechart, the network graph would redraw itself to show exclusively the female relationships.
I'm aware the question may be vague and only loosely fit the guidelines, but I've spent hours digging across to internet for an example of combining dc.js charts with a network diagram.
Can integrating a network graph with dc.js be relatively easily achieved?

A: You can try dc.graph.js
It follows the same sort of data model as dc.js, using crossfilter and accessor functions. The main difference is that there are two crossfilter instances, one for the nodes and one for the edges. Also, it uses accessors on the edges to retrieve the keys of the source and target boxes.
dc.graph.js is still experimental but it definitely supports the use case you describe. Please try it out and report any issues or feature requests!


text:
Q: The pullback of the "space of sections" is the same as the "space of sections" of the pullback I want to verify the sentence:

...can check pullback of the "space of sections" is the "space of sections" of the pullback

in Vakil's Exercise 2.7.E, the latest version.
Let $f:X\to Y$ be a continuous map and $\mathcal G$ be a (pre)sheaf over $Y$ and $G=\bigsqcup_q\mathcal G_q$ be the space of sections (espace etale) as defined in his 2.2.11.
I think the "space of sections of the pullback" is $F=\bigsqcup_p(f^{-1}\mathcal G)_p$, where $f^{-1}\mathcal G$ is the inverse image sheaf.
But I don't know what is the "pullback of the space of sections". I guess I must also prove that they are isomorphic as topological spaces, not just as sets.
If my interpretation is totally wrong, please ignore it and show me the correct interpretation. I only know the definition of the space of sections (espace etale).


text:
Q: No output on webpage from the database When loading my home.php page it should print the data from the select the data from the database 'blog_post' onto the page. However the record gets inserted properly but no data is shown on the page. I have looked up various solutions on here and none of them have seemed to work.
I have looked at many questions on here similar to my problem. None of the answers have seemed to answer my issue. I had tried this using PDO which had worked but with tables, however I do not want to do it that way as it was also a bit much for what I was trying to achieve.
$stmt = $con->prepare("SELECT postTitle, postCont FROM blog_post WHERE
blogid = ? ORDER BY blogid DESC");
$stmt->bind_param('s', $postTitle['postTitle']);
$stmt->execute();
$stmt->bind_result($postTitle, $postCont);
$stmt->fetch();
if(!$postTitle){
    echo "
No Blog Currently Available!
";
} else {
    echo '
';
    echo '
'.var_dump($postTitle).'
';
    echo '
'.$postCont.'
';
    echo '
';
}

I expect that when the data is added to the database via my admin.php page. It should then display the data onto home.php.

A: fetch returns Boolean not an array. You've bound two variables, so use them:
$stmt->bind_result($postTitle, $postCont);
$stmt->fetch();
if(!$postTitle){
    echo "
No Blog Currently Available!
";
} else {
    echo '
';
    echo '
'.$postTitle.'
';
    echo '
'.$postCont.'
';
    echo '
';
}


text:
Q: Print page using html2canvas I'm building a print page function on my web using html2canvas.
function printthispage() {

    html2canvas($("#mydiv"), {
        onrendered: function (canvas) {
            var myImage = canvas.toDataURL("image/png");
            var printWindow = window.open(myImage);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();
        }
    });
}

However the window opened and closed immediately. I've tried removing close(), the image showed on new window but no print function was triggered. Is there something wrong?

A: Try this,it will work:
html2canvas($("#mydiv"), {
    onrendered: function(canvas) {
        var myImage = canvas.toDataURL("image/png");
        var tWindow = window.open("");
        $(tWindow.document.body)
            .html("")
            .ready(function() {
                tWindow.focus();
                tWindow.print();
            });
    }
});

A: Vanilla JS solution
// render HTML to canvas based on target element
html2canvas(document.querySelector('<YOUR SELECTOR>'), {

  // if the canvas is rendered
  onrendered: function (canvas) {

    // create a new window
    var nWindow = window.open('');

    // append the canvas to the body
    nWindow.document.body.appendChild(canvas);

    // focus on the window
    nWindow.focus();

    // print the window
    nWindow.print();

    // reload the page
    location.reload();
  }
});

A: Finally I figure out the solution. The previous handling I used should be made into 2 parts.
1) use html2canvas to render the page into image and store it in a hidden div, when the page is loaded.
html2canvas(divprint, {
    onrendered: function(canvas) {
        var canvasImg = canvas.toDataURL("image/jpg");
        $('#divhidden').html('');
    }
});

2) Once a print button is clicked, open a new window, write the stored div content and jquery function for printing when the loading is done.
$("#printbutton").click(function(e){
    var printContent = document.getElementById("divhidden");
    var printWindow = window.open("", "","left=50,top=50");
    printWindow.document.write(printContent.innerHTML);
    printWindow.document.write("

A: html2canvas(document.querySelector("#mydiv")).then(canvas => {
            var myImage = canvas.toDataURL("image/png");
            var tWindow = window.open("");
            $(tWindow.document.body)
                .html("")
                .ready(function() {
                    tWindow.focus();
                    tWindow.print();
                });
    });


text:
Q: Create javascript document from xmldocument I've been using $.ajax() to get some data from a server but due to incompatibility with previous version of my system (samsung smart tv) I have had to implement XMLHttpRequest also. My problem is that with jQuery, the responseXML returns a [object Document] while XMLHttpRequest's responseXML returns a [object XMLDocument]. Since I already had everything implemented using Documents, is there a way to parse a XMLDocument object or a string object into a Document?
Any help is appreciated, I'm stuck here and don't want to rewrite everything for XMLDocument.
Thanks!

A: In addition to responseXML, you should also have a responseText property coming from XMLHttpRequests. I'm using the following in a similar way.
xhrObj.open('GET', scriptURL, false);
xhrObj.send('');
var se = document.createElement('script');
se.type = "text/javascript";
se.text = xhrObj.responseText;
document.getElementsByTagName('head')[0].appendChild(se);

A: Turned out that diferent browsers return diferent things but in the end is the same.


text:
Q: Recipient address required code": 400 in sending an email using Gmail API in Laravel PHP I am trying to send an email through my system via Gmail API integration, but I receive an error i.e,

Google_Service_Exception
      { "error": { "errors": [ { "domain": "global", "reason": "invalidArgument", "message": "Recipient address required" } ], "code": 400, "message": "Recipient address required" } }

Here is the code in Laravel:
$obj = new \Google_Service_Gmail_Message ();
$raw = "MIME-Version: 1.0\n\r
From: Muhammad Bilal <muhammad.bilal@dynamologic.com>\n\r
To: Umer Sheikh <umer.sheikh@dynamologic.com>\n\r
Subject: SIMPLE TEXT EMAIL\n\r
Date: Thu, 5 Mar 2020 18:45:33 +0500\n\r
Message-ID: <1234@local.machine.example>\n\r
Content-Type: text/plain; charset=\"UTF-8\"\n\r
\n\r
NO BODY";
$raw = rtrim(strtr(base64_encode($raw), '+/', '-_'), '=');
$obj->setRaw($raw);
$obj->setId('1234');
$obj->setInternalDate(null);
$obj->setLabelIds(null);

$payload = new \Google_Service_Gmail_MessagePart ();
$body = new \Google_Service_Gmail_MessagePartBody ();
$body->setData('test');
$body->setSize('1');

    $payload->setBody($body);
    $obj->setPayload($payload);
    $results = $service->users_messages->send($user, $obj);

A: Issue resolved, found a sample code that worked
    $user = 'me';
    $strSubject = 'Test mail using GMail API' . date('M d, Y h:i:s A');
    $strRawMessage = "From: Muhammad Bilal <muhammad.bilal@dynamologic.com>\r\n";
    $strRawMessage .= "To: Muhammad Bilal <mb3451@yahoo.com>\r\n";
    $strRawMessage .= 'Subject: =?utf-8?B?' . base64_encode($strSubject) . "?=\r\n";
    $strRawMessage .= "MIME-Version: 1.0\r\n";
    $strRawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
    $strRawMessage .= "this <b>is a test message!\r\n";
    $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
    $msg = new \Google_Service_Gmail_Message();
    $msg->setRaw($mime);
    $service->users_messages->send("me", $msg);

A: The error message you are getting is due to the fact that the Content-Type should be of type message/rfc822 and not text/plain:
As mentioned in the Users.messages: send documentation:

This method supports an /upload URI and accepts uploaded media with the following characteristics:

*

*Maximum file size: 35MB

*Accepted Media MIME types: message/rfc822

Therefore the entire email message should be in an RFC 2822 formatted base64url encoded string.
Reference

*

*Gmail API Send Messages


text:
Q: Can Docker ignore file metadata like {a,m,c}times when building layers (without build caching)? What I'm doing:
I'm dealing with a setup where the slowest step of my build (>=90% of the run time) is pushing a single image layer to a remote repository. However the file names and contents, the only updates I care about, of that layer only ever changes every few weeks or months and I'm trying to get Docker to reuse some layer that has already been uploaded.
This should in principle be possible because this layer is the the first and only layer on top of a stable image. My Dockerfile look like approximately:
FROM some_stable_base:latest
COPY ["/data/", "/data/"]

Everything works fine if I can use the local build cache, but that assumption doesn't generally apply: in practice many builds are run without the benefit of a populated cache, so the only resource common across all builds will be the remote repository the layers are uploaded to.
Also, I'm having to contend with the issue that the automated build environment has to re-get the files in /data/ each build (this is not too slow) and as a result the file's metadata is different for each build which, as best I can tell, results in each build seeing any COPY/ADD of them into the image as a new, never before seen layer that needs to be uploaded afresh.
Question:
What I'd like to do is make docker ignore (or zero out, or whatever) all the meta data (other than in my case: path and content, maybe group/owner and permissions) so that the layer matches and get that coveted "Layer already exists" when I go to push it.
Is that possible?
In principle it should be, every relevant part of the layer is the same between most builds. But in practice it's looking like docker lacks the ability to be told to ignore the irreverent parts (like file timestamps) that do change.
If it's not possible, I have some other workarounds, but they impose constraints that make "other things" more complicated.

Justifying wanting this:
This would seem to be a generally desirable feature; may builds will only care about file paths and content and be able to produce bit identical content even without a primed cache. But sharing that primed cache across build and build environments is complex and expensive. Being able to reproduce layers would remove that requirement. If fact it seems that it's not uncommon to assume things work the way I'm wanting them to.


text:
Q: DigestOutputStream not reporting the correct digest value I have the following inside a unit test to try and figure out why my DigestOutputStream is not calculating the correct digest for a test .jpg I have in the classpath.
The assertArrayEquals() passes but the final assertEquals() fails with different results.
// the .jpg is 32394 bytes

final MessageDigest md5 = MessageDigest.getInstance("md5");
md5.update(ByteStreams.toByteArray(getInputStream()));
final String h0 = DatatypeConverter.printHexBinary(md5.digest());
System.out.println("MD5 = " + h0); // MD5 = 98BE96C5B9C8D0E41723BBA6E508AADC

// raw MessageDigest from InputStream to ByteArrayOutputStream
final MessageDigest md5a = MessageDigest.getInstance("md5");
final ByteArrayOutputStream baosa = new ByteArrayOutputStream(32394);
ByteStreams.copy(getInputStream(), baosa);
md5a.update(baosa.toByteArray());
final String ha = DatatypeConverter.printHexBinary(md5a.digest());
assertArrayEquals(ByteStreams.toByteArray(getInputStream()),baosa.toByteArray());
assertEquals(h0,ha);

// raw DigestOutputStream to ByteArrayOutputStream
final ByteArrayOutputStream baosb = new ByteArrayOutputStream(32394);
final DigestOutputStream dos = new DigestOutputStream(baosb, MessageDigest.getInstance("md5"));
ByteStreams.copy(getInputStream(), dos);
final String hb = DatatypeConverter.printHexBinary(dos.getMessageDigest().digest());
assertArrayEquals(baosa.toByteArray(), baosb.toByteArray());
assertEquals(h0,hb);  // <-- this is where it fails

Failure:
MD5 = 98BE96C5B9C8D0E41723BBA6E508AADC

org.junit.ComparisonFailure:
Expected :98BE96C5B9C8D0E41723BBA6E508AADC
Actual   :D41D8CD98F00B204E9800998ECF8427E

Why isn't the DigestOutputStream returning the correct value?
And for completeness here is what I am reading in for each of the cases:
private InputStream getInputStream()
{
    return Thread.currentThread().getContextClassLoader().getResourceAsStream("Al_Bundy_Shoot_Me_$12.jpg");
}

Here is the image I am reading in off the classpath in all cases:

A: Solution
I needed to close the DigestOutputStream before trying to get the .digest() off of it.
final DigestOutputStream dos = new DigestOutputStream(baosb, MessageDigest.getInstance("md5"));
ByteStreams.copy(getInputStream(), dos);
dos.close(); // <-- this fixed the problem!
final String hb = DatatypeConverter.printHexBinary(dos.getMessageDigest().digest());

Apparently .flush() makes it behave correctly as well.


text:
Q: Efficient approaches for parsing objects from consecutive fixed size buffers that don't align with object size I am trying to achieve something in C++, where I have an API that reads out objects from a byte array, while the array I pass in is constrained to a fixed size. After it parses out a complete object, the API knows the pointer location where it finishes reading (the beginning of next object to be read from but not complete in the current byte array).
Then I simply need to attach the remaining byte array with the next same fixed size array, and start reading a new object out at the pointer location as if it's the beginning of the new array.
I am new to C++ and I have the following approach working, but looks rather cumbersome and inefficient. It requires three vectors and lots of cleanup, reserve and insertion. I wonder if there is any alternative that may be more efficient, or at least as efficient but the code looks much more concise? I've been reading things like stringstream all such but they don't seem to require less memory copy (probably more as my API has to require byte array gets passed in). Thanks!
std::vector<char> checkBuffer;
std::vector<char> remainingBuffer;
std::vector<char> readBuffer(READ_BUFFER_SIZE);
//loop while I still have stuff to read from input stream
while (in.good()) {
    in.read(readBuffer.data(), READ_BUFFER_SIZE);
    //This is the holding buffer for the API to parse object from
    checkBuffer.clear();
    //concatenate what's remaining in remainingBuffer (initially empty)
    //with what's newly read from input inside readBuffer
    checkBuffer.reserve(remainingBuffer.size() + readBuffer.size());
    checkBuffer.insert(checkBuffer.end(), remainingBuffer.begin(),
    remainingBuffer.end());
    checkBuffer.insert(checkBuffer.end(), readBuffer.begin(),
    readBuffer.end());
    //Call API here, and I will also get a pointerPosition back as to
    //where I am inside the buffer when finishing reading the object
    Object parsedObject = parse(checkBuffer, &pointerPosition)
    //Then calculate the size of bytes not read in checkBuffer
    int remainingBufSize = CheckBuffer.size() - pointerPosition;

    remainingBuffer.clear();
    remainingBuffer.reserve(remainingBufSize);
    //Then just copy over whatever is remaining in the checkBuffer into
    //remainingBuffer and make it be used in next iteration
    remainingBuffer.insert(remainingBuffer.end(),
   &checkBuffer[pointerPosition],&checkBuffer[checkBuffer.size()]);
}

A: Write append_chunk_into(in,vect).  It appends one chunk of data at the end of vect.  It does resizing as needed.  As an aside, a char-sized does-not-zero-memory standard layout struct might be a better choice than char.
To append to end:
size_t old_size=vect.size();
vect.resize(vect.size()+new_bytes);
in.read(vect.data()+old_size, new_bytes);

or whatever the read api is.
To parse, feed it vect.data().  Get back the pointer of when it ends ptr.
Then `vect.erase(vect.begin(), vect.begin()+(ptr-vect.data())) to remove the parsed bytes.  (only do this after you have parsed everything you can from the buffer, to save wasted mem moves).
One vector.  It will reuse its memory, and never grow larger than read size+size of largest object-1.  So you can pre-reserve it.
But really, usually most of the time spent will be io.  So focus optimizarion on keepimg the data flowing smoothly.

A: If I were in your position I would keep only the readBuffer. I would reserve READ_BUFFER_SIZE +sizeof(LargestMessage).
After parsing you would be given back a pointer to the last thing the api was able to read in the vector. I would then convert the end iterator to a pointer &*readbuffer.end() and use it to bound the data we have to then copy to the head of the vector. once you have that data on the head of the vector you can then read the rest in using that same data call except you add in the number of bytes remaining.  There does need to be some way of determining how many characters were in the remaining array but that shouldn't be insurmountable.


text:
Q: Build a project with gulp and requireJS mess up I desperately tried to compile a project using gulp and requireJS.
The project run nicely with AMD modules and requireJS in development environment.
I tried to use the requireJS optimizer relatively to this topic (3rd answer)
All i had is
requirejs task failed {"originalError":{}}

You can find my project here
Here is a screen that can help without browsing the project
project
Use the devDoc to generate project js files dependencies
EDIT:
here are the codes
gulpfile.js
(function () {
'use strict';

var gulp            = require('gulp'),
    bower           = require('gulp-bower'),
    requirejs       = require('requirejs'),
    requirejsConfig = {
        baseUrl       : './lib',
        name          : 'index',
        // optimizeCss   : "none",
        optimize      : "uglify",
        // removeCombined: true,
        // wrap          : true,
        mainConfigFile: './app/main.js',
        out           : './dist/app.js'
    };

// fail with "requirejs task failed {"originalError":{}}"
gulp.task('requirejs', function (taskReady) {
    requirejs.optimize(requirejsConfig, function () {
        taskReady();
    }, function (error) {
        console.error('requirejs task failed', JSON.stringify(error));
        process.exit(1);
    });
});

gulp.task('bower', function() {
  return bower({cmd: 'update'})
    .pipe(gulp.dest('lib/vendor'));
});

gulp.task('default', ['bower']);
}());

main.js
require(
['jquery', 'message', 'forms', 'websocket', 'user', 'chat', 'bootstrap'],
function ($, Message, FormsManager, WebsocketManager, User, ChatManager) {
    'use strict';

    var message   = new Message(),
        forms     = new FormsManager(message),
        user      = new User(message, forms),
        websocket = new WebsocketManager(message, user),
        chat      = new ChatManager(message, websocket, user, forms);

    // Bind WebSocket server callbacks
    websocket.addCallback(message.settings.serviceName, message.parseWebsocketData, message);

    // Make it global to develop
    window.WebsocketManager = websocket;
    window.ChatManager      = chat;
}
);

A: I built the project with success using those configuration files
app.js
requirejs.config({
"paths": {
    "bootstrap"       : "lib/vendor/bootstrap",
    "bootstrap-select": "lib/vendor/bootstrap-select",
    "bootstrap-switch": "lib/vendor/bootstrap-switch",
    "domReady"        : "lib/vendor/domReady",
    "jquery"          : "lib/vendor/jquery",
    "lodash"          : "lib/vendor/lodash",
    "require"         : "lib/vendor/require",
    "chat"            : "lib/chat",
    "forms"           : "lib/forms",
    "message"         : "lib/message",
    "user"            : "lib/user",
    "websocket"       : "lib/websocket"
},
"shim" : {
    "bootstrap" : {
        "deps": ['jquery']
    },
    "bootstrap-select" : {
        "deps": ['bootstrap']
    },
    "bootstrap-switch" : {
        "deps": ['bootstrap']
    }
}
// ...
});

requirejs(['main']);

app.build.js
({
name: "app.js",
mainConfigFile: 'app.js',
out: "../dist/app.js",
optimize: "uglify2",
preserveLicenseComments: false,
generateSourceMaps: true,
optimizeAllPluginResources: true, // usefull ?
findNestedDependencies: true,
wrap: true,
include: ["lib/vendor/require.js"]
})

gulpfile.js
(function () {
'use strict';

var gulp            = require('gulp'),
    bower           = require('gulp-bower'),
    mainBowerFiles  = require('main-bower-files'),
    del             = require('del'),
    shell           = require('gulp-shell');

gulp.task('build', shell.task('node ./node_modules/requirejs/bin/r.js -o app.build.js'));

gulp.task('bower_install', function () {
    return bower();
});

gulp.task('bower_move', ['bower_install'], function () {
    return gulp.src(mainBowerFiles()).pipe(gulp.dest('lib/vendor'));
});

gulp.task('bower_clean', ['bower_move'], function () {
    del(['lib/vendor/*', '!lib/vendor/*.js']);
});

gulp.task('default', ['bower_install', 'bower_move', 'bower_clean']);
}());

It was such an hard task, and automatize this task using gulp was kinda hard too Maybe I'm just a noob but building this project was very difficult. I hope it will help someone to save precious hours.


text:
Q: Facebook API suggestion I need help about the connecting to facebook via api or like that.
I have community users, and they trusting to my application (just a idea) and they gave me their facebook, friendfeeds, twitter username and passwords.
Then i need to send status update to these social networks via their apis.
I found twitter and some social networks connection via api programmatically and they working on my project, but facebook isn't.
Facebook api talking about the facebook connect and it need to httpcookies for authenticating and authorizating the users. But my application's messaging layer working on the middle layer of the my application. So, i have tried to find some solution for connecting to facebook programmatically for per user requests, i didn't anything.
Can someone tell me please, how can do that ?
Also, is there any api or any example code available over the internet for connect to facebook with username and password without API key or SecretKey and so on..
Thank you

A: First of all: collecting people's usernames and passwords is insane. Don't do that. You should be a trusted source and in this day and age of openID and OAuth platform authentication, it's just not necessary or acceptable. Twitter has an authentication method similar to Facebook Connect now as well: http://apiwiki.twitter.com/OAuth-FAQ
That being said...to answer your question, Facebook doesn't have a "direct" API that you can just query. Facebook Connect is a different beast than that of say Flickr, Twitter, or YouTube APIs. You would have to create an application on Facebook and use Facebook Connect to authenticate the user (they login ON Facebook, not giving you any information) first. You cannot access their email or password, but you can contact them through the Facebook API once authenticated. The API is quite limited in what you can access and also has limits on what data specifically you can cache.
Once the user has authenticated your application, you can use the javascript or php libraries to set their status and post wall posts: http://wiki.developers.facebook.com/index.php/Users.setStatus. Please note that to update status you first have to prompt your user to give you the status_update extended permission.
Edit: No, you can't access user's data without an api key or secret or without them authenticating you. Again, asking people for their account information is very shady (IMO).

A:
Facebook is suing Power.com, a
  Brazilian start-up that lets users
  access a number of social networks
  through one portal.

check the article here
That said you might be ok with Facebook Connect


text:
Q: chemfig fehling's reagent I'm trying to draw Fehling's reagent with chemfig.
Here what I come up with
\documentclass{standalone}
\usepackage{chemfig}

\begin{document}
\chemfig[atom sep=20pt]{[:-30]Cu*7(-[:30]O-(=[:-70]O)-[:-30](-OH)-[:-90](-OH)-[:150](=[:70]O)-[:180]O-)}
\end{document}

How do I draw the second cycle (symetric from the first one on cupper atom) ?

A: You can use two identical rings in sequence, just change the angle so that the second is opposite the first
\documentclass{article}
\usepackage{chemfig}

\begin{document}
    \chemfig{Cu*7([:-25.7]-O-(=O)-(-OH)-(-OH)-(=O)-O-)*7([:180]-O-(=O)-(-OH)-(-OH)-(=O)-O-)}
\end{document}

A: I have a very nasty solution:
\documentclass{article}
\usepackage{chemfig}

\begin{document}
\chemfig[atom sep=20pt]{[:-30]Cu*7(-[:30]O-(=[:-70]O)-[:-30](-OH)-[:-90](-OH)-[:150](=[:70]O)-[:180]O-)}
\hskip-5.35cm\hflipnext%
\chemfig[atom sep=20pt]{[:-30]Cu*7(-[:30]O-(=[:-70]O)-[:-30](-OH)-[:-90](-OH)-[:150](=[:70]O)-[:180]O-)}
\end{document}

If someone has a better solution, I am interested in


text:
Q: In which argument is the scalar product linear, and in which is it antilinear? I've been reading about Hilbert spaces and I noticed something that bugs me. All the math books state that the scalar product is linear in its first argument and  antilinear in the second, while all the physics books say it's linear in the second argument and antilinear in the first.
I'm confused. Am I right to assume that the conversion between mathematical and bra-ket notation is:
$$\langle a,b\rangle=\langle b|a\rangle$$
or is there something else going on here?

A: Yes, the standard convention differs between mathematics and physics, and yes,
$$ \langle a,b\rangle = \langle b\vert a\rangle$$
would be one way to deal with that when translating from one field to the other. There's nothing going on here except that the physicist conceives of the ket as the "normal" vector and the bra as its conjugate, so multiplying the ket with a scalar must be linear and the multiplying the bra must be anti-linear.


text:
Q: java run bash script, command not found I tried to use java to run some bash script and store the terminal output in a string. However, there are a lot of commands don't work in this way. It keeps showing command not found, but I can run those commands correctly in terminal, ex node --version, go --version. I guess is the path issue, but have no idea how to fix it.
Another question, when I run "python --version", it shows "Python 2.7.10" but it is in getErrorStream. Can anyone give me some hint?
public static void runscript() throws IOException {
    Runtime rt = Runtime.getRuntime();
    String[] commands = { "/bin/bash", "-c", "node --version" };
    Process proc = null;
    try {
        proc = rt.exec(commands);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    // read the output from the command
    System.out.println("Here is the standard output of the command:\n");
    String s = null;
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
    }

    // read any errors from the attempted command
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
    }
}

A: Reply @VishalKamat comment.
when I tried using the output of "which node" as my path, which is "/usr/local/bin/node". It works!!!
But, does that mean I have to change the path when I need to get different application version info?
I thought I can easily get the info just like I do in terminal.
I try to print $PATH by java in this way
String[] commands = { "/bin/bash","-c", "$PATH" };

The error msg is :
/bin/bash: /usr/bin:/bin:/usr/sbin:/sbin: No such file or directory


text:
Q: List all items from the S3 Bucket with API Gateway on AWS I'm using API Gateway to get my images on S3, but I'm only able to get an object that I already know the name of.
So I need a way to list all the items in the bucket so I can get the objects I want.
https://awsdomain/v1/s3/?key=name-bucket%2Fname-object


text: Q: Recycle Fragment Views when using ViewPager (Mvvmcross) I am using a ViewPager in an Mvvmcross Android App. The Fragments inside the ViewPager are all of the same kind. Is there a possibility to use some view recycling to avoid inflating a new view when scrolling through the ViewPager?


text:
Q: Signed cookies between subdomains on CloudFront Having trouble setting a cookie (subdomain to parent) in a CloudFront configuration:

*

*S3 bucket serving a static site with a CloudFront distribution. CNAME: example.com

*API Gateway API with a custom domain: api.example.com

*S3 bucket with a CloudFront distribution with CNAME: files.example.com
The web application on example.com contacts a lambda proxy GET method on api.example.com. This function, among other things, returns headers with values generated by AWS.CloudFront.Signer.getSignedCookies()
{
    'Set-Cookie': `CloudFront-Expires=...; Domain=.example.com`,
    'SEt-Cookie': `CloudFront-Signature=...; Domain=.example.com`,
    'SET-Cookie': `CloudFront-Key-Pair-Id=...; Domain=.example.com`
}

These are being sent to the client with the response, but for some reason are not sent in GET requests to the S3 bucket on files.example.com.
I am not certain if the issue is with the cookies being set or being sent: By looking at the application tab in chrome dev tools it seems that the cookies aren't there. However, in the network tab the cookies are indeed being sent alongside requests to api.example.com (but not with requests to files.example.com).
As far as I can tell the configuration should work in terms of Domain cookie policy (the subdomain is attempting to set a cookie with a parent domain, under which is a different subdomain of the parent, that should receive the cookies). Any other immediate suspects for this sort of behaviour?

A: You want to use the cookie domain .example.com instead of example.com. The leading . allows subdomains to access the cookie as well.
You also need to ensure that the cookies are being forwarded to the origin in your CloudFront behavior.


text:
Q: Applied Example of Coriolis Force/ Effect for an Object Moving around Earth There are very few examples on the Internet about how to calculate the Coriolis Force of an object moving around Earth.
Could you give me your feedback about how I proceeded ?

The Coriolis Force is given by
$$\overrightarrow{F_c} = 2m (\overrightarrow{v} \times \overrightarrow{\omega}) $$
So the important point is that we are dealing with vectors, so we need to use an appropriate coordinate system. We are given this Coordinate System :

We need the mass, the velocity, the direction and the latitude of the object that travels around the planet. So for example we have an object with a mass of $ m = 4.09 \cdot 10^5$ kg traveling at a speed of $ v = 300 \frac{km}{h} = \frac{300}{3.6} \frac{m}{s}$, in direction south, and a latitude of $53.55°N$.
We will also need the value of the angular velocity $\omega$ of Earth Rotation wich is $\frac{2\pi}{24\cdot 60 \cdot 60} \frac{\text{rad}}{s}$
Now, the most important point is to get the vectors right. Then we simply need to compute the cross product, plug in the values, and we are done.
Knowing the object moves south, and by looking at our coordinate system, we get : $\overrightarrow{v} = (0,-v,0)$. And for $\overrightarrow{\omega} = (0, \omega \cdot \cos\phi, \omega \cdot \sin\phi)$.
We now evaluate the Cross Product and get $\overrightarrow{v} \times \overrightarrow{\omega} = (-v \cdot \omega \cdot \sin\phi,
 0, 0)$.
The angle $\phi$ is equal to the latitude, so in our case $\phi = 53.55° = 0.935$ radians.
We now simply need to plug in all numbers. We get (units in Newtons)
$$\overrightarrow{F_c} = 2m (\overrightarrow{v} \times \overrightarrow{\omega}) = 2m(-v \cdot \omega \cdot \sin\phi,
 0, 0) = (-4000, 0,0) $$
Looking at the Coordinate System, we can see that the Coriolis Force points toward west when the object moves in direction south. The direction could also quickly be obtained with the right hand rule.
Is this correct ?
Thank you for your feedback !

EDIT : Special Case at the Equator
For an object at the Equator, the methodology above is the same. At the Equator, Latitude is zero so $\phi = 0$, $\sin \phi = 0 $ and $\cos \phi = 1$.
So the angular velocity vector is $$\overrightarrow{\omega} = (0, \omega \cdot 1, \omega \cdot 0) = (0, \omega, 0)$$
If the object moves North or South at the Equator, the Coriolis Force is zero because $$\overrightarrow{v} = (0,\pm v,0)$$ and $$ \overrightarrow{v} \times \overrightarrow{\omega} = (0,0,0)$$
However, if the object moves West or East at the Equator, we have $$\overrightarrow{v} = (\pm v,0,0)$$ and $$ \overrightarrow{v} \times \overrightarrow{\omega} = (0, \mp v\cdot \omega \cdot \sin\phi,\pm v\cdot \omega \cdot \cos\phi) = (0, \mp v\cdot \omega \cdot \sin0,\pm v\cdot \omega \cdot \cos0) = (0,0,\pm v\cdot \omega)$$
So we can see that an object moving West at the Equator has a Coriolis Force pointing inside Earth, and moving East pointing toward outer space.
The Eötvös Effect is closely related, see more on Wikipedia : https://en.wikipedia.org/wiki/E%C3%B6tv%C3%B6s_effect

I hope I made no mistake. Feel free to comment if anything is unclear ! Thanks for your feedback !


text:
Q: Abelian Group as the quotient of a free Abelian Group Is it true that every abelian group $G$ is the quotient of a free abelian group $F$?
I think so, since every abelian group $G$ is the quotient of a free group
 $H$ under some relations, but some of them are the commutators of the generators, thus if I quotient by those relations first, I get a free abelian group $F$, then I can take the quotient of the other relations getting the result as requested.
Thanks!

A: Yours is one possible way to show this.
One can also directly use the universal property of the free abelian group: Given an abelian group $G$ let $A(G)$ be the free abelian group on the underlying set of $G$. Then by the universal property of the free abelian group there exists a unique group homomorphism $\varphi \colon A(G) \to G$ with $\varphi(g) = g$ for all $g \in G$. Then $\varphi$ is surjective and therefore $G \cong A(G)/\ker \varphi$.


text:
Q: Schwarz distribution as a derivative of a continuous function - can such continuous functions be chosen to have the same support? The Schwarz theorem states that any function $f$ form the Schwarz class of tempered distributions $S'(\mathbb R^n)$ is a sum of derivatives from some continuous tempered distributions $g_\alpha\in С(\mathbb R^n)$:
$$
f(x) = \sum_{|\alpha|\le m}\partial^\alpha g_\alpha(x).
$$
I seem to rememeber even a variant with one function $g$.
Suppose now that $\mathrm{supp} f$  is in a halfspace $\{x_n\ge 0\}$. Can one take functions $g_\alpha$ s.t. their supoprt is also in the same halfspace?
Is the same true with a convex domain instead of a halfspace?

A: Edit: my previous answer was wrong, try with
$\delta(x,y)=\delta(x)\delta(y)=(\partial_x \partial_y)^2xy 1_{x>0}1_{y >0}$ where $xy 1_{x>0}1_{y >0}$ is not equal to a polynomial on the whole of $x >0$.
For half-spaces it works due to how we can construct $g$ such that $f=(\partial_{x_1}\ldots\partial_{x_n})^m g$:
Take $\psi\in C^\infty(\Bbb{R}), \psi=0$ on $t < -1$, $\psi=1$ on $t > 0$ and
let $J_l \phi(x)=\int_{-\infty}^0 \phi(x+t e_l)dt, I_l\phi(x)=J_l\phi(x+\infty e_l)\psi(x_l)-J_l\phi(x)$.
Then given $f\in S'(\Bbb{R}^n)$ of order $m-1$ define the distribution $g\in S'(\Bbb{R}^n)$ by $$\forall  \phi \in S(\Bbb{R}^n) ,\qquad \langle g,\phi \rangle=\langle f,(I_1\ldots I_n)^m \phi \rangle$$


text:
Q: Make js file not accessible through web console This is most likely a very simple one.
I have created a game in canvas and js. However I stumbled upon a problem. As I can access the variables and code inside the chrome console, I can change f.ex. the player score to whatever I'd like. This is not very good.
Is there some way I can make the file and variables non accessible through the console for players to use?
Thanks!

A: You can put the whole script into an IIFE so that any variables declared will be scoped to the just-invoked function, rather than be on the top level and accessible anywhere. For example:
(function() {
  var playerName = 'bob';
  var turnCount = 1;
  // do stuff with playerName and turnCount,
  // they won't be accessible or changeable from the outside

  // you can declare functions and such here as well
  // which will also only be accessible from the inside

})();

Like this, referencing playerName from the console will fail.

A: you can use a proxy.
javascript proxy
or you can make an IIFE and expose only the required functions such as:
    var App = (function() {

    var test = '';

    var init = function() {
        App.test = 'test';
    };

    return {
        init: init
    };

})();

or define your properties as not writable with Object.defineProperty()


text:
Q: Renew a Long-Lived token used at server side with an Angular application and FB SDK My context:
An AngularJS application using the Javascript Facebook SDK, and my distinct server (REST APIs).
Workflow:
User is logged in the client through the FB SDK using the method FB.login(callback).
This later gives a short-lived token that is then sent to the server in order to transform it to a long-lived token.
I'm interested in the mechanism of refreshing the long-lived token after 60 days.
So, reading the doc, we found this:

Even the long-lived access token will eventually expire. At any point,
  you can generate a new long-lived token by sending the person back to
  the login flow used by your web app - note that the person will not
  actually need to login again, they have already authorized your app,
  so they will immediately redirect back to your app from the login flow
  with a refreshed token - how this appears to the person will vary
  based on the type of login flow that you are using, for example if you
  are using the JavaScript SDK, this will take place in the background,
  if you are using a server-side flow, the browser will quickly redirect
  to the Login Dialog and then automatically and immediately back to
  your app again.

If I interpret it well, when user is ALREADY logged in through FB.login(callback), a simple redirect to the Angular Application's login flow would allow to get a new short-lived token.
I imagine that the FB.login is immediately run anew in this case, without user interaction, as written.
I want to test it simply, so what I've done is:

*

*Logged in into the application through FB.login(callback).

*Clicked on a dummy link making a simple redirect with:  window.location.replace('/');
My application being a single page application, every URL should be considered as the authentication page.
But the FB.login isn't run in the background, as I expected from the doc.
What would be the reason?
Does it work only when the domain making the redirect is distinct from the client? (I just can't test this case right now)
Did I misinterpret the doc?


text:
Q: How do I run/src an HTML file inside another (or a div)? I am trying to src an html file inside another but preferably inside the div of another html file. I tied using the following:
 <? include("./NavigationTree.html"); ?>

but nothing happened. The html files are located in the same folder. And am trying to run the file in the container-inner div.
 Here is my div code:

Thanks!

A: *

*A number of server side tools can do this (Apache Velocity, Java Server Pages, PHP and many others).

*jQuery and maybe some other client-side JavaScript tools can also do.

*HTML supports iframe that allows to include pages one inside another, but I would advise against using it just to organize the website content.

*It may be possible to find generating tools that would build static content including one file into another before it can be uploaded to the server.

Simple static HTML itself cannot be easily included one into another without rather clumsy and relatively complex JavaScript workarounds.

A: I suggest using jQuery. .load() method Then it will be a simple client-side JavaScript call:
$('.container-inner').load('./NavigationTree.html');

A: You might consider using an iframe

The HTML  Element (or HTML inline frame element) represents a nested browsing context, effectively embedding another HTML page into the current page. In HTML 4.01, a document may contain a head and a body or a head and a frame-set, but not both a body and a frame-set. However,an  can be used within a normal document body. Each browsing context has its own session history and active document. The browsing context that contains the embedded content is called the parent browsing context. The top-level browsing context (which has no parent) is typically the browser window.


text:
Q: c++ pointer error (access violation) I am new to C++ and think I am probably doing something I shouldn't be with pointers. I've checked tons of resources, but just can't find the problem. After debugging for a while it looks like this is the problem code.
writeHeader(outFile, width, height);
for (int row=0; row < width+1; row++){ // row == 0 is the bottom row
    for (int col=0; col < height+1; col++){ // col == 0 is the leftmost column
    Color c =  getPixel(row, col);
    outFile.write((char*)c.blue, 1);
    outFile.write((char*)c.green, 1);
    outFile.write((char*)c.red, 1);
    }
}

can anyone see what is wrong?
The getPixel method looks like this.
Color BMPCanvas::getPixel(int x, int y){
if (x<=width && y<=height){
        return image[y*width + x];
    }
    return Color(0,0,0);
}

EDIT: I changed the above code to:
    for (int row=0; row < width; row++){ // row == 0 is the bottom row
        for (int col=0; col < height; col++){ // col == 0 is the leftmost column
        Color c =  getPixel(row, col);
        unsigned char green = c.green, blue = c.blue, red = c.red;
        outFile.write((char*)&blue, 1);
        outFile.write((char*)&green, 1);
        outFile.write((char*)&red, 1);
        }
    }

which I believe fixed one of the problems, but I am still getting a memory error. Green blue and red refer to numbers referring to their color value such as (255,255,255).
I truly appreciate the help.

A: My best guess would be you have an "off by one" error.  C++ arrays are zero based and so when you have an array with 10 slots you iterate from 0 to 9, not 0 to 10.
Try changing getPixel to this:
Color BMPCanvas::getPixel(int x, int y){
if (x<width && y<height){
        return image[y*width + x];
    }
    return Color(0,0,0);
}

And your other loop to this:
for (int row=0; row < width; row++){ // row == 0 is the bottom row
    for (int col=0; col < height; col++){ // col == 0 is the leftmost column


text:
Q: How to develop an Opengeo Suite Client SDK with Eclipse? I have a problem in developing an Client SDK application with Eclipse, maybe someone already do this.
I started by creating a new application with the Client SDK by following the tutorial :
http://suite.opengeo.org/docs/apps/clientsdk.html
Then, I managed to debug the application. Now, i want to go on developing by using the Eclipse IDE.
So I created a new project, imported code source from the application I've just created with the suite-sdk command from tutorial.
In my index.html file, I change the line like this :
<!-- app resources -->
<script type="text/javascript" src="src/app/app.js"></script>

Then, I run the application. Error on Firebug appears :
ReferenceError: gxp is not defined
var app = new gxp.Viewer({

It seems like the ** @require widgets/Viewer.js* line isn't read.
/**
 * Add all your dependencies here.
 *
 * @require widgets/Viewer.js
 */

var app = new gxp.Viewer({

Subsequently the buildjs.cfg file isn't take into account : this file contains the beginning path to the Viewer.js file : /openGeo/src/gxp/script/widgets/Viewer.js.
[app.js]
root =
    src/openlayers/lib
    src/geoext/lib
    src/gxp/script

I really don't know how to solve this problem, maybe it's not due to these file...
Thanks for advance for any help.
Helena

A: You cannot run an SDK app directly from the directory structure. You need to run
$ suite-sdk debug <yourapp>

from the console. You can leave this running, it will pick up your changes. The only exception is that if you add dependencies (@require ...), you have to Ctrl-C and restart.


text:
Q: decimal expansion and square roots given a decimal expansion
$$ 0.345345345... $$
then we can recover the fraction from this decimal expansion , in this case $ \frac{345}{999} $
my question is if for a non-periodic decimal expansion
$$ 0.451235132535126535126164616146462462 $$ we can find two numbers a and b integers so
$$ a+ \sqrt{b} = 0.451235132535126535126164616146462462 $$ or if there is a theroem which make it an impssible task.

A: If you suspect your number is of this form, you can look at its continued fraction.  Anything of the form $a + \sqrt{b}$ with $a$ and $b$ rational will have an eventually  periodic continued fraction, and you can recover $a$ and $b$ from that.  For example, your $0.451235132535126535126164616146462462$ has continued fraction
$$[0; 2, 4, 1, 1, 1, 2, 9, 6, 1, 262, 4, 2, 13, 2, 4, 1, 1, 37, 1, 1, 88, 1, 1, 1, 4, 1, 4, 2, 2, 1, 2, 6, 2, 1, 8, 1, 4, 1, 1 \ldots]$$
i.e.
$$ 0 + 1/(2 + 1/(4 + 1/(1 + 1/\ldots $$
and this gives no sign of becoming periodic.

A: We can't do this for transcendental numbers. If we could do this for a transcendental number $\alpha$, then $\alpha$ would be a root of a polynomial of the form $$x^2-2ax+a^2-b,$$ which is impossible.

A: There's a lot of decimal places after $46462462\ldots$ in your question.  If you only want a finite number of decimal places to match, then yes, it is always possible to find integers $a,b$ such that $a + \sqrt{b}$ agrees with some fixed irrational number to any given precision (the higher the precision, the larger $a$ and $b$ might have to be).  The reason that's true is that the sequence $\{\sqrt{n}\}$ increases to infinity but slowly, in the sense that $\sqrt{n+1} - \sqrt{n} \to 0$.   Any sequence with these two properties will have its fractional parts dense in $[0,1)$.
On the other hand, if you want the two sides to be exactly equal, then this is usually not possible, because there are only countably many pairs of integers and uncountably many real numbers.  A very nice feature of quadratic irrationals is that they may be identified by a periodic continued fraction, much like a rational number can be identified by a periodic decimal expansion.
In this sense you can compute continued fraction coefficients to convince yourself that a given sequence of digits has the form $a + \sqrt{b}$, with the caveat that one can only compute finitely many digits, and any finite number of digits might appear to match $a + \sqrt{b}$ (see the first paragraph) only to disagree in the next digit.


text:
Q: LibreOffice Base crashes on 32bit arch for 16.04 and 17.04 I launch LibreOffice base, create a new base, use all the default (HSQLDB), just click next, OK, chose a file name, click OK, and it crashes.

soffice.bin crashed with SIGSEGV

It is a 32-bit machine, It crashes with 16.04 (tried OpenJDK 8.131 and Oracle Java 8.144 and tried updating LO to latest version), it crashes also with the newest 17.04, fully updated.
I tried on a physical machine and on another one in VirtualBox.
It does not crash using a 64bit install.
Any hint??

A: I finally found some info. Issue started mid June 2017.

*

*LibreOffice Base does not work on a 32 bit Linux machine

*It should be fixed with a new kernel release (hopefully)

*It is a change in the kernel (security fix) that affected Java that is required for LibreOffice Base

*Neither Ubuntu or LibreOffice or OpenJDK can fix this kernel issue (OK, maybe OpenJDK could also fix it)

*There IS a workaround (tested on 16.04 and 17.04): "Add kernel parameter stack_guard_gap=1"

Edit the file /etc/default/grub and change the line beginning GRUB_CMDLINE_LINUX_DEFAULT to include the parameter, for example after your edit it may look like this:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash stack_guard_gap=1"

then run sudo update-grub and reboot.
You should remove this parameter when the new kernel solve the issue (test), because I guess is it less secure without stack_guard ...
References:

*

*The Ubuntu bug report

*The LibreOffice bug report

*A Linux Kernel Mailing List post by Ben Hutchings

*Problematic code
Looks like I cannot post more than 2 Links here. But complete answer is here at ask.libreoffice.org.


text:
Q: emailing with php What's wrong with this...? I don't get an email back...
Also, does the from address have to be a real address? If I run this on a computer that doesn't have Outlook Express, will it not work? How can I make it work on computers like that?
<html>

<head>
<title>Test php</title>
</head>

<?php
$to = "asjjohnson127@aim.com";
$subject = "testing php emailing";
$from = "asjjohnson127@gmail.com";
$headers = "From: $from";
$message = "Your username is " . $_POST['username'];
if (mail($to,$subject,$message,$headers))
    echo "Mail Sent.";
else
    echo "Problem with mail.";
?>

<body>
</body>
</html>

A: If your running the script on a local server you'll need to configure the php.ini look for the following and change to your ISP's SMTP server.
[mail function]
SMTP = smtp.isp.net
sendmail_from = me@isp.net

You code will send email, its an issue with your SMTP configuration.
Another way to do it is set SMTP to localhost then use a SMTP service http://www.softstack.com/freesmtp.html usually runs on port 25 If I remember correctly.

A: You have to send mail from a machine that can be accessed directly from outside - via IP or URL. Having Outlook has absolutely nothing to do with that.

A: Outlook is an email client, you need to connect to an email server, the easy way is to buy a cheap hosting account as this replaces the option where you have to setup your own email server.(Some ISP block port 25 to prevent spam)


text:
Q: SQL Server Multiple cascade sequence Assume Table A has two children tables, B and C with cascade delete between A-B, and cascade delete between A-C.
When a row is deleted in A, the matching rows from B and C are deleted.
How does SQL Server determine the order of the Cascades to fire? What I need is to fire the A-C cascade delete before the A-B cascade delete fires.
I know I can do this with triggers, but I don't want to, unless I absolutely have to.

A: If the order is that important, this is a database design smell and it also points to the fact that you probably should not be using cascading deletes for this data integrity operation.


text:
Q: What does IAppbuilder.UseWebApi do? I've recently been working on an MVC site that has an api and in the startup.cs there is a line that says app.UseWebApi. I did some searching but I couldn't find a decent answer of what it does. Can someone please explain the concept for me? Thanks!

A: You need to install Microsoft ASP.NET Web API2 OWIN Self Host which will resolve the issue.
You can use the following NuGet command shown below:
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

A: It configures ASP.NET Web API to run on top of OWIN. OWIN abstracts a web server and you can run it on top of both IIS as well as HTTP.SYS which allows you to provide a web server in your own console application. To be more specific the piece that runs on top of IIS or HTTP.SYS is Katana which is an implementation of the OWIN specification.
By calling app.UseWebApi you configure OWIN/Katana to send web requests through ASP.NET Web Api that in OWIN terminology is considered a middleware. This requires the NuGet package Microsoft.AspNet.WebApi.Owin.
Interestingly, ASP.NET MVC 5 cannot be configured as an OWIN/Katana middleware. it depends on System.Web and expects the HttpContext singleton to exist so it has to run on top of IIS. However, several NuGet packages that can be used in MVC projects (e.g. for authentication) is built on top of OWIN instead of taking a dependency on HttpContext which makes them more useful. That is one explanation of why you see OWIN used in a MVC project.


text:
Q: more entities are getting loaded into one entity , but expected only one .... How to stop unwanted entity loading in Criteria API? Hi i'm joining 4 tables(Entities) with root entity , along with 9 optional conditions .
        IPRInterestTypeValue entity have one to many relationship with IPRInterestSubTypeValue,and join type is LAZY . While fetching result root entity by applying conditions expectation is 1 IPRInterestTypeValue  along with 1 child entity (IPRInterestSubTypeValue).if The query generated is excecuted in DB  its giving expected result , but while inspecting  result root entity  its generated some more select queries and more number of child(IPRInterestSubTypeValue) are loaded into root entity.here is my joinig implimentation here reference name for getting and joing are declared seperately  How to stop unwanted entity loading?
   CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
    CriteriaQuery<IPRInterestTypeValue> criteriaQuery = criteriaBuilder.createQuery(IPRInterestTypeValue.class);
    Root<IPRInterestTypeValue> iprInterestTypeValue = criteriaQuery.from(IPRInterestTypeValue.class);

    Join<IPRInterestTypeValue, IPRInterestPackage> iprinterestPackage = iprInterestTypeValue.join(INTEREST_PACKAGE, JoinType.INNER);

    Join<IPRInterestTypeValue, IPROrgInterestTypeProductType> iprOrgInterestTypeProductType =iprInterestTypeValue.join(INTEREST_TYPE_PRODUCT_TYPE,JoinType.INNER);

    Join<IPRInterestTypeValue, IPRInterestSubTypeValue> iprInterestSubType = iprInterestTypeValue.join(INTEREST_SUBTYPE_VALUES, JoinType.INNER);

    Join<IPRInterestSubTypeValue, IPRInterestRate> iprinterestRate = iprInterestSubType.join(INTEREST_RATES, JoinType.INNER);

   // iprInterestTypeValue.fetch("INTEREST_SUBTYPE_VALUES",JoinType.INNER);
    List<Predicate> predicates = new ArrayList<Predicate>();

    Expression<Date> validFromDate = iprinterestRate.<Date> get(VALID_FROM);

    Expression<Date> validToDate = iprinterestRate.<Date> get(VALID_TO);

    predicates.add(criteriaBuilder.equal(iprinterestPackage.get(ORG_ID), orgId));
    if (null != interestPackageId) {
        predicates.add(criteriaBuilder.equal(iprinterestPackage.get(INTEREST_PACKAGE_ID), interestPackageId));
    }
    if (null != interestPackageKey) {
        predicates.add(criteriaBuilder.equal(iprinterestPackage.get(INTEREST_PACKAGE_KEY), interestPackageKey));
    }
    if (null != interestSubtypeId) {
        predicates.add(criteriaBuilder.equal(iprInterestSubType.get(INTEREST_SUBTYPE_VALUE_ID), interestSubtypeId));
    }
    if (null != interestTypeCode) {
        predicates.add(criteriaBuilder.equal(iprOrgInterestTypeProductType.get(INTEREST_TYPE_CODE), interestTypeCode));
    }
    if (null != interestRateStatus) {
        predicates.add(criteriaBuilder.equal(iprinterestRate.get(STATUS), interestRateStatus));
    }

    if (searchPeriod != null && String.valueOf(SearchPeriod.CURRENT).equals(searchPeriod)) {
        predicates.add(criteriaBuilder.equal(validFromDate, currentDate));
    }

    if (searchPeriod != null && String.valueOf(SearchPeriod.PAST).equals(searchPeriod)) {
        predicates.add(criteriaBuilder.lessThan(validToDate, currentDate));
    }

    if (searchPeriod != null && String.valueOf(SearchPeriod.FUTURE).equals(searchPeriod)) {
        predicates.add(criteriaBuilder.greaterThan(validFromDate, currentDate));
    }
    criteriaQuery.where(criteriaBuilder.and((predicates.toArray(new Predicate[predicates.size()]))));
    criteriaQuery.orderBy(criteriaBuilder.desc(iprInterestTypeValue.get(INTEREST_TYPE_PRODUCT_TYPE).get(MANDATORY)), criteriaBuilder.asc(iprinterestRate.get(STATUS)));
    List<IPRInterestTypeValue> interestTypeValue = super.getResultListByCriteria(criteriaQuery, pagingElement);
    super.flush();
    return prepareInterestTypeSubTy


text:
Q: Equivalent for $R_n=\sum_{p=n+1}^{+\infty}\frac{\sqrt{p}}{p!}$ I'm asked, as $n$ tends to $+\infty$, to find an equivalent form for $$ R_n=\sum_{p=n+1}^{+\infty}\frac{\sqrt{p}}{p!}.$$   I've just found that $$0\leq R_n \leq \sum_{p=n+1}^{+\infty}\frac{1}{(p-1)!}=e-\sum_{p=0}^{n}\frac{1}{p!}.$$ I'm having problems estimating the last sum. Thank you.

A: We have
$$R_n=\sum_{p=n+1}\frac{\sqrt p}{p!}=\sum_{p=n}^\infty\frac1{p!\sqrt{p+1}}=\frac1{n!\sqrt{n+1}}+\underbrace{\sum_{p=n+1}^\infty\frac1{p!\sqrt{p+1}}}_{=R'_n}$$
and
$$R'_n\le\frac1{\sqrt{n+2}}\sum_{p=n+1}^\infty\frac1{p!}\le \frac1{(n+1)!\sqrt{n+2}}\sum_{k=0}^\infty\frac1{2^k}$$
so we see that
$$R_n=\frac1{n!\sqrt n}+o\left(\frac1{n!\sqrt n}\right)$$
hence we conclude
$$R_n\sim_\infty\frac1{n!\sqrt n}$$

A: The Stirling's inequality gives:
$$ n! \geq n^n e^{-n}\sqrt{2\pi n} $$
hence:
$$\frac{\sqrt{p}}{p!}\leq \frac{1}{\sqrt{2\pi}}\left(\frac{e}{p}\right)^p $$
and:
$$\sum_{p>n}\frac{\sqrt{p}}{p!}\leq\frac{1}{\sqrt{2\pi}}\sum_{p>n}\left(\frac{e}{n}\right)^p \leq \frac{\left(\frac{e}{n}\right)^n}{\sqrt{2\pi}\left(1-\frac{e}{n}\right)}.$$


text:
Q: Chrome Incognito mode save history i have simple question, is here some option how to trace google chrome history in incognito mode? Some extension, settings, extra software or maybe some files stored in temp files?

A: In theory it's possible for an extension to track what you're doing in incognito. By default all extensions are disabled in incognito mode, probably for the very reason that they could potentially track you, but they can be set to 'enabled in incognito'.
A simplier solution might be to capture all traffic flowing through your network or to use a keylogger.