Q: Compare Positions of Values in Php Array $commands = array();

    for($p = 0; $p < $commandCount ; $p++){
          $commands[$p] = $_POST['select'.$p];
    }

So I have this Array $commands. In this Array, a List of Commands is stored. I have to check on which Position the Command "mark" is stored and if a certain command follows after it.
Some Example Data which can be in $commands:
"mark", "ignore", "pick", "random"
 How would You do it?

A: You can use $index = array_search("mark", $commands) which will return the index of the first occurrence of the command "mark" and then you can use $commands[$index + 1] to get the next command in the array.
You will also need to check if $index != null as otherwise it may return the first item in your $commands array because null is interpreted as 0

A: Here is a demonstration with a battery of test cases to fully express how it works and identify fringe cases:  (Demo Link)
*note, array_search() returns false when the needle is not found.
$commands = array("mark", "ignore", "pick", "random");

$attempts = array("mark", "ignore", "pick", "random", "bonk");
foreach($attempts as $attempt){
    echo "$attempt => ";
    $index=array_search($attempt,$commands);
    //                                    vv---increment the value
    if($index===false || !isset($commands[++$index])){  // not found or found last element
        $index=0;                                      // use first element
    }
    echo $commands[$index],"\n";
}

The "or" (||) condition will "short circuit", so if $index is false it will exit the condition without calling the second expression (isset()).
Output:
mark => ignore
ignore => pick
pick => random
random => mark
bonk => mark

A: Just did some double checking you're going to want to assert first that your array contains the value of mark first. array_search will return a false otherwise, and that easily can be translated into 0.
Supporting Documentation :
PHP in_array
PHP array_search
$commands = array("mark", "ignore", "pick", "random");
//checks if $command contains mark,
//gets first index as per documentation
//Or sets index to -1, ie No such value exists.
 $index = in_array("mark",$commands) ? array_search("mark",$commands):-1;
//gets the next command if it exists
 $nextCommand = $index!=-1? $commands[++$index]:"Unable to Find Command: mark";


Q: Javascript image change causes embeded UserControls to flicker I have a n html page being displayed in IE.  It has some buttons made up of images with mouseover/mouseout events on them in JavaScript, and a bunch of embedded .Net UserControls.
When the mouseover/mouseout events fire, I change the images src to something else (simple rollover effect).  The problem is that the UserControls often (but not always) flicker when this happens.
To be clear, the images don't flicker, and the rest of the page doesn't flicker, just the embedded controls.  This page is local, not coming from a server or anything.
So, any ideas?
More information : I've noticed that highlighting text does it too...

A: If you didn't preload the images, you could see this kind of problem.
To preload the images, just add a special div with the wanted urls.

In your css:
#preload { display:none; }

That's it !


Q: Is there any good spec or library for uri-templating(routing) in java or scala I'm trying to create a mvc framework for myself in scala. Routers are necessary. I have a route file, contains:
/              "App.index"
/users         "Users.index"
/users/{id}    "Users.show"
/articles/{year}/{month}/{day} "Article.list"

I need a library to parse the urls and find the best matching.
I know there is one uri-templates, but I hope I can find more.

A: You can look at Routineer - Scala DSL for declaring HTTP routes:
https://github.com/mvv/routineer


Q: jquery condition remove disable I have a class that has the value of total
0

and a class of a radio button
class="radio-livraison element-radio-input" disabled="disabled"

is is possible to disable the radio button and enable it only if total is more than 28;
example you can't check the radio button if span price-value is less than 28

but I get error:
Uncaught TypeError: $ is not a function

I have jQuery and Bootstrap on my template before the code.

A: Try this:

You need to compare the text inside that element, not the element itself.
Hope this helps.

A: demo: http://jsbin.com/toguruzure/1/edit?html,js,output
$(function(){
$(".price-value").change(function(){
 $('.radio-livraison').prop("disabled", !(parseInt($('.price-value').text()) > 28));
});

$("#total").on('input', function(){
  $(".price-value").text($(this).val()).change();
});

})


Q: DB2/400 SQL : How to insert PDF file in Blob Column? I would like to know if my SQL insert code is OK.
Here is my table :
-- Create table
Create table FNS_CHAMP_DEV
(
IDAUTO         Integer not null generated always as identity ( start with
0, increment by 1, no cache) primary key,
BB_COL               BLOB,
CB_COL               CLOB
);

Is my syntax SQL below correct to insert  a PDF file in BLOB Column ?
-- SQL insert request :
   SELECT IDAUTO  AS Last_ID from final table  (Insert into FNS_CHAMP_DEV  (
   BB_COL ) Values(blob('C:\DOC_TECHNIQUE_WD\TEC_VISUAL_STUDIO\WPF_VISUAL_STUDIO.pdf')));

Thanks


Q: Why do I need Sum and Bank class to calculate Money? I am reading Test Driven Development: By Example. I am on chapter 13. Chapter 12 and 13 introduced Plus operation to Money object. A Money object can plus by other Money object.
The author added two classes (Bank and Sum) and one interface (IExpression) to the solution. This is the class diagram of the final solution.

Money store amount and currency for example 10 USD, 5 BAHT, 20 CHF. The Plus method returns Sum object.
public class Money : IExpression
{
    private const string USD = "USD";
    private const string CHF = "CHF";

    public int Amount { get; protected set; }

    public string Currency { get; private set; }

    public Money(int value, string currency)
    {
        this.Amount = value;
        this.Currency = currency;
    }

    public static Money Dollar(int amount)
    {
        return new Money(amount, USD);
    }

    public static Money Franc(int amount)
    {
        return new Money(amount, CHF);
    }

    public Money Times(int times)
    {
        return new Money(this.Amount * times, this.Currency);
    }

    public IExpression Plus(Money money)
    {
        return new Sum(this, money);
    }

    public Money Reduce(string to)
    {
        return this;
    }

    public override bool Equals(object obj)
    {
        var money = obj as Money;

        if (money == null)
        {
            throw new ArgumentNullException("obj");
        }

        return this.Amount == money.Amount &&
            this.Currency == money.Currency;
    }

    public override string ToString()
    {
        return string.Format("Amount: {0} {1}", this.Amount, this.Currency);
    }
}

Sum store two Money objects which come from constructor arguments. It has one method Reduce that return new Money object (create new object by add amount of two object)
public class Sum : IExpression
{
    public Money Augend { get; set; }

    public Money Addend { get; set; }

    public Sum(Money augend, Money addend)
    {
        this.Augend = augend;
        this.Addend = addend;
    }

    public Money Reduce(string to)
    {
        var amount = this.Augend.Amount + this.Addend.Amount;

        return new Money(amount, to);
    }
}

Bank has one method - Reduce. It just call Reduce method of incoming IExpression argument.
public class Bank
{
    public Money Reduce(IExpression source, string to)
    {
        return source.Reduce(to);
    }
}

IExpression is an interface that implemented by Money and Sum.
public interface IExpression
{
    Money Reduce(string to);
}

These are my questions.

*

*Bank does nothing good for the solution at this stage. Why do I need it?

*Why do I need Sum since I can create and return Money object inside Plus of the class Money (Like what the author did with Times)?

*What is the purpose of Bank and Sum? (Right now, it doesn't make any sense for me)

*I think Reduce sound strange for me as the method name. Do you think it is a good name? (please suggest)

A: Keep reading.  Kent Beck is a very smart guy.  He either has a very good reason why he created the example that way, and it  will be clear later on, or it's a poor solution.
"Reduce" is a very good name if map-reduce is the ultimate goal.


Q: getline going over specified amount I have this code....
    file_parser::file_parser(string file){
        txtfile.open(file.c_str(), ios::in);
        if (!txtfile.good()){
            string error=err(0," "+file+" not found. Exit code ",1);
            throw file_parse_exception(error);
        }
        while (!txtfile.eof()){
            char str[200];
            txtfile.getline(str, 200);
            string str2=str;
            vfile.push_back(str2);
        }
        txtfile.close();
    }

and the problem is that if I have a line in the input file greater than 200 characters it hangs then crashes. I checked out the value of str at crash and it is preceded by a null char then it tries to push back a null(non-initialized) string onto the vector which causes the hang/crash. does anyone know a way to get around this? I thought by using getline it would truncate the char array at 199(+null) characters but apparently this isn't happening. I'm stumped. The thing is that I want each pushback to have a max of 200 characters. I really don't want the WHOLE line which is what 'string str' would do. and if a line is over 200 characters it should read the first 200 and then move on to the next line.

A: Replace your input loop with this:
    std::string str;
    while (std::getline(txtfile, str)){
        vfile.push_back(str);
    }

Using ios::eof() as a loop condition almost always creates a buggy program, as it did here. In this case, using eof() has two problems. First, eof() is only set after the read fails, not before, but you are checking it before the read. Second, eof() doesn't check the range of other errors. When an input line has more than 200 characters, istream::getline sets failbit, but not eofbit.

EDIT: With the added requirement of limiting the input lines to 200 characters, this should work:

// untested
std::string str;
while(std::getline(txtfile, str)) {
    if(str.size() > 200)
        str.erase(200, std::string::npos);
    vfile.push_back(str);
}


Q: How do I add line breaks e.g. \\n in a Apache POI HWPF Document I have to modify Word Document in the old .doc format. Using Apache POI with the HWPF representation of the document. I struggled to insert line breaks into any table cell. In the modified document line breaks look like empty boxes.
table cell with added line break
The Code I used for this after I selected the specific cell:
cell.insertBefore("Test "+System.lineSeparator()+" Test");

The Following also doesnt work:
cell.insertBefore("Test "+System.getProperty("line.seperator")+" Test");
cell.insertBefore("Test \n Test");
cell.insertBefore("Test \r\n Test");

everything I tried was transformed into boxes.
I also tried writing the document to a temp file and then just replacing a placeholder with HWPF -> empty boxes.Does anybody know a solution to this?
Thanks in advance.

A: Forget about apache poi HWPF. It is in scratchpad and without any progress since decades. And there are no useable methods to insert or create new paragraphs. All Range.insertBefore and Range.insertAfter methods which take more than only text are private and deprecated and doesn't work properly also since decades. The reason of that may be that the binary file format of Microsoft Word HWPF of course is the most horrible file format of all the other horrible file formats like HSSF, HSLF. So who wants bothering with this?
But to answer your question:
In word processing text is structured in paragraphs containing text runs. Each paragraph takes a new line by default. But "Text\nText" or "Text\rText" or "Text\r\nText" stored in a text run would only mark a line break within that text run but not a new paragraph. Would ..., because of course Microsoft Word has it's own rules. There \u000B marks that line break within the text run.
So what you could do is the following:
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.hwpf.*;
import org.apache.poi.hwpf.usermodel.*;

public class ReadAndWriteDOCTable {

 public static void main(String[] args) throws Exception {

  HWPFDocument document = new HWPFDocument(new FileInputStream("TemplateDOC.doc"));

  Range bodyRange = document.getRange();
  System.out.println(bodyRange);

  TableIterator tableIterator = new TableIterator(bodyRange);
  while (tableIterator.hasNext()) {
   Table table = tableIterator.next();
   System.out.println(table);
   TableCell cell = table.getRow(0).getCell(0); // first cell in table
   System.out.println(cell);
   Paragraph paragraph = cell.getParagraph(0); // first paragraph in cell
   System.out.println(paragraph);
   CharacterRun run = paragraph.insertBefore("Test\u000BTest");
   System.out.println(run);
  }

  FileOutputStream out = new FileOutputStream("ResultDOC.doc");
  document.write(out);
  out.close();
  document.close();

 }
}

That places the text run "Test\u000BTest" before first paragraph in first cell of each table in the document. And the \u000B marks a line feed within that text run.
Maybe that is what you wanted to achieve? But, as said, forget about apache poi HWPF. The next unsolvable problem is only a step far away.


Q: How does module resolution in TypeScript work for global values (i.e. describe)? While using jest on its own the corresponding typescript definitions got detected right after installing @types/jest.
I then started to implement integration tests with cypress. Since cypress is using mocha, I now incorrectly see references of mocha type definitions inside my jest tests. In fact, a number of overlapping type definitions are detected. For instance, describe seems to be defined in a number of files. I even tried to implement my own typing for describe pointing to jest. Unfortunately, every single time mocha "wins".
How can I specify the order of precedence when multiple definitions are detected by the typescript compiler?

My tsconfig.json looks like this:
{
    "compilerOptions": {
        "target": "es5",
        "lib": [ "dom", "dom.iterable", "esnext" ],
        "types": [ "jest", "mocha" ],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "strictNullChecks": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": false,
        "noEmit": true,
        "jsx": "preserve"
    },
    "include": [ "src/**/*" ]
}

However, I also tried the following:
{
    "compilerOptions": {
        "target": "es5",
        "lib": [ "dom", "dom.iterable", "esnext" ],
        "typeRoots": [ "./node_modules/@types", "./src/types" ],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "strictNullChecks": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": false,
        "noEmit": true,
        "jsx": "preserve"
    },
    "include": [ "src/**/*" ]
}

In both cases mocha is being chosen. How can I switch the type for "describe & co." to jest?

A: CompilerOptions.types allow you to restrict the typings you want to be available in the scope(folder)
You can try the following:
Create a top level tsconfig.json with
CompilerOptions.types = []
Inside test folder create tsconfig.json and choose jest typings
CompilerOptions.types = ['jest']
Similarly inside integration folder, create tsconfig.json and choose mocha typings
CompilerOptions.types = ['mocha']


Q: Webview Custom Back Button I need to make custom back button in WebView.
Its any way to get OnBackPress with custom button?
Just have a full screen webview, and i want to make button to going back in the webview.
Thanks.


Q: Get a scenario-by-scenario pass/fail report with JBehave I want to generate a report from JBehave that just lists the name of each scenario and a PASS/FAIL status.  Bonus points if it gives a PASS/FAIL status for a story based on the the scenario results (if all scenarios pass the story passes).  Something like:
PASS:  Story: Build a widget.
    PASS:  Scenario:  Build a normal widget.
    PASS:  Scenario:  Build a custom widget.
FAIL:  Story: Test a widget.
    PASS:  Scenario:  Test a normal widget.
    FAIL:  Scenario:  Test a custom widget.

Text is preferred but I can work with other formats.
This post:
Additional logging JBehave
shows how to use a StoryReporter to capture pass/fail for individual steps, but going through the interface I can't see how to capture the final status of a single scenario.
A commenter later in the same post mentions that there are several view genaration examples in the source distribution.  If someone can give more specific pointers to which of the examples do this that would help too.

A: The StoryReporter code below should do what you are looking for.  It keeps track of each scenario and the pass/fail status of each step in the scenario.  If any step fails, then the scenario is failed.  If any scenario fails, then the story is marked as failed.  At the end of the story it logs the results.
public class MyStoryReporter implements org.jbehave.core.reporters.StoryReporter {
private Story runningStory;
private boolean runningStoryStatus;
private String runningScenarioTitle;
private boolean runningScenarioStatus;
private List<ScenarioResult> scenarioList;
private Log log = LogFactory.getLog(this.getClass());

private class ScenarioResult {
    public String title;
    public boolean result;

    public ScenarioResult(String title, boolean result) {
        this.title = title;
        this.result = result;
    }
}

public void beforeStory(Story story, boolean b) {
    runningStory = story;
    runningStoryStatus = true;
    scenarioList = new ArrayList<>();
}

public void afterStory(boolean b) {
    String storyPrefix = runningStoryStatus ? "PASS: STORY: " : "FAIL: STORY: ";
    log.info(storyPrefix + runningStory.getName() + ".");

    String scenarioPrefix;
    for (ScenarioResult scenario : scenarioList) {
        scenarioPrefix = scenario.result ? "  PASS: SCENARIO: " : "  FAIL: SCENARIO: ";
        log.info(scenarioPrefix + scenario.title + ".");
    }
}

public void beforeScenario(String s) {
    runningScenarioTitle = s;
    runningScenarioStatus = true;
}

public void afterScenario() {
    scenarioList.add(new ScenarioResult(runningScenarioTitle, runningScenarioStatus));
    runningStoryStatus = runningStoryStatus && runningScenarioStatus;
}

public void failed(String s, Throwable throwable) {
    runningScenarioStatus = false;
}


Q: 1-2-3 star level awards algorithm What I am trying to do is to have individual star counts per level based on player performance.  (1-2-3 star awards.)  This will be based on what region the player reaches.  I know how to award the stars but keeping track of it all is throwing me problems.  First lets say a player plays level 2 and receives 1 star for their performance.  Then at a later time, s/he returns to the level and gets a 2 star. I would like the star count for that specific scene to update to two stars, while only adding 1 star ( The one extra s/he got this time) to the totalStarCount.
My initial plan was to have variables:
OldStarCount
NewStarCount
TotalStarCount

Then when a player reaches say region1, and is awarded one star, then NewStarCount would be set to one, then
TotalStarCount = TotalStarCount + (NewStarCount - OldStarCount);
Then update OldStarCount = NewStarCount;
Set NewStarCount = 0;
Move On to next Scene;

Am I approaching this the correct way? Any help would be greatly appreciated.

A: You could have something like this
int result = 0;
int totalStars = 0;
int[] starCounts = new int[NumberOfRegions};
...
currentRegion = 42;

result = play(currentRegion);
if(result > starCounts[currentRegion]){
    totalStars += result - starCounts[currentRegion];
    starCounts[currentRegion] = result;
}

This is just an example of what you could do.  There are obvious scalability issues with this (what happens when you want to add new regions, etc), but you get the gist.


Q: How to specify probabilities as a command line argument for my dna generator? I wrote some code that can spit out a dna sequence of specified length, number of copies, specified probabilities, etc. In IDLE the program works fine as I preset the probabilities I want. I want this program to run efficiently from the command line.
How can I make my probabilities (weights) run as a command line argument like I've done for length and number of copies? I have no clue how to incorporate the probabilities as an argument in the command line. Thanks for your help!
    Here is the code:
#!/usr/bin/env python

import sys
import random

weights=[.25,.25,.25,.25]
dna=['A','G','C','T']

def weighted_choice(weights,dna):
    totals = []
    running_total = 0

    for w in weights:
        running_total += w
        totals.append(running_total)

    rnd = random.random() * running_total
    for i, total in enumerate(totals):
        if rnd < total:
            return dna[i]

def dna_gen(length):

    seq=''

    for i in range(length):
        seq=seq+weighted_choice(weights,dna)
    return seq

def dna_gen2(reps,length,weights,dna):
    for i in range (reps):
        print (dna_gen(length))

def main():
    reps=int(sys.argv[1])
    length=int(sys.argv[2])
    weights=[float (w) for w in sys.argv[3:6]]
    dna_gen2(reps,length,weights,dna)

if __name__=='__main__':
    main()

A: Here you go:
#!/usr/bin/env python

import sys
import random

#weights=[.25,.25,.25,.25]
dna=['A','G','C','T']

def weighted_choice(weights,dna):
    totals = []
    running_total = 0

    for w in weights:
        running_total += w
        totals.append(running_total)

    rnd = random.random() * running_total
    for i, total in enumerate(totals):
        if rnd < total:
            return dna[i]

def dna_gen(length):
    seq=''
    for i in range(length):
        seq=seq+weighted_choice(weights,dna)
    return seq

def dna_gen2(reps,length,weights,dna):
    for i in range (reps):
        print (dna_gen(length))

if __name__=='__main__':
    reps    = int(sys.argv[1])
    length  = int(sys.argv[2])
    weights = [float (w) for w in sys.argv[3:6]]
    dna_gen2(reps,length,weights,dna)

Now when I try it on the command line:
python nameOfYourScript.py 2 2 0.25 0.25 0.25 0.25

I get:
CG
GA


Q: neighbour list with poly2nb() works on 2004 census shapefile but not on 2011 I'm trying to construct neighbours list from polygon list for Lower Layer Super Output Areas (LSOA) in London. I got my shapefiles from the London Datastore, by downloading here: https://data.london.gov.uk/dataset/statistical-gis-boundary-files-london
When I read in the 2004 shapefile (LSOA_2004_London_Low_Resolution.shp) it works perfectly:
ldn <- st_read("statistical-gis-boundaries-london/ESRI/LSOA_2004_London_Low_Resolution.shp")

#make into sp
ldn_sp <- as(ldn, "Spatial")

#create a list of neighbours using the Queen criteria (default, if you want rook chage to queen = FALSE)
w <- poly2nb(ldn_sp)

plot(ldn_sp, border = "grey60")
plot(w, coordinates(ldn_sp), pch = 19, cex = 0.6, add = TRUE)

When I read in the 2011 shapefile (LSOA_2011_London_gen_MHW.shp) however it seems to think that most of the LSOAs don't have neighbours.
When I use the 2011 one with the same code, I get this:
ldn <- st_read("statistical-gis-boundaries-london/ESRI/LSOA_2011_London_gen_MHW.shp")

ldn_sp <- as(ldn, "Spatial")

w <- poly2nb(ldn_sp)

plot(ldn_sp, border = "grey60")
plot(w, coordinates(ldn_sp), pch = 19, cex = 0.6, add = TRUE)

Does anyone have any ideas what I'm doing wrong? LSOAs which clearly should have neighbours show up with 0 links. I have no idea why...!

A: Looks like an issue with how the shapefile has been put together - polygons in LSOA_2011_London_gen_MHW.shp not sharing boundaries completely.
Using the snap argument in poly2nb will force the function to treat boundaries within a certain defined distance to be contiguous, e.g:
w <- poly2nb(ldn_sp, snap=10)

In above example, 10 = decimal degrees as your original data are in WGS84 - might want to convert to BNG and set a reasonable small distance in metres to snap. You'll need to experiment at bit, but 10 decimal degrees in the quick and dirty example above seems to generate something approximating an expected neighbours list.


Q: How to release the GIL in Cython for a multithreaded C++ class? I have a C++ class with some methods that use std::thread that I'm making accessible to Python via Cython. Do you know where in my Cython code I'd want to put the nogill directive? Would I want to put it when I declare the class methods or when I create a Cython wrapper class? I've used the example class from the Cython docs below:
Declaring the class:
cdef extern from "Rectangle.h" namespace "shapes":
    cdef cppclass Rectangle:
        Rectangle() except +
        Rectangle(int, int, int, int) except +
        int x0, y0, x1, y1
        int getArea()
        void getSize(int* width, int* height)
        void move(int, int)

Cython wrapper class:
cdef class PyRectangle:
    cdef Rectangle c_rect      # hold a C++ instance which we're wrapping
    def __cinit__(self, int x0, int y0, int x1, int y1):
        self.c_rect = Rectangle(x0, y0, x1, y1)
    def get_area(self):
        return self.c_rect.getArea()
    def get_size(self):
        cdef int width, height
        self.c_rect.getSize(&width, &height)
        return width, height
    def move(self, dx, dy):
        self.c_rect.move(dx, dy)

A: You probably don't actually need to use nogil. The GIL only stops multiple Python threads being run simulatenously. However, given you're using C++ threads they can quite happily run in the background irrespective of the GIL, provided they don't try to use PyObjects or run Python code. So my suspicion is that you've misunderstood the GIL and you can get away with not thinking about it.
However, assuming that you do actually want to release it, you need to do 2 things:

*

*Mark the C++ functions as nogil to tell Cython that they don't need the GIL. Note that this doesn't actually release it - it just lets Cython know it isn't a problem if it is released:
cdef cppclass Rectange:
   Rectangle(int, int, int, int) nogil except +
   int getArea() nogil
   # ...

*Use with nogil: blocks in your Cython wrapper class to mark the areas where the GIL is actually released.
cdef class PyRectangle:
    # ...
    def __cinit__(self, int x0, int y0, int x1, int y1):
        with nogil:
            self.c_rect = Rectangle(x0, y0, x1, y1)
    def get_area(self):
        cdef int result
        with nogil:
            result = self.c_rect.getArea()
        return result

get_area becomes slightly more complicated since the return statement can't exist inside the with nogil block since it involves generating a Python object.


Q: python logging to terminal, redirect to workspace/file I started tinkering with logging and BLE. Now I got this piece of code I took from the bgapi package. I think I kind of understand how it works, but I'd like to see the output in a file or in the workspace. How would I achieve this?
def pipe_logs_to_terminal(self, level=logging.INFO):
    term = logging.StreamHandler(sys.stdout)
    formatter = logging.Formatter(self._api._serial.portstr + ': %(asctime)s -
    %(name)s - %(levelname)s - %(message)s')
    term.setFormatter(formatter)
    api_logger = logging.getLogger("bgapi")
    api_logger.addHandler(term)
    api_logger.setLevel(level=level)

A: You simply use logging.FileHandler(). I tried to implement it in your method:
def pipe_logs_to_terminal(self, level=logging.INFO):
    log_path = "."  # cwd
    file_name = "my_app"
    # configure root logger
    api_logger = logging.getLogger("bgapi")
    api_logger.setLevel(level=level)
    # set format
    formatter = logging.Formatter(self._api._serial.portstr + ': %(asctime)s - %(name)s - %(levelname)s - %(message)s')
    # configure file handler
    file_handler = logging.FileHandler("{0}/{1}.log".format(log_path, file_name))
    file_handler.setFormatter(formatter)
    api_logger.addHandler(file_handler)
    # configure console handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(formatter)
    api_logger.addHandler(console_handler)

Optionally you could omit the console_handler (called term in your example) part, if you choose to only pipe your logging into a file.


Q: Can't seem to remove any annotations I have some pins that the user can add. In the callout there is a button.
When the user presses the button, I want a new pin to drop in that location, and I want to get rid of the pin that the user pressed (different types of pins).
Basically the first pin is draggable, and when the user has found a proper location they will "lock" it. (the locked pin acts differently in a few ways, which is why I need to replace the old pin)
anyways, this is the method where I do my processing. When I get to the [mapView removeAnnotation:view.annotation]; part all I get is "Program received signal:  “EXC_BAD_ACCESS”."
Can anybody help me out here? (The issue is not that the new annotation does not appear, as it does appear. The issue is that the old annotation does not dissapear).
EDIT: Fixed code as per suggestion.
    - (void) mapView:(MKMapView *)MapView
      annotationView:(MKAnnotationView *)view
calloutAccessoryControlTapped:(UIControl *)control {
    LockedPotholeAnnotation *annotation = [[[LockedPotholeAnnotation alloc] initWithCoordinate:view.annotation.coordinate addressDictionary:nil]autorelease];
     NSString *titleString = [NSString stringWithFormat:@"Pothole at %.4f, %.4f", view.annotation.coordinate.latitude, view.annotation.coordinate.longitude];
     annotation.title = titleString;
     [mapView addAnnotation:annotation];
     //[annotation release];
     NSLog(@"Added Pin");
     NSLog(@"VA: %@", [view.annotation class]);
     [mapView removeAnnotation:view.annotation];
     //[mapView removeAnnotations:mapView.annotations];
     [mapView setNeedsDisplay];
}

A: This may not be the only thing, but the first thing that leaps out is that you autorelease the annotation on the line where you alloc it. Therefore you shouldn't also release it after you've added it to mapView.
As this stands, the annotation will likely be prematurely deallocated when the autorelease pool drains -- and if not exactly then, then at some subsequent point that is still premature. The map view will be stuck with a stale pointer and boom.
Not sure why that would manifest quite as soon as you describe, so there may be something else too...


Q: How to create a data frame aggregating the daily ticket numbers to monthly count? I am having the list of ticket numbers for each date. Date column is transformed to data but the ticket number column is a text.
Created       Ticket
01-Jan-19   a1
02-Jan-19   a2
03-Jan-19   a3
04-Jan-19   a4
05-Jan-19   a5
06-Jan-19   a6
07-Jan-19   a7
08-Jan-19   a8
09-Jan-19   a9
10-Jan-19   a10
11-Jan-19   a11
12-Jan-19   a12
13-Jan-19   a13
14-Jan-19   a14
15-Jan-19   a15
16-Jan-19   a16
17-Jan-19   a17
18-Jan-19   a18
19-Jan-19   a19
01-Feb-19   a20
02-Feb-19   a21
03-Feb-19   a22
04-Feb-19   a23

Tried to use floor data in R but since the ticket number column is character I am not able to use it.
data <- read.csv(file = 'D:\\DS Data\\SampleTickets.csv', stringsAsFactors = FALSE,header = TRUE)

str(data)
library(readr)
library(lubridate)
library(dplyr)

data <- data %>%
  mutate(Created = dmy(Created))

data %>% group_by(month=floor_date(Created, "month")) %>%
  summarize(amount=sum(Ticket))

I am expecting a data frame output like..
CreatedMonth     CountOfTickets
1/1/2019             18
1/2/2019              4

A: You were nearly there: Just use n() instead of sum(Ticket) to count the number of rows:
library(dplyr)
library(lubridate)
data %>%
  mutate(Created = dmy(Created)) %>%
  group_by(month = floor_date(Created, "month")) %>%
  summarize(amount = n())

# A tibble: 2 x 2
  month      amount
  <date>      <int>
1 2019-01-01     19
2 2019-02-01      4

However, there is a shortcut which uses count():
data %>%
  count(CreatedMonth = dmy(Created) %>% floor_date("month"))

# A tibble: 2 x 2
  CreatedMonth     n
  <date>       <int>
1 2019-01-01      19
2 2019-02-01       4

For the sake of completeness, here is also a data.table version:
library(lubridate)
library(data.table)
setDT(data)[, .N, by = .(CreatedMonth = floor_date(dmy(Created), "month"))]

   CreatedMonth  N
1:   2019-01-01 19
2:   2019-02-01  4

Data
data <- readr::read_table("Created       Ticket
01-Jan-19   a1
02-Jan-19   a2
03-Jan-19   a3
04-Jan-19   a4
05-Jan-19   a5
06-Jan-19   a6
07-Jan-19   a7
08-Jan-19   a8
09-Jan-19   a9
10-Jan-19   a10
11-Jan-19   a11
12-Jan-19   a12
13-Jan-19   a13
14-Jan-19   a14
15-Jan-19   a15
16-Jan-19   a16
17-Jan-19   a17
18-Jan-19   a18
19-Jan-19   a19
01-Feb-19   a20
02-Feb-19   a21
03-Feb-19   a22
04-Feb-19   a23")

A: Using dplyr we can first convert Created column to actual Date and group them by each month and count number of tickets for each group.
library(dplyr)
df %>%
  mutate(Created = as.Date(Created, "%d-%b-%y")) %>%
  arrange(Created) %>%
  mutate(Yearmon = format(Created, "%B-%Y"),
         Yearmon = factor(Yearmon, levels = unique(Yearmon))) %>%
  group_by(Yearmon) %>%
  summarise(count = n())

# Yearmon       count
#  <fct>         <int>
#1 January-2019     19
#2 February-2019     4


Q: LINQ Join/Grouping issues So I am stuck again...
I have three tables that I am trying to join and group with linq; Company, Notices and Requests.

*

*A company could have many notices.

*A notice have a SubcategoryId and a CompanyId

*A request have a SubcategoryId.
My aim here is to get a list of companies and for each company get a list of their noticed subcategories and for each noticed subcategory the requests within that subcategory
Ex:
Company x is monitoring the subcategories 4 and 7.
Show him what requests we've got within those subcats.
This is how I do it for only one company. But I can't solve the grouping and joins when I need a list of multiple companies.
Company company = db.Companies.Where(x=>x.UserId == 10).FirstOrDefault();
            var requestByNotices =
            from notice in company.Notices
            join request in db.Requests.Where(z => z.IsApproved &
                 z.Status.Status == "Active") on notice.SubcategoryId equals
                 request.Subcategoryid

UPDATE
Let me rephrase my questions.
This query is producing a table with the results I am looking for:
SELECT Companies.CompanyId, Companies.Name, Account.Email, Notices.SubcategoryId, Requests.FriendlyName FROM Companies
INNER JOIN Notices  ON Companies.CompanyId = Notices.CompanyId
INNER JOIN Account  ON Account.UserId = Companies.Uid
INNER JOIN Requests ON Notices.SubcategoryId = Requests.Subcategoryid
WHERE Requests.StartDate > '2013-12-22';

But instead of generating a flat list I would like to translate this into to linq but also group by CompanyId. So each company is represented by one row only and within that company I can get the requests.
So instead of a list like this:
CompanyId   Name   Email            SubcategoryId     FriendlyName
1           Test   test@test.com    2                 x
1           Test   test@test.com    4                 y

I would like to have it like this:
CompanyId   Name   Email            GroupOfRequests
1           Test   test@test.com    contains two

Thankful for any help!

A: UPDATED: if i understand right you want something like this
var result =
        from company in db.Companies
        from notice in company.Notices
        join request in db.Requests.Where(z => z.IsApproved &&
             z.Status.Status == "Active") on notice.SubcategoryId equals request.Subcategoryid
        group new {notice, request } by company into gr
        select new {gr.Key, Value = gr.ToList() }

UPDATE2
for your sql it seems like this
from company in db.Companies
join notice in db.Notices on company.CompanyId equals notice.CompanyId
join account in db.Account on company.Uid equals account.UserId
join request in db.Requests on notice.SubcategoryId equals request.SubcategoryId

group new {notice, request} by new {company, account} into g
select new {g.Key, value = g}


Q: Do WebAudio scriptProcessorNodes *require* an output to be connected? Here is a link to a simple jsFiddle which measures the loudness of a live input using web-audio (it outputs the values as a percentage to the console).
http://jsfiddle.net/XSnsF/
I was planning to have one input and no outputs, since there's no need to delay my audio signal waiting for my custom node to finish working out the volume.
However, it soom became apparent that the scriptProcessor only logs the values if it's connected to context.destination. Am I doing something wrong? Or is this a bug? Or is this the expected behaviour?
function gotStream(stream) {

    var mediaStreamSource = context.createMediaStreamSource(stream);

    var gainNode = context.createGain();
    gainNode.gain.value = 3;

    var levelChecker = context.createScriptProcessor(2048);

    mediaStreamSource.connect(gainNode);
    gainNode.connect(levelChecker);

    //Commenting out the line directly below stops the script processor from working!
    levelChecker.connect(context.destination);
    levelChecker.onaudioprocess = process;

}

function process(e) {
    var buffer = e.inputBuffer.getChannelData(0);

    var maxVal = 0;

    for (var i = 0; i < buffer.length; i++) {

        if (maxVal < buffer[i]) {
            maxVal = buffer[i];
        }
    }

    console.log(Math.round(maxVal * 100) + "%");
}

A: It's a bug in the Blink & Webkit implementations.  From the spec: "audioprocess events are only dispatched if the ScriptProcessorNode has at least one input or one output connected."  It doesn't need both.
For now, just connect it to a zero-gain GainNode connected to the audiocontext.destination.


Q: Bootstrap 3 2 Column Full Height Fixed Header and Footer I'm having issues trying to make a 3 column full height layout work, but with a fixed nav, and fixed footer.
I can get the basics to work, 2 columns, with fixed nav and footer, but when I attempt to enable full height on the columns it tends to break completely.
On some attempts to resolve this the content disappears under the footer, and spills out below it. Other times when you resize the browser to test responsive elements, the footer sticks to the content pain when scrolling up the content, and not the bottom of the browser.
Is there any way to achieve this on a responsive framework? Or is it easier just to re-jig the design, or even fake full height, say by using a positioned repeating background. But then again that wouldn't be responsive either.
I've spent over 2-3 hours on this, so I'm throwing myself on the mercy of someone with better front end skills than I. Help!


Q: Problems running FFprobe with Ruby I am fairly new to Ruby and programming, less than a year experience. This is ruby 1.9.3 and the newest ffmpeg for Ubuntu from FFmpeg. Files I am using are basic .avi, some v210 .mov, other quicktime/finalcutpro types of files.
I am trying to write an automated probing tool that will help lessen the manual work load for me when I start testing with and dealing with lots of media files. Basically the script goes through a directory and probes each file, extracting the info I need, and writes it out to csv.
Currently, everytime I run it, the actual capture on command line is failing.
def prober(file)
  @the_file = file
  stdout,stderr,status = Open3.capture3("ffprobe -v quiet -print_format json -      show_format -show_streams #{@the_file}")
  STDERR.puts stderr
  if status.success?
    out = stdout
  else
    STDERR.puts "There was a problem, please try again."
  end
  @raw_output = JSON.parse(out)
end

I don't know if it is something to do with how I am running the command (I don't really fully understand I/O streams), or something with ffprobe. When it does make it past the probe it is returning @raw_output as nil, which causes JSON parsing to puke, or my other methods for splitting and parsing the metadata fail on nil.
Any help at all would great, I have been stuck on this for a while. Thanks! I can provide more code if needed for clarification,.

A: After the holidays I came back fresh and found the problem. The filepath string needs to have quotes around it when fed to the stdin for ffprobe, but when I aggregated the files it stripped the quotes. The fix? add quotes around the filepath in the string.
I hope this helps someone, apparently I am the only person in the whole internet to have this problem.


Q: How to avoid a reflow when changing box-shadow or text-shadow properties? This is my test css:
.btn {
    display: block;
    height: 30px;
    width: 30px;
    background-color: red;
    position: relative;
}
.btn:hover {
    box-shadow: 0 0 0 1px black;
    text-shadow: 0 0 1px black;
}

Applied to a simple div with the "btn" class. Using Firefox's 28 Web Developer Console I discovered that 1 reflow is executed every time the mouse goes hover the div, and another reflow is executed when the mouse is no more hover the div.
If I change the "position" property from "relative" to "absolute" nothing changes, neither if I deactivate the "text-shadow" or the "box-shadow" property. The only way that I've found that doesn't trigger the two reflows is by disablig both the "box-shadow" and the "text-shadow" properties.
Why is this happening and how I can avoid the execution of the two reflows?


Q: Download file from tag library in jsp file I created a tag library to display a table same as 'display tag' with some other features. Now I would like to add download option to the tag library. I tried it with just changing the content type and resetting the response but that was not possible as the contents before in the response are already flushed.
     I found the 'display tag' uses a filter namely 'ResponseOverrideFilter' to prevent contents to be sent so that the resetting response would work. But I did not find any line of code in my 'web.xml' about the filter registration and url-mapping as I used the 'display tag'. Please help me. Thanking you in-advance...
taglibrary :
        <disp:dipxTable id="outer"  style="width:60%; margin-left:20%" list="<%=dtoList %>"  >
             <disp:dipxColumn sortable="true" href="javascript:showReport('${pageUrl }', '${row.monthName }', '${row.year}')" group="1" style="text-align:center;" property="monthName" title="Month"/>
             <disp:dipxColumn group="2" style="text-align:center;" sortable="true"  property="distanceRange" title="Distance"/>
             <disp:dipxColumn   style="text-align:center;" sortable="true"  property="vehicleType" title="Cab"/>
             <disp:dipxColumn style="text-align:center;" sortable="true"  property="totalTrips" expandable="true"  title="#.Trips"/>
             <disp:dipxColumn style="text-align:center;" sortable="true" property="rate" title="Trip Cost"  />
             <disp:dipxColumn style="text-align:center;" sortable="true"  format="{0,number,0.00}"  property="escortRate" title="Escort Cost" />

             <disp:dipxTable id="inner" type="inner" property="trips" parentProperty="totalTrips" >
                <disp:dipxColumn property="trip_code" title="Trip Code" />
                <disp:dipxColumn property="tripDate"  title="Trip Date" />
                <disp:dipxColumn property="trip_time"  title="Time" />
                <disp:dipxColumn property="trip_log"  title="Shift" />
                <disp:dipxColumn property="tripRate"  title="Trip Rate" />
                <disp:dipxColumn property="escortRate"  title="Escort Cost" />

             </disp:dipxTable>

              <disp:DispxGroupSummaryRow groupProperty="monthName" id="grp">

                 <disp:dipxColumn style="text-align:center; font-weight:bold;"  property="totalTrips" />
                 <disp:dipxColumn style="text-align:center; font-weight:bold;"  property="rate"  />
                 <disp:dipxColumn style="text-align:center; font-weight:bold;"  property="escortRate" format="{0,number,0.00}" />
             </disp:DispxGroupSummaryRow>
             <disp:DispxSummaryRow style="background-color:#fff;" >

                Grand Total

                 <disp:dipxColumn style="text-align:center; font-weight:bold;"  property="totalTrips" />
                 <disp:dipxColumn style="text-align:center; font-weight:bold;"  property="rate"  />
                 <disp:dipxColumn style="text-align:center; font-weight:bold;"  property="escortRate"  format="{0,number,0.00}"  />

             </disp:DispxSummaryRow>

        </disp:dipxTable>

tld file content of tag dispxTable
<tag>
        <description>This tag is parent tag to display table </description>
        <name>dipxTable</name>
        <tag-class>com.nfl.table.DispxTable</tag-class>
        scriptless
        <attribute>
            <name>list</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>type</name>
             <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>property</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>parentProperty</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>id</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>name</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>style</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>styleClass</name>
            <required>false</required>
             <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>headerRowStyleClass</name>
            <required>false</required>
             <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>headerRowStyle</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>rowStyleClass</name>
            <required>false</required>
             <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>rowStyle</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>expanded</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>

</tag>

Tag support Class
enter code here

package com.nfl.table;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import com.nfl.dto.SorterFood;
import com.nfl.dto.support.NflJSONObject;
import com.nfl.dto.support.Sorter;
import com.nfl.dto.support.exception.NflJSONException;
import com.nfl.table.container.ColumnContainer;

public class DispxTable  extends SimpleTagSupport implements ColumnContainer {
/* type of table , inner or outer */
private String type;

/* property name of object to be displayed */
private String property;

/* property name of parent table where this table is drawn as child table of the given property */
private String parentProperty;

/* class attribute of table */
private String styleClass;

/* style attribute of table */
private String style;

/* style attribute of th within thead */
private String headerRowStyle;

/* style attribute of tr within thead */
private String headerRowStyleClass;

/* style attribute of tr within tbody */
private String rowStyle;

/* class attribute of tr within tbody */
private String rowStyleClass;

/* this is a property of inner table to render as expanded by default */
private boolean expanded;

/* id attribute of table */
private String id;

private int colomns;
private boolean groupPropegation;

public String getHeaderRowStyle() {
    return headerRowStyle;
}
public void setHeaderRowStyle(String headerRowStyle) {
    this.headerRowStyle = headerRowStyle;
}
public String getHeaderRowStyleClass() {
    return headerRowStyleClass;
}
public void setHeaderRowStyleClass(String headerRowStyleClass) {
    this.headerRowStyleClass = headerRowStyleClass;
}
public String getRowStyle() {
    return rowStyle;
}
public void setRowStyle(String rowStyle) {
    this.rowStyle = rowStyle;
}
public String getRowStyleClass() {
    return rowStyleClass;
}
public void setRowStyleClass(String rowStyleClass) {
    this.rowStyleClass = rowStyleClass;
}
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
private Object row;

/* each dto is kept as NflJSONObject as a generic */
private NflJSONObject summaryItem;

/* keeps summary attributes */
private Map<String, NflJSONObject> groupSummaryMap = new HashMap<String, NflJSONObject>();

public String getType() {
    return type;
}
public void setType(String type) {
    this.type = type;
}
public String getProperty() {
    return property;
}
public void setProperty(String property) {
    this.property = property;
}
private int level;
private Object innerList;
private Object list;
private   NflJSONObject item;
private   NflJSONObject preItem;
private   NflJSONObject nextItem;
public NflJSONObject getPreItem() {
    return preItem;
}
public void setPreItem(NflJSONObject preItem) {
    this.preItem = preItem;
}
private String name="sddfd";
private boolean isHeader;
private int rowCount;
private  HashMap<Integer, SorterFood> groupMap= new HashMap<Integer, SorterFood>();
private HashMap<Integer, SorterFood> sortMap= new HashMap<Integer, SorterFood>();

private HashMap<Integer, SorterFood>   putAll(HashMap<Integer, SorterFood> pgMap,HashMap<Integer, SorterFood> psMap) {
    HashMap<Integer, SorterFood> allMap=new HashMap<Integer, SorterFood>();

    Set<Integer> keys=null;
    int i=0;
    if(pgMap!=null&&pgMap.size()>0) {
        keys= pgMap.keySet();

        for(int key:keys) {
            allMap.put(key, pgMap.get(key));
            //System.out.println("pg keys " + key+" i:"+i);
            //System.out.println("putting ("+key+", "+" "+psMap.get(key)+")");
            if(key>i) {
                i=key;
            }
        }
    }
    if(psMap!=null&&psMap.size()>0) {
        keys= psMap.keySet();

        for(int key:keys) {

            Set <Integer> gkeys=pgMap.keySet();
            boolean contains=false;
            for(int gkey:gkeys) {
                SorterFood gSf=pgMap.get(gkey);
                SorterFood sSf= psMap.get(key);
                if(gSf.getProperty().equals(sSf.getProperty())) {
                    contains=true;

                    allMap.put(gkey,sSf);

                    break;
                }

            }
            if(!contains) {
                allMap.put(i+1, psMap.get(key));
            }

         i++;
        }

    }

    return allMap;

}

public NflJSONObject getItem() {
    return item;
}
public void setItem(NflJSONObject item) {
    this.item = item;
}
public HashMap<Integer, SorterFood> getGroupMap() {
    return groupMap;
}
public void setGroupMap(HashMap<Integer, SorterFood> groupMap) {
    this.groupMap = groupMap;
}
public HashMap<Integer, SorterFood> getSortMap() {
    return sortMap;
}
public void setSortMap(HashMap<Integer, SorterFood> sortMap) {
    this.sortMap = sortMap;
}
public Object  getList() {
    return list;
}
public void setList(Object  list) {
    this.list = list;
}

private String returnClass() {
    String styleString="";
    if(styleClass==null||styleClass.trim().equals("") ) {

         styleString="class=\"displaytag\"";
    }else {
        // System.out.println("=================================class=="+styleClass);
         styleString="class=\""+ styleClass+"\"";
    }

    return styleString;

}

private String returnHeaderClass() {
    String styleString="";
    if(headerRowStyleClass ==null||headerRowStyleClass.trim().equals("") ) {

         styleString="";
    }else {
        //    System.out.println("=================================class=="+styleClass);
         styleString="class=\""+ headerRowStyleClass+"\"";
    }

    return styleString;

}

private String returnHeaderStyle() {
    String styleString="";
    if(headerRowStyle!=null&&headerRowStyle.trim().equals("")==false ) {

         styleString=" style=\""+ headerRowStyle+"\" ";
    }

    return styleString;

}

private String returnRowClass(int index) {
    String styleString="";
    String commonClass= ((index%2==0)?"even":"odd") ;
    if(rowStyleClass ==null||rowStyleClass.trim().equals("") ) {

         styleString= "class=\"" + commonClass+ "\"";

    }else {
        // System.out.println("=================================class=="+styleClass);
         styleString="class=\"" + commonClass + " "+ rowStyleClass+"\"";
    }

    return styleString;

}

private String returnRowStyle() {
    String styleString="";
    if(rowStyle!=null&&rowStyle.trim().equals("")==false ) {

         styleString=" style=\""+ rowStyle+"\" ";
    }

    return styleString;

}

private String returnStyle() {
    String styleString="";
    if(style!=null&&style.trim().equals("")==false ) {

         styleString=" style=\""+ style+"\" ";
    }

    return styleString;

}

@Override
public void doTag() throws JspException, IOException {
    // TODO Auto-generated method stub

     PageContext ctx = (PageContext)getJspContext();

     HttpServletRequest request = (HttpServletRequest) ctx.getRequest();
     HttpServletResponse response = (HttpServletResponse) ctx.getResponse();

     String download=request.getParameter("download");
     if(download!=null&&download.equals("xls")) {
         String mimeType = "application/vnd.ms-excel";
         //response.flushBuffer();

    //  response.reset();
     //    ctx.getOut().clearBuffer();
     //  response.flushBuffer();

        /* for(String s:response.getHeaderNames()) {
             // System.out.println("Header "+s + " value "+response.getHeader(s));
         }*/
         response.setContentType(mimeType);
         String fname = new Date().toString();
         response.setHeader("Content-Disposition", "inline; filename = APL" + fname + ".xls");
         response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
         response.setHeader("Cache-Control", "post-check=0, pre-check=0");
         response.setHeader("Pragma", "no-cache");
         response.setHeader("Pragma", "public");
         response.setHeader("Expires", "Mon, 1 Jan 1995 05:00:00 GMT");
         Boolean b = (Boolean) ctx.getAttribute("pageStarted");
/*         if(b==null||b==false) {
         ctx.getOut().write("<form>");
         ctx.setAttribute("pageStarted", true);
         }*/

     }

    JspWriter out = getJspContext().getOut();

    List list = (List) getList();
    preItem=null;
    if(type!=null&&type.equals("inner"))
    {

        /*
         * inner table starts
         */

        DispxTable t= (DispxTable) getParent();
         int myRowCount=t.getRowCount();
         if(!t.isHeader())
         {

             if(t!=null)
                {
                 // System.out.println("inner table row ");
                 //org.json.JSONObject obj= new org.json.JSONObject(t.getItem());
                 NflJSONObject obj;

                 /*catch (JSONException e) {
                    // TODO Auto-generated catch block
                //  e.printStackTrace();
                    // System.out.println(""+e);
                    out.write("

"+e+"

");
                }*/

                  //// System.out.println("Param "+  request.getParameter("expandableProperty"));
                    String paramRowCount=request.getParameter(t.getId()+"-rowCount");
                       String exandablePropery=request.getParameter(t.getId()+"-expandableProperty");
                      parentProperty= parentProperty==null?"":parentProperty;
                   exandablePropery= exandablePropery==null?"":exandablePropery;

                     if((parentProperty.equals("")||exandablePropery.equals("")) ==false&& parentProperty.equals(exandablePropery)&&String.valueOf(myRowCount).equals(paramRowCount) || isExpanded())
                    {
                     try {
                         obj= t.getItem();
                        level=t.getLevel()+1;
            //              // System.out.println("subjects : "+obj.get(property));
                        Object object= obj.get(property);
                        list = (List) object;

                        if(list!=null&&list.size()>0)
                        {

                            setList(list);
                            out.write("
 ");
                            out.write("
");
                            String tableStart=String.format("Close

",id,returnStyle(), returnClass(),"id=\""+id+"\"", returnHeaderClass(), returnHeaderStyle() );
                            isHeader=true;
                            out.write(tableStart);
                            row=list.get(0);
                            getJspBody().getJspContext().setAttribute("row", row);

                            getJspBody().invoke(out);

                            out.write("

");
                            isHeader=false;
                            Map<Integer,SorterFood> allMap= putAll(getGroupMap(), getSortMap());
                            //System.out.println("Sort map size :"+ sortMap.size());
                            //System.out.println("All map size :"+ allMap.size());
                            if(allMap!=null&&allMap.size()>0) {
                                list=Sorter.sort(list, allMap);
                            }
                            rowCount=0;
                            for(Object o:list){
                                setGroupPropagation(true);
                                setColomns(0);
                                row=o;

                                item=new NflJSONObject( row);
                                if(list.indexOf(o)<(list.size()-1)) {
                                    nextItem = new NflJSONObject( list.get(list.indexOf(o)+1));
                                } else {
                                    nextItem = new NflJSONObject();
                                }
                                getJspBody().getJspContext().setAttribute("row", row);
                                getJspBody().getJspContext().setAttribute("rowCount",list.indexOf(row));
                                out.write(String.format("
 ", returnRowClass(list.indexOf(row)), returnRowStyle()) );
                                getJspBody().invoke(null);
                                preItem=item;
                                out.write("
");
                                rowCount++;
                            }
                            out.write("

");
                            out.write("
 ");
                            out.write("
  	 ");
                        }

                    } catch (  NflJSONException e) {
                        // TODO Auto-generated catch block
                        throw new IOException(""+e);
                    }

                    }

                }

         }

        /*
         * inner table ends
         */

    } else if(list!=null&&list.size()>0)
    {

        String tableStart=String.format("

",returnStyle(), returnClass(),"id=\""+id+"\" ", returnHeaderClass(), returnHeaderStyle() );
        isHeader=true;
        out.write(tableStart);
        row=list.get(0);
        getJspBody().getJspContext().setAttribute("row", row);

        getJspBody().invoke(null);

        out.write("

");
        isHeader=false;
        Map<Integer,SorterFood> allMap= putAll(getGroupMap(), getSortMap());
        //System.out.println("Group map size >"+ getGroupMap().size());
        //System.out.println("Sort map size >"+ getSortMap().size());
        //System.out.println("All map size >"+ allMap.size());
        if(allMap!=null&&allMap.size()>0) {
            list=Sorter.sort(list, allMap);
        }

        rowCount=0;
        for(Object o:list){
            setGroupPropagation(true);
            setColomns(0);
            row=o;
            // System.out.println("outer table row open");

            try {
                item=new NflJSONObject( o);
                if(list.indexOf(o)<(list.size()-1)) {
                    nextItem = new NflJSONObject( list.get(list.indexOf(o)+1));
                } else {
                    nextItem = new NflJSONObject();
                }
            } catch (NflJSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //ctx.setAttribute("row", item);

            getJspBody().getJspContext().setAttribute("row", row);
            getJspBody().getJspContext().setAttribute("rowCount",list.indexOf(row));
            out.write(String.format("
 ", returnRowClass(list.indexOf(row)), returnRowStyle() ) );
            getJspBody().invoke(out);
            preItem=item;
            out.write("
 ");
            // System.out.println("outer table row close");
            rowCount++;
        }
        out.write("

");
    }else
    {
        out.write("
 No display
");
    }

/*  if(download!=null&&download.equals("xls")) {
        Boolean b = (Boolean) ctx.getAttribute("pageStarted");
        if(b!=null&&b==true) {

            out.write("</form>" );
        ctx.setAttribute("pageStarted", true);
        }

    }
    */

}
public boolean isHeader() {
    return isHeader;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Object getInnerList() {
    return innerList;
}
public String getParentProperty() {
    return parentProperty;
}
public void setParentProperty(String parentProperty) {
    this.parentProperty = parentProperty;
}
public int getRowCount() {
    return rowCount;
}
public void setRowCount(int rowCount) {
    this.rowCount=rowCount;
}
public int getColomns() {
    return colomns;
}
public void setColomns(int colomns) {
    this.colomns = colomns;
}
public String getStyleClass() {
    return styleClass;
}
public void setStyleClass(String styleClass) {
    this.styleClass = styleClass;
}
public NflJSONObject getSummaryItem() {
    return summaryItem;
}
public void setSummaryItem(NflJSONObject summaryItem) {
    this.summaryItem = summaryItem;
}
public Object getRow() {
    return row;
}
public void setRow(Object row) {
    this.row = row;
}
public int getLevel() {
    return level;
}
public String getStyle() {
    return style;
}
public void setStyle(String style) {
    this.style = style;
}
@Override
public void setGroupPropagation(boolean flag) {
    // TODO Auto-generated method stub
    groupPropegation = flag;

}
@Override
public boolean hasGroupPropagation() {
    // TODO Auto-generated method stub
    return groupPropegation;
}
public NflJSONObject getNextItem() {
    return nextItem;
}
public void setNextItem(NflJSONObject nextItem) {
    this.nextItem = nextItem;
}
public Map<String, NflJSONObject> getGroupSummaryMap() {
    return groupSummaryMap;
}
public boolean isExpanded() {
    return expanded;
}
public void setExpanded(boolean expanded) {
    this.expanded = expanded;
}

}
I dont think you need all this details to answer on how to just register a filter which is defined in taglibary.


Q: Gitlab - path to git command I have took over sel-hosted gitlab from former co-worker. I have a qustion about git version/location which gitlab use because I wanted to do upgrade which require git 2.31.x and later. Server is CentOS 7.9. I have found several different versions in the system. How do I find which one is used by gitlab?
By "yum list installed":
git.x86_64                       1.8.3.1-23.el7_8                         @updates

"git --version"
git version 2.8.0

Gitlab web intefrace -> Admin area -> Overview -> Gitaly Servers
git version 2.29.0

"whereis git":
git: /usr/bin/git /usr/local/git /usr/local/git/bin/git /usr/share/man/man1/git.1.gz /usr/src/git-2.8.0/git.c /usr/src/git-2.8.0/git.rc /usr/src/git-2.8.0/git.spec /usr/src/git-2.8.0/git.o /usr/src/git-2.8.0/git

Thank you
EDIT:
su git
which git
   => /usr/local/git/bin/git
/usr/local/git/bin/git --version
   => git version 2.8.0

gitlab.yml:
git: /opt/gitlab/embedded/bin/git
/opt/gitlab/embedded/bin/git --version
   => git version 2.29.0

So I can yum remove git and rm -rf /usr/local/git/ because gitlab use /opt/gitlab/embedded/bin/git?


Q: What does SomeMethod(() => x.Something) mean in C# (Note the code is an example)
I have the following syntax:
SomeMethod(() => x.Something)

What do the first brackets mean in the expression?
I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?

A:
What do the first brackets mean in the expression?

It's the lambda syntax for a method that takes no parameters. If it took 1 parameter, it'd be:
SomeMethod(x => x.Something);

If it took n + 1 arguments, then it'd be:
SomeMethod((x, y, ...) => x.Something);

I'm also curious how you can get the property name from argument that is being passed in. Is this possible?

If your SomeMethod takes an Expression<Func<T>>, then yes:
void SomeMethod<T>(Expression<Func<T>> e) {
    MemberExpression op = (MemberExpression)e.Body;
    Console.WriteLine(op.Member.Name);
}

A: The () is an empty argument list. You're defining an anonymous function that takes no arguments and returns x.Something.
Edit: It differs from x => x.Something in that the latter requires an argument and Something is called on that argument. With the former version x has to exist somewhere outside the function and Something is called on that outside x. With the latter version there does not have to be an outside x and even if there is, Something is still called on the argument to the function and nothing else.

A: It's a lambda expression.  That is, it's a way to create an anonymous function or delegate.
The general form is:
(input parameters) => expression

If you have
() => expression

then you have created a function that takes no arguments, and returns the result of the expression.
C# uses type inference to figure out what the types of the values are, and it captures local variables (like your "x" variable) by means of a lexical closure.

A: I assume x is declared in somewhere inside your method, if yes, you can compare this lambda expression with a delegate that has no paramaters and return the type of x.someproperty
delegate{
 return x.someproperty;
}

that is the same as:
() => x.someproperty

A: the () mean that this method doesn't take any parameters.
for example, if you assign a normal event handler using a lambda expression, it would look like this:
someButton.Click += (s, e) => DoSomething();

A: See also the following two blog posts that discuss exactly your second question and provide alternative approaches:
How to Find Out Variable or Parameter Name in C#?
How to Get Parameter Name and Argument Value From C# Lambda via IL? (Or "How NOT to Use .NET Linq Expressions in Order to Get Parameter Name and Argument Value From C# Lambda?")

A: To get the name of the property you need SomeMethod to have an argument of the type of System.Linq.Expressions.Expression<System.Func<object>>. You can then go through the expression to determine the property name.


Q: Input definition optional keys I generated an action with sails generate action task/update-task. I now am trying to create an input parameter that should be an object with optional keys:
  inputs: {
    fields: {
      type: {
        body: 'string?',
        rruleSetStr: 'string?',
      },
      required: true,
      description: 'All keys are not required, but at least one is'
    },

However I keep getting error:
 The action `task/update-task` could not be registered.  It looks like a machine definition (actions2), but it could not be used to build an action.
Details: ImplementationError: Sorry, could not interpret "task/update-task.js" because its underlying implementation has a problem:
------------------------------------------------------
• Invalid input definition ("fields").  Unrecognized `type`.  (Must be 'string', 'number', 'boolean', 'json' or 'ref'.  Or set it to a type schema like `[{id:'number', name: {givenName: 'Lisa'}}]`.)
------------------------------------------------------

If you are the maintainer of "task/update-task.js", then you can change its implementation to solve the problem above.  Otherwise, please file a bug report with the maintainer, or fork your own copy and fix that.
 [?] See https://sailsjs.com/support for help.
    at machineAsAction (C:\Users\Mercurius\Documents\GitHub\Homie-Web\node_modules\machine-as-action\lib\machine-as-action.js:271:28)
    at helpRegisterAction (C:\Users\Mercurius\Documents\GitHub\Homie-Web\node_modules\sails\lib\app\private\controller\help-register-action.js:63:27)
    at C:\Users\Mercurius\Documents\GitHub\Homie-Web\node_modules\sails\lib\app\private\controller\load-action-modules.js:146:13

Does anyone know where the documentation is on how to make optional keys in this? I tried here - http://node-machine.org/spec/machine#inputs - but no luck.

A: Type must be 'string', 'number', 'boolean', 'json' or 'ref' like error say.
So u need set type to 'ref' (object or array), and u can use custom function for validate.
inputs: {
        fields: {
            type: 'ref',
            custom: function (data) {
                // some logic
                // example
                if (typeof data.body !== "string") {
                    return false;
                    // or u can use trow Error('Body is not a string')
                }
                return true;
            },
            required: true,
            description: 'All keys are not required, but at least one is'
        }

Now input is type object and in custom function return false or trow Error('Some problem') break validation.
If u use schema type, just remove ? from your example:
inputs: {
        fields: {
            type: {
              body: 'string',
              rruleSetStr: 'string'
            },
            required: true,
            description: 'All keys are not required, but at least one is'
        }

This is Runtime (recursive) type-checking for JavaScript., please check documentation for writing rules.


Q: iteration with the list monad I'm having trouble understanding how the iterative behavior of the list monad can be derived from its definition.
instance Monad [] where
  m >>= f  = concatMap f m
  return x = [x]
  fail s   = []

Discussions I've read seem to pass over the question of how >>= creates a control structure, as shown most clearly with do notation:
allEvenOdds :: Int -> [(Int,Int)]
allEvenOdds n = do
  evenValue <- [2,4 .. n]
  oddValue <- [1,3 .. n]
  return (evenValue,oddValue)

Is this built in to Haskell, the way I assume the IO monad's interface to actual i/o is?

A: There's nothing built-in, everything is a simple consequence of the Monad instance you quoted (and, since this example uses do notation, how that desugars to uses of the >>= operator):
allEvenOdds n = do
  evenValue <- [2,4 .. n]
  oddValue <- [1,3 .. n]
  return (evenValue,oddValue)

-- desugaring the do notation
allEvenOdds n =
  [2,4 .. n] >>= \evenValue ->
  [1,3 .. n] >>= \oddValue ->
  return (evenValue, oddValue)

-- using the list instance of Monad to replace >>= and return
allEvenOdds n =
  concatMap (\evenValue ->
    concatMap (\oddValue -> [(evenvalue, oddValue)]) [1,3 .. n]
  ) [2,4 .. n]

which you can hopefully easily see "iterates over" both lists and results in a list of all pairs of (even, odd) with values taken from both lists.
At a high level, we can say that the list monad results in iteration simply because concatMap, like map, executes the given function for each element of the list, so it implicitly iterates over the list.

A: The list instance of the Monad typeclass models nondeterminism: you can see each var <- someList as a for loop like in Python.
The do notation is desugared to [2,4 .. n] >>= (\evenValue -> [1, 3 .. n] >>= (\oddValue -> return (evenValue, oddValue))), so this is equivalent to something in Python like:
    result = []
    for evenValue in range(2, n, 2):
        for oddValue in range(1, n, 2):
            result.append((evenValue, oddValue))

or with list comprehension:
    result = [
        (evenValue, oddValue)
        for evenValue in range(2, n, 2)
        for oddValue in range(1, n, 2)
    ]

This works since for instance Monad [], the expression [2,4 .. n] >>= (\evenValue -> [1, 3 .. n] >>= (\oddValue -> return (evenValue, oddValue))) is thus equivalent to:
concatMap (\evenValue -> [1, 3 .. n] >>= (\oddValue -> return (evenValue, oddValue))) [2,4 .. n]

and thus:
concatMap (\evenValue -> concatMap (\oddValue -> [(evenValue, oddValue)]) [1, 3 .. n]) [2,4 .. n]

But do notation is not "hardwired" to IO: IO is just an instance of Monad that is implemented in such way that one IO action will run before the second one. For lists, it thus is implemented in an equivalent way as spanning Python for loops.


Q: Need help converting a expression in python to C# Maybe someone in either of the camps can tell me whats going on here:
Python:
temp = int('%d%d' % (temp2, temp3)) / 10.0;

I'm working on parsing temperature data, and found a piece of python that I can't understand. What is going on here? Is python adding together two numbers here and casting them to int, and then divide by  10?
C# might look like:
temp = ((int)(temp2+temp3))/10;

But I am not sure what that % does? Data is jibberish so I don't know what is correct translation for that line in python to C#

A: In C# it looks like:
var temp = int.Parse(temp2.ToString() + temp3.ToString())/10f;

or:
var temp = Convert.ToInt32(string.Format("{0}{1}", temp2, temp3))/10f;

A: this is similar: What's the difference between %s and %d in Python string formatting?
name = 'marcog'
number = 42
print '%s %d' % (name, number)

will print marcog 42. Note that name is a string (%s) and number is an integer (%d for decimal).
See
  http://docs.python.org/library/stdtypes.html#string-formatting-operations
  for details.

So it seems like the "%" is just telling python to put the values on the right into the placeholders on the left.
from the documentation linked in the answer I quoted:

Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language. If format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object.

Would probably want to set up a python script and try it out, placing your own values into the variables.


Q: How can I create only one button to perform multiple tasks? I have created one button named as battery-saver in the android, now i want that when i click on the battery saver button then the "WIFI" and "BLUETOOTH" should be turned off. So, can anybody help me for the code of this that when I click on the button then i can turn off the "WIFI" and "BLUETOOTH" both ?

A: *

*Add permission

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

*Try this
btnLogin.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(false);

        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter.disable();
    }
});


Q: Understanding std::move and unique_ptr I am new to c++11 and trying to understand to meaning of std::move and unique_ptr and wrote the following code, which I use std::move on a unique_ptr in two different ways:
void unique_ptr_plain_move() {
  unique_ptr<int> intptr(new int(10));
  unique_ptr<int> intptr2;

  printf("*intptr = %d\n", *intptr);
  intptr2 = std::move(intptr);
  printf("*intptr2 = %d\n", *intptr2);
  // as expected, crash here as we have already moved intptr's ownership.
  printf("*intptr = %d\n", *intptr);
}

/////////////////////////////////////////////

void function_call_move(unique_ptr<int>&& intptr) {
  printf("[func] *intptr = %d\n", *intptr);
}

void unique_ptr_function_call_move() {
  unique_ptr<int> intptr(new int(10));

  printf("*intptr = %d\n", *intptr);
  function_call_move(std::move(intptr));
  // this does not crash, intptr still has the ownership of its pointed instance ....
  printf("*intptr = %d\n", *intptr);
}

In unique_ptr_plain_move(), intptr2 takes the ownership of intptr after std::move and therefore we can no longer use intptr.  However, in unique_ptr_function_call_move(), when using std::move in a function call, intptr still have its ownership of its pointed instance.  Can I know what exactly happened when we pass a std::move(unique_ptr) to a function?  Thank you.

A: The key concept here is that std::move by itself won't do any moving.
You can think of it as marking the object as a object that can be moved from.
The signature for function_call_move is
void function_call_move( unique_ptr<int>&& ptr );

Which means it can only receive objects that could be moved from, formally known as rvalues, and bind that to a reference. The act of associating an rvalue to a rvalue reference don't invalidate the state of the original object either.
So, unless function_call_move actually moves ptr to another std::unique_ptrinside it, your call to function_call_move(std::move(intptr)); won't invalidate intptr and your usage will be perfectly fine.


Q: Springboot jersey with multiple source paths (servlets) I am starting to use Springboot in my application. My web.xml looks like this
    <servlet>
        <servlet-name>Internal Tools</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>in.playment.internal.api;in.playment.auditor.api</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>org.glassfish.jersey.filter.LoggingFilter;org.glassfish.jersey.media.multipart.MultiPartFeature;in.playment.gateway.RequestFilter;in.playment.gateway.ResponseFilter;in.playment.gateway.DebugExceptionMapper;in.playment.gateway.security.Binder</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Internal Tools</servlet-name>
        <url-pattern>/v0/internal/*</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>External Apis</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>in.playment.rutherford.api;in.playment.payment.api;in.playment.payment.resource</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>org.glassfish.jersey.filter.LoggingFilter;org.glassfish.jersey.media.multipart.MultiPartFeature;in.playment.gateway.RequestFilter;in.playment.gateway.ResponseFilter;in.playment.gateway.DebugExceptionMapper;in.playment.gateway.security.Binder;in.playment.payment.exception.PaymentExceptionMapper</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>External Apis</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

I want to use two different base paths for urls. I have different packages and different exception mappers. How can I achieve this in Springboot embedded tomcat. So far, I am able to achieve only one of these. If I try to do two registries, it throws me Exception saying org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.glassfish.jersey.server.ResourceConfig' available: expected single matching bean but found 2: jerseyConfig,getResourceConfig


Q: SVG Rect Ignores Height? Here is a working demo of a rectangle. I'd like to move the height property to css and well, it doesn't work and gives me a blank. It happens in firefox and chrome.
Is there a different name for it? I don't understand why I can't use a css file. The fill color works.
Working example.
css:
rect {
    fill:rgb(0, 0, 255);
    /*doesnt work height:100;*/
}

html:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <rect width="100" height="100" style="stroke-width:1;stroke:rgb(0,0,0)"/>
</svg>

A: The width of a <rect> element isn't a CSS property in SVG, it's only usable as an attribute. It's for example like the size of a <select> element in HTML. You can only set it as an attribute.

A: SVG doesn't have a straightforward support for CSS for setting shape dimensions.
However there's a workaround for rects, which can also be used to generate horizontal and vertical lines:

*

*Set width and height to 1, and use CSS transform: scale(width, height)

*Don't specify x,y location, and use transform: translate(x, y)

E.g.

.svg {
  width: 100px;
  height: 30px;
}
.rectangle {
  transform: scale(30, 10);
  fill: orange;
}
.horiz-line {
  transform: translate(15px,5px) scale(50, 1);
  fill: red;
}
.vert-line {
  transform: translate(10px, 5px) scale(1, 30);
  fill: blue;
}
<svg>
  <rect class="rectangle" width="1" height="1" />
  <rect class="horiz-line" width="1" height="1" />
  <rect class="vert-line" width="1" height="1" />
</svg>

A: In SVG the x, y, width and height of <rect> elements are attributes rather than CSS properties. Only CSS properties can be styled using CSS.

A: workaround for symmetric rectangles:

rect:hover {
  stroke-width: 20 !important;
}
<svg width="100" height="100">
  <rect
    stroke-width="0"
    fill="blue" stroke="blue"
    x="30" y="30" width="40" height="40"
  />
</svg>

(darkreader will use different colors for stroke and fill)


Q: Can I develop Windows 8 Apps without installing 2012 Express for Windows 8?
Microsoft provides two free tools, designed to work together, that help you develop, test, and deploy Windows Store apps: Microsoft Visual Studio Express 2012 for Windows 8 and Blend for Visual Studio. (These tools require Windows 8.)

I already have too many IDE's on my box. One of them is Visual Studio 2012 Pro. If I want to develop Windows 8 Apps, expecially the HTML5 variety, do I really need to install that huge SDK along with Visual Studio Express 2012 for Windows 8?? Or can I just install some templates and add some nuget packages?

A: you can install the Windows 8 SDK http://msdn.microsoft.com/en-us/windows/desktop/hh852363.aspx


Q: Construct json with multiple identical keys in Qt5 I want to generate a json that looks like this:
{
    "myRepeatedKey": "test_data_1",
    "myRepeatedKey": "test_data_2",
    "myRepeatedKey": "test_data_3",
    "myRepeatedKey": "test_data_4"
}

using Qt5. My naive approach looks like this:
QVariantMap map;
map_fill["myRepeatedKey"]="test_data_1";
map_fill["myRepeatedKey"]="test_data_2";
map_fill["myRepeatedKey"]="test_data_3";
map_fill["myRepeatedKey"]="test_data_4";
QJsonDocument doc=QJsonDocument::fromVariant(map);
qDebug()<<doc.toJson();

Since this replaces data for the entry, this outputs (not surprisingly) this:
}
    "myRepeatedKey": "test_data_4"
}

So how could I do this in Qt5?
PS: According to RFC4627 it is recommended but not required for names in name/value pairs in json data to be unique, so even though what I am asking for is not recommended practice, I would still know how to do it.
Thanks!

A: I think adding duplicate keys is a bad idea. You should use json array (QJsonArray) in this case.
QJsonArray array;
array.append("test_data_1");
array.append("test_data_2");
array.append("test_data_3");
array.append("test_data_4");

QJsonObject o;
o["myArray"] = array;

QJsonDocument doc(o);
qDebug() << doc.toJson();

Output will be
{
    "myArray": [
        "test_data_1",
        "test_data_2",
        "test_data_3",
        "test_data_4"
    ]
}


Q: .Net Xml Deserialization I have the following XElement
  <Issue Type="Duplicate" Distance="1">
    <Record>
      <ID>6832</ID>
      <Name_First>JAMES </Name_First>
      <Name_Last>SMITH</Name_Last>
      <Company>SMITH CO.</Company>
    </Record>
    <Record>
      <ID>6831</ID>
      <Name_First>JAMES</Name_First>
      <Name_Last>SMITH</Name_Last>
      <Company>SMITH CO.</Company>
    </Record>
  </Issue>

I'm trying to Deserialize it into this object
public class Issue
{
    [XmlAttribute]
    public string Type { get; set; }

    [XmlArrayItem(typeof(XElement), ElementName = "Record")]
    public List<XElement> Record { get; set; }
}

The type works no problem, but I can't get the two Record nodes into the Record list of the object.
Is it possible without overriding ISerializable and writing custom code?

A: Try this:
public class Issue
{
    [XmlAttribute]
    public string Type { get; set; }

    [XmlAnyElement("Record")]
    public List<XElement> Record { get; set; }
}

I think that tells the serializer that multiple Record elements will go in the list.

A: Implement Record class which has ID, Name_First, Name_Last and Company fields


Q: Get Model name in a partial view Is there any way to get the name of current model in a partial view?
I want to do something like:
@if(Model.Name=="Something"){
....
}
else{
...
}

A: you can use try something like
@model.GetType().Name


Q: Make Selectable True for only given date range in React Big Calendar I am using React Big Calendar. By Default selectable true make the whole calendar selectable but I want to make only selectable true of given time and change the background color of that time range in the calendar. I am not willing to create event. Just make selectable true of given times.
Thanks

A: I found a solution that may help you to disable some dates , in my case , I needed to disable unavailability events, so I used  selectable="ignoreEvents"
         `<BigCalendar
            selectable="ignoreEvents"
            localizer={localizer}
            events={events}
            views={allViews}
            step={60}
            showMultiDayTimes
            defaultDate={new Date()}
            defaultView={BigCalendar.Views.WEEK}
            style={{height: "90vh" }}
            resources={resourceMap}
            resourceIdAccessor="resourceId"
            resourceTitleAccessor="resourceTitle"
            onSelectSlot={this.handleSelect}
            eventPropGetter={(this.eventStyleGetter)}
          />`

use eventPropGetter to style you events


Q: How to hook api calls in another application I am trying to hook the ExtTextOut and DrawTextExt GDI method calls of another application.
I know that I need to Use GetProcAddress to find the address of those methods in gdi32.dll, and overwrite the address in the process I want to hook with the address of my function.  Then in my function I do what I need, then call the original function.
I want to make this hook functionality available to .net applications, and apparently this is do-able by creating an 'intermediate' unmanaged dll that does the hooking, and is capable of firing a event on the .net side, so that the new function can bet written in the managed environment.  I'm just not sure how to implement this.  Does anyone have any code samples or links to information?

A: I would recommend Microsoft's Detours (C++ x86 only) or EasyHook (C++ & C#, x86/x64).
http://easyhook.codeplex.com/
I've used it before, works pretty well. You have to pass a function or address and where you want it redirected to, and you can have all calls (for all processes or a specific one) sent into your function. The tutorials cover most of the basics, but I can edit code into this answer if you'd like.
A bit of trivia is that it also works the other way. Pass a pointer to your function and you can redirect calls into external code. Makes for some interesting integration with old apps or closed-source ones.

A: You can use Deviare API Hook, use DeviareCSharpConsole that is a tool that is in the package that let you hook any API and see parameter values in a treeview-like control.
The only trick that it needs in Windows7 is to be load as admin, I reported.

A: How I Built a Working Poker Bot has samples of injecting code and hooking gdi events.


Q: Jasper Report graph in iReport repeating I have a line graph in iReport which is incrementally repeating in every page, that is, if the graph has 30 x/y pairs (this is dynamic), the report will have 30 pages, of which the first will have just one value, the 2nd two values, and so on. Only the last one will contain the complete graph.
Questions "chart repeat many time" and "Problem with charting using JasperReport" and "How to print the grand total only in the last page of a very long report?" did not solve my problem. I understand that putting the chart in the Detail section makes the chart repeat, but putting it in the Summary, Footer, lastPageFooter, Title, etc. sections makes it display only one value. Same when I put it in the Detail section and use <printWhenExpression>.
My code:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="nodes-allarmipersistenti" language="groovy" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <field name="day" class="java.lang.Number"/>
    <field name="month" class="java.lang.String"/>
    <field name="year" class="java.lang.String"/>
    <field name="dsunita" class="java.lang.String"/>
    <field name="valueNumber" class="java.lang.Number"/>
    <field name="logo" class="java.lang.String"/>
    <field name="today" class="java.lang.String"/>
    <field name="option" class="java.lang.String"/>
    <title>
        <band height="89">
            <staticText>
                <reportElement mode="Opaque" x="0" y="67" width="424" height="22" backcolor="#CCFFFF"/>
                <textElement textAlignment="Right" verticalAlignment="Middle" markup="none">
                    <font size="10" isBold="true" pdfFontName="Helvetica-Bold" isPdfEmbedded="true"/>
                </textElement>
                <text><![CDATA[GRAFICO PARAMETRO]]></text>
            </staticText>
            <staticText>
                <reportElement x="600" y="0" width="100" height="38"/>
                <textElement verticalAlignment="Middle"/>
                <text><![CDATA[Stampato in data]]></text>
            </staticText>
            <textField>
                <reportElement x="700" y="0" width="102" height="38"/>
                <textElement textAlignment="Right" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{today}]]></textFieldExpression>
            </textField>
            <image>
                <reportElement x="0" y="0" width="100" height="67"/>
                <imageExpression><![CDATA[$F{logo}]]></imageExpression>
            </image>
            <staticText>
                <reportElement x="700" y="38" width="102" height="29"/>
                <textElement textAlignment="Right"/>
                <text><![CDATA[MaRe - Telecontrollo]]></text>
            </staticText>
            <textField>
                <reportElement mode="Opaque" x="424" y="67" width="378" height="22" backcolor="#CCFFFF"/>
                <textElement verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[' ' + $F{option}]]></textFieldExpression>
            </textField>
        </band>
    </title>
    <lastPageFooter>
        <band height="387" splitType="Stretch">
            <xyLineChart>
                <chart evaluationTime="Page">
                    <reportElement x="0" y="0" width="802" height="387"/>
                    <chartTitle/>
                    <chartSubtitle/>
                    <chartLegend/>
                </chart>
                <xyDataset>
                    <dataset incrementType="Report"/>
                    <xySeries>
                        <seriesExpression><![CDATA["Unità " + $F{dsunita}]]></seriesExpression>
                        <xValueExpression><![CDATA[$F{day}]]></xValueExpression>
                        <yValueExpression><![CDATA[$F{valueNumber}]]></yValueExpression>
                    </xySeries>
                </xyDataset>
                <linePlot>
                    <plot/>
                </linePlot>
            </xyLineChart>
        </band>
    </lastPageFooter>
</jasperReport>

Datasource here is a JRBeanCollectionDataSource.

A: Putting it in the Detail band is wrong (as you noticed). Putting it in the Title or Summary will work. Your choice of evaluationTime="Page" doesn't look right. Try changing this to evaluationTime="Report"