text:
Q: Drag and Drop: How to get the URL of image being dropped if image is a link (not the url of the link) I have this code:
function drop(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    var imageUrl = evt.dataTransfer.getData('URL');
    alert(imageUrl);
}

FIDDLE
If you drop the  element it alerts the url of the image. So far so good.
My problem is that if you drop the  element it alerts the url of the href of  element. I want to alert the url of the  element inside the  like if you droped the image in the above example.
Is that possible?
I dont mind using Jquery or any other library. I just want to take the url of the image inside a  element.
The whole point is to drag images-links from other websites to mine and get the url of images.
To be more clear what i am trying to achieve try to drag my profile image just under this post and drop it to fiddle. It alerts http://stackoverflow.com/users/3074592/laaposto. I want http://i.stack.imgur.com/juvdV.jpg?s=32&g=1 to be alerted.
I want the solution to work on latest version of Chrome and Firefox.

A: function drop(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    var imageUrl = evt.dataTransfer.getData('text/html');
    var rex = /src="?([^"\s]+)"?\s*/;
    var url, res;
    url = rex.exec(imageUrl);
    alert(url[1]);
}

It works on Chrome and Firefox, but note that if you drag an image from Chrome to Firefox it doesn't work.

A: Using jQuery. (I'm just using it to get the "src" attribute so i think you can do without it)
I replaced:
var imageUrl = evt.dataTransfer.getData('URL');

with:
var imageUrl = evt.dataTransfer.getData('text/html');

Oh, and I replace the alert with a console.log so you'll need to open it.

A: Here's how I'd do it (only tested in Firefox):

*

*use jQuery

*analyze the dropped html-code using jQuery: search for image inside with .find()

*read src-attribute from the found image with .attr()
Here's the important part from my new drop(event) function:
// Get text/html instead of text/uri-list!
// So you get raw html that is passed even between different websites
var droppedHTML = evt.dataTransfer.getData("text/html");

// add this html to some container.
// if you skip this, the following code won't work if a single img element is dropped
var dropContext = $('
').append(droppedHTML);

// now you can read the img-url (not link-url!!) like this:
var imgURL = $(dropContext).find("img").attr('src');

A: Here is my fiddle: http://fiddle.jshell.net/ep2z5/
This works in chrome on my Mac. Basically you take the html returned, and then convert into jquery object, and since the return string is a meta tag, and an img tag, you have to take the 2nd element (number 1 in the array returned by jquery parsing) and jquery-ify that item, and then grab the src attribute.
Update: checked firefox and it isn't working there, researching now.
Update: Okay here is the newest fiddle tested in both chrome and firefox.
http://fiddle.jshell.net/ep2z5/6/
It uses recursion, which can be dangerous, but i think will work okay, as long as there isn't to many nested elements.

A:

Drage Folder

Drop Folder

Create drag-drop.js file and add following code.
var Drag = {
    obj : null,

    init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
    {
            o.onmousedown     = Drag.start;

            o.hmode                                  = bSwapHorzRef ? false : true ;
            o.vmode                                  = bSwapVertRef ? false : true ;

            o.root = oRoot && oRoot != null ? oRoot : o ;

            if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
            if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
            if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
            if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

            o.minX     = typeof minX != 'undefined' ? minX : null;
            o.minY     = typeof minY != 'undefined' ? minY : null;
            o.maxX    = typeof maxX != 'undefined' ? maxX : null;
            o.maxY    = typeof maxY != 'undefined' ? maxY : null;

            o.xMapper = fXMapper ? fXMapper : null;
            o.yMapper = fYMapper ? fYMapper : null;

            o.root.onDragStart  = new Function();
            o.root.onDragEnd    = new Function();
            o.root.onDrag                          = new Function();
    },

    start : function(e)
    {
            var o = Drag.obj = this;
            e = Drag.fixE(e);
            var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
            var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
            o.root.onDragStart(x, y);

            o.lastMouseX          = e.clientX;
            o.lastMouseY          = e.clientY;

            if (o.hmode) {
                    if (o.minX != null)      o.minMouseX           = e.clientX - x + o.minX;
                    if (o.maxX != null)    o.maxMouseX         = o.minMouseX + o.maxX - o.minX;
            } else {
                    if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
                    if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
            }

            if (o.vmode) {
                    if (o.minY != null)     o.minMouseY          = e.clientY - y + o.minY;
                    if (o.maxY != null)    o.maxMouseY         = o.minMouseY + o.maxY - o.minY;
            } else {
                    if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
                    if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
            }

            document.onmousemove        = Drag.drag;
            document.onmouseup             = Drag.end;

            return false;
    },

    drag : function(e)
    {
            e = Drag.fixE(e);
            var o = Drag.obj;

            var ey      = e.clientY;
            var ex      = e.clientX;
            var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
            var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
            var nx, ny;

            if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
            if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
            if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
            if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

            nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
            ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

            if (o.xMapper)                         nx = o.xMapper(y)
            else if (o.yMapper)  ny = o.yMapper(x)

            Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
            Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
            Drag.obj.lastMouseX               = ex;
            Drag.obj.lastMouseY               = ey;

            Drag.obj.root.onDrag(nx, ny);
            return false;
    },

    end : function()
    {
            document.onmousemove = null;
            document.onmouseup   = null;
            Drag.obj.root.onDragEnd(       parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]),
                                                                    parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
            Drag.obj = null;
    },

    fixE : function(e)
    {
            if (typeof e == 'undefined') e = window.event;
            if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
            if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
            return e;
    }
};

A: This problem can be solved using only Javascript.
Piece of Code:
// onDrop
function onDrop(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    var imageUrl = evt.dataTransfer.getData("URL");
    var links = getAllElementsWith("a", "href", imageUrl);
    var image;
    // console.log(links, evt);

    if(links.length){
        image = links[0].getElementsByTagName("img");
        if(image.length)
            imageUrl = image[0].getAttribute("src");
        else
            imageUrl = "#no-image";
    }

    alert(imageUrl);
};

JSFiddle Here: http://jsfiddle.net/hayatbiralem/7pr7N/5/
Thanks to kevinfahy
for getAllElementsWithAttribute function.

A: I have added a little correction to @Frederike answer:
  function drop(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    var droppedObject = $('
').html(evt.dataTransfer.getData("text/html"));
    var image = droppedObject.find("img");
    if(image != undefined && image.length > 0){
      console.log(image);
      var imageUrl = image.attr('src');
      if(imageUrl != undefined)
        console.log(imageUrl);
    } else {
      console.log("image undefined");
    }
  }

Example on JSFiddle: https://jsfiddle.net/0joker01/xdL6gqk0/

A: event.dataTransfer.getData('text/html') can be used to get the HTML of the dropped image. DOMParser can be used to read the source of the image afterward, which works both for images on the page and images dropped from other sites. DOMParser avoids the possibility of executing any scripts in the HTML that would result from directly appending the HTML to a newly created element.
Demo:

let dropArea = document.getElementById('dropArea');
dropArea.addEventListener('dragover', e => e.preventDefault());
dropArea.addEventListener('drop', function(e) {
  e.preventDefault();
  let html = e.dataTransfer.getData('text/html');
  let src = new DOMParser().parseFromString(html, "text/html")
              .querySelector('img').src;
  console.log(src);
});

Drop here

A: Add an event listener to the window for the "drag" event. Set a global variable to the event source (I.E. The element in the page being dragged.) Then on "drop" you grab that the information you require from the element.
var dropbox = document.getElementById('dropbox'),
    DragElement;

window.addEventListener('drag', handleClicks, false);

dropbox.addEventListener('dragenter', noopHandler, false);
dropbox.addEventListener('dragexit', noopHandler, false);
dropbox.addEventListener('dragover', noopHandler, false);
dropbox.addEventListener('drop', drop, false);

function handleClicks(evt){
    DragElement = evt.srcElement;
}

function noopHandler(evt) {
    evt.stopPropagation();
    evt.preventDefault();
}
function drop(evt) {
    console.log(evt);
    evt.stopPropagation();
    evt.preventDefault();
    var imageUrl = DragElement.src;
    alert(imageUrl);
}

http://fiddle.jshell.net/exx4e/


text:
Q: How can I create a record with an ID from a variable? I'm trying to create a record in SurrealQL with a variable:
CREATE student:$name SET age = 38

but for some reason the syntax isn't allowed. Any idea why this is the case?

A: CREATE type::thing("student", $name) SET age 38

https://surrealdb.com/docs/surrealql/functions/type#thing covers this, but you can use a type function to create a record link, which in your case can be passed to CREATE.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Relay not switching correctly, controlled from ATtiny85, output to motor I have an ATtiny85 switching an NPN transistor, which will in turn switch on a relay that will run a motor. Everything is run off a 3.7V 18650 Li-Ion battery, but I have since moved over to a variable power supply with same problem:

Without the motor, the relay switches fine, ATtiny85 will switch the relay on for one second, and then off for one second, and repeat, and the oscilloscope (connected to relay output and GND) and clicks are showing correct behaviour for the relay.
When I connect the motor, the relay still clicks, but the oscilloscope is showing zero voltage. Seems like relay tries to switch, but doesn't. I connected an LED to Pin0 of the ATtiny85, and it flashes instead of staying on for one second and going off for 2 second.
Seems to me that the problem could be:

*

*The ATtiny85 is resetting because not enough current going through. This doesn't make sense because I've switched over to a bench power supply and same thing happens, voltage is still the same.

*Some sort of feedback from the motor? The motor runs fine if I connect it directly to battery so I don't think power is an issue.

Some additional information:

*

*Relay switches on for 1 second then off for 1 second. I am not doing PWM, but just have this on/off behaviour for testing.

*This is the motor: 3V-12V water pump motor

*Power supply is set at 3.9V with 2A current available. Increasing it to something like 5V still doesn't work.

EDIT: Although the answers all helped me figure out my problem, I chose the one that helped me the most. Found that it wasn't back-emf or your standard type of decoupling required. The motor was dropping the voltage down hard and no capacitor was going to fix it (already had these in place), although these are common issues.
More findings here

A: I have two suggestions for you:
1) check to make sure that the relay is able to handle the current the DC motor is pulling.
2) use the variable power supply to run the control circuit, and the battery to run the motor with relay. if this proves to be working, you can then work your way back to re-integrate the motor back to your system.

A: Depending on how the motor is wound, it could be giving an inductive kick onto the power supply rails as the brushes disconnect from the coils. This is why you see sparks at the brushes of a spinning motor. This kick could glitch the chip and cause exactly the kind of stuff you are seeing (relaTo remedy this, you can try putting another flyback diode across the motor leads just like the one across the relay coil.
It is also good practice to use a decoupling capacitor across the leads of the chips. This will filter any sudden power spikes or dips that could otherwise cause the chip to glitch. Try putting a ~1uF capacitor physically as close to the leads of the chip as possible.

A: Something like this:

simulate this circuit – Schematic created using CircuitLab
Are you actually PWM'ing?
Why relay?
Why not FET?


text:
Q: Need help identifying subject in sentence with a conjunction Currently, I am involved in a disagreement as to interpreting the grammatical meaning of the following sentence:
"Restores 10% of Att as HP in battle."
Given that "Att" and "HP" are nouns (with numerical values, if that makes a difference), from a purely grammatical standpoint does this sentence mean that either:

*

*10% of "Att" is restored

*10% of "HP" is restored

*Neither, something different, or is not grammatically correct

Edit for clarity:

The sentence represents the effect of an item in an MMORPG. "Att" is a
  numerical value for "Attack Power" and "HP" is a different numerical
  value for "Health Points." We are in agreement that the intended
  meaning of the sentence is that "HP" is restored by an amount equal to
  10% of "Att." The dispute is regarding whether the given sentence is a
  grammatically correct way of conveying the given meaning. Under
  assumptions #1 or #3 it would not be correct while under assumption #2
  it would be correct. Hopefully this helps.

A: It seems to me that in the light of your explanation, your statement that

We are in agreement that the intended meaning of the sentence is that "HP" is restored by an amount equal to 10% of "Att."

represents a justifiable interpretation. In the context of the explanation, I also find no problem with the wording of your query sentence, despite its terseness.
It is also evident that neither of your propositions 1) or 2) means the same as what you and your fellow gamers have agreed the query sentence means; but that meaning is covered (vaguely) by the 'something different' component of 3).

A: "restored" is not the right word.  . There is no reason to believe HP is "restored"; that would entail returning it to its prior value, which I presume is unknown (that is, it could vary by situation). What if HP's prior value were lower? You would have to REDUCE it in order to "restore" it. What if increasing HP by 10% of Att brought HP to a higher vale than it had ever been? That would not be "restoring" either!  And "replenish" would involve similar conundrums.
So it should say that HP is "increased" or "augmented" by 10% of the value of Att.

A: If the HP increases by 10% of the current ATT value whilst the ATT value remains the same: then the statement is incorrect.
I understand it to mean, 10% of the current ATT value will be deducted and given as HP.
If the former is what actually happens in game, then it should say;
Restores HP by 10% of ATT value.


text:
Q: replacing values in 2d arrays in c I have searched through this site and found some very helpful information up to this point but I struggle in rewriting elements in arrays or finding info on this site on how to go about doing it. This is the part of the code I'm stuck on.
int game_board[3][3];
int row, col, i = 1;
for (row = 0; row < 3; row++)
    for (col = 0; col < 3; col++)
        game_board[row][col] = i++;

for (row = 0; row < 3; row++)
{
    for (col = 0; col < 3; col++)

        printf("%d\t", game_board[row][col]);
    printf("\n");
}
int spot1 = game_board[0][0];
int spot2 = game_board[0][1];
int spot3 = game_board[0][2];
int spot4 = game_board[1][0];
int spot5 = game_board[1][1];
int spot6 = game_board[1][2];
int spot7 = game_board[2][0];
int spot8 = game_board[2][1];
int spot9 = game_board[2][2];

printf("enter the number of the square you want to place an x in\n");
scanf("%d", );//what goes here?

printf("%d", game_board[row][col]);
printf("\n");`

This gives me the numbers 1-9 but I dont know the next step to change the value in the array. Any direction would be appreciated.

A: Enter the position of the square? You just need to know the position of the square to put a x over that square.
#define CROSS -1
int i,j;
scanf("%d%d",&i,&j);
game_board[i][j]=CROSS;

So what should you do?
#define CROSS -1
int row1,col1;
printf("enter the position of the square you want to place an x in\n");
scanf("%d%d",&row1,&col1 );//what goes here?
// modify game_board[row1][col1] as you need. Assuming zero-indexing.
if(row1<3 && col1<3)
    game_board[row1][col1]=CROSS;

Note: Instead of hardcoding the magic numbers here 3, just use them as a macro. In this case it will be...
#define MAXROW 3
#define MAXCOL 3

These will help you change your code easily later.
You put checks like this ..
if(row<MAXROW && col <MAXCOL)
   // do something

The benefit is if you reconsider using a board size of 9x9 then you don't have to change all the 3's to 9's. Rather just change
#define MAXROW 9
#define MAXCOL 9

A: int r, c;

printf("enter the row number of the square you want to place an x in\n");
scanf("%d", &r);

printf("enter the column number of the square you want to place an x in\n");
scanf("%d", &c);

if (r <= row && c <= column)
    game_board[r][c] = 'x';
else
    /* error */
printf("%d\n", game_board[r][c]);


text:
Q: Database backup from jsp page I have a struts 2 (jsp) web application with MySQL database.
Is it possible to take database backup from jsp/java page?
Is it possible to restore in the same way?
Please give me some tutorials or tips..
My actual need is to give a access to admin to take back up and restore it using gui itself, without accessing MySQL from server.
Thanks in advance..

A: If you are using mySQl you can do something like
   static int BUFFER = 10485760;

public static String getData(String host, String port,    String user, String password, String db) throws Exception {

Process run = Runtime.getRuntime().exec(
           "C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump --host="  + host + " --port=" + port +
           " --user=" + user + " --password=" + password +
           " --compact --databases --add-drop-table --complete-insert --extended-insert " +
           "--skip-comments --skip-triggers "+ db);
InputStream in = run.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuffer temp = new StringBuffer();
int count;
 char[] cbuf = new char[BUFFER];

while ((count = br.read(cbuf, 0, BUFFER)) != -1)
         temp.append(cbuf, 0, count);

 br.close();
 in.close();

 return temp.toString();
}

public static void main(String[] args) {
byte[] data = BackupRestore.getData("localhost", "3306",
    "root", "", "test").getBytes();
File filedst = new File(path);
FileOutputStream dest = new FileOutputStream(filedst);
dest.write(data);
}

But i believe until you have not any compelling/fancy reason to do this better user command line tools
You can use GUI tool being shipped with MySQL,more tested and more easy to use.
String path="C:/datadump/db_backup.sql"

make sure that path C:/datadump should exist or you can provide any other path of your choice.

A: You can do this, though its probably not a good idea. MySQL logical backups are SQL, and don't require any access to server internals. You can make a backup using the documented SQL interface.

*

*You can get the list of databases, tables, views, etc. from information_schema, or from show tables, etc.

*You can get the table definitions from information_schema, or show create table

*You can get the contents of tables using select * from table_name

*etc.

Of course, you risk missing something (did you remember triggers, stored procedures, user-defined-functions, …?). Even if you aren't missing anything today, you risk missing something new tomorrow, when a new MySQL version comes out.
mysqldump should be preferred because the MySQL authors take care of remembering to add new stuff to back up to it. You could shell out to call it; its output (by default) is SQL.
Restoring a backup is fairly straight-forward; just run the SQL statements one after another.


text:
Q: jQuery one element event influence another What Im trying to achive is to show/hide one div if input field somewhere is focused. Show  works but it wont hide it. Im new to jQuery
I cant figure it out whats wrong in my code.
$(document).ready(function(){

if ($("#a").has(":focus")){
        $("#b").css("visibility","visible");}
    else {
        $("#b").css("visibility","hidden");}
});

html:

        Company

        <input id="inputcompany" name="company" class="element text medium" type="text" maxlength="255" value=""/>

        Name

        <input id="company" name="company" class="element text medium" type="text" maxlength="255" value=""/>

Sorry guys, secon li should have been with id "b".

A: The javascript code will only be executed once. It seems as if you want an event handler - code that will be executed whenever #a loses/gains focus.
$('#a').focus(function() {
  $("#b").css("visibility","visible");
}).blur(function() {
   $("#b").css("visibility","hidden");
});

A: I think that your doing it the wrong way if you want to show the next li when hovering the first one, I'll do it like that :
//For example on mouseover the #a
$('#a').on({
    mouseover:function() {
        $('#b').css("visibility","visible"); //we show the #b
    },
    //on mouseleave
    mouseleave: function() {
        if($('#a').find('input').val().length == 0) { //if nothing was entered in the first input
            $('#b').css("visibility","hidden"); //hide the #b
        }
    }
});

See a live example here.
Hope that's help.

A: Try this,
$('#a input').focus(function() {
  $("#b").css("visibility","visible");
}).blur(function() {
   $("#b").css("visibility","hidden");
});


text:
Q: OpenSSL binary distribution: meaning of the char at the end of version I am using libcurl which depends on OpenSSL thus I need to link with it too.
There are binary distributions for Windows here, but I do not understand what does the character at the end of the version stands for (packages named like: Win32 OpenSSL v1.0.1b, Win32 OpenSSL v1.0.0i, ...).
I might miss something but quick lurking through site/page gave no explanation about that.
What is the difference between them?

A: See OpenSSL Support FAQ 8: How does the versioning scheme work?:

After the release of OpenSSL 1.0.0 the versioning scheme changed. Letter releases (e.g. 1.0.1a) can only contain bug and security fixes and no new features. Minor releases change the last number (e.g. 1.0.2) and can contain new features that retain binary compatibility. Changes to the middle number are considered major releases and neither source nor binary compatibility is guaranteed.


text:
Q: Storing and Retrieving Image Path From android application folder On Pre Created SQLite Database & Setting the image to Image View I'm currently trying to make an Simple Application Quiz, that will have an image attached to each question with 4 answers, so i have about 100++ images to store in the database
So far i can figure out how to make the questions without an image on each question trough this tutorial here  : Chuck Application Part 1
i've found out a way to store an image path is by hardcoding the path to the textfields in the SQLite Database from this links below
Saving resources path in SQLite
According to the link above, he stated that he saves the reference of the image by typing "R.drawable.picture1" to a text field inside the SQLite Database,
if it's true, is it the correct way to do so (by saving the image in drawable folders and writing the path to the text field)? if it's not then what's the correct way to do so,
how do i construct the image path (setting the setter and getter methods) for getting the field from the database?,
and how do i set the path to an imageview?
any help will be appreciated, thankyou in advance
UPDATE
so i learned from another link how to use a string for reference and i edited the string below, where  ImageI.getImage1(); refers to a row from my database that contains my image name
private void showImage() {
        String imagea = ImageI.getImage1();
        int imageResource = getResources().getIdentifier(imagea , "drawable", context.getPackageName());
        ImageView gambar = (ImageView) findViewById(R.id.imagetest);
         Drawable image = getResources().getDrawable(imageResource);
         gambar.setImageDrawable(image);
    }

but i always got a force close, where did i do wrong?
so far i've tried writing in my database row
R.Drawable.picture
Drawable/picture
picture

but nothing works....
this is my query
    public List<ImageQuestions> getImageQuestionSet(int ingroup, int numQ) {
        List<ImageQuestions> questionSet = new ArrayList<ImageQuestions>();
        Cursor c = myDataBase.rawQuery("SELECT * FROM IMAGETEST WHERE INGROUP=" + ingroup +
                " ORDER BY RANDOM() LIMIT " + numQ, null);
         while (c.moveToNext()){
                //Log.d("IMAGEQUESTIONS", "Images Found in DB: " + c.getString(1));
               ImageQuestions I = new ImageQuestions();
               I.setQuestion(c.getString(1));
               I.setImage1(c.getString(2));
               I.setAnswer(c.getString(3));
               I.setOption1(c.getString(4));
               I.setOption2(c.getString(5));
               I.setGroup(ingroup);
               questionSet.add(I);
           }
           return questionSet;
        }
}

this is my log cat
07-18 03:28:41.283: W/dalvikvm(647): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
07-18 03:28:41.293: E/AndroidRuntime(647): FATAL EXCEPTION: main
07-18 03:28:41.293: E/AndroidRuntime(647): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
07-18 03:28:41.293: E/AndroidRuntime(647):  at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
07-18 03:28:41.293: E/AndroidRuntime(647):  at java.util.ArrayList.get(ArrayList.java:311)
07-18 03:28:41.293: E/AndroidRuntime(647):  at learning.everything.quiz.GamePlayI.getNextQuestion(GamePlayI.java:113)
07-18 03:28:41.293: E/AndroidRuntime(647):  at learning.everything.BigAss.onCreate(BigAss.java:32)
07-18 03:28:41.293: E/AndroidRuntime(647):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-18 03:28:41.293: E/AndroidRuntime(647):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

i realized its caused by getting an arraylist from the database so here is my GamePlayI class
    public class GamePlayI {

    private List<ImageQuestions> questions = new ArrayList<ImageQuestions>();

    public void setQuestions(List<ImageQuestions> questions) {
        this.questions = questions;
        }

    public void addQuestions(ImageQuestions I) {
        this.questions.add(I);
    }

    public List<ImageQuestions> getQuestions() {
        return questions;
    }

    public ImageQuestions getNextQuestion() {

        //get the question
        //below is line 113\\
        ImageQuestions next = questions.get(this.getRound());
        //update the round number to the next round
        this.setRound(this.getRound()+1);
        return next;

    }

}

    public void setNumRounds(int numRounds) {
    this.numRounds = numRounds;
        }

    public int getNumRounds() {
    return numRounds;
}

A: I would only save the image name in the db and then get the resource identifier with context.getResources().getIdentifier(). Check out this similar question.


text:
Q: iterating through the hierarchy of objects - C# - linq I have an object (say A) with hierarchy as below,

obj A --> Contains list of obj B --> Contains list of obj C -->
  Contains list of obj D

Given the obj A, i need to get the list of all obj D in total, irrespective of its association with obj C and obj B. something like List<D> GetAllofD(A a)
Can you please suggest me the best way to get it done - don't want to use multiple for loops. Any better approach using linq?

A: As per @feiyun's comment, repeated application of SelectMany can be used to progressively rollup all levels of the class hierarchy:
var allDsInTheTree = new A().Bs.SelectMany(b => b.Cs.SelectMany(c => c.Ds));

Given the class hierarchy:
public class D { public int Id { get; set; } }
public class C {
    public IEnumerable<D> Ds { get; set; }
}
public class B
{
    public IEnumerable<C> Cs { get; set; }
}
public class A
{
    public IEnumerable<B> Bs { get; set; }
}

SelectMany at a single level would be something similar to:
var cs = new List<C>();
foreach (var b in a.Bs)
{
   cs.AddRange(b.Cs);
}

A: handle null condition for collections
a.b == null ? new List<D>() : a.b.SelectMany(b=>b.c==null ? new List<D>() : b.c.SelectMany(c=>c.d))


text:
Q: Is there anyway to deploy private Ethereum network that have automining feature along with no gas cost system? I am creating POC web app using Ganache as a Blockchain network locally.
For now, I need to deploy everything to a testing server but the problem is that I still could not find the way to set up a private Blockchain network that has automining like what we have with Ganache locally also about the gas fee as well, when I develop locally I need to manually and ether to every newly created account for them to be able to make a transaction. But once when I deploy everything to the testing server, it would be better if I don't need to keep transferring ether since this is just a POC app on a private network anyway.
Any tools that I should take a look for this problem?
Thanks!

A: You are roughly describing a demo chain or a PoA chain.
OpenEthereum has a demo chain flag which uses this spec.
Alternatively, Almost all ETH1 clients support building PoA chains so you can cherry pick the EIP's you want to cinclude. Geth supports clique. OpenEthereum supports AuRa and clique.
If you want a production grade private network, i'd recommend either using AuRa or QBFT from GoQuorum.
Each client and its consensus algo have its own set of requirements like minimum number of validator nodes e.t.c.


text:
Q: How to create a div with javascript? I want to create a div inside a div. I want to create a div with a class of videos, inside the videos div. But it seems to not work.

    var div = document.createElement("div");
    div.class = "video";
    videosDiv.appendChild(div)const videosDiv = document.getElementById("videos");

    var div = document.createElement("div");
    div.class = "video";
    videosDiv.appendChild(div)```

A: Use const collection = document.getElementsByClassName("videos"); If you are filtering div elements by class videos and iterate the collection and append child with each element.


text:
Q: Enabling both a PHP parser and an Include statement I have an existing SHTML page with a few INCLUDE statements for menu's.  This has worked well.  To this point, my .htaccess file has looked like:
Options +FollowSymLinks

And my Include statement looked like this:
<!--#include virtual="menu_primary.shtml" -->

I have a new need to add some PHP code to the main page.  The PHP code queries a Mysql database to return a single row.  If the row exists in the database, I want to show it on the SHTML page.  If the row does not exist, do nothing.  Here's the PHP code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT notice from notification where page = 'home'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "Message is: " . $row["notice"]. "<br>";
    }
} else {
    echo "";
}
mysqli_close($conn);
?>
</body>
</html>

When I implemented this PHP code, the page seemed to interpret everything after the Greater Than symbol as text.  When I posted that problem, someone on this forum suggested altering the .htaccess file to include a PHP parser.  For a while. I altered my .htaccess file to look like this:
Options +FollowSymLinks
<FilesMatch "\.(htm|html|shtm|shtml)$">
    SetHandler application/x-httpd-php5
</FilesMatch>

However when I do that, the PHP code works fine and I display the data from the database on the SHTML page, but the #Include statements no longer work.  How can I enable both the PHP and #Include code together in the same SHTML page?  Thanks very much for looking at this.

A: In your PHP script you can invoke the virtual function to work with your SSI
<?php
virtual('menu_primary.shtml');

There's a very old page that talks about this in more detail
http://www.zytrax.com/tech/php/php_ssi.htm


text:
Q: Black screenshots using c++ and cygwin sshd service I have a problem when trying to capture screenshots using c++ on windows xp.
The code is similar to this:
hDc = CreateCompatibleDC(0);
hBmp = CreateCompatibleBitmap(GetDC(0), width, height);
HGDIOBJ obj = SelectObject(hDc, hBmp);
BitBlt(hDc, 0, 0, width, height, GetDC(0), 0, 0, SRCCOPY);

It runs fine on the machine normally, but when I login with ssh to the cygwin shell I just get a black screenshot running the same code. BitBlt returns 0 and GetLastError returns 6 which indicates an invalid handle. But none of the handles are 0. So how could I make this work, I am a bit lost as to what exactly the problem is.

A: When you log into Cygwin over SSH, you don't have a screen (at least not one Windows knows how to see): you just have the sshd service - so you can't take a screenshot.

A: Your login session probably doesn't have permission to use the desktop DC since it isn't part of the desktop.
Edit: If your intent is to get a screenshot of the Cygwin window only, you might be able to use the GetConsoleWindow function to get the HWND of that window - assuming it exists in a sshd session.


text:
Q: newline in a list box OK I am having problems with writing a newline in a listbox. Its gotta be something simple and
I cannot figure it out.
dim decInput1 as decimal = 40.65
dim decInput2 as decimal = 500.90
dim decInput3 as decimal = 450.89
dim strOutput as string

strOutput = " Here is decInput1 " & decInput1.tostring("c")
strOutput &= " Here is decInput2 " & decInput2.tostring("c")
strOutput &= " here is decInput3 " & decInput3.tostring("c")

lstBox.items.clear()
lstBox.items.add(strOutput)

the output i want should be
40.65
500.90
450.89
 but i keep getting it all in one line. this isnt code out of the actual program I am working on but similar. thank you for you help

This is my actual program. Im trying to display in 2 columns for the title and the amounts in 4 diferent listbox for 4 diferent employees. and i am at this point so lost. as u can see its not to unifom when it comes to tthe dif strEmployee statements where ive tried several diferent techniques.  I dont need an answer. Just maybe an exapmle statement in as simplest form u can for me please. thank you
Private Sub btnEnter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnter.Click
    Dim intCount1 As Integer = 1                          ' count increment
    Dim intCount2 As Integer = 1
    Dim intColumn As Integer = 1
    Dim decEmployee4Hours As Decimal = 0
    Dim decPayRate As Decimal = 0                        ' stores pay rate
    Dim decEmployee1Pay As Decimal = 0                   ' employee 1 pay rate
    Dim decEmployee2Pay As Decimal = 0
    Dim decEmployee3Pay As Decimal = 0
    Dim decEmployee4Pay As Decimal = 0
    Dim decHours As Decimal = 0                          ' stores hours
    Dim decEmployee1Hours As Decimal = 0                 ' stores the hours for each employee
    Dim decEmployee2Hours As Decimal = 0
    Dim decEmployee3Hours As Decimal = 0
    Dim strInput As String                               ' stores string
    Dim dblStateTax As Double = CDbl(txtStateTax.Text)
    Dim dblFedTax As Double = CDbl(txtFedTax.Text)
    Dim dblFICA As Double = CDbl(txtFICA.Text)
    Dim decEmployee1Gross As Decimal = 0
    Dim decEmployee2Gross As Decimal = 0
    Dim decEmployee3Gross As Decimal = 0
    Dim decEmployee4Gross As Decimal = 0
    Dim decEmployee1StateTax As Decimal = 0
    Dim decEmployee2StateTax As Decimal = 0
    Dim decEmployee3StateTax As Decimal = 0
    Dim decEmployee4StateTax As Decimal = 0
    Dim decEmployee1FedTax As Decimal = 0
    Dim decEmployee2FedTax As Decimal = 0
    Dim decEmployee3FedTax As Decimal = 0
    Dim decEmployee4FedTax As Decimal = 0
    Dim decEmployee1FICA As Decimal = 0
    Dim decEmployee2FICA As Decimal = 0
    Dim decEmployee3FICA As Decimal = 0
    Dim decEmployee4FICA As Decimal = 0
    Dim decEmployee1NetPay As Decimal = 0
    Dim decEmployee2NetPay As Decimal = 0
    Dim decEmployee3NetPay As Decimal = 0
    Dim decEmployee4NetPay As Decimal = 0
    Dim strEmployee1 As String
    Dim strEmployee2 As String
    Dim strEmployee3 As String
    Dim strEmployee4 As String

    ' get pay rate for each employee
    For intCount1 = 1 To 4 Step 1

        strInput = InputBox("Enter Pay Rate for employee " & intCount1.ToString())
        If intCount1 = 1 Then
            decEmployee1Pay = CDec(strInput)
            lblEmployee1A.Text = decEmployee1Pay.ToString("c")
        ElseIf intCount1 = 2 Then
            decEmployee2Pay = CDec(strInput)
            lblEmployee2A.Text = decEmployee2Pay.ToString("c")
        ElseIf intCount1 = 3 Then
            decEmployee3Pay = CDec(strInput)
            lblEmployee3A.Text = decEmployee3Pay.ToString("c")
        ElseIf intCount1 = 4 Then
            decEmployee4Pay = CDec(strInput)
            lblEmployee4A.Text = decEmployee4Pay.ToString("c")
        End If

    Next

    For intCount2 = 1 To 4 Step 1
        strInput = InputBox("Enter the hours for employee " & intCount2.ToString())
        If intCount2 = 1 Then
            decEmployee1Hours = CDec(strInput)
            lblEmployee1B.Text = decEmployee1Hours.ToString()
        ElseIf intCount2 = 2 Then
            decEmployee2Hours = CDec(strInput)
            lblEmployee2B.Text = decEmployee2Hours.ToString()
        ElseIf intCount2 = 3 Then
            decEmployee3Hours = CDec(strInput)
            lblEmployee3B.Text = decEmployee3Hours.ToString()
        ElseIf intCount2 = 4 Then
            decEmployee4Hours = CDec(strInput)
            lblEmployee4B.Text = decEmployee4Hours.ToString()
        End If

    Next

    decEmployee1Gross = decEmployee1Pay * decEmployee1Hours
    decEmployee1StateTax = decEmployee1Gross * dblStateTax
    decEmployee1FedTax = decEmployee1Gross * dblFedTax
    decEmployee1FICA = decEmployee1Gross * dblFICA
    decEmployee1NetPay = decEmployee1Gross - decEmployee1FedTax - decEmployee1StateTax -decEmployee1FICA

    lstBox1.Items.Clear()

    For intColumn = 1 To 2 Step 1
        If intColumn = 1 Then
            strEmployee1 = " Gross pay: "
            lstBox1.Items.Add(strEmployee1)
            strEmployee1 = " State Income tax: "
            lstBox1.Items.Add(strEmployee1)
            strEmployee1 = " Federal Income Tax: "
            lstBox1.Items.Add(strEmployee1)
            strEmployee1 = " FICA: "
            lstBox1.Items.Add(strEmployee1)
            strEmployee1 = " Net Pay: "
            lstBox1.Items.Add(strEmployee1)
        ElseIf intColumn = 2 Then
            strEmployee1 = decEmployee1Gross.ToString("c")
            lstBox1.Items.Add(strEmployee1)
            strEmployee1 = decEmployee1StateTax.ToString("c")
            lstBox1.Items.Add(strEmployee1)
            strEmployee1 = decEmployee1FedTax.ToString("c")
            lstBox1.Items.Add(strEmployee1)
            strEmployee1 = decEmployee1FICA.ToString("c")
            lstBox1.Items.Add(strEmployee1)

        End If
    Next

    decEmployee2Gross = decEmployee2Pay * decEmployee2Hours
    decEmployee2StateTax = decEmployee2Gross * dblStateTax
    decEmployee2FedTax = decEmployee2Gross * dblFedTax
    decEmployee2FICA = decEmployee2Gross * dblFICA
    decEmployee2NetPay = decEmployee2Gross - decEmployee2FedTax - decEmployee2StateTax - decEmployee2FICA

    strEmployee2 = " Employee Gross pay " & vbCrLf & "    " & decEmployee2Gross.ToString("c") & vbCrLf & "aaaaa"
    strEmployee2 &= " Employee State Income tax " & vbCrLf & "     " & decEmployee2StateTax.ToString("c") & vbCrLf
    strEmployee2 &= " Employee Federal Income Tax " & vbCrLf & "     " & decEmployee2FedTax.ToString("c") & vbCrLf
    strEmployee2 &= " Employee FICA " & vbCrLf & "     " & decEmployee2FICA.ToString("c")
    strEmployee2 &= " Net Pay " & vbCrLf & "     " & decEmployee2NetPay.ToString("c")

    lstBox2.Items.Clear()

    lstBox2.Items.Add(strEmployee2)

    decEmployee3Gross = decEmployee3Pay * decEmployee3Hours
    decEmployee3StateTax = decEmployee3Gross * dblStateTax
    decEmployee3FedTax = decEmployee3Gross * dblFedTax
    decEmployee3FICA = decEmployee3Gross * dblFICA
    decEmployee3NetPay = decEmployee3Gross - decEmployee3FedTax - decEmployee3StateTax - decEmployee3FICA

    strEmployee3 = " Employee Gross pay " & vbCrLf & "    " & decEmployee3Gross.ToString("c") & vbCrLf
    strEmployee3 &= " Employee State Income tax " & vbCrLf & "     " & decEmployee3StateTax.ToString("c") & vbCrLf
    strEmployee3 &= " Employee Federal Income Tax " & vbCrLf & "     " & decEmployee3FedTax.ToString("c") & vbCrLf
    strEmployee3 &= " Employee FICA " & vbCrLf & "     " & decEmployee3FICA.ToString("c")
    strEmployee3 &= " Net Pay " & vbCrLf & "     " & decEmployee3NetPay.ToString("c")

    lstBox3.Items.Clear()

    lstBox3.Items.Add(strEmployee3)

    decEmployee4Gross = decEmployee4Pay * decEmployee4Hours
    decEmployee4StateTax = decEmployee4Gross * dblStateTax
    decEmployee4FedTax = decEmployee4Gross * dblFedTax
    decEmployee4FICA = decEmployee4Gross * dblFICA
    decEmployee4NetPay = decEmployee4Gross - decEmployee4FedTax - decEmployee4StateTax - decEmployee4FICA

    strEmployee4 = " Employee Gross pay " & vbNewLine & " " & decEmployee4Gross.ToString("c") & vbNewLine
    strEmployee4 += " Employee State Income tax " & vbNewLine & " " & decEmployee4StateTax.ToString("c") & vbNewLine
    strEmployee4 += " Employee Federal Income Tax " & vbNewLine & " " & decEmployee4FedTax.ToString("c") & vbNewLine
    strEmployee4 += " Employee FICA " & vbNewLine & " " & decEmployee4FICA.ToString("c") & vbNewLine
    strEmployee4 += " Net Pay " & vbNewLine & " " & decEmployee4NetPay.ToString("c")

    lstBox4.Items.Clear()

    lstBox4.Items.Add(strEmployee4)
End Sub

A: You can, but it's a little bit of work.
You have to set the DrawMode = OwnerDrawVariable, and then subscribe to the DrawItem and MeasureItem events.
In it's simplest form:
Protected Overrides Sub OnLoad(e As EventArgs)
  ListBox1.DrawMode = DrawMode.OwnerDrawVariable
  ListBox1.Items.Add("This is line one." + Environment.NewLine + "This is line two.")
  ListBox1.Items.Add("This is another line.")
  MyBase.OnLoad(e)
End Sub

Private Sub ListBox1_MeasureItem(sender As Object, e As MeasureItemEventArgs) Handles ListBox1.MeasureItem
  e.ItemHeight = e.Graphics.MeasureString(ListBox1.Items(e.Index).ToString, ListBox1.Font).Height
End Sub

Private Sub ListBox1_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ListBox1.DrawItem
  e.DrawBackground()
  e.Graphics.DrawString(ListBox1.Items(e.Index).ToString, ListBox1.Font, Brushes.Black, e.Bounds)
End Sub

A: The only way to have multiple lines in a listbox is to add each line as a separate item. The only work around is to build your own control that only looks like a listbox, and that's not at all trivial or simple.


text:
Q: Ruby on Rails delegate throwing undefined method error I have a profile model:
 # Experience
  has_many :experiences, dependent: :destroy
   accepts_nested_attributes_for :experiences, allow_destroy: true
  delegate :incomplete, to: :experiences, prefix: true

Experiences Model:
  belongs_to :profile
  def incomplete
    true
  end

But when I do @profile.experiences_incomplete from the controller it gives me this error:
undefined method `incomplete' for #< Experience::ActiveRecord_Associations_CollectionProxy:0x00000004600938>


text:
Q: Sqlite order by special characters I executed an SQLite query, but I got a result that is not in the order that we need,the character "á" is being shown after z.
How can I configure my query to ignore special characters?

A: Not sure if you just want to ignore all the results having these special characters or you have difficulties in sorting the result.
You can treat this as a hint (not an answer):
SELECT *
FROM _table-name_
WHERE _column-name_ COLLATE Latin1_General_BIN NOT LIKE '%[^ a-zA-Z]%'


text:
Q: Angular autocomplete - replace field with current highlighted selection I'm using the Angular autocomplete in a project.
The user can navigate the autocomplete results with arrow-up and arrow-down. However, I would like to make it behave like the google-suggest does; when selecting a value using arrow-up or arrow down, that the input text also changes.
I currently have the optionSelected but I need it before selection.
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="onSelectSuggestion($event)">
    <mat-option *ngFor="let result of (suggestions$ | async)" [value]="result">
        {{ result.suggestion }}
    </mat-option>
</mat-autocomplete>

So for example; I type jag, the autocomplete might suggest jaguar. I navigate to that entry using the arrows and type car. The input would ideally contain jaguar car by then.
What would be the best approach to accomplish this?
UPDATE:
I can use the optionActivated, but then just as I select the first entry, it gets activated and put in the search-input. I don't want that, I want it to get in the searchbox if the user starts typing when an item is still selected.


text:
Q: Disabling of checkBoxes inside gridview on Page_Load I want to

disable the gridview checkboxes which is inside gridview.

I tried like below:-
public static void DisableFormControls(ControlCollection ChildCtrls)
{
    foreach (Control Ctrl in ChildCtrls)
    {
        if (Ctrl is Obout.Grid.Grid)
            ((Obout.Grid.Grid)Ctrl).Enabled = false;
        if (Ctrl is HtmlGenericControl)
            ((HtmlGenericControl)Ctrl).Disabled = true;
    }
}

and on Page_load
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["userid"] != null && Request.QueryString["userid"] != "")
    {
        Hid_userid.Value = Request.QueryString["userid"];
        Hid_HR.Value = "Y";
        FundiableEnable();

        DisableFormControls(Form.Controls);
    }
}

But it is not working for me. Any idea what's wrong with the code
Here is my html of GridView:
<cc1:Grid ID="GrdWorkingCompany" runat="server"  EnableTypeValidation="true" CallbackMode="true"
    ShowFooter="false" AutoGenerateColumns="false" AllowAddingRecords="true" AllowSorting="false"
    Width="100%" FolderStyle="~/Styles/Grid/style_12" PageSize="18">
    <Columns>
        <cc1:Column ID="Sr_No" ReadOnly="true" DataField="SrNo" HeaderText="Sr.No." Width="50px">
        </cc1:Column>
        <cc1:Column ID="Points" ReadOnly="true" DataField="Points" HeaderText="Points" runat="server" Width="300px">
        </cc1:Column>
        <cc1:Column ID="chkPoor" ReadOnly="true" DataField="Rating1" HeaderText="Poor" Width="110px" TemplateId="tpltPoor">
        </cc1:Column>
        <cc1:Column ID="chkSatisfactory" DataField="Rating2" HeaderText="Satisfactory" ReadOnly="true"
            Width="110px" TemplateId="tpltSatisfactory">
        </cc1:Column>
        <cc1:Column ID="chkGood" ReadOnly="true" HeaderText="Good" DataField="Rating3" Width="110px" TemplateId="tpltGood">
        </cc1:Column>
        <cc1:Column ID="chkExcellent" HeaderText="Excellent" DataField="Rating4" Width="110px" ReadOnly="true"
            TemplateId="tpltEx1">
        </cc1:Column>
    </Columns>
    <TemplateSettings GroupHeaderTemplateId="GroupTemplate" />
    <Templates>
        <cc1:GridTemplate runat="server" ID="GridTemplate2">
            <Template>
                <%# Container.Column.HeaderText %>
                :
                    <%# Container.Value %> (<%# Container.Group.PageRecordsCount %><%# Container.Group.PageRecordsCount > 1 ? "records" : "record" %>)
            </Template>
        </cc1:GridTemplate>
    </Templates>
    <Templates>
        <cc1:GridTemplate ID="tpltPoor">
            <Template>
                <input type="checkbox" id="chkA1<%# (Container.RecordIndex)%>" name="chkAC1" style="width: 17px;
                    height: 17px;" value="<%# (Container.RecordIndex)%>" onclick="AppoveCheckA(this)" /></Template>
        </cc1:GridTemplate>
        <cc1:GridTemplate ID="tpltSatisfactory">
            <Template>
                <input type="checkbox" id="chkA2<%# (Container.RecordIndex) %>" name="chkAC2" style="width: 17px;
                    height: 17px;" value="<%# (Container.RecordIndex)%>" onclick="AppoveCheckA(this)" /></Template>
        </cc1:GridTemplate>
        <cc1:GridTemplate ID="tpltGood">
            <Template>
                <input type="checkbox" id="chkA3<%# (Container.RecordIndex) %>" name="chkAC3" style="width: 17px;
                    height: 17px;" value="<%# (Container.RecordIndex)%>" onclick="AppoveCheckA(this)" /></Template>
        </cc1:GridTemplate>
        <cc1:GridTemplate ID="tpltEx1">
            <Template>
                <input type="checkbox" id="chkA4<%# (Container.RecordIndex) %>" name="chkAC4" style="width: 17px;
                    height: 17px;" value="<%# (Container.RecordIndex)%>" onclick="AppoveCheckA(this)" /></Template>
        </cc1:GridTemplate>
    </Templates>
</cc1:Grid>

A: Well, you didn't say a word that you are using OBOUT ASP.NET Grid and not a default grid control. In this case it's important. However I manually recreated your example and this is how I made it work.
Firstly I changed your Grid code to use server controls for checkboxes:
<cc1:Grid ID="GrdWorkingCompany" runat="server" EnableTypeValidation="true" CallbackMode="true" Serialize="true"
    ShowFooter="false" AutoGenerateColumns="false" AllowAddingRecords="true" AllowSorting="false"
    Width="100%" FolderStyle="~/Styles/Grid/style_12" PageSize="18">
    <Columns>
        <cc1:Column ID="Sr_No" ReadOnly="true" DataField="SrNo" HeaderText="Sr.No." Width="50px">
        </cc1:Column>
        <cc1:Column ID="Points" ReadOnly="true" DataField="Points" HeaderText="Points" runat="server" Width="300px">
        </cc1:Column>
        <cc1:Column ID="chkPoor" ReadOnly="true" DataField="Rating1" HeaderText="Poor" Width="110px" TemplateId="tpltPoor">
        </cc1:Column>
        <cc1:Column ID="chkSatisfactory" DataField="Rating2" HeaderText="Satisfactory" ReadOnly="true"
            Width="110px" TemplateId="tpltSatisfactory">
        </cc1:Column>
        <cc1:Column ID="chkGood" ReadOnly="true" HeaderText="Good" DataField="Rating3" Width="110px" TemplateId="tpltGood">
        </cc1:Column>
        <cc1:Column ID="chkExcellent" HeaderText="Excellent" DataField="Rating4" Width="110px" ReadOnly="true"
            TemplateId="tpltEx1">
        </cc1:Column>
    </Columns>
    <TemplateSettings GroupHeaderTemplateId="GroupTemplate" />
    <Templates>
        <cc1:GridTemplate runat="server" ID="GridTemplate2">
            <Template>
                <%# Container.Column.HeaderText %>
            :
                <%# Container.Value %> (<%# Container.Group.PageRecordsCount %><%# Container.Group.PageRecordsCount > 1 ? "records" : "record" %>)
            </Template>
        </cc1:GridTemplate>
    </Templates>
    <Templates>
        <cc1:GridTemplate ID="tpltPoor">
            <Template>
                <input type="checkbox" id="chkA1" name="chkAC1" style="width: 17px; height: 17px;"
                    value="<%# (Container.RecordIndex)%>" onclick="AppoveCheckA(this)" runat="server"/>
            </Template>
        </cc1:GridTemplate>
        <cc1:GridTemplate ID="tpltSatisfactory">
            <Template>
                <input type="checkbox" id="chkA2" name="chkAC2" style="width: 17px; height: 17px;"
                    value="<%# (Container.RecordIndex)%>" onclick="AppoveCheckA(this)" runat="server"/>
            </Template>
        </cc1:GridTemplate>
        <cc1:GridTemplate ID="tpltGood">
            <Template>
                <input type="checkbox" id="chkA3" name="chkAC3" style="width: 17px; height: 17px;"
                    value="<%# (Container.RecordIndex)%>" onclick="AppoveCheckA(this)" runat="server"/>
            </Template>
        </cc1:GridTemplate>
        <cc1:GridTemplate ID="tpltEx1">
            <Template>
                <input type="checkbox" id="chkA4" name="chkAC4" style="width: 17px; height: 17px;"
                    value="<%# (Container.RecordIndex)%>" onclick="AppoveCheckA(this)" runat="server"/>
            </Template>
        </cc1:GridTemplate>
    </Templates>
</cc1:Grid>

You don't need to worry about duplicate Id because ASP.NET will generate appropriate Ids on client side. It's necessary to user server controls for checkboxes because if you use generic html tags it will create DataBoundLiteralCOntrol for each checkbox and its inconvenient to change their code in code behind (they are treated as static text). If we use server control we can access their attributes in code behind - in that case HtmlInputCheckBox will be created for each checkbox.
Then I iterate each row and look for checkbox control:
private void GrdWorkingCompany_RowDataBound(object sender, Obout.Grid.GridRowEventArgs e)
    {
        foreach (Obout.Grid.Column column in GrdWorkingCompany.Columns)
        {
            if (!string.IsNullOrEmpty(column.TemplateId))
            {
                var cell = e.Row.Cells[column.Index] as Obout.Grid.GridDataControlFieldCell;
                var checkBoxControls = cell.FindControlsByType(typeof(HtmlInputCheckBox));
                if (checkBoxControls.Count > 0)
                {
                    var checkbox = checkBoxControls[0] as HtmlInputCheckBox;
                    checkbox.ClientIDMode = ClientIDMode.Static;
                    checkbox.ID = checkbox.ID + e.Row.RowIndex;
                    checkbox.Attributes.Add("disabled", "true");
                }
            }
        }
    }

I only check for cells in column that have TemplateId defined because FindControlsByType will throw error if it not find any control. So I assume that every template column have at least one checkbox. If you need more flexible approach you could define your own function similar to FindControlsByType - there are examples on StackOverflow for that kind of functions (e.g. Get all controls of a specific type or Find all child controls of specific type using Enumerable.OfType<T>() or LINQ). After you find the right control you can add custom attributes.
The last step is to hoop up to the event called when row gets bounded. To do that I used Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
    GrdWorkingCompany.RowDataBound += GrdWorkingCompany_RowDataBound;

    if (!IsPostBack)
    {
        GrdWorkingCompany.DataSource = new List<Test>() { new Test(), new Test() };
        GrdWorkingCompany.DataBind();
    }

}

My test class:
public class Test
{
    public string SrNo { get; set; }
    public string Points { get; set; }
    public string Rating1 { get; set; }
    public string Rating2 { get; set; }
    public string Rating3 { get; set; }
    public string Rating4 { get; set; }
}

Update:
After a conversation with the @coder he told me that ids of the checkboxes need to be exacly as before my change to server controls. In order to do this I below added code to GrdWorkingCompany_RowDataBound method:
checkbox.ClientIDMode = ClientIDMode.Static;
checkbox.ID = checkbox.ID + e.Row.RowIndex;

With this in place ids of the checkboxes will remain the same as if the control was client side.

A: Code not tested but hopefully helps you.
You can change your checkboxes and make these asp:CheckBox so that you can disable it in your code behind, something like this:
Handle OnRowDataBound Event to your GridView
<cc1:Grid ID="GrdWorkingCompany" runat="server"  EnableTypeValidation="true" CallbackMode="true"
    ShowFooter="false" AutoGenerateColumns="false" AllowAddingRecords="true" AllowSorting="false"
    Width="100%" FolderStyle="~/Styles/Grid/style_12" PageSize="18" OnRowDataBound="GrdWorkingCompany_RowDataBound">

<Template>
    <asp:CheckBox ID="cbTest" runat="server" />
</Template>

In your code behind, you should enable or disable your checkbox like this:
protected void GrdWorkingCompany_RowDataBound(object sender, GridViewRowEventArgs e)
{
    CheckBox chkbox = (CheckBox)e.Row.FindControl("cbTest");
    chekbox.Enable = false;
}

Method 2, you can create a jquery function that will be call in your code behind, something like this:

And call the function in your code behind:
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["userid"] != null && Request.QueryString["userid"] != "")
    {
        Hid_userid.Value = Request.QueryString["userid"];
        Hid_HR.Value = "Y";
        FundiableEnable();

        //DisableFormControls(Form.Controls);
        Page.ClientScript.RegisterStartupScript(this.GetType(),"TEST", "DisableAllCheckBox()",true);
    }
}

A: 100% working Simple just bind your gride view method after page load event like this
protected void Page_LoadComplete(object sender, EventArgs e)
{
     DisableFormControls(Form.Controls);
}

remove this method from page load and use above event

A: Sorry if there are any syntax errors.
function DisableControls() {
        //Get target base & child control.
        var TargetBaseControl =
        document.getElementById('<%= this.grid.ClientID %>');
        var TargetChildControl = "chkA";

        //Get all the control of the type INPUT in the base control.
        var Inputs = TargetBaseControl.getElementsByTagName("input");

        //disable or enable all the checkBoxes in side the Grid.
        for (var n = 0; n < Inputs.length; ++n)
            if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl, 0) >= 0)
                Inputs[n].disabled= false; //i am not sure if this is the correct syntax for disabling
    }


text:
Q: Validates uniqueness of :link I have a url field named link in my model with the following validation
validates_uniqueness_of :link, :case_sensitive => false

When I put "http://stackoverflow.com", it goes well.
Now when I put "https://stackoverflow.com/" (with the trailing slach), this is also accepted as unique.
But I want it to be invalid though there is "/" at the last?

A: I'd suggest that you normalize your URLs (add/strip trailing slash, etc. see http://en.wikipedia.org/wiki/URL_normalization) before storing them in the DB and even before validation.
validates_uniqueness_of :link, :case_sensitive => false
before_validation :normalize_urls

def normalize_urls
  self.link.strip!
  self.link.gsub!(/\/$/,'')
end

This isn't quite what you were asking for but if you don't store normalized URLs, you'll have to query your DB for all possible variations during validation and that could quickly get expensive.

A: You could always do a custom validator (by using the validate method, for example).
It might look something like this:
class MyModel < ActiveRecord::Base
  validate :link_is_unique

  def link_is_unique
    #Clean up the current link (removing trailing slashes, etc)
    link_to_validate = self.link.strip.gsub(/\/$/,'')

    # Get the current count of objects having this link
    count = MyModel.count(:conditions => ['link = ?', link_to_validate])

    # Add an error to the model if the count is not zero
    errors.add_to_base("Link must be unique") unless count == 0
  end
end

You could then add other logic to clean up the link (i.e. check for http://, www, etc.)

A: You can customize validations. See this railscast.


text:
Q: Justify-content: space-evenly not working I'm trying to create a responsive navbar with three items in the same container in the middle as shown below.

For some reason the ul items are not being space evenly and it is showing me this:

I used these lines of code:

nav {
  font-size: 1.5em;
  display: flex;
  justify-content: space-between;
}

ul {
  flex: 1;
  max-width: 50%;
  display: flex;
  justify-content: space-evenly;
}

ul,
li {
  display: inline;
  margin: 0;
  padding: 0;
}

  Home

      Learn More

      About

      Contact

  Sign Up

I appreciate any help and apologize if this post is unclear; I'm still new to this website.

A: What seemed to fix the issue was changing the "ul {...}" item in css to "nav ul{...}". Hopefully this can help out someone else in the future as well.

A: space-evenly or space-between will work!

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

header {
  display: block;
  width: 90%;
  margin: 5% auto;
}

nav {
  display: flex;
  justify-content: space-evenly;
}

ul {
  margin: 0;
  padding: 0;
  list-style: none;
  display: flex;
}

li+li {
  margin-left: 1.5rem;
  float: left;
  display: inline-block;
}

    Home

Learn More

About

Contact

    Sign Up


text:
Q: How do i get body of message when using keyword mentions in teams in automate i have a flow. I am using "When keywords are mentioned".  the keyword i entered is "test"
I Selected, the team,channel,etc... all correctly.
when someone types "the test is a success". in that channel.  how do i get the full string "the test is a success"?
I have tried a few operations "get Messages", also tried a few dynamic content options and a few triggeroutput variations.  all either are blank or provide a long json string with subscription,channelId,teamId,etc.  but not the string I am trying to get.

A: The Get message details action should help you ...

In the body of the response, you'll clearly see the text that was entered to invoke the trigger.

A: Use Get message details, you will get message detail of that reply message. Then get your text with expression like this:
outputs('Get_message_details')?['body']['body']['plainTextContent']


text:
Q: How to handle multiple speech recognition events in C#? First off I must admit that I'm fairly new to C#. I am using C# speech recognition for writing an application that will interface between a human and a robot. An example of a dialogue is as follows:

Human: Ok Robot, Drill.
Robot: Where?
Human shows where.
Robot: I am ready to drill.
Human: Ok Robot, start.

My approach is having two speech recognizes. The first one is for higher level commands such as "Drill", "Cut Square", "Cut Rectangle", "Play Game" etc. The second one is for start/stop commands for each of the higher level tasks.
This is my current code:
using System.IO;
using System.Speech.Recognition;
using System.Speech.Synthesis;

namespace SpeechTest
{
    class RobotSpeech
    {
        public SpeechRecognitionEngine MainRec = new SpeechRecognitionEngine();
        public SpeechRecognitionEngine SideRec = new SpeechRecognitionEngine();
        public SpeechSynthesizer Synth = new SpeechSynthesizer();
        private Grammar mainGrammar;
        private Grammar sideGrammar;
        private const string MainCorpusFile = @"../../../MainRobotCommands.txt";
        private const string SideCorpusFile = @"../../../SideRobotCommands.txt";

        public RobotSpeech()
        {
            Synth.SelectVoice("Microsoft Server Speech Text to Speech Voice (en-US, ZiraPro)");
            MainRec.SetInputToDefaultAudioDevice();
            SideRec.SetInputToDefaultAudioDevice();
            BuildGrammar('M');
            BuildGrammar('S');
        }

        private void BuildGrammar(char w)
        {
            var gBuilder = new GrammarBuilder("Ok Robot");
            switch (w)
            {
                case 'M':
                    gBuilder.Append(new Choices(File.ReadAllLines(MainCorpusFile)));
                    mainGrammar = new Grammar(gBuilder) { Name = "Main Robot Speech Recognizer" };
                    break;
                case 'S':
                    gBuilder.Append(new Choices(File.ReadAllLines(SideCorpusFile)));
                    sideGrammar = new Grammar(gBuilder) { Name = "Side Robot Speech Recognizer" };
                    break;
            }
        }

        public void Say(string msg)
        {
            Synth.Speak(msg);
        }

        public void MainSpeechOn()
        {
            Say("Speech recognition enabled");
            MainRec.LoadGrammarAsync(mainGrammar);
            MainRec.RecognizeAsync(RecognizeMode.Multiple);
        }

        public void SideSpeechOn()
        {
            SideRec.LoadGrammarAsync(sideGrammar);
            SideRec.RecognizeAsync();
        }

        public void MainSpeechOff()
        {
            Say("Speech recognition disabled");
            MainRec.UnloadAllGrammars();
            MainRec.RecognizeAsyncStop();
        }

        public void SideSpeechOff()
        {
            SideRec.UnloadAllGrammars();
            SideRec.RecognizeAsyncStop();
        }
    }
}

In my main program I have the speech recognized event as follows:
private RobotSpeech voiceIntr;
voiceIntr.MainRec.SpeechRecognized += MainSpeechRecognized;
private void MainSpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            if (!e.Result.Text.Contains("Ok Bishop")) return;
            switch (e.Result.Text.Substring(10))
            {
                case "Go Home":
                    voiceIntr.Say("Going to home position.");
                    UR10MoveRobot.GoHome();
                    break;
                case "Say Hello":
                    voiceIntr.Say("Hello. My name is Bishop.");
                    break;
                case "Drill":
                    voiceIntr.Say("Show me where you want me to drill.");
                    // Actual code will be for observating the gestured pts and
                    // returning the number of pts observed
                    var msg = "I am ready to drill those " + new Random().Next(2, 5) + " holes.";
                    voiceIntr.Say(msg);
                    voiceIntr.SideSpeechOn();
                    voiceIntr.SideSpeechOff();
                    break;
                case "Cut Outlet":
                    voiceIntr.Say("Show me where you want me to cut the outlet.");
                    // Launch gesture recognition to get point for cutting outlet
                    break;
                case "Stop Program":
                    voiceIntr.Say("Exiting Application");
                    Thread.Sleep(2200);
                    Application.Exit();
                    break;
            }
        }

The problem I am having is, when one of the MainRec events gets triggered, I am in one the cases here. Now I only want to listen for "Ok Robot Start" and nothing else which is given by the SideRec. If I subscribe to that event here this will go to another eventhandler with a switch case there from which I wouldn't know how to get back to the main thread.
Also after telling the human that the robot is ready for drilling, I would like it to block until it receives an answer from the user for which I need to use a synchronous speech recognizer. However, after a particular task I want to switch off the recognizer which I can't do if its synchronous.
Here are the files for the grammers:
MainRobotCommands.txt

Go Home
Say Hello
Stop Program
Drill
Start Drilling
Cut Outlet
Cut Shap
Play Tic-Tac-Toe
Ready To Play
You First

SideRobotCommands.txt:

Start
Stop

The speech recognition is only a part of a bigger application hence it has to be async unless I want to make it preciously block. I am sure there is better way to design this code, but I'm not sure my knowledge of C# is enough for that. Any help is greatly appreciated!
Thanks.

A:
My approach is having two speech recognizes.

There is no need for 2 recognizers, you can have just 1 recognizer and load/unload grammars when you need them.

private void BuildGrammar(char w)

This is not a straightforward programming style to use switch statement and invoke same function two times with different arguments. Just create two grammars sequentially.

The problem I am having is, when one of the MainRec events gets triggered, I am in one the cases here. Now I only want to listen for "Ok Robot Start" and nothing else which is given by the SideRec. If I subscribe to that event here this will go to another eventhandler with a switch case there from which I wouldn't know how to get back to the main thread.

If you have one recognizer it's enough to have a single handler and do all work there.

Also after telling the human that the robot is ready for drilling, I would like it to block until it receives an answer from the user for which I need to use a synchronous speech recognizer. However, after a particular task I want to switch off the recognizer which I can't do if its synchronous.

It not easy to mix async and sync style in the same design. You need to use either sync programming or async programming. For event-based software there is actually no need to mix, you can work in strictly async paradigm without waiting. Just start new drilling action inside MainSpeechRecognized event handler when "ok drill" is recognized. You can also synthesize audio in async mode without waiting for the result and continue processing in on SayCompleted handler.
To track the state of your software you can create a state variable and check it in event handlers to understand in what state you are and choose next action.
This programming paradigm is called "Event-driven programming", you can read a lot about it in network, check Wikipedia page and start with this tutorial.


text:
Q: showing array member dependent the name of difference array I created a site by laravel and I want to show categories and relevant products names.
I have an array and like this
$category  = [
    '1' => 'cat1',
    '2' => 'cat2'
];

$product = [
    '0' => array(
     'name' => 'product1',
     'category_id' => '2'
),
    '1' => array(
     'name' => 'product2',
     'category_id' => '2'
),
    '2' => array(
     'name' => 'product3',
     'category_id' => '2'
),
    '3' => array(
     'name' => 'product4',
     'category_id' => '1'
),
    '4' => array(
     'name' => 'product5',
     'category_id' => '1'
),
    '5' => array(
     'name' => 'product6',
     'category_id' => '2'
)];

and I want to showing it like this

cat1

product4

product5

cat2

product1

product2

product3

product6

You have to know I'm using laravel and I want doing this job with laravel but you also can coding with PHP, I think I can to convert it in laravel

A: You can make use of Laravel collections' groupBy for your use case.
In your controller file, group by category_id key and render them in your blade by looping.
Controller Snippet:
public function someMethod(){
    $category  = [
        '1' => 'cat1',
        '2' => 'cat2'
    ];

    $product = [
        '0' => array(
         'name' => 'product1',
         'category_id' => '2'
    ),
        '1' => array(
         'name' => 'product2',
         'category_id' => '2'
    ),
        '2' => array(
         'name' => 'product3',
         'category_id' => '2'
    ),
        '3' => array(
         'name' => 'product4',
         'category_id' => '1'
    ),
        '4' => array(
         'name' => 'product5',
         'category_id' => '1'
    ),
        '5' => array(
         'name' => 'product6',
         'category_id' => '2'
    )];

    $category_collection = collect($product)->groupBy('category_id')->toArray();

    return view('your_blade_name',compact('category_collection','category'));
}

Blade Snippet:
@foreach($category_collection as $category_id => $data)

{{ $category[$category_id] }}

    @foreach($data as $current_data)

{{ $current_data['name'] }}

    @endforeach

@endforeach

A: You can use simple foreach loop like next:
foreach($category as $ind=>$cat){
    echo "
".$cat."
".PHP_EOL;
    foreach($product as $row){
        if($row['category_id'] == $ind) {
            echo "
".$row['name']."
".PHP_EOL;
        }
    }
    echo "

".PHP_EOL;
}

Demo
Outputs:

cat1

product4

product5

cat2

product1

product2

product3

product6

A: try
@foreach($category as $key => $cat)

{{$cat}}

@foreach($product as $pr)
    @if($pr['category_id'] == $key)

{{$pr['name']}}

    @endif
@endforeach

@endforeach


text:
Q: How to view autogenerated code in ASP.NET MVC? I'm using Telerik's Grid control and it's seemingly randomly throwing an exception: a key is  being added twice to a dictionary in some auto generated code. Is there a way I can view this auto generated code so I can get a better understanding of what's happening?

A: Their MVC controls are open source http://telerikaspnetmvc.codeplex.com/. Include their projects in your solution, hit CTRL+ALT+E and select Break on All Exceptions. That should get you to the code you are looking for.


text:
Q: win.RegisterRawInputDevices Always Returns false I'm using the https://github.com/lxn/win package to access low level Windows calls in Go. I'm calling win.RegisterRawInputDevices to register devices for raw input data, but it always returns false. I've done this in C# with no problems. Below is my code:
package main

import (
    "fmt"
    "syscall"
    "unsafe"
    "github.com/lxn/win"
)

func WndProc(hWnd win.HWND, msg uint32, wParam, lParam uintptr) uintptr {
    switch msg {
    case win.WM_CREATE:
        fmt.Println("Received WM_CREATE message")
        devices := getRawInputDevices(hWnd)
        len := uint32(len(devices))
        size := uint32(unsafe.Sizeof(devices[0]))
        if !win.RegisterRawInputDevices(&devices[0], len, size) {
            panic("Unable to register devices")
        }

    case win.WM_DESTROY:
        fmt.Println("Posting quit message")
        win.PostQuitMessage(0)
    default:
        return win.DefWindowProc(hWnd, msg, wParam, lParam)
    }

    return 0
}

func getRawInputDevices(hWnd win.HWND) []win.RAWINPUTDEVICE {
    devices := make([]win.RAWINPUTDEVICE, 5)
    devices[0].UsUsagePage = 0x01
    devices[0].UsUsage = 0x02
    devices[0].DwFlags = win.RIDEV_INPUTSINK
    devices[0].HwndTarget = hWnd
    devices[1].UsUsagePage = 0x01
    devices[1].UsUsage = 0x06
    devices[1].DwFlags = win.RIDEV_INPUTSINK
    devices[1].HwndTarget = hWnd
    devices[2].UsUsagePage = 0x00
    devices[2].UsUsage = 0x51
    devices[2].DwFlags = win.RIDEV_INPUTSINK
    devices[2].HwndTarget = hWnd
    devices[3].UsUsagePage = 0x00
    devices[3].UsUsage = 0x04
    devices[3].DwFlags = win.RIDEV_INPUTSINK
    devices[3].HwndTarget = hWnd
    devices[4].UsUsagePage = 0x00
    devices[4].UsUsage = 0x00
    devices[4].DwFlags = win.RIDEV_INPUTSINK
    devices[4].HwndTarget = hWnd
    return devices
}

func WinMain() int {

    hInstance := win.GetModuleHandle(syscall.StringToUTF16Ptr(""))
    lpszClassName := syscall.StringToUTF16Ptr("WNDclass")
    var wcex win.WNDCLASSEX
    wcex.HInstance = hInstance
    wcex.LpszClassName = lpszClassName
    wcex.LpfnWndProc = syscall.NewCallback(WndProc)
    wcex.CbSize = uint32(unsafe.Sizeof(wcex))
    win.RegisterClassEx(&wcex)
    win.CreateWindowEx(
        0, lpszClassName, syscall.StringToUTF16Ptr("Simple Go Window!"),
        win.WS_OVERLAPPEDWINDOW,
        win.CW_USEDEFAULT, win.CW_USEDEFAULT, 400, 400, 0, 0, hInstance, nil)
    var msg win.MSG
    for {
        if win.GetMessage(&msg, 0, 0, 0) == 0 {
            break
        }
        win.TranslateMessage(&msg)
        win.DispatchMessage(&msg)
    }
    return int(msg.WParam)
}

func main() {
    WinMain()
    return
}

I'm receiving the WM_CREATE message, but win.RegisterRawInputDevices is always returning false with a "The parameter is incorrect." error. As I mentioned, I've done this in C# with no problems, so I'm familiar with the basic steps. I am new to Go, so I may be missing something. Any ideas?

A: After a couple of hours researching Go's structure alignment strategy and all kinds of other low level stuff, I finally realized that I had incorrect values for RAWINPUTDEVICE.UsUsagePage! Elements 2, 3, and 4 should have UsUsagePage set to 0x0D instead of 0x00! Oh well, at least I learned a lot about how Go aligns structure elements to word boundaries!


text:
Q: re.sub replaces only first two instances I have found this interesting issue with re.sub:
import re

s = "This: is: a: string:"
print re.sub(r'\:', r'_', s, re.IGNORECASE)

>>>> This_ is_ a: string:

Notice how only the first two instances were replaced. It seems that adding the [implicit] argument name for flags fixes the issue.
import re

s = "This: is: a: string:"
print re.sub(r'\:', r'_', s, flags=re.IGNORECASE)

>>>> This_ is_ a_ string_

I was wondering if anyone could explain it or it is in fact a bug.
I've encountered this issue before with the missing argument name string but never for flags and with string it usually blows up.

A: The fourth argument to re.sub is not flags but count:
>>> import re
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the match object and must return
    a replacement string to be used.

>>>

This means that you need to explicitly do flags=re.IGNORECASE or otherwise re.IGNORECASE will be treated as an argument to count.
Additionally, the re.IGNORECASE flag is equal to 2:
>>> re.IGNORECASE
2
>>>

So, by doing count=re.IGNORECASE in your first example, you told re.sub to only replace 2 occurrences of : in the string, which it did.


text:
Q: All categories for each week and group Hi I have a data source as such
Data:

Weeknum
Group
Priority
Total

202106
A
High
10

202106
B
Medium
15

202107
A
Medium
88

Priorities:

Priority

High

Medium

Low

The data has already been grouped such that each weeknum+group+priority is unique. What I need to do is return the full list of priorities for each week/group including zeros:

Weeknum
Group
Priority
Total

202106
A
High
10

202106
A
Medium
0

202106
A
Low
0

202106
B
High
0

202106
B
Medium
15

202106
B
Low
0

202107
A
High
0

202107
A
Medium
88

202107
A
Low
0

It doesn't matter if it also returns records for 202107/B as well but it must return a record for each priority.
Any help appreciated. :\

A: Use a cross join to generate the rows and then left join to bring in the columns you want:
select wg.weeknum, wg.group, p.priority,
       coalesce(t.total, 0) as total
from (select distinct weeknum, group
      from t
     ) wg cross join
     priorities p left join
     t
     on t.weeknum = wg.weeknum and t.group = wg.group and
        t.priority = p.priority;


text:
Q: Authorize data access at database level From the question title you might guess what is this about. I'll try to describe what I currently have and what I want to archive.
Suppose an application that handles four entities: User, Team, Repository and Document. The relationships between those entities are:

*

*Each user belong to zero or more teams.

*Each document belong to one repository

*An user may own zero or more repositories

*Each repository can be created as public or private

*The content of a public repository is visible to all users who share a team with the repository's owner.

*A private repository is only visible to it's owner.

Accessing documents of an user is not a problem, those are all documents stored in repositories that he owns. But the thing get complicated because what I really need is all documents visible to an user, this is all it's documents plus those documents other people made public and share a team with him.
Currently I'm enforcing this authorization mechanism in the Data Access Layer. This implies fetching all documents and do some filtering following rules above. I'm aware that this implementation is not scalable and I wonder if I can improve my database model by moving the authorization logic to the database. This way the filtering will be done by the DB engine and only requested entities will be returned to the client code.
This question is not tied to an specific implementation, but I'll tag it for the specific tools I'm using. Maybe it can be useful for someone's answer.

A: First let me explain why using entity framework (or another ORM tool) is more elegant than using stored procedures.
Stored Procedures are evil. That's why. As the link explains in detail, stored procedures tend to grow as a second BL and are therefore difficult to maintain. A simple task as renaming a column will become a big task when this column is used in multiple stored procedures. When you use a ORM tool, visual studio will do most of the work for you.
That said brings me to the second advantage of entity framework. You can compose your query by using your favorite .net language. Entity framework will not execute your query directly. You control when the query will be executed as you can read here. When doing this entity framework will compile your Linq statements to a complete tsql statement and run this against the database. So there is absolutely no need to fetch all data and loop through each record.
Tip: Move your cursor over the variable name and ef will give you a preview of the TSQL statement it will compile.
So how should your Linq query look like? I composed a test database based on your description and made an entity framework (ef6) model of it which looks like:

This Linq query will do what you want, at least as I understood your question correctly.
private IEnumerable<Document> GetDocumentsOfUser(Guid userId)
    {
        using (var db = new DocumentRepositoryEntities())
        {
            // Get owned repositories by the user
            var ownedRepositories = db.Repositories
                          .Where(r => r.Owner.UserId == userId);

            // Get all users of teams the user belongs to
            var userInOtherTeams =
                 db.Users.Where(u => u.UserId == userId)
                        .SelectMany(u => u.Teams)
                        .SelectMany(t => t.Users);

            // Get the public repositories owned by the teammembers
            var repositoriesOwnedByTeamMembers =
                userInOtherTeams.Where(u => u.Repositories.Any())
                                .SelectMany(u => u.Repositories)
                                .Where(r => !r.Private);

            // Combine (union) the 2 lists of repositories
            var allRepositories = ownedRepositories.Concat(
                                  repositoriesOwnedByTeamMembers);

            // Get all the documents from the selected repositories
            return allRepositories.SelectMany(r => r.Documents)
                                  .Distinct()
                                  .ToArray(); //query will be composed here!
        }
    }

Note that the linq statement will be compiled to a TSQL select statement when the call to .ToArray() is made.

A: Based on your description, the goal is to find all of the repositories that the user currently has access to, then retrieve the documents from each of those repositories.
If this were my implementation, I would add a stored procedure to the database that accepts the current user's ID, then gathers the list of accessible repositories into a local table variable, then select from the documents table where the repository for the document is in the list of accessible repositories.
DECLARE
  @Teams TABLE (TeamID UNIQUEIDENTIFIER NOT NULL PRIMARY KEY (TeamID))

DECLARE
  @Repositories TABLE (RepositoryID UNIQUEIDENTIFIER NOT NULL PRIMARY KEY (RepositoryID))

  /* Get the list of teams the user is a member of */
INSERT INTO @Teams
SELECT Teams.TeamID
  FROM Teams INNER JOIN TeamUsers ON Teams.ID = TeamUsers.TeamID
 WHERE TeamUsers.UserID = @UserID

  /* Get the list of repositories the user shares a team member with */
INSERT INTO @Repositories
SELECT RepositoryID
  FROM Repositories
 WHERE OwnerID = @UserID
    OR (OwnerID IN (SELECT DISTINCT TeamUsers.UserID
                     FROM TeamUsers INNER JOIN @Teams ON TeamUsers.TeamID = @Teams.TeamID)
       AND IsShared = 1)

  /* Finally, retrieve the documents in the specified repositories */
SELECT Documents.*
  FROM Documents INNER JOIN @Repositories ON Documents.RepositoryID = @Repositories.RepositoryID

A: While the answer competent_tech suggests is valid, and good if your need is a one-off, what you would ideally want to do is implement your authorization requirements in a dedicated layer, in an externalized fashion. Reasons to do this include:

*

*easier to maintain a decoupled architecture

*you can update your authorization without touching your application and/or database

*you do not need SQL / stored procedure knowledge

*you can report more easily on what authorization is applied where: this is important if you have auditors breathing down your neck.

To achieve externalized authorization (see here for a Gartner report on the topic), you need to consider attribute-based access control (ABAC - see here for a report on ABAC by NIST) and the eXtensible Access Control Markup Language (XACML - more info here) as a means to implement ABAC.
If you follow the ABAC approach you get:

*

*a clean, decoupled architecture with the notion of

*

*an enforcement point or interceptor that will sit between your application and  your database (in the case of ABAC applied to databases)

*an authorization decision engine that reaches decisions and will produce a filter statement (a WHERE clause in the case of a SQL database) that the enforcement point will append to the original SQL statement

*a policy-based and attribute-based authorization model whereby you can write authorization requirements in easy-to-understand statements instead of procedures, PL-SQL or other SQL artefacts. Examples include:

*

**a user can edit a document they own

*a user can view documents if the user's team == the document's team

*a user can view documents of another team if and only if the documents are marked as public

*a user with the role editor can edit documents that belong to their team if and only if the document state is draft*

In the above examples, the user type, the resource type (document), the action (view, edit), the document's team, the user's team, and the document's visibility (private or public) are all examples of attributes. Attributes are the lifeline, the building blocks of ABAC.
ABAC can easily help you implement your authorization requirements from the simplest ones to the more advanced ones (such as can be found in export regulations, compliance regulations, or other business rules).
One neat benefit of this approach is that it is not specific to databases. You can apply the same principle and policies to home-grown apps, APIs, web services, and more. That's what I call the any-depth architecture / approach to externalized authorization. The following diagram summarizes it well:

The PDP is your centralized authorization engine.


text:
Q: Strange symbols in string in PDF but not in string? I am printing a string to a PDF. When I var_dump the string it looks pretty normal, no special chars or symbols are printed. After printing it to a PDF, it looks like this though:
https://screenshots.firefox.com/Fo1oucu7rCBnfdoc/null
As you can see, it prints something that looks like a closing button twice, sometimes once, but its always somewhere. Where it appears there is nothing visible in the string which could be replaced by this. This is the code I use for printing:
$text[] = $myText;
foreach ($text as $part) {
    $page->drawText(strip_tags(ltrim($part)), 285, $y - 50, 'UTF-8');
    $y -= 15;
}

If I fill $myText with just some static string, it works perfectly, no strange symbols are shown. Any ideas how to fix that?
Thanks!


text:
Q: Plotting multiple store sales into 1 plot I have problem plotting multiple timeseries into 1 plot.
My dataframe looks like this:

So I want all 10 stores plotted into 1 plot, such that all stores have different colours, with the end product looking like this:

So far I've tried with the foloowing code, but it does not work:
store_daily_sales = train.groupby(['store', 'date'], as_index=False)['sales'].sum()
plt.figure(figsize=(12,8), dpi = 150)
plt.plot(store_daily_sales)
plt.title = ('Daily sales')
plt.xlabel('Date')
plt.ylabel('sales')
plt.show()

Can anybody help?

A: I think you're best off reformatting a bit first and then plotting. Hopefully this does the trick:
reformat = pd.pivot(train,values='sales',index='date',columns='store')
reformat.plot()


text: Q: How to use SNMP with Java? I'm writing an application that accesses a network printer. As a part of that application, I need to know the "status" of the printer. The only way the printer advertises its status is through SNMP. Java itself doesn't have any tools that speak the SNMP protocol, so I'm not sure what to do. How can I access the printer's SNMP status updates from a Java application?


text:
Q: Java battleship program not printing board correctly I am having a problem with my java battleship program not printing the coordinates that the user enters. When the user guesses a spot on the board its supposed to update the space with an "X" if its a hit, if not then the board remains the same. But when a user guesses wrong on my program, it prints everything except the space where the user guessed. I believe that my else statement where the board updates is the problem, but any modification I did resulted in the board not printing anything.
import java.util.Random;
import java.util.Scanner;

class Battleship {
     public static char randChar(){
         final String alphabet = "ABCDE";
         final int N = alphabet.length();
         char rand;
         Random r = new Random();
         rand = alphabet.charAt(r.nextInt(N));
         return rand;
    }

    public static void main (String[] args) throws java.lang.Exception {
        char[] letters = {' ', 'A', 'B', 'C', 'D', 'E'};
        int[] numbers ={1, 2, 3, 4, 5};
        int[][] ships = new int[7][2];
        char colGuess;
        int rowGuess;
        Boolean boardFlag=false;
        Scanner scan = new Scanner(System.in);
        //creates the board
        for (int i = 0 ; i <= 5 ; i++) {
            for (int j = 0 ; j <= 5 ; j++) {
                if (i == 0) {
                    System.out.print(letters[j] + " ");
                }
                else if (j == 0) {
                    System.out.print(numbers[i - 1]);
                }
                else {
                    System.out.print(letters[j] + "" + numbers[i-1]);
                }
                System.out.print(" ");
            }
        System.out.println();
        }
        //assigns ships to random spots
        assignShips(ships);
        System.out.println("Enter your guess for the column:");
        colGuess = scan.next().charAt(0);
        //converts to uppercase
        colGuess = Character.toUpperCase(colGuess);
        System.out.println("Enter your guess for the row:");
        rowGuess = scan.nextInt();
        //shows player what they entered
        System.out.println("you entered: " + (char) colGuess + rowGuess);
        //calls method to check for a hit
        fire(colGuess, rowGuess, ships);
        boardFlag = fire(colGuess, rowGuess, ships);
        System.out.println(boardFlag);
        //updates the board
        for (int i = 0 ; i <= 5 ; i++) {
            for (int j = 0 ; j <= 5 ; j++) {
                if (i == 0) {
                    System.out.print(letters[j] + " ");
                }
                else if (j == 0) {
                    System.out.print(numbers[i - 1]);
                }
                else {
                    if(letters[j] == colGuess && numbers[i - 1] == rowGuess) {
                        if(boardFlag==true) {
                            System.out.print(" " + "X");
                        }
                    }
                    else {
                        System.out.print(letters[j] + "" + numbers[i - 1]);
                    }
                }
                System.out.print(" ");
            }
            System.out.println();
        }
    }

    public static void assignShips(int[][] ships) {
        Random random = new Random();
        for(int ship = 0; ship < 7; ship++) {
            ships[ship][0] = randChar();
            ships[ship][1] = random.nextInt(5);
            //gives location of ships, for testing purposes
            System.out.print("Ship:" + (ship+1)+ " is located at"+(char)ships[ship][0]+ships[ship][1]+"\n");
        }
    }

    //checks user input to see if we have a hit
    public static Boolean fire(char colGuess, int rowGuess, int[][] ships) {
        Boolean hitFlag=false;
        for(int ship = 0; ship < ships.length; ship++){
            if(colGuess ==ships[ship][0] && rowGuess == ships[ship][1]){
                hitFlag=true;
            }
        }
        if(hitFlag == true) {
            System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
        }
        else {
            System.out.println("sorry chief we missed em");
        }
        return hitFlag;
    }
}

A: The reason its not showing up when you miss is because your net telling it to print anything.
if(letters[j] == colGuess && numbers[i-1] == rowGuess){
    if(boardFlag==true) {
        System.out.print(" "+"X");
    }
}

Your only handling the coordinate the user input if they hit. To fix this you would need an else statement after your if(boardFlag == true)to handle printing if you miss.

A: The problem is in your update board portion of the code because you don't do anything if the guessed location isn't a hit.
if(letters[j]==colGuess && numbers[i-1]==rowGuess && boardFlag) {
    System.out.print(" "+"X");
} else {
    System.out.print(letters[j]+""+numbers[i-1]);
}

Full Update Portion:
//updates the board
for (int i = 0 ; i <= 5 ; i++){
    for (int j = 0 ; j <= 5 ; j++){
        if (i == 0) {
            System.out.print(letters[j]+" ");
        } else if (j == 0){
            System.out.print(numbers[i-1] );
        } else {
            if(letters[j]==colGuess && numbers[i-1]==rowGuess && boardFlag){
                System.out.print(" "+"X");
            } else {
                System.out.print(letters[j]+""+numbers[i-1]);
            }
        }
        System.out.print(" ");
    }
    System.out.println();
}

A: This block (old version):
     if(hitFlag==true){
        System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
     } else {
        System.out.println("sorry chief we missed em");
     }

Should be (new version):
    if(hitFlag==true){
        System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
    } else {
        System.out.println("sorry chief we missed em at " + (char)colGuess+rowGuess);
    }

this will print:
sorry chief we missed em at D3      //D3 is a random possible set of coordinates

Rather than:
sorry chief we missed em            //Old version

So all you have to add is (char)colGuess+rowGuess, which prints the coordinates of your previous guess.

Comment if you have any questions!