text:
Q: Excel to xml conversion not working for columns with different datatype values starts from number to string I am facing a problem while reading the excel and writing them to XML using LINQ to XML.
I am having a column name as PinCode which has values like
9999
12
"123"
"20"
"999"
3
While converting the excel to dataset I have the values 9999,12,3. I am not able to retrieve the values in string format.
I dont want to change the formats in excel sheets. Is it possible to change the connectiion string to read all the data in a column irrespective of the datatype of the column
Note:- I tried using IMEX=1 in extended properties it is not working.
Reading the data like this
private static OleDbDataReader GetDatafromExcel(OleDbConnection oledbConn)
        {
            OleDbDataReader OledBReader = null;
            try
            {
                string query = "SELECT * FROM [Sheet1$]";
                OleDbCommand oledbCommand = new OleDbCommand(query, oledbConn);
                OledBReader = oledbCommand.ExecuteReader();

            }
            catch (Exception ex)
            {

            }
            return OledBReader;
        }

A: Caution - known hack -
For the first record in the Excel spread sheet make it '9999 instead of 9999.  This should treat the values as a string instead of a number.
alt text http://www.freeimagehosting.net/uploads/86e14302e9.png


text:
Q: Matlab: vertical lines at x-values specified by vector I have a vector of x-values at which I would like to add vertical lines to a graph, say a row vector: vec = [1 2 3 4 5]
I know that you can add single vertical lines like this:
plot([1 1],[0 1])
(gives a vertical line at x=1 from y=0 to y=1).
But when I try something like
vec = [1 2 3 4 5];
lowLine = [0 0 0 0 0];
highLine = [1 1 1 1 1];
plot([vec vec],[lowLine highLine])
It does not give the required result, instead it gives a z-shape. Where am I going wrong?

A: In order to plot several lines in a single plot, you need to use the fact that MATLAB's plot function handles matrices as inputs, and that it sees each column of the inputs as different plots :

If X and Y are both matrices, then they must have equal size. The plot
  function plots columns of Y versus columns of X.

Thus, in order to get the expected result, you need to write :
vec = [1 2 3 4 5];
lowLine = [0 0 0 0 0];
highLine = [1 1 1 1 1];
plot([vec;vec],[lowLine;highLine])

Result :

redpajama_set_name: RedPajamaStackExchange


text:
Q: Draw fixed line in real time graph jfreechart So far I use TimeSeriesChart and DynamicTimeSeriesCollection to creat a chart like this:

But the requirement is to let user click on the graph and define a "High" and "Low" boundary like the below picture:

I've got this block of code to get the value when we click mouse on the graph:
public void chartMouseClicked(ChartMouseEvent cme) {
            Point2D p = chart.translateScreenToJava2D(cme.getTrigger().getPoint());
            Rectangle2D greyChartArea = chart.getChartRenderingInfo().getPlotInfo().getDataArea();
            double valueY = ((NumberAxis) plot.getRangeAxis()).java2DToValue(p.getY(), greyChartArea, plot.getRangeAxisEdge());
            double valueX = ((NumberAxis) plot.getDomainAxis()).java2DToValue(p.getX(), greyChartArea, plot.getDomainAxisEdge());
            System.out.println(valueY);
        }

The question is how to draw a fixed line when mouse is clicked with a real-time graph which has a dynamic x-axis? (Clicked points on the line should be movable and able to deleted)
Any pointers will be appreciated.
//Updated:

So far I can define my "High" and "Low" region by mouse but the problem is when the data comes in:
public void draw(Data data) {
    dataset.advanceTime();
    float[] info = new float[1];
    info[0] = data.getInfo();
    dataset.appendData(info);
}

the "High" and "Low" series will be disappeared or pushed away. Is there any way that can make "High" and "Low" fixed line?


text:
Q: Struggling with Keylisteners (Java) I've been following TheCherno's tutorial series on java game development. He uses sprites for only four directions, whereas I want to use for 8 ( up+right etc.)
I've been trying to get the code to return booleans for when two of the directional keys are pressed and I seem to have hit a stump, I'm not sure what to do next. Any ideas? Thanks.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashSet;
import java.util.Set;

public class Keyboard implements KeyListener {

    private Set<Character> pressed = new HashSet<Character>();
    public boolean up, down, left, right, upright, downright, downleft, upleft;

    public void update() {
        for (Character c : pressed) {
            if (c == KeyEvent.VK_A) {
                left = true;
            } else if (c == KeyEvent.VK_S) {
                down = true;
            } else if (c == KeyEvent.VK_D) {
                right = true;
            } else if (c == KeyEvent.VK_W) {
                up = true;
            }
        }

        if (up && right) upright = true;
        if (down && right) downright = true;
        if (down && left) downleft = true;
        if (up && left) upleft = true;

    }

    public void keyReleased(KeyEvent e) {

        pressed.remove(e.getKeyChar());

    }

    public void keyPressed(KeyEvent e) {

        pressed.add(e.getKeyChar());

    }

    public void keyTyped(KeyEvent e) {

    }
}


text:
Q: What is crtc and how many outputs can I enable using xrandr? I'm using a Lenovo x220i thinkpad, running crunchbang linux (which uses the openbox window manager). The laptop has a DP and VGA plug on the side.
Hooking up the DP and VGA cables and running xrandr, I notice that the following outputs are available/active:
VGA1
DP1
LVDS1  <- the laptop screen

If I try to enable more that 2 (using any combination), then I get the error "cannot find crtc for output for [VGA1/DP1/LVDS1]"
What is crtc? How do I find out how many are available? Is it possible to add more in software or perhaps through a PCI card?
Thanks.

A: CRTC stands for "Cathode Ray Tube Controller" but wikipedia prefers "Video Display Controller".
They are still often called CRTCs - technical terms can be slow to change sometimes.
There is always a more complicated explanation, but an adequate summary is that each CRTC corresponds to a video buffer on a video card that is destined to be output. I chose this specific wording to highlight some nuances:

*

*A software screen, such as the one used for a headless VNC server, will use RAM for video memory and not have anything to do with a video card, or get any hardware acceleration from one. No CRTCs needed because it's not on the video card.

*If you're using a video card to render a scene and then getting the final result's buffer back into memory/disk, there is no CRTC involved because it's not bound for output, despite using the video card's rendering capabilities and memory.

*A video card may support outputting one CRTC to multiple displays. They must be the same resolution and may or may not (I don't know) have to be the same frequency. Simply using display settings to "Show the same screen" on two or more displays is likely to not take advantage of this, and be mirroring the final buffer on two CRTCs. Making sure that a single CRTC is being cloned onto two displays is, so far, beyond my technical ability.

So to answer your other questions:

How do I find out how many [CRTCs] are available?

$ xrandr --listproviders  Providers: number : 1 Provider 0: id: 0x4d cap: 0xb, Source Output, Sink Output, Sink Offload crtcs: 4 outputs: 10 associated providers: 0 name:Intel
Notice that, like you, I have more outputs than CRTCs: crtcs: 4 outputs: 10, there are good reasons that outputs are numerous, mostly coming down to video ports having a lot of convenience baked in:

*

*A DisplayPort connector may have 2 or 3 outputs associated with it if daisy-chaining is supported.

*A DVI-I connector may be split into its digital and analog components to run one monitor of each type. The old lazy solution was to clone these in hardware, but it's now common for video devices to have a DVI and a VGA output associated with such a port.

*A laptop dock can easily double the number of outputs, and then some, because they want to offer the convenience of abundant extra connectors on the dock.

*A video device may have unimplemented connectors because it's been rushed to production or because it's a re-implementation of another device, but has some connectors omitted.

Is it possible to add more [CRTCs] in software or perhaps through a PCI card?

Since CRTCs are provided by a GPU, the only way to have more is to add a video device that will work simultaneously with the one you already have. I know this is possible, and that there are many limitations, but nothing more. You'll have to research multiple GPU setups to see if this is even feasible for you.

P.S. I am learning a lot of this just today and stumbled upon your question during my own research.

A: crtc stands for cathode ray tube controller. In ancient times, monitors used to use a CRT (the heavy devices made of glass) rather than the LCD display of today.

A: I'm afaid that it's hardware limitation in your display device.
I've simmilar situation - laptop(t430) with docking station. I can use in parallel 3 of monitors - 2*DP and LVDS or 3*DP or LVDS and DP and HDMI.. but enabling any monitor more show me the same error like yours.


text:
Q: How can I find all buildings of a certain type in Anno 1404? In Anno 1404, is there any way to find out how many buildings of a certain type (for example Carpenters) I have built in my settlement and where they are located? This is a not an issue in small settlements, but larger cities can be quite confusing.
Thanks,
Adrian

A: To answer my own question: The Venice Addon to Anno 1404 solves exactly this problem: By building the Bailiwick, you can see stats on all buildings on the same island and also reduce maintenance costs for production buildings.


text:
Q: Weight Decay in Neural Networks Can weights decay in neural network be negative?I know that usually it takes a value slightly less than 1.

A: This does not make sense. Let's consider (without loss of generality) L2-regularizer. In this case the (regularized) error function to be minimized takes form $$\widetilde{J}(\mathbf{w})=J(\mathbf{w})+\lambda\|\mathbf{w}\|_2^2.$$
Now if $\lambda<0$, $\widetilde{J}$ can be minimized trivially by letting $\|\mathbf{w}\|_2 \rightarrow +\infty$, and Neural Network won't learn at all. So only non-negative values of $\lambda$ are of interest.
Regarding $\lambda<1$, this actually depends on scale of the data, and typically the optimal value of $\lambda$ is found by cross-validation.
UPDATE: Even though $\lambda<0$ does indeed have no sence, the explanation was not completely precise. $J(\mathbf{w})$ might also go to infinity with this of $\|\mathbf{w}\|_2$.
Let's consider a simple example, linear regression $\mathbb{R}\ni\widehat{y}(\mathbf{x}):=\mathbf{w}\cdot\mathbf{x}+b,\mathbf{w}\in\mathbb{R}^d$ for only 1 data pair $(\mathbf{x},y)$. Loss function is $J(\mathbf{w})=(\mathbf{w}\cdot\mathbf{x}+b-y)^2$. A set $H_{\mathbf{x},\alpha}=\{\mathbf{w}\in\mathbb{R}^d | \mathbf{w}\cdot\mathbf{x}=\alpha\}$ defines $(d-1)$-dimensional hyperplane in $\mathbb{R}^d$ (linear subspace). If we choose any $\mathbf{w}\in H_{\mathbf{x},y-b}$, then $J(\mathbf{w})=0$ and we can let $\|\mathbf{w}\|_2 \rightarrow +\infty$ by keeping it in $H_{\mathbf{x},y-b}$. In case we have multiple points $\{(\mathbf{x}_1,y_1)\ldots(\mathbf{x}_N,y_N)\}$ we can perform the same for $\mathbf{w}\in H:=\cap_{n=1}^N H_{\mathbf{x}_n,y_n-b}$ provided linear subspace $H$ is non-empty (which is violated already for $N>d$ for linearly independent $\mathbf{x}_n$'s).
Thus $\widetilde{J}(\mathbf{w})$ might or might not be optimized in this way. But anyway, back to the original question, $\lambda<0$ has nothing to do with regularization goal of weight decay, which is to keep weights small. Vice versa, $\lambda<0$ will favor larger weights, which will possibly result in overfitting. Therefore, in this case the generalization performance of the machine learning algorithm is expected to be worse.


text:
Q: What expression is needed for mapping this property? I am trying to map two objects that are mostly similar with AutoMapper but one member (AudioSummary) raises the following exception :
The following property on EchoNestModel.AudioSummary cannot be mapped: AudioSummary
Add a custom mapping expression, ignore, add a custom resolver, or modify the destination type EchoNestModel.AudioSummary.
Context:
- Mapping to property AudioSummary from EchoNest.Api.AudioSummary to EchoNestModel.AudioSummary
- Mapping from type EchoNest.Api.TrackProfile to EchoNestModel.Profile
Exception of type 'AutoMapper.AutoMapperConfigurationException' was thrown.
Mapping definition
var map = Mapper.CreateMap<TrackProfile, Profile>();
map.ForMember(dest => dest.ForeignIds, opt => opt.ResolveUsing<ForeignIdResolver>());
map.ForMember(dest => dest.ForeignReleaseIds, opt => opt.ResolveUsing<ForeignReleaseIdResolver>());
map.ForMember(s => s.Media, t => t.Ignore());
map.ForMember(s => s.ProfileId, t => t.Ignore());
map.ForMember(s => s.AudioSummary, t => t.MapFrom(s => s.AudioSummary));

I've added the following two lines but a totally different error occurs :
map.ForMember(s => s.AudioSummary.Profile, t => t.Ignore());
map.ForMember(s => s.AudioSummary.AudioSummaryId, t => t.Ignore());

Expression 's => s.AudioSummary.Profile' must resolve to top-level member and not any child object's properties.
Use a custom resolver on the child type or the AfterMap option instead.
Parameter name: lambdaExpression
How can I successfully map AudioSummary ?
Source object

Target object

A: EDIT: In general, try AutoMapper.Mapper.AssertConfigurationIsValid();, this will show you all possible problems in your mapper setup.
From the information you provided, it looks like you need to define map for the AudioSummary classes (dest and source) as well:
    [TestFixture]
    public class MappingTest
    {
        public class SourceAudioSummary
        {
            public int Id { get; set; }
            public string OtherData { get; set; }
        }

        public class TrackProfile
        {
            public string Whatever { get; set; }
            public SourceAudioSummary AudioSummary { get; set; }
        }

        public class DestAudioSummary
        {
            public int Id { get; set; }
            public string OtherData { get; set; }
        }

        public class Profile
        {
            public string Whatever { get; set; }
            public DestAudioSummary AudioSummary { get; set; }
        }

        [Test]
        public void Mapping()
        {
            Mapper.CreateMap<SourceAudioSummary, DestAudioSummary>();
            Mapper.CreateMap<TrackProfile, Profile>();

            var trackProfile = new TrackProfile
                {
                    Whatever = "something",
                    AudioSummary = new SourceAudioSummary
                        {
                            Id = 1,
                            OtherData = "other"
                        }
                };

            var profile = Mapper.Map<TrackProfile, Profile>(trackProfile);

            Assert.That(profile.Whatever == "something");
            Assert.That(profile.AudioSummary.Id == 1);
            Assert.That(profile.AudioSummary.OtherData == "other");
        }
    }


text:
Q: Is there a library or an malloc implementation, which allocates memory on heap as/like on stack? I have a need to get heap memory in big chunks. And these memory chunks will be used as memory pools, and will not be released until the process exits.
So, the traditional malloc may be not as simple (nor as fast) as I want.
I think, a stack-like allocation (LIFO) would be more efficient than malloc.
Is there any existing libraries can do that?
Or should I write a new one for this purpose?
PS: I guess obstack best describes what I'm talking about. Any other candidate or introduction about obstack?

A: Listen to everyone else saying to just use malloc efficiently first, but if you really do need a region-based allocator, that can free stuff in big lumps, look to the Apache Portable Runtime library.

A: From Wikipedia:

In C, the library function malloc is used to allocate a block of memory on the heap.

malloc will be plenty simple and fast.
Also, what does this mean?

I think it will be OK to regard the heap memory allocation as the way on stack.

If you mean you want to use stack space for your memory pool, you'll be disappointed.  The stack is typically only a few MB (precise size depending on the machine and ?compiler).  Perhaps you have your ideas of stack and heap backwards?  The stack is where function frames, with arguments and local variables, go; the heap is where persistent, dynamically allocated memory goes.

A: malloc causes slowdown when it's called over and over again, like in the middle of a triply-nested loop.  If you're allocating a few large chunks with malloc and holding on to them for a long time, you're already using malloc efficiently.
For example, suppose you're working with 3D point data, and you have a struct Point.  If you worked with a Point ** array and allocated each point individually, like:
for (int i = 0; i < size; ++i)
    points[i] = malloc(sizeof(struct Point));

it would be slow.  But working with a block of struct Point instead of struct Point *, you figure out the size ahead of time and only call malloc once.
points = malloc(sizeof(struct Point) * size);

It's fine, because malloc only runs once.


text:
Q: Displaying text inside a control element with type edit Pretty simple: I would like to have a edit-field where there is already text inside (a kind of default value) but which is also editable.
I tried a lot of different version but nothing wanted to work yet.
This is the last version I tried (the checkbox works just fine):
<Property Id="MYPROPERTY" Value="default" />
        <UI>
            <Dialog Id="ConfigVariablesDlg" Width="370" Height="270">
                <Control Type="Edit" Id="InputField" Property="MYPROPERTY" X="125" Y="27" Width="100" Height="15" Indirect="yes" Text="[MYPROPERTY]">
                    <Condition Action="disable"><![CDATA[EnableBox<>"1"]]></Condition>
                    <Condition Action="enable">EnableBox="1"</Condition>
                </Control>
                <Control Type="CheckBox" Id="MyBox" Width="10" Height="10" X="110" Y="30" Property="EnableBox" CheckBoxValue="1"/>
            </Dialog>
        </UI>

A: when you define your property you simply have to assigne it a value like this
<Property Id="MYPROPERTY">Text you want to fill in</Property>

So you cut away your Value Field from your Control Element and define your Property beforehand. (Still Inside your UI Element!)
So in the end your code should look something like this
<UI>
    <Property Id="MYPROPERTY">Text you want to fill in</property>
    <Dialog Id="ConfigVariablesDlg" Width="370" Height="270">
        <Control Type="Edit" Id="InputField" Property="MYPROPERTY" X="125" Y="27" Width="100" Height="15" Indirect="yes">
            <Condition Action="disable"><![CDATA[EnableBox<>"1"]]></Condition>
            <Condition Action="enable">EnableBox="1"</Condition>
        </Control>
        <Control Type="CheckBox" Id="MyBox" Width="10" Height="10" X="110" Y="30" Property="EnableBox" CheckBoxValue="1"/>
    </Dialog>

*edit also I am pretty (but not entirely sure)
![CDATA[EnableBox<>"1"]]

should be
![CDATA[EnableBox<>1]]

atleast thats how it worked for me


text:
Q: Android XML resource format/structure How to properly write android xml resource where object has a main ID and sub-objects has subID's
I have very good example to explain my problem. Example is written in Plist(modified xml version for iOS):
<plist version="1.0">
<dict>
<key>223</key>----main key/ID
<dict>
<key>name</key>----sub-key/ID
  <string>Bill</string>
<key>uzvards</key>
  <string>Gates</string>
<key>adress</key>
  <string>Broadway</string>

So i need this type of data structure written in android XML. I guess xml file should be created in Values folder and use Resource type !? Thank you.

A: After looking into Plist, I think my comment was a suitable answer. In your actual code, you will want to use something like a hashmap, for your data. Depending on what you want, there are numerous ways to set this up but you can create a new hashmap
HashMap<String, String> myMap = new Hash<String, String>();

then use put(key, value) to add things to the map which you may get from a TextView and could display in an EditText. You can also use ArrayList and many others depending on what you want to accomplish. Or HashMaps inside of HashMaps.
Note: if you want to keep the order of your map you will want to use a linked hashmap
The res directory is where you store your XML for layouts(UI). My comment link should explain that very well. Hope this helps.


text:
Q: How do I create conditions for both the original table and a left join? My database has 4 relevant tables for this query: clients, appointments, invoices, and invoice details.  I am trying to calculate the average amount a customer paid in the past year minus any tips.
TABLES INVOLVED IN QUERY
Clients = All basic client information.  I need this table so that I can limit it to what school the customer attends, and get their name and clientId
Appointments = This is all appointment information, which matches the client table based on clientId.  I need this table so that I can limit it to customers from this past year and get the appointment location.
Invoices = This would be the total costs of the invoice and relevant information about when we posted the invoice online.  This matches with my client table based on clientId.  I need this table so that I can sum all invoices posted to the account in the past year
Invoice Detail = This is for the contents of the invoice, each entry is an item purchased with a price.  This matches with my invoices table based on invoiceId.  I need to include this table so I can remove tips.
I am attempting to do this using left joins, but I'm having a hard time wrapping my brain around it.
SELECT c.clientId, c.studentFirstName, c.studentLastName, a.date, a.subLocation, SUM(i.invoiceCost-i.invoiceDiscount), d.itemPrice
FROM clients c
JOIN appointments a ON a.clientId = i.clientId
INNER JOIN invoices i ON c.clientId = i.clientId
INNER JOIN invoiceDetail d ON i.invoiceId = d.invoiceId
WHERE c.school = "Test University"
AND a.date > "2019-04-01"
AND a.date < "2019-08-31"
AND i.datePosted > "2019-04-01"
AND i.datePosted < "2019-08-31"
AND (i.invoiceStatus = "Completed" OR i.invoiceStatus = "Invoiced")
AND i.shipping = 0
AND d.itemName LIKE "%tip%"

The error I am currently receiving is:

Unknown column 'c.clientId' in 'on clause'

But, I have a feeling I'm using the wrong approach anyway.

A: Test
SELECT c.clientId, c.studentFirstName, c.studentLastName, a.date, a.subLocation, SUM(i.invoiceCost-i.invoiceDiscount), d.itemPrice
FROM clients c
INNER JOIN appointments a ON c.clientId = a.clientId
LEFT JOIN invoices i ON c.clientId = i.clientId
                    AND i.datePosted > "2019-04-01"
                    AND i.datePosted < "2019-08-31"
                    AND i.invoiceStatus IN ("Completed", "Invoiced")
                    AND i.shipping = 0
LEFT JOIN invoiceDetail d ON i.invoiceId = d.invoiceId
                         AND d.itemName LIKE "%tip%"
WHERE c.school = "Test University"
  AND a.date > "2019-04-01"
  AND a.date < "2019-08-31"


text:
Q: Delphi application retrieves incorrect date format on windows 10 system I have a delphi application compiled in delphi 10.2.2.
My task is to retrieve the system date format from delphi application.
I use following procedure
procedure TForm1.GetsSytemDateFormat;
var
  myDate : string;
begin
  myDate:=GetLocaleStr(GetThreadLocale(), LOCALE_SSHORTDATE, '');
  edtSysDefault.Text := myDate;
end;

to retrieve the date format.
When I execute the exe on windows 10 system if the system date format is set to dd-MM-yyyy then,
in delphi application its retrieved as M/d/yyyy.
I am trying to get same date format in delphi application as per the system date format.
However,the same application works on other systems having windows 7 and windows 10.
Can anyone tell me, what could be the issue with this?


text:
Q: Create a Book in Open Graph without an ISBN number We are trying to markup book pages on our site so that those pages map to the Open Graph and are clearly identified to Facebook as book pages. One of the items needed for the markup is the International Standard Book Number or ISBN#.
However, many books (especially e-books) don't have ISBN numbers and for those books Facebook rejects the identification of that object as a book. If a book doesn't have an ISBN number, what would you provide for this tag?

A: This is a known Facebook issue:
https://developers.facebook.com/bugs/238075889669083
As a workaround, it seems you can use the older open graph type book
<meta property="og:type" content="book">
<meta property="og:image" content="http://ecx.images-amazon.com/images/I/5126EaBrekL.jpg">
<meta property="og:title" content="Frankie in Paris">
<meta property="book:release_date" content="2012-12-17 00:00:00 UTC">

instead of the newer books.book open graph type


text:
Q: Docker bash: ng: command not found (Angular) I try to run my container which contains angular but it crashes when I start docker-compose start and I get the following error:

Here is my Dockerfile.angular
FROM node:v16.10-alpine
ARG DEV_EMAIL
ARG DEV_NAME
ARG NODE_APP_ARG=node-app
ENV NODE_APP $NODE_APP_ARG
WORKDIR /usr/src/app
RUN sh -c "apk add git bash && git config --global user.email \"${DEV_EMAIL}\" && git config --global user.name \"${DEV_NAME}\" && npm install -g
@angular/cli"
EXPOSE 4200

this is my docker-compose.yml
services:
  angular:
    build:
      context: .
      dockerfile: Dockerfile.angular
      args:
        DEV_NAME: ${DEV_NAME}
        DEV_EMAIL: ${DEV_EMAIL}
        NODE_APP_ARG: ${NODE_APP}
    command: bash -c "( [ \"$$(ls -A)\" ] && echo \"App already made\" || ng new ${NODE_APP} --style=scss --routing=true --strict=true ) && cd /usr/src/app/${NODE_APP} && npm start"
    ports:
      - 4201:4200
    working_dir: /usr/src/app
    # volumes:
    #   - ./app/nodejs:/usr/src/app
    environment:
      NODE_APP: ${NODE_APP}
      MYSQL_HOST: mysql
      MYSQL_USER: root
      MYSQL_PASSWORD:
      MYSQL_DB: ${APP_DB}

A: You don't put anything in your docker container.
That means it's a pristine alpine distro with nothing else in it.
Try using the COPY command like so
COPY . .

This should put all of your files into the docker container.
Also, do not install the CLI globally. Instead, use the RUN command like so
RUN npm i

Which will install your dependencies, then you can run this
CMD ['npx', 'ng', 'serve']

I strongly advise you to learn more about docker before using it. It may seem simple, but it's not !


text:
Q: Issue saving PDF file using TCPDF I want to save some html to pdf file on a button click. The problem is that I get the issue after the ajax call:

%PDF-1.7 %���� 8 0 obj << /Type /Page /Parent 1 0 R /LastModified
  (D:20190328213806+02'00') /Resources 2 0 R /MediaBox [0.000000
  0.000000 595.276000 841.890000] /CropBox [0.000000 0.000000 595.276000 841.890000] /BleedBox [0.000000 0.000000 595.276000 841.890000] /TrimBox [0.000000 0.000000 595.276000 841.890000] /ArtBox [0.000000
  0.000000 595.276000 841.890000] /Contents 9 0 R /Rotate 0 /Group << /Type /Group /S /Transparency /CS /DeviceRGB >> /Annots [ 6 0 R 7 0 R
  ] /PZ 1 >> endobj 9 0 obj <> stream x��ۏ�q���
  |�`ɐVU}���e).e�rI66�$^$�d3�
  �������]EYb�"I��g?ΙKwU���|�gy�s|r��o�߿������G���vqy|�]��H�������ȄQ��F�D�S��F���@�.��'�}���e�8
  �B�@����UH��@M�MC�g���P8���g[t���?P�#E���=��@�P��g�
  KysL�m�.�0qC�{�[�}Tlg�kY�?���������3�K��9��g�%Mq��=����
  0vw��G�}����Obڃ�l�/��WC��|����?��O���y��u;�ݽ����L
  �_���qŁ�JG�ׇ��~���a?K�^���g��--�,�L3����?-�Z�e��W!1�D���a�I#���s?

I have found the similar issue here - Tcpdf on Laravel 3 controller
But I don't know what the Response::make is? Any ideas how to fix it? Thanks.
Code:
jQuery/Ajax
$(document).on("click", "#testButtonClick", function() {
   savePDF($("#test").html(), "Test1", "Test2");
 });

function savePDF(info, name, data) {
$.ajax({
    type: "post",
    url: "includes/worker",
    data: {"test": info, "name": name, "data": data},
    xhr: function() {
        try {
            if (window.ActiveXObject) {
                return new window.ActiveXObject("Microsoft.XMLHTTP");
            }
        } catch(e) { }

        return new window.XMLHttpRequest();
    },
    success: function(result) {
        console.log(result);
    },
    error: function(response) {
    }
});
}

PHP
    require_once("tcpdf.php");
    $pdfData = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, "UTF-8", false);  //
    $pdfData->SetCreator("Test..");
    $pdfData->SetTitle("Test..");
    $pdfData->SetHeaderData("", "", PDF_HEADER_TITLE, PDF_HEADER_STRING);
    $pdfData->setHeaderFont(Array(PDF_FONT_NAME_MAIN, "", PDF_FONT_SIZE_MAIN));
    $pdfData->setFooterFont(Array(PDF_FONT_NAME_DATA, "", PDF_FONT_SIZE_DATA));
    $pdfData->SetFooterMargin(PDF_MARGIN_FOOTER);
    $pdfData->SetMargins(PDF_MARGIN_LEFT, "5", PDF_MARGIN_RIGHT);
    $pdfData->setPrintHeader(false);
    $pdfData->setPrintFooter(false);
    $pdfData->SetAutoPageBreak(true, 10);
    $pdfData->setFontSubsetting(true);
    $pdfData->AddPage();
    $pdfData->SetFont("freeserif", "", 10);
    $pdfData->writeHTML(iconv("Windows-1251", "UTF-8", "Это тест...."));
    $pdfData->Output("Test.pdf", "D");

A: So, I have fixed it by using auto form JS and escaping characters such as ".
Code:
    var pdfForm = $("<form action=\"includes/worker\" method=\"post\" enctype=\"multipart/form-data\" target=\"_blank\"></form>");
      pdfForm.append("<input type=\"hidden\" name=\"test\" value=\"" + htmlValidation($("#test").html()) + "\">");
      pdfForm.append("<input type=\"hidden\" name=\"name\" value=\"Test1\">");
      pdfForm.append("<input type=\"hidden\" name=\"data\" value=\"Test2\">");
      $("body").append(pdfForm);
      $(pdfForm).submit();

   function htmlValidation(data) {
     return data
       .replace(/&/g, "&")
       .replace(/</g, "<")
       .replace(/>/g, ">")
       .replace(/"/g, """)
       .replace(/'/g, "'");
   }


text:
Q: PowerShell script to query xml tag attribute in database I want to write a query in powerShell which checks an attribute value in an xml column called(xml_multiple) and return boolean value 1 if it exist(otherwise 0) and pass it to a variable and call a sendemail function.
According to the value of variable the email will be sent.
1- for success
0- for failure
I'm new to powershell and not very good at it. I'm open to suggestion as long it works.Thanks in advance. Check the code below and xml
$dataSource = "DB.abc.com"
$connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$query = " " <#here i want to write my query#>
$command = $connection.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$table = new-object "System.Data.DataTable"
$table.Load($result)
$connection.Close()

function sendemail()
{

$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "abc@xyz.com"
 if ($send -eq 1) <#here i want to pass value from db#>
    {
     $Mail.Subject = "Process Successful"
     $Mail.Body ="Success`n`nThank you"
    }
 else
   {
    $Mail.Subject = "Process Unsuccessful"
    $Mail.Body ="Unsuccess`n`nPlease look into it"
   }
$Mail.Send()
}

Note: This is the xml and if any xml has a attribute start="1" return 1 else 0. for a particular day(There will be only one record in a day which will have this attribute,so we can use a filter in the query for that)
<jobparameters start="1">
<work>1
</work>
</jobparameters>

P

lease give suggestions

A: It is possible to get the needed results directly from SQL Server:

DECLARE @x XML = '
<jobparameters start="1">
<work>1
</work>
</jobparameters>';
DECLARE @t TABLE (xml_multiple XML);
INSERT @t(xml_multiple) VALUES(@x);
SELECT c.value('@start','INT') send
FROM @t
OUTER APPLY xml_multiple.nodes('/jobparameters')x(c);


text:
Q: Overlaying two histograms in R Plotly I'm trying to overlay two histogram plots in R plotly. However only one of them shows up. Here's the code I'm using with some random data:
    myDF <- cbind.data.frame(Income = sample(1:9, size = 1000, replace= TRUE),
                           AgeInTwoYearIncrements = sample(seq(from = 2, to = 70, by = 2), size = 1000, replace = TRUE))

plot_ly(data = myDF, alpha = 0.6) %>%
  add_histogram(x = ~Income, yaxis = "y1") %>%
  add_histogram(x = ~AgeInTwoYearIncrements, yaxis = "y2") %>%
  layout(
    title = "Salary vs Age",
    yaxis = list(
      tickfont = list(color = "blue"),
      overlaying = "y",
      side = "left",
      title = "Income"
    ),
    yaxis2 = list(
      tickfont = list(color = "red"),
      overlaying = "y",
      side = "right",
      title = "Age"
    ),
    xaxis = list(title = "count")
  )

Any help would be much appreciated!

A: It is the main cause to give the 1st yaxis overlaying. And because xaxis is count, Income and Age is y.
plot_ly(data = myDF, alpha = 0.6) %>%
  add_histogram(y = ~Income, yaxis = "y1") %>%    # not `x =`
  add_histogram(y = ~AgeInTwoYearIncrements, yaxis = "y2") %>%
  layout(
    title = "Salary vs Age",
    yaxis = list(
      tickfont = list(color = "blue"),
      # overlaying = "y",     # the main cause is this line.
      side = "left",
      title = "Income"
    ),
    yaxis2 = list(
      tickfont = list(color = "red"),
      overlaying = "y",
      side = "right",
      title = "Age"
    ),
    xaxis = list(title = "count")
  )

[Edited: just flip]
plot_ly(data = myDF, alpha = 0.6) %>%
  add_histogram(x = ~ Income, xaxis = "x1") %>%
  add_histogram(x = ~ AgeInTwoYearIncrements, xaxis = "x2") %>%
  layout(
    margin = list(t = 60),
    title = "Salary vs Age",
    xaxis = list(
      tickfont = list(color = "blue"),
      side = "left",
      title = "Income"
    ),
    xaxis2 = list(
      tickfont = list(color = "red"),
      overlaying = "x",
      side = "top",
      position = 0.95,
      title = "<br>Age"
    ),
    yaxis = list(title = "count")
  )

A: You can mix histograms:

plot_ly(data = myDF, alpha = 0.6) %>%
  add_histogram(x = ~Income) %>%
  add_histogram(x = ~AgeInTwoYearIncrements) %>%
layout(
  title = "Salary and Age",
  yaxis = list(
    tickfont = list(color = "blue"),
    overlaying = "y",
    side = "left",
    title = "count"
  ),
  xaxis = list(title = "Salary and Age value")
)

A histogram has normally on the y-axis the frequency / count and not on the x-axis. We can produce a diagram like you want but I'm not sure if it is still a histogram.
Also, like you see in my picture you the frequency/count for salary (here blue) is more high and the variability is less then age. That make it difficult for a good looking diagram. Maybe this is just a problem of your sample data...
So When you like to go with the histogram function, you have to invert the meaning of the frequency and the value on the x-axis.
But anyway, I think a scaternplot would be a better solution to show the relation between salary and age.
edit:
This is the result I get when I run your code:

Like this I don't see the sense in the plot and what you want. The meaning of the first orange colum is that a age of 59 occurs between 0 and 5 times in your dataset. The third colum means a age of 88 ocours between 10 and 15 times in your dataset.
To present this information in a barplot don't work. Because you can have several Age-values in on categorie of counts...I hope this is clear.
Anyway, to answer your question I need more clarification.

A: Following the responses here, I wanted to answer this with an example that others can easily use when for instance plotting two overlapping histograms.
# Add required packages
library(plotly)

# Make some sample data
a = rnorm(1000,4)
b = rnorm(1000,6)

# Make your histogram plot with binsize set automatically
fig <- plot_ly(alpha = 0.6) # don't need "nbinsx = 30"
fig <- fig %>% add_histogram(a, name = "first")
fig <- fig %>% add_histogram(b, name = "second")
fig <- fig %>% layout(barmode = "overlay",
                      yaxis = list(title = "Frequency"),
                      xaxis = list(title = "Values"))

# Print your histogram
fig

And here is the result of the code:

A: Easy way to handle any number of dimensions without repetition
TL;DR: You can rearrange your data to long-form before passing it to plot_ly().
df |>
  mutate(row_number = row_number()) |>
  pivot_longer(!row_number) |>
  plot_ly() |>
  add_histogram(x = ~ value,
                color = ~ name,
                opacity = 0.5) |>
  layout(barmode = 'overlay')

Explanation
Given a DF with multiple columns, like the one the OP posted:
df = cbind.data.frame(Income = sample(1:9, size = 1000, replace= TRUE),
                      AgeInTwoYearIncrements = sample(seq(from = 2, to = 70, by = 2), size = 1000, replace = TRUE))

Then, using tidyr::pivot_longer():
df |> mutate(row_number = row_number()) |> pivot_longer(!row_number)

This gives:
# A tibble: 2,000 × 3
   row_number name                   value
        <int> <chr>                  <dbl>
 1          1 Income                     1
 2          1 AgeInTwoYearIncrements    20
 3          2 Income                     1
 4          2 AgeInTwoYearIncrements    48
 5          3 Income                     3
 6          3 AgeInTwoYearIncrements    26
 7          4 Income                     4
 8          4 AgeInTwoYearIncrements    30
 9          5 Income                     4
10          5 AgeInTwoYearIncrements    60
# … with 1,990 more rows

Finally, just pipe this to plot_ly(), so the full command is:
df |>
  # Add a column to keep track of the row numbers
  mutate(row_number = row_number()) |>
  # Squash and lengthen the df with one row per row per column (in this case, double its length)
  pivot_longer(!row_number) |>
  plot_ly() |>
  # The magic is here. We set color to track the name variable, which will
  # add a separate series per column.
  # We set the opacity so we can see where our plots overlap.
  add_histogram(x = ~ value,
                color = ~ name,
                opacity = 0.5) |>
  # Without setting this, bars will be plotted side by side for the same x value
  # rather than overlapping.
  layout(barmode = 'overlay')

Output


text:
Q: Ubuntu 20.04 LTS resume/boot directly after suspend I have a server running Ubuntu Server 20.04. To enable power management, I would like to suspend the system and wake it up as soon as I need it (WoL). The problem I face is that the system does not stay in suspend mode. It directly (some seconds to minutes) after the suspend it boot again.
I have unplugged the server from the network and it seems to stay in suspend mode. As soon as I plug in the network cable, the server startup. So, it might be related to the network interface. I have tested to turn off WoL but it does not help.
Any ideas?
UPDATE
It seems to be an issue w/ the Fritz!Box 7490 (v7.21). If I disconnect the router from the local network, the suspend and WoL works fine. The WoL option in the Fritz!Box setting is disabled.
This is the tcpdump on the server w/ repaiting packages from the router (about every 30 seconds):
tobias@home:~$ sudo tcpdump -vvveni any ether proto 0x0842
tcpdump: listening on any, link-type LINUX_SLL (Linux cooked v1), capture size 262144 bytes
10:53:12.443846   B c0:25:06:f4:19:77 ethertype Unknown (0x0842), length 118:
        0x0000:  ffff ffff ffff b42e 99cd 4561 b42e 99cd  ..........Ea....
        0x0010:  4561 b42e 99cd 4561 b42e 99cd 4561 b42e  Ea....Ea....Ea..
        0x0020:  99cd 4561 b42e 99cd 4561 b42e 99cd 4561  ..Ea....Ea....Ea
        0x0030:  b42e 99cd 4561 b42e 99cd 4561 b42e 99cd  ....Ea....Ea....
        0x0040:  4561 b42e 99cd 4561 b42e 99cd 4561 b42e  Ea....Ea....Ea..
        0x0050:  99cd 4561 b42e 99cd 4561 b42e 99cd 4561  ..Ea....Ea....Ea
        0x0060:  b42e 99cd 4561                           ....Ea
10:53:12.543643   B c0:25:06:f4:19:77 ethertype Unknown (0x0842), length 118:
        0x0000:  ffff ffff ffff b42e 99cd 4561 b42e 99cd  ..........Ea....
        0x0010:  4561 b42e 99cd 4561 b42e 99cd 4561 b42e  Ea....Ea....Ea..
        0x0020:  99cd 4561 b42e 99cd 4561 b42e 99cd 4561  ..Ea....Ea....Ea
        0x0030:  b42e 99cd 4561 b42e 99cd 4561 b42e 99cd  ....Ea....Ea....
        0x0040:  4561 b42e 99cd 4561 b42e 99cd 4561 b42e  Ea....Ea....Ea..
        0x0050:  99cd 4561 b42e 99cd 4561 b42e 99cd 4561  ..Ea....Ea....Ea
        0x0060:  b42e 99cd 4561                           ....Ea
10:53:42.423757   B c0:25:06:f4:19:77 ethertype Unknown (0x0842), length 118:
        0x0000:  ffff ffff ffff b42e 99cd 4561 b42e 99cd  ..........Ea....
        0x0010:  4561 b42e 99cd 4561 b42e 99cd 4561 b42e  Ea....Ea....Ea..
        0x0020:  99cd 4561 b42e 99cd 4561 b42e 99cd 4561  ..Ea....Ea....Ea
        0x0030:  b42e 99cd 4561 b42e 99cd 4561 b42e 99cd  ....Ea....Ea....
        0x0040:  4561 b42e 99cd 4561 b42e 99cd 4561 b42e  Ea....Ea....Ea..
        0x0050:  99cd 4561 b42e 99cd 4561 b42e 99cd 4561  ..Ea....Ea....Ea
        0x0060:  b42e 99cd 4561                           ....Ea
10:53:42.523736   B c0:25:06:f4:19:77 ethertype Unknown (0x0842), length 118:
        0x0000:  ffff ffff ffff b42e 99cd 4561 b42e 99cd  ..........Ea....
        0x0010:  4561 b42e 99cd 4561 b42e 99cd 4561 b42e  Ea....Ea....Ea..
        0x0020:  99cd 4561 b42e 99cd 4561 b42e 99cd 4561  ..Ea....Ea....Ea
        0x0030:  b42e 99cd 4561 b42e 99cd 4561 b42e 99cd  ....Ea....Ea....
        0x0040:  4561 b42e 99cd 4561 b42e 99cd 4561 b42e  Ea....Ea....Ea..
        0x0050:  99cd 4561 b42e 99cd 4561 b42e 99cd 4561  ..Ea....Ea....Ea
        0x0060:  b42e 99cd 4561                           ....Ea

UDPATE
I've restarted the Fritz!Box and the problem seem to be fixed. I get no repeating packages from the router. The server goes to suspend mode if idle and start w/ WoL. The problem now is that the server does not awake if I request the computer. Ports in the router are set and the option to use WoL if a request from the internet arrives is enabled. But this problem seems to be a Fritz!Box related issue.


text:
Q: Android - Foreground is not working in Oreo. OS killed service after some interval I have an application which is using location service in background at every 5 minute of interval. We are using Fusedlocationproviderclient in foreground service. It is working fine when app is in open.
When I put application in background or swipe to kill from background , Foreground service is automatically killed by OS on android 8.0 and higher version.
We are facing problem in samsung note 8 , one plus 5t and red mi devices.
Please let me know How can I implement service which is compatible for all devices.
This is my location service class.
    public class TrackingForgroundService extends Service {

    private final long UPDATE_INTERVAL = (long) 2000;
    private static final long FASTEST_INTERVAL = 2000;

    public BookingTrackingForgroundService() {

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            String action = intent.getAction();

            switch (action) {
                case ACTION_START_FOREGROUND_SERVICE:
                    startForegroundService();

                    break;
                case ACTION_STOP_FOREGROUND_SERVICE:
                    stopForegroundService();

                    break;
            }
        }
        return START_STICKY;
    }

    private class TimerTaskToGetLocation extends TimerTask {
        @Override
        public void run() {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // Call webservice evry 5 minute
                }
            });

        }
    }

    private void startForegroundService() {

        Log.d(TAG_FOREGROUND_SERVICE, "Start foreground service.");

        context = this;
        startLocationUpdates();
        notify_interval1 = Prefs.with(this).readLong("notify_interval1", 5000);
        mTimer = new Timer();
        mTimer.scheduleAtFixedRate(new TimerTaskToGetLocation(), 15000, notify_interval1);
        mTimer.scheduleAtFixedRate(new TimerTaskToSendCsvFile(), 60000, 1200000);
        prefsPrivate = getSharedPreferences(Constants.prefsKeys.PREFS_PRIVATE, Context.MODE_PRIVATE);
        internet = new NetConnectionService(context);

        Intent notificationIntent = new Intent(this, ActTherapistDashboard.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Geolocation is running")
                .setTicker("Geolocation").setSmallIcon(R.drawable.app_small_icon_white)
                .setContentIntent(pendingIntent);
        Notification notification = builder.build();
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription(CHANNEL_DESCRIPTION);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(channel);
        }
        startForeground(SERVICE_ID, notification);
    }

    private void stopForegroundService() {
        stopLocationUpdates();
        Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");
        if (mTimer != null) {
            mTimer.cancel();
        } else {
            mTimer = null;
        }
        // Stop foreground service and remove the notification.
        stopForeground(true);

        // Stop the foreground service.
        stopSelf();
    }

    public static boolean isServiceRunningInForeground(Context context, Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                if (service.foreground) {
                    return true;
                }

            }
        }
        return false;
    }

    private void startLocationUpdates() {
        // create location request object
        mLocationRequest = LocationRequest.create();

        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

        // initialize location setting request builder object
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        LocationSettingsRequest locationSettingsRequest = builder.build();

        // initialize location service object
        SettingsClient settingsClient = LocationServices.getSettingsClient(this);
        Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(locationSettingsRequest);
        task.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
            @Override
            public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                registerLocationListner();
            }
        });

    }

    private void registerLocationListner() {
        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                onLocationChanged(locationResult.getLastLocation());
            }
        };

      //location permission
        LocationServices.getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, locationCallback, null);

    }

    private void onLocationChanged(Location location) {

        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            latitudeTemp = latitude;
            longitudeTemp = longitude;
        }

    }

}

A: Please see answer here to a similar question and the linked site dontkillmyapp which provides a very useful summary for developers to help understand this issue across different handset manufacturers and Android OS versions.


text:
Q: Faking Scrollbars With JavaScript or jQuery I am currently working on a custom table that I have made with knockoutJS and jQuery. Because this table is possibly dealing with 1,000 - 100,000 rows, I have implemented my own virtual scrolling technique in KnockoutJS to ensure that only 35 or so elements are visible at a time (depending on viewport height). When scrolling with the scroll-wheel, the table's tr elements are dynamically updated in-place to give the illusion of scrolling. This much works.
However, I need to think of a way to implement fake scrollbars. I am needing a fake scrollbar that does not actually scroll the page, but rather calls a function when dragged so that I can re-direct that info to my knockoutJS virtual scroller for updating the tr elements.
I have looked a bit into jScrollPane, but am not sure if it will support what I want. Does anyone else have experience with this?
Thanks.

A: Here's a rough demo of doing it with actual scrollbars and scrolling. You can see it better if you make the snippet full-screen.
The idea is that you have a window of visible items, somewhat like you have already, but it is displayed in fixed position over a tall, scrolling window. When the window is scrolled, you find its new position and use that to recompute which of your items should be visible.
As it is here, I had to put in a fudge factor to get to the last items in the list. I did say it's a "rough" demo.

const vm = {
  items: ko.observableArray([]),
  percent: ko.observable(0),
  visibleItems: ko.pureComputed(() => {
    const start = Math.floor(vm.percent() * vm.items().length);

    return vm.items.slice(start, start + 22);
  })
};

for (let i = 0; i < 5000; ++i) {
  vm.items.push(i);
}

ko.bindingHandlers.scroll = {
  init: (el, va) => {
    let top = el.parentNode.scrollTop;
    const percent = va();

    setInterval(() => {
      const newTop = el.parentNode.scrollTop;

      if (newTop !== top) {
        percent(newTop / (0.859 * el.parentNode.scrollHeight));
        top = newTop;
      }

    }, 50);
  }
};

ko.applyBindings(vm);
.scroll-me {
  background-color: rgba(255, 30, 30, 0.3);
  height: 3000px;
}
.all-you-see {
  background-color: white;
  width: 100%;
  position: fixed;
}


text:
Q: How to rewrite a Awk script to process several files instead of one I am writing a report tool which processes the source files of some application and produce a report table with two columns, one containing the name of the file and the other containing the word TODO if the file contains a call to some deprecated function deprecated_function and DONE otherwise.
I used awk to prepare this report and my shell script looks like
report()
{
  find . -type f -name '*.c' \
    | xargs -n 1 awk -v deprecated="$1" '
BEGIN { status = "DONE" }
$0 ~ deprecated{ status = "TODO" }
END {
  printf("%s|%s\n", FILENAME, status)
}'
}
report "deprecated_function"

The output of this script looks like
./plop-plop.c|DONE
./fizz-boum.c|TODO

This works well but I would like to rewrite the awk script so that it supports several input files instead of just one — so that I can remove the -n 1 argument to xargs.  The only solutions I could figure out involve a lot of bookkeeping, because we need to track the changes of FILENAME and the END event to catch each end of file event.
awk -v deprecated="$1" '
BEGIN { status = "DONE" }
oldfilename && (oldfilename != FILENAME) {
  printf("%s|%s\n", oldfilename, status);
  status = DONE;
  oldfilename = FILENAME;
}
$0 ~ deprecated{ status = "TODO" }
END {
  printf("%s|%s\n", FILENAME, status)
}'

Maybe there is a cleaner and shorter way to handle this.
I am using FreeBSD's awk and am looking for solutions compatible with this tool.

A: This will work in any modern awk:
awk -v deprecated="$1" -v OFS='|' '
    $0 ~ deprecated{ dep[FILENAME] }
    END {
        for (i=1;i<ARGC;i++)
            print ARGV[i], (ARGV[i] in dep ? "TODO" : "DONE")
    }
' file1 file2 ...

Any time you need to produce a report for all files and don't have GNU awk for ENDFILE, you MUST loop through ARGV[] in the END section (or loop through it in BEGIN and populate a different array for END section processing). Anything else will fail if you have empty files.

A: Your awk script could be something like this:
awk -v deprecated="$1" '
FNR==1 {if(file) print file "|" (f?"TODO":"DONE"); file=FILENAME; f=0}
$0 ~ deprecated {f=1}
END {print file "|" (f?"TODO":"DONE")}' file1.c file2.c # etc.

The logic is fairly similar to your program so hopefully it's all clear. FNR is the record number of the current file, which I'm using to detect the start of a new file. Admittedly there's some repetition in the END block but I don't think it's a big deal. You could always use a function if you wanted to.
Testing it out:
$ cat f1.c
int deprecated_function()
{
    // some deprecated stuff
}
$ cat f2.c
int good_function()
{
    // some good stuff
}
$ find -name "f?.c" -print0 | xargs -0 awk -v deprecated="deprecated" 'FNR==1 {if(file) print file "|" (f?"TODO":"DONE"); file=FILENAME; f=0} $0 ~ deprecated {f=1} END {print file "|" (f?"TODO":"DONE")}'
./f2.c|DONE
./f1.c|TODO

I have used -print0 and the -0 switch to xargs so that both programs with work file names separated by null bytes "\0" rather than spaces. This means that you won't run into problems with spaces in file names.


text: Q: Hide used source port in TCP with XDP(eBPF) from different network namespace I have topology with 2 network namespaces and one veth pair with one in each namespace. Let's call namespaces server and client. I want to run 2 process in each namespace which will communicate with each other via TCP but server process will not know the client's real port number. Want to load XDP(eBPF) program which will change the source and destination port number in TCP header on the client's side. Are the packet's sent in client's namespace processed in client's eBPF program (process packets on arrival) ?  Is it possible to implement it or I would need more complex topology with the bridge?


text:
Q: Is it possible to develop the same application for Windows Phone 7 and Windows Mobile 6.x without much additional effort? I have to develop an application for Windows Mobile 6.x and version 7 and my skillset is .net  and web based.  Since version 7 is not backwards compatible I am thinking that I will end up with a lot of duplicate work.
I had a look at Rhomobile and Phonegap but the later does not support windows mobile 6.x and the former would require ruby knowledge.
I thought that I could have as much logic in class libraries as possible and then "include as link" the classes into projects so that they can be compiled for the specific platform.  I feel like I may end up with a lot of #if PHONE7 style logic in that case and also the user interface code would have to be implemented for each platform.
What is the most efficient way to solve this problem?

A: If you can separate the UI from the logic you can begin to multi-target. The other consideration is the runtime of the phone (Silverlight 4?) and the phone sandboxing giving you limitations.
MVVM Light is multi-targeted and is open source, you could use this to review how they tackled it:
http://mvvmlight.codeplex.com/SourceControl/changeset/view/d546dc69fffd
In short though, your "add as link" idea is pretty much the basis of it.
The other question to ask is will the application fit on both platforms? The usage style from mobile to metro is a big change. People expect things to behave a certain way and look a certain way on metro. If you can confine this to the UI and move as much logic out as possible, then you should be ok. But there will come a point where it isn't worth sharing, it is simply easier to duplicate.
Sorry for a lack of detail in this answer, to be honest it is heavily app specific. I would personally start with separate applications and refactor as commonalities appear, using a combination of linked code files and hash defines.
A cute trick... you can always make the classes partial and have a partial code file for each hash define:
MyBusinessClass.CF.cs
MyBusinessClass.Silverlight.cs


text:
Q: Rank-based Spatial Clustering in Python I was wondering if there was any python (or R) packages out there that can do spatial clustering on ranked data?
For each US state I spatially varying value for education rankings. For example, for Virginia the ranking may be 50 compared to a ranked value of 10 for the state of Missouri. These are not categorical (e.g. A vs B) or ratio (e.g. 1.5), but ranked in the sense that a value of 50 for Virginia does not mean that this state is 5 times higher in educational value that Missouri. Its synonymous to ranked outcomes at the end of a marathon (e.g. 1st, 2nd,....places). Most of the stuff I've been finding online relate to the relationship between records across different attribute themes in tabular data (e.g. Gower distance). I'm looking for a spatially clustering method such as Moran's I where the attribute vector being analyzed is an education rank value for each state polygon.


text:
Q: Como editar o titulo de TODOS os alerts no ionic app, e não somente um? Seguindo a documentação do ionic, consigo editar o título de um alert, usando o ensinado no link seguinte:inserir a descrição do link aqui
Porém, quando o alert é disparado de dentro de um iframe, ele é mostrado como um alert "natural" do android, algo que não combina com meu app. Como consigo realizar uma mudança em TODOS os títulos de TODOS os alerts, mesmo aqueles que são disparados pelo iframe?

A: Eu fiz um app utilizando ionic v1 utilizando as mesma propriedades da documentação do ionic v3 e funcionou pra mim. Segue a abaixo o que eu utilizei:
$ionicPopup.confirm({
      title: titulo,
      subTitle: subtitle,
      template:
      `<style>
        .popup{
          border-radius: 7px !important;
        }
        .popup-head {
          background: ${backgroundTitulo} !important;
          border-top-left-radius: 7px !important;
          border-top-right-radius: 7px !important;
        }
        .popup-title {
          color: ${corTitulo} !important;
        }
        .popup-sub-title{
          color: ${corTitulo} !important;
          font-weight: normal;
          font-size: 12pt;
        }
        .popup-body{
          background: ${background} !important;
          /*color:#fff !important;
          font-size:24px !important;*/
          text-align: center;
        }
        .popup-buttons{
          background: ${background} !important;
          border-bottom-left-radius: 7px !important;
          border-bottom-right-radius: 7px !important;
        }
        .popup-buttons .button {
          color: ${corBotaoTexto} !important;
        }
        .popup-buttons .button {
          background: ${corBotao} !important;
          color: ${corBotaoTexto} !important;
          box-shadow: none !important;
          border-radius: 5px !important;
        }
      </style>
      <p>${message}</p>
      `
      ,buttons: [
        { // Array[Object] (optional). Buttons to place in the popup footer.
          text: 'Não',
          type: 'button-default',
          onTap: function(e) {
            if( cancelCallback != null){
              cancelCallback(e);
            }
            return e;
          }
        },
        {
          text: 'Sim',
          type: 'button-positive',
          onTap: function(e) {
            if(confirmCallback != null){
              confirmCallback(e);
            }
            return e;
          }
        }
      ]
    });
  };

Obs: o que está dentro de ${...}, que é o interpolador de string do javascript ES2015, são variáveis javascript que eu define em meu código.


text:
Q: How can I describe jobs in Azkaban UI? I just discovered Azkaban and I want to know if it is possible to put some description next to the jobs/flows in the project view ?
(See this image for more accuracy)


text:
Q: Iterate in C++ like in python I would like to iterate in C++ over a set of values. In python, it looks like
for v in [v1, v2, v3]:
    do_something()

What is the correct way to do it in C++?

A: for (const auto& v : {v1, v2, v3}) { do_something(); }

Would be equivalent (except for the fact that the elements in the initializer list will conceptually be copied - even if the optimizer elides those copies - so they will need to be copyable).

A: you can use the auto keyword and a range based for loop
 std::vector<int> v = {0, 1, 2, 3, 4, 5};

 for (auto const& e:v){
      // here e is value from v
 }

more info: https://en.cppreference.com/w/cpp/language/range-for

A: What about  std::apply  C++17 function:
std::apply([](auto&& v){ do_something_over_v();}, std::tie(v1,v2,v3) ) ;

*

*Needn't copy of v1, v2, v3 elements, just took reference of them.

*Needn't require to identity type of v1, v2, v3.

If you don't have C++17, just copy implementation from reference -) , worked for C++14 mode, as I know.
reference to std::apply


text:
Q: Using an array of strings for UISlider I want to change a UILabel with strings based on an array.  Here is what I have so far:
- (IBAction) sliderValueChanged:(UISlider *)sender {
   scanLabel.text = [NSString stringWithFormat:@" %.f", [sender value]];
    NSString *wholeText = @"Very Bad";
    self.scanLabel.text = wholeText;

}

Instead of just "Very Bad," I want different values to show "very Bad, Bad, Okay, Good, Very Good."
Where do I declare the NSMutableArray, and how do I implement it with the slider?
Update: Thank you all for your help! (I love stackoverflow)

A: This is not compiler checked...but you may get some idea.
NSArray *texts=[NSArray arrayWithObjects:@"very Bad", @"Bad", @"Okay", @"Good", @"Very Good",nil];
NSInteger sliderValue=[sender value]; //make the slider value in given range integer one.
self.scanLabel.text=[texts objectAtIndex:sliderValue];

A: You declare it in the same class as the above method.
Let's say it's called wholeTexts.
The code will look like this:
- (IBAction) sliderValueChanged:(UISlider *)sender {
    scanLabel.text = [NSString stringWithFormat:@" %.f", [sender value]];
    NSString *wholeText = [wholeTexts objectAtIndex:(wholeTexts.count - 1) * (int)(sender.value - sender.minimumValue)/(sender.maximumValue - sender.minimumValue)];
    self.scanLabel.text = wholeText;
}

A: You can implement the array anywhere you want, as long as it's created before you need to use the slider. Sliders can only have a value between 0 and 1 in iOS, so you'll need to multiply the value by something to get numbers as high as the number of items in your array (minus 1), and you'll need to convert them to an integer, so you can use that value as the index into the array. Something like this:
- (IBAction) sliderValueChanged:(UISlider *)sender {
   scanLabel.text = [myArray objectAtIndex:(int)(sender.value * 10)];

}

A: Put your text values into an array
NSArray* array =  @[@"very Bad", @"Bad", @"Okay", @"Good", @"Very Good"];

*

*set your slider to have a min value of 0 and maximum value of 4

*turn your [sender value] into an int, eg floor([sender value])
pick an item from the array using your int, eg
NSString* result = [array objectAtIndex:myInt];


text:
Q: How to instal phpDocumntor on Symfony4? I'm trying to install phpDocumentor on my project, but I've got this problem.
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - phpdocumentor/phpdocumentor[v3.1.0, ..., v3.1.2] require symfony/cache ^5.0 -> found symfony/cache[v5.0.0, ..., v5.3.7] but the package is fixed to v4.4.30 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
    - Root composer.json requires phpdocumentor/phpdocumentor ^3.1 -> satisfiable by phpdocumentor/phpdocumentor[v3.1.0, v3.1.1, v3.1.2].

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

I really don't want to change my Symfony version and I haven't found the way to install the phpDoc on that project :c Do you have any ideas how to install it without changing my project version?

A: Taking a quick look at the phpDocumentor history, I don't think there's a version that'll be compatible with Symfony 4; they go from Symfony 2 on v2.9 to Symfony 5 on v3.0.
I'm not sure you'd want to tie up your project's requirements with those of an external tool like that, anyway.
I'd suggest using the phar distribution.  If you want it included with your project when it's cloned, you can either commit it to the repo or download it with a Composer script on install.


text:
Q: Jquery * Selector Query I know this might sound simple but somehow I am not able to understand the logic behind following piece of code
<!DOCTYPE html>
<html lang="en">
    <head>
        <script src="./js/jquery-1.7.2.min.js"></script>
    </head>
    <body>
        <script>
            alert("Dom Length:"+$('*').length);
            var a = "hi";
            alert($.type(a));
        </script>
    </body>
</html>

I am getting output as Dom Length:5 but I am not understanding how the lenght is populated.
UPDATE1:
I alerady had idea that it will select all elements in DOM, counting was misleading me. One more addition to this what if I add <p> hi </p> in body; it still shows length as 5. Is it right or should it be 6?

A: Well, you have these tags :

*

*1 <html>

*1 <head>

*1 <body>

*2 <script>
So 1 + 1 + 1 + 2 = 5.

A: $('*') use the all-selector and you have 5 elements in your page :

*

*html

*head

*script

*body

*script

I suggest you run this in the console :
$('*').get().map(function(e){ return e.tagName })

EDIT for your second question :
Adding hi in the body wouldn't add an element but a text node, that's why the count wouldn't change. Read more about nodes and elements.

EDIT for your comment :
Note that the script doesn't see the elements that are after itself. If you want it to see the whole DOM, change it to
$(function(){
    alert("Dom Length:"+$('*').length);
});

A: '*' represesnt all in jQuery, so when we say $('*') it means all DOM elements.

A: You are basically selecting all elements of an HTML.
In this case you have total 5 elements.
Indeed, it is a simple question. However, you are not alone.
I have been facing same issue but things answered easily by using reference card.
you can get one from the following link:
http://marieraney.com/webclass/docs/jquery_selectors_refcard.pdf


text:
Q: How do I find if a particular ID has a record of a specific value? Let's say we have a table booking where a peopleid can have multiple bookings. What's the best way to find people with at least 1 booking of active? Other booking values are cancelled,closed
I was thinking this, but I feel like there's gotta be a more efficient method:
select a.peopleid
     , sum(case status.status_desc when 'active' then 1 else 0 end) as counted
  from booking a
 inner join people
    on a.peopleid = people.peopleid
 inner join status
   on a.statusid = status.statusid
group by a.personid

I plan on doing a left join to this to get a simple yes or no indicator for if a person has at least one active booking or not
grain of booking is bookingid|statusid|peopleid and 1 person can have multiple bookings

A: If you just want to find the people with at least one active booking, just do a simple JOIN and put the desired status in the WHERE clause.
SELECT DISTINCT a.peopleid
FROM booking AS b
JOIN status AS s ON b.statusid = s.statusid
WHERE s.status_desc = 'active'

There's no need to join with people (unless you want to get other information about the person, which isn't shown in the question). And there's no need to count the matches; if there are no rows that match the status_desc = 'active' condition they won't be returned by the JOIN. SELECT DISTINCT gets rid of the duplicates when someone has multiple bookings.

A: You can use EXiSTS to check which user has at least one booking that match the condition.
select p.peopleid
from   people p
where  exists (select 1
               from   booking b
               join   status  s
               where  b.peopleid = p.peopleid
                      s.statusid = b.statusid
               and    s.status_desc = 'active');

A: Just use count with a WHERE clause.
select a.peopleid
     , COUNT(*) as counted
 from booking a
 inner join people
   on a.peopleid = people.peopleid
inner join status
 on a.statusid = status.statusid
where status.status_desc = 'active'
group by a.personid

A: Why not a simple join:
select p.* from people p
join booking b on b.peopleid  = a.peopleid
join status on status.statusid = b.statusid
where status.status_desc = 'active'

If you don't need any other info from the the people like their name, address.. then you can skip the people table and get the ID from the booking table.


text:
Q: Edit Template File from Table Angular I have a template excel file stored in an s3 Bucket that I am downloading which more or less matches the layout column by column of a table I have inside my web application. Basically what I want to do is take some information that is in the web table and write it into the template file on download.
I am downloading from the s3 bucket like so, which is generates a URL to be downloaded from
Export()
  {
    console.log("This function is running")
    const myKey = '...key'
    const mySecret = '...secret'
    AWS.config.update
    ({
      accessKeyId: myKey,
      secretAccessKey: mySecret
    });
    let s3 = new AWS.S3();
    const myBucket = 'bucket'
    const bucketKey = 'bucket key'
    const signedUrlExpireSeconds = 60 * 5

    let url = s3.getSignedUrl('getObject', {
      Bucket: myBucket,
      Key: bucketKey,
      Expires: signedUrlExpireSeconds
    })

    console.log("The URL is " + url)

    function downloadDataUrl(url)
    {
      let link = document.createElement('a')
      link.download = 'downloadFileName'
      link.href = url
      document.body.appendChild(link)
      link.click();
    }

    downloadDataUrl(url)
  }

Now the table I have in my webpage has basically the same columns what I hope to do, if possible is when the download button is clicked not only is the template file downloaded but the data that's in the table on the webpage is also added into the relevant cells in this case the template file is an excel. I am not sure however, if this sort of data transfer needs to occur on the S3 side of things or if I do it within my angular program or both.


text:
Q: How to display different images for annotations according to string value I have A MapView with multiple annotations. I need to put different images to annotations according to string value in my data.plist
My current code (work just for one category, one image):
NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];

    NSArray *anns = [dict objectForKey:@"Category1"];
    pinView.image = [UIImage imageNamed:[[anns objectAtIndex:0] objectForKey:@"Icon"]];

    pinView.canShowCallout=YES;

My plist file construction:

EDIT
My MapViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSMutableArray *annotations = [[NSMutableArray alloc]init];

    NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];

    NSArray *anns = [dict objectForKey:@"Category1"];

    NSLog(@" MapView is %@",mapView);
    NSLog(@"anns is: %@", anns);

    for(int i = 0; i < [anns count]; i++) {

        NSString *coordinates = [[anns objectAtIndex:i] objectForKey:@"Coordinates"];

        double realLatitude = [[[coordinates componentsSeparatedByString:@","] objectAtIndex:1] doubleValue];
        double realLongitude = [[[coordinates componentsSeparatedByString:@","] objectAtIndex:0] doubleValue];

        MyAnnotation *myAnnotation = [[MyAnnotation alloc] init];
        CLLocationCoordinate2D theCoordinate;
        theCoordinate.latitude = realLatitude;
        theCoordinate.longitude = realLongitude;

        //calculate distance
        CLLocationCoordinate2D annocoord = myAnnotation.coordinate;
        CLLocationCoordinate2D usercoord = self.mapView.userLocation.coordinate;

        NSLog(@"ANNO  = %f, %f", annocoord.latitude, annocoord.longitude);
        NSLog(@"USER = %f, %f", usercoord.latitude, usercoord.longitude);

        CLLocation *loc = [[CLLocation alloc] initWithLatitude:myAnnotation.coordinate.latitude longitude:myAnnotation.coordinate.longitude];
        CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude];

        NSLog(@"LOC  = %f, %f", loc.coordinate.latitude,  loc.coordinate.longitude);
        NSLog(@"LOC2 = %f, %f", loc2.coordinate.latitude, loc2.coordinate.longitude);

        CLLocationDistance dist = [loc distanceFromLocation:loc2];

        NSLog(@"DIST: %f", dist);

        myAnnotation.coordinate=CLLocationCoordinate2DMake(realLatitude,realLongitude);
        myAnnotation.title = [[anns objectAtIndex:i] objectForKey:@"Name"];
        myAnnotation.subtitle = [NSString stringWithFormat:@"%.f", dist];

        [mapView addAnnotation:myAnnotation];
        [annotations addObject:myAnnotation];
    }

    NSArray *alko = [dict objectForKey:@"Category2"];

    NSLog(@" MapView is %@",mapView);
    NSLog(@"alko is: %@", alko);

    for(int i = 0; i < [alko count]; i++) {

        NSString *coordinates = [[alko objectAtIndex:i] objectForKey:@"Coordinates"];

        double realLatitude = [[[coordinates componentsSeparatedByString:@","] objectAtIndex:1] doubleValue];
        double realLongitude = [[[coordinates componentsSeparatedByString:@","] objectAtIndex:0] doubleValue];

        MyAnnotation *myAnnotation = [[MyAnnotation alloc] init];
        CLLocationCoordinate2D theCoordinate;
        theCoordinate.latitude = realLatitude;
        theCoordinate.longitude = realLongitude;

        myAnnotation.coordinate=CLLocationCoordinate2DMake(realLatitude,realLongitude);
        myAnnotation.title = [[alko objectAtIndex:i] objectForKey:@"Name"];
        myAnnotation.subtitle = [[alko objectAtIndex:i] objectForKey:@"Address"];

        [mapView addAnnotation:myAnnotation];
        [annotations addObject:myAnnotation];
    }

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [self.locationManager startUpdatingLocation];

}

Annotation
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{

    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;

    static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
    MKPinAnnotationView* pinView = [[MKPinAnnotationView alloc]
                                    initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];

    NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];

    NSArray *anns = [dict objectForKey:@"Category1"];
    pinView.image = [UIImage imageNamed:[[anns objectAtIndex:0] objectForKey:@"Icon"]];

    pinView.canShowCallout=YES;

    return pinView;
}

A: Is this what you need?
NSString *theCategory;

// set theCategory to what you need.
theCategory = @"Category1"

NSArray *anns = [dict objectForKey:theCategory];

Edit 1
First you'd better set the annotation class as following:
MyAnnotation.h
#import <MapKit/MapKit.h>

@interface MyAnnotation : NSManagedObject <MKAnnotation>{

CLLocationCoordinate2D coordinate;
UIImage *imageForMyAnnotation;
}

@property (nonatomic,readwrite) CLLocationCoordinate2D coordinate;
@property (nonatomic, retain) UIImage *imageForMyAnnotation;

MyAnnotation.m
#import "MyAnnotation.h"

@implementation MyAnnotation

- (CLLocationCoordinate2D)coordinate
{
//here you can set the coordinate of your annotation
return coordinate;
}

- (UIImage *)imageForMyAnnotation{
//set the image here, i think it is depend on the coordinate right? You can put some code here to chose the category that corresponding to the coordinate
return image;
}

// optional
- (NSString *)title
{
return title;
}
- (NSString *)subtitle
{
return subtitle;
}

Then in your mapView, you can add the annotation with
MapView.m
[self.mapView addAnnotations:myAnnotationArray];

or
[self.mapView addAnnotation:myAnnotation];

and
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation{

UIImageView *annotationImageView = [[UIImageView alloc] initWithImage: myAnnotation.imageForMyAnnotatioin];

customPinView.leftCalloutAccessoryView = annotationImageView;

}


text:
Q: Ncurses: Dialog box background color be changed? I am working on Linux Operating System. I want to display a dialog box on an item selection from a drop down menu implemented in ncurses, but the problem is that the dialog box fills up the screen with blue background and further nothing can be done.So, is there a way to display ncurses dialog box inside current window preserving existing ncurses components?
Thanks in advance.

A: You might use CDK (Curses development kit) to the create dialog box. It provides many other widgets that you can use such as,
Alphalist
Button
Buttonbox
Calendar
Entry Field
File Viewer
Floating Scale
Floating Slider
Graph
Histogram etc...

see this


text:
Q: Finding The Zeros Of $\frac{z^2\sin z}{\cos z -1}$ $$f(z)=\frac{z^2\sin z}{\cos z -1}$$
$$\frac{z^2\sin z}{\cos z -1}=0\iff z^2\sin z=0$$ so $z=\pi k$ and $z=0$ are zeros, to find the order we must derive $\frac{z^2\sin z}{\cos z -1}$?

A: Since
$\sin(2x)=2\sin(x)\cos(x)$
and
$\cos(2x)=\cos^2(x)-\sin^2(x)
=1-2\sin^2(x)$
so
$\cos(2x)-1
=-2\sin^2(x)
$,
$f(2z)
=\frac{4z^2\sin 2z}{\cos 2z -1}
=\frac{4z^22\sin(z)\cos(z)}{-2\sin^2(z)}
=\frac{-2z^2\cos(z)}{\sin(z)}
=-2\frac{z}{\sin(z)}z\cos(z)
$.
The zeros are
$z=0$
(taking the limit
since it is undefined there)
and the zeros of
$\cos(z)$
which are
$(k+\frac12)\pi$.

A: Note that the denominator $\cos z - 1$ has zeroes at $z = 2m\pi$, so not all zeroes of $\sin z$ are zeroes of $f(z)$. To show this, apply L'Hopital's rule
$$ \lim_{z\to 2m\pi \ne 0} \frac{z^2\sin z}{\cos z - 1} = \lim_{z\to 2m\pi \ne 0}\frac{2z\sin z + z^2\cos z}{-\sin z} = \text{DNE} $$
Hence, the zeroes of $\sin z$ where $z=n\pi = 2m\pi$ are actually poles. This leaves the odd multiples, $z = (2m+1)\pi$, which are indeed zeroes of $f(z)$.
$z = 0$ is also a zero, which you can show by applying L'Hopital once more
To simplify computations, we rewrite
$$ f(z) = \frac{z^2\sin z}{\cos z - 1} = -\frac{2z^2 \sin(\frac{z}{2})\cos(\frac{z}{2})}{2\sin^2(\frac{z}{2})} = -z^2\cot\left(\frac{z}{2}\right) $$
which confirms $z = (2m+1)\pi$ as the zeroes of $\cot(\frac{z}{2})$. Futhermore
$$ f'(z) = -2z\cot\left(\frac{z}{2}\right) + \frac{z^2}{2}\csc^2\left(\frac{z}{2}\right) $$
You can check that
$$ \lim_{z\to 0} f'(z) = -4\lim_{z\to0} \frac{\frac{z}{2}}{\sin\left(\frac{z}{2}\right)}\cos\left(\frac{z}{2}\right) + 2 \lim_{z\to 0} \frac{\left(\frac{z}{2}\right)^2}{\sin^2\left(\frac{z}{2}\right)} = -2 $$
and
$$ f'\big((2m+1)\pi\big) = \frac{(2m+1)^2\pi^2}{2} $$
Proving that these are all first-order zeroes


text:
Q: Has anyone got a tutorial up on getting your own smartcard and getting pkcs#11 working on it? Has anyone got a tutorial up on getting your own smartcard and getting pkcs#11 working on it? In Linux? (Windows would be fine too).
Most of the vendors seem to assume you'll be wanting enough for your whole company, not one or two.

A: This heavily depends on the driver and application you use. We use OpenSC/OpenCT for all non-Enterprise Smartcard uses. They have decent documentation.

A: Yes, check out what OpenSC supports.
Make sure that you know what you want - USB tokens or full-size smart cards. There are pros and cons with both solutions - USB tokens require drivers, often by the manufacturer, to use on some platforms (eg Windows7 or OSX can be troublesome). But they are easy to use once set up and sometimes offer better performance than ISO smartcards. Casual smart cards on the other hand have also contactless interfaces and can be used with pinpad readers which provide higher security than USB tokens.
If you're into fancier features and may want to extend your card infra further than just pkcs#11 crypto, javacards might be useful (OpenSC can not work with JavaCards directly but certain applets are supported, like Muscle) Otherwise look for a supported card operating system.


text:
Q: An error has occured opening the folder on the FTP server. Make sure you have permission to access the folder
I cannot access the folder in my FTP server remotely.

FTP unable to work

I can login using cmd

enter image description here

A: This could be the FTP Firewall Support issue, you can try the following steps to solve the problem:
1.Go to IIS Manger -> Server name, double click on FTP Firewall Support.
2.Change the Data channel Port Range to 0-0 and remove the External IP addresses of Firewall in it is used for internal only.


text:
Q: PHP: sort array ouput but randomize same values Whats the best/easiest way to get this:
what i have:
array('100', '100', '100', '80', '70', '70', '50', '45');

what the output should look like:
100 (random order)
100 (random order)
100 (random order)
80
70 (random order)
70 (random order)
50
45

A: you have to use usort or uasort (uasort keeps keys of the array). Using PHP 5.3, you may do it like this :
shuffle($array); // randomize

uasort($array, function($a, $b){
    if($a === $b) {
        return rand(0, 1);
    }
    return $a < $b;
});

You may have to name the function before, like the php documentation shows http://www.php.net/manual/fr/function.uasort.php

A: You can use usort (http://www.php.net/manual/en/function.usort.php) or uksort depending on your requirements. You can then choose to randomly return a positive or negative number if the values are equal.

A: Try something like this:
http://codepad.org/SzSeUM4u
Based on the aasort from:
Sort Multi-dimensional Array by Value


text:
Q: Use the style defined in resource dictionary : I  have a style defined for listboxitem in a resource dictionary. I want to use this style in a cs file of listbox :
I am doing the below thing but it gives me null ,CustomListBoxItemStyle is a name of a key given to the style.
public class CustomListBox : ListBox
{
    public CustomListBox()
    {
        this.ItemContainerStyle = Application.Current.Resources["CustomListBoxItemStyle"] as Style;
    }
}

There is no xaml for this.
How to achieve this?

A:
I have a style defined for listboxitem in a resource dictionary.

but is that resource dictionary merged into the application's resource dictionary.  It doesn't happen automatically you need to include it in the App.xaml like this:-
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="MyResourceDictionary.xaml" />
        </ResourceDictionary.MergedDictionaries>
        <!-- other resource defined directly in app xaml -->
    </ResourceDictionary>
</Application.Resources>

A: Ok i tried almost every thing but there was no way to get rid of getting the this.ItemContainerStyle = null
So i changed the way of doing , Instead setting the ItemContainerStyle in a customlistbox.cs inherited from Listbox..I removed it from there.
Then where I was using mine custom listbox that was a usercontrol, so there was axaml for it :), hence i defined my  ItemContainerStyle  in the usercontrol.resource as shown below :
 <UserControl.Resources>
        <Style x:Key="CustomListBoxItemStyle" TargetType="ChargeEntry:CustomListBoxItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ChargeEntry:CustomListBoxItem">
                        <Grid Background="{TemplateBinding Background}">
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal"/>
                                    <VisualState x:Name="MouseOver">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To=".35" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="fillColor"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Disabled">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To=".55" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="contentPresenter"/>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="SelectionStates">
                                    <VisualState x:Name="Unselected"/>
                                    <VisualState x:Name="Selected">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To=".75" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="fillColor2"/>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="FocusStates">
                                    <VisualState x:Name="Focused">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Visibility" Storyboard.TargetName="FocusVisualElement">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <Visibility>Visible</Visibility>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Unfocused"/>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <Grid HorizontalAlignment="Stretch">
                                <TextBlock x:Name="txtName" />
                            </Grid>
                            <Rectangle x:Name="fillColor" Fill="#FFBADDE9" IsHitTestVisible="False" Opacity="0" RadiusY="1" RadiusX="1"/>
                            <Rectangle x:Name="fillColor2" Fill="#FFBADDE9" IsHitTestVisible="False" Opacity="0" RadiusY="1" RadiusX="1"/>
                            <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}"/>
                            <Rectangle x:Name="FocusVisualElement" RadiusY="1" RadiusX="1" Stroke="#FF6DBDD1" StrokeThickness="1" Visibility="Collapsed"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

    </UserControl.Resources>

and then used it to custom listbox defined inside the usercontrol only..
 <CustomListBox  x:Name="lstComboBoxResult"  ItemContainerStyle="{StaticResource CustomListBoxItemStyle}"   />


text:
Q: Create go back button function like Angry Birds I'm creating an app in which Go Back Button function like Angry Birds have, I've created popup window, it has close button and other buttons working.
To go back I use:
@Override
public void onBackPressed() {
    // Write your code here
    initiatePopupWindow();
    super.onBackPressed();
}

I know about finish() code that do not go back to pervious Activity
this code is working when goback Button is pressed. Popup Window opens but instantly it go back to previous Activity.
My Question is : How can stay popup window when go back button is pressed and do not leave to previous activity like Angry Bird games has
When user pressed go back button it open the popup window and user have to select one option
i want to make something like that
looking for suggestions
thanks

A: Remove this line:
super.onBackPressed();

From:
@Override
public void onBackPressed() {
    // Write your code here
    initiatePopupWindow();
    super.onBackPressed();
}


text:
Q: Android DroidGap null pointer onKeyDown() I am learning to develop web app with jquerymobile and Android sdk.
My web app is structured in some pages that are loaded with:
private void loadURL(final String in){
    handler.post(new Runnable() {
        public void run() {
            webView.loadUrl(in);
        }
    });
}

public void loadPage(String in){
    final String url = HTML_ROOT + in;
    loadURL(url);
}

This is my onCreate method:
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    webView = new WebView(this); //super.init();

    setContentView(webView);
    webView.getSettings().setJavaScriptEnabled(true);

    .....

    handler = new Handler();
    webView.addJavascriptInterface(this, "MyTeam");
    loadPage("menu.html");

}

And onkeydown method:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
   if(webView == null){
          Log.d("My Tag", "Webview is null on KeyCode: " + String.valueOf(keyCode));
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
}

The problem is:
example a:
1- from menu.html I go in another page xxx.html
2- I click back button on my smartphone
3- onKeyDown is fired
example b:
1- from menu.html I click on smartphone backbutton or another button
After return super.onkeydown I have returned in example a and example b:
12-01 15:34:56.796: E/AndroidRuntime(14048): FATAL EXCEPTION: main
12-01 15:34:56.796: E/AndroidRuntime(14048): java.lang.NullPointerException
12-01 15:34:56.796: E/AndroidRuntime(14048):    at org.apache.cordova.DroidGap.onKeyUp(DroidGap.java:1018)

Why DroidGapClass return me null pointer exception?????
Thanks a lot.


text:
Q: easily add hover animation to SVG from SVG sprite I'm buliding an SVG sprite as follows:

    <svg display="none" width="0" height="0" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
    <symbol id="icon-arrow-down" viewBox="0 0 1024 1024">
      <title>arrow-down</title>
      <path class="path1" d="M715.215 393.582l-204.117 204.166-206.141-206.092c-9.533-9.533-24.942-9.533-34.475 0s-9.533 24.966 0 34.475l223.378 223.33c4.584 4.584 10.776 7.144 17.237 7.144s12.678-2.56 17.237-7.144l221.355-221.403c9.533-9.533 9.533-24.966 0-34.475-9.533-9.533-24.942-9.533-34.475 0z"></path>
      <path class="path2" d="M512 0c-282.331 0-512 229.669-512 512s229.669 512 512 512c282.307 0 512-229.693 512-512s-229.693-512-512-512zM512 975.238c-255.439 0-463.238-207.799-463.238-463.238s207.799-463.238 463.238-463.238 463.238 207.799 463.238 463.238c0 255.439-207.799 463.238-463.238 463.238z"></path>
    </symbol>
    </defs>
    </svg>

                     <svg class="icon icon-arrow-down"><use xlink:href="#icon-arrow-down"></use></svg>

What I would like to do is animate the paths for example turn a triangle into a square. I guess it has to be done with Snap.svg, but how exactly?

A: You can simply use <animate> to animate the d attribute with the one restriction that the paths have to match as far as the curves and lines go.  So for instance, if you original path is one line followed by a curve and 2 lines, your animation must animate to the same, though you can change the coordinates for each.  This can be a bit tricky depending on the shapes you are trying to morph and may require things like using a curve but providing values that actually makes it a straight line, etc.
For example, by changing just the first M and the first two lines in your animation, you can get this:
http://jsfiddle.net/hp7ncyy2/1/

<svg display="none" width="0" height="0" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
        <symbol id="icon-arrow-down" viewBox="0 0 1024 1024">
            <title>arrow-down</title>
            <path class="path1">
                <animate attributeName="d" dur="2s" repeatCount="indefinite" values="
                        M715.215 393.582l-204.117 204.166-206.141-206.092c-9.533-9.533-24.942-9.533-34.475 0s-9.533 24.966 0 34.475l223.378 223.33c4.584 4.584 10.776 7.144 17.237 7.144s12.678-2.56 17.237-7.144l221.355-221.403c9.533-9.533 9.533-24.966 0-34.475-9.533-9.533-24.942-9.533-34.475 0z;
                        M715.215 493.582l-204.117 -204.166-206.141 206.092c-9.533-9.533-24.942-9.533-34.475 0s-9.533 24.966 0 34.475l223.378 223.33c4.584 4.584 10.776 7.144 17.237 7.144s12.678-2.56 17.237-7.144l221.355-221.403c9.533-9.533 9.533-24.966 0-34.475-9.533-9.533-24.942-9.533-34.475 0z;
                        M715.215 393.582l-204.117 204.166-206.141-206.092c-9.533-9.533-24.942-9.533-34.475 0s-9.533 24.966 0 34.475l223.378 223.33c4.584 4.584 10.776 7.144 17.237 7.144s12.678-2.56 17.237-7.144l221.355-221.403c9.533-9.533 9.533-24.966 0-34.475-9.533-9.533-24.942-9.533-34.475 0z" />
            </path>
            <path class="path2" d="M512 0c-282.331 0-512 229.669-512 512s229.669 512 512 512c282.307 0 512-229.693 512-512s-229.693-512-512-512zM512 975.238c-255.439 0-463.238-207.799-463.238-463.238s207.799-463.238 463.238-463.238 463.238 207.799 463.238 463.238c0 255.439-207.799 463.238-463.238 463.238z"></path>
        </symbol>
    </defs>
</svg>

    <svg class="icon icon-arrow-down">
        <use xlink:href="#icon-arrow-down"></use>
    </svg>

This is obviously not a perfect square, but you get the basic idea.  You would need to manipulate the path to get the exact shape you want.
If you change the number or type of commands in the path, the animate will just jump back and forth with no animation.