text:
Q: UITextView with Syntax Highlighting How to do Syntax Highlighting in a UITextView, specifically syntax highlighting (and detection) for Objective-C on the iPhone?
Some of my ideas of how to do this:

*

*NSAttributedString. Now available in iOS 3.2 and greater. But how would I put a NSAttributedString into a UITextView?

*UIWebView. Overlay it when the user finished editing and color the text with CSS stylesheets. But how would I do this in a UIWebView, giving it the text and then coloring it?

A: UPDATE: Since iOS 7 and TextKit, syntax highlighting has become easy as pie. Look no further than here for an introduction (by me).

Assuming that you want an editable component, there is not too much hope. Giving a quick overview, just to make sure I cover everything:

*

*UITextView: plain text only, no (public) way around. But editable. No chance to alter anything, no chance to get geometry etc. Uses a web view internally. Each paragraph is a <div>, which is altered by the editing engine. You could change the DOm in there but that's all private API. All private, hence no option.

*UIWebView: html, so it can be styled, have embedded images, etc. I guess (without looking into it) that this is what the previously mentioned Three 20 UI uses. The problem: cannot be edited. There's no (public) way around that. You canot get selections, acces the DOM, etc without private API and a lot of headaches. Editing would work like in UITextView but require a whole new level of headache. Still: private.

*CoreText Framework: Since iOS 3.2 a very very good rendering engine. But that's it. Can directly layout and render NSAttributesStrings. However, there is no user interaction. No text selection, no text input, no spell checking, no replacements, no highlights, no no no no no. Just rendering. And quite a bit of work to make it fast on old devices with long texts.

*UITextInput Protocol: Allows interaction with the keyboard and to grab text input. Also features basic text replacements. Problem: text input only, badly documented. No text selection etc (see above).

So here we are. Two fully functional components that lack a central function and two partial solutions that lack the missing link. Here are all viable approaches I can come up with:

*

*Have the user edit a UITextView unstyled and display the content styled in a UIWebView. For the latter you can use the Three20 thing.

*Build the missing link between CoreText and UITextInput. This includes, but is not limited to, text selection, highlight, background colors, text storage & management, efficiency, spell checking etc. Some of these are provided by system frameworks but still need a lot of integration.

*File a bug and wait for a nice public API to come (my personal approach).

*Convince Apple to allow private API again and mess with UItextViews DOM.

The Omni Group has taken the second approach and created an editable text view. You can find it in the OmniUI framework. However, this implementation is far from perfect. (at least it was when I last checked a few months ago). They tried hard but still didn't manage to get to Apples perfection in user interaction. Apple must have invested at least a few man-years into doing only the UI-interaction with text selection and editing. Nothing to be done at home, and as it seems even for companies as the omni group.
There is a interesting aspect to all of this: iWork. Apple claims to not use any private API in them. But the text selection is the very same as in the OS. So they must have copied framework source into the apps. Very honest approach ;)

A: JTextView is a UITextView replacement that supports an NSAttributedString text store. It allows the display of rich text but is incomplete.

A: If anybody is still looking for a complete solution for this, I know two libraries that provides this:

*

*Highlightr: A Swift library for syntax highlighting, supports hundreds of languages but uses JS as backend. It's fast enough for live editing, though. (Disclaimer: I am the creator of this library).

*SyntaxKit: A native solution by Sam Soffes, but on early stages of development. Should support any TextMate syntax in the future. This should be the way to go when the library is mature enough.

A: Since iOS 5 you can use a UIWebView and set contenteditable="true" on a div in it. This makes the UIWebView open a keyboard up and allow the user to directly input text into the DOM. You can then write a webapp that does syntax highlighting. You can communicate with the cocoa app with custom URLs.
The only issue I have is you don't seem to get spellchecking.

A: I don't know much about syntax detection, but if you want to have multiple styles in the same UITextView, then Three 20 UI is a thing that you should look at
Here is another question that may relate to you: What is the best way to implement syntax highlighting of source code in Cocoa. I am not sure if it is Mac or iPhone but I think if you combine this and Three20, then you can have your own in iPhone. Good luck


text:
Q: Simple Slideshow on Hover, Slideshow stops on mouseleave This is my first post. My code works in chrome and safari, but the slideshow won't stop in firefox. I want to show a live version of this code to make it easier, but I'm working locally. I'm wondering if its because I wrote it with hover instead of mouseover and mouseleave, but I dont know how to write it out correctly that way. There may even be an error in this code, but the browser is not detecting it.
HTML:

jQuery:
jQuery(document).ready(function($) {

$(".fadelinks").each(function(){
    var $this = this;
    $($this).hover(function(){

      $('> :gt(0)', $this).hide();
      timer = setInterval(function(){$('> :first- child',$this).fadeOut()
      .next().fadeIn().end().appendTo($this);}, 1500);
      }, function() {
      clearInterval(timer);

    });

  });

});

A: a simpler way to achieve is to add onmouseover = "mouseoverFunction();" onmouseout = "mouseoutFunction()" to each img tag
then in javascript
mouseoverFunction()
loop through image array
show next
wait
mouseoutFunction()
stop looping
you do not need the a tags

A: well you want that on mouse hover your images start sliding here is another code i am not so good in jquery but here is the code:
css
   #fadelinks{
   width: 100px;
   height: 100px;
   overflow: hidden;
}

set your image height and width equal to the width and height of fadelinks
HTML

<button onclick="slid1">image1<button>
<button onclick="slid2">image2<button>
<button onclick="slid3">image3<button>
<button onclick="slid4">image4<button>

jquery
 var slide1 = function(){

    $(document).ready(function(){
      $("#same1, #same2, #same3, #sam4").fadeout(100);$("#same1").fadeIn();
    });
}
  var slide2 = function(){

    $(document).ready(function(){
      $("#same1, #same2, #same3, #sam4").fadeout(100);$("#same2").fadeIn();
    });
} var slide3 = function(){

    $(document).ready(function(){
      $("#same1, #same2, #same3, #sam4").fadeout(100);$("#same3").fadeIn();
    });
} var slide4 = function(){

    $(document).ready(function(){
      $("#same1, #same2, #same3, #sam4").fadeout(100);$("#same4").fadeIn();
    });

you will understand what will this do but as i told you i am not so good in jquery so i have done this in you know in noob style. but from this you might get the idea and you can intregate this with event handler  mousehover and mouseout and also use setinterval to slide automatically.
thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: if {} in if: endif Why it won't work? Appears Parse error: syntax error, unexpected ':' ... on line 7
$a = 0; $b = 1; $c = 3; $d = 4;
if ($a == $b):
   if ($b == $c) {
       // something
   }
else:
   $c = $a;
endif;

But if i change it to (just added else statement):
$a = 0; $b = 1; $c = 3; $d = 4;
if ($a == $b):
   if ($b == $c) {
       // something
   } else {
       // something
   }
else:
   $c = $a;
endif;

It works fine.
Why is that? isn't it a PHP bug? Or there is a rule about if...else i should know?
Anyway, i'm using PHP 5.3.3 version.

A: I am not sure if I would call this is a bug, but I believe you're having this issue because of a dangling else, in conjunction with your mixed if-else syntax:
if ($a == $b):            // 1
    if ($b == $c) {       // 2
        // something      // 3
    }                     // 4
else:                     // 5 - this else
    $c = $a;              // 6
endif;                    // 7

Note how the else on line 5 is ambiguous: it could "belong" either to the first or second if statements.
You can easily remove that ambiguity and fix your syntax error by adding a semicolon after your nested if:
if ($a == $b):            // 1
    if ($b == $c) {       // 2
        // something      // 3
    };                    // 4 - here
else:                     // 5
    $c = $a;              // 6
endif;                    // 7

On another note, please don't use this syntax unless you want your fellow programmers to bludgeon you to death in your sleep.

A: As mentioned in comments on the PHP manual's control structure page the parser appears to not always assume that an if from one style should not be matched with an else using the other.

A: The colon form of the if/else can be ambiguous when dealing with nested ifs.  In your example the else is being attached the the second if (as it should.)  In order to avoid this you must explicitly let the interpreter know that that else is paired with the first if, either by adding an else to the second if (as you show in your second code block), or using {} to explicitly define the control flow.
In other words, you can use multiple forms of if statements. For example:
if (foo):
  //statements
else {
  //statements
}

Is perfectly valid.  Although I would advise against mixing forms since it takes away from the readability.

A: By PSD standards, always use brackets.
$a = 0;
$b = 1;
$c = 3;
$d = 4;
if ($a == $b) {
    if ($b == $c) {
        // something
    } else {
        $c = $a;
    }
}

Its more readable, safer and clear.


text:
Q: Content Editor Webpart and SharePoint 2007 object model? I have to supply the query and should display the information  on the SharePoint 2007 page based on the Enterprise Search Results. I wonder, if it can be achieved through Content Editor WebPart ?
Want to display the Related info like it works in sharepointoverflow when we enter the title.

A: In order to pull that off in a CEWP, you are going to have to use some combination of AJAX and/or jQuery with the SharePoint Web Services.
It's a lot of work. A couple of references related to the search web service:
http://msdn.microsoft.com/en-us/library/ms543175(v=office.12).aspx
http://www.mosssearch.com/searchwebservice.html

A: Why do you want to use the CEWP and not use the CQWP instead?


text:
Q: Migrating a CXF client that uses "simple frontend" to JAX-WS I have a web service client written with Apache CXF, that uses the simple frontend style. It can dynamically invoke a method on a remote web service, given its location and the interface implemented by the service.
public static void callWsMethod(Class<?> serviceInterface, String address, String methodName,...) {
    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    factory.setServiceClass(serviceInterface);
    factory.setAddress(address);
    Object instance = factory.create();
    ... /*invoke method "methodName" on instance */

I want to migrate this code to a pure JAX-WS implementation. My code should look something like:
public static void callWsMethod(Class<?> serviceInterface, String address, String methodName,...) {
    URL wsdlLocation = new URL(address + "?wsdl");
    QName serviceName = new QName( .... , ....); //??? what goes here
    Service service = Service.create(wsdlLocation, serviceName);
    Object instance = service.getPort(serviceInterface);
    ... /*invoke method "methodName" on instance */

I suspect that this is possible because the CXF doc cited above says:

In a 'simple' case, very nearly identical things happen in the Simple front end as in JAX-WS.

My first problem is the QName constructor:
QName(java.lang.String namespaceURI, java.lang.String localPart)

how does CXF figure out the right namespaceURI and localPart to invoke the ws?

A: Do you have a WSDL?
namespaceUri = /wsdl:definitions/@targetNamespace
localPort = /wsdl:definitions/wsdl:service/@name

If you have a WSDL. Why not simply generate the SEI classes using wsimport? You'll see the generated automatically contains the right QName.


text:
Q: getting whitespaces when concatenating strings I am trying to concat a string variable into another string but I keep getting white spaces before and after the variable
objwriter.WriteLine("netsh int ipv4 Set address "+adaptername+" dhcp")
Output is the following
netsh int ipv4 Set address  Wi-Fi  dhcp

I have tried the following methods to concat the string also
objwriter.WriteLine("netsh int ipv4 Set address "& adaptername &" dhcp")
objwriter.WriteLine("netsh int ipv4 Set address "" & adaptername & "" dhcp")

A: objwriter.WriteLine("netsh int ipv4 Set address " & adaptername.Trim() & " dhcp")

A: TRY THIS
VB.Net
objwriter.WriteLine("netsh int ipv4 Set address " &  adaptername.Trim() & " dhcp")

C#
objwriter.WriteLine("netsh int ipv4 Set address " +  adaptername.Trim() + " dhcp");


text:
Q: How to use function_score on nested geo_point field I've been trying to use function_score on nested geo_type but Elasticsearch always returns documents with _score = 1.
My mapping
{
   "myindex": {
      "mappings": {
         "offers": {
            "properties": {
               "country_id": {
                  "type": "long"
               },
               "created_at": {
                  "type": "date",
                  "format": "yyyy-MM-dd HH:mm:ss"
               },
               "locations": {
                  "type": "nested",
                  "properties": {
                     "city": {
                        "type": "string",
                        "store": true,
                        "fields": {
                           "city_original": {
                              "type": "string",
                              "analyzer": "keyword_analyzer"
                           }
                        }
                     },
                     "coordinates": {
                        "type": "geo_point"
                     }
                  }
               }
            }
         }
      }
   }
}

The problem is that some of documents can have empty coordinates. My query:
GET /myindex/offers/_search?explain
{
   "query": {
      "nested": {
         "path": "locations",
         "query": {
            "function_score": {
               "functions": [
                  {
                     "filter": {
                        "exists": {
                           "field": "locations.coordinates"
                        }
                     },
                     "gauss": {
                        "locations.coordinates": {
                           "origin": {
                              "lat": 49.1,
                              "lon": 17.03333
                           },
                           "scale": "10km",
                           "offset": "20km"
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}

As I said, Elasticsearch returns documents with _score = 1 and explanation: Score based on child doc range from 21714 to 21714
What am I doing wrong? My version of Elastisearch is 1.7.


text:
Q: Database import from text/csv file and many to many relationship I have a Windows SQL Server database with a many-to-many relationship between some articles and categories, the relation is made by an ArticleCategorie table with two columns => [ArticleID] - [CategorieID].
The problem now is that I have a csv file which look like this (*picture) with two columns article id and article tags (let's say the article id is 5; and that it has 4 different categories which has respectively id 1,4,6 and 7) so here is how the CSV looks like =>
   |ArticleID----|Article Categories---|
   |5------------|1,4,6,7--------------|

*Picture :

The best way I found was to manually add to the table all data (articles + categories) like this :

So this is above the final result that I want.  Unfortunately I have more than seven hundreds articles, and can't find any faster way to import them, any solutions ? How can I import my data in a fast way? Maybe I could go for a better database design ?

A: Its not an elegant solution but it works. Import the data from the csv file to a temporary table using openrowset or import data. Then run the following code
declare @aid varchar(88)
declare @cid varchar(88)
declare @cur as cursor
SET @cur = CURSOR FOR(SELECT * FROM temp)
open @cur
FETCH NEXT FROM @cur INTO @aid,@cid
while @@FETCH_STATUS=0
BEGIN
insert into article select @aid,value from dbo.Split(',',@cid)
FETCH NEXT FROM @cur INTO @aid,@cid
END
CLOSE @cur
DEALLOCATE @cur

Here is the code for the split() function
CREATE FUNCTION [dbo].[Split] (@sep char(1), @s varchar(5120))
RETURNS table
AS
RETURN (
WITH pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT
pn + 1,
stop + 1, CHARINDEX(@sep, @s, stop + 1)
FROM pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 5120 END) AS Value
FROM pieces
)


text:
Q: How to place footnotes in rmarkdown html under specific header? I want to place Rmarkdown footnotes under the header Endnotes. Whereas References can be placed with

, that method seems not to work with footnotes, though. I opened the html document produced by Rmarkdown that revealed footnotes are collected under a tag called

. I also tried

, but that won't work either. How do I do this right?
Code I'm using:
---
output: html_document
references:
- id: hawking_thermodynamics_1983
  author:
  - family: Hawking
    given: S. W.
  - family: Page
    given: Don. N.
  publisher: Communications in Mathematical Physics
  title: Thermodynamics of Black Holes in Anti-de Sitter Space.
  volume: 87
  type: article-journal
  issued:
    year: 1983
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Section 1
Lorem ipsum dolor^[always look on the bright side of life] sit amet, consetetur
sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna
aliquyam erat, sed diam voluptua [@hawking_thermodynamics_1983].

## Endnotes

## References

## Appendix
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.

Output produced:

Expected output:
Section 1
Lorem ipsum dolor1 sit amet, consetetur
sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua (Hawking and Page 1983).
Endnotes

*

*always look on the bright side of life

References
Hawking, S. W., and Don. N. Page. 1983. "Thermodynamics of Black Holes in Anti-de Sitter Space." 87.
Appendix
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.

A: In the context of a HTML document, JavaScript can be used.
For instance, this Rmd file renders as you want.
---
output: html_document
references:
- id: hawking_thermodynamics_1983
  author:
  - family: Hawking
    given: S. W.
  - family: Page
    given: Don. N.
  publisher: Communications in Mathematical Physics
  title: Thermodynamics of Black Holes in Anti-de Sitter Space.
  volume: 87
  type: article-journal
  issued:
    year: 1983
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Section 1
Lorem ipsum dolor^[always look on the bright side of life] sit amet, consetetur
sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna
aliquyam erat, sed diam voluptua [@hawking_thermodynamics_1983].

## Endnotes {#endnotes}

## References

## Appendix
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.

```{js, echo=FALSE}
$(document).ready(function() {
  $('.footnotes ol').appendTo('#endnotes');
  $('.footnotes').remove();
});
```

Here, the JS script moves the list of footnotes in the endnotes section and finally removes the footnotes section.


text:
Q: executing stored requests in a table and getting the values into a variable I have a table T1 with a column 1 where I store some SQL requests in the pattern " select Var1 from T2". But the problem is that when I put "select A1 from T1" I get the request only in a form of a string. Is there any way to execute the requests stored in the column A1 and return the value into a variable ??
Thanks for Help in Advance :)

A: You can dynamically create a SQL statement and then run that command
CREATE TABLE dbo.test89
 (
  Id int,
  Var1 nvarchar(1)
  )

INSERT dbo.test89
VALUES(1, 'A'),
      (2, 'B')

CREATE TABLE dbo.test90
 (
  Id int,
  Col1 nvarchar(max)
  )

INSERT dbo.test90
VALUES(1, 'SELECT Var1 FROM dbo.test89')

DECLARE @dsql nvarchar(max)
DECLARE @varTable TABLE(Var1 nvarchar(1))
SELECT @dsql = Col1
FROM dbo.test90
WHERE Id = 1
INSERT @varTable
EXEC sp_executesql @dsql
SELECT *
FROM @varTable


text:
Q: Extract rows and columns of a tensor using indices I have a 2-D tensor x, which is a placeholder x = tf.placeholder(tf.int32, shape=[None, 100]).
Now in the graph, I want to extract randomly 50% rows of x.
Here is what I tried:
idxs = tf.range(tf.shape(x)[0])
ridxs = tf.random_shuffle(idxs)[: int(tf.shape(x)[0] * 0.5)]
x = tf.gather(x, ridxs, axis=0)

It throws the following error:
Traceback (most recent call last):
  File "main_gcn_random_sampling.py", line 76, in <module>
    model = GCN_RANDOM_SAMPLING(FLAGS.learning_rate, num_input, num_classes, hidden_dimensions=hidden_sizes, act=tf.nn.relu)
  File "/home/tiendh/Projects/EPooling/gcn_random_sampling.py", line 63, in __init__
    ridxs = tf.random_shuffle(idxs)[: int(tf.shape(x)[0] * 0.5)]
TypeError: unsupported operand type(s) for *: 'Tensor' and 'float'

I could declare another placeholder for predefined indices, but it would look ugly. Any other suggestion?

A: That's almost right, but:

*

*You have to cast to tf.shape(x)[0] to float before multiplying by 0.5.

*You cannot use int to cast a tensor data type, you need to use tf.cast.

idxs = tf.range(tf.shape(x)[0])
num_half_idx = tf.cast(tf.cast(tf.shape(x)[0], tf.float32) * 0.5, tf.int32)
ridxs = tf.random_shuffle(idxs)[: num_half_idx]
x = tf.gather(x, ridxs, axis=0)

Note that, if you are always getting a 50% of the rows, you can also simply do:
idxs = tf.range(tf.shape(x)[0])
ridxs = tf.random_shuffle(idxs)[: tf.shape(x)[0] // 2]
x = tf.gather(x, ridxs, axis=0)


text:
Q: Cocktail Party/Graph Theory Problem 15 people are at a party. If in every group of 3 people, at least 2 do not know each other, what is the greatest possible number of pairs of people that know each other?
I've been working on this for days and I've looked around but I can't seem to solve it.

A: Hint: Represent each person with a vertex, and make two vertices adjacent to one another if and only if the two corresponding people know one another. Then the property that in every group of 3 people at least two do not know each other is equivalent to the resulting graph being triangle-free. Now see Mantel's Theorem.


text:
Q: Auth::attempt() does not return anything I'm using laravel 4.
This is my Seeder
User::create(array(
        'name'     => 'Rubber Gajulu',
        'username' => 'awesome',
        'email'    => 'awesome@awe.com',
        'password' => Hash::make('awesome'),
    ));

And this is where I am testing the Auth::attempt() function
Route::get('testlogin',function(){

$userdata = ['email'=> 'awesome@awe.com','password'=> 'awesome'];

echo Auth::attempt($userdata);

if (Auth::attempt($userdata))
    echo 'SUCCESS!';
else
    echo 'FAILURE!';
});

It just returns FAILURE. The first echo does not return anything.

A: Your controller code is wrong. It should be this:
Route::get('testlogin',function(){

$userdata = ['email'=> 'awesome@awe.com','password'=> 'awesome'];

if (Auth::attempt($userdata))
    echo 'SUCCESS!';
else
    echo 'FAILURE!';
});

Otherwise in your current code you are trying to login the user twice, so the second one fails.

A: Check if logs/laravel.log shows any error on hitting this url.
Share that.

A: Okay I found my mistake
Thanks to Isabell Knauers answer
My model had
$table->string('password',32)

Data was being truncated to 32 characters. Now I changed it to
$table->string('password',100)

and everything works as intended


text:
Q: Big O notation compare with itertools.product and for loop I have two array of integers and I want to the minimum absolute difference between any elements from two array. I have two different way to do it. Both seems pretty much the same, but I do not understand what is Big O notitaion for two methods.
are they both are O(mk)?
list1 = [1,3,7,12]
list2 = [11,39,9,-1]
from itertools import product
def method1(l1,l2):
    return min([abs(x[0]-x[1]) for x in product(l1, l2)])

def method2(l1,l2):
    num = []
    for i in l1:
        for j in l2:
            num.append(abs(i-j))
    return min(num)
print(method1(list1,list2))
print(method2(list1,list2))

A: Yes. Both methods are exaclty the same
Suggestion for method1:
def method1(l1,l2):
    return min([abs(a - b) for a, b in product(l1, l2)])


text:
Q: UITextfield value for each indexpath.row My uitableview consists of 10 cells and each cell has 2 uitextfield's.
I need to take values from each uitextfield in each cell and add it to an array
// my custom cell
class MatchTableViewCell: UITableViewCell, UITextFieldDelegate {
@IBOutlet weak var Team2Score: UITextField!
@IBOutlet weak var Team1Score: UITextField!
@IBOutlet weak var Team2: UILabel!
@IBOutlet weak var Image2: UIImageView!
@IBOutlet weak var Image1: UIImageView!
@IBOutlet weak var Team1: UILabel!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
}

A: Make sure in the cell initializer for tableviewcontroller that your using your custom cell name and that you've set your identifier correctly. Then just initalize a cell and say something to the effect of
cell.Team2Score.text = "100"

A: you will need a global array to hold the strings. So..
var wordArray: [String] = []

you will need to add a button within the cell so when you hit the button it will add (append in the input of string (letters) to the array.
You need to add a tag to the button to know which cell it was clicked in.
button.tag = indexPath.row
@IBaction button(sender: UIButton){

var team2Words = Team2Score.text
wordArray.append(team2Words)

// do the samething for Team1Score
// you can use and if statement to check if one or the other one is empty

}

This will give you a lead


text:
Q: C++ CMake compilation error (/usr/bin/ld: cannot find ) *I know there are lots of questions about this, but they simply don't help much when talking about CMake, hence my decision of making the question *
So I was working on CLion which uses CMake in order to import and give parameters to the compiler, and successfully included (imported) an external library (cereal: to serialize classes into json files) located on a folder called "ExternalLibraries" which is on the root of my project folder. It was working just fine, untill I restarted the IDE and tried to ran the code again... It returned a compilation error (I think).
My CMake file looks like this:
cmake_minimum_required(VERSION 3.3)
project(xMemory)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

include_directories ("${PROJECT_SOURCE_DIR}/ExternalLibraries/cereal-1.1.2/include/")

set(SOURCE_FILES main.cpp xObject.cpp xObject.h)
add_executable(xMemory ${SOURCE_FILES})
target_link_libraries (xMemory cereal)

And when I try to run/compile the shell gives me this:
/home/lunaticsoul/Documents/clion-1.2.4/bin/cmake/bin/cmake --build /home/lunaticsoul/.CLion12/system/cmake/generated/95701c38/95701c38/Debug0 --target xMemory -- -j 4
Scanning dependencies of target xMemory
[ 33%] Building CXX object CMakeFiles/xMemory.dir/xObject.cpp.o
[ 66%] Building CXX object CMakeFiles/xMemory.dir/main.cpp.o
[100%] Linking CXX executable xMemory
/usr/bin/ld: cannot find -lcereal
collect2: error: ld returned 1 exit status
make[3]: *** [xMemory] Error 1
make[2]: *** [CMakeFiles/xMemory.dir/all] Error 2
make[1]: *** [CMakeFiles/xMemory.dir/rule] Error 2
make: *** [xMemory] Error 2

I'm not sure about what is happening cause the library seems to actually import into the code (There are no red letters when including cereal) and as I said before, I think it just stopped working.
Can someone tell me if there is something wrong with my CMake file?
PD: Here's a screenshot just in case anyone need it.
PD2: I'm using elementary os: Freya (Ubuntu 14.04)

A: You should use
link_directories(directory1 directory2 ...)

directive to specify library directories.
https://cmake.org/cmake/help/v3.0/command/link_directories.html

A: I'm a bit late to the party, but maybe this will help someone.
I had a very similar issue with googletest:
dpoliaru@host:~/Documents/test/gtest/build$ make
Scanning dependencies of target s1
[ 50%] Building CXX object CMakeFiles/s1.dir/s1.cpp.o
[100%] Linking CXX executable s1
/usr/bin/ld: cannot find -lgtest
/usr/bin/ld: cannot find -lgmock
/usr/bin/ld: cannot find -lgtest
/usr/bin/ld: cannot find -lgmock
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/s1.dir/build.make:84: s1] Error 1
make[1]: *** [CMakeFiles/Makefile2:73: CMakeFiles/s1.dir/all] Error 2
make: *** [Makefile:84: all] Error 2
dpoliaru@host:~/Documents/test/gtest/build$

Here is an approach I used to debug it:
Make sure you can build manually:
compile:
g++ -c -m64 -I/home/dpoliaru/.local/lib/pkgconfig/../../include s1.cpp

and link:
g++ -L/home/dpoliaru/.local/lib/pkgconfig/../../lib s1.o -o s1 -lgtest -lgmock -lpthread

Make sure cmake properly locates libraries during generation stage:
dpoliaru@host:~/Documents/test/gtest/build$ cmake -L .. -D CMAKE_BUILD_TYPE=Debug
-- The C compiler identification is GNU 9.2.1
-- The CXX compiler identification is GNU 9.2.1
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found PkgConfig: /usr/bin/pkg-config (found version "0.29.1")
-- Checking for module 'gtest'
--   Found gtest, version 1.10.0
-- Checking for module 'gmock'
--   Found gmock, version 1.10.0
-- Configuring done
-- Generating done
-- Build files have been written to: /home/dpoliaru/Documents/test/gtest/build
-- Cache values
CMAKE_BUILD_TYPE:STRING=Debug
CMAKE_INSTALL_PREFIX:PATH=/usr/local
pkgcfg_lib_GMOCK_gmock:FILEPATH=/home/dpoliaru/.local/lib/libgmock.a
pkgcfg_lib_GMOCK_gtest:FILEPATH=/home/dpoliaru/.local/lib/libgtest.a
pkgcfg_lib_GMOCK_pthread:FILEPATH=/usr/lib/x86_64-linux-gnu/libpthread.so
pkgcfg_lib_GTEST_gtest:FILEPATH=/home/dpoliaru/.local/lib/libgtest.a
pkgcfg_lib_GTEST_pthread:FILEPATH=/usr/lib/x86_64-linux-gnu/libpthread.so
dpoliaru@host:~/Documents/test/gtest/build$

Finally, rin CMakeLists.txt, I updated linker directory search paths per @mustafagonlu advice using target_link_directories() cmake-commands(7).
target_link_directories(${PROJECT_NAME} PUBLIC ${GTEST_LIBRARY_DIRS} ${GMOCK_LDFLAGS})
And it worked.

A: it works if adding:
target_link_libraries (xMemory /library_build_path/libcereal.a)

details:
ld is looking for the libraries in a very short list of folders defined in
/etc/ld.so.conf

and it usually looks like following:
include /etc/ld.so.conf.d/*.conf

and actual paths list from those *.conf files usually is like:
# Legacy biarch compatibility support
/lib32
/usr/lib32
# Multiarch support
/usr/local/lib/x86_64-linux-gnu
/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu

if your project linking library is not in the folder of this list, ld won't find it unless either a special linking variable set LD_LIBRARY_PATH with the path to your library or a complete path/library name provided in cmake target_link_libraries directive.
details on how to proper setup LD_LIBRARY_PATH variable discussed here


text:
Q: how to make angularjs call to nodejs api and auth with stormpath The following code starts in angularjs, then is routed through node which then should make an external api call. What is happening, stormpath is intercepting the call and trying to authenticate it (the login screen is served...I checked res.data). I thought the app was good to go already since I had to login initially. I didn't define a route in ui-router because I want node to handle it and not angular. So, my question is how do I configure the different layers to handle the call.
angular -> node/stormpath -> external api
node route:
  app.use('/api/v1/accounts/:search', stormpath.groupsRequired(['dataentry']), apiAccounts.findAll);

stormpath setup:
  app.use(stormpath.init(app, {
     apiKeyFile: config.stormpathapi.apiKeyFile,
     application: config.stormpathapi.application,
     secretKey: config.stormpathapi.secretKey,
     sessionDuration: 1000 * 60 * 30,
     enableAutoLogin: true,
     enableUsername: true
  }));

angular code:
  $scope.getCustomers = function(chars) {
    var customers = [],
        url = 'api/v1/accounts/' + encodeURIComponent(chars) + '/';

    console.log('getCustomers: ' + url);
    try
    {
        //return $http.jsonp(url)
        return $http.get(url)
            .then(function(res) {
                if(angular.isArray(res.data))
                {
                    customers = res.data;
                }

                return customers;
            }, function (error) {
                console.log('Unable to load the customers: ' + error)
            });
    }
    catch(e){
        console.log("error searching comapny: " + e);
    }

}

The url is correctly formated. If I make the call in a new browser window it works as expected (and authenticates me via stormpath api. I want this functionality so that no one can use the api without being logged into the app.
url format:
  http://localhost:3000/api/v1/accounts/ap/

res.data contains stormpath html:
   <!DOCTYPE html>

   <meta charset="utf- 8"><title>Log In</title><meta content="Log into your account!" name="description"><meta   content="width=device-width" name="viewport"><link href="//fonts.googleapis.com/css?    family=Open+Sans:300italic,300,400italic,400,600italic,600,700italic,700,800italic,800"    rel="stylesheet" type="text/css"><link    href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">


text:
Q: Setting path parameters in AWS API Gateway JavaScript SDK I'm trying to set path parameters when making calls to API Gateway endpoints via the JavaScript SDK and not having any luck.  It looks like I either have something misconfigured or there is a bug in the SDK generation.
I am able to successfully call endpoints that do not take path parameters but when I try to pass in a parameter to be used as a path parameter the SDK just replaces the path parameter with a blank and my call fails.
Example, assume client is a properly initialized API Gateway client.  I have an endpoint called /measurement with a child of /measurement/{id}.  I am able to call both directly.
client.measurementGet({},{}); - successfully calls my /measurement endpoint
client.measurementIdGet({"id": "1234"}, {}); - Browser makes a call to /measurement/ instead of /measurement/1234
Looking at the source of my apigClient.js, it appears that the SDK generator is not putting path parameters into the list of parameters that it's looking for.  For example, the code of my generated measurementIdGet method looks like this:
    apigClient.measurementIdGet = function (params, body, additionalParams) {
        if(additionalParams === undefined) { additionalParams = {}; }

        apiGateway.core.utils.assertParametersDefined(params, [], ['body']);

        var measurementIdGetRequest = {
            verb: 'get'.toUpperCase(),
            path: pathComponent + uritemplate('/measurement/{id}').expand(apiGateway.core.utils.parseParametersToObject(params, [])),
            headers: apiGateway.core.utils.parseParametersToObject(params, []),
            queryParams: apiGateway.core.utils.parseParametersToObject(params, []),
            body: body
        };

        return apiGatewayClient.makeRequest(measurementIdGetRequest, authType, additionalParams, config.apiKey);
    };

I dug into the assertParametersDefined and parseParametersToObject and it looks like those methods are expecting a list of parameters to look for.  In both cases the SDK has generated empty lists instead of putting my path parameter in there.
If I manually update the generated file to change the two lines to
apiGateway.core.utils.assertParametersDefined(params, ['id'], ['body']);
and
apiGateway.core.utils.parseParametersToObject(params, ['id'])
The SDK makes the proper call.
Am I missing something in my configuration or is there a bug in the code generator?

A: If you are using cloud formation like me. You will need to add it in the RequestParameters.
for a resource like this /api/pets/{id}/attributes/{attrid}  following code works
  PetsByIdAttributesByAttridGetMethod:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref MyApi
      ResourceId: !Ref PetsByIdAttributesByAttridResource
      HttpMethod: GET
      AuthorizationType: AWS_IAM
      RequestParameters:
        method.request.path.id : true
        method.request.path.attrid : true
      Integration:
        Type: AWS_PROXY
        IntegrationHttpMethod: POST
        Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambda.Arn}/invocations

A: I know it's an old question, but for those new to AWS that may still run into this issue like I did, I hope this answer helps:
In the AWS API Gateway Console, make sure that you specify the "URL Query String Parameters" in the "Method Request" for your "GET". Then re-deploy your API and generate the SDK again. This time the apigClient.js will be generated with the defined Query Parameter keys correctly filled in to the calls to assertParametersDefined and parseParametersToObject.

A: Assuming that you're importing a swagger definition to create the API, defining your parameters at the method level as opposed to the path level will result in a generated SDK with the key filled out and should work correctly.
{
    ...
    "/path/{to}/resource": {
        "get": {
            "parameters": [ // define here
                "name": "to",
                "in": "path",
                ...
            ],
            ...
        },
        "parameters": [] // not here
}

Although defining parameters at the path level is correct according the the Swagger spec and API Gateway does use them in the created API, it appears that API Gateway disregards them in some contexts.

A: This look's like an issue doesn't parse the params.
https://github.com/aws/chalice/issues/498enter link description here


text:
Q: Is there a way to parallelize swig C file generation? We have a setup where we create a python interface to a C library. We are naively exposing every function, for a number of reasons, and while this is not optimal, it's the least bad solution for the time being.
Our swig interface file simply imports two dozen C header files, and we swig that, then compile, then link the results.
The problem is, that the compilation of the resulting C file is very slow, and by far the slowest step in our build process. We have highly parallel machines, so it would be nice to split this up.
The problem is, when making multiple interface files, compiling them to object files works well, but during the final linking, the linker (rightfully) complains that:
foo1.c:9147: multiple definition of `PyInit__bar_lib'
foo2.c:74285: first defined here

Is there a way to split up swig'ging?


text:
Q: TypeError: this is not a function at IntroJs._introExitCallback I'm trying to pass a div to showOff on intro.onexit() but I am getting this error.
TypeError: this.hideStep is not a function
    at IntroJs._introExitCallback (http://localhost:8100/build/main.js:511:18)
    at IntroJs._exitIntro (http://localhost:8100/build/vendor.js:120298:31)
    at HTMLDivElement.overlayLayer.onclick [as __zone_symbol__ON_PROPERTYclick] (http://localhost:8100/build/vendor.js:121508:20)
    at HTMLDivElement.H (http://localhost:8100/build/polyfills.js:3:23950)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:15660)
    at Object.onInvokeTask (http://localhost:8100/build/vendor.js:5125:33)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:15581)
    at r.runTask (http://localhost:8100/build/polyfills.js:3:10834)
    at e.invokeTask [as invoke] (http://localhost:8100/build/polyfills.js:3:16794)
    at p (http://localhost:8100/build/polyfills.js:2:27648)

I also got this error trying to pass the menuCtrl.close() with this.menuCtrl.close() I had to declare it into he function intro() get it work. I am thinking that, that was because I am calling a function of a component, so I actually will have to create a component to pass false into ?
I am kind of Lost right now, I'm learning, maybe I have the wrong definitions.
This is my code
public step1 = true;

 hideStep(){
    this.step1 = false;
  }

intro() {
    let intro = introJs.introJs();
    let menuCtrl = this.menuCtrl;

    intro.setOptions({
    steps: [
      {
        intro: "Hello!! we want to give you some recommendations"
      },
      {
        element: '#step1',
        intro: "You can see the profile settings, just tapping in your profile picture",
        position: 'bottom'

      },
      {
        element: '#step2',
        intro: "You can see the profile settings, just tapping in your profile picture",
        position: 'bottom'
      }
    ]
    });

    intro.start();
    intro.onexit(function() {
      menuCtrl.close();
      this.hideStep();
    });
  }

  ngAfterViewInit(): void {
    this.intro();
  }

A: Try use fat arrow function instead of method funtion, it is the this keyword issue:
intro.onexit(() => {
    menuCtrl.close();
    this.hideStep();
});

The this keyword of method function refers to the owner of the function it is in


text:
Q: Decoding QRCode with zxing. Java I generated a QRCode using zxing library.
    QRCode qrcode = QRCode.from("Encoding string").withSize(17,17).to(ImageType.PNG);
    ByteArrayOutputStream out = QRCode.from(output.toString()).withSize(10, 10).to(ImageType.PNG).stream();
    FileOutputStream fout = new FileOutputStream(new File("D:\\QR_Code.JPG"));
    fout.write(out.toByteArray());
    fout.flush();
    fout.close();

It works fine but now I want to decode generated QRCode. Is it possible to decode QRCode from an image with zxing? If so, can you give me a hint how to do it because I haven't found appropriate class or method. Thanks in advance.

A: Here is what you can do:

*

*You'll need an instance of QRCodeReader to decode qrcode data from a BinaryBitmap

*You need to instanciate a HybridBinarizer and pass it as a constructor argument to create your BinaryBitmap

*The HybridBinarizer needs an instance of LuminanceSource

*Take a look at BufferedImageLuminanceSource
Here is an example that would decode data from a buffered image:
public static String qrDecodeFromImage(BufferedImage img) {
        if(img!=null) {
            LuminanceSource bfImgLuminanceSource = new BufferedImageLuminanceSource(img);
            BinaryBitmap binaryBmp = new BinaryBitmap(new HybridBinarizer(bfImgLuminanceSource));
            QRCodeReader qrReader = new QRCodeReader();
            Result result;
            try {
                result = qrReader.decode(binaryBmp);
                return result.getText();
            } catch (NotFoundException e) {} catch (ChecksumException e) {} catch (FormatException e) {}
        }
        return null;
    }

A: You'll need to have the ZXing project included in your project(source, etc).
Then you can use all sorts of ZXing classes to performing decoding/encoding, etc:
Look into these classes: BinaryBitmap, QRCodeReader, ParsedResult, ResultParser and give this a try:
Bitmap b = ...;//TODO: create a bitmap from your source...
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(new RGBLuminanceSource(b)));
Result result = null;
QRCodeReader reader = new QRCodeReader();
try {
    result = reader.decode(bitmap);
    ParsedResult parsedResult = ResultParser.parseResult(result);
    //TODO: use parsedResult
}
catch(OutOfMemoryError e) {

}
catch(Exception e) {

}


text:
Q: How would I use js to convert a decimal to number to a hex string? Decimal input: 76561198291043943
Hex output: 110000113b74660
Hex expected output: 110000113b74667
For some reason, when I use the following snippet and execute it, the expected result does not occur, but when I use https://www.binaryhexconverter.com/decimal-to-hex-converter to convert a decimal number to a hex string, I get the expected output.

console.log(Number(76561198291043943).toString(16))

A: 76561198291043943 is greater than Number.MAX_SAFE_INTEGER.
Use BigInt instead:

console.log(BigInt("76561198291043943").toString(16))


text:
Q: NReco PdfGenerator disable selection I want to disable selection, just like an image, even if contain text.
I know PDF contain layers, but i dont find where to remove the text layer.
Thanks.
        var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
        htmlToPdf.Size = NReco.PdfGenerator.PageSize.Letter;

        htmlToPdf.Margins = new NReco.PdfGenerator.PageMargins()
        {
            Bottom = 0,
            Top = 0,
            Left = 0,
            Right = 0
        };
        string ID = "Test";
        Response.ContentType = "application/pdf";

        Response.AppendHeader("content-disposition", string.Format("inline;FileName=\"{0}.pdf\"", ID));

        htmlToPdf.GeneratePdfFromFile("Page.aspx", null, Response.OutputStream);

        Response.End();

A: PdfGenerator internally uses wkhtmltopdf and it renders text content as text blocks and they are selectable by default; this behavior cannot be changed. If you want to guarantee that text cannot be selected it should be rendered as image (= you can render HTML to image first, and then produce PDF that contains this image).
Another alternative is encryption of produced PDF with iTextSharp, see answer for Lock PDF against editing using iTextSharp
- with only PdfWriter.ALLOW_PRINTING option (LGPL version 4.1.6 of iTextSharp can be used for this purpose).


text:
Q: PHP 'break' operator with non-constant operand is no longer supported I'm running this code and I got this error.
    $no=0;
    out:for($i=0;$i<count($r);$i++){
            foreach ($r as $q){
                if($no++>$noOfQuestion)break out;
           }
    }

This is my error
'break' operator with non-constant operand is no longer supported

I'm running php 5.4.3.

A: Use break 2; instead of break out;.

A: Check the new* goto operator.
* version >= 5.3.0


text:
Q: How to use counter excel? I have 5000 strings of excel like
0,./data/images/client_0001 (1).jpg,1.0
0,./data/images/client_0001 (1).jpg,1.0
0,./data/images/client_0001 (1).jpg,1.0
0,./data/images/client_0001 (1).jpg,1.0
0,./data/images/client_0001 (1).jpg,1.0
0,./data/images/client_0001 (1).jpg,1.0
...

But I need like:
0,./data/images/client_0001 (1).jpg,1.0
0,./data/images/client_0001 (2).jpg,1.0
0,./data/images/client_0001 (3).jpg,1.0
0,./data/images/client_0001 (4).jpg,1.0
0,./data/images/client_0001 (5).jpg,1.0
0,./data/images/client_0001 (6).jpg,1.0
...

How can I change it? I tried to use counter then I add 0,./data/images/client_0001 at the start and .jpg,1.0 at the end. But it does not work.

A: Thanks! I just use it and I paste it for excel
def print_hi(name):

    for i in range(614):
        i1 = 249 + i
        i2 = i + 1
        print(str(i1)+',./data/images/imposter_0001 ('+str(i2)+').jpg,0.0')

if __name__ == '__main__':
    print_hi('PyCharm')


text:
Q: Why doesn't a magnetic field accelerate moving charges? As a magnetic field of intensity, $\mathbf{B}$ applies a force of $\mathbf{F}= q\mathbf{v} \times \mathbf{B}$ on a charge $q$ moving with velocity $\mathbf{v}$, this force $\mathbf{F}$ should be accelerating the charge, so it's its kinetic energy should increase. But that doesn't seem to happen, why? I know that the work done is zero because the force acts perpendicularly to the direction of the velocity vector, but there acts a force, and it should be accelerating the charge and it should be increasing its speed in some direction whatsoever, but that force seems only to change the charged particle's direction, why is that so?

A: Acceleration is a change in velocity. Since velocity is a vector quantity there are two ways in which it can change. The magnitude (speed) can change, or the direction can change (or both at the same time).
For the magnetic force it always acts perpendicular to the velocity. Hence this force only produces a change in the direction of the velocity. This is still an acceleration, since the velocity vector is changing.
Therefore, to address misconceptions I see in your question:

*

*Acceleration does not mean change in kinetic energy (although a change in kinetic energy must be accompanied by an acceleration).

*Acceleration does not mean change in speed (although a change in speed must be accompanied by an acceleration).

*The magnetic force, just like all forces, do produce accelerations (assuming there are not other forces that counteract this force).

why do perpendicular forces only contribute to change in direction but not for the change in speed?

The velocity changes in the direction of the force (i.e. the direction of the acceleration). If the force is always perpendicular to the velocity, then you are not adding anything to the "length" (magnitude) of the vector. Think about your usual examples of centripetal forces and circular motion (like a car going around a curve, or spinning an object around on a string). The centripetal force only causes the direction of the velocity to change. In order to change the speed you need a force along the velocity.

A:
... there acts a force, ... but that force seems only to change the charged particle's direction, why is that so?

What we observe in the interaction between a moving electron and an external magnetic field:

*

*If the direction of the electron movement and the direction of the magnetic field are parallel, nothing happens, the electron moves straight ahead. Except for one small peculiarity: The electron has its own magnetic dipole and this dipole is aligned to the external magnetic field.

*If the movement of the electron is nonparallel to the magnetic field and at minimum four things happens to the electron:

*

*The electrons magnetic moment is aligned by the magnetic field.

*The electron is deflected perpendicular to the plane between the motion vector of the electron and the direction of the magnetic field.

*The electron emits photons.

*The emission of photons reduces the kinetic energy of the electron (The emission of photons reduces the kinetic energy of the electron (and the electron moves in a spiral path until it exhausts all the kinetic energy and comes to a standstill in the centre of the spiral).

What has not been considered so far is the sequence of the these events:

*

*Does the alignment of the magnetic dipole led to the emission of photons?

*Does the photon emission led to a tiny deflection of the electron and to a miss-alignment of the electrons magnetic dipole again?

This seems to be an interesting area of research.


text:
Q: Focus on scroll I have a user control with a scrollbar (scrollbar appears as a contained user control, which inherits from Panel, is too large). When using the mouse to scroll all is well, but trying to scroll with the mousewheel dont work.
My solution here is to set focus to my child-control in an eventhandler for Scroll. This works. Now the question; Will this result in a lot of unecessary calls to childControl.Focus()? Is there a more neat way of doing this?
Edit: I think I was a bit unclear with my question so Rephrasing the question:
is
private void ChildControl_OnScroll(object sender, ScrollEventArgs scrollEventArgs)
{
    this.childControl.Focus();
}

a bad way of setting the focus? I.e. will the focus be set mutliple times each time I scroll? or rather, will this cause (tiny) performance issues.

A: The MouseWheel event is an event that "bubbles".  Windows sends it to the control that has the focus, regardless of where the mouse cursor is located.  The most typical problem is that you have a control that cannot receive the focus.  A Panel for example.
This changes when you put a control on the panel.  Now that control can get the focus and gets the MouseWheel message.  It won't have any use for it so the message passes to its parent.  Which does have a use for it, the panel scrolls as expected.
You can get a focusable panel control from this answer.  A generic "make it work like a browser or Office program" solution from this question

A: Here's another approach that gives focus when the scrollbar area of panel1 inside SomeUserControl is clicked.  It uses NativeWindow so you don't have to change the panel in your UserControl.  This way Focus() will only be called once, when the mouse goes down in the scrollbar area:
public partial class SomeUserControl : UserControl
{
    private TrapMouseDownOnScrollArea trapScroll = null;

    public SomeUserControl()
    {
        InitializeComponent();
        this.VisibleChanged += new EventHandler(SomeUserControl_VisibleChanged);
    }

    void SomeUserControl_VisibleChanged(object sender, EventArgs e)
    {
        if (this.Visible && trapScroll == null)
        {
            trapScroll = new TrapMouseDownOnScrollArea(this.panel1);
        }
    }

    private class TrapMouseDownOnScrollArea : NativeWindow
    {
        private Control control = null;
        private const int WM_NCLBUTTONDOWN = 0xA1;

        public TrapMouseDownOnScrollArea(Control ctl)
        {
            if (ctl != null && ctl.IsHandleCreated)
            {
                this.control = ctl;
                this.AssignHandle(ctl.Handle);
            }
        }

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_NCLBUTTONDOWN:
                    if (this.control != null)
                    {
                        Rectangle screenBounds = control.RectangleToScreen(new Rectangle(0, 0, control.Width, control.Height));
                        if (screenBounds.Contains(Cursor.Position))
                        {
                            control.Focus();
                        }
                    }

                    break;
            }
            base.WndProc(ref m);
        }

    }

}

This might be overkill for your scenario, but it demonstrates one way to trap lower level messages.  As said before, you could also derive from Panel to achieve the same affect.  You could also trap messages at the application level with IMessageFilter.

A: If childControl has a MouseEnter() event then use that instead:
    private void childControl_MouseEnter(object sender, EventArgs e)
    {
        childControl.Focus();
    }

Then the mouse wheel events should be direct to childControl.


text:
Q: How to know when a user has really released a key in Java? (Edited for clarity)
I want to detect when a user presses and releases a key in Java Swing, ignoring the keyboard auto repeat feature. I also would like a pure Java approach the works on Linux, Mac OS and Windows.
Requirements:

*

*When the user presses some key I want to know what key is that;

*When the user releases some key, I want to know what key is that;

*I want to ignore the system auto repeat options: I want to receive just one keypress event for each key press and just one key release event for each key release;

*If possible, I would use items 1 to 3 to know if the user is holding more than one key at a time (i.e, she hits 'a' and without releasing it, she hits "Enter").

The problem I'm facing in Java is that under Linux, when the user holds some key, there are many keyPress and keyRelease events being fired (because of the keyboard repeat feature).
I've tried some approaches with no success:

*

*Get the last time a key event occurred - in Linux, they seem to be zero for key repeat, however, in Mac OS they are not;

*Consider an event only if the current keyCode is different from the last one - this way the user can't hit twice the same key in a row;

Here is the basic (non working) part of code:
import java.awt.event.KeyListener;

public class Example implements KeyListener {

public void keyTyped(KeyEvent e) {
}

public void keyPressed(KeyEvent e) {
    System.out.println("KeyPressed: "+e.getKeyCode()+", ts="+e.getWhen());
}

public void keyReleased(KeyEvent e) {
    System.out.println("KeyReleased: "+e.getKeyCode()+", ts="+e.getWhen());
}

}

When a user holds a key (i.e, 'p') the system shows:
KeyPressed:  80, ts=1253637271673
KeyReleased: 80, ts=1253637271923
KeyPressed:  80, ts=1253637271923
KeyReleased: 80, ts=1253637271956
KeyPressed:  80, ts=1253637271956
KeyReleased: 80, ts=1253637271990
KeyPressed:  80, ts=1253637271990
KeyReleased: 80, ts=1253637272023
KeyPressed:  80, ts=1253637272023
...

At least under Linux, the JVM keeps resending all the key events when a key is being hold. To make things more difficult, on my system (Kubuntu 9.04 Core 2 Duo) the timestamps keep changing. The JVM sends a key new release and new key press with the same timestamp. This makes it hard to know when a key is really released.
Any ideas?
Thanks

A: This could be problematic. I can't remember for sure (it's been a long time), but it's likely the repeating-key feature (which is handled by the underlying operating system, not Java) isn't providing enough information for the JVM developer to distinguish those additional key events from the 'real' one. (I worked on this in the OS/2 AWT back in 1.1.x by the way).
From the javadoc for KeyEvent:

"Key pressed" and "key released" events are lower-level and depend on the platform and keyboard layout. They are generated whenever a key is pressed or released, and are the only way to find out about keys that don't generate character input (e.g., action keys, modifier keys, etc.). The key being pressed or released is indicated by the getKeyCode method, which returns a virtual key code.

As I recall from doing this in OS/2 (which at the time still had only the 2-event up/down flavor of keyboard handling like older versions of Windows, not the 3-event up/down/char flavor you get in more modern versions), I didn't report KeyReleased events any differently if the key was just being held down and the events auto-generated; but I suspect OS/2 didn't even report that information to me (can't remember for sure). We used the Windows reference JVM from Sun as our guide for developing our AWT - so I suspect if it were possible to report this information there, I'd have at least seen it on their end.

A: This question is duplicated here.
In that question, a link to the Sun bug parade is given, where some workaround is suggested.
I've made a hack implemented as an AWTEventListener that can be installed at the start of the application.
Basically, observe that the time between the RELEASED and the subsequent PRESSED is small - actually, it is 0 millis. Thus, you can use that as a measure: Hold the RELEASED for some time, and if a new PRESSED comes right after, then swallow the RELEASED and just handle the PRESSED (And thus you will get the same logic as on Windows, which obviously is the correct way). However, watch for the wrap-over from one millisecond to the next (I've seen this happen) - so use at least 1 ms to check. To account for lags and whatnots, some 20-30 milliseconds probably won't hurt.

A: I've refined stolsvik hack to prevent repeating of KEY_PRESSED and KEY_TYPED events as well, with this refinement it works correctly under Win7 (should work everywhere as it truly watches out for KEY_PRESSED/KEY_TYPED/KEY_RELEASED events).
Cheers!
Jakub
package com.example;

import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.swing.Timer;

/**
 * This {@link AWTEventListener} tries to work around for KEY_PRESSED / KEY_TYPED/     KEY_RELEASED repeaters.
 *
 * If you wish to obtain only one pressed / typed / released, no repeatings (i.e., when the button is hold for a long time).
 * Use new RepeatingKeyEventsFixer().install() as a first line in main() method.
 *
 * Based on xxx
 * Which was done by Endre Stølsvik and inspired by xxx (hyperlinks stipped out due to stackoverflow policies)
 *
 * Refined by Jakub Gemrot not only to fix KEY_RELEASED events but also KEY_PRESSED and KEY_TYPED repeatings. Tested under Win7.
 *
 * If you wish to test the class, just uncomment all System.out.println(...)s.
 *
 * @author Endre Stølsvik
 * @author Jakub Gemrot
 */
public class RepeatingKeyEventsFixer implements AWTEventListener {

 public static final int RELEASED_LAG_MILLIS = 5;

 private static boolean assertEDT() {
  if (!EventQueue.isDispatchThread()) {
   throw new AssertionError("Not EDT, but [" + Thread.currentThread() + "].");
  }
  return true;
 }

 private Map<Integer, ReleasedAction> _releasedMap = new HashMap<Integer, ReleasedAction>();
 private Set<Integer> _pressed = new HashSet<Integer>();
 private Set<Character> _typed = new HashSet<Character>();

 public void install() {
  Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);
 }

 public void remove() {
  Toolkit.getDefaultToolkit().removeAWTEventListener(this);
 }

 @Override
 public void eventDispatched(AWTEvent event) {
  assert event instanceof KeyEvent : "Shall only listen to KeyEvents, so no other events shall come here";
  assert assertEDT(); // REMEMBER THAT THIS IS SINGLE THREADED, so no need
       // for synch.

  // ?: Is this one of our synthetic RELEASED events?
  if (event instanceof Reposted) {
   //System.out.println("REPOSTED: " + ((KeyEvent)event).getKeyChar());
   // -> Yes, so we shalln't process it again.
   return;
  }

  final KeyEvent keyEvent = (KeyEvent) event;

  // ?: Is this already consumed?
  // (Note how events are passed on to all AWTEventListeners even though a
  // previous one consumed it)
  if (keyEvent.isConsumed()) {
   return;
  }

  // ?: KEY_TYPED event? (We're only interested in KEY_PRESSED and
  // KEY_RELEASED).
  if (event.getID() == KeyEvent.KEY_TYPED) {
   if (_typed.contains(keyEvent.getKeyChar())) {
    // we're being retyped -> prevent!
    //System.out.println("TYPED: " + keyEvent.getKeyChar() + " (CONSUMED)");
    keyEvent.consume();
   } else {
    // -> Yes, TYPED, for a first time
    //System.out.println("TYPED: " + keyEvent.getKeyChar());
    _typed.add(keyEvent.getKeyChar());
   }
   return;
  }

  // ?: Is this RELEASED? (the problem we're trying to fix!)
  if (keyEvent.getID() == KeyEvent.KEY_RELEASED) {
   // -> Yes, so stick in wait
   /*
    * Really just wait until "immediately", as the point is that the
    * subsequent PRESSED shall already have been posted on the event
    * queue, and shall thus be the direct next event no matter which
    * events are posted afterwards. The code with the ReleasedAction
    * handles if the Timer thread actually fires the action due to
    * lags, by cancelling the action itself upon the PRESSED.
    */
   final Timer timer = new Timer(RELEASED_LAG_MILLIS, null);
   ReleasedAction action = new ReleasedAction(keyEvent, timer);
   timer.addActionListener(action);
   timer.start();

   ReleasedAction oldAction = (ReleasedAction)_releasedMap.put(Integer.valueOf(keyEvent.getKeyCode()), action);
   if (oldAction != null) oldAction.cancel();

   // Consume the original
   keyEvent.consume();
   //System.out.println("RELEASED: " + keyEvent.getKeyChar() + " (CONSUMED)");
   return;
  }

  if (keyEvent.getID() == KeyEvent.KEY_PRESSED) {

   if (_pressed.contains(keyEvent.getKeyCode())) {
    // we're still being pressed
    //System.out.println("PRESSED: " + keyEvent.getKeyChar() + " (CONSUMED)");
    keyEvent.consume();
   } else {
    // Remember that this is single threaded (EDT), so we can't have
    // races.
    ReleasedAction action = (ReleasedAction) _releasedMap.get(keyEvent.getKeyCode());
    // ?: Do we have a corresponding RELEASED waiting?
    if (action != null) {
     // -> Yes, so dump it
     action.cancel();

    }
    _pressed.add(keyEvent.getKeyCode());
    //System.out.println("PRESSED: " + keyEvent.getKeyChar());
   }

   return;
  }

  throw new AssertionError("All IDs should be covered.");
 }

 /**
  * The ActionListener that posts the RELEASED {@link RepostedKeyEvent} if
  * the {@link Timer} times out (and hence the repeat-action was over).
  */
 protected class ReleasedAction implements ActionListener {

  private final KeyEvent _originalKeyEvent;
  private Timer _timer;

  ReleasedAction(KeyEvent originalReleased, Timer timer) {
   _timer = timer;
   _originalKeyEvent = originalReleased;
  }

  void cancel() {
   assert assertEDT();
   _timer.stop();
   _timer = null;
   _releasedMap.remove(Integer.valueOf(_originalKeyEvent.getKeyCode()));
  }

  @Override
  public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
   assert assertEDT();
   // ?: Are we already cancelled?
   // (Judging by Timer and TimerQueue code, we can theoretically be
   // raced to be posted onto EDT by TimerQueue,
   // due to some lag, unfair scheduling)
   if (_timer == null) {
    // -> Yes, so don't post the new RELEASED event.
    return;
   }
   //System.out.println("REPOST RELEASE: " + _originalKeyEvent.getKeyChar());
   // Stop Timer and clean.
   cancel();
   // Creating new KeyEvent (we've consumed the original).
   KeyEvent newEvent = new RepostedKeyEvent(
     (Component) _originalKeyEvent.getSource(),
     _originalKeyEvent.getID(), _originalKeyEvent.getWhen(),
     _originalKeyEvent.getModifiers(), _originalKeyEvent
       .getKeyCode(), _originalKeyEvent.getKeyChar(),
     _originalKeyEvent.getKeyLocation());
   // Posting to EventQueue.
   _pressed.remove(_originalKeyEvent.getKeyCode());
   _typed.remove(_originalKeyEvent.getKeyChar());
   Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(newEvent);
  }
 }

 /**
  * Marker interface that denotes that the {@link KeyEvent} in question is
  * reposted from some {@link AWTEventListener}, including this. It denotes
  * that the event shall not be "hack processed" by this class again. (The
  * problem is that it is not possible to state
  * "inject this event from this point in the pipeline" - one have to inject
  * it to the event queue directly, thus it will come through this
  * {@link AWTEventListener} too.
  */
 public interface Reposted {
  // marker
 }

 /**
  * Dead simple extension of {@link KeyEvent} that implements
  * {@link Reposted}.
  */
 public static class RepostedKeyEvent extends KeyEvent implements Reposted {
  public RepostedKeyEvent(@SuppressWarnings("hiding") Component source,
    @SuppressWarnings("hiding") int id, long when, int modifiers,
    int keyCode, char keyChar, int keyLocation) {
   super(source, id, when, modifiers, keyCode, keyChar, keyLocation);
  }
 }

}

A: I have found a solution to this problem without relying on timing (which according to some users is not necessarily consistent 100% of the time) but instead by issuing extra key presses to override the key repeat.
To see what I mean, try holding a key and then hitting another mid-stream. The repeat will stop. It seems that, on my system at least, the key hits issued by Robot also have this effect.
For an example implementation, tested in Windows 7 & Ubuntu, see:
http://elionline.co.uk/blog/2012/07/12/ignore-key-repeats-in-java-swing-independently-of-platform/
Also, thanks to Endre Stolsvik's solution for showing me how to do a global event listener! Appreciated.

A: Save the timestamp of the event (arg0.when()) in keyReleased. If the next keyPressed event is for the same key and has the same timestamp, it is an autorepeat.
If you hold down multiple keys, X11 only autorepeats the last key pressed. So, if you hold down 'a' and 'd' you'll see something like:
a down
a up
a down
d down
d up
d down
d up
a up

A: I've found a solution that does without waiting in case you have something like a game loop going. The idea is storing the release events. Then you can check against them both inside the game loop and inside the key pressed handler. By "(un)register a key" I mean the extracted true press/release events that should be processed by the application. Take care of synchronization when doing the following!

*

*on release events: store the event per key; otherwise do nothing!

*on press events: if there is no stored release event, this is a new press -> register it; if there is a stored event within 5 ms, this is an auto-repeat -> remove its release event; otherwise we have a stored release event that hasn't been cleared by the game loop, yet -> (fast user) do as you like, e.g. unregister-register

*in your loop: check the stored release events and treat those that are older than 5 ms as true releases; unregister them; handle all registered keys

A: Well, you said that it is possible that the time between key events in case of key repeat be non-negative. Even so, it is likely very short. You could then threshold this time to some very small value, and everything equal or lower than it be considered a key repeat.

A: You might want to use the action map of the component you are interested in. Here's an example that deals with a specific key (SPACE BAR) but I'm sure that if you read the documentation you may be able to modify it to handle generic key presses and releases.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;

import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class Main {
    public static void main(String[] args) {
        JFrame f = new JFrame("Test");
        JPanel c = new JPanel();

        c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke("SPACE"), "pressed");
        c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke("released SPACE"), "released");
        c.getActionMap().put("pressed", new Action() {
            public void addPropertyChangeListener(
                    PropertyChangeListener listener) {
            }

            public Object getValue(String key) {
                return null;
            }

            public boolean isEnabled() {
                return true;
            }

            public void putValue(String key, Object value) {
            }

            public void removePropertyChangeListener(
                    PropertyChangeListener listener) {
            }

            public void setEnabled(boolean b) {
            }

            public void actionPerformed(ActionEvent e) {
                System.out.println("Pressed space at "+System.nanoTime());
            }
        });
        c.getActionMap().put("released", new Action() {
            public void addPropertyChangeListener(
                    PropertyChangeListener listener) {
            }

            public Object getValue(String key) {
                return null;
            }

            public boolean isEnabled() {
                return true;
            }

            public void putValue(String key, Object value) {
            }

            public void removePropertyChangeListener(
                    PropertyChangeListener listener) {
            }

            public void setEnabled(boolean b) {
            }

            public void actionPerformed(ActionEvent e) {
                System.out.println("Released space at "+System.nanoTime());
            }
        });
        c.setPreferredSize(new Dimension(200,200));

        f.getContentPane().add(c);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }
}

A: This approach stores key presses in a HashMap, resetting them when the key is released.
Most of the code is courtesy of Elist in this post.
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class KeyboardInput2 {
    private static HashMap<Integer, Boolean> pressed = new HashMap<Integer, Boolean>();
    public static boolean isPressed(int key) {
        synchronized (KeyboardInput2.class) {
            return pressed.get(key);
        }
    }

    public static void allPressed() {
        final Set<Integer> templist = pressed.keySet();
        if (templist.size() > 0) {
            System.out.println("Key(s) logged: ");
        }
        for (int key : templist) {
            System.out.println(KeyEvent.getKeyText(key));
        }
    }

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            @Override
            public boolean dispatchKeyEvent(KeyEvent ke) {
                synchronized (KeyboardInput2.class) {
                    switch (ke.getID()) {
                        case KeyEvent.KEY_PRESSED:
                            pressed.put(ke.getKeyCode(), true);
                            break;
                        case KeyEvent.KEY_RELEASED:
                            pressed.remove(ke.getKeyCode());
                            break;
                        }
                        return false;
                }
            }
        });
    }
}

You can use the HashMap to check if a certain key is pressed, or call KeyboardInput2.allPressed() to print every pressed key.

A: What am I not getting about all the elaborate but questionable suggestions? The solution is so simple! (Overlooked the key part of OP's question: "under Linux, when the user holds some key, there are many keyPress and keyRelease events being fired")
In your keyPress event, check if the keyCode is already in a Set<Integer>. If it is, it must be an autorepeat event. If it is not, put it in and digest it. In your keyRelease event, blindly remove the keyCode from the Set - assuming that OP's statement about many keyRelease events is false. On Windows, I only get several keyPresses, but only one keyRelease.
To abstract this a little, you could create a wrapper that can carry KeyEvents, MouseEvents, and MouseWheelEvents and has a flag that already says that the keyPress is just an autorepeat.


text:
Q: Initializing a class with numpy array question So I have defined the following function to be entered into a class:
MatrixConverter(arr)

Which works exactly how I want it to, taking in a numpy array as argument, and produces a simpler matrix as a numpy array.
Now, I would like to define a class that is initialized by a numpy array, and once I enter a matrix into the class, called SeveralConvertor, to run the entered matrix through MatrixConverter, thus creating an internal representation of the converted matrix. My attempt at this goes as follows:
class SeveralConvertor:
    def __init_(self,matrix)
    self.matrix=np.array(matrix)

def MatrixConverter(self)

Letting q be some random array, and then typing q.MatrixConverter gives the following error:
<bound method SeveralConverter.MatrixConverter of <__main__.SeveralConverter object at 0x7f8dab038c10>>

Now, as I said, the function MatrixConverter(arr) works fine as a function, but when I entered it into the class, I exchange all arr for self, which might have something to do with the problem.
Help would be much appriciated!

A: No need to do anything too fancy, we can bind the (unit tested) function to a class method, then invoke that in the __init__ function.

def matrixConverter(arr):
    # Some complicated function you already wrote
    raise NotImplementedError

class SeveralConverter:
    def __init__(self, matrix):
        self.matrix = self._MatrixConverter(matrix)

    @staticmethod
    def _MatrixConverter(arr):
        """ Call the Matrix Converter Function """
        return MatrixConverter(arr)

Then in your code (put the above in a module and import the class)
matrix_converted = SeveralConverter(ugly_matrix)
print(matrix_converted.matrix)  # Prints the converted matrix


text:
Q: How to set coveragerc and/or setup.cfg to test a package with specific tests location I am implementing tests on a python package and I try to make them with pytest.
The project has the following architecture:

*

*package_name/

*

*__init__.py

*file1.py

*file2.py

*...

*tests/

*

*test_file1.py

*test_file2.py

*...

*setup.py

*setup.cfg

*.coveragerc
How can I setup pytest to launch all the tests with a single command such as:
coverage run setup.py test

I tried a few settings, however it seems like pytest do not find the test files in the tests/ directory.

A: Did you try to run the command pytest tests/?
You can also try using marker test invocation:
@pytest.mark.my_tests
class TestsFilaA:
    def test_something():
        pass

    def test_something_else():
        pass

@pytest.mark.my_tests
class TestsFilaB:
    def test_something_b():
        pass

    def test_something_else_b():
        pass

and run the command pytest -v -m my_tests


text:
Q: RuntimeWorkerException: Invalid nested tag tr found, expected closing tag td As you can see, my problem seems to be simple, just an inattention and forgetting to close a  tag, right?
error detail:
com.itextpdf.tool.xml.exceptions.RuntimeWorkerException: Invalid nested tag tr found, expected closing tag td.
    at com.itextpdf.tool.xml.XMLWorker.endElement(XMLWorker.java:135)
    at com.itextpdf.tool.xml.parser.XMLParser.endElement(XMLParser.java:396)
    at com.itextpdf.tool.xml.parser.state.ClosingTagState.process(ClosingTagState.java:71)
    at com.itextpdf.tool.xml.parser.XMLParser.parseWithReader(XMLParser.java:236)
    at com.itextpdf.tool.xml.parser.XMLParser.parse(XMLParser.java:214)
    at com.itextpdf.tool.xml.parser.XMLParser.parse(XMLParser.java:175)
    at com.lecom.workflow.robo.satelite.inmetro.balcao.RbINMETROGeraProcedimentoSeiBalcao.createPdfFromHtmlString(RbINMETROGeraProcedimentoSeiBalcao.java:1626)
    at com.lecom.workflow.robo.satelite.inmetro.balcao.RbINMETROGeraProcedimentoSeiBalcao.executar(RbINMETROGeraProcedimentoSeiBalcao.java:257)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at br.com.lecom.workflow.servicos.business.ServicoBuilderRobo.executar(ServicoBuilderRobo.java:80)
    at com.lecom.workflow.robo.ExecutaRobo.run(ExecutaRobo.java:32)
    at com.lecom.workflow.robo.CustomRobotExecute.execute(CustomRobotExecute.java:19)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)

And this is the Html code expecting a closing td tag:

 XXXXXXXXXXX

Nº do Protocolo da Solicitação: XXXXXX

Dados do Solicitante

           <col width='33%' />
           <col width='34%' />
           <col width='33%' />

               CNPJ: XXXXXXXX

               Nome da Empresa/Instituição: XXXXX

               CPF: XXXXXX

               Nome: XXXXXXX

               E-mail: XXXXXXX

               Telefone: XXXXXXXX

               UF: XX

Documentos anexos

                   Nome
                   Arquivo

                   XXXXXXX
                   XXXXXXX

                   XXXXXXX
                   XXXXXXX

                   XXXXXXX
                   XXXXXXX

                   XXXXXXX
                   XXXXXXX

                   XXXXXXX
                   XXXXXXX

                   XXXXXXX
                   XXXXXXX

                   XXXXXXX
                   XXXXXXX

                   XXXXXXX
                   XXXXXXX

                   XXXXXXX
                   XXXXXXX

                   XXXXXXX
                   XXXXXXX

                   XXXXXXX
                   XXXXXXX

               Detalhameto da solicitação:

               XXXXXXXXXXX

XXXX
XXXXX

Documentos do Analista

                   Nome
                   Arquivo

                   XXXXXXX
                   XXXXXXX

Outras Informações

               Analista Responsável: XXXXXXX

               Data do envio da solicitação: XXXXXXX

I spent hours and hours trying to identify the problem but without success.
OBS 1: I've only shared what's inside the  tag because I think it's the only relevant one.
OBS 2: Im using XMLParser:
    // XML Worker
    XMLWorker worker = new XMLWorker(css, true);
    XMLParser p = new XMLParser(worker);
    p.parse(new ByteArrayInputStream(htmlString.getBytes()));

the variable htmlString is the html from above


text:
Q: Separating points from open sets in a compact space without isolated points Given that $S$ is compact and it has no isolated point. Show that given any nonempty open set $P$ of $S$ and any point $x\in S$,
there exists a nonempty open set $V\subset P $ such that $x\notin \bar V $
. I am not very sure what i have to do to finish it. My thought is that it for $x\in S$, it is not an isolated point so there exist an $y\in S$ but then not sure how to proceed, and not sure how to know the existence of $V$


text:
Q: How can I write code that compiles with Xcode 9.x(iOS11) and Xcode10.x(iOS12) when using UNAuthorizationStatus.provisional? Hello I have some switch case code that handles UNAuthorizationStatus, since iOS12 a new status has been added: .provisional. In C or other old style compiler stuff I would write a precompiler directive to surround .provisional handling code however in swift that seems to lead to errors.
private func checkNotificationSettings() {
    UNUserNotificationCenter.current().getNotificationSettings { settings in
        switch settings.authorizationStatus {
        if #available(iOS 12.0, *) { // ERROR here
        case .provisional: // ERROR here too
            // Do my thing
        }
        case .authorized:
            // Do my thing
        case .notDetermined:
            // Request authorization and if granted do my thing
        case .denied:
            // Do not do my thing
        }
    }
}

Errors:

Switch must be exhaustive
  All statements inside a switch must be covered by a 'case' or 'default'

Is there any smart way of handling this? I would like to avoid this because it is too long and repetitive:
if #available(iOS 12.0, *) {
    NUserNotificationCenter.current().getNotificationSettings { settings in
        switch settings.authorizationStatus {
        case .provisional:
        ...
    }
} else {
    NUserNotificationCenter.current().getNotificationSettings { settings in
        switch settings.authorizationStatus {
        ...
    }
}

A: You could do all common cases as normal and add the available checks in the default part like this
NUserNotificationCenter.current().getNotificationSettings { settings in
    switch settings.authorizationStatus {
        case .stateX:
         //do stuff
        default:
          if #available(iOS 12.0, *) {
               if settings.authorizationStatus == .provisional {
                //Handle case
               }
          }
    }
}

A: This isn't the most elegant solution, but it's simple to use if else instead of switch. In my case I remap .provisional to .authorized. Something like:
func didTapNotificationsCell(authorizationStatus: UNAuthorizationStatus) {
    if #available(iOS 12.0, *), authorizationStatus == .provisional {
        handleCommonStatus(.authorized)
    } else {
        handleCommonStatus(authorizationStatus)
    }
}

private func handleCommonStatus(_ status: UNAuthorizationStatus) {
    if status == .authorized {
        // Do something

    } else if status == .notDetermined {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (_, _) in
        }

    } else if status == .denied {

    }
}


text:
Q: GtkIconView Right Click Activate I'm building an application using GTK 3+ with Python, and I'm having trouble with GtkIconView. When there are icons in the view, I would like to be able to left and right click on the icon. A single left click works correctly, but I'm having trouble selecting on right click.
Right click is supposed to show a popup menu. I had a look at https://askubuntu.com/questions/144311/how-to-make-a-gtk-iconview-react-to-single-click-instead-of-double-click
It was suggested that I work with a button_press_event then move on from there.
Here is my code with regards to the above suggestion:
def on_button_press_event(self, widget, event):
    if event.type == Gdk.EventType.BUTTON_PRESS:
        choice = util.get_selection(.....)
        #get the text of the selected icon

        if event.button == 3:
            print("Right CLick")
            print(choice)
        elif event.button == 1:
            print("LEFT CLICK")
            print(choice)

At this stage when I click on the icon, both left and right click do not select the icon thereby choice becomes []. Only double clicking selects the icon.
Is there a way to select the icon with a single click regardless on the button?
I've added GtkIconView.add_events(Gdk.EventMask.BUTTON_PRESS_MASK) but that does not seem to do anything.

A: I managed to solve the problem by using the button_press_event.
 if event.type == Gdk.EventType.BUTTON_PRESS:
    path = GtkIconView.get_path_at_pos(event.x, event.y)
    if path != None:
        GtkIconView.select_path(path)
        choice = util.get_selection(GtkIconView,GtkListStore)
        if event.button == 3:
            # popup on right click
        elif event.button == 1:
            self.on_GtkIconView_activated(widget,choice)

To receive any signal from a mouse click you have to add
GtkIconView.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)

So any mouse button click on the icon will result in the text of the icon being displayed, which is what I needed.

A: First, is setting the activate-on-single-click property not sufficient enough? I don't think this was mentioned anywhere in the question you linked.
Anyway, you need to return the Python equivalent of GDK_EVENT_PROPAGATE (whatever that is) from your GDK events (like button-press-event), otherwise other event handlers (like the ones that are part of GtkIconView itself) won't run. I assume you're hitting undefined behavior because you aren't returning anything explicitly and in this case the undefined behavior is "return the equivalent of GDK_EVENT_STOP".


text:
Q: Asterisk call transfer on DAHDI channells
All channels on Asterisk configured as DAHDI channels.After customer make payment I want to transfer the customer to the representative who interact customer before.
I try to make it by Dial() command. This is the dialplan
exten => s,1,Set(TRFNUM=${CALLERID(num)})
exten => s,2,Set(TRFNAME=${CALLERID(name)})
exten => s,3,AGI(agi://192.168.7.20/customivr)
exten => s,4,Dial(DAHDI/1/${TRFNUM}&DAHDI/2/${TRFNUM}&DAHDI/3/${TRFNUM}&DAHDI/4/${TRFNUM}&DAHDI/5/${TRFNUM}&DAHDI/6/${TRFNUM}&DAHDI/7/${TRFNUM}&DAHDI/8/${TRFNUM},30)
exten => s,5,Hangup

For example: Call comes to DAHDI/1 after the payment DAHDI/1 dial all channels one them Answer the others Hangup. DAHDI/1 bridge call by with DAHDI/2. However, although Customer and representative close phones, Channels do not Hangup. They stay Busy.
Where do i make mistake. I should hangup call channels or find another way to transfer.

A: It seems to be configured correctly,
I think your AGI script hangup the call when he finishes his work,
It can happen if you have $agi>hangup in the end,
or if you make any outputs in the scripts (echo, print_r, etc...),
even empty spaces output can cause this behavior,
another thing you can try is make the Dial command from the agi itself using:
agi->exec("Dial","options");


text:
Q: Trouble getting started with AWS Lambda locally I'm trying to get a simple dotnet lambda up and running using the Rider AWS toolkit - starting with the SAM HelloWorld sample project, but in creating, I run into this error
java.util.concurrent.CompletionException: java.lang.RuntimeException: Could not execute `sam init`!: [Cloning from https://github.com/aws/aws-sam-cli-app-templates, Error: Unstable state when updating repo. Check that you have permissions to create/delete files in C:\Users\user_name\AppData\Roaming\AWS SAM directory or file an issue at https://github.com/aws/aws-sam-cli/issues]

I checked the permissions on that directory, and I should have full read/write. I'm not seeing anyone else running into this particular problem online. Is this indicative of any other steps I missed along the way?

A: The root cause is apparently a long filename issue.  There is a workaround here: https://github.com/aws/aws-sam-cli/issues/3781#issuecomment-1081263942
What I did was:

*

*Using regedit set HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled" to 1

*With admin permissions, run git config --system core.longpaths true


text:
Q: Does the given C code has both syntax error and semantic error? Already, so many downvotes for this question. Is anyone reading it carefully, I didn't applied comma intentionally.
#include<stdio.h>

int main()

{

      aloft a b ; // I have not applied comma intentionally

      a = 4.00 ; b = 20.00;

      printf("%d %d",a,b);

      return 0;

}

I ran the above program and I got the following output:
prog.c: In function 'main':
prog.c:7:7: error: unknown type name 'aloft'
       aloft a b ;
       ^
prog.c:7:15: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'b'
       aloft a b ;
               ^
prog.c:9:7: error: 'a' undeclared (first use in this function)
       a = 4.00 ; b = 20.00;
       ^
prog.c:9:7: note: each undeclared identifier is reported only once for each function it appears in
prog.c:9:18: error: 'b' undeclared (first use in this function)
       a = 4.00 ; b = 20.00;
                  ^

Clearly, a and b are undeclared as shown in the output, so it gives clear information that there is a semantic error.
But, I am not having a clear idea that is it syntax error or not ?
As the code suffers from the following output :
expected '=', ',', ';', 'asm' or '__attribute__' before 'b'

This shows that syntax is not properly encoded in the program. Does this means syntax error?
Alternatively, I tried to run this program as:
#include<stdio.h>

int main()

{
      typedef float aloft;

      aloft a b ;

      a = 4.00 ; b = 20.00;

      printf("%d %d",a,b);

      return 0;

}

But still the output shows B undeclared and no use of comma, ;, etc.
prog.c: In function 'main':
prog.c:8:15: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'b'
       aloft a b ;
               ^
prog.c:8:15: error: 'b' undeclared (first use in this function)
prog.c:8:15: note: each undeclared identifier is reported only once for each function it appears in
prog.c:10:7: error: 'a' undeclared (first use in this function)
       a = 4.00 ; b = 20.00;
       ^

It is clear that semantic error is there. But, Is there syntax error ? If not, then how it passes the syntax analysis phase ?

A: There are both syntax and semantic errors.
The syntax error is missing comma between a and b.
The semantic error is wrong type name (aloft instead of float) for a and b variables.
The reason why you see both syntax and semantic errors is that compiler does the best job in order to recover and provide as much output as possible. Even though it might be misleading and produces lot more than it's really necessary to fix the root cause, in many cases it may help and avoids many runs of compiler to fix the issues sequentially.


text:
Q: LFTP transfer_log repopulate? Using LFTP my transfer_log was getting REALLY large and trying to cat transfer_log was taking a really long time. I am hoping to find out that if I remove this transfer_log will it be re-created once LFTP starts running again?

A: It's better to truncate the file using :>~/.lftp/transfer_log.
If you just remove the log and an lftp instance has it open, it will grow and occupy disk space until lftp finishes.
BTW, newer lftp versions starting with 4.5.0 have a setting xfer:max-log-size to rotate the transfer_log automatically.


text:
Q: Debug OpenCV images in Python Visual Studio allows to visualize OpenCV images using Image Watch plugin (https://visualstudiogallery.msdn.microsoft.com/e682d542-7ef3-402c-b857-bbfba714f78d) during debug. This is very helpful for computer vision coding.
What is the proffered way to visualize images in Python binding to OpenCV? I am aware that it is possible to use cv2.imshow("name", image) but that is not very practical in contrast to Image Watch which allows to show many images at the same time and automatically does the update after change.
Is there any alternative to Image Watch for Python?

A: If you use VSCode, you can try the simply_view_image_for_python_opencv_debugging VSCode-Extension.
https://marketplace.visualstudio.com/items?itemName=johnguo.simply-view-image-for-python-opencv-debugging

A: I think maybe you'll want to look at Visual-Logging. It can produce a rather nice collection of your output that you can just open up in a browser. It is pip installable like so:
pip install visual-logging

Here is a page with a concise walkthrough that shows how it is used.
It's not nearly as fancy as that Visual Studio tool, but it might be your best option that already exists.

A: I had similar problems, so I've just created OpenCV Image Viewer Plugin, which works as you expect. You can install it to any JetBrains IDE, which support Python (directly or via plugin).
https://plugins.jetbrains.com/plugin/14371-opencv-image-viewer


text:
Q: How do i exclude negative numbers in an if loop? For my project, the user enters a set of numbers, and some calculations are performed to give the desired output. One of the calculations is the find the sum of the odd numbers that are inputted. Looking at the given test cases, I noticed my code was adding the negative odd numbers, while the correct test cases do not.  Is there any easy fix for this?
Thanks
Here is some of the code, what I have written minus a few parts.
import java.util.Scanner;

public class Test
{
public static void main (String[] args)
{
    int min_interger = 0;
    int sum_of_pos = 0;
    int sum_of_odd = 0;
    int count_of_pos = 0;
    int userInput;

    Scanner consoleInput = new Scanner(System.in);

    do {userInput = consoleInput.nextInt();

    if(userInput % 2 != 0)
    {
        sum_of_odd = sum_of_odd + userInput;
    }

    while (userInput != 0);

    System.out.print("The sum of the odd integers is " + sum_of_odd + "\n")
}

}

A: Make sure to add odd and greater than zero numbers
if(userInput % 2 != 0 && userInput > 0)
    {
        sum_of_odd = sum_of_odd + userInput;
    }


text:
Q: Optimization tips for WP code and high data volumes Looking for tips on how I might re-factor a shortcode which outputs a table of custom post types with meta field values that is hitting memory limits with 250 - 300 results on page.
Setup Details
Using Gravity Forms Quiz add-on and WCK Custom Field / Post Type Creator I have setup a training system which has the following custom post types for different data collections (capitals) and general flow. STUDENT is scheduled in CLASSES that can have multiple COURSES that are collection of QUIZZES. Each time a student takes a quiz they generate a result which has separate meta data fields identifying the ID of the course, class, quiz and student.
The current version uses datatables jQuery to display all the results to the class teacher and handle pagination, search, sort, download to .xls and other table features. But I'm hitting some memory / performance issues with the number of results to loop through WP_Query is over 250.
The analysis page uses a shortcode - code snippet pastebin to output the table data, essentially:

*

*WP_Query Loops through each COURSE, CLASS and QUIZ custom post type storing ID / Title in it's own array with ID as key.

*foreach loop through all users and stores as an array for name, email

*WP_Query loop through all RESULTS and does a match based on meta data for right data to present.

Looking for tips on how I might re-factor this or which would be best to focus on first with the only real caveat being that keeping GF Quiz as data entry point. Some things I've been considering:

*

*Optomizing the WP_Query params

*Are CPT and meta fields the right place to store this?

*Is something in how WCK generates it's CPTs adding to massive overhead?

*Using WP Ajax pagination for results and a separate build process to download .csv. But how would that download be built without hitting same performance problems?

*Does the WP import / export code offer some examples I really should look at?

*Other examples where people have 1,000's of results to display to page / download?

*I doubt "throw more hardware at it" is viable solution as environment generally is pretty responsive for load. But if so, what area should focus on given the scenario (multi-core, processor speeds, memory, etc)

Much thanks!

A: if data doesn't get updated constantly, maybe try static html files, here's a plugin for you. but as suggested by CodeMoose, pagination is your friend also.


text:
Q: Is there any mechanism to obtain location data for a web application running on an Android Device without enabling device location settings I want to obtain the location of users' for a web application without wanting them to externally enable the location via the Android device location settings.
Currently I'm using HTML5 Geolocation API to obtain the users' location. The problem is when the web page is viewed through an Android Device, other than enabling the location permissions on the browser, Android device built in location settings should also be enabled to obtain the location.
I want to find out whether there is a mechanism where you can achieve this kind of a thing. Though I did spend lot of time searching through the internet for a tip, couldn't find a one. Glad if any one could give an idea about my approach here.