text:
Q: Split DateTime into 1-Minute Slots Across the Day I have a bunch of DateTimes using slqserver express 2012, and I would like to split and allocate those datetimes into 1-minute slots across the day, noting that there will potentially be more than one day in the data. However, I will first concentrate on only one day of data. For example, if I have the following input data:
OnTime            OffTime           Duration
2017-11-01 00:03  2017-11-01 00:04  1
2017-11-01 00:08  2017-11-01 00:11  3
2017-11-01 00:13  2017-11-01 00:14  1
2017-11-01 00:21  2017-11-01 00:24  3
2017-11-01 00:26  2017-11-01 00:30  4

I would like the output to be slotted into each minute slot of the day, where there are 1440 minutes in the day, and if the datetime spans the minute slot in question and logical 1 is put into the corresponding columns and a 0 otherwise, startin at 0000 = minute slot 0 and 2359 = minute slot 1439. Output data would thus be something like:
Minute   Active
0        0
1        0
2        0
3        1
4        0
5        0
6        0
7        0
8        1
9        1
10       1
11       0
12       0
13       1
14       0
15       0
...      ...
1440     0

I was thinking that I could cross apply the datetimes with a duration of one minute but I don't know exactly where to go with that or if its even the best way. I would also be interested in extending this idea to slot into seconds or hours gaps instead of minutes etc. Any help greatly appreciated.
Regards, M

A: Try the below code
CREATE FUNCTION [dbo].[GetAllMinutesBetweenRange]
(
   @FromDate DATETIME
   ,@ToDate DATETIME

)
RETURNS @Dates TABLE
(
   DateVal DATETIME
)
AS
BEGIN

;WITH CTE
AS
(
    SELECT @FromDate AS FromDate
    UNION ALL
    SELECT DATEADD(MI,1,FromDate)
    FROM CTE
    WHERE FromDate < @ToDate
)

INSERT INTO @Dates
SELECT FromDate FROM CTE
option (maxrecursion 0)

RETURN;

END

    SELECT ROW_NUMBER() OVER(ORDER BY DATEVAL) AS MINUTE
      ,DATEVAL
      ,CASE WHEN TableA.OnTime IS NULL THEN 0 ELSE 1 END
FROM [dbo].[GetAllMinutesBetweenRange]('2017-11-01 00:00:00','2017-11-01 23:59:00') Res1
LEFT JOIN TableA ON Res1.DateVal >= TableA.OnTime AND Res1.DateVal< TableA.OffTime

The table valued function can be modified to handle the seconds as well
Hope this helps!

A: try This
WITH CTE
AS
(
   SELECT
    SeqNo = 0,
    Strt = CAST(CAST(GETDATE() AS DATE) AS DATETIME)

  UNION ALL

  SELECT
    SeqNo = SeqNo+1,
    Strt = DATEADD(minute,1,Strt)
  FROM CTE
    WHERE CAST(CAST(Strt AS DATE) AS DATETIME)=CAST(CAST(GETDATE() AS DATE) AS DATETIME)

)
SELECT
  SeqNo AS Minute,
  Active = CASE WHEN T1.Duration IS NOT NULL THEN 1 ELSE 0 END
FROM CTE C1
  LEFT JOIN T1
    ON CAST(T1.OnTime AS DATETIME) >= CAST(C1.Strt AS DATETIME)
      AND CAST(T1.OffTime AS DATETIME) <= CAST(C1.Strt AS DATETIME)
OPTION (maxrecursion 0)

A: This query will generate the resultset you need for some date. You can put it in a function. cte part is just for demo purpose you must use your table.
DECLARE @somedate date = '2017-11-01'

DECLARE @somedateN nvarchar(10) = CAST(@somedate as nvarchar(10))
DECLARE @start datetime = CAST(@somedateN +' 00:00:00' as datetime),
        @end datetime = CAST(@somedateN +' 23:59:59' as datetime)

-- Simulation of your table with some new rows
;WITH cte AS (
    SELECT  OnTime,
            OffTime,
            Duration
    FROM (VALUES
    ('2017-11-01 00:03', '2017-11-01 00:04', 1),
    ('2017-11-01 00:08', '2017-11-01 00:11', 3),
    ('2017-11-01 00:13', '2017-11-01 00:14', 1),
    ('2017-11-01 00:21', '2017-11-01 00:24', 3),
    ('2017-11-01 00:26', '2017-11-01 00:30', 4),
    ('2017-11-01 00:59', '2017-11-01 01:30', 31),   -- new row
    ('2017-11-01 23:57', '2017-11-02 00:02', 5)     -- new row
    ) as t(OnTime,OffTime,Duration)
), minutes_ AS ( -- table with all minutes from 0 to 1440
    SELECT  0 as [Minute]
    UNION ALL
    SELECT  [Minute] + 1
    FROM minutes_
    WHERE [Minute] <= DATEDIFF(minute,@start,@end)
)
-- here we go!
SELECT  [Minute],
        CASE WHEN c.Duration IS NULL THEN 0 ELSE 1 END as [Active]
FROM minutes_ m
LEFT JOIN cte c
    ON m.[Minute] >= DATEDIFF(minute,@start,OnTime)
    AND m.[Minute] < DATEDIFF(minute,@start,OffTime)
OPTION (MAXRECURSION 0)

Output:
Minute      Active
----------- -----------
0           0
1           0
2           0
3           1
4           0
5           0
6           0
7           0
8           1
9           1
10          1
11          0
12          0
13          1
...
1434        0
1435        0
1436        0
1437        1
1438        1
1439        1
1440        1

A: Another solution for you to consider. This query is focused on one day:
declare @dateTable table(OnTime datetime, OffTime datetime, Duration int)
insert into @dateTable values('2017-11-01 00:03','2017-11-01 00:04',1)
insert into @dateTable values('2017-11-01 00:08','2017-11-01 00:11',3)
insert into @dateTable values('2017-11-01 00:13','2017-11-01 00:14',1)
insert into @dateTable values('2017-11-01 00:21','2017-11-01 00:24',3)
insert into @dateTable values('2017-11-01 00:26','2017-11-01 00:30',4)

declare @result table(minute int, active bit)
declare @length int = 1440
declare @index int = 0

while @index <= @length
begin
    insert into @result values(@index,0)
    set @index = @index + 1
end

update t
set t.active = case when d.OnTime is not null then 1 else 0 end
from @result as t
left join @dateTable as d on t.minute >= datepart(hour,ontime)*60 + datepart(minute,ontime)
                        and t.minute < datepart(hour,offtime)*60 + datepart(minute,offtime)

select * from @result


text:
Q: How to customise googlemap infoWindow using Swift 3 Xcode version:
8.1
aim:
To replace native infoWindow by custom one
problem:

*

*When I click on the marker, my custom infoWindow did not show up but the native one,
Or

*Thread 1:signal SIGABRT shown if I don't delete myView.delegate = self(See my code & my research #21)

what I have done:

*

*Created a .swift file and a .xib file with my custom infoWindow design.

*Inserted mapView function into ViewController.swift:
override func viewDidLoad() {
    super.viewDidLoad()

...
    let camera = GMSCameraPosition.camera(withLatitude: latitude,
                                          longitude: Longitude, zoom: 16)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    mapView.delegate = self  // Thread 1:signal SIGABRT shown if i add this line
    mapView.isMyLocationEnabled = true
    self.view = mapView

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2DMake(latitude, Longitude)
    marker.title = "Me"
    marker.map = mapView
    mapView.selectedMarker = marker
}

func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
    let infoWindow = Bundle.main.loadNibNamed("CustomInfoWindow", owner: self.view, options: nil)!.first! as! CustomInfoWindow
    infoWindow.title.text = marker.title
    return infoWindow
}

my research:

*

*https://developers.google.com/maps/documentation/ios-sdk/marker

*https://developers.google.com/maps/documentation/ios-sdk/reference/protocol_g_m_s_map_view_delegate-p

*https://forums.developer.apple.com/thread/8462

*http://kevinxh.github.io/swift/custom-and-interactive-googlemaps-ios-sdk-infowindow.html

*https://productforums.google.com/forum/#!topic/maps/w0sP7r3XAF4

*Custom InfoWindow for marker Google Maps SDK, Swift 2.0

*https://www.youtube.com/watch?v=ILiBXYscsyY

*Custom annotation view in Google Maps SDK

*Creating custom info window in swift with the Google maps iOS sdk?

*How to show a Info window in iOS Google maps without tapping on Marker?

*Custom info window in IOS google maps sdk

*IOS Google Map Custom InfoWindow Xib error

*Google Maps Info window's resizing based on the internal content

*Custom Info Window for Google Maps

*Custom InfoWindows issue -Google Maps iOS SDK-

*How to customize the InfoWindow of google map iOS SDK?

*swift 3 google maps custom infowindow

*How to initialise a UIView Class with a xib file in Swift, iOS

*https://github.com/ziyang0621/GoogleMaps-Swift/blob/master/GoogleMapSwift/ViewController.swift

*https://github.com/ryanmaxwell/GoogleMapsCalloutView

*Implementing custom markerInfoWindow in swift not working

*https://codedump.io/share/hh7CO7c2j3PI/1/custom-infowindow-for-marker-google-maps-sdk-swift-20

A: Did you implement GMSMapViewDelegate?
ViewController: GMSMapViewDelegate {

   ...

}

It seems to be that you are getting the error(crash) because you are setting the delegate to self, but your controller does not conform to that protocol.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create new instances of a class from an array of classes with Java I'm trying to create an array of classes in Java. Not objects, but classes. Currently I have a class MyBaseClass and I extend three classes MyClass1, MyClass2, and MyClass3 from it. I store these classes to a static array like this:
private static MyBaseClass[] classes = {
        new MyClass1(),
        new MyClass2(),
        new MyClass3()
};

public static MyBaseClass getInstanceOfClass(int index) {
    return classes[index];
}

and then I use those methods like this:
try {
    MyBaseClass obj = getInstanceOfClass(index).getClass().newInstance();
} catch (InstantiationException | IllegalAccessException e) {
    e.printStackTrace();
}

Now I'm wondering if I could do this in an easier way. If I could create an array of classes I might be able to escape the getInstanceOfClass() method and some possible exceptions. I tried doing this:
private static Class<MyBaseClass>[] classes = {
        MyClass1.class,
        MyClass2.class,
        MyClass3.class
};

But this gives me an error "Incompatible types" as MyClass1 is not equal to MyBaseClass. Interestingly enough, this seemingly works:
private static Class<?>[] classes = {
        new MyClass1().getClass(),
        new MyClass2().getClass(),
        new MyClass3().getClass()
};

But the idea of that is horrible and it's even marked by my debugger. So, any better ways of doing this?
Edit:
This works:
private static Class<?>[] classes = {
        MyClass1.class,
        MyClass2.class,
        MyClass3.class
};

But then the result of getInstanceOfClass(index).newInstance(); is an Object so I have to do typecasting. I'm not really sure if that's safe in this case...

A: You have to indicated that you are looking for possibly subclasses of MyBaseClass. For this you can add ? extends to the generic type description. Note that this will also accept MyBaseClass itself.
Added to this, you can use .class to get the Class object of a class, instead of making an isntance and calling getClass().
Unfortunately this doesn't work with arrays because they don't allow generic types. So you have to add them to a list (which is almost always a good thing):
private static ArrayList<Class<? extends MyBaseClass>> classes = new ArrayList<Class<? extends MyBaseClass>>();

...

classes.add(MyClass1.class),
classes.add(MyClass2.class),
classes.add(MyClass3.class),


text:
Q: SDL2 render texture visibly lags behind mouse I'm using SDL2 on Windows (I've tested both Windows 7 and Windows 8). I was playing around with rendering a texture locked to the mouse coordinates to create a sort of "crosshair" effect.
It works, but the texture visibly lags behind the mouse which creates an awkward delay between mouse motion and the rendered updates. Honestly, the delay is very minor, but to someone who cares about absolute accuracy, it would drive the person insane.
My question is basically, is this normal? I'm guessing that the delay is due to the time it takes for Windows to deliver the event to SDL and then SDL to deliver the event to me. How can one achieve a locked "crosshair" effect via SDL?
My code for reference:
#include "SDL.h"

int main( int argc, char* args[] )
{
    SDL_Init( SDL_INIT_EVERYTHING );

    SDL_Window* window = SDL_CreateWindow("SDL", 100, 100, 640, 480, SDL_WINDOW_SHOWN);

    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    SDL_Surface* surface = SDL_LoadBMP("mouse.bmp");

    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
    SDL_FreeSurface(surface);

    bool isExiting = false;
    int x = 0;
    int y = 0;

    while(!isExiting)
    {
        SDL_Event e;
        while(SDL_PollEvent(&e))
        {
            if(e.type == SDL_QUIT)
            {
                isExiting = true;
                break;
            }
            else if(e.type == SDL_MOUSEMOTION)
            {
                x = e.motion.x;
                y = e.motion.y;
            }
        }

        SDL_Rect destRect;
        destRect.h = 19;
        destRect.w = 19;
        destRect.x = x;
        destRect.y = y;

        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, texture, NULL, &destRect);
        SDL_RenderPresent(renderer);
    }

    SDL_Quit();

    return 0;
}

A: While I cannot be sure why your loop lags, SDL has support for changing the mouse surface, as well as some other functions you may be interested in. It seems like you could put SDL_CreateColorCursor(SDL_Surface* surface, int hot_x, int hot_y) to good use. Here's a link to the wiki page on mouse support: http://wiki.libsdl.org/CategoryMouse
Happy coding!

A: In a project I'm working on, I do something like this:
(Outside the main game loop):
SDL_Texture* cursor = //blah;
SDL_Rect cursor_hitbox;
SDL_QueryTexture(cursor, NULL, NULL, &cursor_hitbox.w, &cursor_hitbox.h);

(In the main game loop):
SDL_GetMouseState(&cursor_hitbox.x, &cursor_hitbox.y);

While using this I haven't really noticed any input lag. Maybe it's just the event type?
Note that this is most likely not as efficient though, since you would be getting the mouse state every frame, instead of just when you move the mouse.


text:
Q: Setting a QDialog to be an alien In a standalone GUI application where I don't have a windowmanager nor a composite manager I want to display a QDialog to the user to ask for values.
The dialog is quite big, so I want to make it translucent so that the user can look through it to see what happens in the application while the dialog is shown.
The problem is that for translucency of X native windows, there needs to be a composite manager. Qt internal widgets can be painted translucent because they don't correspond to native X windows (aliens) and are completely only known to Qt.
Is there a way to make the background of a QDialog translucent without having a composite manager running? Perhaps making it a normal child widget/alien of the application's main window? Is there a better alternative to this?

A: I don't know of any way of turning a QDialog into a normal child widget. Looking at the Qt for X11 code, I can't figure out a way of not setting the Qt::WindowFlags passed to the QWidget (parent) constructor so that it would be a plain widget and not a window of its own (but I could be wrong, didn't spend a lot of time on that).
A simple alternative is to use a plain QWidget as your container, instead of a QDialog. Here's a sample "PopupWidget" that paints a half-transparent-red background.
#include <QtGui>

class PopupWidget: public QWidget
{
 Q_OBJECT

 public:
  PopupWidget(QWidget *parent): QWidget(parent)
  {
   QVBoxLayout *vl = new QVBoxLayout;
   QPushButton *pb = new QPushButton("on top!", this);
   vl->addWidget(pb);
   connect(pb, SIGNAL(clicked()), this, SLOT(hide()));
  }

 public slots:
  void popup() {
   setGeometry(0, 0, parentWidget()->width(), parentWidget()->height());
   raise();
   show();
  }

 protected:
  void paintEvent(QPaintEvent *)
  {
   QPainter p(this);
   QBrush b(QColor(255,0,0,128));
   p.fillRect(0, 0, width(), height(), b);
  }
};

To show it, call it's popup() slot which will raise it to the top of the widget stack, make it as large as its parent, and show it. This will mask all the widgets behind it (you can't interact with them with the mouse). It hides itself when you click on that button.
Caveats:

*

*this doesn't prevent the user from using Tab to reach the widgets underneath. This could be fixed by toggling the enabled property on your "normal" widget container for example. (But don't disable the PopupWidget's parent: that would disable the popup widget itself.)

*this doesn't allow for a blocking call like QDialog::exec

*the widgets in that popup won't be transparent, you'd have to create custom transparent-background versions for all the widget types you need AFAIK.

But that's probably less of a hassel than integarting a compositing manager in your environment.


text:
Q: Helm kubernetes on AKS Pod CrashLoopBackOff I'm trying to deploy a simple nodejs application via helm kubernetes on Azure Kubernetes Service, but after pulling my image it says CrashLoopBackOff.
Here's what I have tried so far:
My Dockerfile:
FROM node:6
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 32000
CMD [ "npm", "start" ]

My server.js:
'use strict';

const express = require('express');

const PORT = 32000;
const HOST = '0.0.0.0';

const app = express();
app.get('/', (req, res) => {
  res.send('Hello world from container.\n');
});

app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);

I have pushed this image to ACR.

New Update: Here's the complete output of kubectl describe pod POD_NAME:

Name:               myrel02-mychart06-5dc9d4b86c-kqg4n
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               aks-nodepool1-19665249-0/10.240.0.6
Start Time:         Tue, 05 Feb 2019 11:31:27 +0500
Labels:             app.kubernetes.io/instance=myrel02
                    app.kubernetes.io/name=mychart06
                    pod-template-hash=5dc9d4b86c
Annotations:        <none>
Status:             Running
IP:                 10.244.2.5
Controlled By:      ReplicaSet/myrel02-mychart06-5dc9d4b86c
Containers:
  mychart06:
    Container ID:   docker://c239a2b9c38974098bbb1646a272504edd2d199afa50f61d02a0ce335fe60660
    Image:          registry-1.docker.io/arycloud/docker-web-app:0.5
    Image ID:       docker-pullable://registry-1.docker.io/arycloud/docker-web-app@sha256:4faab280d161b727e0a6a6d9dfb52b22cf9c6cd7dd07916d6fe164d9af5737a7
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Completed
      Exit Code:    0
      Started:      Tue, 05 Feb 2019 11:39:56 +0500
      Finished:     Tue, 05 Feb 2019 11:40:22 +0500
    Ready:          False
    Restart Count:  7
    Liveness:       http-get http://:http/ delay=0s timeout=1s period=10s #success=1 #failure=3
    Readiness:      http-get http://:http/ delay=0s timeout=1s period=10s #success=1 #failure=3
    Environment:
      KUBERNETES_PORT_443_TCP_ADDR:  cluster06-ary-2a187a-dc393b82.hcp.centralus.azmk8s.io
      KUBERNETES_PORT:               tcp://cluster06-ary-2a187a-dc393b82.hcp.centralus.azmk8s.io:443
      KUBERNETES_PORT_443_TCP:       tcp://cluster06-ary-2a187a-dc393b82.hcp.centralus.azmk8s.io:443
      KUBERNETES_SERVICE_HOST:       cluster06-ary-2a187a-dc393b82.hcp.centralus.azmk8s.io
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-gm49w (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  default-token-gm49w:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-gm49w
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason     Age                    From                               Message
  ----     ------     ----                   ----                               -------
  Normal   Scheduled  10m                    default-scheduler                  Successfully assigned default/myrel02-mychart06-5dc9d4b86c-kqg4n to aks-nodepool1-19665249-0
  Normal   Pulling    10m                    kubelet, aks-nodepool1-19665249-0  pulling image "registry-1.docker.io/arycloud/docker-web-app:0.5"
  Normal   Pulled     10m                    kubelet, aks-nodepool1-19665249-0  Successfully pulled image "registry-1.docker.io/arycloud/docker-web-app:0.5"
  Warning  Unhealthy  9m30s (x6 over 10m)    kubelet, aks-nodepool1-19665249-0  Liveness probe failed: Get http://10.244.2.5:80/: dial tcp 10.244.2.5:80: connect: connection refused
  Normal   Created    9m29s (x3 over 10m)    kubelet, aks-nodepool1-19665249-0  Created container
  Normal   Started    9m29s (x3 over 10m)    kubelet, aks-nodepool1-19665249-0  Started container
  Normal   Killing    9m29s (x2 over 9m59s)  kubelet, aks-nodepool1-19665249-0  Killing container with id docker://mychart06:Container failed liveness probe.. Container will be killed and recreated.
  Warning  Unhealthy  9m23s (x7 over 10m)    kubelet, aks-nodepool1-19665249-0  Readiness probe failed: Get http://10.244.2.5:80/: dial tcp 10.244.2.5:80: connect: connection refused
  Normal   Pulled     5m29s (x6 over 9m59s)  kubelet, aks-nodepool1-19665249-0  Container image "registry-1.docker.io/arycloud/docker-web-app:0.5" already present on machine
  Warning  BackOff    22s (x33 over 7m59s)   kubelet, aks-nodepool1-19665249-0  Back-off restarting failed container

Update: docker logs CONTAINER_ID output:

> nodejs@1.0.0 start /usr/src/app
> node server.js

Running on http://0.0.0.0:32000

How can I avoid this issue?
Thanks in advance!

A: As I can see from kubectl describe pod command output, your Container inside the Pod has been already completed with exit code 0 (@4c74356b41 mentioned about it in the comments).  Reason: Completed, which states about successful completion without any errors/problems. However the life cycle of the Pod was very short, therefore Kubernetes continuously schedules new Pods but Liveness and Readiness probes are still failing on the container healthiness.
To keep the Pod running, you must specify a task (process) inside to the container for the ability of continuously running. There are lots of discussions and solutions available on how to solve that kind of issue, more hints can be found here.

A: kubectl logs command only works if the pod is up and running. If they are not, you can use the kubectl events command. It will give you some log of events and sometimes (in my experience) will give you also clues on what is going on.
kubectl get events -n <your_app_namespace> --sort-by='.metadata.creationTimestamp'

By default it does not sort the events, hence the --sort-by flag.


text:
Q: Can I use html5 Websockets with windows domain authentication? Our setup is like this: we use a coldfusion 10 server, and files are on a local intranet. Users use a domain login to access any files over https. I'm interested in using html5 websockets, but the first attempt gave me an error because no credentials were supplied. Is there a way around this? If not, is there a recommended technology for this scenario?
The user does log in on the client side. If it's possible, what I'd really like to do here is pass those credentials when making the connection to the server.

A: you should be able to supply the authentication header to your web socket server before the elevation to web socket read that and send it back in the headers for the elevation (first frame) then when the browser connects it should have the authentication it needs.
if your using a custom authentication E.G in page not authentication header you can also do this by passing any custom header to your server.
Or mandate that the first thing your web client sends is the authentication details this could be something like {username_hash}.{password_hash} if they don't close the socket to them.

A: Do not do this.
You're now responsible for sending and encrypting the authentication credentials yourself, bypassing something that already works and is tested.
Anyone can snoop on an unencrypted websocket port. Use HTTPs for an intranet, use stable solutions, don't reinvent this wheel because it tickles your fancy.
In a couple of years some colleague will have to maintain this and will have to figure out how your homebrew version works versus something that's solid like plain browser authentication.
My advice: Leave this to the browser and to well-tested coldfusion libraries.


text:
Q: pure javascript select child dom I'm learning not use jquery only pure javascript, just start and have trouble .....
how to select child dom
<div class="row-button">
    <input type="submit" />
</div>

I'm trying below code but all shows error message.
var submit_button = document.getElementsByClassName("row-button");
console.log(submit_button.nodeType); //undefined
console.log(submit_button.firstChild); // undefined
console.log(submit_button.childNodes[0]);  // TypeError: 'undefined' is not an object (evaluating 'submit_button.childNodes[0]')

or I thought maybe need to add window onload to  sure dom ready so
window.onload = function () {
    var submit_button = document.getElementsByClassName("row-button");
    console.log(submit_button.nodeType); //undefined
    console.log(submit_button.firstChild); // undefined
    console.log(submit_button.childNodes[0]);  // TypeError: 'undefined' is not an object (evaluating 'submit_button.childNodes[0]')
}

A: Pay attention: it's getElementsByClassName.
This means it returns a NodeList (an array-like object) of matching elements.
Try:
submit_button = document.querySelector(".row-button");

This will not only add support for IE8, but also return a single element, that being the first element with the desired class.

A: getElementsByClassName("row-button")

returns an array of elements of class "row-button". So to get its first (and only in your code) child, use
 var submit_button = document.getElementsByClassName("row-button")[0];


text:
Q: Python: Send Integer value over socket I'm using Python to communicate data over a TCP socket between a server and client application. I need to send a 4 bytes which represent a data sample. The initial sample is an 32-bit unsigned integer. How can I send those 4 bytes of raw data through the socket?
I want to send the data: 0x12345678 and 0xFEDCBA98
The raw data sent over the socket should be exactly that if I read it on wireshark/tcpdump/etc. I don't want each value in the 8 hex numbers to be represented as an ascii character, I want the raw data to remain intact.
Thank you

A: The main method to send binary data in Python is using the struct module.
For example, packing 3 4-byte unsigned integers is done like this
In [3]: struct.pack("III", 3, 4, 5)
Out[3]: '\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00'

Note to keep the endianess correct, using "<", ">", and so on.

A: you could use bytes(). Thats what I use to send strings over a network but you can use it for ints as well. Its usage is bytes([3])
Edit: bytes converts an int (3) to bytes. a string of bytes is represented as b'\x03'. so like your byte string: 0x12345678 would be b'\x12345678'
check the docs for more info:
https://docs.python.org/3.1/library/functions.html#bytes


text:
Q: How to read data from realm DB in react native? I followed a realm db tutorial in react native and I succeed to create, insert, delete data from DB but I have problem reading from database.
I always get same result which is not resolved and useless.
I checked my codes a lot But I cant find out my mistake.
Here is my code:
database.js
import Realm from 'realm';

export const HEART_QUEUE_SCHEMA = 'HeartQueue';

export const HeartQueueSchema = {
    name : HEART_QUEUE_SCHEMA,
    primaryKey : 'id',
    properties: {
        id : 'int', // primary key
        requestTime : {type : 'string', indexed: true}
    }
};

const databaseOptions = {
    path: 'mizWord.realm',
    schema : [HeartQueueSchema],
    schemaVersion : 0,
}

export const insertToHeartQueue =  (item) => new Promise((resolve, reject) => {
    Realm.open(databaseOptions).then(realm => {
        realm.write(()=>{
            realm.create(HEART_QUEUE_SCHEMA, item);
            resolve(item);
        })
    }).catch((error) => reject(error));
});

export const updateHeartQueue =  (item) => new Promise((resolve, reject) => {
    Realm.open(databaseOptions).then(realm => {
        realm.write(()=>{
            let updatingRow = realm.objectForPrimaryKey(HEART_QUEUE_SCHEMA, item.id);
            updatingRow.requestTime = 'hello world';
            resolve();
        })
    }).catch((error) => reject(error));
});

export const deleteHeartQueue =  (itemID) => new Promise((resolve, reject) => {
    Realm.open(databaseOptions).then(realm => {
        realm.write(()=>{
            let updatingRow = realm.objectForPrimaryKey(HEART_QUEUE_SCHEMA, itemID);
            realm.delete(updatingRow);
            resolve();
        })
    }).catch((error) => reject(error));
});

export const deleteAllHeartQueue = () => new Promise((resolve, reject) => {
    Realm.open(databaseOptions).then(realm => {
        realm.write(()=>{
            let updatingRows = realm.objects(HEART_QUEUE_SCHEMA);
            realm.delete(updatingRows);
            resolve();
        })
    }).catch((error) => reject(error));
});

export const getAllHeartQueue = () => new Promise((resolve, reject) => {
    Realm.open(databaseOptions).then(realm => {
        let allHeartsList = realm.objects(HEART_QUEUE_SCHEMA);
        resolve(allHeartsList);
    }).catch((error) => reject(error));
});

export default new Realm(databaseOptions)

and here is my app.js file

import realm from './databases';
import {insertToHeartQueue, deleteHeartQueue, deleteAllHeartQueue, getAllHeartQueue} from './databases'

export default class App extends Component {

constructor(){
  super();
  this.state = {
    data : "test",
    time : 0,
    testDB : '',
    xxxz : []
  }
}

_readDB = () => {
  getAllHeartQueue().then((allHeartsList)=>{
    console.log('data',allHeartsList);
    this.setState({
      xxxz : allHeartsList
    })
  }).catch((err)=>{
    alert(err)
  });

}

  render() {
    console.log('state', this.state.xxxz)
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.welcome}>{this.state.time}</Text>
        <View>
          <Button
            onPress={()=> this._readDB()}
            title="Ask for Data"
            color="#cc77v"
            accessibilityLabel="Learn more about this purple button"
          />
          <View>
          </View>
        </View>
      </View>
    );
  }
}

bu I always get this:
Proxy {type: "object", optional: false, Symbol(realm): 140510983537104, Symbol(id): 175, …}

A: Try to love resolve() outside the write transactions.


text:
Q: How can I get visitor ID from Piwik via JavaScript? I tried this:
var visitor_id;
    _paq.push([ function () { visitor_id = this.getVisitorId(); }]);

This are working perfect until I clear the browser cookies, once I clear the browser cookies, Piwik getVisitorId() isn't bringing the old visitor ID. Piwik is still tracking under the old visitor ID itself, I just want to retrieve it.
You can see the error on one of the client sites here: https://www.artsocket.com/

A: var visitor_id;
_paq.push([ function() { visitor_id = this.getVisitorId(); }]);

This one works for sure if cookies are enabled in the browser. It takes the visitor ID from Piwik's _pk_id cookie. It's also the recommended version to get the cookie because in this case you are not creating a new tracker object.


text:
Q: Hibernate saveOrUpdate, update needs all fields of original row I am using mysql and hibernate to insert and update rows in a table. I use saveOrUpdate call. Now, When I try to update a row in a table, I get a exception. Exception states that my column requestTime cannot be null. Obviously its true since I have setup the column property to be NotNull.
I am able to add the row. But when update it with values of 2 more columns, I get this exception.
I am assuming that when I update, I need to read the row from the table, and update the entire row. Is that true ? I was kinda hoping that hibernate saveOrUpdate would do it for me. So I have a Object that has getters for all the columns when I insert a new row. But when I update I have a Object that only has getters for the primary key and new columns.
Transaction txD;
Session session;
session = currentSession();
txD = session.beginTransaction();
session.saveOrUpdate(dataStore);
txD.commit();

Exception
749368 [Thread-2] DEBUG org.hibernate.internal.util.EntityPrinter  - com.mcruiseon.carpool.concrete.SubscribeProviderConcrete{acceptedTime=Mon Jul 30 03:39:23 UTC 2012, requestTime=null, subscriberIdentityHash=1218553253, requestIdentity=167093126, subscribedProviderHash=-284086361, isAccepted=true}
749375 [Thread-2] DEBUG org.hibernate.SQL  - update carPoolSubscribedProvider set subscriberIdentityHash=?, requestTime=?, subscribedProviderHash=?, isAccepted=?, acceptedTime=? where requestIdentity=?
749398 [Thread-2] DEBUG org.hibernate.engine.jdbc.spi.SqlExceptionHelper  - Column 'requestTime' cannot be null [n/a]
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'requestTime' cannot be null

select * from carPoolSubscribedProvider
+-----------------+------------------------+---------------------+------------------------+------------+--------------+
| requestIdentity | subscriberIdentityHash | requestTime         | subscribedProviderHash | isAccepted | acceptedTime |
+-----------------+------------------------+---------------------+------------------------+------------+--------------+
| 167093126       | -284086361             | 2012-07-27 16:13:19 | 1218553253             |          0 | NULL         |
+-----------------+------------------------+---------------------+------------------------+------------+--------------+

Edit :
| carPoolSubscribedProvider | CREATE TABLE `carPoolSubscribedProvider` (
  `requestIdentity` varchar(50) NOT NULL DEFAULT '',
  `subscriberIdentityHash` varchar(100) NOT NULL,
  `requestTime` datetime NOT NULL,
  `subscribedProviderHash` varchar(100) DEFAULT NULL,
  `isAccepted` tinyint(1) DEFAULT '0',
  `acceptedTime` datetime DEFAULT NULL,
  PRIMARY KEY (`requestIdentity`),

A: Hibernate cannot figure out how you want attribute with null value be treted. It cannot make difference between cases where:

*

*some attribute is null -> should set to null in database

*some attribute is null -> should not update such an attribute.

Setting value for attribute that was previously non-null to null means that value of attribute should be changed.
If you want to make column never be part of update statement, you can set updatable attribute to false in @Column annotation. According documentation it defines: Whether the column is included in SQL UPDATE statements generated by the persistence provider

A: If you write your table definition will be easier.
There are two case for your not null column:

*

*You have a "default value".

    create table t1
    (
        id integer not null,
        column1 char not null default 'Y',
        column2 date not null default sysdate,
        column3 varchar2(30) not null default user,
        intcol integer not null default 12
    );

if you not specify in INSERT or UPDATE this columns, oracle automatically will put default value in table.

*

*You don't have a "default value".

    create table t1
    (
        id integer not null,
        column1 char not null,
        column2 date not null ,
        column3 varchar2(30) not null,
        intcol integer default 12
    );

if you not specify in INSERT or UPDATE this columns, oracle automatically throw you an error messages.
This is theory about not null in database, let's go to Hibernate:
you can put in column annotation something like this:
 insert="false", update="false"

Then database will use a default value, but if in your table definition default is not specified then value of this field should be always be not null.
EDIT:
So I see now you have 3 columns "NOT NULL".
For column where you have a definied default 'requestIdentity' you can use a dynamic update, or dynami insert: http://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/
But for rest of them you have to put value in variable:
private Date requestTime = new Date();

private String subscriberIdentityHash = "someDefaultHashHere";

A: oUp = Updated row with null fields &
oDb = Row fetched from database at update time
public static <T> T updateChanges(T oDb, T oUp) {
    try {
        java.lang.reflect.Field[] fields = oDb.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.get(oUp) != null) {
                field.set(oDb, field.get(oUp));
            }
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return oDb;
}


text:
Q: swap columns with pandas I want to swap these two columns:
khushboo    खुशबू
khushbuu    खुशबू
khushbu खुशबू
khusbhu खुशबू
tera    तेरा
teraa   तेरा
thera   तेरा
teraaa  तेरा
badan   बदन
sulgeh  सुलगे
sulage  सुलगे
sulge   सुलगे
mehke   महके
mahake  महके

I know I can read these columns with pandas using like dataset = pd.read_csv('/file.txt', delimeter ='\t', encoding='utf-8') and even split dataset into two parts using dataset.iloc[:0] and dataset.iloc[:-1].
but how can I swap them and create a new csv or text file? I tried pd.to_csv but don't know how to pass the arguments, I always get a list in return.
I want it to look like this:
तेरा tera
तेरा terra
तेरा thera

Just want to swap these columns.

A: Let's say the first column header is khushboo and the second column header is
 खुशबू
dataset = pd.read_csv('/file.txt', delimeter ='\t', encoding='utf-8')
dataset = dataset[['खुशबू','khushboo']]
dataset.to_csv('file.csv', index=False)  #you may also have to pass `encoding='utf-8'` again.

A: Try:
dataset = pd.read_csv('/file.txt', delimeter ='\t', encoding='utf-8')
dataset = dataset[[dataset.columns[1], dataset.columns[0]]]
dataset.to_csv("file.csv", sep=" ", index=False)


text:
Q: Stop script from working if screen size is smaller than I have this small snippet of jQuery:
if (jQuery(window).innerWidth() > 568) {
    jQuery('#boardOfTrustees').masonry({
        itemSelector: '.postWrapper',
    });
}

This works fine, but I want to stop this from working, or uninitialize it on resize if the screen is smaller than a certain size.  I've tried this:
jQuery(window).smartresize(function() {
    if (jQuery(window).innerWidth() > 568) {
        jQuery('#boardOfTrustees').masonry({
            itemSelector: '.postWrapper',
        });
    }
});

.smartresize is a debounce script, it works well, but for this particular scenario, its not doing anything and the masonry script is still initialized.  How can I make first set of jQuery stop applying itself to the elements if the screen is smaller than 568 pixels but then start working again if the resize is larger than 568?

A: This would work on load. Not on resize:
if (jQuery(window).innerWidth() < 568) {
    jQuery('#boardOfTrustees').masonry({
        itemSelector: '.postWrapper',
    });
}

To make it work on resize then you would need to use the method destroy as detailed at the documentation.
$(window).resize(function () {
    if (jQuery(window).innerWidth() < 568) {
        jQuery('#boardOfTrustees').masonry('destroy');
    } else {
        jQuery('#boardOfTrustees').masonry({
            itemSelector: '.postWrapper',
        });
    }
});

A: Destroy it
else {
    jQuery('#boardOfTrustees').masonry('destroy')
}


text:
Q: How do I change the value of a boolean variable inside an if statement in SwiftUI? In this SwiftUI file, I am trying to set a @State variable to false in the if statement however I am getting an error.
Here is the code:
@State var showingTags: Bool = true

 if product_array_status_search {

                        VStack(spacing: 15) {
//HERE: showingTags = false

                                ScrollView(.vertical, showsIndicators: false) {
                                    ForEach(MarketplaceModel.filteredBusiness.filter { ($0.business_name ?? "").contains(searchText)}, id: \.self) { business in
                                        HStack {
                                                    Image("ImageHere")
                                                        .resizable()

                                            Text(business.business_name ?? "")
                                        }
                                    }
                                }
                            }
                        } else if product_array_status_tags {
                             ScrollView(.vertical, showsIndicators: false) {
                                LazyVGrid(columns: Array(repeating: GridItem(.flexible(),spacing: 10), count: 2),spacing: 20){
                                    ForEach(MarketplaceModel.product_tag_array){product in
                                        ProductView(productData: product)

                                    }
                                }
                            }
                        } else {
                             SearchPlaceholderView()
                        }

When I put in the line 'showingTags = false', I get the error: Type '()' cannot conform to 'View' (on the if statement)
I have also tried making a function that does this and calling that but I get the same error.
How can I make showingTags = false when this if statement is initialised?


text:
Q: Flask is not retrieving data from phpadmin enter image description here
I have a table in php admin under dms database. I want to display all the rows and columns from patients tables under dms table. My code is not displaying anything on my homepage except the title and heading. My code is here:
from flask import Flask, render_template
from flask_mysqldb import MySQL

app = Flask(__name__)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'hms'

mysql = MySQL(app)

@app.route('/')
def Home():
  cur = mysql.connection.cursor()
  cur.execute("SELECT * FROM patients")
  Fdata = cur.fetchall()
  cur.close()

  return render_template('home.html', data=Fdata)

if __name__ == "__main__":
  app.run(debug=True)

A: Try this:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hospital Management</title>
    <link rel="shortcut icon" href="{{url_for('static', filename = 'HM.png' )}}">

 Welcome To Hospital Management System

Title Row 0

        {% for row in data %}

{{row[0]}}

        {% endfor %}

Take a look at data use. It's using Jinja template.


text:
Q: Using multiple svg transformations at the same time. Is it possible to use use multiple transformations on the same svg ? I have a transform="translate(-186.57429,-373.01893)" already in my code but I want to reduce the size of the image to half using scale(0.5).
I haven't been able to find an answer to this, maybe bad Googling skills on my part. Any help will be appreciated. Here is the SVG code
<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   width="32.2"
   height="37"
   id="svg2"
   version="1.1"
   inkscape:version="0.48.2 r9819"
   sodipodi:docname="comment.svg">
  <defs
     id="defs4" />
  <sodipodi:namedview
     id="base"
     pagecolor="#ffffff"
     bordercolor="#666666"
     borderopacity="1.0"
     inkscape:pageopacity="0.0"
     inkscape:pageshadow="2"
     inkscape:zoom="2.8"
     inkscape:cx="51.134813"
     inkscape:cy="31.956267"
     inkscape:document-units="px"
     inkscape:current-layer="layer1"
     showgrid="false"
     inkscape:window-width="1920"
     inkscape:window-height="1147"
     inkscape:window-x="-8"
     inkscape:window-y="-8"
     inkscape:window-maximized="1"
     fit-margin-top="0"
     fit-margin-left="0"
     fit-margin-right="0"
     fit-margin-bottom="0"
     preserveAspectRatio="xMinYMin"/>

  <g
     inkscape:label="Layer 1"
     inkscape:groupmode="layer"
     id="layer1"
     transform="translate(-186.57429,-373.01893)">
    <path
       style="fill:#ececec;stroke:#ececec;stroke-width:0.70775092px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
       d="m 207.25539,445.72259 c 8.18855,-4.77517 9.49259,-8.30548 9.49259,-8.30548 0,0 -18.93579,3.54059 -24.23426,-3.35689 -5.29848,-6.89746 -8.67023,-55.71033 -1.44504,-58.3632 7.22519,-2.65288 50.58563,-4.2446 55.88411,2.12229 5.29847,6.3669 4.81679,51.99632 -0.48168,56.77149 -5.29848,4.77517 -18.5529,3.01002 -18.5529,3.01002 0,0 -7.65748,6.53005 -20.66282,8.12177 z"
       id="path2985"
       inkscape:connector-curvature="0"
       sodipodi:nodetypes="ccsssscc" />
  </g>
</svg>

A: You can just pass another transform definition for the scale:
<g transform="scale(0.5 0.5) translate(-186.57429 -373.01893)">

From the MDN docs on transform:

The transform attribute defines a list of transform definitions that
  are applied to an element and the element's children. The items in the
  transform list are separated by whitespace and/or commas, and are
  applied from right to left.

Alternatively, you can pass a transformation matrix to apply both scale and translate:
<g transform="matrix(0.5 0 0 0.5 -186.57429 -373.01893)">

How does it work? Transformation matrices have six attributes, as can be seen by examining the arguments in the above snippet - matrix(<a> <b> <c> <d> <e> <f>).
Each argument maps to a parameter of the transformation in the following manner:
<a> - scale X
<b> - skew Y
<c> - skew X
<d> - scale Y
<e> - translate X
<f> - translate Y


text:
Q: How to match ios5 max zoomlevel MKMapView in ios6 It seems that the max zoomlevel (where you see max details) is different on iOS 6; I am not able to get as close to the surface as in iOS 5.
Does anybody know a way to match the max zoomlevel of iOS 5 in iOS6?
If I set a span of delta lon/lat 0.000001, 0.000001 (which is far beyond the max zoomlimit)
I get these results back from the mapview.region.span
// ios 5: actual span after zoom 0.002747, 0.001277
// ios 6: actual span after zoom 0.003460, 0.001608

the next matchable zoomlevel supported by Google is:
// actual span after zoom 0.005493, 0.002553

That is quite a jump.

A: I had the same problem on iOS 6 and found no way to fix it.
Just installed Xcode 4.6 DP1 and tested my App with Simulator 6.1 . Max zoomlevel now seems to be (nearly) the same .

A: The following post describes the solution for iOS 7 and up:
How to get to the max zoomlevel on iOS MKMapView
It uses the MKMapCamera to determine to zoom level.


text:
Q: Bootstrap Collapse not automatically collapsing I just inserted a Bootstrap collapse into my payment view in Laravel. The Bootstrap collapses when I click on it, But I want it to be collapsed automatically.
I know I have to set this: aria-expanded="false"
But its still not working. Maybe because it has its own id like this?
href="#collapse{{ $charity->id }}"
Here is my full panel snippet:
@foreach($charities as $charity)

                    id }}" aria-expanded="false" aria-controls="collapseOne">

                                photo }}" width="75px" height="65px" alt="{{ $charity->name }}">

                                {{ $charity->name }}

id }}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">

                    {{ $charity->description }}

@endforeach

A: If you want the first panel closed on page load, remove the .in class from it.
From this -->
id }}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
To this -->
id }}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">

The collapse plugin utilizes a few classes to handle the heavy
  lifting:

*

*.collapse hides the content

*.collapse.in shows the content

*.collapsing is added when the transition starts, and removed when it finishes

See Collapse Usage in the Docs.
Example:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

              NAME

        DESC


text:
Q: WebView2 - Improving Load Times and/or Considering Alternatives I recently built a .NET WPF utility app for Windows around the MS WebView2 control, and in some ways, it has worked very nicely. The app is expected to prevent browsing other than the task at hand and is parameterized so that it can be configured, varying the URL, navigation options, visuals aspects, size, and new window behavior, allowing them to use it in many situations, and replacing IE. The only issue is slowness. It is slower than launching a new window in an already loaded browser, and it is faster than loading a full browser from scratch, but it still takes a few seconds to load. I looked at my code, and tried a little bit of optimization, converting the load process into a couple of async methods, but that saves only 0.2 seconds, with the bulk of the load time the actual site load and render.
This brings me to a few questions:

*

*Is there a way to optimize the WebView control to load faster, say by changing options?

*Are there alternative web view controls I could use to replace WebView2, and if so, could I keep the UI, or would I need to write in a different language/platform?

*I haven't written this before, but was wondering if I could reuse an existing window, and treat the app like a browser adding tabs, possibly by using something like NamePipes to send the app messages. I think I can see limitations, since WebView2 is topmost, possibly preventing me from using a tab control.

Any thoughts?

A: To improve performance, or at least the perception of it, I loaded up my app configurations first, set the view properties, and then awaited loading of the control:
Await EnsureCoreWebView2Async


text:
Q: search in txt file and every result in new file For context, this is a follow-up on search in txt file then print in new txt file with a few extra complications.
I have 2 txt files the first one is data.txt file which contains over 2000 lines, the data in it like:
alpha
hmld 573
otndgd 29
fidnt 1962

beta
jdkrshm 2
adny 14
urmekhjf 6893
...

the 2nd file is values.txt,
I want to search and print (in new txt file) for any line containing one of list of values in values.txt like
dn
hm
sf

, and the result1.txt like (with the head like "alpha"):
fidnt 1962 alpha
adny 14 beta

and the result2.txt like:
hmld 573 alpha
jdkrshm 2 beta

my system: ubuntu
best regards

A: Again, awk's your friend here:
awk '
  !values_processed {
    result[$0] = "result"FNR".txt"; next
  }
  !NF {FNR=0; next}
  FNR==1 {header=$0; next}
  {
    for (value in result)
      if (index($0, value))
        print $0, header > result[value]
  }' values.txt values_processed=1 data.txt

That's using the same approach as in the answer to your earlier question, but getting the list of values from the lines of the values.txt file into an associative array which records the name of the output file for each value based on the line number in values.txt, and looking for them in data.txt using index() instead of /regex/ matching to do a substring search.

A: I think what you want is (untested):
awk '
    NR==FNR {
        out[$1] = "result" NR ".txt"
        next
    }
    {
        for ( i=2; i<=NF; i++ ) {
            for ( str in out ) {
                if ( index($i,str) ) {
                    print $i, $1 > out[str]
                }
            }
        }
    }
' values.txt RS='' FS='\n' data.txt

That could exceed a "too many open files" threshold if values.txt is large. If that's an issue let us know.


text:
Q: How to order entries from a many2one field? So i have a field called Shipments, it's a many2one field. When you click it,  it shows lots of shipment dates and  the first entries are shipments from 2016.
Is there any way i can order them somehow that when i click there first entries will be  2017 ?

Here is a picture, sorry i didn't manage to put it right here in the message.
I'm new in this and need some help.

A: In your 'Shipments' model add
_order = 'your_date_field DESC'

Where your_date_field is the displayed date.


text:
Q: Stored procedure to delete duplicate rows I need help to fix my problem:
create procedure dbo.spDelDdup
    (@field1 nvarchar(50)= null,
     @field2 varchar(50),
     @tblName varchar(50))
as
BEGIN
    WITH CTE (@field1, @field2, Duplicate_Record_Count) AS
    (
        SELECT
            @field1, @field2,
            ROW_NUMBER() OVER(PARTITION BY @field1, @field2 ORDER BY @field1) AS Duplicate_Record_Count
        FROM
            @tblName
    )
    DELETE FROM CTE
    WHERE Duplicate_Record_Count > 1
END

I get an error:

Msg 102, Level 15, State 1, Procedure spDelDdup, Line 91
  Incorrect syntax near '@field1'.

Would be nice to fix my problem

A: You need to use Dynamic SQL as below:
You have also declared @field1 as optional parameter which you need to manage it, however it is a bit strange. But if this is exactly what you want, please leave a comment, so that I will update my answer based on it.
create procedure dbo.spDelDdup
(@field1 nvarchar(50)= null,
@field2 varchar(50),
@tblName varchar(50))
as
BEGIN
Declare @q AS Nvarchar(max)
Set @q = N'WITH CTE ('+@field1+', '+@field2+', Duplicate_Record_Count)
AS
(
    SELECT '+@field1+','+@field2+',
    ROW_NUMBER() OVER(PARTITION BY '+@field1+','+@field2+' ORDER BY '+@field1+') AS Duplicate_Record_Count
    FROM '+@tblName+'
)
DELETE
FROM CTE
WHERE Duplicate_Record_Count > 1'

EXEC(@q);

END

You can also use sp_executesql too.


text:
Q: strcpy() and arrays of strings I need to store the input from a user into an array of strings.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char *history[10] = {0};

int main (void) {

    char input[256];

    input = "input";

    strcpy(history[0], input);

    return (EXIT_SUCCESS);

}

Running it on the terminal I get a Segmentation Fault and in NetBeans I get main.c:11: error: incompatible types in assignment. I also tried to shift all the history to store the newest input into the first position (history[0]).
history[9] = history[8];
history[8] = history[7];
history[7] = history[6];
history[6] = history[5];
history[5] = history[4];
history[4] = history[3];
history[3] = history[2];
history[2] = history[1];
history[1] = history[0];
history[0] = input;

But this causes output like this.
If input is "input"
History 0: input
History 1: null
etc.
If then input is "new"
History 0: new
History 1: new
History 2: null
etc.
Each time a new input is entered the pointers to the string shift but it causes only the newest value to be saved in the history array.

A: You need to allocate space for the string.  This can be done several ways, the two leading contenders look like:
char history[10][100];

and
char *history[10];
for (j = 0;  j < 10;  ++j)
    history [j] = malloc (100);

The first statically allocates ten character buffers at 100 characters each.  The second, as you wrote it, statically allocates ten pointers to characters.  By filling in the pointer with dynamically allocated memory (which could each be arbitrary lengths), there is memory to read the string later.

A: strcpy() does not allocate new memory area for the string, it only copies data from one buffer to another. You need to allocate new buffers using strdup() or create the array pre-allocated (char history[10][100];). In this case, do not try to move pointers and use strcpy to copy the data.

A: main.c:11: error: incompatible types in assignment
(Code: input = "input";)

This happens because you try to make the array 'input' point to the string "input". This is not possible, since the array is a const pointer (i.e. the value it points to can not change).
The correct way to do what you are trying is:
strcpy(input,"input");

Of course this is a minor problem, the major problem has already been posted twice. Just wanted to point it out.
Btw I don't know how you even compile this when running it on the terminal. Don't you get an error? Maybe just a warning? Try compiling with -Wall -pedantic


text:
Q: Trigger on update to prevent update when isedit != 1 I have a table:
ID NAME isedit
1  jon   0
2  smit  1
3  eve   0

I need to create a trigger that prevents the row from being updated when isedit is NOT 1.
It must however allow me to set isedit in the first place e.g.
update base SET isedit = 0 WHERE id = @id

I tried the following:
CREATE TRIGGER dbo.onupdate
ON base
AFTER UPDATE
AS
  BEGIN
  If (SELECT isedit FROM base) NOT LIKE '1'
  Begin
    Return
  END
END

But it doesn't make much sense I think.

A: *

*Use set based logic, taking into account that Inserted can have multiple (or zero) records.

*Use rollback to undo the update when its not valid to do so.

*To allow you to set and clear isedit, because you update it as a single column update you can use the update(column) function to test for a change to that column and allow it to pass.

    create trigger dbo.onupdate
    on base
    after update
    as
    begin
      set nocount on;

      if not update(isedit) and exists (
        select 1
        from Inserted I
        where isedit != 1
      ) begin
        rollback;
      end;
    end

A: Please try this logic.
When you trying to update something basically insert and delete operation will get perform in SQL.
So, when you perform update it deletes your original row and keeps it under the logical table of the name 'deleted' and inserts a new row from the logical table of the name 'inserted'.
in this way you can fetch the value from the table 'deleted' and identify the value of the column isEdit != 1 then it will throw an error with rollback transaction.
Create TRIGGER [dbo].onupdate
ON [dbo].base
FOR UPDATE
AS
    IF EXISTS(SELECT NULL FROM deleted where isEdit <> 1)
    BEGIN
        RAISERROR('You can not update when isEdit value is 1', 16, 1)
        ROLLBACK TRAN
    END


text:
Q: SignalR - sending push notification to a specific user I'm working on a PoC for a notification engine. I'm able to successfully connect and call Hub functions from JS, but I can't seem to get push notifications to work. I'm getting an Object reference not set to an instance of an object error.
Triggering class
// I was able to confirm that the connectionIds are valid
   public void HandleEvent(NewNotificationEvent eventMessage)
   {
        // _connections handles connectionids of a user
        // multiple connection ids to handle multiple open tabs
        var connectionIds = _connections.GetConnectionsByUser(eventMessage.Notification.UserId);

        foreach(var connectionId in connectionIds)
        {
            // a client is returned, but aside from the connectionid, all the properties are either null or empty
            var client = _notificationHub.Clients.Client(connectionId);

            ///// ERROR HAPPENS HERE
            ///// I'm guessing NewNotification() isn't defined somewhere, but I don't know where.
            client.NewNotification("Hello");
        }
    }

View.cshtml
    var notificationHub = $.connection.NotificationHub;
    $.connection.hub.qs="userId=@userId"

    // Initialization
    $.connection.hub.start().done(function () {
        // get count unread notification count
        notificationHub.invoke("unReadNotificationsCount")
            .done((unreadCount) => {
                if (unreadCount > 0) {
                    $('#notificationBadge').html(unreadCount);
                    hasNewNotification = true;
                }
                console.log('SignalR connected!');
            })
            .fail((data) => {
                console.log('Unable to reach server');
                console.log(data);
            })
            .always(() => $('#dropdownNotificationOptions').show());

    });
    // also tried notificationHub.NewNotification()
    notificationHub.client.NewNotification = function (notification) {
        console.log(notification);
    }

NotificationHub.cs
[HubName("NotificationHub")]
public class NotificationHub : Hub
{

    //ctor
    public override Task OnConnected()
    {
        var userId = Context.QueryString["userid"];
        if(userId.IsNotNullOrEmpty())
        _connections.Add(Context.ConnectionId, Guid.Parse(userId));
        else
            _connections.Add(Context.ConnectionId, Guid.NewGuid());
        return base.OnConnected();
    }

    public override Task OnDisconnected(bool stopCalled = true)
    {
        _connections.Remove(Context.ConnectionId);
        return base.OnDisconnected(stopCalled);
    }
    public override Task OnReconnected()
    {
        Guid userId;
        if (Guid.TryParse(Context.QueryString["userid"],out userId))
        {
            //var userId = _workContext.CurrentUser.Id;
            var userConnection = _connections.GetUserByConnection(Context.ConnectionId);
            if (userConnection == null || userConnection.IsNotNullOrEmpty())
            {
                _connections.Add(Context.ConnectionId, userId);
            }
        }

        return base.OnReconnected();
    }
}

A: You should have your NewNotification before the $.connection.hub.start() such as:
var notificationHub = $.connection.NotificationHub;
$.connection.hub.qs="userId=@userId"

// Moved to define before the connection start
notificationHub.client.NewNotification = function (notification) {
    console.log(notification);
}

// Initialization
$.connection.hub.start().done(function () {
    // get count unread notification count
    notificationHub.invoke("unReadNotificationsCount")
        .done((unreadCount) => {
            if (unreadCount > 0) {
                $('#notificationBadge').html(unreadCount);
                hasNewNotification = true;
            }
            console.log('SignalR connected!');
        })
        .fail((data) => {
            console.log('Unable to reach server');
            console.log(data);
        })
        .always(() => $('#dropdownNotificationOptions').show());

});


text:
Q: How to get/create anonymous method from TRttiMethod? I want to handle a TRttiMethod as anonymous method. How could I do this?
Here is a simplified example of how I wish things to work:
Interface:
TMyClass = class
public
  // this method will be acquired via Rtti
  procedure Foo;

  // this method shall return above Foo as anonymous method
  function GetMethodAsAnonymous: TProc;
end;

Implementation:
function TMyClass.GetMethodAsAnonymous: TProc;
var
  Ctx: TRttiContext;
  RttiType: TRttiType;
  RttiMethod: TRttiMethod;
begin
  Ctx := TRttiContext.Create;
  try
    RttiType := Ctx.GetType(Self.ClassType);
    RttiMethod := RttiType.GetMethod('Foo');

    Result := ??????; // <-- I want to put RttiMethod here - but how?
  finally
    Ctx.Free;
  end;
end;

A: If you really want an anonymous method, then make an anonymous method:
Result := procedure
          begin
            RttiMethod.Invoke(Self, []);
          end;

You can also construct a simple method pointer:
var
  Method: procedure of object;

TMethod(Method).Code := RttiMethod.CodeAddress;
TMethod(Method).Data := Self;
Result := Method;

The most direct way of course doesn't use RTTI at all:
Result := Foo;


text:
Q: Shopify pop-up - adding checkout button I am trying to add a "checkout" button to the standard cart popup that occurs when a customer "adds to cart".
I am using the Shopify debut theme, but the question would apply to pretty much any Shopify theme that has a "add to cart pop-up".
It was pretty easy to add the extra code to "cart-popup.liquid", as I copied it over from "cart-template.liquid".
The button itself is showing, but it doesn't work.
The other buttons I added, checkout with Paypal and Amazon checkout all show and also work fine.
Below is the 'donor code'

    <input type="submit" name="checkout" class="cart__submit btn btn--small-wide" value="{{ 'cart.general.checkout' | t }}">

    {{ 'general.accessibility.error' | t }}  {% include 'icon-error' %}

  {%- if additional_checkout_buttons -%}

{{ content_for_additional_checkout_buttons }}

  {%- endif -%}

And this extra code shows the buttons correctly on the popup.
the buttons all work except for the main one! checkout
I think something is missing ... any suggestions?
Thanks!


text:
Q: Create multiple Debian templates in VMware with different disk sizes I have vmware infrastructure deployed, now I'm planning to create Debian templates with different disk sizes (5,20,50,100GB). Are there any vmware templates available which can be customized , or do I have to create 4 different virtual machines and do the same things with them? (install base system, fw, basic utils, etc.)
EDIT: I have Essentials Plus kit.

A: Well I'm certain that there won't be any prebuilt 'templates' setup exactly as you'd like - and certainly not the same template with varying disk sizes.
There's a number of ways you can go about this easily however;

*

*Build the smallest VM you want, use LVM and then simply duplicate the template for each larger template required, changing the disk size on each version and using LVM to 'stretch' whichever filesystems you want changed.

*If you can afford the minor IO performance hit on writes you could just make a thin-provisioned VM at its largest required size. This was VMs all think they have say 100GB each but only actually take up the real space required.

*Build them all manually - this idea sucks unless you have a scripted build, which in itself might be a cool idea to have to hand anyway - depends on your skills in this area of course.

The choice is yours.


text:
Q: java patterns to maintain consistent the indexes on data in a collection Suppose that i have a List<Person> all data structure, where Person is defined as:
class Person {
   String firstName;
   String secondName;
   boolean hasValidDrivingLicense;
}

I want to mantain a redundant List<Person> drivers that contains only the persons that have a valid driving license. I think it can also be seen as an index (well an index would contain all the items, but the purpose is very similar).
This is to avoid the need for looping through the entire list each time i need those data.
(Looping each time has the advantage that i have a single-authoritative-representation of my hasValidDrivingLicense information; abandoning this road requires: a)valid reasons b)tested alternative. The reasons depend on the specific problem; the alternative is what i'm developing here :-) )
the problem
I probably have something like this:
void add(Person p) {
   all.add(p);
   if (p.hasValidDrivingLicense()) {
       drivers.add(p);
   }
}

this often works.
Person p = new Person(); //then set fields, of course.
add(p);
p.setHasValidDrivingLicense(true);

Here it doesn't.
So the problem is: redundant information may misalign. Indexes may "broke".
solutions

*

*Person's hasValidDrivingLicense property implement Observable design pattern (or publish-subscriber, what in swing is based on the Listener interface)
If objects can change and i want my indexes to be up-to-date with their changes, i need a way to notify the index-mantainer that an object has changed a relevant property. Observable seems to be a definitive solution. No questions about it.

*Person is immutable

Problem
Immutability seems to be a viable solution, but, from the collection maintainer point of view, that is the person who writes the code:
public void add(Person p) {
     ...
}

has to ensure that p is immutable or better, that at least hasValidDrivingLicense is final.
a) this may be done through reflection (http://stackoverflow.com/questions/203475/how-do-i-identify-immutable-objects-in-java)
But doesn't this require a new performance evaluation? Doesn't reflection come at a cost?
b) are there, perhaps in design patterns or in new features of the language (eg.annotations) other solutions to this problem?

A: I guess what you want is a "live" filtered view of your all collection.
This can be done quite nicely with Google Guava and a Predicate:
http://docs.guava-libraries.googlecode.com/git-history/v11.0.2/javadoc/com/google/common/collect/Collections2.html#filter%28java.util.Collection,%20com.google.common.base.Predicate%29
On the other hand, just implementing a List personsWithDriversLicens() {...} is also easy, so perhaps Guava is overkill - depends on your needs, including performance characteristics.


text:
Q: PhpStorm - CSS files link to root of server and not project root Basically I'm trying to run a HTML file in PhpStorm on localhost.
My issue is the fact that my CSS file have paths relative to the root of the server (as they should) but in PhpStorm another folder is automatically added for the project.
In short, my CSS files link to:
localhost:port/css/style.css

While PhpStorm makes the location be:
localhost:port/projectname/css/style.css

How do I fix this?
Thanks!
-Jamie

A: If you like to change the default web path on built-in web server, you have to re-configure the server by editing your system hosts file accordingly - see http://youtrack.jetbrains.com/issue/WEB-8988#comment=27-577559.


text: Q: How to connect AWS instance to a VPN and still be able to access it? I want to connect my AWS EC2 Linux server to a VPN via PPTP. The problem is if I do that I immediatelly lose connection to the server. And I won't be able to connect to it unless I restart. Is there a way for me to connect the server to VPN while still be able to access it through SSH?


text:
Q: Shell script menu option I need to create a script with different menu options. One of them is to create a file containing

*

*who is logged in

*disk usage

*running processes

The file should be date stamped and saved to a directory.
I'm new to Linux so I'm trying to figure this out. So far I know that to stamp a file I can use (date"+%Y.%m.%d"), to show who is logged in I can use the who command, to show disk space is df -h, running processes ps -aux and to create a file is touch.
How do I put these together to create this menu option?
Update:
This is what i created and it works! However it doesn't save to the log_dir directory. It just saves it to home directory
filename=log_file-$(date +%Y.%m.%d)
touch $filename
{ who; df -h; ps -aux; } > $HOME/$log_dir/$filename

I tried a different option like this but i gives me an error message "permission denied"

filename=log_file-$(date +%Y.%m.%d)
touch $filename
{ who; df -h; ps -aux; } > $log_dir/$filename

What's going wrong?
Thank you for all the help! Much appreciated

A: In general, to create a new file with the output of a command, you redirect with >.  So cmd > path puts the output of cmd into path.  To add the output of multiple commands into a file, you have several options.  Two commonly used approaches are:
{ who; df -h; ps -aux; } > /p/a/t/h-$(date +%Y.%m.%d)

or:
output=output-$(date +%Y.%m.%d)
who > "$output"
df -h >> "$output"
ps -aux >> "$output"

A third popular choice is to use exec to redirect all output of the script to the file.  For example:
exec > output-file
who
df -h
ps -aux

This cause all output of the script to go to the output-file unless redirected again, and this sometimes causes some confusion.  It is easy to save/restore the output, and you will often see:
exec 3>&1 > output
cmd
cmd2
exec >&3

A: Put this in the function you called for that menu option:
#!/bin/bash

# Creating `newFile` using touch command
fileName=newFile-$(date +%Y.%m.%d)
touch $fileName

# Who is logged in
# Double gt in line 9 means appending the output at the end of the file
echo "-------Who is logged in----------" >> $fileName
echo "$(who)" >> $fileName

# Disk usage
echo "-------Disk Usage----------" >> $fileName
echo "$(df -h)" >> $fileName

# Running processes
echo "-------Running Processes----------" >> $fileName
echo "$(ps -aux)" >> $fileName


text:
Q: A good VML tutorial / reference Has anybody here come across a good tutorial or a reference on VML?

A: How about The W3C's official tutorial? It get's really in-depth (no joke, it's 90.96 KB (not counting images))  and it can be your complete reference.

A: Microsoft's VML Reference is here.
Lucas is right, the submission to the W3C is good too.


text:
Q: Cochran's Q but for more than two outcomes Formal problem
I have a random variable $X$ that takes (unordered) discrete values $i\in [0, 2]\subset\mathbb N$ (there is no order here, I just don't know how to write it neater) that is measured $t \in [0, 3] \subset\mathbb N$ times. I can denote the true pmf. of $X$ as $\rho(t, i)$. Measurements are not independent, i.e., $\text{Cov}[\rho(t_1, i), \rho(t_2,i)] \neq 0$ for any pair $(t_1, t_2)$.
I have an estimator $f(t,i)$ that predicts/approximates $\rho$ (essentially a table of a-priori odds) and a set of $N$ observations of $X$ at different levels of $t$. From these observations I can construct the natural estimator $\hat\rho(t,i) = x_{i,t}/N$ where $x_{i,t}$ denotes the number of times $X$ took the value $i$ at time $t$.
How can I evaluate $f$ in terms of $\hat\rho$?

Less mathy formulation
Less formally, I have a set of $N=360$ sequences of repeated measurements (repeated $t=4$ times) of a categorical variable with $i=3$ levels. I also have a hypothesized distribution $f$ for these measurements (table of odds), and I want to test this distribution $f$. What is the appropriate test to use?
I know about McNemar's test, but that one only applies to outcomes with two levels (I have more than two). Similar Cochran's Q also needs a binary outcome variable. $\chi^2$ is out as well, due to repeated measurements. This exhausts my knowledge of parameterized tests involving categorical outcomes, so I am curious what I should be doing instead.

My poor-man's solutions
I thought up two approaches to this problem, but they are courtesy of me and - since I'm actually not a mathematician - come without warranty of any kind including, but not limited to the warranty of fitness for a particular purpose. They are likely good for nothing, and I am too naive to see it.
The first test takes a subjectivist approach. I can compute the KL-divergence $D_{KL}(\hat\rho||f)$ and come up with alternative estimators, e.g., a uniform estimator $\hat\rho_\text{uniform}(t,i) = 1/i_\text{max}$, for which I can also compute $D_{KL}$. I can then treat the divergence as a fit index - lower is better - and potentially consider others, e.g. a Gini coefficient. With this I can do a "standard" model comparison. This sounds similar what people in variational inference do (? not sure).
The second test would be to bootstrap the dataset and use this to compute a $.95$-confidence bound for each $\hat\rho(t,i)$. I can then check if $f$ lies within this bound, and if not reject it as a poor estimator.
I can also combine the two, and do a bootstrap to compute the median $D_{KL}(\hat\rho || f)$, which might make the first approach more convincing?
But as I said above, likely both approaches won't do me any good, and I am simply too inexperienced to see it. - As you can see, I feel a little lost and would appreciate guidance.

Data
As per kjetil's comment, I will try to add more context here as well as the data.
The hypothesized distribution $f$ over levels $i$ of the random variable $X$ at different times $t$ takes the following form.

$t$
$t=0$
$t=2$
$t=2$
$t=3$

$i$

$i=1$
.33
.225
.25
.1

$i=2$
.47
.55
.65
.8

$i=3$
.2
.225
.1
.1

The frequency of occurence of observations at different levels of $t$ looks like this (based on $N=360$ replications):

$t$
$t=0$
$t=2$
$t=2$
$t=3$

$i$

$i=1$
130
41
105
142

$i=2$
150
253
170
141

$i=3$
80
66
85
77

Background
The data comes from an experiment, where humans (participants) watch a video of a robot going about its business. The objective for participants is to guess the robot's intent. The video is paused $t=4$ times and each time participants are asked to guess the robot's intent by choosing one of $i=3$ multiple-choice options. The true intent is revealed at the end of the video.
I can assume that the data from different participants is iid. Intuitively, you'd think that it matters who watched/rated the video, but - as it turns out - none of the commonly (and not so commonly) assumed confounds show any association with participant's guesses. The only one that seems to matter is level of English language proficiency; presumably, because you don't know what to do if you can't read the instructions. (The data on confounds is so boring, in fact, that I initially thought my plotting scripts were broken.)
The hypothesized distribution $f$ comes from prior work on the topic, i.e., a researcher has derived a clever model of this is how people's belief evolves when they watch a robot going about its business. It's a fairly complex model involving the way the robot behaves. At this stage, I treat it like a black box (even though it isn't, it's just kinematics and some non-linear math) and simply look at the output of said model for that one behavior that is shown in the video. This yields my hypothesized distribution $f$.
I'm not sure if I can trust this model (and its implied distribution $f$), so I want to use the data I collected to verify (or reject) the model.


text:
Q: How to deep copy a hashmap when working with multiple threads In my application I have two threads. Thread 1 is transferring data to Thread 2. After the data is transferred the data in thread 1 is cleared within thread 2. Thread 1 goes on its merry way placing more data in the HashMap as it comes in to be transferred to Thread 2 later. In the meantime, Thread 2 does what it needs to do with the data. The code I have below is the part in thread 2 where that data transfer between threads happens. The entire application works just fine, but my questions is, is there a better way to make this copy of the thread 1 data for thread 2 without using the keyword new to create a whole new object?
I figure doing this might cause more garbage collections to occur? Should I not worry about this?
synchronized(this){
    // Make a copy of the data map then clear it.
    cachedData = new HashMap<String,ArrayList<Float>>(data);
    data.clear();
}

A: Why not just:
    synchronized(this){
        cachedData = data;
        data = new HashMap<String,ArrayList<Float>>();
    }

This is similar to what you have, but involves no copying of the data.
I wouldn't worry about the new too much (not unless you can prove through profiling that it's a problem).

A: So if you are accessing this data HashMap from multiple threads then you will have to have a synchronized block on every access.  Just because you are grabbing a cached copy here does not mean that other threads get to use the data without synchronization.
If you want to have concurrent usage of HashMap without having to synchronize around each usage then you should be using a ConcurrentHashMap.

The entire application works just fine, but my questions is, is there a better way to make this copy of the thread 1 data for thread 2 without using the keyword new to create a whole new object?

Taking into account the cautions I mentioned above, if you want to take a snapshot of a HashMap so you can work with the contents in a specific thread then the pattern you mention is fine and is often used.  This pattern is also used when you need to iterate through a Collection and modify it inside of the loop but without doing an iterator.remove().
If you just need the keys or the values then make sure to take a copy of the data.keySet() or data.values() instead.


text:
Q: How to trigger the Dark Wanderer's three secrets in this week's tavern brawl? The Dark Wanderer in this week's Tavern Brawl starts the game with three secrets. I played a Annoyotron, triggering one of the secrets (Play a minion with Taunt - changes all minions' attacks to 1).
What are the other two secrets' triggers and effects? I am given to understand that triggering all three secrets results in nothing interesting happening at all, certainly not a secret cow level.

A: There are a total of 10 possible secrets, 3 of which are randomly chosen each game.
Those are:

*

*Visions of the Amazon - Secret: When your opponent summons a minion
with Battlecry, Summon a Mirror Image for both players.

*Visions of
the Assassin - Secret: When your opponent summons a minion with
Stealth, All minions equip a dagger.

*Visions of the Barbarian -
Secret: When your opponent summons a minion with Charge, THUNDER
FURY!

*Visions of the Crusader - Secret: When your opponent summons a
minion with Taunt, change all minions' attacks to 1.

*Visions of the
Necromancer - Secret: When your opponent summons a minion with
Deathrattle, destroy it.

*Visions of the Sorcerer - Secret: When your
opponent summons a minion with Spell Damage, Summon 2 Guardians.

*Visions of Fate - Secret: When your opponent takes lethal damage...
save him.

*Visions of Hate - Secret: When both heroes have 15 or less
Health, BRAWL!

*Visions of Valor - Secret: When your opponent summons
a Legendary minion, give all minions Windfury.

*Visions of Knowledge -
Secret: When your opponent's hand has 9 or more cards, reduce the
cost of all cards in both hands to (1).

Source: http://www.hearthpwn.com/news/2134-the-dark-wanderer-is-this-weeks-tavern-brawl-and


text:
Q: Deadlock - how does it happen in this example? can anyone explain:

*

*why do we  get a deadlock?

*how can Gaston enter function bow before Alphonse exit that function? (it should return from function bowBack() in order to exit the function bow() - or)?

This is the output I get - and then program is stuck!

Alphonse: Gaston  has bowed to me!
Gaston: Alphonse  has bowed to me!

public class Deadlock {
    static class Friend {
        private final String name;
        public Friend(String name) {
            this.name = name;
        }
        public String getName() {
            return this.name;
        }
        public synchronized void bow(Friend bower) {
            System.out.format("%s: %s"
                + "  has bowed to me!%n",
                this.name, bower.getName());
            bower.bowBack(this);
        }
        public synchronized void bowBack(Friend bower) {
            System.out.format("%s: %s"
                + " has bowed back to me!%n",
                this.name, bower.getName());
        }
    }

    public static void main(String[] args) {
        final Friend alphonse = new Friend("Alphonse");
        final Friend gaston = new Friend("Gaston");

        new Thread(new Runnable() {
            public void run() { alphonse.bow(gaston); }
        }).start();
        new Thread(new Runnable() {
            public void run() { gaston.bow(alphonse); }
        }).start();
    }
}

A: Thread 1:
alphonse instance gets locked from alphonse.bow(gaston); which prints a line and then calls gaston.bowBack() (but gaston is locked from Thread 2 due to synchronized bow() instance called on it below)
Thread 2:
gaston instance gets locked from gaston.bow(alphonse); which prints a line and then calls alphonse.bowBack()(but alphonse is locked from Thread 1 due to synchronized bow() instance called on it)
So they're both waiting for the release and cannot exit bow() method, hence the Deadlock

A: First of all, the usage of synchronized is wrong. The oracle tutorial nicely states:

First, it is not possible for two invocations of synchronized methods on the same object to interleave.

As explained by the other answer: the code shown in the example does not use a "common lock" (synchronized methods on two different objects do not affect the "other" method call).
Beyond that: as soon as you remove those System.out.format() calls - your program can (will most often) not run into a deadlock.
Or: put a println() in your main before you start the threads - again, the program will not deadlock.
In other words: printing to the console is extremely time consuming. Therefore this affects the timing of your threads dramatically! What happens here is that most of the time is spent for those console output actions. See here for a similar question that even uses the same names ;-)

A: What happens in your example:

*

*Thread Alphonse is acquiring the lock to Alphonse by entering the function bow.

*Thread Gaston is acquiring the lock to Gaston by entering the function bow.

*Thread Alphonse is requesting the lock to Gaston to enter the function bowBack but that lock is currently held by Thread Gaston, so Alphonse is forced to wait.

*Thread Gaston is requesting the lock to Alphonse to enter the function bowBack but that lock is currently held by Thread Alphonse, so Gaston is forced to wait.
Dead-lock.
Why this is happening:
A synchronized function is syntactic sugar for synchronized(this) { ... } So the class above could also be written like this:
public void bow(Friend bower) {
    synchronized (this) {
        System.out.format("%s: %s has bowed to me!%n", this.name, bower.getName());
        bower.bowBack(this);
    }
}

public void bowBack(Friend bower) {
    synchronized (this) {
        System.out.format("%s: %s has bowed back to me!%n", this.name, bower.getName());
    }
}

this in this example is however the instance of the class, so each instance has it's individual lock. If you want to lock on the same object in all instances of a class, you need to lock on a static object like this:
protected static final Object STATIC_LOCK = new Object();

public void bow(Friend bower) {
    synchronized (STATIC_LOCK) {
        System.out.format("%s: %s has bowed to me!%n", this.name, bower.getName());
        bower.bowBack(this);
    }
}

public void bowBack(Friend bower) {
    synchronized (STATIC_LOCK) {
        System.out.format("%s: %s has bowed back to me!%n", this.name, bower.getName());
    }
}

Since this LOCK object is static, both threads will now lock on the same object, and therefore correctly lock out each other. Notice the keyword final which is strongly recommended in this case, because otherwise what synchronized locks on could change during execution (by bugs or oversights in your code), which would put you back into the dead-lock situation for the exact same reason as above.

A: The synchronized block / method is synchronized to this, that is the object instance the block / method is called. (For static "object instance" is to be replaced with "class instance".)
That is your 2 objects get synchronized to themselves, not a common object.
Try something like this:
public class Deadlock {
   static class Friend {
      private final String name;
      public Friend(String name) {
         this.name = name;
      }
      public String getName() {
         return this.name;
      }
      public void bow(Friend bower) {
         synchronized (getClass()) {
            System.out.format("%s: %s  has bowed to me!%n", this.name, bower.getName());
            bower.bowBack(this);
         }
      }
      public void bowBack(Friend bower) {
         synchronized (getClass()) {
            System.out.format("%s: %s has bowed back to me!%n", this.name, bower.getName());
         }
      }
   }
   public static void main(String[] args) {
      final Friend alphonse = new Friend("Alphonse");
      final Friend gaston = new Friend("Gaston");
      new Thread(new Runnable() {
         public void run() { alphonse.bow(gaston); }
      }).start();
      new Thread(new Runnable() {
         public void run() { gaston.bow(alphonse); }
      }).start();
   }
}


text:
Q: $_SESSION['myvar'] unsets upon reloading page I have a login form that submits to a simple "checklogin" file that starts a session and redirects to the index page if the "username" and "password" matches. On the index page, I have a function that redirects back to the login form page if the session id no longer matches.
I did an echo $_SESSION['sid']; on the index page and the session_id seems to have carried over just fine. However, when I reload the page, $_SESSION['sid'] is unset and is no longer assigned a value. It proceeds to redirect back to the login page.
Below is my code. Any assistance appreciated.
FILE 1 - checklogin.php
<?php
session_start();
$uid = username;
$pw = password;
if (($uid == 'username'   and $pw == 'password'))
    {
        $_SESSION['sid']=session_id();
        header("location:index.php");
        exit();
    }
?>

FILE 2 - index.php
<?php
session_start();
if ($_SESSION['sid'] !== session_id()) {
header("location:login.php");
}
?>

ADDITIONAL INFO:
The servers are running PHP 5.4. It works fine, however, when I run it on localhost via XAMPP (PHP 7). Is there a workaround?


text:
Q: storing an array of dom elements in local storage does not work. How to fix? I'm trying to store an array that holds DOM elemenst into localStorage. I can't append the elements I store in the array when storing/getting it from localStorage. But currently, my program works if I don't use localStorage, and I can append the array elements completely fine. Here's an example I just quickly wrote up which would lead to an error for me when using localStorage. What is the cause for this error?
**html**

 Store this text

**index.js**
let arr = [];
if (localStorage.length == 0) localStorage.setItem("arr", JSON.stringify(arr));
else {
   //psuedocode: Calling the imported method in "other.js"
}

**other.js**
method() {
   let temp = [];
   temp = JSON.parse(localStorage.getItem("arr"));
   temp.push(document.querySelector(".stuff");
   localStorage.setItem("arr", JSON.stringify(temp));

   const storeHere = document.querySelector(".storeHere");

   storeHere.appendChild(temp[0]); //Error, not of type Node

}

A: Put only serializable values into storage. Elements aren't serializable.
If you want to store Store this text, then store just that text. If the dynamic values include nested elements, either construct those nested elements when needed, or store the whole HTML string and set the .innerHTML of the container.
Here, the child of .stuff is only a plain single string, so just put that one string into storage.
// store string
localStorage.stuffText = document.querySelector('.stuff').textContent;

// retrieve string and put into DOM
if (localStorage.stuffText) {
  document.querySelector('.stuff').textContent = localStorage.stuffText;
  // or if you want to put it into a .storeHere element, use that selector instead
}

If you want to store an array of strings, then maybe something like
const storedArr = localStorage.arr ? JSON.parse(localStorage.arr) : [];
// store string
storedArr.push(document.querySelector('.stuff').textContent);
localStorage.stuffText = JSON.stringify(storedArr);

// retrieve string and put into DOM
if (localStorage.arr) {
  const storedArr = JSON.parse(localStorage.arr);
  for (const item of storedArr) {
    document.querySelector('.stuff').textContent = item;
  }
  // or if you want to put it into a .storeHere element, use that selector instead
}

A: HTML Element is not serializable, so the localStorage cannot store it. You need to serialize it into string before save it. I recommend using element.outerHTML with JSON.stringify .
Example code in your case with array:
// Serialize
const arr = []
// convert to string
const elementAsString = document.querySelector('div').outerHTML
// add to your current array
arr.push(elementAsString)
// use JSON.stringify to keep correct array format in localStorage
localStorage.setItem('arr', JSON.stringify(arr))

// Deserialize
const saveArr = JSON.parse(localStorage.getItem('arr'))
// we need create an empty element first
const e = document.createElement('div')
// append element to a parent before set outerHTML
document.body.append(e)
// set HTML for it
e.outerHTML = saveArr[0]

A: You just need to replace these two line and your bugs will fix.
Inside other.js method() function :-
function method () {
 //temp.push(document.querySelector(".stuff"));
 temp.push(document.querySelector(".stuff").outerHTML);

  //storeHere.appendChild(temp[0])
  storeHere.innerHTML += temp[0];
}

Explanation

*

*We cannot stringify a HTMLNode ( which is returned by the document.querySelector) because it is not a string, but we can get it as a string using its outerHTML property.

*When you push the HTMLNode in the arr and set it to localStorage as string then localStorage.getItem("arr") return "[ '[object HTMLNode]' ]" as a string which you parsed as an array. It makes temp[0] = '[object HTMLNode]', which is a string ( not the HTMLNode ), which give you the error on appending it as a child Node ( that you mentioned in the comment ).

I was a bit late in answering because something came up when I was typing the answer


text:
Q: How to define a template function that only accepts a base class with parameter T of type its subclass? It is not specific to casting. My scenario is how to define a template function that only accepts a base class for parameter T of type subclass.
template<typename T> // T must be a subclass
T* DoSomething(<I don't know> parent) // parent must be a base class
{
    // here the specified subclass of type T is produced.
    // return object of type T which is a subclass.
}

A contrived usage:
Parent* p = new Child();
Child* c = DoSomething<Child>(p);
delete p;

A: One way could be by using std::is_base_of or std::is_base_of_v in combination with a static_assert:
template<typename Derived, typename Base>
Derived* CastChecked(Base* parent)
{
    static_assert(std::is_base_of_v<Base,Derived>);

    return dynamic_cast<Derived*>(parent);
}

A: As you are not specifying a language version, I want to add the C++20 and beyond way is to use concepts. Your case is actually shown as an example on cpp reference.
For your case
#include <type_traits>

// concept
template <class D, class B>
concept Derived = std::is_base_of_v<B, D>;

template <typename D, typename B>
    requires Derived<D, B>
D* CastChecked(B* parent) {
    return dynamic_cast<D*>(parent);
}

struct Foo {};
struct Bar : Foo {};
struct Baz {};

int main() {
    auto foo{Foo{}};
    Bar* bar{&foo};

    auto const r1{CastChecked<Foo>(bar)};

    // auto const r2{CastChecked<Baz>(bar)}; fails
}

However, you don't have to roll your own concept, as there's already a concept in the standard library: std::derived_from. So you can just write:
#include <concepts>

template <typename D, typename B>
    requires std::derived_from<D, B>
D* CastChecked(B* parent) {
    return dynamic_cast<D*>(parent);
}


text:
Q: Sum between elements of a vector using indices of start and end positions I have a vector (in this case extracted from a data frame) that I would like to calculate a some sums from using a two additional vectors containing start and end indices of the data vector to be used.  For this, I am working in R.
For example, my vector to use for calculations is:
Data Vector:
[1] 1.45
[2] 1.56
[3] 1.57
[4] 1.40
[5] 3.45
[6] 1.45
[7] 1.66
[8] 2.03
[9] 1.33

Using other information in my data frame, I have calculated two other vectors containing the index positions of the above vector which I have called "start" and "stop" to denote the ranges between which I want to sum values.  For example:
Start:
[1] 1
[2] 4
[3] 7

End:
[1] 3
[2] 6
[3] 9

I would like to use these two index vectors to sum between elements 1-3, 4-6, and 7-9 in my data vector.  I'm struggling with a way to implement this across a data frame with several hundred rows.
I'm now attempting to write a function to do this, but wanted to put this up in case there is a simpler solution that I am missing.

A: Maybe there is a better solution, but I wrote some quick code that does what you want for a single vector, could rewrite some of it to calculate sums for multiple columns I am sure, if that is what you want.
 sum<-c(rep(0,length(start)))

 for (i in 1:length(start)){
     for (j in start[i]:end[i]){
        if(is.na(data[j] == FALSE)){
        sum[i]<-sum[i]+data[j]
        }
    }
 }

Edited to work with NAs.  Again probably a better way to do it (I'm not R expert either) but that should work.

A: This will work without too many checks and does not cover N/As (hopefully you will have filtered them out from the data.frame the number vector came from).
subSums <- function(vector, start_vector, end_vector){
  if (length(start_vector) != length(end_vector)){
    print("Start and End Point vectors are not the same length")
    return()
  }

  result <- NULL
  for (index in seq_along(start_vector)) {
    result[index] <- sum(vector[start_vector[index]:end_vector[index]])
  }

  return(result)
}

example of use:
vec<-1:20
subSums(vec, c(1,3), c(2,4))


text:
Q: scanf to string and use if with it I'm still new at programming C and I searched so much for a solution, but couldn't find one..
I'm trying to ask the user to enter the letter c or f and do the correct printf according to the letter of choice.
#include <stdio.h>
#include <conio.h>

void startScreen();
char choice[1];

int main()
{
    startScreen;
    _getch();
    return 0;
}

void startScreen()
{

    printf("Please choose c or f\n");
    scanf("%s", choice);
    if (choice[0] == 'f' || choice[0] == 'F')
        printf("Good choice");
    if (choice[0] == 'c' || choice[0] == 'C')
        printf("Good luck");
}

Appreciate all the help I can get, thank you!

A: Thank you Chad Estes and Ahmed Aboumalek, I combined what you both pointed at and it worked!
#include <stdio.h>
#include <conio.h>

void startScreen();

int main()
{
    startScreen();
    _getch();
    return 0;
}

void startScreen()
{
    char c;

    do
    {
        scanf_s("%c", &c);
        switch (c)
        {
        case 'f':
        case 'F':
            printf("Good choice");
            break;
        case 'c':
        case 'C':
            printf("Good luck!");
            break;
        default:
            printf("Invalid input. Try again.");
            break;
        }
    }
    while (c != 'c' && c != 'C' && c != 'f' && c != 'F');
}

A: My C is quite rusty, but I imagine the issue you're having is when you call this and input something other than 'C' or 'F'.  Looks like you need to alter your startScreen() function like so:
void startScreen()
{
    printf("Please choose c or f\n");
    do {
      scanf("%s", choice);
      switch(choice[0]) {
         case 'f':
         case 'F':
           printf("Good choice");
           break;
         case 'c':
         case 'C':
           printf("Good luck");
           break;
         default:
           printf("Invalid input. Try again.");
       }
    } while (choice[0] != 'c' && choice[0] != 'C' && choice[0] != 'f' && choice[0] != 'F');
}