Q: How do I replace only PART of an image source on hover using jquery?
Personal
 Information

This is what i trying
$(".navbar-nav li a").hover(function(){
        $(this).children("img").attr('src').replace('hover','static');
});

A: Firstly your arguments to replace() are the wrong way around. Secondly, you need to actually set the value after making the replacement. Lastly you'll also need to provide another function argument to hover() that sets the original image back on mouseout. Try this:

$(".navbar-nav li a").hover(function() {
  $(this).children("img").prop('src', function(i, src) {
    return src.replace('static', 'hover');
  })
}, function() {
  $(this).children("img").prop('src', function(i, src) {
    return src.replace('hover', 'static');
  })
});

      Personal
 Information

A: You are replacing src code, but not assigning it back.
$(".navbar-nav li a").hover(function(){
    var newSrc = $(this).children("img").attr('src').replace('hover','static');
     $(this).children('img').attr('src', newSrc)
});

A: Why are you targeting , then select its child ? Why not apply that to the image directly?
$(".navbar-nav li a img").hover(function(){
    $(this).attr('src') = $(this).attr('src').replace('hover','static');
});


Q: How can I let a set retain all strings that contain my specified substring in java? I use a hashset for a dictionary. Now I would like to filter out words that do not start with my substring. So it should be something like this:
String word = 'ab';
List<String> list = Arrays.asList(word);
boolean result = lexiconSet.retainAll(list);

And instead of this resulting in the lexicon only containing the word 'ab', I would like to keep all words beginning with 'ab'. How can I do this?
I know I can convert the set to a string arraylist, and loop over all elements to see if the strings starts with 'ab', but since I think this can be time consuming and not efficient, I would like to hear better solutions. Thank you in advance!

A: With Java 8, life is easy:
list.removeIf(s -> !s.startsWith("ab"));

This will remove all elements that don't begin with "ab".
Note that you can use values() to retrieve the map's values and work directly on them, without the need to convert to ArrayList.


Q: Concatenate with NULL values ( Should not replace NULL ) After some time searching for an answer, I got a LOT of question saying to use coalesce,concat(), and etc, but what I need is:
Table:
create table nulos ( nome varchar(max))
alter table nulos add cidade varchar(max)

values:
insert into nulos values ( 'rafael','são paulo'),('juliana',null)

I need to concatenate the values inside this table, to a insert, like this:
 select 'insert into nulos (nome,cidade) values ('+nome+','+cidade+')'
from nulos

And the result of the select:
insert into nulos (nome,cidade) values (rafael,são paulo)
NULL

how can I use the NULL value inside this concatenation? every answer says something to replace the null with '' or '_', But what I need it this:
insert into nulos (nome,cidade) values (rafael,são paulo)

insert into nulos (nome,cidade) values (Juliana,NULL)

SET CONCAT_NULL_YIELDS_NULL on is not an option because it just deletes the NULL value, and I need to insert it.

A: Wrap your strings in single quotes so they will be input as strings.  The NULL does not need quotes.
SELECT 'INSERT INTO nulos (nome,cidade) VALUES (' +
    CASE WHEN nome is null then 'NULL' ELSE ''''+
        REPLACE(nome,'''','''''')+'''' END +
    ',' +
    CASE WHEN cidade is null then 'NULL' ELSE ''''+
        REPLACE(cidade,'''','''''')+'''' END +
    ')'
FROM nulos

This will give you:
INSERT INTO nulos (nome,cidade) VALUES ('rafael','são paulo')
INSERT INTO nulos (nome,cidade) VALUES ('Juliana',NULL)


Q: Put File Mask on tFileList Component dynamically I was wondering if you let me know how I can set file mask for tFilelist component in Talend that it recognize date automatically and it will download only data for desired date?
I have tried some approach and I faced with some errors like "the method add (string) in the type list <String> is not applicable for the arguments (Date)"

A: There are two ways of doing it.

*

*Create context variable and use this variable in file mask.

*Directly use TalendDate.getDate() or any other date function in file mask.

See both of them in component
1st approach,

*

*Create context variable named with dateFilter as string type.

*Assign value to context.dateFilter=TalendDate.getDate("yyyy-MM-dd");

*Suppose you have file name as "ABC_2015-06-19.txt" then

*In tFileList file mask use this variable as follows.
"ABC_"+context.dateFilter+".*"
2nd approach

*

*In tFileList file mask use date function as follows.
"ABC_"+TalendDate.getDate("yyyy-MM-dd")+".*"
these are the two best way, you can make changes in file mask per your file names.


Q: Material Design Lite responsive CSS not working on a Mobile/Tablets or in the Chrome DevTools emulator When experimenting with the responsive features of Google's Material Design Lite, this code hides messages as expected when resizing the browser window, but when I look at my page in Chrome DevTools device emulator or on an actual device, it only shows the "Desktop" version. How do I fix my HTML?

     <link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.1/material.indigo-pink.min.css">

          You are on a desktop

          You are on a phone

          You are on a tablet

A: To fix MDL not scaling for different devices, add this line inside your HTML's  :
<meta name="viewport" content="width=device-width, initial-scale=1.0">


Q: Flutter Gridview button functionality to new screen with Firebase I've made a Gridview using Firebase and Streambuilder and Gridview.builder. This grid displays album titles, the album cover art for each album, and the artists that make each album. I'd like for each grid tile to be able to be pressed and navigate to a separate page with its specific album details. The plan was on press, the app would be able to identify the entire document the grid tile was referring to, move to a new page, and display the document in full to unveil the album details. The thing is, I don't know how to do that. Since snapshot.data.documents[index]['Title'] worked when iterating though all the documents to create the gridview, I thought that typing snapshot.data.documents[index] would work, but it just displays Instance of 'DocumentSnapshot' in the debug console. I'm out of ideas on how to tackle this, so any suggestions are welcome
My code is shown below
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final Services services = Services();
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: bgcolour,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: Icon(Icons.menu),
        title: Text("Home"),
        actions: <Widget>[
          Padding(padding: EdgeInsets.all(10), child: Icon(Icons.more_vert))
        ],
      ),
      body: StreamBuilder(
          stream: Firestore.instance.collection('music').snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) return const Text("Loading...");
            return GridView.builder(
              itemCount: snapshot.data.documents.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2, childAspectRatio: 0.655172413),
              //cacheExtent: 1000.0,
              itemBuilder: (BuildContext context, int index) {
                var url = snapshot.data.documents[index]['Cover Art'];

                return GestureDetector(
                  child: Container(
                    width: 190.0,
                    child: Card(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(32)),
                      color: hexToColor(
                          snapshot.data.documents[index]['Palette'][0]),
                      elevation: 1,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          SizedBox(height: 12),
                          ClipRRect(
                              borderRadius: BorderRadius.circular(21.0),
                              child: Image.network(url,
                                  height: 180.0, width: 180)),
                          SizedBox(height: 10),
                          Text(
                              snapshot.data.documents[index]['Artist']
                                  .join(', '),
                              textAlign: TextAlign.center,
                              style: GoogleFonts.montserrat(
                                  textStyle: TextStyle(color: Colors.white),
                                  fontSize: 14,
                                  fontWeight: FontWeight.w300)),
                          SizedBox(height: 10),
                          Text(snapshot.data.documents[index]['Title'],
                              style: GoogleFonts.montserrat(
                                  textStyle: TextStyle(color: Colors.white),
                                  fontSize: 16,
                                  fontWeight: FontWeight.w600),
                              textAlign: TextAlign.center),
                        ],
                      ),
                    ),
                  ),
                  onTap: () {
                    print("Tapped ${snapshot.data.documents[index]}");
                  },
                );
              },
            );
          }
          ),
    );
  }
}

A: Is there an ID for your snapshot.data.documents[index]? If yes, add it to the end.
onTap: () {
     print("Tapped ${snapshot.data.documents[index]['the property you want']}");
},


Q: Unable to get text values present within strong tag using Selenium Java While trying to print values present with in strong tag using xpath I'm getting following exception:
org.openqa.selenium.NoSuchElementException: Unable to locate element: strong

This is my code :
WebElement eleText = driver.findElement(By.xpath("//strong"));
String testerName = eleText.getText();
System.out.println(testerName);

This is my webpage which I'm trying to get values within strong tag :

    heizil :
      " First Device Test"

    riya:
     " Second Device Test"

Expected output: heizil,riya
If this is not the proper way can any one suggest any other way of getting the values present in  tag

A: As per the given HTML text heizil is within  tag which is the immediate descendant of the  tag.

    heizil
    :

        ...
        ...

Solution
To print the text heizil you can use either of the following locator strategies:

*

*Using cssSelector and getAttribute("innerHTML"):
System.out.println(driver.findElement(By.cssSelector("a.activity > strong")).getAttribute("innerHTML"));

*Using xpath and getText():
System.out.println(driver.findElement(By.xpath("//a[@class='activity']/strong")).getText());

Ideally, to extract the text value, you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following locator strategies:

*

*Using cssSelector and getText():
System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a.activity > strong"))).getText());

*Using xpath and getAttribute("innerHTML"):
System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='a-link-normal' and @id='vvp-product-details-modal--product-title']"))).getAttribute("innerHTML"));


Q: File Level Tracking In Git (Files from multiple branches in same directory) Is there any script that lets one remember branch/commit seperatly for files in some directory so that one can simultaneously work on file1 on branch1 and file2 on branch2 in the same directory and have them commit appropriately.  If not I'll implement it myself.
My plan is to have hidden checkout directories for various branches/repos and populating the apparent checkout with links to these files so that commits simply committed their respective hidden branches but advice would be appreciated.  Thus one could do something like
mgit checkout branch1 filename/filegroup
mgit add filename   (automatically to it's correct branch/repo)
mgit commit  (automatically to it's correct branch/repo)

Before anyone tells me this is a bad idea or incorrect use of version control consider the application:
So often when writing academic documents in TeX you end up with loosely related files that you wish to keep in version control. The problem is that these files are related and can benefit from the history/merging info git provides but often different versions of the files need to be selected independently.  Most commonly you simply want to work on variant1 of some paper while also working of variant2 of another but you also have situations where TeX combines several files so it's important to be able to put your choice of variants in the same folder.
In short you have a bunch of distinct files with distinct names which often derive from each other (thesis becomes paper), benefit from being in a single repo but it is unwieldy to have a dozen different checkouts to work on whatever versions of each file currently need attention.

A: No, I don't think this is natively supported by git.
May be a local hook like a pre-commit one hook might try to check and checkout the right branch before allowing the commit to proceed.


Q: interchanging integral and limit Consider the limit
$$\lim_{n\to \infty }\int_0^1(1-t^n)f(t)\;dt$$
Where $f$ is a continuous function on $[0,1]$.
Is it safe to put the limit inside the integral and so that case the limit would be $\int_0^1 f(t)\;dt$? are there any conditions to verify here before putting the limit inside ?

A: You can use the Dominated convergence Theorem, your function is dominated by $f(t)$.

A: Since $f$ is continuous on $[0,1]$, there is a finite maximum $M=\max_{t\in[0,1]}|f(t)|$. Then $|(1-t^n)f(t)|\leq M$ for all $t\in[0,1]$ and all $n$ (i.e. the sequence of functions $(1-t^n)f(t)$ is dominated by the constant function $M$), so Lebesgue's Dominated Convergence Theorem gives you
$$\lim_{n\to\infty}\int_0^1(1-t^n)f(t)\,dt=\int_0^1\lim_{n\to\infty}(1-t^n)f(t)\,dt=\int_0^1f(t)\,dt.$$


Q: O JavaScript não esta relacionando no HTML estou treinando o consumo de uma API, porém meu JavaScript não está funcionando e nem está se comunicando com o HTML. Alguém sabe me dizer  o que estou fazendo de errado?
Javascript:
function carregar_dados() {
    var casos = { brasil: 0, data: 0, }
    var lista = []
    var request = new XMLHttpRequest()
    request.open('GET', 'https://api.covid19api.com/summary', true)
    request.onload = function () {
        var data = JSON.parse(this.response)

        if (request.status >= 200 && request.status < 400) {
            for (var k in data["Countries"]) {
                if (data["Countries"][k].CountryCode == "BR") {
                    casos.brasil = data["Countries"][k].TotalConfirmed
                }

                document.getElementById('dados-brasil').textContent = casos.brasil.toLocaleString('pt-BR')
                carregar_lista(lista)
            }
        }
        request.send()
    }
}

function carregar_lista(lista) {
    lista.sort((a, b) => parseInt(b.TotalConfirmed) - parseInt(a.TotalConfirmed))
    var ul = document.getElementById('dados-ranking')
    lista.forEach(geraLista);

    function geraLista(element, index) {

        var li = document.createElement('li')
        li.setAttribute('class', 'list-group-item')
        ul.appendChild(li)
        li.innerHTML = li.innerHTML + parseInt(index + 1) + "º - " + element.Country + " : " + element.TotalConfirmed.toLocaleString('pt-BR')

    }
}

HTML
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="..\..\asset\styles.css">

    <title>Covid-19 Brasil</title>

        Home
        Casos no Brasil
        Ranking Mundial

Brasil

 xxxxxxxxxxxxx

A: O problema está localizado na parte em que é enviado a requisição.
Você precisa colocar o request.send() fora da function onload, pois o onload só é executado após a chamada ser concluída.
Seu código ficará assim:
function carregar_dados() {
    var casos = { brasil: 0, data: 0, }
    var lista = []
    var request = new XMLHttpRequest()
    request.open('GET', 'https://api.covid19api.com/summary', true)
    request.onload = function () {
        var data = JSON.parse(this.response)

        if (request.status >= 200 && request.status < 400) {
            for (var k in data["Countries"]) {
                if (data["Countries"][k].CountryCode == "BR") {
                    casos.brasil = data["Countries"][k].TotalConfirmed
                }

                document.getElementById('dados-brasil').textContent = casos.brasil.toLocaleString('pt-BR')
                carregar_lista(lista)
            }
        }
    }

    request.send(); <-- aqui
}

Perceba que o request.send() está após a function onload.


Q: Are atomic operations on non-atomic types in C atomic? The C17 standard specifies a list of atomic operations. For example, an atomic read-write-modify operation on an atomic object of type A is defined in the standard as:
C atomic_fetch_add(volatile A *object, M operand);

But we can call atomic_fetch_add on non-atomic types:
static int x;
static int foo(void *arg) {
  atomic_fetch_add(&x, 3);
}

My question: is the above atomic_fetch_add operation on the non-atomic object x guaranteed to be atomic?

A:
on an atomic object of type A is defined in the standard
But we can call

GCC will accept it. But on clang you'll get an error.

is the above atomic_fetch_add operation on the non-atomic object x guaranteed to be atomic?

No. In the standard the behavior of the code you presented is not defined, there is no guarantee of any kind. From https://port70.net/~nsz/c/c11/n1570.html#7.17 :

5 In the following synopses:

*

*An A refers to one of the atomic types. [...]

And then all the functions are defined in terms of A, like in https://port70.net/~nsz/c/c11/n1570.html#7.17.7.5p2 :
C atomic_fetch_key(volatile A *object, M operand);
Atomic type is a type with _Atomic.


Q: convert ElasticSearch SearchResponse object to JsonObject I want to convert the elasticsearch search result to Json Object. I havent found any proper way to convert directly.
SearchResponse response = client.prepareSearch(index).setExplain(true).execute().actionGet();

response->JSON Object.

Is there any way to convert an ElasticSearch response to a Json Object?

A: In Java, you can directly convert the SearchResponse to JSONObject.
Below is the handy code.
SearchResponse SR = builder.setQuery(QB).addAggregation(AB).get();

JSONObject SRJSON = new JSONObject(SR.toString());

A: You need to use the SearchResponse.toXContent() method like this:
SearchResponse response = client.prepareSearch(index).setExplain(true).execute().actionGet();

XContentBuilder builder = XContentFactory.jsonBuilder();
response.toXContent(builder, ToXContent.EMPTY_PARAMS);
JSONObject json = new JSONObject(builder.string());


Q: Transparency between UITableViewCells I want to have transparency between UITableViewCells. Space between the cells.
I user custom created cells and for setting a background i use this code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CustomCell = @"CustomBookingCell";

    currentBooking = [arrayBookings objectAtIndex:indexPath.row];

    CustomBookingCell *cell = (CustomBookingCell *)[tableView dequeueReusableCellWithIdentifier:CustomCell];

    if (cell == nil) {

        UIViewController *c = [[UIViewController alloc] initWithNibName:@"CustomBookingCell" bundle:nil];
        cell = (CustomBookingCell *)c.view;
        [ c release ];
    }

    bookingImage = [[UIImageView alloc] initWithImage:
                     [UIImage imageNamed:currentBooking.imageSource]];

    [cell.imageForBooking addSubview:bookingImage];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    cell.contentView.backgroundColor = [UIColor clearColor];

    UIView* backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    UIImage* bgImage = [UIImage imageNamed:@"Background_300_82.png"];
    UIColor *bgColor = [[UIColor alloc] initWithPatternImage: bgImage];

    backgroundView.backgroundColor = bgColor;
    cell.backgroundView = backgroundView;
    cell.label.text = currentBooking.title;

    [bookingImage release];
    [bgColor release];
    [backgroundView release];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

The height of the cell is 10 pixels higher that the tableCellBg.png.
My background view has also a image as background (this background is supposed to be shown between the cells of course).
So I tried to add 10 pixels with transparency to my tableCellBg.png in the bottom to fix this. But the space between the cells is black. I can't see the view background between my cells.
What shall I do? Do I have to create a UIView in cellForRowAtIndexPath with the height of the tableCellBg.png and then add the Custom UITableViewCell as subview to the created UIView with a less higher height?
Or is there a much more simplyfied way to accomplish this?

A: Your table view needs a clear background colour. For example
myTableView.backgroundColor = [UIColor clearColor];

A: I solved it by using another method to add the background image to the UITableViewCell:
    UIImage *image = [UIImage imageNamed:@"ny_bg_event.png"];
UIImageView  *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, 300, 84);
cell.backgroundView = imageView;
cell.backgroundColor = [UIColor clearColor];
[imageView release];

[cell setFrame:CGRectMake(0, 0, 300, 84)];

cell.contentView.backgroundColor = [UIColor clearColor];

Instead of creating a UIView I just used a UIImageView instead.


Q: webkit css resize doesn't work with canvas as child? Suppose the following html and css code snippet:

#outer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  resize: both;
  border: 1px solid black;
}
#inner {
  width: 100%;
  height: 100%;
}

  <canvas id="inner"></canvas>

I would expect the div to be resizeable, and in firefox, it is. However in webkit-based browsers such as chrome and opera, it isn't. If I replace the inner canvas with a div however, it works there too. So my question is: why does the canvas element in this case prevent the outer div from beeing resizeable? And how can I work around this?

A: it seems that the canvas is taking the mouse event preventing the resize. If you consider pointer-events:none on canvas it will work:

#outer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  resize: both;
  border: 1px solid black;
}
#inner {
  width: 100%;
  height: 100%;
  pointer-events:none
}

  <canvas id="inner"></canvas>

To better illustrate, decrease the size of the canvas a little to avoid the overlap with the resize widget and it will also work:

#outer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  resize: both;
  border: 1px solid black;
}
#inner {
  width: 100%;
  height: calc(100% - 10px);
  background:red;
}

  <canvas id="inner"></canvas>

You can also play with z-index:

#outer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  resize: both;
  border: 1px solid black;
  position:relative;
  z-index:0; /* mandatory to create a stacking context and keep the canvas inside */
}
#inner {
  width: 100%;
  height: 100%;
  position:relative;
  z-index:-1;
  background:red;
}

  <canvas id="inner"></canvas>


Q: Google play services leak in Main While trying to implement ads into my app I am getting this error upon showing the ad.
The only thing I've added to my app in regards to Google play services is importing into gradle and adding to my manifest. I could not find any information on initialization or any other info where I have to add any code to my main.
Here is the log
06-26 21:53:31.062 E/ActivityThread(15754): android.app.ServiceConnectionLeaked: Activity com.intellidev.bitrich.MainActivity has leaked ServiceConnection com.google.android.gms.common.zza@5db576d that was originally bound here

update
Seems I need to initialize play services builder then connect. However the only reason it is implemented is to work with supersonic ads. So here less my problem on hpw to implement it.

A: Your supersonic ad sdk is causing the bug. The ad view connects to play services and does not disconnect properly.


Q: Content negotiation: how to remove JSON as a supported format? I'm implementing a web service in ASP.NET Core 2.1 based on a specification that exclusively supports XML.  Therefore, the content negotiation process must return a XML document or respond with an error.  Unfortunately ASP.NET Core 2.1 supports JSON by default, and by default the content negotiation process always succeeds if a request is made with Accept: application/json.
Does anyone know if it's possible to configure an ASP.NET Core project so that the content negotiation process throws an error if any media type other than XML is set?

A: Sorry if I am late to the party. This works for me:
        services.AddMvc(options =>
        {
            options.OutputFormatters.RemoveType(typeof(JsonOutputFormatter));
            options.InputFormatters.RemoveType(typeof(JsonInputFormatter));
            options.ReturnHttpNotAcceptable = true;
        })
        .AddXmlSerializerFormatters()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

A: Use MVC input and output formatters:
services.AddMvc(configure =>
{
    // remove JSON formatter
    var outputFormatters = configure.OutputFormatters;
    var jsonOutputFormatter = outputFormatters.First(f => f is JsonOutputFormatter);
    outputFormatters.Remove(jsonOutputFormatter);
    var inputFormatters = configure.InputFormatters;
    var jsonInputFormatter = inputFormatters.First(f => f is JsonInputFormatter);
    inputFormatters.Remove(jsonInputFormatter);
}).AddXmlSerializerFormatters()


Q: Ограничение ввода числа в input с помощью NumberFormat isAllowed есть код, который в принципе работает так что если в поле вписать число больше чем maxValue, то оно просто не пишется, но для пользователя это неудобно. Как сделать так, чтобы число автоматически заменялось на максимальное?
вот код:
isAllowed={values => {
    const { formattedValue, floatValue } = values;
    if (attributes.maxValue)
      return formattedValue === '' || floatValue <= attributes.maxValue;
    return values;
       }}


Q: WSO2 API Manager - unable to access resource properties I am not able to access resource property test1, mentioned in property section in the screenshot.
I am trying to access it by using the expression. get-property('test1'). I am expecting this result in console as test1-value. But the is showing as null.
Updated
I have tried following options but nothing is working for this test1 property.
<property expression="get-property('registry', 'gov:/data/xml/collectionx@test1')" name="test_property2"/>
<property expression="get-property('registry', 'gov:/_system/governance/apimgt/customsequences/in/Seq1.xml@test1')" name="test_property4"/>
<property expression="get-property('gov:/_system/governance/apimgt/customsequences/in/Seq1.xml@test1')" name="test_property6"/>

A: Try this.
<property name="regProperty" expression="get-property('registry', 'gov:/data/xml/collectionx@abc')"/>

Ref: http://movingaheadblog.blogspot.com/2015/09/wso2-esb-how-to-read-registry-property.html

A: To get the value of test1, use following property.
<property expression="get-property('registry', 'gov:/apimgt/customsequences/in/Seq1.xml@test1')" name="test_property5"/>

From above example the location of resource is showing /_system/governance/apimgt/customsequences/in/Seq1.xml. So to make its path, we will use subpath and leave /_system/governance from the beginning. The path will be gov:/apimgt/customsequences/in/Seq1.xml. Now to access test1 property, simply append @test1 to the path.


Q: Generally major network subnet mask is given for subnetting, how would you calculate it if it was not given? Generally you're given address with subnet mask to subnet. For example:
192.168.0.0/16

But say you're not given the address. You've to assume the address.
The hosts are given:
There are 5 departments:

*

*HR = 60

*Marketing = 60

*Coding = 60

*Testing = 60

*Control department = 5

So total hosts are 60*4+5=245
i.e you require 8 bits of host address(which is incorrect but keep on at it). You got 256 addresses.
But You should sacrifice initial and ending ip addresses. So total ip required becomes 245+5*2=255
I know that this is not correct because you can't allocate 62 ip addresses in subnetting, you can only do 64.
So is there any formula or sth so that I can find out the subnet mask from the number of hosts given directly?
I am pretty aware that I could choose major network subnet mask to be /1 and my job would be done. But that would make me look insane.

A:
How to find major network subnet mask?

There are 5 departments:

*

*HR = 60

*Marketing = 60

*Coding = 60

*Testing = 60

*Control department = 5

Firstly make 5 equations-:
4*(2^x-2)=60*4-
ie 2^x -2 =60 --eqn 1)
2^y - 2=5 ---eqn 2)
Find the values of x and y.
x=log_2 (60+2)
y=log_2 (5+2)
Subnet mask required=z=32-x-y=23
Hence /23 is the major network subnet mask.

Another easier approach would be to think in terms of binary.
For 60 hosts can sit only in 64 ip address space. And 5 hosts in 8 ip address. So 64*4+8=264
log_2(264)=9
i.e 9 bits required for representing 264 addresses.
Thus subnet mask=32-9=23.

empirical answer for someone who likes to use math rather than calculation-:
Summation of (2^log_2(number of hosts per subnet+2)).
Summation ranges from first department to nth department.
but mind you to not use calculator as it will create wrong results.
first calculate log_2(no. of hosts per subnet+2)
then calculate its 2th power.
eg-: for 60, log_2(62)=6
then 2^6 =64
Similarly for another 4 subnets it becomes 64*4=256
Then for final subnet
log_2(7)=3
2^3=8
Thus 256+8=264 ip addresses are required.
log_2(264)=9
So 9 bits is required for these amount of hosts. i.e 32-9=23 as subnet mask.


Q: Send SMS from SQL Server Integration Services I am new to using SSIS and I am looking for a way to send messages using SMS. Is this possible to do? And if yes, is there a way to use a Web API in SSIS to send SMS messages?

A: After i did more search i found this Question
and his first answer was what i want.
the second part of my  Question was about api to use i found this 2 api

*

*Nexmo

*Infobip but you will have to contact them first

both of them will give you atest account to use it at first , but i used the first one from SQL SSIS.


Q: keyDown function not working with shift key I am trying to hold down the 'shift' key and press the 'down' key using the pyautogui module. But the pyautogui.keyDown() does not function with shift key.
The py.keyDown('shift') does not seem to work. Only the py.press('down') is working without holding down the shift key.
pyautogui.keyDown('shift')
pyautogui.press('down')
pyautogui.press('down')
pyautogui.keyUp('shift')

The thing i would like to do is- hold down the shift key and use the down arrow keys on the key board to move down selecting all items below with the down arrow.

A: #You can try this
#So, you have to make left and right shifts down at the same time to activate this feature which is wired.
pyautogui.keyDown('shiftleft')
pyautogui.keyDown('shiftright')
pyautogui.hotkey('right','right','ctrl','up')
pyautogui.keyUp('shiftleft')
pyautogui.keyUp('shiftright')

#credits:Tian Chu
#https://stackoverflow.com/users/13967128/tian-chu

A: Previous answer is good. I was able to successfully highlight a whole Excel column using:
pyautogui.hotkey('ctrl','shiftright','shiftleft','down')

I tried using both shiftright and shiftleft on their own and it wouldn't work unless they were both used together.

A: Thanks, I lost almost 1 hour to find this answer cause on the documentation this is not specified, for me worked example:
py.keyDown('shiftleft')
py.keyDown('shiftright')
py.press('down', presses=253)
py.keyUp('shiftleft')
py.keyUp('shiftright')
Again, Thanks.


Q: How do I distinguish the users who do not exist now but exit previously? Now I have a user set involving one tweet. But some users do not exit now. I wonder how to distinguish those users from current users.

A: I believe the only thing you can do in this case is to use the users/lookup or users/show endpoints to check whether those user IDs return a Not Found error (or similar) in order to filter them out from your result set.
Note that the Twitter Developer Policy and Agreement explicitly states that if content has been removed from Twitter (if e.g. a user is deleted or suspended) you cannot display that it in app, or store that data, and must take steps to remove it from your system as soon as possible.


Q: AWS Amplify Graphql query on @connection I am using AWS Amplify (with Cli and Angular 7 for front end) for Graphql/AppSync and wondering how to get all connected items when it exceeds 10 items?
Let's say I have created a schema.graphql like this:
type User @model {
  id: ID!
  firstname: String
  lastname: String
  project: Project @connection(name: "ProjectUsers")
}

type Project @model {
  id: ID!
  title: String
  task: String
  members: [User] @connection(name: "ProjectUsers")
}

When running amplify push it generates queries and mutations. When running the GetProject query with the id of a project (from the generated API.service.ts file) it returns the Project item with the connected Users. But if the project have more than 10 Users, it only gives me the 10 first users and a next token:
{
  id: "67b1fc0a-fd1f-4e8b-9bd7-b82b2aea5d3b",
  title: "Test",
  task: "test",
  members: {
    items: {
      0: {__typename: "User", id: "f245809a...}
      1: ...
      (2-8: ...)
      9: ...
      nextToken: "qwerj23r2kj....3223oop32kjo",
       __typename: "ModelUserConnection";
    }
  }
  __typename: "Project"
}

I can see multiple solutions for this, but not how to do them:

*

*Is it possible to change schema.grapql to change the codegen so that it can generate the ability to change the limit, ex. 100 instead of the standard 10?

*Use the nextToken to paginate the results, from the generated API.service.ts file?

*Change the schema.graphql file so that the generated ModelUserFilterInput has the userProjectId field (to use in the generated ListUsers query)?
Or are there any other solutions to get all the Users of a Project with the queries in the automatically generated file (API.service.ts)?
As of now the only solution I can see is to first run the ListUsers query (without any filters), and then loop through all of them to check if it has the correct project id. But if the users database is large this can grow to be a lot of data and be really slow, and the benefits to use @connection isn't really there.
Sorry for long post and I hope I have explained the problem enough.

A: A) Change your query
query {
  getProjet(id: "123") {
    id
    members(limit: 50) {
      items {
        firstname
      }
    }
 }

B) Attach a Resolver
In the AWS AppSync console, at the right end side of the Schema section. Filter by UserConnection or similar find UserConnection.items and click Attach.
1) DataSource: UserTable0
2) Request mapping template: ListItems
{
    "version" : "2017-02-28",
    "operation" : "Scan",
    "limit": $util.defaultIfNull(${ctx.args.limit}, 50),
    "nextToken": $util.toJson($util.defaultIfNullOrBlank($ctx.args.nextToken, null))
}

Use the limit coming as an argument ctx.args.limit or if its null use 50.
3) Response mapping template
$util.toJson($ctx.result.items)

By doing this you can change how the underlying table is being scanned/fetched.
C) Paginate
Another solution would be to paginate at the application level and leave the 10 items limit.
Note: I may be missing other solutions.
Update: to use this solution together with Amplify Console.
Now, you can update your resolvers locally and use the Amplify CLI to push the updates into your account. Here’s how it works.
After creating your AWS AppSync API, you will now have a new empty folder called resolvers created in your Amplify project in the API folder. To create a custom resolver, create a file (i.e.
Query.getTodo.req.vtl) in the resolvers directory of your API project. The next time you run amplify push or amplify api gql-compile, your resolver template will be used instead of the auto-generated template. You may similarly create a Query.getTodo.res.vtl file to change the behavior of the resolver’s response mapping template.
<amplify-app>
    |_ amplify
      |_ .config
      |_ #current-cloud-backend
      |_ backend
        |_ api
          |_ resolvers
             Query.getProject.req.vtl
             Query.getProject.res.vtl
      team-provider-info.json

More details, 11 Feb 2019


Q: Select only specific properties from an array of objects Let's  say I create object like this:
updates.push({
      id: this.ids[i],
      point: point,
      value: value
    });

Later on I want to use JSON.stringify on updates object, however I need only
point and value  like:
updates[{point: 1, value: 12}, {point: 2, value: 24}]

What's the best ES6 solution for that?
I looked at some examples with delete, but that's not what I actually need, as I do not want to delete ids.

A: Try the following :
JSON.stringify(updates.map(({point,value})=>({point,value})));

let updates = [{id : 1, point : 1, value: 2},{id : 1, point : 1, value: 2}];
console.log(JSON.stringify(updates.map(({point,value})=>({point,value}))));

A: If updates is an array. Then you might want something like this:
const newArrayWithoutId = updates.map(({ point, value }) => {
  return {
    point,
    value,
  }
}

A: Just ({id, ...rest}) => ({...rest}) is too short for an answer, so how about this?

const withoutId = ({id, ...rest}) => ({...rest})

const vals = [
  {id: 'a', point: 1, value: 'foo'},
  {id: 'b', point: 2, value: 'bar'},
  {id: 'c', point: 3, value: 'baz', meaning: 42}
]

const reduced = vals.map(withoutId)

console.log(reduced)


Q: Docker for Windows: "Operation not permitted" trying to run an executable inside a container (bind-mount only) I'm pretty sure that the last update of Docker for Windows has broken something.
Here is the thing. I have a custom image named toolbox, built from alpine, with a bounch of script inside it (bind-mount the local folder ./mnt/):
version: '3'

services:
    # ...

    toolbox:
        build:
            context: ./.docker/toolbox
        restart: always
        volumes:
            - ./mnt/etc/periodic/daily:/etc/periodic/daily

Files have the right permissions:
/ # ls -la /etc/periodic/daily/
total 4
drwxrwxrwx    1 root     root          4096 Mar 16 17:49 .
drwxr-xr-x    7 root     root          4096 Jan 16 22:52 ..
-rwxr-xr-x    1 root     root           332 Mar  1 23:57 backup-databases
-rwxr-xr-x    1 root     root            61 Mar  1 23:51 cleanup-databases-backups

When I try to execute backup-databases I get the following error:

/ # /etc/periodic/daily/backup-databases /bin/sh:
  /etc/periodic/daily/backup-databases: Operation not permitted

The strange thing is, if I create a script (from inside the container) it works:
echo "echo Hello" > /etc/periodic/daily/test
chmod +x /etc/periodic/daily/test
/etc/periodic/daily/test


Q: Scraping html data from a web site with
* tags I am trying to to get data from this lottery website:
https://www.lotterycorner.com/tx/lotto-texas/2019
The data I would like scrape is the dates and the winning numbers for 2017 to 2019. Then I would like to convert the data into a list and save to a csv file or excel file.
I do apologize if my question isn't understandable i am new to python. Here is a code I tried, but I don't know what to do after this
page = requests.get('https://www.lotterycorner.com/tx/lotto-texas/2017')
soup = BeautifulSoup(page.content,'html.parser')
week = soup.find(class_='win-number-table row no-brd-reduis')
dates = (week.find_all(class_='win-nbr-date col-sm-3 col-xs-4'))
wn = (week.find_all(class_='nbr-grp'))

I would like my result to be something like this:

A: Code below create csv files by year with data with all headers and values, in example below will be 3 files: data_2017.csv, data_2018.csv and data_2019.csv.
You can add another year to years = ['2017', '2018', '2019'] if needed.
Winning Numbers formatted to be as 1-2-3-4-5.
from bs4 import BeautifulSoup
import requests
import pandas as pd

base_url = 'https://www.lotterycorner.com/tx/lotto-texas/'
years = ['2017', '2018', '2019']

with requests.session() as s:
    for year in years:
        data = []

        page = requests.get(f'https://www.lotterycorner.com/tx/lotto-texas/{year}')
        soup = BeautifulSoup(page.content, 'html.parser')
        rows = soup.select(".win-number-table tr")

        headers = [td.text.strip() for td in rows[0].find_all("td")]
        # remove header line
        del rows[0]
        for row in rows:
            td = [td.text.strip() for td in row.select("td")]
            # replace whitespaces in Winning Numbers with -
            td[headers.index("Winning Numbers")] = '-'.join(td[headers.index("Winning Numbers")].split())
            data.append(td)

        df = pd.DataFrame(data, columns=headers)
        df.to_csv(f'data_{year}')

To save only Winning Numbers, replace df.to_csv(f'data_{year}') with:
df.to_csv(f'data_{year}', columns=["Winning Numbers"], index=False, header=False)

Example output for 2017, only Winning Numbers, no header:

9-14-16-27-45-51 2-4-15-38-48-53 8-22-23-29-34-36
  6-10-11-22-30-45 5-10-16-22-26-46 12-14-19-34-39-47
  4-5-10-21-34-40 1-25-35-42-48-51

A: This should export the data you need in a csv file:
from bs4 import BeautifulSoup
from csv import writer
import requests

page = requests.get('https://www.lotterycorner.com/tx/lotto-texas/2019')

soup = BeautifulSoup(page.content,'html.parser')

header = {
    'date': 'win-nbr-date col-sm-3 col-xs-4',
    'winning numbers': 'nbr-grp',
    'jackpot': 'win-nbr-jackpot col-sm-3 col-xs-3',
}

table = []

for header_key, header_value in header.items():
    items = soup.find_all(class_=f"{header_value}")
    column = [','.join(item.get_text().split()) if header_key=='winning numbers'
                       else ''.join(item.get_text().split()) if header_key == 'jackpot'
    else item.get_text() for item in items]
    table.append(column)

rows = list(zip(*table))

with open("winning numbers.csv", "w") as f:
    csv_writer = writer(f)
    csv_writer.writerow(header)
    for row in rows:
        csv_writer.writerow(row)

header is a dictionary mapping what will be your csv headers to their html class values
In the for loop we're building up the data per column. Some special handling was required for "winning numbers" and "jackpot", where I'm replacing any whitespace/hidden characters with comma/empty string.
Each column will be added to a list called table.  We write everything in a csv file, but as csv writes one row at a time, we need to prepare our rows using the zip function (rows = list(zip(*table)))

A: Don't use BeautifulSoup if there are table tags. It's much easier to let Pandas do the work for you (it uses BeautifulSoup to parse tables under the hood).
import pandas as pd

years = [2017, 2018, 2019]

df = pd.DataFrame()
for year in years:
    url = 'https://www.lotterycorner.com/tx/lotto-texas/%s' %year
    table = pd.read_html(url)[0][1:]
    win_nums = table.loc[:,1].str.split(" ",expand=True).reset_index(drop=True)
    dates = pd.DataFrame(list(table.loc[:,0]), columns=['date'])

    table = dates.merge(win_nums, left_index=True, right_index=True)

    df = df.append(table, sort=True).reset_index(drop=True)

df['date']= pd.to_datetime(df['date'])
df = df.sort_values('date').reset_index(drop=True)

df.to_csv('file.csv', index=False, header=False)

Output:
print (df)
          date   0   1   2   3   4   5
0   2017-01-04   5   7  36  39  40  44
1   2017-01-07   2   5  14  18  26  27
2   2017-01-11   4  13  16  19  43  51
3   2017-01-14   7   8  10  18  47  48
4   2017-01-18   6  11  17  37  40  49
5   2017-01-21   2  13  17  39  41  46
6   2017-01-25   1  14  19  32  37  46
7   2017-01-28   5   7  30  48  51  52
8   2017-02-01  12  19  26  29  37  54
9   2017-02-04   8  13  19  25  26  29
10  2017-02-08  10  15  47  49  51  52
11  2017-02-11  24  25  26  29  41  53
12  2017-02-15   1   4   5  43  53  54
13  2017-02-18   5  11  14  21  38  44
14  2017-02-22   4   8  21  27  52  53
15  2017-02-25  16  37  42  46  49  54
16  2017-03-01   3  24  33  34  45  51
17  2017-03-04   2   4   5  17  48  50
18  2017-03-08  15  19  24  33  34  47
19  2017-03-11   5   6  24  28  29  37
20  2017-03-15   4  11  19  27  32  46
21  2017-03-18  12  15  16  23  38  43
22  2017-03-22   3   5  15  27  36  52
23  2017-03-25  21  25  27  30  36  48
24  2017-03-29   7   9  11  18  23  43
25  2017-04-01   3  21  28  33  38  52
26  2017-04-05   8  20  21  26  51  52
27  2017-04-08  10  11  12  47  48  52
28  2017-04-12   5  26  30  31  46  54
29  2017-04-15   2  11  36  40  42  53
..         ...  ..  ..  ..  ..  ..  ..
265 2019-07-20   3  35  38  45  50  51
266 2019-07-24   2   9  16  22  46  49
267 2019-07-27   1   2   6   8  20  53
268 2019-07-31  20  24  34  36  41  44
269 2019-08-03   6  17  18  20  26  34
270 2019-08-07   1   3  16  22  31  35
271 2019-08-10  18  19  27  36  48  52
272 2019-08-14  22  23  29  36  39  49
273 2019-08-17  14  18  21  23  40  44
274 2019-08-21  18  28  29  36  48  52
275 2019-08-24  11  31  42  48  50  52
276 2019-08-28   9  21  40  42  49  53
277 2019-08-31   5   7  30  41  44  54
278 2019-09-04   4  26  36  37  45  50
279 2019-09-07  22  23  31  33  40  42
280 2019-09-11   8  11  12  30  31  49
281 2019-09-14   1   3  24  28  31  41
282 2019-09-18   3  24  26  29  45  50
283 2019-09-21   2  20  31  43  45  54
284 2019-09-25   5   9  26  38  41  44
285 2019-09-28  16  18  39  45  49  54
286 2019-10-02   9  26  39  42  47  49
287 2019-10-05   6  10  18  24  32  37
288 2019-10-09  14  18  19  27  33  41
289 2019-10-12   3  11  15  29  44  49
290 2019-10-16  12  15  25  39  46  49
291 2019-10-19  19  29  41  46  50  51
292 2019-10-23   4   5  11  35  44  50
293 2019-10-26   1   2  26  41  42  54
294 2019-10-30  10  11  28  31  40  53

[295 rows x 7 columns]

A: Here is a concise way with bs4 4.7.1+ that uses :not to exclude header and zip to combine columns for output. Results are as on page. Session is used for efficiency of tcp connection re-use.
import requests, re, csv
from bs4 import BeautifulSoup as bs

dates = []; winning_numbers = []

with requests.Session() as s:
    for year in range(2017, 2020):
        r = s.get(f'https://www.lotterycorner.com/tx/lotto-texas/{year}')
        soup = bs(r.content)
        dates.extend([i.text for i in soup.select('.win-nbr-date:not(.blue-bg)')])
        winning_numbers.extend([re.sub('\s+','-',i.text.strip()) for i in soup.select('.nbr-list')])

with open("lottery.csv", "w", encoding="utf-8-sig", newline='') as csv_file:
    w = csv.writer(csv_file, delimiter = ",", quoting=csv.QUOTE_MINIMAL)
    w.writerow(['date','numbers'])
    for row in zip(dates, winning_numbers):
        w.writerow(row)

A: This one works:
import requests
from bs4 import BeautifulSoup
import io
import re

def main():
    page = requests.get('https://www.lotterycorner.com/tx/lotto-texas/2018')
    soup = BeautifulSoup(page.content,'html.parser')
    week = soup.find(class_='win-number-table row no-brd-reduis')
    wn = (week.find_all(class_='nbr-grp'))
    file = open ("vit.txt","w+")
    for winning_number in wn:
        line = remove_html_tags(str(winning_number.contents).strip('[]'))
        line = line.replace(" ", "")
        file.write(line + "\n")
    file.close()

def remove_html_tags(text):
    import re
    clean = re.compile('<.*?>')
    return re.sub(clean, '', text)

This part of the code loops through the wn variable and writes every line to the "vit.txt" file:
    for winning_number in wn:
        line = remove_html_tags(str(winning_number.contents).strip('[]'))
        line = line.replace(" ", "")
        file.write(line + "\n")
    file.close()
The "stripping" of the <li> tags could be probably done better, e.g. there should be an elegant way to save the winning_number to a list and print the list with 1 line.


Q: Datepicker submit format In the new version of materialize the new 'datepicker' seems to have lost the option for 'formatSubmit'
format: 'dd/mm/yyyy'
formatSubmit: 'yyyy-mm-dd'
You use to be able to display the date in the page in one format and submit it in another.
Anyone have a way round this?


Q: Metric density theorem in most general setting? It's a consequence of Lebesgue's theorem that every measurable $E\subset\mathbb{R}^n$ has a metric density that's $1$ a.e. on $E$ and $0$ a.e. on $\mathbb{R}^n\setminus E$. What are the most general conditions on the measure space for this property to hold?

A: It is true for doubling metric-measure spaces.
Check Theorem 1.8 in "Lectures on analysis on metric spaces" by Heinonen.


Q: What is the good way to provide an authentication in FASTAPI? what is the best way to provide an authentication for API. I read about authentication, Given an approach to write user: str = Depends(get_current_user) for each every function. I don't think so this is the good way to write an authentication. Can we erite a middleware for it, and add a userid to request object, so that we can take that in the API request processing. Could you any send me the middleware if some one already written.

A: There is already good implementations in:

*

*fastapi_contrib

*fastapi-users


Q: retrieve appointment from OWA(on premises outlook web Access) using C# How to retrieve calendar meetings and appointments list from OWA(outlook web Access) using C#. without using exchange web services

A: You can use Microsoft Graph Api:
https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/user_list_events
Or Outlook Api:
https://msdn.microsoft.com/en-us/office/office365/api/calendar-rest-operations
Simple googling will get you the above results...


Q: flask-sqlalchemy count function Consider a table named result with the following schema
+----+-----+---------+
| id | tag | user_id |
+----+-----+---------+
|  0 | A   |       0 |
|  1 | A   |       0 |
|  2 | B   |       0 |
|  3 | B   |       0 |
+----+-----+---------+

for user with id=0 I would like to count they number of times a result with tag=A has been appeared. For now I have implemented it using raw SQL statement
db.session.execute('select tag, count(tag) from result where user_id = :id group by tag', {'id':user.id})

How can I write it using flask-sqlalchemy APIs?
Most of results I get mention the sqlalchemy function db.func.count() which is not available in flask-sqlalchemy or has a different path which I am not aware of.

A: I was using PyCharm as my IDE and it was not showing module members correctly, hence I thought count is missing. Here is my solution for the above
user.results.add_columns(Result.tag, db.func.count(Result.tag)).group_by(Result.tag).all()


Q: Removing Title Bar on Android App So I know there are a ton of these questions, but every time I try what they say, my app does not seem to remove the title bar. I have done the style change:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowNoTitle">true</item>   <!-- This should work but it does not -->
</style>

I have also tried:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide(); //This guy here
    setContentView(R.layout.activity_title);

The above works but I still want to use the space the title bar takes for content in my app, which is why I want to be able to modify the XML code rather than use java. Any suggestions?

A: You can either:
<style name="noActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

and in your layout(at the root layout)
android:theme="@theme/noActionBar"

Or
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

However, the last one also hides the Statusbar. You can also set the theme to a default theme(look through the themes and find those with NoActionBar). The last one is useful if you have no plans to style the activity(for an instance if you use SurfaceView) with custom colors, etc.
For an instance you can change AppBaseTheme to have the parent Holo.Light.NoActionBar or any similar theme, but the name has to contain NoActionBar, othervise it has an actionbar

A: Add the below theme to style.xml:
<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

Then set this theme to your Activity in manifest:
<activity
   android:name=".MainActivity"
   android:theme="@style/AppTheme.NoActionBar" />


Q: List of properties not changing when set In a class constructor I have a instantiate a list containing properties:
public MDInstrument() : base()
{
    // bidss = new TickData[] {Bid0};
    Bids = new List<TickData> { Bid0, Bid1, Bid2, Bid3, Bid4, Bid5, Bid6, Bid7, Bid8, Bid9, Bid10, Bid0, Bid11, Bid13, Bid14, Bid15, Bid6, Bid17, Bid18, Bid19};
    Offers = new List<TickData> { Ask0, Ask1, Ask2, Ask3, Ask4, Ask5, Ask6, Ask7, Ask8, Ask9, Ask10, Ask0, Ask11, Ask13, Ask14, Ask15, Ask6, Ask17, Ask18, Ask19};
}

A method in the class updates the object in the list but why is the object always null ?

I must be missing something

A: Your problem is that to begin with Bid{x} and Ask{x} have not been instantiated, i.e. they're null, and then you store a reference to those values, and of course the reference is null.  When you then later on update Bid0 (for example), then that reference is updated, but nothing can know that this is intended to be stored within your set.
Suggest that you change your list to be an array of a fixed known size (here, 20) which will be all nulls to begin with.  Then change your getter/setter accessors for the individual Bid items to actually the array internally.  Then you also don't need all of those separate Bid{x}/Ask{x} variables.


Q: Creating POJO/beans dynamically and set values using CGLib I have a requirement to parse a text file and generate JSON document. The text file has a pattern of text which contains a key which is a name and the value is a huge text of TSV with headers.
I could parse the text file and generate bean classes using the headers and now i want to set the data to this generated bean class. I am using reflection to do this.
Class<?> beanClass = BeanClassGenerator.beanGenerator(k, mapForBeanGeneration);
            try {
                Object beanClassObject = beanClass.newInstance();
                lines.forEach(line -> {
                    if (line != null && !line.isEmpty() && !line.equals("null")) {
                        String[] lineData = line.split("\t");
                        System.out.println("LineData length :: " + lineData.length);
                        Method[] methods = beanClass.getMethods();
                        System.out.println("Methods length :: " + methods.length);
                        int index = 0;
                        for (Method m : methods) {
                            m.setAccessible(true);
                            if (m.getName().startsWith("set")) {
                                try {
                                    if ((lineData.length <= index) && lineData[index] != null) {
                                        m.invoke(beanClassObject, lineData[index]);
                                        index++;
                                    } else {
                                        m.invoke(beanClassObject, " ");
                                    }
                                } catch (IllegalAccessException | InvocationTargetException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                });
                ObjectMapper om = new ObjectMapper();
                System.out.println(om.writeValueAsString(beanClassObject));
            } catch (InstantiationException | IllegalAccessException | JsonProcessingException e) {
                e.printStackTrace();
  }});

The problem with the approach is that most of the times all the column values may not have data it can be nulled.
I am wondering if there is an easier way of doing this. Any help is appreciated.
Here is the bean generation method.
public static Class<?> beanGenerator(final String className, final Map<String, Class<?>> properties) {
        BeanGenerator beanGenerator = new BeanGenerator();
        beanGenerator.setNamingPolicy(new NamingPolicy() {
            @Override
            public String getClassName(String prefix, String source, Object key, Predicate names) {
                return className;
            }
        });

        BeanGenerator.addProperties(beanGenerator, properties);
        return (Class<?>) beanGenerator.createClass();
    }

Here is the sample text file which needs to be converted to the JSON output.
<Data1>
Col1  col2 col3 col4 col5
even    sense   met has
root    greatest    spin    mostly
gentle  held    introduced  palace
cold    equator remember    grandmother
slightly    butter  depth   like
distant second  coast   everyone

<Data2>
Col1  col2 col3 col4 col5 col6 col7 col8
greatest    rope    operation   flies   brown   continent   combination read
slightly    diagram he  grandfather where   party   fifty   pour
well    put plastic anyway  refer   careful correct furniture
how since   army    tongue  birthday    been    clock   official
table   command specific    distant cutting hill    movie   experience
national    though  stopped youth   army    underline   five    know

<Data3>
Col1 col2 col3 col4 col5 col6 col7 col8 col9 col9 col10
vessels characteristic  ship    joy than    tomorrow    high    seven   future  trade
try gray    fourth  advice  week    stream  motion  musical whom    tin
limited daughter    large   rice    came    home    chicken wheat   engine  box
easy    city    pair    strange stage   visitor coach   announced   allow   simple
jet therefore   single  during  construction    flag    bigger  muscle  complex pleasure
income  several coat    range   dull    cattle  damage  jump    present shake

JSON output:
[{
    "<Data1>": [{
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": ""
        }
    ]

}, {
    "<Data2>": [{
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": "",
            "col5": "",
            "col6": "",
            "col7": "",
            "col8": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": "",
            "col5": "",
            "col6": "",
            "col7": "",
            "col8": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": "",
            "col5": "",
            "col6": "",
            "col7": "",
            "col8": ""
        }
    ]

}]

I came up with a solution using the Maps.
Map<String, List<Map<String, String>>> finalMap = new HashMap<>();
        metadataMap.forEach((k, v) -> {

            List<Map<String, String>> datamap = new ArrayList<>();

            String key = k;
            String[] fields = v.getFields();
            List<String> lines = v.getLines();

            lines.forEach(line -> {
                if (line != null && !line.isEmpty() && !line.equals("null")) {
                    String[] fieldData = line.split("\t");
                    Map<String, String> eachLineMap = new HashMap<>();
                    for (int index = 0; index < fields.length; index++) {
                        if (index < fieldData.length && (fieldData[index] != null && !fieldData[index].isEmpty())) {
                            eachLineMap.put(fields[index], fieldData[index]);
                        } else {
                            eachLineMap.put(fields[index], " ");
                        }
                        datamap.add(eachLineMap);
                    }
                }
            });
            finalMap.put(key, datamap);
        });

        try {
            output = new ObjectMapper().writeValueAsString(finalMap);
        }catch(JsonProcessingException e){
            e.printStackTrace();
        }

A: You don't need to write all that logic, you can just use Apache Commons BeanUtils; which provides a utility method (among MANY other utilities), that takes a Map of field names versus field values and populate a given bean with it:
    BeanUtils.populate(target, fieldNameValueMap);

Then the only thing you need to implement is the logic to create the fieldNameValueMap Map; which you can do with this simple method:
    Map<String, String> createFieldNameValueMap(String headerLine, String valuesLine) {
        String[] fieldNames = headerLine.split("\t");
        String[] fieldValues = valuesLine.split("\t");

        return IntStream.range(0, fieldNames.length)
            .mapToObj(Integer::new)
            .collect(Collectors.toMap(idx -> fieldNames[idx], idx -> fieldValues[idx]));
    }

You can test this solution with the following working demo:
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.apache.commons.beanutils.BeanUtils;

import lombok.Data;

public class DynamicBeanUtils {

    static Map<String, String> createFieldNameValueMap(String headerLine, String valuesLine) {
        String[] fieldNames = headerLine.split("\t");
        String[] fieldValues = valuesLine.split("\t");

        return IntStream.range(0, fieldNames.length)
            .mapToObj(Integer::new)
            .collect(Collectors.toMap(idx -> fieldNames[idx], idx -> fieldValues[idx]));
    }

    public static void main(String[] args) {
        String headerLine = "booleanValue\tintValue\tstringValue\tdoubleValue\totherValue";
        String valuesLine = "true\t12\tthis bean will be populated\t22.44\ttest string!!!";

        Object target = new MyBean();
        try {
            BeanUtils.populate(target, createFieldNameValueMap(headerLine, valuesLine));
        } catch (IllegalAccessException | InvocationTargetException e) {
            // HANDLE EXCEPTIONS!
        }

        System.out.println(target);
    }

    @Data
    public static class MyBean {
        private String stringValue;
        private double doubleValue;
        private int intValue;
        private boolean booleanValue;
        private String otherValue;
    }
}

This is the maven repository page for this dependency, so you can include it in your build: https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils/1.9.3
I used Lombok in this solution as well, only to save me the pain of writing getter/setters/toString to test this solution; but it is not required for your solution.
Complete code on GitHub
Hope this helps.

A: You are going way overboard with your solution.
Your data is organized as an array of variable length arrays;
and does not require some crazy on-the-fly class generation solution.
As a side note,
on-the-fly class generation is not inherently crazy;
it is crazy to use on-the-fly class generation in this situation.
Do this:

*

*Look at your data;
it is organized as follows:

*

*first: outer key

*second: exactly one line containing a variable number of space separated array of inner keys.

*third: some number of lines containing values.

*Design a solution to fix your problem

*

*Read the outer key.
Use that value to create the outer key portion of your JSON.

*Read the inner keys.
Store these in an array;
use LinkedList,
not ClownList (ArrayList).

*Do this until the next empty line:

*

*Read a line of values.

*Write the inner JSON; use the inner keys as the keys for this.

*Skip empty lines until one of the following:

*

*If at end of file, write the ending portion of the JSON.

*If you read the next outer key, goto to line 2 (Read the inner keys) above.

*Write the code.

A: I realized that instead of creating the POJOs with a complex approach. It is better to use the Maps and convert them to JSON using Jackson ObjectMapper. Posting for others who think this might be a useful approach.
public String convert(Map<String, ? extends Metadata> metadataMap) {
        String output = "";
        Map<String, List<Map<String, String>>> finalMap = new HashMap<>();
        metadataMap.forEach((k, v) -> {

            List<Map<String, String>> datamap = new LinkedList<>();

            String key = k;
            String[] fields = v.getFields();
            List<String> lines = v.getLines();

            lines.forEach(line -> {
                if (line != null && !line.isEmpty() && !line.equals("null")) {
                    String[] fieldData = line.split("\t",-1);
                    Map<String, String> eachLineMap = new HashMap<>();
                    for (int index = 0; index < fields.length; index++) {
                        if (index < fieldData.length && (fieldData[index] != null && !fieldData[index].isEmpty())) {
                            eachLineMap.put(fields[index], fieldData[index]);
                        } else {
                            eachLineMap.put(fields[index], " ");
                        }
                        datamap.add(eachLineMap);
                    }
                }
            });
            finalMap.put(key, datamap);
        });

        try {
            output = new ObjectMapper().writeValueAsString(finalMap);
        }catch(JsonProcessingException e){
            e.printStackTrace();
        }

        return output;
    }


Q: Angular can't navigate to other component I'm new in Angular.
I'm trying to build a simple application with a list page and a detail page.
The issues are multiple:
1- the search page shows the the th twice and shows it in all pages.
2- when I try to use route link, the app doesn't load the detail page.
I've spent hour searching solution in order to fix this issues...
Here my code:
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { SearchService } from './home/search.service';
import { SearchComponent } from './home/search.component';
import { CharDetailComponent } from './char-detail/char-detail.component';
import { RouterModule } from '@angular/router';

@NgModule({
  declarations: [
    AppComponent,
    SearchComponent,
    CharDetailComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    AppRoutingModule,
    RouterModule,
  ],
  providers: [SearchService],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule { }

export class MyTemplatesModule { }

app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SearchComponent } from './home/search.component';
import { CharDetailComponent } from './char-detail/char-detail.component';

const routes: Routes = [
  {path:'', component: SearchComponent},
  {path:'showDetails', component: CharDetailComponent},

];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

search.component.ts
import { Component, OnInit } from '@angular/core';
import { SearchService } from './search.service';
import { MovieCharacter } from './movie-character';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit{
  people: MovieCharacter[];
  constructor(private searchService: SearchService,
    private router: Router,
    private route: ActivatedRoute
    ) {
      console.log('data');
     }

  ngOnInit() {
    this.searchService.getPeople().subscribe(data=>{
      console.log(data);
      this.people = data.results;
    });
  }

  ngAfterViewInit(){
    this.searchService.getPeople().subscribe(data=>{
      console.log(data);
      this.people = data.results;
    });
  }

  onSelect(name: string){
    this.router.navigate(['/showDetails/'+name]);
  }
}

search.component.html

        name
        description
        url

        {{person.name}}
        {{person.description}}

        {{person.url}}
        <button >
            Go to master Page
        </button>

<router-outlet></router-outlet>

char-detail.component.ts
import { Component, OnInit } from '@angular/core';
import { MovieCharacter } from '../home/movie-character';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-char-detail',
  templateUrl: './char-detail.component.html',
  styleUrls: ['./char-detail.component.css']
})
export class CharDetailComponent implements OnInit{
  people: MovieCharacter[];
  param : string;

  constructor(private route: ActivatedRoute) { }

  ngOnInit():void {
    this.showDetails();
  }

  showDetails(){
    this.param = this.route.snapshot.paramMap.get('name');

  }
}

char-detail.component.html

my name is {{param}}

<router-outlet></router-outlet>

I know the code is very dirty and there are a lot of mistake, but please help me!

A: Welcome to the world of Angular!
To begin with, remove the <router-outlet></router-outlet> from all pages except app.component.html.
After you have done this, retest your pages. If the details page still doesn't show, look at your console for any Javascript errors and please post here :)

A: There are few issues in your code. Here is the solution:

*

*Remove the <router-outlet></router-outlet> from all pages except app.component.html

*If you need to pass name parameter in showDetails page then you need to specify that in app-routing.module.ts so instead of {path:'showDetails', component: CharDetailComponent}, you need to put {path:'showDetails/:name', component: CharDetailComponent}
After this change, ng serve your application again and you are good to go :). Hope this help you.


Q: isnull function vs IS NULL as part of a case statement in a wider sql script, I have the following:
WHEN KWB.ASYCONDTYPE IN ('CIVIL','CIVIL2') AND KWB.CIVCONDGRADE is null THEN 'NO CIVIL CG'
This will set the field to 'NO CIVIL CG' for 1405 records
WHEN KWB.ASYCONDTYPE IN ('CIVIL','CIVIL2') AND ISNULL(KWB.CIVCONDGRADE,'') = '' THEN 'NO CIVIL CG'
This will set the field for 1410 records, which would appear to be the right answer,
as the 5 fields not set in the first instance have ASYCONDTYPE = 'CIVIL' and CIVCONDGRADE is indeed NULL
Slightly worrying, as I'd expect them to produce the same result, and if it wasn't for excel filtering, it might have gone unnoticed.
Can anyone provide an explanation or at least somewhere I can check in the dataset or database to enable me to understand what's going on?

A: That should be becouse you got 1405 records where "KWB.CIVCONDGRADE" is actually NULL and 5 records where "KWB.CIVCONDGRADE" isn't NULL but simply an empty field.
Try to check with this query if it results 5 records:
WHEN KWB.ASYCONDTYPE IN ('CIVIL','CIVIL2') AND KWB.CIVCONDGRADE = '' THEN 'NO CIVIL CG'


Q: Annotated bean config doesnt see bean from XML config Im really confused. I have web-app with Spring Security. I have database.xml config with embedded database:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <jdbc:embedded-database id="dataSource" type="H2" />

</beans>

I have also PersistenceJpaConfig:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("pl.springsecurity.repositories")
public class PersistenceJpaConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
        entityManager.setDataSource(dataSource);
        entityManager.setPackagesToScan(new String[] { "pl.springsecurity.domain" });

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        //vendorAdapter.setShowSql(true);
        entityManager.setJpaVendorAdapter(vendorAdapter);
        return entityManager;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

That works fine when my Spring Security configuration is in xml bean file, and Spring Security filters are declared in web.xml.
But... Since Im trying move Spring Security config to Java class, which means that filters are no longer needed in web.xml, and since I created AbstractSecurityWebApplicationInitializer, Spring can't find DataSource bean delcared in database.xml and bind it into my Jpa Configuration. im really confused why...
Here is my stack trace:
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceJpaConfig': Injection
 of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could no
t autowire field: private javax.sql.DataSource pl.springsecurity.config.PersistenceJpaConfig.dataSource; nested exceptio
n is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource]
found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency ann
otations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(Autowire
dAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBea
nFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBea
nFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanF
actory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.jav
a:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java
:368)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractA
utowireCapableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapa
bleBeanFactory.java:1014)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBea
nFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanF
actory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.jav
a:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationCo
ntext.java:747)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4914)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5201)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3746)
    at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:292)
    at org.apache.catalina.core.StandardContext.backgroundProcess(StandardContext.java:5528)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1349)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSour
ce pl.springsecurity.config.PersistenceJpaConfig.dataSource; nested exception is org.springframework.beans.factory.NoSuc
hBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found for dependency: expected at least 1 be
an which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factor
y.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(Autow
iredAnnotationBeanPostProcessor.java:561)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(Autowire
dAnnotationBeanPostProcessor.java:331)
    ... 40 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSo
urce] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependen
cy annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultLista
bleBeanFactory.java:1301)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.
java:1047)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.ja
va:942)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(Autow
iredAnnotationBeanPostProcessor.java:533)
    ... 42 more

sty 29, 2016 1:40:12 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [dispatcher] in web application [/SpringSecurity] threw load() exception
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found
 for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotati
ons: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultLista
bleBeanFactory.java:1301)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.
java:1047)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.ja
va:942)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(Autow
iredAnnotationBeanPostProcessor.java:533)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(Autowire
dAnnotationBeanPostProcessor.java:331)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBea
nFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBea
nFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanF
actory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.jav
a:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java
:368)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractA
utowireCapableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapa
bleBeanFactory.java:1014)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBea
nFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanF
actory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.jav
a:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationCo
ntext.java:747)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4914)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5201)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3746)
    at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:292)
    at org.apache.catalina.core.StandardContext.backgroundProcess(StandardContext.java:5528)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1349)
    at java.lang.Thread.run(Unknown Source)

Any ideas guys?

A: Use @ImportResource to load your xml file.
@Configuration
@ImportResource(locations = "classpath:/database.xml")
....
public class PersistenceJpaConfig {

Change the location appropriately.

A: You have to load the xml. See docs
You can use @ImportXml("classpath:com/company/app/datasource-config.xml")
on your configuration class


Q: How to make fancyhdr examples work In the Training slides, with examples of the fancyhdr resources there's an example which unfortunately doesn't work or is poorly documented. According to http://mirrors.ctan.org/info/german/fancyhdr/fancyfolien+bsp.pdf (page after 17)
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{fancyhdr}
\usepackage{lipsum}

\pagestyle{fancy}
\fancyhf{}
\fancyhead[EL]{\thepage}
\fancyhead[OR]{\thepage}
\fancyhead[ER]{
\begin{tabular}[b]{l}
Beispielezu\texttt{fancyhdr}\\
HansFriedrichSteffani\\
LehrstuhlElektr.Masch.u.Antriebe
\end{tabular}
\includegraphics[height=3\baselineskip]{tulogo}
}
\fancyhead[OL]{
\includegraphics[height=3\baselineskip]{tulogo}
\begin{tabular}[b]{l}
Beispielezu\texttt{fancyhdr}\\
HansFriedrichSteffani\\
LehrstuhlElektr.Masch.u.Antriebe
\end{tabular}
}

\addtolength{\headheight}{2\baselineskip}
\addtolength{\headheight}{0.61pt}

\begin{document}
\maketitle
\begin{abstract}
\end{abstract}

\section{}
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn

fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
fdklsafjlksdafjlksadjf fjdsaklfj sdalk fdskjlaf lkösad jfklösad jflöksadjf lsdkfj kölsadjf dsklalöjdfj

kfdjslakjf salökfj klsdöafj klsdafj lksöadfj lkösadfj lkösadf jklösafmn
v
\end{document}

should work, but it only compiles with one text for one page on which the header is not displayed (picture tulogo is present), \lipsum[1-20] doesn't work neither.

A: It works OK here, as does \lipsum. Of course, as Marc van Dongen pointed out, you need to load graphicx. If you want to see the different headers, you also want twoside as a class option. I don't have tulogo so I used some images from mwe.

\documentclass[a4paper,10pt,twoside]{article}
\usepackage[utf8]{inputenc}
\usepackage{fancyhdr,graphicx}
\usepackage{lipsum}

\pagestyle{fancy}
\fancyhf{}
\fancyhead[EL]{\thepage}
\fancyhead[OR]{\thepage}
\fancyhead[ER]{
\begin{tabular}[b]{l}
Beispielezu\texttt{fancyhdr}\\
HansFriedrichSteffani\\
LehrstuhlElektr.Masch.u.Antriebe
\end{tabular}
\includegraphics[height=3\baselineskip]{example-image-a}
}
\fancyhead[OL]{
\includegraphics[height=3\baselineskip]{example-image-b}
\begin{tabular}[b]{l}
Beispielezu\texttt{fancyhdr}\\
HansFriedrichSteffani\\
LehrstuhlElektr.Masch.u.Antriebe
\end{tabular}
}

\addtolength{\headheight}{2\baselineskip}
\addtolength{\headheight}{0.61pt}

\begin{document}
\lipsum[1-7]

\end{document}

Note that \maketitle will not use the standard page style on the page with the title. The assumption is that you will not want a header on the title page since you'll have, well, the title. And as Marc van Dongen also pointed out, \maketitle will cause errors if you have not specified anything for it to make the title with.


Q: Not showing from folder So guys I have made a admin system which saves images to a specific folder with specific id according to rows in database.
The picture is in the folder but its not showing..
MY index.php CODe:
    <?php
    include 'admin/connect.php';
        $sql = "SELECT * FROM products";
        $run = mysqli_query($conn, $sql);
        while ($row = $run->fetch_assoc()) {
            $id = $row['id'];

    ?>
    <img src="inventory_images/"<?php echo $id; ?> />
    <?php

}
?>

A: Try removing the " before you echo the id and adding it at the end:
<img src="inventory_images/<?php echo $id; ?>" />

(otherwise your image link is inventory_images/"54 for example)


Q: Bochs 2.6.8 compile with --enable-debugger problem on Ubuntu 16.04LTS x64 I've problems with compiling Bochs. I've tried compile bochs from svn and from sourceforge. Actually I'm trying to compile Bochs 2.6.8 on Ubuntu 16.04LTS x64.
This is how I'm trying to do this:
./configure --enable-debugger

The output is:
http://pastebin.com/WNYAQicN
Then:
make

and I get this error:
http://pastebin.com/7w1qhJy8
Any ideas?


Q: SQL to HiveQL in Hive Hadoop I am trying to write a HiveQL query which joins two data sets by a BAN column where one datasets timestamp is 72+ hours after the other datasets timestamp.  I can write this in SQL but the syntax isn't the same in HiveQL.  Can anyone help?
For example :
SELECT * FROM Session_Step_Table, Case_Table
WHERE Session_Step_Table.BAN = Case_Table.BAN AND
  DATEADD(hour, 72, Session_Step_Table.timestamp) <= Case_Table.timestamp

A: I think you should use date_add() function provided in Hive. Look here