问:
change function to accept multiple arguments
I need to modify the functions below to accept multiple arguments instead of only 4 arguments, I have been able to modify the first function UseWicketToGoFromGooglePolysToWKT successfully, however I am not able to modify UseJstsToDissolveGeometries as I am unsure how to loop through the arguments and assign a variable name to be used later in the function and I also get the error Uncaught TypeError: Cannot read property 'union' of undefined

How can I modify UseJstsToDissolveGeometries to accept multiple arguments?

```<code>function UseWicketToGoFromGooglePolysToWKT(poly1,poly2,poly3,poly4) {
   var wicket = new Wkt.Wkt();

   wicket.fromObject(poly1);
   var wkt1 = wicket.write();

   wicket.fromObject(poly2);
   var wkt2 = wicket.write();

   wicket.fromObject(poly3);
   var wkt3 = wicket.write();

   wicket.fromObject(poly4);
   var wkt4 = wicket.write();

   return [wkt1, wkt2, wkt3, wkt4];
}

function UseJstsToDissolveGeometries(wkt1, wkt2, wkt3, wkt4) {
  // Instantiate JSTS WKTReader and get two JSTS geometry objects
  var wktReader = new jsts.io.WKTReader();
  var geom1 = wktReader.read(wkt1);
  var geom2 = wktReader.read(wkt2);
  var geom3 = wktReader.read(wkt3);
  var geom4 = wktReader.read(wkt4);

  // In JSTS, "union" is synonymous with "dissolve"

  var dissolvedGeometry;
  dissolvedGeometry = geom2.union(geom1);
  dissolvedGeometry = dissolvedGeometry.union(geom3);
  dissolvedGeometry = dissolvedGeometry.union(geom4);

  // Instantiate JSTS WKTWriter and get new geometry's WKT

  var wktWriter = new jsts.io.WKTWriter();
  var wkt = wktWriter.write(dissolvedGeometry);

  // Use Wicket to ingest the new geometry's WKT

  var wicket = new Wkt.Wkt();
  wicket.read(wkt);
}

function DoEverything() {
   var wkt = UseWicketToGoFromGooglePolysToWKT(polygon6, polygon7,polygon8, polygon9);
   UseJstsToDissolveGeometries(wkt[0], wkt[1], wkt[2], wkt[3]);
}
</code>```

My attempt

```<code>function UseWicketToGoFromGooglePolysToWKT(...args) {
   var wicket = new Wkt.Wkt();
   return args.map(item => {
     wicket.fromObject(item);
     return wicket.write();
   })
}

function UseJstsToDissolveGeometries(...args) {
  var wktReader = new jsts.io.WKTReader();
  args.map(item => {
    return wktReader.read(item);
  })

  var dissolvedGeometry;
  args.map(item => {
    return dissolvedGeometry = dissolvedGeometry.union(item)
  })

  var wktWriter = new jsts.io.WKTWriter();
  var wkt = wktWriter.write(dissolvedGeometry);

  // Use Wicket to ingest the new geometry's WKT
  var wicket = new Wkt.Wkt();
  wicket.read(wkt);
}

function DoEverything() {
   var wkt = UseWicketToGoFromGooglePolysToWKT(polygon6, polygon7,polygon8, polygon9);
   UseJstsToDissolveGeometries(wkt[0], wkt[1], wkt[2], wkt[3]);
}
</code>```

答:
I believe you're looking for something like this, the problem is you're using
dissolvedGeometry before it's been defined

```<code>function UseJstsToDissolveGeometries(...args) {
  var wktReader = new jsts.io.WKTReader();
  var geoms = args.map(item => {
    return wktReader.read(item);
  })

  var dissolvedGeometry = geoms.reduce((accumulator , item, currentIndex, array) => {
    if (currentIndex == 0) {
      return array[1].union(item);
    }

    if(currentIndex == 1){
      return accumulator;
    }

    return accumulator.union(item)
  })

  var wktWriter = new jsts.io.WKTWriter();
  var wkt = wktWriter.write(dissolvedGeometry);

  // Use Wicket to ingest the new geometry's WKT
  var wicket = new Wkt.Wkt();
  wicket.read(wkt);
}
</code>```

Also, you need the result from the .map. Also as you only want one result in dissolvedGeometry, I think a .reduce would be better

P.S as I don't actually know what these objects produce, what methods they have etc, this code might not work but will give you the idea on what to do to get it to work

Body:
I need to modify the functions below to accept multiple arguments instead of only 4 arguments, I have been able to modify the first function UseWicketToGoFromGooglePolysToWKT successfully, however I am not able to modify UseJstsToDissolveGeometries as I am unsure how to loop through the arguments and assign a variable name to be used later in the function and I also get the error Uncaught TypeError: Cannot read property 'union' of undefined

How can I modify UseJstsToDissolveGeometries to accept multiple arguments?

function UseWicketToGoFromGooglePolysToWKT(poly1,poly2,poly3,poly4) {
   var wicket = new Wkt.Wkt();

   wicket.fromObject(poly1);
   var wkt1 = wicket.write();

   wicket.fromObject(poly2);
   var wkt2 = wicket.write();

   wicket.fromObject(poly3);
   var wkt3 = wicket.write();

   wicket.fromObject(poly4);
   var wkt4 = wicket.write();

   return [wkt1, wkt2, wkt3, wkt4];
}

function UseJstsToDissolveGeometries(wkt1, wkt2, wkt3, wkt4) {
  // Instantiate JSTS WKTReader and get two JSTS geometry objects
  var wktReader = new jsts.io.WKTReader();
  var geom1 = wktReader.read(wkt1);
  var geom2 = wktReader.read(wkt2);
  var geom3 = wktReader.read(wkt3);
  var geom4 = wktReader.read(wkt4);

  // In JSTS, "union" is synonymous with "dissolve"

  var dissolvedGeometry;
  dissolvedGeometry = geom2.union(geom1);
  dissolvedGeometry = dissolvedGeometry.union(geom3);
  dissolvedGeometry = dissolvedGeometry.union(geom4);

  // Instantiate JSTS WKTWriter and get new geometry's WKT

  var wktWriter = new jsts.io.WKTWriter();
  var wkt = wktWriter.write(dissolvedGeometry);

  // Use Wicket to ingest the new geometry's WKT

  var wicket = new Wkt.Wkt();
  wicket.read(wkt);
}

function DoEverything() {
   var wkt = UseWicketToGoFromGooglePolysToWKT(polygon6, polygon7,polygon8, polygon9);
   UseJstsToDissolveGeometries(wkt[0], wkt[1], wkt[2], wkt[3]);
}

My attempt

function UseWicketToGoFromGooglePolysToWKT(...args) {
   var wicket = new Wkt.Wkt();
   return args.map(item => {
     wicket.fromObject(item);
     return wicket.write();
   })
}

function UseJstsToDissolveGeometries(...args) {
  var wktReader = new jsts.io.WKTReader();
  args.map(item => {
    return wktReader.read(item);
  })

  var dissolvedGeometry;
  args.map(item => {
    return dissolvedGeometry = dissolvedGeometry.union(item)
  })

  var wktWriter = new jsts.io.WKTWriter();
  var wkt = wktWriter.write(dissolvedGeometry);

  // Use Wicket to ingest the new geometry's WKT
  var wicket = new Wkt.Wkt();
  wicket.read(wkt);
}

function DoEverything() {
   var wkt = UseWicketToGoFromGooglePolysToWKT(polygon6, polygon7,polygon8, polygon9);
   UseJstsToDissolveGeometries(wkt[0], wkt[1], wkt[2], wkt[3]);
}

Body:
I believe you're looking for something like this, the problem is you're using
dissolvedGeometry before it's been defined

function UseJstsToDissolveGeometries(...args) {
  var wktReader = new jsts.io.WKTReader();
  var geoms = args.map(item => {
    return wktReader.read(item);
  })

  var dissolvedGeometry = geoms.reduce((accumulator , item, currentIndex, array) => {
    if (currentIndex == 0) {
      return array[1].union(item);
    }

    if(currentIndex == 1){
      return accumulator;
    }

    return accumulator.union(item)
  })

  var wktWriter = new jsts.io.WKTWriter();
  var wkt = wktWriter.write(dissolvedGeometry);

  // Use Wicket to ingest the new geometry's WKT
  var wicket = new Wkt.Wkt();
  wicket.read(wkt);
}

Also, you need the result from the .map. Also as you only want one result in dissolvedGeometry, I think a .reduce would be better

P.S as I don't actually know what these objects produce, what methods they have etc, this code might not work but will give you the idea on what to do to get it to work


来源: stackexchange

问:
google app engine 500 Unknown error
While calling endpoint API, sometimes we are getting 500 Unknown error from server, but most of the time API works fine. And also in case of 500 Unknown error, we are unable to see any logs in google console logs.
API response takes 2 sec approx. We are using App engine Java deployment.

Can anyone help me find the root cause of this problem?

Following is the chrome console error
/conge-portal/#!/dashboard/myage:1 XMLHttpRequest cannot load https://a-master-server.appspot.com/_ah/api/ageEndPoint/v1/aghie…5648/674390454714943921958166322392772?showTarget=true&month=May&year=2017. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 500.

答: Issue stopped after migrating to endpoint framework 2.0</p>

ContentLicense: CC BY-SA 3.0

Title: google app engine 500 Unknown error


问:
Array in Array in Array - Cant get data from JSON String
Original Post: Objects in Arrays...

The data I provided was only one line. I have many lines of the same with different "Bestaende" and "Menge":

```<code>[{"Ean":"","Barcode":"010241770148","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770149","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770151","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770152","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90}]
</code>```

The foreach you describe I understand, but it doesn't work as expected .

```<code>$jsonarray = json_decode($jsonfile,true);
echo 'Array 0 Menge: '.$jsonarray['0']['Bestaende']['0']['Menge'].'<br>';
echo 'Array 1 Menge: '.$jsonarray['1']['Bestaende']['0']['Menge'].'<br>';
echo 'Array 2 Menge: '.$jsonarray['2']['Bestaende']['0']['Menge'].'<br>';
echo 'Array 3 Menge: '.$jsonarray['3']['Bestaende']['0']['Menge'].'<br>';
</code>```

brings out

```<code>Array 0 Menge: 1
Array 1 Menge: 1
Array 2 Menge: 1
Array 3 Menge: 1
</code>```

Okay. But when I try to foreach it (because I have a list of base data), the output is only one row. I get only one entry "1". Nothing more.

```<code>$x=0;
foreach($jsonarray[$x]['Bestaende'] as $idx => $Bestaende) {
   echo 'Print Menge: ';
   print_r($Bestaende['Menge']);
 $x++;
}
</code>```

So I try to loop over the Array to get the data. The Result is:

```<code>Array ( [Filiale] => 1 [FilialeBez] => Laden [Menge] => 1 [Gln] => [Dispo] => 0 )
Print Menge: 1
</code>```

I have a problem with the array in array in array ... Is there a better way to get the data I want?

Or is my foreach loop wrong?

答:
Try it like this </p>

```<code>foreach($jsonarray as $k=>$alldata)
{
   foreach($alldata["Bestaende"] as $idx => $Bestaende)
   {
       echo '```';
       echo 'Print Menge: '.$Bestaende['Menge'];
       echo '```';
   }
}
</code>```

Body:
Original Post: Objects in Arrays...

The data I provided was only one line. I have many lines of the same with different "Bestaende" and "Menge":

[{"Ean":"","Barcode":"010241770148","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770149","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770151","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770152","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90}]

The foreach you describe I understand, but it doesn't work as expected .

$jsonarray = json_decode($jsonfile,true);
echo 'Array 0 Menge: '.$jsonarray['0']['Bestaende']['0']['Menge'].'
';
echo 'Array 1 Menge: '.$jsonarray['1']['Bestaende']['0']['Menge'].'
';
echo 'Array 2 Menge: '.$jsonarray['2']['Bestaende']['0']['Menge'].'
';
echo 'Array 3 Menge: '.$jsonarray['3']['Bestaende']['0']['Menge'].'
';

brings out

Array 0 Menge: 1
Array 1 Menge: 1
Array 2 Menge: 1
Array 3 Menge: 1

Okay. But when I try to foreach it (because I have a list of base data), the output is only one row. I get only one entry "1". Nothing more.

$x=0;
foreach($jsonarray[$x]['Bestaende'] as $idx => $Bestaende) {
   echo 'Print Menge: ';
   print_r($Bestaende['Menge']);
 $x++;
}

So I try to loop over the Array to get the data. The Result is:

Array ( [Filiale] => 1 [FilialeBez] => Laden [Menge] => 1 [Gln] => [Dispo] => 0 )
Print Menge: 1

I have a problem with the array in array in array ... Is there a better way to get the data I want?

Or is my foreach loop wrong?

Body:
Try it like this

foreach($jsonarray as $k=>$alldata)
{
   foreach($alldata["Bestaende"] as $idx => $Bestaende)
   {
       echo '<pre>';
       echo 'Print Menge: '.$Bestaende['Menge'];
       echo '</pre>';
   }
}


问:
Write text behind image keeping everything responsive
This is what I'm trying to achieve through HTML/CSS on my website:

I want to add a div of text behind an image which I have been able to achieve on a laptop screen but I am struggling to keep it from overlapping with the text to the image's right when I resize the screen. How can I keep this structure responsive?

答:
You can do a lot with absolute positions and z-index.

In the following example I've used absolute positions and percentages to keep the responsiveness intact, and i've used z-index to overlap the bottom div.

Click Full Page to test it out. Hope this helps.

.background {
  position: relative;
  width: 100%;
  height: 400px;
  background: yellow;
}

.image {
  position: absolute;
  height: 350px;
  width: 30%;
  background: blue;
  left: 15%;
  z-index: 1;
}

.imagetext {
  position: absolute;
  left: 50%;
}

.text {
  position: absolute;
  width: 80%;
  height: 100px;
  left: 10%;
  bottom: 0;
  background: grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="background">
<div class="image"></div>
<div class="imagetext">Lorem ipsum dolor sit amet</div>
<div class="text">Lorem ipsum dolor sit amet</div>
</div></code>```

Body:
You can do a lot with absolute positions and z-index.

In the following example I've used absolute positions and percentages to keep the responsiveness intact, and i've used z-index to overlap the bottom div.

Click Full Page to test it out. Hope this helps.

.background {
  position: relative;
  width: 100%;
  height: 400px;
  background: yellow;
}

.image {
  position: absolute;
  height: 350px;
  width: 30%;
  background: blue;
  left: 15%;
  z-index: 1;
}

.imagetext {
  position: absolute;
  left: 50%;
}

.text {
  position: absolute;
  width: 80%;
  height: 100px;
  left: 10%;
  bottom: 0;
  background: grey;
}

<div class="background">
<div class="image"></div>
<div class="imagetext">Lorem ipsum dolor sit amet</div>
<div class="text">Lorem ipsum dolor sit amet</div>
</div>


答:
You loop only over $jsonarray[0]['Bestaende'] which only contains one item. You should loop over $jsonarray and from there dive in deeper.

```<code>foreach($jsonarray as $item) {
    echo 'Print Menge: ';
    print_r($item['Bestaende']['0']['Menge']);
    // or even dive in deeper
    foreach ($item['Bestaende'] as $bestaende) {
        // .. $bestaende['Menge'];
    }
}
</code>```

Title: Array in Array in Array - Cant get data from JSON String

Body:
You loop only over $jsonarray[0]['Bestaende'] which only contains one item. You should loop over $jsonarray and from there dive in deeper.

foreach($jsonarray as $item) {
    echo 'Print Menge: ';
    print_r($item['Bestaende']['0']['Menge']);
    // or even dive in deeper
    foreach ($item['Bestaende'] as $bestaende) {
        // .. $bestaende['Menge'];
    }
}


问:
How would one implement a variable sized cache object to reduce memory allocations in C++?
Before the performance people tear my head off: yes, I have done profiling before asking this :)

I'm once again looking at my one of a type container, and while I have a solution that works, the performance is poor because each type of item that's cached results in a separate allocation on the heap (which is of course expensive).

Based on static analysis of my program's input, I have figured out a way to know the total size required by all of the objects that might be put in my cache object that's getting passed around. Basically, I have a list of objects that may be constructed in a given cache object, so I know what the size of what I might have to cache is in advance, but not at compile time -- runtime only.

Basically, what I'd like to do is what boost::make_shared does -- gets a single memory block, and constructs the shared_ptr bits as well as the controlled object in the same memory block.

I don't have to worry about preserving copying behavior as the cache object is noncopyable and passed around by pointer by clients (it's usually stored in something like a ptr_vector or a std::auto_ptr).

I'm not familiar however with how exactly one would implement such a container however, namely how one follows alignment restrictions and such.

In pseudocode, what I'd like to do:

```<code>//I know a lot of what's in here is not portable -- I need to run only on x86
//and x64 machines. Yes, this couple of classes looks hacky, but I'd rather
//have one hacky class than a whole programfull :)

class CacheRegistrar
{
    //Blah blah
public:
    //Figures out what objects will be in the cache, etc
    const std::vector<std::size_t>& GetRequiredObjectSizes() const;
    //Other stuff...
    template <typename T>
    void RegisterCacheObject();
    template <typename T>
    std::size_t GetObjectIndex() const;
    // etc.
};

class CacheObject;

std::auto_ptr<CacheObject> CacheObjectFactory(const CacheRegistrar& registrar)
{
    //Pretend this is in a CPP file and therefore CacheObject is defined...
    const std::vector<size_t>& sizes(registrar.GetRequiredObjectSizes());
    std::size_t sumOfCache = std::accumulate(sizes.begin(), sizes.end());
    sumOfCache += sizeof(CacheObject);
    boost::scoped_array<char> buffer(new char[] sumOfCache);
    CacheObject *obj = new (reinterpret_cast<void *>(buffer.get())) CacheObject;
    buffer.release(); //PSEUDOCODE (boost::scoped_array has no release member);
    return std::auto_ptr<CacheObject>(obj); //Nothrow
}

class CacheObject
{
    CacheRegistrar *registrar; //Set by my constructor
public:
    template<typename T>
    T& Get()
    {
        char * startOfCache = reinterpret_cast<char *>(this) +
            sizeof(CacheObject);
        char * cacheItem = startOfCache + registrar->GetObjectIndex<T>();
        return *reinterpret_cast<T*>(cacheItem);
    }
};
</code>```

Is my general concept sound here? Is there are better way of accomplishing this?

答: But first, read this article by Andrei Alexandrescu on what he thinks he should have written in that chapter -- a way to build heaps using Heap Layers (by yours truly). I used Heap Layers to build Hoard, DieHard, and DieHarder, as well as the custom allocators used in our OOPLSA 2002 paper, Reconsidering Custom Memory Allocation, which you should also read before embarking on creating a custom allocator.</p>

ContentLicense: CC BY-SA 2.5

Body:
Before the performance people tear my head off: yes, I have done profiling before asking this :)

I'm once again looking at my one of a type container, and while I have a solution that works, the performance is poor because each type of item that's cached results in a separate allocation on the heap (which is of course expensive).

Based on static analysis of my program's input, I have figured out a way to know the total size required by all of the objects that might be put in my cache object that's getting passed around. Basically, I have a list of objects that may be constructed in a given cache object, so I know what the size of what I might have to cache is in advance, but not at compile time -- runtime only.

Basically, what I'd like to do is what boost::make_shared does -- gets a single memory block, and constructs the shared_ptr bits as well as the controlled object in the same memory block.

I don't have to worry about preserving copying behavior as the cache object is noncopyable and passed around by pointer by clients (it's usually stored in something like a ptr_vector or a std::auto_ptr).

I'm not familiar however with how exactly one would implement such a container however, namely how one follows alignment restrictions and such.

In pseudocode, what I'd like to do:

//I know a lot of what's in here is not portable -- I need to run only on x86
//and x64 machines. Yes, this couple of classes looks hacky, but I'd rather
//have one hacky class than a whole programfull :)

class CacheRegistrar
{
    //Blah blah
public:
    //Figures out what objects will be in the cache, etc
    const std::vector<std::size_t>& GetRequiredObjectSizes() const;
    //Other stuff...
    template <typename T>
    void RegisterCacheObject();
    template <typename T>
    std::size_t GetObjectIndex() const;
    // etc.
};

class CacheObject;

std::auto_ptr<CacheObject> CacheObjectFactory(const CacheRegistrar& registrar)
{
    //Pretend this is in a CPP file and therefore CacheObject is defined...
    const std::vector<size_t>& sizes(registrar.GetRequiredObjectSizes());
    std::size_t sumOfCache = std::accumulate(sizes.begin(), sizes.end());
    sumOfCache += sizeof(CacheObject);
    boost::scoped_array<char> buffer(new char[] sumOfCache);
    CacheObject *obj = new (reinterpret_cast<void *>(buffer.get())) CacheObject;
    buffer.release(); //PSEUDOCODE (boost::scoped_array has no release member);
    return std::auto_ptr<CacheObject>(obj); //Nothrow
}

class CacheObject
{
    CacheRegistrar *registrar; //Set by my constructor
public:
    template<typename T>
    T& Get()
    {
        char * startOfCache = reinterpret_cast<char *>(this) +
            sizeof(CacheObject);
        char * cacheItem = startOfCache + registrar->GetObjectIndex<T>();
        return *reinterpret_cast<T*>(cacheItem);
    }
};

Is my general concept sound here? Is there are better way of accomplishing this?


问:
Connect to sql server windows authentication
I have a sql server instance ,

I can connect with sql autehntication

```<code>public static void main(String[] args) {
     Connection conn = null;
     String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
     String url = "jdbc:sqlserver://localhost:1434;databasename=Test;";
     String userName = "sa";
     String password = "paquito";
     Statement stmt;
     try{
       Class.forName(driver);//.newInstance();
       conn = DriverManager.getConnection(url,userName,password);
       stmt = conn.createStatement();
       System.out.println("conectado = ");
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
}
</code>```

but with windows authentication

```<code>public static void main(String[] args) {
     Connection conn = null;
     String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
     String url = "jdbc:sqlserver://localhost:1434;databasename=Test;integratedSecurity=true";
     String userName = "paco";
     String password = "";
     Statement stmt;
     try{
       Class.forName(driver);//.newInstance();
       conn = DriverManager.getConnection(url,userName,password);
       stmt = conn.createStatement();
       System.out.println("conectado = ");
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
}
</code>```

i take this error:

```<code>com.microsoft.sqlserver.jdbc.SQLServerException: Unable to open the "Test" database requested by the login. Login failed. Client connection ID: 577da72f-f0d4-4ac6-abab-243f0f84d0e3
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:279)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:99)
</code>```

NOTE: in sql management i can connect with sql authentication and windows authentication

suggestion?

答: Can you replace integratedSecurity with Integrated Security in your connection string and try this?</p>

Body:
I have a sql server instance ,

I can connect with sql autehntication

public static void main(String[] args) {
     Connection conn = null;
     String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
     String url = "jdbc:sqlserver://localhost:1434;databasename=Test;";
     String userName = "sa";
     String password = "paquito";
     Statement stmt;
     try{
       Class.forName(driver);//.newInstance();
       conn = DriverManager.getConnection(url,userName,password);
       stmt = conn.createStatement();
       System.out.println("conectado = ");
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
}

but with windows authentication

public static void main(String[] args) {
     Connection conn = null;
     String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
     String url = "jdbc:sqlserver://localhost:1434;databasename=Test;integratedSecurity=true";
     String userName = "paco";
     String password = "";
     Statement stmt;
     try{
       Class.forName(driver);//.newInstance();
       conn = DriverManager.getConnection(url,userName,password);
       stmt = conn.createStatement();
       System.out.println("conectado = ");
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
}

i take this error:

com.microsoft.sqlserver.jdbc.SQLServerException: Unable to open the "Test" database requested by the login. Login failed. Client connection ID: 577da72f-f0d4-4ac6-abab-243f0f84d0e3
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:279)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:99)

NOTE: in sql management i can connect with sql authentication and windows authentication

suggestion?


问:
Implementing HMAC and SHA1 encryption in swift
I am relatively new to Swift and i'm stuck encrypting using HMAC and SHA1. I Found the following answer https://stackoverflow.com/a/24411522/4188344 but i can't work out how to implement this properly. Any help would be amazing.</p>

答:
I have checked the above answers and found it so lengthy.

Solution: I got third party: IDZSwiftCommonCrypto

Use pod: pod 'IDZSwiftCommonCrypto'

and use the following function to achieve desired output:

```<code>func getHMacSHA1(forMessage message: String, key: String) -> String? {
    let hMacVal = HMAC(algorithm: HMAC.Algorithm.sha1, key: key).update(string: message)?.final()
    if let encryptedData = hMacVal {
        let decData = NSData(bytes: encryptedData, length: Int(encryptedData.count))
        let base64String = decData.base64EncodedString(options: .lineLength64Characters)
        print("base64String: \(base64String)")
        return base64String
    } else {
        return nil
    }
}
</code>```

For check the result use following website:

https://hash.online-convert.com/sha1-generator

Tested in Swift 4.0

Body:
I have checked the above answers and found it so lengthy.

Solution: I got third party: IDZSwiftCommonCrypto

Use pod: pod 'IDZSwiftCommonCrypto'

and use the following function to achieve desired output:

func getHMacSHA1(forMessage message: String, key: String) -> String? {
    let hMacVal = HMAC(algorithm: HMAC.Algorithm.sha1, key: key).update(string: message)?.final()
    if let encryptedData = hMacVal {
        let decData = NSData(bytes: encryptedData, length: Int(encryptedData.count))
        let base64String = decData.base64EncodedString(options: .lineLength64Characters)
        print("base64String: \(base64String)")
        return base64String
    } else {
        return nil
    }
}

For check the result use following website:

https://hash.online-convert.com/sha1-generator

Tested in Swift 4.0


问:
Create new "groups" from existing list of groups using date and status
So I currently have a list of "pursuits" (shown in the "label" column). I need to break these pursuits into separate instances depending on whether they are active or inactive and how many times they have been active or inactive. I currently have:

```<code> datetime                                      title    label   status           option_title
1  2016-08-06 What is the current stage of this Pursuit?      AIG     <NA> 1 - Opportunity Review
2  2016-08-06                            Pursuit status:      AIG   Active                   <NA>
3  2016-08-31 What is the current stage of this Pursuit?      AIG     <NA>    2 - Solution Review
4  2016-12-13 What is the current stage of this Pursuit?      AIG     <NA>    4 - Submit Proposal
5  2016-10-27 What is the current stage of this Pursuit?  Allianz     <NA>      Pre-Qualification
6  2016-11-14                            Pursuit status:  Allianz   Active                   <NA>
7  2017-05-18 What is the current stage of this Pursuit?  Allianz     <NA> 1 - Opportunity Review
8  2017-05-18 What is the current stage of this Pursuit?  Allianz     <NA>      Pre-Qualification
9  2017-08-24                            Pursuit status:  Allianz Inactive                   <NA>
10 2016-10-27 What is the current stage of this Pursuit?  Allianz     <NA>      Pre-Qualification
11 2016-11-14                            Pursuit status:  Allianz   Active                   <NA>
12 2016-12-19 What is the current stage of this Pursuit?  Allianz     <NA> 1 - Opportunity Review
13 2017-04-14 What is the current stage of this Pursuit?  Allianz     <NA>    2 - Solution Review
</code>```

I want to get:

```<code> datetime                                      title          label         option_title
1  2016-08-06 What is the current stage of this Pursuit?      AIG - Active1   1 - Opportunity Review
2  2016-08-31 What is the current stage of this Pursuit?      AIG - Active1   2 - Solution Review
3  2016-12-13 What is the current stage of this Pursuit?      AIG - Active1   4 - Submit Proposal
4  2016-10-27 What is the current stage of this Pursuit?  Allianz - Active1   Pre-Qualification
5  2017-05-18 What is the current stage of this Pursuit?  Allianz - Active1   1 - Opportunity Review
6  2017-05-18 What is the current stage of this Pursuit?  Allianz - Active1   Pre-Qualification
7  2016-10-27 What is the current stage of this Pursuit?  Allianz - Inactive1 Pre-Qualification
12 2016-12-19 What is the current stage of this Pursuit?  Allianz - Active2   1 - Opportunity Review
13 2017-04-14 What is the current stage of this Pursuit?  Allianz - Active2   2 - Solution Review
</code>```

I'm assuming this could be done in dplyr using the "datetime" field with the "status" field, but I'm unsure how to approach it. Any ideas?

答:
As per expectation  it looks like you want to sort list by label & Date. You can call sort function on your array to sort and implement your logic for sorting in block.

Refer Sort array of objects by two properties

Body:
So I currently have a list of "pursuits" (shown in the "label" column). I need to break these pursuits into separate instances depending on whether they are active or inactive and how many times they have been active or inactive. I currently have:

 datetime                                      title    label   status           option_title
1  2016-08-06 What is the current stage of this Pursuit?      AIG     <NA> 1 - Opportunity Review
2  2016-08-06                            Pursuit status:      AIG   Active                   <NA>
3  2016-08-31 What is the current stage of this Pursuit?      AIG     <NA>    2 - Solution Review
4  2016-12-13 What is the current stage of this Pursuit?      AIG     <NA>    4 - Submit Proposal
5  2016-10-27 What is the current stage of this Pursuit?  Allianz     <NA>      Pre-Qualification
6  2016-11-14                            Pursuit status:  Allianz   Active                   <NA>
7  2017-05-18 What is the current stage of this Pursuit?  Allianz     <NA> 1 - Opportunity Review
8  2017-05-18 What is the current stage of this Pursuit?  Allianz     <NA>      Pre-Qualification
9  2017-08-24                            Pursuit status:  Allianz Inactive                   <NA>
10 2016-10-27 What is the current stage of this Pursuit?  Allianz     <NA>      Pre-Qualification
11 2016-11-14                            Pursuit status:  Allianz   Active                   <NA>
12 2016-12-19 What is the current stage of this Pursuit?  Allianz     <NA> 1 - Opportunity Review
13 2017-04-14 What is the current stage of this Pursuit?  Allianz     <NA>    2 - Solution Review

I want to get:

 datetime                                      title          label         option_title
1  2016-08-06 What is the current stage of this Pursuit?      AIG - Active1   1 - Opportunity Review
2  2016-08-31 What is the current stage of this Pursuit?      AIG - Active1   2 - Solution Review
3  2016-12-13 What is the current stage of this Pursuit?      AIG - Active1   4 - Submit Proposal
4  2016-10-27 What is the current stage of this Pursuit?  Allianz - Active1   Pre-Qualification
5  2017-05-18 What is the current stage of this Pursuit?  Allianz - Active1   1 - Opportunity Review
6  2017-05-18 What is the current stage of this Pursuit?  Allianz - Active1   Pre-Qualification
7  2016-10-27 What is the current stage of this Pursuit?  Allianz - Inactive1 Pre-Qualification
12 2016-12-19 What is the current stage of this Pursuit?  Allianz - Active2   1 - Opportunity Review
13 2017-04-14 What is the current stage of this Pursuit?  Allianz - Active2   2 - Solution Review

I'm assuming this could be done in dplyr using the "datetime" field with the "status" field, but I'm unsure how to approach it. Any ideas?


问:
before_destroy callback not stopping record from being deleted
I am trying to prevent a record from being destroyed if there are children.

```<code>class Submission < ActiveRecord::Base

has_many :quotations, :dependent => :destroy

 before_destroy :check_for_payments

  def quoted?
    quotations.any?
  end

  def has_payments?
   true if quotations.detect {|q| q.payment}
  end

  private

  def check_for_payments
    if quoted? && has_payments?
      errors[:base] << "cannot delete submission that has already been paid"
      false
    end
  end

end

class Quotation < ActiveRecord::Base

    #associations
    belongs_to :submission
        has_one :payment_notification
        has_one :payment

         before_destroy :check_for_payments

private

def check_for_payments
  if payment_notification || payment
    errors[:base] << "cannot delete quotation while payment exist"
    return false
  end
end
end
</code>```

When I test this code the before_destroy :check_for_payments prevents the Quotation record from being deleted.

However the :check_for_payments in the Submission before_destroy callback does not stop the Submission from being deleted.

How can I stop the Submission with payments from being destroyed?

答:
In Rails 5 you could also:</p>

```<code>def destroy
  quoted? && has_payments? ? self : super
end

submission.destroy # => submission
submission.destroyed? # => true/false
</code>```

Body:
I am trying to prevent a record from being destroyed if there are children.

class Submission < ActiveRecord::Base

has_many :quotations, :dependent => :destroy

 before_destroy :check_for_payments

  def quoted?
    quotations.any?
  end

  def has_payments?
   true if quotations.detect {|q| q.payment}
  end

  private

  def check_for_payments
    if quoted? && has_payments?
      errors[:base] << "cannot delete submission that has already been paid"
      false
    end
  end

end

class Quotation < ActiveRecord::Base

    #associations
    belongs_to :submission
        has_one :payment_notification
        has_one :payment

         before_destroy :check_for_payments

private

def check_for_payments
  if payment_notification || payment
    errors[:base] << "cannot delete quotation while payment exist"
    return false
  end
end
end

When I test this code the before_destroy :check_for_payments prevents the Quotation record from being deleted.

However the :check_for_payments in the Submission before_destroy callback does not stop the Submission from being deleted.

How can I stop the Submission with payments from being destroyed?

Body:
In Rails 5 you could also:

def destroy
  quoted? && has_payments? ? self : super
end

submission.destroy # => submission
submission.destroyed? # => true/false


问:
Adding padding to
 in CSS is making the content not move with consistent line-height
My predicament is this. I have a list, a simple cart, login, user registration list. I want to move the list up by adding padding. But I cannot with out the list adding line height. What is the way around this? See examples below. This list is in the header.

Before:

.content{
  border: 2px solid #000;
}

li {
 list-style-type: none;
 font-size: 10px;
 direction: right;
 text-align: right;
 padding-bottom: 20px;
 line-height: 1;
 display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  <ul>
    <li>Cart</li>
    <li>Login</li>
    <li>Customer Registration</li>
  </ul>
</div></code>```

After:

答: You need to add the padding to the ul and not the li .

Title: Adding padding to <li> in CSS is making the content not move with consistent line-height

Body:
My predicament is this. I have a list, a simple cart, login, user registration list. I want to move the list up by adding padding. But I cannot with out the list adding line height. What is the way around this? See examples below. This list is in the header.

Before:

.content{
  border: 2px solid #000;
}

li {
 list-style-type: none;
 font-size: 10px;
 direction: right;
 text-align: right;
 padding-bottom: 20px;
 line-height: 1;
 display: block;
}

Cart

Login

Customer Registration

After:


问:
Django: DetailView, Where to update a counter?
I have the following class:

```<code>class ImageGalleryDetail(DetailView):

    model = ImageGallery
    template_name = 'galleries/imagegallery_detail.html'

    def get_context_data(self, **kwargs):
        context = super(ImageGalleryDetail, self).get_context_data(**kwargs)
        context['image'] = self.object
        context['gallery'] = self.object.owner_gallery

        return context

    def update_counter(self):
        self.object.hits = F('hits') + 1
        self.object.save()
</code>```

And as you can see I have a method called update_counter() where I used an F expression to update a counter atomically.

My question is, where should I locate the call to this function? the way I see it I could locate it in the get_context_data() method but it sounds odd to me, the name of the method starts with get not set. And I think I shouldn't be saving model-related stuff in there... (beginner here!)

Method Flowchart of DetailView is the following:

```<code>1. dispatch()
2. http_method_not_allowed()
3. get_template_names()
4. get_slug_field()
5. get_queryset()
6. get_object()
7. get_context_object_name()
8. get_context_data()
9. get()
10. render_to_response()
</code>```

So I honestly have no idea what method should I overwrite in order to call update_counter function. Any help would be appreciated. Or if this is the wrong way of doing things... I would like to know that too! :)

答:
in a detail view  if your model contains a page_click field</p>

```<code>def get_context_data(self, **kwargs):
    context = super(DetailView, self).get_context_data(**kwargs)
    obj = self.get_object()
    obj.page_click = obj.page_click + 1
    obj.save()
    return context
</code>```

Body:
I have the following class:

class ImageGalleryDetail(DetailView):

    model = ImageGallery
    template_name = 'galleries/imagegallery_detail.html'

    def get_context_data(self, **kwargs):
        context = super(ImageGalleryDetail, self).get_context_data(**kwargs)
        context['image'] = self.object
        context['gallery'] = self.object.owner_gallery

        return context

    def update_counter(self):
        self.object.hits = F('hits') + 1
        self.object.save()

And as you can see I have a method called update_counter() where I used an F expression to update a counter atomically.

My question is, where should I locate the call to this function? the way I see it I could locate it in the get_context_data() method but it sounds odd to me, the name of the method starts with get not set. And I think I shouldn't be saving model-related stuff in there... (beginner here!)

Method Flowchart of DetailView is the following:

1. dispatch()
2. http_method_not_allowed()
3. get_template_names()
4. get_slug_field()
5. get_queryset()
6. get_object()
7. get_context_object_name()
8. get_context_data()
9. get()
10. render_to_response()

So I honestly have no idea what method should I overwrite in order to call update_counter function. Any help would be appreciated. Or if this is the wrong way of doing things... I would like to know that too! :)

Body:
in a detail view  if your model contains a page_click field

def get_context_data(self, **kwargs):
    context = super(DetailView, self).get_context_data(**kwargs)
    obj = self.get_object()
    obj.page_click = obj.page_click + 1
    obj.save()
    return context


问:
UWP - Cant create a package under release mode in Visual Studio Enterprise Edition 2015
Please see the screenshot of the errorenter image description here</p>

答: Could you delete the x86 or x64 folder (whichever you are using) inside the "obj" folder of your project and then try to build it again. It usually works for me.</p>


问:
text overflow: ellipsis inside flexible height div inside a div with a limited height
I have a div with a fixed size that contains a floated image, a title and a description. My issue is that the desc div does not stay within the boundaries of its parent when a lot of text is added to it. What I'd like to have is the text being cut off by an ellipsis when it reaches the bottom of the div. I have no control over the length of the content in the name and desc divs, so I can't impose a height on them. This seems very trivial, but I can't figure out where I'm going wrong. JSFiddle

For the sake of clarity, I mean that I want my result to look something like this:

```<code>{{name}}
{{desc.}} Lorem ipsum dolor
sit amet, consectetur adipisi
cing elit, sed do eiusmod tem
por incididunt ut labore et...
</code>```

Edit: It turns out that this problem is a lot more involved than I expected. The issue doesn't have anything to do with div boundaries, but rather that multi-line ellipsis endings are not a trivial thing to accomplish.

HTML

```<code><div id="data" class="clearfix">
 <img id="icon" src="{{imgurl}}">
 <div id="text">
    <div id="name">{{name}}</div>
    <div id="desc">{{desc}}</div>
 </div>
</div>
</code>```

CSS

```<code>#data {
 background-color:red;
 width:300px;
 position: absolute;
 margin: 23px 44px;
 height: 100px;
 padding: 10px 10px;
 color: #fff;
 text-overflow: ellipsis;
}
#icon {
 background-color: grey;
 width: 80px;
 height: 80px;
 float: left;
 margin-right: 10px;
}
#text {
 float: right;
 width: 200px;
 height: 100%;
 overflow: hidden;
 text-overflow: ellipsis;
}
#name {
 font-size: 18px;
 font-weight: bold;
 line-height: 1.5em;
}
#desc {
 font-size: 13px;
 line-height: 1.1em;
 text-overflow: ellipsis;
}
</code>```

Live Example on JSFiddle

答:
This is a great solution to your problem of multiple lines ellipsis found on codepen:
Pure CSS multiline text with ellipsis</p>

```<code>$font-size: 26px;
$line-height: 1.4;
$lines-to-show: 3;

h2 {
  display: block; /* Fallback for non-webkit */
  display: -webkit-box;
  max-width: 400px;
  height: $font-size*$line-height*$lines-to-show; /* Fallback for non-webkit */
  margin: 0 auto;
  font-size: $font-size;
  line-height: $line-height;
  -webkit-line-clamp: $lines-to-show;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
 }
</code>```

Body:
I have a div with a fixed size that contains a floated image, a title and a description. My issue is that the desc div does not stay within the boundaries of its parent when a lot of text is added to it. What I'd like to have is the text being cut off by an ellipsis when it reaches the bottom of the div. I have no control over the length of the content in the name and desc divs, so I can't impose a height on them. This seems very trivial, but I can't figure out where I'm going wrong. JSFiddle

For the sake of clarity, I mean that I want my result to look something like this:

{{name}}
{{desc.}} Lorem ipsum dolor
sit amet, consectetur adipisi
cing elit, sed do eiusmod tem
por incididunt ut labore et...

Edit: It turns out that this problem is a lot more involved than I expected. The issue doesn't have anything to do with div boundaries, but rather that multi-line ellipsis endings are not a trivial thing to accomplish.

HTML

{{name}}

{{desc}}

CSS

#data {
 background-color:red;
 width:300px;
 position: absolute;
 margin: 23px 44px;
 height: 100px;
 padding: 10px 10px;
 color: #fff;
 text-overflow: ellipsis;
}
#icon {
 background-color: grey;
 width: 80px;
 height: 80px;
 float: left;
 margin-right: 10px;
}
#text {
 float: right;
 width: 200px;
 height: 100%;
 overflow: hidden;
 text-overflow: ellipsis;
}
#name {
 font-size: 18px;
 font-weight: bold;
 line-height: 1.5em;
}
#desc {
 font-size: 13px;
 line-height: 1.1em;
 text-overflow: ellipsis;
}

Live Example on JSFiddle

Body:
This is a great solution to your problem of multiple lines ellipsis found on codepen:
Pure CSS multiline text with ellipsis

$font-size: 26px;
$line-height: 1.4;
$lines-to-show: 3;

h2 {
  display: block; /* Fallback for non-webkit */
  display: -webkit-box;
  max-width: 400px;
  height: $font-size*$line-height*$lines-to-show; /* Fallback for non-webkit */
  margin: 0 auto;
  font-size: $font-size;
  line-height: $line-height;
  -webkit-line-clamp: $lines-to-show;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
 }


问:
Why overloaded methods defined in OOPS?
Interviewer had asked me what is method overloading and I had given answer saying, method overloading is within same class where two or more methods have same name but different signature, with following example -

```<code>//method with two parameters
public int add(int a, int b){
  return a + b;
}

//method with three parameters
public int add(int a, int b, int c){
  return a + b + c;
}
</code>```

To this example, he said why do we need two methods with same name i.e. add. Instead we can have two methods with different names i.e. addTwoNumbers and addThreeNumbers which indicates, method names are more verbose and if we follow this approach, we don't need method overloading. (And same is true for other Java apis where method overloading is used.)

Considering his above thought, he asked why OOPS principle still have method overloading and why is being used so intensively? What is intention of inventors to introduce concept of method overloading?

答:
The main reason behind this is the cleanliness of the code.
For example let's take print method in java. It is an overloaded function since it can have different arguements but with same name.

```<code>System.out.print(Boolean b),System.out.print(Integer b),System.out.print(String b),System.out.print(Float b)
</code>```

etc etc. But all we know is that there is a print method and we have to pass whatever we need to print. Had there not been overloading then the names of the function would look like

```<code> System.out.printBoolean(Boolean b),System.out.printInteger(Integer b),System.out.printString(String b),System.out.printFloat(Float b)
</code>```

which not only makes the code complex but also hard to remember which function to call when. Overloading is used when the ultimate goal is same but the path or objects used may be different. In this case our ultimate goal was to print whether it be an integer or string etc.

Title: Why overloaded methods defined in OOPS?

Body:
Interviewer had asked me what is method overloading and I had given answer saying, method overloading is within same class where two or more methods have same name but different signature, with following example -

//method with two parameters
public int add(int a, int b){
  return a + b;
}

//method with three parameters
public int add(int a, int b, int c){
  return a + b + c;
}

To this example, he said why do we need two methods with same name i.e. add. Instead we can have two methods with different names i.e. addTwoNumbers and addThreeNumbers which indicates, method names are more verbose and if we follow this approach, we don't need method overloading. (And same is true for other Java apis where method overloading is used.)

Considering his above thought, he asked why OOPS principle still have method overloading and why is being used so intensively? What is intention of inventors to introduce concept of method overloading?

Body:
The main reason behind this is the cleanliness of the code.
For example let's take print method in java. It is an overloaded function since it can have different arguements but with same name.

System.out.print(Boolean b),System.out.print(Integer b),System.out.print(String b),System.out.print(Float b)

etc etc. But all we know is that there is a print method and we have to pass whatever we need to print. Had there not been overloading then the names of the function would look like

 System.out.printBoolean(Boolean b),System.out.printInteger(Integer b),System.out.printString(String b),System.out.printFloat(Float b)

which not only makes the code complex but also hard to remember which function to call when. Overloading is used when the ultimate goal is same but the path or objects used may be different. In this case our ultimate goal was to print whether it be an integer or string etc.


问:
What exactly Java EE6 and do I have choice not to include some of features?
When I looked into Java EE6 doc and some other articles, Java EE6 is a platform.

To me, platform is just Java with bunch of API/framework available like JSF, JPA, Web services  like REST. (more like bunch of jars maybe?)

So anyway I got Netbean6.9/Java EE6/GlassFish v3 bundle but figured I don't need JSF at all.

Is there a way to remove JSF from Java EE6 so that I can save some disc space on my server?

Sorry if my statement doesn't make sense because I'm not fully understand what exactly Java EE6 by reading documentation.. (or this JSF is bundled with Netbean6.9...)

Update:

I'm building REST web app so far using JAX-RS and JPA (toplink essential) and for UI side, JSF was going to be used but we decided not to, so wondering if things that won't get used can be removed. (after reading comments I think removing JSF is not good idea though)

答:
Java EE is a set of interfaces/annotations/etc for performing tons of different kinds of tasks commonly needed when building, well, 'Enterprise' applications.  (the definition of which is its own multipage thread.)  Glassfish is includes an implementation for each of the different APIs that make up JavaEE.  Basically, when you use Glassfish, you can just go ahead and use anything in a 'javax ' package and it will be there for you, working.  (although sometimes not the most performant or scalable implementation available...)

There are several options for java web containers that don't include implementations of the entire J2EE API built in.  Tomcat and Jetty are probably the two most popular and widely used.  Tomcat installs and integrates right into netbeans very well.  But if you find yourself wanting to use something in most javax packages, you will need to provide an implementation, include the jar files yourself, etc.

--

Also, as an aside, the very, very nice Glassfish administration console (which is to me the chief motivator for using Glassfish) is done in JSF, so no, you can't really remove it :)


问:
Navbar growing wider than bootstrap column width
I am trying to position navbar fixed to the left-hand side of the screen effectively in a sidebar with the rest of the page content rendering to the right.

Currently, I have tried to split the page into two using bootstrap columns like so:

html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}

/********************************************
*                                           *
*                                           *
*               WRAPPERS                    *
*                                           *
*                                           *
********************************************/

#sidebarWrapper {
  height: 100%;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
  background-color: red;
  overflow-x: hidden;
  overflow-y: auto;
  transition: all 0.5s ease;
}

/********************************************
*                                           *
*                                           *
*             SIDEBAR NAV STYLE             *
*                                           *
*                                           *
********************************************/

.sidebar-nav {
  margin: 0;
  padding: 0;
  top: 0;
  list-style: none;
  position: absolute;
}

.sidebar-nav>li {
  display: inline-block;
  line-height: 20px;
  position: relative;
  width: 100%;
}

/********************************************
*                                           *
*                                           *
*                  DIV STYLE                *
*                                           *
*                                           *
********************************************/

.container-fluid {
  height: 100%;
}

.container-fluid h1 {
  padding: 0;
  margin: 0;
}

/********************************************
*                                           *
*                                           *
*              PAGE BODY STYLE              *
*                                           *
*                                           *
********************************************/

.header {
  height: 10%;
  background-color: yellow;
}

.contentBody {
  height: 80%;
  background-color: green;
}

.footer {
  height: 10%;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="row">
    <div class="col-lg-2">
      <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation" id="sidebarWrapper">
        <ul class="nav sidebar-nav">
          <li>
            Dashboard
          </li>
        </ul>
      </nav>
    </div>
    <div class="col-lg-10">
      <div class="header">
        <h1>Header</h1>
      </div>
      <div class="contentBody">
        <h1>Content</h1>
      </div>
      <div class="footer">
        <h1>Footer</h1>
      </div>
    </div>
  </div>
</div></code>```

However, as you can see from the snippet my navbar seems to brute force over any bootstrap column restrictions and takes the width of the whole page.

How can I prevent it from doing so, so that it takes 100% of the width of the bootstrap column but no more and no less?

答:
Because the navbar has fixed position it no longer has an inherent width (the only reason it has any width at all in your demo is due to a right:0; declaration in .navbar-fixed-top).

If you want the navbar's width to match the column width then you will need to set an explicit width on it. It can be a pixel unit or percentage, but keep in mind that a percentage is relative to the width of the viewport. This is because fixed position elements are taken out of the document flow, so their dimensions are calculated relative to the viewport, rather than their parent element.

In your demo the column width you are trying to match is defined as a 16.66666667% (when the viewport is wider than 1200px), so if you set the navbar to the same width then they should match.

Note: Bootstrap may have native methods for defining the dimensions of a fixed position navbar/element. I am not intimately familiar with Bootstrap so I am answering from a general CSS standpoint.

Body:
I am trying to position navbar fixed to the left-hand side of the screen effectively in a sidebar with the rest of the page content rendering to the right.

Currently, I have tried to split the page into two using bootstrap columns like so:

html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}

/********************************************
*                                           *
*                                           *
*               WRAPPERS                    *
*                                           *
*                                           *
********************************************/

#sidebarWrapper {
  height: 100%;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
  background-color: red;
  overflow-x: hidden;
  overflow-y: auto;
  transition: all 0.5s ease;
}

/********************************************
*                                           *
*                                           *
*             SIDEBAR NAV STYLE             *
*                                           *
*                                           *
********************************************/

.sidebar-nav {
  margin: 0;
  padding: 0;
  top: 0;
  list-style: none;
  position: absolute;
}

.sidebar-nav>li {
  display: inline-block;
  line-height: 20px;
  position: relative;
  width: 100%;
}

/********************************************
*                                           *
*                                           *
*                  DIV STYLE                *
*                                           *
*                                           *
********************************************/

.container-fluid {
  height: 100%;
}

.container-fluid h1 {
  padding: 0;
  margin: 0;
}

/********************************************
*                                           *
*                                           *
*              PAGE BODY STYLE              *
*                                           *
*                                           *
********************************************/

.header {
  height: 10%;
  background-color: yellow;
}

.contentBody {
  height: 80%;
  background-color: green;
}

.footer {
  height: 10%;
  background-color: blue;
}

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

            Dashboard

Header

Content

Footer

However, as you can see from the snippet my navbar seems to brute force over any bootstrap column restrictions and takes the width of the whole page.

How can I prevent it from doing so, so that it takes 100% of the width of the bootstrap column but no more and no less?


问:
Uncaught TypeError:Cannot read property 'top' of undefined
I am getting this error.</p>

```<code>$.fn.scroller = function(targetid){
this.on('click', function(event) {

            var target = $("#" + this.getAttribute('data-scroll'));

         $('html, body').animate({scrollTop: target.offset().top}, 1000);
    });
    return this;};
</code>```

答:
The only reason offset returns undefined is if you call it on a jQuery set that's empty. So apparently, $("#" + this.getAttribute('data-scroll')) returned an empty set.

You'll want to add a guard. In fact, I'd probably add two:

```<code>$.fn.scroller = function(targetid) {
    this.on('click', function(event) {
        var id = this.getAttribute('data-scroll') || ""; // ***
        if (id) {                                        // ***
            var target = $("#" + id);
            if (target[0]) {                             // ***
                $('html, body').animate({
                    scrollTop: target.offset().top
                }, 1000);
            }                                            // ***
        }
    });
    return this;
};
</code>```

or more concisely and efficiently:

```<code>$.fn.scroller = function(targetid) {
    this.on('click', function(event) {
        var id = this.getAttribute('data-scroll');
        var target = id && document.getElementById(id);
        if (target) {
            $('html, body').animate({
                scrollTop: $(target).offset().top
            }, 1000);
        }
    });
    return this;
};
</code>```

Body:
I am getting this error.

$.fn.scroller = function(targetid){
this.on('click', function(event) {

            var target = $("#" + this.getAttribute('data-scroll'));

         $('html, body').animate({scrollTop: target.offset().top}, 1000);
    });
    return this;};

Body:
The only reason offset returns undefined is if you call it on a jQuery set that's empty. So apparently, $("#" + this.getAttribute('data-scroll')) returned an empty set.

You'll want to add a guard. In fact, I'd probably add two:

$.fn.scroller = function(targetid) {
    this.on('click', function(event) {
        var id = this.getAttribute('data-scroll') || ""; // ***
        if (id) {                                        // ***
            var target = $("#" + id);
            if (target[0]) {                             // ***
                $('html, body').animate({
                    scrollTop: target.offset().top
                }, 1000);
            }                                            // ***
        }
    });
    return this;
};

or more concisely and efficiently:

$.fn.scroller = function(targetid) {
    this.on('click', function(event) {
        var id = this.getAttribute('data-scroll');
        var target = id && document.getElementById(id);
        if (target) {
            $('html, body').animate({
                scrollTop: $(target).offset().top
            }, 1000);
        }
    });
    return this;
};


答: give margin-top in minus so it will move upside


问:
ExtJS open window with max height
I am trying to open a window (Ext.Window) by clicking on a button (Ext.Button). The problem is that this window must have size 80% width and 100% height of the screen of the user, that is it should cover all the vertical space.

I am really not able to create a working example. The button I use is hiding/showing this window, which always has wrong size..

Can anyone help me?

Thanks

答:
You are looking for Ext.getBody().getViewSize(). More Specifically, Ext.getBody().getViewSize().height and Ext.getBody().getViewSize().width

This should work in your button's handler -

```<code>new Ext.Window({
    title:'Hello World Window',
    html:'Am I the right size?',
    height:Ext.getBody().getViewSize().height,
    width:Ext.getBody().getViewSize().width*0.8 //80%
}).show();
</code>```

Title: ExtJS open window with max height

Body:
You are looking for Ext.getBody().getViewSize(). More Specifically, Ext.getBody().getViewSize().height and Ext.getBody().getViewSize().width

This should work in your button's handler -

new Ext.Window({
    title:'Hello World Window',
    html:'Am I the right size?',
    height:Ext.getBody().getViewSize().height,
    width:Ext.getBody().getViewSize().width*0.8 //80%
}).show();


问:
Java Spring SQL how to combine/join 3 tables into one
I have 3 tables that I want to combine/join into one, I have tried different methods like join, left/right join but somehow i lose myself in the amount of statements i write so i cant get it to work properly.

I want to map the name in measurement to measurement_id in measurement_data_points and then map data_points_id in measurement_data_points to id in measurement_point

I have included a made-up result that i would like at the bottom to give a clear understanding.

My Tables:

```<code>+-------------------------+
| Tables_in_db_datapoints |
+-------------------------+
| measurement             |
| measurement_data_points |
| measurement_point       |
+-------------------------+
</code>```

measurement table

```<code>mysql> select * from measurement;
+----+----------------------+
| id | name                 |
+----+----------------------+
|  1 | identifiedNeed       |
|  2 | identifiedBackground |
|  3 | identifiedGoal       |
+----+----------------------+
</code>```

measurement_data_points table

```<code>mysql> select * from measurement_data_points;
+----------------+----------------+
| measurement_id | data_points_id |
+----------------+----------------+
|              1 |              1 |
|              1 |              2 |
|              1 |              3 |
|              1 |              4 |
|              2 |              5 |
|              2 |              6 |
|              2 |              7 |
|              2 |              8 |
|              3 |              9 |
|              3 |             10 |
|              3 |             11 |
|              3 |             12 |
+----------------+----------------+
</code>```

measurement_point table

```<code>+----+------------+-----+----------+--------+
| id | date       | f1  | precison | recall |
+----+------------+-----+----------+--------+
|  1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
|  2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
|  3 | 2017-11-15 | 0.5 |      0.3 |    0.1 |
|  4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
|  5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
|  6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|  7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
|  8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
|  9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
| 10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| 11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
| 12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+----+------------+-----+----------+--------+
</code>```

I want the result to mainly be like this:

```<code>+-----------------------+----------------+------------+-----+----------+
| measurement_id        | data_points_id |  date      | f1  | precison | recall |
+-----------------------+----------------+------------+-----+----------+
| identifiedNeed        |              1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
| identifiedNeed        |              2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
| identifiedNeed        |              3 | 2017-11-15 | 0.5 |      0.3 |    0.1
| identifiedNeed        |              4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
| identifiedBackground  |              5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
| identifiedBackground  |              6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| identifiedBackground  |              7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
| identifiedBackground  |              8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
| identifiedGoal        |              9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
| identifiedGoal        |             10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| identifiedGoal        |             11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
| identifiedGoal        |             12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+-----------------------+----------------+------------+-----+----------+
</code>```

If that doesnt work then this works as well

```<code>+----------------+----------------+------------+-----+----------+--------+
| measurement_id | data_points_id | date       | f1  | precison | recall |
+----------------+----------------+------------+-----+----------+--------+
|              1 |              1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
|              1 |              2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
|              1 |              3 | 2017-11-15 | 0.5 |      0.3 |    0.1 |
|              1 |              4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
|              2 |              5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
|              2 |              6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|              2 |              7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
|              2 |              8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
|              3 |              9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
|              3 |             10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|              3 |             11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
|              3 |             12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+----------------+----------------+------------+-----+----------+--------+
</code>```

答:
Try the following:</p>

```<code>select M.Name, data_points_id, date, f1 ,precision , recall
from measurement M
Inner join measurement_data_points md on m.id=md.measurement_id
inner join measurement_point mp on mp.id=md.data_points_id
</code>```

Body:
I have 3 tables that I want to combine/join into one, I have tried different methods like join, left/right join but somehow i lose myself in the amount of statements i write so i cant get it to work properly.

I want to map the name in measurement to measurement_id in measurement_data_points and then map data_points_id in measurement_data_points to id in measurement_point

I have included a made-up result that i would like at the bottom to give a clear understanding.

My Tables:

+-------------------------+
| Tables_in_db_datapoints |
+-------------------------+
| measurement             |
| measurement_data_points |
| measurement_point       |
+-------------------------+

measurement table

mysql> select * from measurement;
+----+----------------------+
| id | name                 |
+----+----------------------+
|  1 | identifiedNeed       |
|  2 | identifiedBackground |
|  3 | identifiedGoal       |
+----+----------------------+

measurement_data_points table

mysql> select * from measurement_data_points;
+----------------+----------------+
| measurement_id | data_points_id |
+----------------+----------------+
|              1 |              1 |
|              1 |              2 |
|              1 |              3 |
|              1 |              4 |
|              2 |              5 |
|              2 |              6 |
|              2 |              7 |
|              2 |              8 |
|              3 |              9 |
|              3 |             10 |
|              3 |             11 |
|              3 |             12 |
+----------------+----------------+

measurement_point table

+----+------------+-----+----------+--------+
| id | date       | f1  | precison | recall |
+----+------------+-----+----------+--------+
|  1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
|  2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
|  3 | 2017-11-15 | 0.5 |      0.3 |    0.1 |
|  4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
|  5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
|  6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|  7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
|  8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
|  9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
| 10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| 11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
| 12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+----+------------+-----+----------+--------+

I want the result to mainly be like this:

+-----------------------+----------------+------------+-----+----------+
| measurement_id        | data_points_id |  date      | f1  | precison | recall |
+-----------------------+----------------+------------+-----+----------+
| identifiedNeed        |              1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
| identifiedNeed        |              2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
| identifiedNeed        |              3 | 2017-11-15 | 0.5 |      0.3 |    0.1
| identifiedNeed        |              4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
| identifiedBackground  |              5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
| identifiedBackground  |              6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| identifiedBackground  |              7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
| identifiedBackground  |              8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
| identifiedGoal        |              9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
| identifiedGoal        |             10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| identifiedGoal        |             11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
| identifiedGoal        |             12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+-----------------------+----------------+------------+-----+----------+

If that doesnt work then this works as well

+----------------+----------------+------------+-----+----------+--------+
| measurement_id | data_points_id | date       | f1  | precison | recall |
+----------------+----------------+------------+-----+----------+--------+
|              1 |              1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
|              1 |              2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
|              1 |              3 | 2017-11-15 | 0.5 |      0.3 |    0.1 |
|              1 |              4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
|              2 |              5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
|              2 |              6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|              2 |              7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
|              2 |              8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
|              3 |              9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
|              3 |             10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|              3 |             11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
|              3 |             12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+----------------+----------------+------------+-----+----------+--------+

Body:
Try the following:

select M.Name, data_points_id, date, f1 ,precision , recall
from measurement M
Inner join measurement_data_points md on m.id=md.measurement_id
inner join measurement_point mp on mp.id=md.data_points_id


答:
Try to use subquery and join with it

```<code>SELECT d.*
FROM datasource d
JOIN
  (
    SELECT [date],MAX(Creation_date) LastCreationDate
    FROM datasource
    GROUP BY [date]
  ) l
ON d.[date]=l.[date] AND d.Creation_date=l.LastCreationDate
</code>```

Or the second variant if Creation_date is common for all the [date]

```<code>SELECT *
FROM datasource
WHERE Creation_date=(SELECT MAX(Creation_date) FROM datasource)
</code>```

Title: Specific group by latest date in SQL Server

Body:
I want to run a SQL query on the following set of data

date       creation_date    value
------------------------------------
2018-01-01 2017-05-05       1
2018-01-02 2017-05-05       0
2018-01-03 2017-05-05       1
2018-01-04 2017-05-05       0
2018-01-05 2017-05-05       1
2018-01-06 2017-05-05       1
2018-01-02 2017-05-11       5

I want to get the following results

2018-01-01 2017-05-05       1
2018-01-02 2017-05-11       5
2018-01-03 2017-05-05       1
2018-01-04 2017-05-05       0
2018-01-05 2017-05-05       1
2018-01-06 2017-05-05       1

Basically I want to get all the dates, group it by dates and get the latest creation date and get the value for that creation date.

I tried

select date, max(Creation_date), value
from datasource
group by date, blocked

but that doesn't do it.

Body:
Try to use subquery and join with it

SELECT d.*
FROM datasource d
JOIN
  (
    SELECT [date],MAX(Creation_date) LastCreationDate
    FROM datasource
    GROUP BY [date]
  ) l
ON d.[date]=l.[date] AND d.Creation_date=l.LastCreationDate

Or the second variant if Creation_date is common for all the [date]

SELECT *
FROM datasource
WHERE Creation_date=(SELECT MAX(Creation_date) FROM datasource)


问:
how to receive push notification when app is turned off?
I am implementing a push notification functionality for my app and everything is running smoothly except for one case.

The situation is this:
When the app is off (not running in background either) and the user receives a push notification. The user hits "Close" and then later on decides to go to the app. I would like my app delegate to know the push notification that was received earlier however, I don't know how to check that. I know that I can have a function call in my didLaunch... but that works when the user decides to hit the "View" button instead of "Close".

Any hints?

Thanks!

答: Really, the answer is don't bother. You can never guarantee that the alert was received, so unfortunately you'll run into problems later if you rely on this. apns doesn't guarantee a device will receive a payload.</p>


问:
angular 4 - regular expression limit - show user to number of character left
I want to display message to user that to how many characters are left while typing. The regular expression is sending from server and here are some regular expression examples which are sending from server.

^[a-zA-Z0-9_\-. ()]{1,25}$

^(void|[0-9]{0,20})$

once user started typing i want to show message with "Number of character is left {{count}}" and once limit(max length from regx) is reached it should not allow user to enter any character in input. I try with this regx to find out limit in regx (/\^[(.*)]{([0-9]+),([0-9]+)}\$/i) and match it with the string but this pattern is not working with all regx..

How i Can achieve this?

Thanks

答:
Here is your solution

Get regular expression from server

Find maximum length you need to restrict user to

Use input element .length property to get length of current user input and then show it to user

If it is less than maximum length it is fine if not then remove last n characters where n is length-max characters from input string

You dont need to match it with regex to restrict a string's length as pointed out in many comments. Keep it simple so you can understand and maintain it later as well.


问:
Angular 4 Component is rendered as empty
I am new to Angular, I am trying to define a component and use it in my main page.

The thing is that when using the component in index.html all I can see is my <custom-component></custom-component> empty, nothing inside it.

So what I did is:

in Angular cli: ng generate component custom.

in custom.component.html I have just a text inside paragraph tag.

in index.html I inserted the selector found in custom.component.ts (app-custom) as tag.

in app.module.ts I imported the custom component.

ng serve outputs only app-custom tag without the paragraph tag that should be inside it.

What did I miss?

Update:
Code of my component:

custom.component.html

```<code><p>
 component works!
</p>
</code>```

custom.component.ts

```<code>import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.css']
})
export class CustomComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}
</code>```

index.html

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>TestApp</title>
  <base href="/">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-custom></app-custom>
</body>
</html>
</code>```

app.module.ts:

```<code>import { CustomComponent } from './custom/custom.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { FlexLayoutModule } from '@angular/flex-layout';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    CustomComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
     BrowserAnimationsModule,
    FlexLayoutModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答: Try to add exports after declarations => [AppComponent, CustomComponent] ? in app.module. Or create a new cli project with the last version</p>

Body:
I am new to Angular, I am trying to define a component and use it in my main page.

The thing is that when using the component in index.html all I can see is my <custom-component></custom-component> empty, nothing inside it.

So what I did is:

in Angular cli: ng generate component custom.

in custom.component.html I have just a text inside paragraph tag.

in index.html I inserted the selector found in custom.component.ts (app-custom) as tag.

in app.module.ts I imported the custom component.

ng serve outputs only app-custom tag without the paragraph tag that should be inside it.

What did I miss?

Update:
Code of my component:

custom.component.html

 component works!

custom.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.css']
})
export class CustomComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

index.html

<!doctype html>

  <meta charset="utf-8">
  <title>TestApp</title>
  <base href="/">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-custom></app-custom>

app.module.ts:

import { CustomComponent } from './custom/custom.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { FlexLayoutModule } from '@angular/flex-layout';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    CustomComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
     BrowserAnimationsModule,
    FlexLayoutModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
Why is the OpenLDAP for windows installer asking for a Serial Number?
I downloaded OpenLDAP for Windows (2.4.43 x86) from SourceForge and the installer is asking for a Serial Number:

As far as I can find there is no such thing?

I tried entering anything but the next button will not allow me to progress

答:
This question is very old, but in case anyone else gets to this page, the answer is quite simple. Read the instructions :-)

Enter an organisation name

Take a screen shot

Email it to the address specified (currently info@matear.eu - but use the address that it tells you)

Clicking the "back" button on the OP's dialogue would reveal what needs to be done:


问:
How to get DD-MM-YYYY format date
I'm using Parse database. I store date format. when using console i get this format :  Tue Jul 18 2017 15:46:47 GMT+0100 (CET)
 I want to get this format : 18-07-2017.
Any idea please

答:
I have been able to get the result that you want in react-native like this:

import moment from 'moment'; // Import momentjs -->
https://momentjs.com

const maxDate = moment(new Date, 'DD-MM-YYYY').format(); //
15-11-2017T11:17:30+01:00

I hope this is useful for you.

Title: How to get DD-MM-YYYY format date


问:
Can I run multiple TCP Listeners sharing a single port but different URIs
Is it possible to run multiple instances of a TCP Listener on the same port but with different listener URIs? E.g.

```<code>tcp://localhost:555/MyService1
tcp://localhost:555/MyService2
</code>```

Context is Windows and .NET

答:
TCP is a low level protocol - it's just streams of bytes flowing in both directions, with the connection uniquely identified by the 4-tuple of (client IP address, client port, server IP address, server port).

If you want more than this, such as these high-falutin URIs that you speak of, it's up to you to a) switch to an existing higher level protocol that uses URIs and layers itself above TCP (e.g. HTTP), or b) for you to construct a higher level protocol that knows of URIs and layers itself above TCP.

In either (a) or (b) case though, at the TCP level, there's still only one listener.

Body:
Is it possible to run multiple instances of a TCP Listener on the same port but with different listener URIs? E.g.

tcp://localhost:555/MyService1
tcp://localhost:555/MyService2

Context is Windows and .NET


问:
Apache CLI: Required options contradicts with help option.
If I have 2 options defined as required such as:

```<code> public static void main(String [] args){
      Options options= new Options();
      Option  inputFileOp=Option.builder("i").longOpt("input").hasArg().desc("Input file").argName("file").required().build();
        options.addOption(inputFileOp);

      Option outputFileOp=Option.builder("o").longOpt("output").hasArg().desc("Output file").argName("file").required().build();
        options.addOption(outputFileOp);
</code>```

and a help option

```<code>    Option helpOp =new Option("h",false,"Show Help");
    helpOp.setLongOpt("help");
    helpOptions.addOption(helpOp);
</code>```

and parser

```<code>DefaultParser parser = new DefaultParser();
CommandLine cmd=parser.parse(options,args);

if(cmd.hasOption(helpOp.getOpt())){
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp( "MyApp.sh", options );
        System.exit(0);
    }

}
</code>```

When the user input for example myApp -h .. An exception is raised in the parsing step  that there are missing required options, While I want to print the help data.

How to allow calling the help while keeping these options declared as required?

答:
Add another method, as the previous poster said, but make sure you stop at the first unrecognized argument.

```<code>private static boolean hasHelp(final Option help, final String[] args) throws ParseException
{
    Options options = new Options();
    options.addOption(help);
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);
    return cmd.hasOption(help.getOpt());
}
</code>```

If stopAtNonOption is set to false, then this function would throw for valid arguments, like java -jar app.jar -doStuff

Body:
If I have 2 options defined as required such as:

 public static void main(String [] args){
      Options options= new Options();
      Option  inputFileOp=Option.builder("i").longOpt("input").hasArg().desc("Input file").argName("file").required().build();
        options.addOption(inputFileOp);

      Option outputFileOp=Option.builder("o").longOpt("output").hasArg().desc("Output file").argName("file").required().build();
        options.addOption(outputFileOp);

and a help option

    Option helpOp =new Option("h",false,"Show Help");
    helpOp.setLongOpt("help");
    helpOptions.addOption(helpOp);

and parser

DefaultParser parser = new DefaultParser();
CommandLine cmd=parser.parse(options,args);

if(cmd.hasOption(helpOp.getOpt())){
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp( "MyApp.sh", options );
        System.exit(0);
    }

}

When the user input for example myApp -h .. An exception is raised in the parsing step  that there are missing required options, While I want to print the help data.

How to allow calling the help while keeping these options declared as required?

Body:
Add another method, as the previous poster said, but make sure you stop at the first unrecognized argument.

private static boolean hasHelp(final Option help, final String[] args) throws ParseException
{
    Options options = new Options();
    options.addOption(help);
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);
    return cmd.hasOption(help.getOpt());
}

If stopAtNonOption is set to false, then this function would throw for valid arguments, like java -jar app.jar -doStuff