text:
Q: Angular nested object I'm trying to display an object attribute nested in another object. Each employee has a category. I manage to display employees attributes but not the category.name
thanks for your help
here is the code:
model:
export interface Category{
id : number;
name: string;
    }

import {Category} from "./Category";

export interface Employee {
  id: number;
  name: string;
  email: string;
  jobTitle: string;
  phone: string;
  imageUrl: string;
  employeeCode: string;
  active: boolean;
  category : Category;
}

service:
  public getEmployees(): Observable<Employee[]> {
    return this.http.get<Employee[]>(`${this.apiServerUrl}/employee/all`);
  }

app.ts
public getEmployees(): void {
    this.employeeService.getEmployees().subscribe(
      (response: Employee[]) => {
        this.employees = response;
        console.log(this.employees);
      },
      (error: HttpErrorResponse) => {
        alert(error.message);
      }
    );
  }}

html, error coming from {{employee?.category.name}}

{{employee?.email}}

Phone : {{employee?.phone}}

Active : {{employee?.active}}

Category : {{employee?.category.name}}

JSON example of one object data that it received from backend:
 {"id":1,
"name":"ericparis",
"email":"xxxxxx.x@gmail.com",
"jobTitle":"BA",
"phone":"06xxxxxxxx",
"imageUrl":"https://bootdey.com/img/Content/avatar/avatar1.png",
"active":true,
"category":{"id":1,"name":"cadre"}}

A: it sounds like one or several of the objects doesn't have a category. in this case this piece of code would fix that
{{employee?.category?.name}}


text:
Q: ST3: Find text results in panel instead of a buffer I must have hit a setting in ST3 and caused my program to display results in a panel instead of in a buffer. How do I get it back so that find-text results go into their own tab? I've done some digging around but I can't find what I did.

A: In the Find in Files panel, there is a series of buttons to the left of the Find field, and the right most one of those is the one that controls whether the find results show up in a panel or in a buffer.
Note that the button may look different in your version as it appears that you're using a different theme (the image below shows the default theme). You can verify that you have the correct button based on the tool tip text.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamics CRM: Is there a way to impersonate OrganizationData service? I have some legacy code which for now I want to reuse in rewritten application. This code was used in silverlight, where user credential where available, but now it is supposed to run on server, so I need to impersonate it. Unfortunately, the code uses CRM OrganizationData service (https://crm/OnBoarding/XRMServices/2011/OrganizationData.svc/) and I cannot find any way to turn impersonation on.
Is there a way to do it? I would like to avoid using NTLM.

A: After connecting the CrmServiceClient with System Administrator credentials you are able to set the CallerId property to impersonate the user.
CallerId would be the SystemUserId on SystemUser.


text:
Q: Proof with valuations in Liu's book I have a question about a claim I found in Liu's book Algebraic Geometry and Arithmetic Curves in the Proof of Theorem 8.3.26 (b) page 356:

In (b) uses the notation of a "center". This can be looked up on previous pages:
By a center $x \in X$ of valaution $\nu$ of $K(X)$ Liu means the existence of a morphism $\operatorname{Spec} \ O_{\nu} \to \operatorname{Spec} \ O_{X,x}$ extending canonical inclusion of generic point $Spec \ K(X) \to X$. $O_{\nu}$ is the DVR with maximal ideal $m_{\nu}$ induced by $\nu$.
Also, the proof uses following assertion which we consider as black box:

($\alpha$) There exists a blowing-up morphism $X' \to X$ such that the center $x'$
  of $\nu$ in $X'$ verifies $\operatorname{trdeg}_{k(x)} k(x') ≥ n$.

The relevant part I not understand is:

Let $Y \to X'$ be the normalization. This is a finite
  morphism because $X'$ is Nagata (Proposition 2.29(b); we can also accept it as black box). Hence $\nu$ admits a center
  $y \in Y$ which is a point lying above $x'$.

QUESTION: Why finiteness of $Y \to X'$ allows to lift the center $x'$ with respect to $\nu$ to $Y$?
I think the problem can be translated to commutative algebra as follows:
The center is: if $\nu$ is a non-trivial
valuation of $K(X)$ and has $x \in X$ center, this means simply that $O_{\nu}$ dominates $O_{X,x}$, i.e. we have  $O_{X,x} \subset O_{\nu}$ and $m_x \subset m_{\nu}$ for unique maximal ideals (equivalently: $m_{\nu} \cap O_{X,x}=m_x$.
Assume $\nu$ has center in $x' \in X'$, that is $O_{x',X'} \subset O_{\nu}$ and $O_{\nu}$ dominates $O_{x',X'} $. Let $y_1,...,y_m$ the primages of $x'$ with respect the normalization map. By Nagata argument the normalization map was finite and thus we have finitely many preimages.
futhermore for every $y_i$ the induced maps between local rings $O_{X',x'} \to O_{Y,y_i}$ are finite.
That is the question is why there exist a $y_i$ such that $O_{x',X'} \subset O_{\nu}$ extends to $O_{y_i,Y} \subset O_{\nu}$?


text:
Q: Can't run a timer in GCD block with a dispatch_source_t in iOS application I want to create a timer in GCD block ( which will fire once every 2 seconds and call a method ) to use it as a background task. But as i see timer fires never. Here is my code:
- (void)startMessaging
{
    BOOL queue = YES;
    dispatch_queue_t _queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, _queue);
    dispatch_source_set_timer(timerSource, dispatch_walltime(NULL, 0), 2ull * NSEC_PER_SEC,1ull * NSEC_PER_SEC );
    dispatch_source_set_event_handler(timerSource, ^{
        if (queue) {
            [self observeNewMsgs];
        }
    });
    dispatch_resume(timerSource);
}

- (void)observeNewMsgs
{
    NSLog(@"JUST TO TEST");
    // Staff code...
}

So what's a problem with this? How can I fix this?

A: You have to make your dispatch_source_t a class property or instance variable, so it doesn't fall out of scope (because in ARC, when it falls out of scope, it is released). If you do that, your code will work fine, e.g.:
@interface ViewController ()
@property (nonatomic, strong) dispatch_source_t timerSource;
@property (getter = isObservingMessages) BOOL observingMessages;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self startMessaging];
}

- (void)startMessaging
{
    self.observingMessages = YES;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(self.timerSource, dispatch_walltime(NULL, 0), 2ull * NSEC_PER_SEC, 1ull * NSEC_PER_SEC);
    dispatch_source_set_event_handler(self.timerSource, ^{
        if (self.isObservingMessages) {
            [self observeNewMsgs];
        }
    });
    dispatch_resume(self.timerSource);
}

- (void)observeNewMsgs
{
    NSLog(@"JUST TO TEST");
    // Staff code...
}

@end

Also note, if you wanted the ability to change the value of your BOOL after the background process was initiated, you might want to make that a class property, too, as demonstrated above. I also renamed it to observingMessages to make its purpose more plain.
(It's just stylistic, but I only use the underscore character for class instance variables, so I renamed your _queue variable to be queue.)


text:
Q: Hostlistener with Onwindowscroll() for a particular div in the template This is my .html file
<table class="table" #scroller  [class.fixed]="fixed">
 <thead>

 </thead>
</table>

like this.My requirement is, i want to scroll the table and fix the table header after certain scroll.
My .ts file is this
@ViewChild('scroller') scroller: ElementRef
  @HostListener("window:scroll", ['$event'])
   onWindowScroll($event) {
     debugger;
     let num = this.document.body.scrollTop;
      if ( num >50 ) {
      this.fixed = true;
      }else if (this.fixed && num < 5) {
      this.fixed = false;
      }
    }

But when i use this all time this windows scroller method is getting activated.i want it to be getting activated while scrolling the table only.so i took the element with Viewchild.The problem is with this code.
let num = this.document.body.scrollTop;

I am taking the whole document body,i want only the table body scroll event.How can i do it with elementref.Please help me.Thanks in advance.


text:
Q: SQL Moving Aggregation Issue:  For a given recordset containing a date column, an arbitrary number of category columns, and a value column, I would like to compute aggregations of value for an arbitrary date window, such as 30 days, 365 days, etc.  I have looked at the window aggregate functions, CTEs, and a few others but they do not appear (to me at least) to perform the desired function.
The SQL (T-SQL) below typifies the basic idea what I a trying to accomplish, but I have a bad feeling about its scalability, particularly the join, and the increased difficultly once I try grouping by other nominal groups.
    SELECT
        basedate
        , count(*) as [n]
        , sum(Value) as [SumValue]
        , avg(value) As [AverageValue]
        , stdev(value) As [StdevValue]
FROM
    (SELECT t1.basedate , t2.*
     FROM
        (SELECT DISTINCT dt as basedate from foo)as t1
         ,foo as t2
      WHERE datediff(d, t1.basedate, t2.dt) between -30 and 0
      ) t3
GROUP BY t3.basedate
ORDER BY t3.BASEDATE DESC

I created a SQLFiddle to try to make it more concrete.
SQLFiddle
Thank you.

A: In my brief testing this is faster than your current query if the dt field is indexed:
SELECT    a.dt AS basedate
        , count(*) as [n]
        , sum(b.Value) as [SumValue]
        , avg(b.value) As [AverageValue]
        , stdev(b.value) As [StdevValue]
FROM  foo a
JOIN  foo b
   ON b.dt BETWEEN DATEADD(DAY,-30,a.dt) AND a.dt
GROUP BY a.dt
ORDER BY a.dt DESC

Edit:  I asked about version because in SQL Server 2012+ there's support for RANGE/ROWS which can create a moving window like you're going for, I believe you're stuck with a self-join.  Using DATEADD() and comparing the dt values is marginally faster than your DATEDIFF() version.

A: Playing around a bit with the setup provided in the SqlFiddle I came to these two potential solutions: (well, the first one is only half of the solution, not sure how I would add stdev() on there in an efficient way)
WITH t1
  AS (SELECT DISTINCT dt as basedate from foo),
     sumcount
  AS (SELECT basedate,
             SUM((CASE WHEN datediff(d, t1.basedate, t2.dt) between -30 and 0 THEN 1 ELSE 0 END)) as [n],
             SUM((CASE WHEN datediff(d, t1.basedate, t2.dt) between -30 and 0 THEN value ELSE 0 END)) as [Sumvalue]
        FROM t1, foo t2
       GROUP BY basedate)
SELECT basedate,
       [n],
       [Sumvalue],
       [Sumvalue] / [n] as [Averagevalue]
  FROM sumcount
ORDER BY basedate DESC

GO

WITH t1
  AS (SELECT DISTINCT dt as basedate from foo),
     t2
  AS (SELECT basedate, min_date = DateAdd(day, -30, basedate), max_date = DateAdd(day, 0, basedate) from t1)

SELECT basedate,
          count(*) as [n]
        , sum(b.value) as [Sumvalue]
        , avg(b.value) As [Averagevalue]
        , stdev(b.value) As [Stdevvalue]
FROM  t2
JOIN  foo b
   ON b.dt BETWEEN t2.min_date AND t2.max_date
GROUP BY basedate
ORDER BY basedate DESC

I prefer the last one for it's simple readability, and coincidently it runs quite a bit faster too although I can't quite tell why yet. Mind that I loaded the test-data a 100 times extra (using the magic of GO 100) to get some longer durations out of it on my laptop. (it's hard to compare 1ms vs 1ms =)

Surprisingly, the (accepted) solution from Halt CO returns different results than the original query (or 'my' queries) when given the 'extended' test-set; you might want to look into that! (The reason being that it finds the base-dates multiple times, sums mulitple times due to this and then in the end ends up with much bigger Counts and SumValues. I'm not sure this is what you want, or if it is something that might happen with 'real data', but since you put an index and not a UNIQUE index on that foo table I'm assuming doubles can occur... )


text:
Q: Writing iOS Apps development Remotely I got a request, where I need to write to code for a Someone. But they want me to write on their machines instead Remotely.
Does any one know any software by which i can access someone else screen remotely?
Yes i can use VNC or Microsoft Remote Desktop but then the Question is then, How will i run that code from Xcode on my end into the Real device for testing.

A: There's also the Screen Sharing feature - although this is essentially a nicely integrated VNC client with some smarts.
This kind of working arrangement does not sound like a terribly productive one - many features of XCode rely on quick user interaction - for instance code completion.  On a laggy remote connection these will become highly irritating or entirely unusable.
As you suggest, there is no way to remotely debug on a device. You can however create an AdHoc build which can then be installed on your own device via the web or through iTunes.
The Apple Developer programme puts a few barriers in the way of a contract development relationship - particularly with respect to code-signing - which you'll need to run on a real device as well as app-store submission.   The only two solutions are either a corporate ADC account (you are added as an 'employee' user) or having your own individual account which is used for development.

A: Two immediate solutions:

*

*you can generate adhoc build and install on any device with the developer approved provisioning profile.

*generate ipa and install on a JB device.


text:
Q: Text background not working with html2canvas I am trying to generate a picture from my Div using Html2Canvas but it is not working fine, The problem is the background on my text. You can see that here:

window.takeScreenShot = function() {
  html2canvas(document.getElementById("est1"), {
    onrendered: function(canvas) {
      document.body.appendChild(canvas);
    },
    width: 320,
    height: 220
  });
}
#example4 {
  display: block;
  font-size: 60px;
  color: rgb(0, 0, 0);
  font-family: Arial;
  background: -webkit-linear-gradient(top, rgb(213, 11, 27), rgb(28, 79, 145));
  -webkit-text-stroke-width: 0px;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

Test

<button onclick="takeScreenShot()">to image</button>

I have a text background style and it shows fine the text, but if You click on To Image, html2canvas generate a picture with a black text and wrong background.
How I can do to generate a correct picture using html2canvas?

A: Try to use CSS as inline and you can generate a correct Picture using html2canvas.

Test


text:
Q: How to randomly download many files from a google drive folder I looked answers from this question Download file from Google Drive to local folder from Google Apps Script
The answers to above questions only give instructions to download a single file or folder, But I want to download a small no.(say 50) of random files from a folder, Is there any way to do this programmatically?

A: I would suggest by starting with file.list to return the first 100 files on your google drive account, you can then loop through them and download each of them one at a time.    The file.list method has an option called q which would allow you to search for only files with in a directory using parents.
yes all of this can be done programmatically


text:
Q: Overlay map in checkbox only shows with first base map The Overlay map in the checkbox only works on click of the first base map in the control layer, I can see the attribution when I am on the second  base map, but not the map itself. I am working with leaflet seems rather strange.............................................................................................

  var googleearth = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
    minZoom : 6,
    maxZoom: 17,
    attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
  });

  var googleTerrain = L.tileLayer('http://{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',{
    maxZoom: 20,
    subdomains:['mt0','mt1','mt2','mt3']
  });

  var map = L.map("mapid", {
    zoom: 10,
    center: [55.7363, -6.1771],
    layers: [ googleearth, googleTerrain],
    zoomControl: false,
    attributionControl: true,
    measureControl: true

  });

  var baseLayers = {
       "Aerial Imagery": googleearth,
       "googleTerrain":googleTerrain
  };

 L.control.layers(baseLayers,null,{collapsed:false}).addTo(map);

 var OpenTopoMap = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
    maxZoom: 17,
    visibility: true,
    attribution: 'Map data: © OpenStreetMap, SRTM | Map style: © OpenTopoMap (CC-BY-SA)'
  });

$(document).ready(function(){
    $("#layercontrol2").change(function(){
        if($(this).prop("checked")){
    OpenTopoMap.addTo(map);
    return;
  }else {

    OpenTopoMap.remove();

    return;

    }
  });
});

<!DOCTYPE html>

  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />

    <input id="layercontrol2" type="checkbox" /> Topo Map

A: The Leaflet Layers Control automatically manages the z-index of the layers you pass to it, if you let the autoZIndex option to true (default value):

If true, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.

So your 2 Tile Layers googleearth and googleTerrain have a z-index of 1 and 2 respectively.
Now your 3rd Tile Layer (OpenTopoMap, the one you try to manage externally with your own checkbox) has only a z-index of 1 (default value), so it will be underneath the googleTerrain one.
The solution is simply to specify a high z-index value for your 3rd Tile Layer OpenTopoMap.
You could also turn the autoZIndex to false, so that all your Tile Layers have the default z-index value of 1, in which case the last added Tile Layer appears on top.

var googleearth = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
  minZoom: 6,
  maxZoom: 17,
  attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
});

// Note: replacing the Tile Server to comply with Google Maps Terms.
var googleTerrain = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '© OpenStreetMap contributors'
});

var map = L.map("mapid", {
  zoom: 10,
  center: [55.7363, -6.1771],
  layers: [googleearth, googleTerrain],
  zoomControl: false,
  attributionControl: true,
  measureControl: true

});

var baseLayers = {
  "Aerial Imagery": googleearth,
  "googleTerrain": googleTerrain
};

L.control.layers(baseLayers, null, {
  collapsed: false,
  //autoZIndex: false,
}).addTo(map);

var OpenTopoMap = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
  zIndex: 100, // Make sure you specify a high enough value.
  maxZoom: 17,
  visibility: true,
  attribution: 'Map data: © OpenStreetMap, SRTM | Map style: © OpenTopoMap (CC-BY-SA)'
});

$(document).ready(function() {
  $("#layercontrol2").change(function() {
    if ($(this).prop("checked")) {
      OpenTopoMap.addTo(map);
      return;
    } else {

      OpenTopoMap.remove();

      return;

    }
  });
});
<!DOCTYPE html>

  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />

    <input id="layercontrol2" type="checkbox" /> Topo Map


text:
Q: OOPS (Design Patterns) hey, hi i want put limit on object creation means a class can have at most suppose 4 objects not more than that how to achieve this?

A: You can count the numbers of instances created by using a static class property to store the count.  This can either be done in the class constructor or you can make use of a factory pattern.  It is a bit difficult to answer this more precisely without knowing the target language.

A: Try modifying the Singleton pattern. You can use a count variable. You'll need to keep the Constructor private to have control over the no. of instances.

A: One approach is using an object factory that creates at most 4 instances. It's an interesting need... Would an object pool serve the same need?

A: One way to achieve is the Singleton Design pattern,
Whenever we make a call to create an instance, check the count of the instance which are already created, if the instance count is already reached 4, then use the same instance for your application.
TO have a count, Creat Static Int Counter = 0; and keep incrementing it to get the results.

A: The simplest way to do this would be to have a class level attribute called "count", and in your constructor, just make sure that "count" isn't above a certain number.
//pseudocode
class foo
  static count = 0

  def constructor()
    if count < 4
      //create object
    else
      //there are too many!

A: This  is short code snippest that will give the above result in c#
sealed class clsInstance
    {
        public static int count = 0;
        private static readonly clsInstance inst = new clsInstance();
        clsInstance()
        {

        }

        public static clsInstance Inst
        {
            get
            {
                if (count < 4)
                {

                    Console.WriteLine("object : " + count);
                    count++;
                    return inst;
                }
                return null;
            }
        }

    }

   class MainClass
   {
       public static void Main(String[] args)
       {
           clsInstance c1 = clsInstance.Inst;
           clsInstance c2 = clsInstance.Inst;
           clsInstance c3 = clsInstance.Inst;
           clsInstance c4 = clsInstance.Inst;
           Console.ReadLine();
           clsInstance c5 = clsInstance.Inst;
           Console.ReadLine();
       }
   }


text:
Q: Progress bar from bottom to top controlled by I want to create battery indicator for a web app. I use the progress bar tag. The problem is that it starts from left to right and i want to be from bottom to top. The second problem is that JavaScript seems to not change anything. How to fix this problems? Note: I already read this answers: Progress Bar Fill Up Bottom-To-Top
and this which is not using progress tag:
How to show a vertical progress bar from bottom to top

 navigator.getBattery().then(function(battery) {
  battery.addEventListener('levelchange', function() {
   document.getElementById('bat').innerHTML=((battery.level*100));
  })
   document.getElementById('bat').innerHTML=((battery.level*100));
});
progress#bat{

    position:absolute;
    top:5vh;
    right:5vh;
    height:90vh;
    border:none;
    background-color:black;
    color:red;
}

BatteryLevel

    <progress max='100' value="22" id='bat'></progress>

A: To resolve the "top to bottom" directional issue for the progress indicator, one solution would be to use CSS transforms in this way:
transform:rotate(90deg);

That would have the effect of rotating the <progress/> element to make the indicator track from top to bottom. You'd then flip the values of width and height to achieve the dimensions of an "upright battery".
Lastly, to cause the progress element to update with changing battery levels, you should set the value field on the bat element rather than innerHTML as you currently are to achieve automatic updates, like so:

navigator.getBattery().then(function(battery) {

  battery.addEventListener('levelchange', function() {

    /* Apply battery.level * 100 to value field to cause
       bat element to update as expected */
    document.getElementById('bat').value = battery.level * 100;
  });

  /* Apply battery.level * 100 to value field to cause
     bat element to update as expected */
  document.getElementById('bat').value = battery.level * 100;
});
progress#bat{

    position:absolute;
    top:5rem;
    left:1rem;
    border:none;
    background-color:black;
    color:red;

    transform:rotate(90deg); /* rotation flips
                perception of width and height */

    height:4rem; /* height appears to be width */
    width:9rem;  /* width appears to be height */
}

  <progress max='100' value="12" id='bat'></progress>


text:
Q: Getting 404 resource not found in jersey uploading a file I am developing jersey web service to upload file.I have written the code for this but whenever I click on the submit button of WelcomeFile.jsp to upload the file it throws an error 404 resource not found.
I don't know where I am wrong in this code Please help me improve it by doing.
Thanks in advance.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Rest</display-name>

    <welcome-file-list>
            <welcome-file>/WEB-INF/ViewPages/WelcomeFile.jsp</welcome-file>
    </welcome-file-list>

</web-app>

pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>Rest</groupId>
    <artifactId>Rest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <repositories>
        <repository>
            <id>maven2-repository.java.net</id>
            <name>Java.net Repository for Maven</name>
            <url>http://download.java.net/maven/2/</url>
            <layout>default</layout>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.8</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-multipart</artifactId>
            <version>1.8</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <webXml>WebContent\WEB-INF\web.xml</webXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

WelcomeFile.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome File</title>

File Upload with Jersey

    <form action="file/upload" method="post" enctype="multipart/form-data">

        Select a file : <input type="file" name="file" size="45" />

       <input type="submit" value="Upload It" />
    </form>

UploadFileService.java
package serviceServer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

@Path("/file")
public class UploadFileService {
    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail) {

        System.out.println("hi inside server");
        String uploadedFileLocation = "d://uploaded/" + fileDetail.getFileName();

        // save it
        writeToFile(uploadedInputStream, uploadedFileLocation);

        String output = "File uploaded to : " + uploadedFileLocation;

        return Response.status(200).entity(output).build();

    }

    // save uploaded file to new location
    private void writeToFile(InputStream uploadedInputStream,
        String uploadedFileLocation) {

        try {
            OutputStream out = new FileOutputStream(new File(
                    uploadedFileLocation));
            int read = 0;
            byte[] bytes = new byte[1024];

            out = new FileOutputStream(new File(uploadedFileLocation));
            while ((read = uploadedInputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
            out.close();
        } catch (IOException e) {

            e.printStackTrace();
        }

    }
}


text:
Q: Android ScrollView below Toolbar fails to show all content I have made a base-activity with a toolbar and add my layouts to this. But when I add a scrollview in the main content it doesn't show the bottom part when scrolling down. The missing part seems to be the same height as the toolbar.
My activitybase.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/ToolBarStyle"
        android:background="?attr/colorPrimary" />
    <FrameLayout
        android:id="@+id/root_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

My fragmentinfo.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/default_margin">
        <TextView
            android:id="@+id/info_header"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/default_margin"
            android:text="hei"
            style="@style/TextLarge" />
        <TextView
            android:id="@+id/info_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/small_margin"
            android:text="-SOME LONG TEXT-"
            style="@style/TextNormal" />

      <TextView
            android:id="@+id/info_header2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/default_margin"
            android:text="Test"
            style="@style/TextLarge" />
    </LinearLayout>
</ScrollView>

Screenshot below. This is scrolled all the way down. "Test" should be showing with 16 dp margin below it...

A: In FrameLayout
<FrameLayout
  ...
  android:layout_marginBottom="56dp"
  ...
/>

Here 56dp is the Action Bar size.

A: Add android:layout_marginBottom to the ScrollView, using the action bar height dimen.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="@dimen/abc_action_bar_default_height_material"
    android:fillViewport="true">


text:
Q: Plot sometimes does not react to mouse input in windows forms I'm using an ILPlotcube with line- and point-plots inside a windows forms window. Somehow the mouse control of the PlotCube, like zooming and dragging does not work anymore. For example: i can't zoom into the plot by drawing a rectangle over the region i want to see. The mouse doesn't seem to be recognized anymore.
Basically the code looks like this:
public void init() {
    Thread backgroundThread = new Thread(
        new ThreadStart(() =>
        {
            makePlot();
        }));
    backgroundThread.Start();
}

makePlot() looks like this:
public void makePlot()
{
   ILPlotCube plotCube = _ilPanel.Scene.First<ILPlotCube>();

   if (plotCube == null) {

      plotCube = new ILPlotCube {
         new ILLinePlot(tosingle(_data1), "plot1", lineColor: Color.Blue),
         new ILLinePlot(tosingle(_data2), "plot2", lineColor: Color.Red),
         new ILLegend("data1","data2")
       };
       _ilPanel.Scene = new ILScene { plotCube };
   }
   else
   {
      plotCube.First<ILLinePlot>(tag: "plot1").Line.Positions.Update(tosingle(_data1);
      plotCube.First<ILLinePlot>(tag: "plot2").Line.Positions.Update(tosingle(_data2);
   }

   _ilPanel.Scene.Configure();

   _ilPanel.Invoke((MethodInvoker)delegate { _ilPanel.Refresh(); });
}

I call init() in Form1_Load() not in ilPanel1_Load()
Actually there is an other thing. The Class Reference says ILLinePlot has a Method "Update" to update the positions of the plotted line. But Visual Studio tells me ILLinePlot doesn't have such a member Function. Instead i'm using
   linePlot.Line.Positions.Update

Also if i don't call Configure() on the Scene Element it won't plot the legend but if i do, the whole Plotting takes much more time.

A: I got it to work after i switched
ilpanel.Scene = new ILScene { plotCube }

to
ilpanel.Scene.Add( plotCube )

A: It is hard to guess without some code. But I suppose there are multiple plot cubes in your scene. And they probably use the same screen area (probably the whole panel area?). Mouse events will fire on the topmost camera object or one of its children, if configured that way. Possibly the plot cube lays "behind" some other camera object which catches all the events. You can find out by registering an event handler on the root node and print out all mouse down events:
ilPanel1.Scene.MouseDown += (_s, _e) => { Debug.WriteLine(_e.Target); };

This will give the node below the mouse which was selected as target for the mouse event during the mouse down action. In order for the (correct) plotcube to properly receive the mouse events for zoom / rotate/ pan operations there should be either the plotcube node (plotcube derives from ILCamera) or one of its children found as target.
Another easy way to inspect the scene and detect all camera nodes contained is to create a breakpoint at the very end of your setup method (mostly this will be ilPanel1_Load(..). Once you stopped in the debugger, execute the following code in the Immediate window:
ilPanel1.Scene.Find<ILCamera>()

Count = 2
[0]: "Camera: #2 - Polar r:10 φ:0° ρ:0° - Pos X:0 Y:0 Z:10 - Lookat X:0 Y:0 Z:0 - Top X:0 Y:1 Z:0"
[1]: "ILPlotCube #30 'PlotCube' Children:[2]"

How many plot cubes do you count?


text:
Q: Attempting to extract stock prices using python I am currently trying to extract stock prices from a list of stock codes contained on a csv file by using pandas and yfinance.
I have 145 companies I need to do this for, is there a way of doing it? As I have tried over a period of 5 days without success.
I just need to know if its possible and what would you recommend to achieve this.

A: yfinance.Ticker(ticker).history(start=start_date) gets you the data that you desire.
if you have a giant  csv, with a field "ticker", you can create a pandas dataframe with the below:
import pandas as pd
import yfinance
def read_create_giant_df(file_in):
    df = pd.read_csv(file_in)
    out = []
    for item in df["ticker"]:
        ticker_df = yfinance.Ticker(item).history(start="1930-01-01")
        ticker_df["ticker"] = item
        out.append(ticker_df)
    return pd.concat(out)

A: below code should work , if any module missing use command to install it .
pip install yfinance
pip install yahoofinancials

Run below code to get the data for Amazon-AMZN
import pandas as pd
import yfinance as yf
from yahoofinancials import YahooFinancials
amzn_df = yf.download('AMZN',
                  start='2019-01-01',
                  end='2019-12-31',
                  progress=False)
amzn_df.head()


text:
Q: Connect to wifi before Lubuntu install (prepare in live mode?) I am in the situation where only bootable external media I can use is an USB flash and only option I can use to connect to Internet is Wi-Fi.
I am trying to install Lubuntu on an older Acer laptop and I am having the issue with the grub installation, I've read that it can be solved by connecting the device to the Internet (people are also advising to select .../sdX instead of .../sda, but the installation is stuck there, so I am trying this way).
Also I would like for it to get any updates while installing, that's reason No.2.
So how would I connect to wifi, before the installation?
Can it somehow be prepared from the live run?
Lubuntu ISO I am using: lubuntu-16.10-desktop-amd64.iso
I will be grateful for any advice/help ! Thanks :)
(I am a linux sometimes-user, I know a few basic commands, but I am not an expert...)


text:
Q: Angular mock Spec I am using ng-mocks this way -
import { MockDirective, MockComponent, ngMocks } from 'ng-mocks';

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
                      MockComponent(ComponentName),

      ],

      schemas:      [ NO_ERRORS_SCHEMA ]

    })
    .compileComponents();
  }));

I am seeing the below error -
Failed: ng-mocks is not in JIT mode and cannot resolve declarations

A: I got this error after upgrading my project from angular @12.2.16 to @13.2.4. However I was getting the exact same error:
MyComponent declaration has been passed into ng-mocks without Angular decorators. Therefore, it cannot be properly handled. Highly likely, jest.mock() has been used on its file, or ng-mocks is not in JIT mode
My project versions:

*

*ng-mocks: 12.5.1

*@angular/core: 13.2.4

After trying a lot of possible solutions a could solve my problem just reinstalling ng-mocks with the latest version and everything  got fixed up and all tests were passing successfully.
Update ng-mocks to the latest version with:
$ npm uninstall ng-mocks
$ npm install ng-mocks@latest --save-dev

Good lucky, hope this help someone else.

A: this issue has been fixed recently. In your case, it means that ComponentName has been imported wrongly, or has a wrong type.
MockComponent accepts classes. Therefore, it should be used like:
import { MockDirective, MockComponent, ngMocks } from 'ng-mocks';

beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [
      MockComponent(ComponentClass), // <- its class instead of its name.
    ],
  }).compileComponents();
}));


text:
Q: Delphi indy10 sockets data exchange on multiple forms I am using indy10 sockets, and I ran into a small snag. I have my IdTCPServer on form one and I am wanting to send data from form 2 to remote location. I would think AContext.IOHandler.WriteLn() would work but in form 2 it throws errors and Identifier not found AContext.
It was simple to send and receive text on the client side. But, I am looking for a way to send text from the server on different form from the socket. If anything I will do a messy job and put invisible memo to send to then read the memo from there and send it off.

A: You are on the right track - using the IOHandler object of a given TIdContext - but you are looking in the wrong place for it.  From outside of the server's event handlers, you can access active TIdContext objects using the TIdTCPServer.Contexts property., which is a TThreadList of active connections.  To keep track of per-client data, such as login identifiers, you can use the TIdContext.Data property, or derive a new class from TIdServerContext and then assign it to the TIdTCPServer.ContextClass property.


text:
Q: randomly replacing a specific value in a dataset with frac in pandas I've got a dataset with some missing values as " ?" in just one column
I want to replace all missing values with other values in that column (Feature1) like this:
Feature1_value_counts = df.Feature1.value_counts(normalize=True)

the code above gives me the number I can use for frac in pandas
Feature1 contains 15 set of unique values
so it has 15 numbers (all percentage)
and now I need to just randomly replace " ?"s with those unique values (All strings) with that frac probability
I don't know how to do this using pandas!
I've tried loc() and iloc()
and also some for and ifs I couldn't get there

A: You can take advantage of the p parameter of numpy.random.choice:
import numpy as np

# ensure using real NaNs for missing values
df['Feature1'] = df['Feature1'].replace('?', np.nan)

# count the fraction of the non-NaN value
counts = df['Feature1'].value_counts(normalize=True)
# identify the rows with NaNs
m = df['Feature1'].isna()

# replace the NaNs with a random values with the frequencies as weights
df.loc[m, 'Feature1'] = np.random.choice(counts.index, p=counts, size=m.sum())

print(df)

Output (replaced values as uppercase for clarity):
  Feature1
0        a
1        b
2        a
3        A
4        a
5        b
6        B
7        a
8        A

Used input:
df = pd.DataFrame({'Feature1': ['a', 'b', 'a', np.nan, 'a', 'b', np.nan, 'a', np.nan]})


text:
Q: AsyncTask ProgressBars in Fragments crash in onPreExecute() method I have an ASyncTask handling multiple ProgressBars on a Background Thread.
The line below is causing an error/crash.
    @Override
    protected void onPreExecute() {
        progress = maskBars[currentProgressBarId].getProgress();
    }

I am stumped as it works fine in the demo ( inside 2 placeholder fragments).
My fragments are created using fragmentManager, could this be the reason??
aSyncTask Method
    private AsyncTaskUpdateProgress asyncTaskUpdateProgress;

    public class AsyncTaskUpdateProgress extends AsyncTask<Void, Integer, Void> {
        int progress;

        @Override
        protected void onPostExecute(Void result) {
            currentProgressBarId++;

            if ((maxProgressValue - currentProgressBarId * 100 > 0) && (currentProgressBarId < maskBars.length)) {
                if (!isCancelled()) {
                    SystemClock.sleep(PROGRESS_BAR_DELAY);
                    asyncTaskUpdateProgress = new AsyncTaskUpdateProgress();
                    asyncTaskUpdateProgress.execute();
                }
            } else {
                buttonStop.setEnabled(false);
                buttonReset.setEnabled(true);
            }
        }

        @Override
        protected void onPreExecute() {
            progress = maskBars[currentProgressBarId].getProgress();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            textViewProgress.setText(String.valueOf(crgBrId * 100 + values[0]));
            maskBars[currentProgressBarId].setProgress(values[0]);
        }

        @Override
        protected Void doInBackground(Void... args) {
            int limit = maxProgressValue - currentProgressBarId * 100;
            if (limit > 100) { limit = 100; }

            while ((!isCancelled()) && (progress < limit)) {
                progress++;

                publishProgress(progress);
                SystemClock.sleep(PROGRESS_DELAY);
            }

            return null;
        }
    }

LOG
    12-15 17:04:42.088: E/AndroidRuntime(7305): FATAL EXCEPTION: main
    12-15 17:04:42.088: E/AndroidRuntime(7305): Process: com.black.app, PID: 7305
    12-15 17:04:42.088: E/AndroidRuntime(7305): java.lang.NullPointerException
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at com.myob.app.VerticalProgressBars$AsyncTaskUpdateProgress.onPreExecute(VerticalProgressBars.java:56)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at android.os.AsyncTask.execute(AsyncTask.java:535)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at com.black.app.VerticalProgressBars.onClick(VerticalProgressBars.java:140)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at android.view.View.performClick(View.java:4445)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at android.view.View$PerformClick.run(View.java:18429)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at android.os.Handler.handleCallback(Handler.java:733)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at android.os.Handler.dispatchMessage(Handler.java:95)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at android.os.Looper.loop(Looper.java:136)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at android.app.ActivityThread.main(ActivityThread.java:5089)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at java.lang.reflect.Method.invokeNative(Native Method)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at java.lang.reflect.Method.invoke(Method.java:515)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
    12-15 17:04:42.088: E/AndroidRuntime(7305):     at dalvik.system.NativeStart.main(Native Method)
    12-15 17:04:42.095: W/ActivityManager(434):   Force finishing activity com.blagmynames.app/.NameActivity
    12-15 17:04:42.627: W/ActivityManager(434): Activity pause timeout for ActivityRecord{41b08cf8 u0 com.blackmagicnames.app/.NameActivity t29 f}
    12-15 17:04:42.767: I/ActivityManager(704): Timeline: Activity_idle id: android.os.BinderProxy@41ae0c10 time:27575356
    12-15 17:04:43.181: I/ActivityManager(434): Timeline: Activity_windows_visible id: ActivityRecord{41faaa98 u0 com.cyanogenmod.trebuchet/com.android.launcher3.Launcher t1} time:27575770


text:
Q: problem with nan in python ( pandas) the program can't recognize the nan I stock in strange situation
i have Data frame , some of the values are nulls
when I try do change the null , i cant do it , for some reason the console dosent recognize the null
for example:

df["volume_fermentor"]=df["volume_fermentor"].replace(np.nan,999)

when i run it , the console success do it but nothing change in the data frame
another example:
df["volume_fermentor"][4]

Out[79]: nan

df["volume_fermentor"][4]==df["volume_fermentor"][4]

Out[80]: False

df["volume_fermentor"][4]==np.nan

Out[81]: False'


text:
Q: stubbing a method for all instances of a class Trying to stub a method getSigningKey of jwksClient. However, it actually executes the non stub version of the function and returns an error instead of the mockResponse. How to stub it such that it will return the mockResponse instead?
const jwksClient = require('jwks-rsa');
sinon.stub(jwksClient(sinon.match.any), 'getSigningKey').callsArgWith(1, null, mockResponse)
const client = auth0authorizer.jwksClient({
     cache: true,
     cacheMaxEntries: 5, // Default value
     cacheMaxAge: ms('10h'), // Default value
     jwksUri: jwksUri
});
client.getSigningKey('abc',(err,key) => {
  // doesn't stub returns error
})

A: This code looks more complex than necessary, especially the Sinon part. I am assuming auth0authorizer.jwksClient is a typo in your example code, and that you really meant just jwksClient.
If you mean to stub the instance, you need to stub the generated instance, not a non-existing method on the factory method (which is what you are doing!).
That would simply mean
const client = jwksClient({
     cache: true,
     jwksUri: jwksUri
});
sinon.stub(client, 'getSigningKey').callsArgWith(1, null, mockResponse)

But if the problem is that you have no access to the generated client object for some reason, such as it being generated outside of your control, you will have to stub the prototype of the jwksClient. It looks like you are not able to import the JwksClient class directly, as the lib is transpiled by Babel, and does not export the class. In that case, you can make use of Object.getPrototypeOf().
Just invoke the jwksClient function first, and get hold of the dummy object returned. We will only use this to modify the prototype:
 const proto = Object.getPrototypeOf( jwksClient(options) );
 // create stub on the class method
 const stub = sinon.stub(proto, 'getSigningKey').callsArgWith(1, null, mockResponse);
 // proceed with test as normal

Just remember to restore the stub afterwards, as you might have weird errors in later tests otherwise :-)
Discloser: I am on the Sinon team.


text:
Q: How do I fix this except statement properly? I'm doing the Collatz Sequence problem from Automate the Boring Stuff for Python and I can't seem to figure out why I can't print 'Please enter an integer' even when I encounter a ValueError.
def collatz(number):
    while number!=1:
        if number%2==0: #even
            number=number//2
            print(number)
        elif number%2==1: #odd
            number=3*number+1
            print(number)

while True:
    print('Enter number:')
    a=int(input())
    try:
        collatz(a)
    except ValueError:
        print('Please enter an integer')

A: For your code, you need to include following line after try statement then exception will work
a = int(input()

Hereafter is my code snippet and it worked perfectly
#!/usr/bin/python
def collatz(i):
    if i % 2 == 0:
        n = i // 2
        print n
        if n != 1:
            collatz(n)
    elif i % 2 == 1:
        n = 3 * i + 1
        print n
        if n != 1:
            collatz(n)
try:
    i = int(raw_input("Enter number:\n"))
    collatz(i)
except ValueError:
    print "Error: You Must enter integer"


text:
Q: How to do integral $\int_{0}^{\infty} \frac{x^4 e^{x}}{(e^x-1)^2}\,dx$ $$\int_{0}^{\infty} \frac{x^4 e^{x}}{(e^x-1)^2}\,dx$$
This integral came from the Debye theory of the molecular heat capacity of crystal.
I heard that this integral form is related to Riemann Zeta function and Gamma function.
Also, i heard that it can be solved by using Feynmann's Trick.
How can i evaluate this integral?

A: The Riemann/Gamma way:$$\int_0^\infty\frac{x^4e^{-x}dx}{(1-e^{-x})^2}=\sum_{n\ge 1}n\int_0^\infty x^4e^{-nx}dx=\sum_{n\ge 1}\frac{4!}{n^4}=24\zeta(4)=\frac{4\pi^4}{15}.$$

A: Recall the integral representation of the Polylogarithm given by

$$\operatorname{Li}_s(z)~=~\frac1{\Gamma(s)}\int_0^\infty \frac{t^{s-1}}{e^t/z-1}\mathrm dt$$

Moreover note that
$$\frac{\partial}{\partial z}\left[\frac{t^{s-1}}{e^t/z-1}\right]=\frac{t^{s-1}e^t}{(e^t-z)^2}$$
which is precisely the structure of your integrand. Thus, by applying a variation of Feynman's Trick we obtain
\begin{align*}
\frac{\mathrm d}{\mathrm dz}\Gamma(s)\operatorname{Li}_s(z)&=\frac{\mathrm d}{\mathrm dz}\int_0^\infty \frac{t^{s-1}}{e^t/z-1}\mathrm dt\\
\Gamma(s)\frac{\mathrm d}{\mathrm dz}\operatorname{Li}_s(z)&=\int_0^\infty \frac{\partial}{\partial z}\frac{t^{s-1}}{e^t/z-1}\mathrm dt\\
\Gamma(s)\frac{\operatorname{Li}_{s-1}(z)}z&=\int_0^\infty\frac{t^{s-1}e^t}{(e^t-z)^2}\mathrm dt
\end{align*}
Now plugging in $s=5$ and $z=1$ yields to
\begin{align*}
\Gamma(5)\frac{\operatorname{Li}_{5-1}(1)}1&=\int_0^\infty\frac{t^{5-1}e^t}{(e^t-1)^2}\mathrm dt\\
4!\operatorname{Li}_4(1)&=\int_0^\infty\frac{t^{4}e^t}{(e^t-1)^2}\mathrm dt
\end{align*}
Note that the RHS is the integral we are interested in whereas the LHS can be evaluated directly in terms of the Riemann Zeta Function. Overall this boils down to utilizing the value of $\zeta(4)$, as J.G.'s answer did aswell, since $\operatorname{Li}_s(1)=\zeta(s)$ as one can verify by using the series representation of the Polylogarithm.

$$\therefore~\int_0^\infty\frac{t^{4}e^t}{(e^t-1)^2}\mathrm dt~=~4!\operatorname{Li}_4(1)~=~\frac{4\pi^4}{15}$$

A: For a slight variation along a polylogarithmic theme, observe that for the polylogarithm of order $s = -1$ one has
$$\operatorname{Li}_{-1} (z) = \frac{z}{(1 - z)^2}.$$
Setting $z = e^{-x}$ leads to
$$\operatorname{Li}_{-1} (e^{-x}) = \frac{e^{-x}}{(1 - e^{-x})^2}.$$
Now for the integral
$$I = \int_0^\infty \frac{x^4 e^x}{(e^x - 1)^2} \, dx,$$
rewriting it as
$$I = \int_0^\infty \frac{x^4 e^{-x}}{(1 - e^{-x})^4} \, dx,$$
which in terms of polylogarithms becomes
$$I = \int_0^\infty x ^4 \operatorname{Li}_{-1} (e^{-x}) \, dx. \tag1$$
Now since
$$\int \operatorname{Li}_s (e^{-x}) \, dx = - \operatorname{Li}_{s + 1} (e^{-x}) + C,$$
integrating (1) four times by parts leads to
\begin{align}
I &= 4! \int_0^\infty \operatorname{Li}_3 (e^{-x}) \, dx = 4! \big{[} - \operatorname{Li}_4 (e^{-x}) \big{]}_0^\infty = 4! \operatorname{Li}_4 (1) = 4! \cdot \frac{\pi^4}{90},
\end{align}
or
$$\int_0^\infty \frac{x^4 e^x}{(e^x - 1)^2} \, dx = \frac{4 \pi^4}{15},$$
as required.

Comment
The real advantage of this approach lay in the fact it can be used to find the corresponding indefinite integral
$$\int \frac{x^4 e^x}{(e^x - 1)^2} \, dx.$$
Following exactly the method outlined above, one finds
$$\int \frac{x^4 e^{x}}{(e^x - 1)^2} \, dx = -x^4 \operatorname{Li}_0 (e^{-x}) - 4x^3 \operatorname{Li}_1 (e^{-x}) - 12 x^2 \operatorname{Li}_2 (e^{-x}) - 24x \operatorname{Li}_3 (e^{-x}) - 24 \operatorname{Li}_4 (e^{-x}) + C.$$
Note the polylogarithm expressions of order zero and one can be expressed as
$$\operatorname{Li}_0 (e^{-x}) = \frac{1}{e^x - 1} \qquad \text{and} \qquad \operatorname{Li}_1 (e^{-x}) = - \ln(1 - e^{-x}).$$


text:
Q: Copy a single file in MSBuild without using Exec or ItemGroup Is there any way to do this?  I just need to copy a single file and thought there may be some syntax for the SourceFiles parameter of the Copy task that means you don't need to define an ItemGroup beforehand, I'd rather stick with ItemGroup than use Exec though.

A: Just put the single file name as the value for "SourceFiles".
Easy-Peezey.
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="AllTargetsWrapper" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

    <PropertyGroup>
        <WorkingCheckout>.</WorkingCheckout>
    </PropertyGroup>

    <Target Name="AllTargetsWrapper">
        <CallTarget Targets="CopyItTarget" />
    </Target>

    <Target Name="CopyItTarget">
        <Copy SourceFiles="c:\windows\system.ini" DestinationFolder="$(WorkingCheckout)\"/>
        <Error Condition="!Exists('$(WorkingCheckout)\system.ini')" Text="No Copy Is Bad And Sad" />
    </Target>

</Project>

A: Copy files also takes a straight propertygroup as input:
<PropertyGroup>
  <SourceFile>Some file</SourceFile>
</PropertyGroup>
<Copy SourceFiles="$(SourceFile)" DestinationFolder="c:\"/>

Or even just a string
<Copy SourceFiles="Pathtofile" DestinationFolder="c:\"/>

A: For what it's worth, I needed to do the same thing, and wanted to put some version information in the file name. Here is how I did it for a project in $(SolutionDir) that references an executable created by another project in another solution that I can easily express the path to:
  <Target Name="AfterBuild">
    <GetAssemblyIdentity AssemblyFiles="$(SolutionDir)..\bin\$(Configuration)\SomeExectuable.exe">
      <Output TaskParameter="Assemblies" ItemName="AssemblyVersions" />
    </GetAssemblyIdentity>
    <CreateProperty Value="$(TargetDir)$(TargetName)-%(AssemblyVersions.Version)$(TargetExt)">
      <Output TaskParameter="Value" PropertyName="NewTargetPath" />
    </CreateProperty>
    <Copy SourceFiles="$(TargetPath)" DestinationFiles="$(NewTargetPath)" />
  </Target>


text:
Q: debugging no such file or directory I keep getting this no such file or directory error in my workflow but I don't know why as I don't even need to have any kind of files or directories at all.
This is structure of my github repository
.github
 -- workflows
 ----my_workflow.yml
README.md
yoga.txt

This is my .yml file.
name: Exercises
on:
  workflow_dispatch:

jobs:
  first:
    runs-on: [ ubuntu-latest ]
    outputs:
      pose_output: ${{ steps.read_file.outputs.pose_output }}

    steps:
      - name: Get COde
        uses: actions/checkout@v2

      - name: Read from file
        id: read_file
        run: |
            poses=$(cat yoga.txt)
            echo $poses
            echo "::set-output name=pose_output::$(echo ${poses})"

      - name: List all
        id: list_all
        run: |
          POSES=${{ steps.read_file.outputs.pose_output }}

          for input in ${POSES[@]}; do echo $input; done;

yoga.txt is basically a string, it's not an array, it's a bunch of words separated by space
input1 input2 input3 etc.
I have two problems:

*

*Outputs - how to use them the right way? As you can see I pass the output of my read_file step to the next step, but then I declare another variable to basically pass that output to variable which I can use in for loop. I know this is simple script and I can do this in one step but I want to practice.

*The first step runs successfully and when I echo $poses I get input1 input2 input3 but in next step list_all when I want to list all inputs via for loop I get input1 no such file or directory. It makes no sense.


text:
Q: MySQL data type for movie times I have chapter times in the form of HH:MM:SS. I am parsing them from a document, and I will have times as a string in the format of '00:12:14'. How would I store this in a mysql column, and then retrieve it in the required format to be able to:

*

*1) order by time;

*2) convert to a string in the above format.

A: I suggest you look at the MySQL time type.  It will allow you to sort and format as you wish.
http://dev.mysql.com/doc/refman/5.0/en/time.html

A: Use the TIME type.
It allows "time values to be represented in several formats, such as quoted strings or as numbers, depending on the exact type of the value and other factors." In addition, you can perform various functions to manipulate the time.

A: If I have such a simple task, I choose a simple solution: I would choose the python datetime.time module (see: datetime.time) and store a TIME object using strftime.
Loading it back in is a little painful as you would have to split your string at : and then pass the values to the time constructor. Example:
def load(timestr):
    hours,minutes,seconds = timestr.split(":")
    return datetime.time(hours,minutes,seconds)

Hope this helps.


text:
Q: SVG Skewing without translate-side Effect I'm trying to Skew svg elements inside the javascript with HTML5,
for example:
<svg>
<g transform="skewX(20)>
<rect width="50" height="35" fill="red"></rect>
</g>
</svg>

The rect inside the <g> element is skewed alright,
but the rect element also moved to the right(unwanted), I tried to set the position manually
with transform="translate(-20)" but the measure is not correct,
Is there any solution to this?

A: do you mean this?
<svg>
<g transform="skewX(20) translate(-20, 0)">
<rect width="50" height="35" fill="red"></rect>
</g>
</svg>


text:
Q: Can't send images to gmail through PHPMailer I'm using PHPMailer to send some messages in my intranet, the problem occurs when I try to send images in the body of the email, if I just send the images as an attachment everything goes smoothly, but when I try to send the images in the body of the mail Gmail (and just Gmail) ignores the image, even though it shows the message.
The one in the right is gmail, and the blacked out thing is the company logo, added through the AddEmbeddedImage() function
Even stranger is that I send an embedded image to header of the mail, and this one shows normally.
What can I do so that the images appear?
This is the code:
public function enviaEmail($email = "", $subject, $body, $nomes_anexos, $tipo_noticia = false) {

        global $config;

        if($tipo_noticia && ($tipo_noticia == 'company' || $tipo_noticia == 'company')){
            $this->mail->FromName = $config['email_fromname_company'];
        } else {
            $this->mail->FromName = $config['email_fromname'];
        }

        $this->mail->From = $config['email_from'];

        $header = $this->includeHeader($subject);
        $footer = $this->includeFooter();

        if(empty($email)){
            $this->logger->log("Email em branco.");
            return false;
        }

        $this->mail->ClearAllRecipients();
        $this->mail->AddAddress($email);
        $this->mail->Subject = $subject;
        $this->mail->Body    = $header.$body.$footer;
        $this->mail->AltBody = strip_tags($body).$footer;

        //THIS WORKS
        if($tipo_noticia && ($tipo_noticia == 'company' || $tipo_noticia == 'mensagem_company')){
            $this->mail->AddEmbeddedImage(dirname(__FILE__).'/../../public/img/company.png', 'logo', 'company.png');
        } else {
            $this->mail->AddEmbeddedImage(dirname(__FILE__).'/../../public/img/logo_local_novo.png', 'logo', 'local.png');
        }

        if(!empty($nomes_anexos)){
            foreach($nomes_anexos as $an){
                $nome_anexo_final = preg_replace("/^(.*)?-/","", $an);
                $this->mail->AddAttachment(PATH_ANEXOS."/".$an, urldecode($nome_anexo_final));
            }
        }
        if(!$this->mail->Send()) {
            $this->logger->log("Erro ao enviar e-mail '$subject' para '$email': ". $this->mail->ErrorInfo);
            return false;
        }

        return true;

    }


text:
Q: How to Iterate testng.xml file for different credentials and application urls I am running my testng.xml using a batch file. I need to run the same testng.xml multiple times with different urls (Say 10 urls). The test cases remain same for all the Urls.
I am giving the Application Urls in the property file. Currently I have only 1 url in the property file and I am changing the url manually. I want to automate this
I want separate emailable testng report for each iteration

A: if you are using maven to run, you can pass mvn -Durl="ur url"


text:
Q: Why are my Typescript tests shown multiple times in VS Test Explorer using Chutzpah? I've gotten Chutzpah test detection working with my Typescript code in my ASP.NET Core project. After adding another test file though all the tests show up twice in the Test Explorer. Hovering shows that tests from one file are found in the other and vise-versa.
How do I stop all the duplicate tests from showing up?
Here is my chutzpah.json:
{
  "Framework": "jasmine",
  "Compile": {
    "Extensions": [ ".ts" ],
    "ExtensionsWithNoOutput": [ ".d.ts" ],
    "Mode": "External",
    "UseSourceMaps": true
  },
  "References": [
    {
      "Includes": [
        "*/scripts/*.ts",
        "*/wwwroot/lib/xxxxxxxxxxxx.js",
        "*/wwwroot/lib/yyyyyyyyyyyy.js",
        "*/wwwroot/lib/zzzzzzzzzzzz.js",
      ],
      "Excludes": [ "*/scripts/*/*.d.ts" ]
    }
  ],
  "Tests": [
    {
      "Includes": [ "*/scripts/test/*.ts" ],
      "Excludes": [ "*/scripts/test/*.d.ts", "*/wwwroot/*" ]
    }
  ]
}

BTW you can see how I got testing working in the first place in this blog post, and see the whole project on Github.

A: Your references section is too permissive and is including all your test code. See this Chutzpah Issue.
You need to change you references too:
  "References": [
    {
      "Includes": [
        "*/scripts/*.ts",
        "*/wwwroot/lib/xxxxxxxxxxx.js",
        "*/wwwroot/lib/yyyyyyyyyyy.js",
        "*/wwwroot/lib/zzzzzzzzzzz.js",
      ],
      "Excludes": [
        "*/scripts/*/*.d.ts",
        "*/scripts/test/*.ts" // <- Exclude test directory!
      ]
    }
  ],


text:
Q: which is faster, left join the whole table, or left join a subselection of said table? I have two tables (A & B) my objective is to have some columns from A left joined with a few columns of B (both tables have a LOT of columns)
is it faster to :
A) Select A -> left join -> subselect B:
(selecting only the desired columns BEFORE the join)
SELECT * FROM (
    SELECT A.col_1,A.col_2,A.col3,A.col_b FROM A
    LEFT JOIN (
        SELECT B.col_1,B.col_2,B.col_a FROM B) B_temp
    ON A.col_b = B_temp.col_a

B) Select A -> left join -B:
(selecting only the desired columns AFTER the join)
SELECT A.col_1,A.col_2,A.col3,B.col_1,B.col_2 FROM A
LEFT JOIN B
ON A.col_b = B_temp.col_a

My gut tells me even tho the second option is way more readable, it might be worse since it first aglutinates everything moving a lot of data around. My consideration for this is:

*

*If the left join returns many results the simple-trivial approach (option B) might have to carry all these extra unecessary columns

Am I going in the right-way towards optimizing this sql query ?

A: Unless your SQL software is old and moldy, its query planner will handle your two example queries the same way.


text:
Q: Cron not working but manually run in terminal works I placed a command in a script file called app.sh that simply execute an application.
sh app.sh

When I run it with terminal directly works fine!! but when put it under cron does not work..I tired with three ways of actually the same command but different approach(see below commands).  It did not work either.  What went wrong in the script?  Anyone see something?
/opt/extras.ubuntu.com/pushbullet-indicator/bin/pushbullet-indicator

gnome-terminal -x sh -c "/opt/extras.ubuntu.com/pushbullet-indicator/bin/pushbullet-indicator"

exec /opt/extras.ubuntu.com/pushbullet-indicator/bin/pushbullet-indicator

under the crontab -e
*/1 * * * * sh /home/app.sh


text:
Q: Why $\arctan x$ not equal to $\arcsin(x)/\arccos(x)$? Why $\arctan x$ not equal to $\frac{\arcsin(x)}{\arccos(x)}$? Is there a counter example that I can use to show that they are not equal? Thank!

A: Aside from $x=0$ and a value near $0.450116$ you can try any value you want.

A: It's not terribly difficult to show if $h(x)=\frac{f(x)}{g(x)}$, then, in general,
$$h^{-1}(x) \neq \frac{f^{-1}(x)}{g^{-1}(x)}$$
Or, more generally, if $g(x)=f_1\circ ... \circ f_n (x)$,
$$g^{-1}(x) \neq f_1^{-1}\circ ... \circ f_n^{-1}(x).$$

A: Sure:
$$\arctan1=\frac\pi4\neq\frac{\cfrac\pi2}{0}=\frac{\arcsin 1}{\arccos 1}$$

A: Counterexamples are useful, but knowing how to derive the inverse is also useful!
Suppose $$y= \tan(x).$$
Then try to solve for x:
$$y^2 = \tan^2(x) = sec^2(x)-1,$$
so $$cos^2(x) = \frac{1}{y^2+1},$$
$$\implies \cos(x) = \pm\sqrt{ \frac{1}{y^2+1}}.$$
Thus
$$\arctan(y) = \arccos\left(\pm\sqrt{\frac{1}{y^2+1}}\right)$$

A: The functions $f(x)=\arctan(x)$ and $g(x)=\frac{\arcsin(x)}{\arccos(x)}$ are different for several reasons:

*

*As mentioned in other answers, they take different values at many points. For example, $f(1)=\frac{\pi}{4}$ while $g(1)=\frac{\pi/2}{0}$ is undefined.

*They have different domains: the domain of $\arctan$ is $\mathbb R$ while the domain of $\arcsin$ and $\arccos$ is $[-1,1]$, so the domain of $g$ is included in $[-1,1]$. Precisely, since $\arccos(x)=0 \iff x=1$ the domain of $g$ is $[-1,1)$.

*The function $\arctan$ is odd, while $g$ is not. Indeed, since $\arcsin$ is odd, $f=g$ would imply that $\arccos(x)=\arcsin(x)\arctan(x)$ is even, which is known to be false.

Of course, one of these arguments is sufficient in itself.

A: comment..It holds for very small values of argument.
If we take a power operation
$$ z=\frac{x}{y}$$
then
$$ z^p=\frac{x^p}{y^p}$$
holds.
But then that is as far as it goes.
not (even) for
$$ arctan z = \frac{arctan x}{ arctan y} $$
or other operations.


text:
Q: @PathVariable containing backslash quote returns 400 Bad Request If you run this simple RestController with Spring Boot (2.5.3):
@RestController
public class SampleRestController {

    @GetMapping("/search/{criteria}")
    public String hello(@PathVariable(name = "criteria") String criteria) {
        return "Hello: " + criteria;
    }

}

And try to open this link in your browser:
 http://localhost:8080/search/%22%5C%22bug%5C%22%22

Then you will get "400 Bad Request", returned by the embedded Tomcat.
I don't understand, is this a bug in Tomcat ? Is this not a valid URL ?
EDIT: As per some of the replies: I went step-by-step through the Tomcat 9.0.50 source-code and saw the line about ALLOW_BACKSLASH.
And neither of the values true or false is good for me, because with true it replaced \ with / and with false it returns 400 Bad Request.
What I needed was to allow backslash without replacing it with slash.
My question is really whether this is a bug in Tomcat, since for me the URL seems to be valid. I am not technically putting a \ into the URL, I am putting a %-encoded backslash. What is the purpose of the %-encoding if not to allow the user to send any character in the URL ?

A: Refer to Piotr P. Karwasz comments above for better explanation.
The tomcat version correspond to Spring Boot (2.5.3) is 9.0.50.
By checking the source code of CoyoteAdaptor and Tomcat System parameter documentation, the url checking is configured by a flag ALLOW_BACKSLASH through System Property org.apache.catalina.connector.CoyoteAdapter.ALLOW_BACKSLASH, with false as default value.
...
    protected static final boolean ALLOW_BACKSLASH =
        Boolean.parseBoolean(System.getProperty("org.apache.catalina.connector.CoyoteAdapter.ALLOW_BACKSLASH", "false"));

...

To allow backslash in the URL, we can add below when running the application.
-Dorg.apache.catalina.connector.CoyoteAdapter.ALLOW_BACKSLASH=true

This property is replaced after tomcat 10.0.0-M4.

Remove org.apache.catalina.connector.CoyoteAdapter.ALLOW_BACKSLASH system property, replaced by the allowBackslash attribute on the Connector. (remm)

A: Yes it seems like an invalid URL, you also get an error by Spring Boot refering to RFC 7230 and RFC 3986 specifications.
But you could use some query parameter to avoid this error, e.g.:
@GetMapping("/search")
public String hello(@RequestParam(name = "criteria", required = false) String criteria) {
    return "Hello: " + criteria;
}

And call it like:
http://localhost:8080/search?criteria=%22%5C%22bug%5C%22%22

A: While samabcde's answer provides a solution for your problem, let me answer to your more general questions:

*

*your URL is perfectly valid although RFC 3986, section 7.3 allows some restriction to be imposed for security reasons,

*these restrictions are not a Tomcat bug, as they were introduced as an answer to CVE-2007-0450. Before Tomcat 6.0.10 the sequences /, %2F and %5C were used to split the request URI into components. If Tomcat was behind a proxy that forwarded only an application (let's say /app), you could use /app/%5C../manager/html to access Tomcat Manager.

If you set org.apache.catalina.connector.CoyoteAdapter.ALLOW_BACKSLASH=true you expose your system to the aforementioned vulnerability and all %5C sequences will appear as / in the servletPath and pathInfo ServletRequest properties. Since the requestURI property contains the undecoded URI path (cf. this question) your example will work.


text:
Q: How to build somewhat complicated recyclerview layout without ugly codes?  The picture above is what I am building, and I have already finish the default layout. I am using GridLayoutManager with a simple formula(position - 3 * (position / 3)) + switch to calculate the span of each cell, and then the adapter also calls the same formula to get the result accordingly to use the correct layout file: 1:1 or 16:9 (using ConstraintLayout + ImageView). There is also a ItemDecoration to add 4dp of white space between each cell.
Now when I start to build the smallest width = 600 configuration, some problem occur: since there is a small margin between each elements, the size of the wider one is actually slightly narrower than 2:1, which means the wider cell will be slightly taller than the 1:1 cell. For example, the perfect ratio of the wider cell in 600dp should be 398:198 when there is a 4dp margin between the 2 images.
I know that I can always just merge multiple layout files into 1 to make sure each row will share the same height, but since I would like to continue to add more configurations, the code will probably become super messy at the end. So my question is:
1) Is it possible to do it with GridLayoutManager? If yes, how?
2) Even if GridLayoutManager can do the job, is there any better method to do that? A custom LayoutManager maybe?

A: Yes you can do this with GridLayoutManager but its complicated. Android provides StaggeredGridLayoutManager to implement such type of views. It makes easy to implement with recyclerview.
   StaggeredGridLayoutManager  mLayoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
            yourRecyclerView.setLayoutManager(mLayoutManager);
//set adapter to recyclerview

For example
https://android--code.blogspot.in/2015/12/android-recyclerview.html
Official docs:
https://developer.android.com/reference/android/support/v7/widget/StaggeredGridLayoutManager.html

A: Ahhh of course there's already a library that does that: https://github.com/Arasthel/SpannedGridLayoutManager
Still trying it out but so far it seems to do exactly what I need to do!


text:
Q: Kotlin: Create custom CoroutineContext I'm using Kotlin in my API backend. I don't want to run db queries in the common pool. Basically, I want to create a CoroutineContext that has a number of threads that matches the database maximumPoolSize.
What's the best way to accomplish this (generally and for my specific use case)? I know Kotlin provides contexts out of the box, but what's the best approach to create my own?
Bonus question: If I have a jdbc connection pool size of 3, does it make sense to use a coroutinecontext with a thread pool size of 3? Can this guarantee the best concurrency possible?

A: The function newFixedThreadPoolContext is now considered obsolete with current version of Kotlin coroutines (1.3.0), as it is now annotated with @ObsoleteCoroutinesApi and it will give you a warning if you would try to use. The documentation also states that it will be replaced in the future.
The recommended way to create a CoroutineContext is now through
Executors.newFixedThreadPool(3).asCoroutineDispatcher()

So a complete example with imports, where also creating a CoroutineScope, would look like this
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.asCoroutineDispatcher
import java.util.concurrent.Executors
import kotlin.coroutines.CoroutineContext

fun coroutineScope(threads: Int): CoroutineScope {
    val context: CoroutineContext = Executors.newFixedThreadPool(threads).asCoroutineDispatcher()
    return CoroutineScope(context)
}

A: You can create a CoroutineContext that's backed by a thread pool with a fixed number of threads using newFixedThreadPoolContext:
val myContext = newFixedThreadPoolContext(nThreads = 3, name = "My JDBC context")

And yes, it seems like a good idea to match your thread pool's size to the connection pool's size, because that way your threads (assuming they each use one connection at a time) will always have a database connection ready for them - here's a blog post suggesting the same.

A: The answer by zsmb13 works perfectly, but Android Studio warns that newFixedThreadPoolContext is a delicate API and should only be used in specific cases.
The recommended alternative (as of Spring 2022) for limited parallelism is limitedParallelism:
Creates a view of the current dispatcher that limits the parallelism to the given value. The resulting view uses the original dispatcher for execution, but with the guarantee that no more than parallelism coroutines are executed at the same time.
This method does not impose restrictions on the number of views or the total sum of parallelism values, each view controls its own parallelism independently with the guarantee that the effective parallelism of all views cannot exceed the actual parallelism of the original dispatcher.

(from https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-dispatcher/limited-parallelism.html)
So an alternative solution would be to create a view on the thread pool used for the db connection like:
val dbDispatcher = Dispatchers.IO.limitedParallelism(maximumPoolSize)

and then use this as coroutine dispatcher.


text:
Q: Form of isomorphisms between subgroups of GLn Suppose that I've been given two subgroups of the general linear group (over the real numbers), which are isomorphic. From this information alone, can I deduce the form of the isomorphism? I suspect that there should be an invertible matrix $S$ such that each matrix $A$ gets mapped to $S^{-1}AS$. Is that correct? How could I prove it?
Since the original question has been answered, I like to rephrase it a bit: Suppose the subgroups are in fact Lie groups. Under which conditions on the subgroups is my conclusion valid?

A: I'm afraid this is false.
A mapping of the form $A\mapsto S^{-1}AS$ will give the identity mapping on the sets of determinants of the elements of the group. This alone gives us the following two counterexamples:
Let $G$ be the subgroup of $GL_2(\mathbf{R})$ generated by the matrix $\pmatrix{2&0\cr0&1\cr}$, and let $H$ be the subgroup generated by the matrix $\pmatrix{1&0\cr1&1\cr}$. Both are infinite cyclic groups, so they are isomorphic. However, the determinants of all the matrices in $H$ are equal to one, but the determinants of the elements of $G$ are of the form $2^n, n\in\mathbf{Z}$.
Things won't improve, if we restrict ourselves to finite groups. Either one of the matrices
$\pmatrix{-1&0\cr0&-1\cr}$ or $\pmatrix{-1&0\cr0&1\cr}$ will generate a cyclic group of order 2. But $-1$ is a determinant of only the latter group.
There are counterexamples even of such finite groups that have the same multiset of determinants. If a finite group has two non-isomorphic faithful real representations of the same dimension, then with a little bit of luck the multisets of determinants (consisting obviously of $\pm1$:s only) are equal, and we are done. The first example that comes to mind is the cyclic group of order 4. Either
$$
\pmatrix{0&1&0&0\cr-1&0&0&0\cr0&0&1&0\cr0&0&0&1\cr}\quad \text{or}\quad
\pmatrix{0&1&0&0\cr-1&0&0&0\cr0&0&0&1\cr0&0&-1&0\cr}
$$
will generate such a group, so they are isomorphic. This time the determinants are all ones. However, the multisets of traces differ. Recall that $tr(S^{-1}AS)=tr(A)$.
Here the traces of the elements of the group generated by the first matrix are $4,2,0,2$ and those of the group generated by the second matrix are $4,0,-4,0$, so no isomorphism of the prescribed type can exist.

Only if the groups have the property that even the traces of the matrices match up under the isomorphism (elementwise, i.e. the matrices paired up by the isomorphism have the same trace), then representation theory of finite groups promises the kind of isomorphism that you are looking for. Edit: the presence of outer automorphisms may kill this argument. Striking it for now.


text:
Q: Echo term slug op post on archive page I want to echo the term slug for each post on an archive page.
To get the term slug i'm using the following code:
$terms = get_the_terms( get_the_ID(), 'type_kennisbank' );

That returns me the data that I want:
array(1) { [0]=> object(WP_Term)#18648 (11) { ["term_id"]=> int(28) ["name"]=>
string(10) "Whitepaper" ["slug"]=> string(10) "whitepaper" ["term_group"]=>
int(0) ["term_taxonomy_id"]=> int(28) ["taxonomy"]=> string(15)
"type_kennisbank" ["description"]=> string(0) "" ["parent"]=> int(0)
["count"]=> int(3) ["filter"]=> string(3) "raw" ["term_order"]=> string(1) "0" } }

If I want to echo the slug I'm using:
echo $terms["slug"]

However it returns nothing. I already found a solution to echo the term slug but I'm wondering why my own echo code doesn't return the slug.
Anyone who can explain this?

A: The get_the_terms function returns array of WP_Term objects.
So you need to use something like this to echo a single term slug:
echo $terms[0]->slug;

Also be aware of results of this function. As documentation says it returns:

Array of WP_Term objects on success, false if there are no terms or the post does not exist, WP_Error on failure.

So you need some checks before trying to echo terms. The following code may help you.
$terms = get_the_terms( get_the_ID(), 'type_kennisbank' );

if ( $terms && ! is_wp_error( $terms ) ) {
    foreach ( $terms as $term ) {
        echo $term->slug;
    }
}


text:
Q: Which STL container for ordered data with key-based access? Let's say I have a collection of Person objects, each of which looks like this:
class Person
{
  string Name;
  string UniqueID;
}

Now, the objects must be stored in a container which allows me to order them so that I can given item X easily locate item X+1 and X-1.
However, I also need fast access based on the UniqueID, as the collection will be large and a linear search won't cut it.
My current 'solution' is to use a std::list in conjunction with a std::map. The list holds the Persons (for ordered access) and the map is used to map UniqueID to a reference to the list item. Updating the 'container' typically involves updating both map and list.
It works, but I feel there should be a smarter way of doing it, maybe boost:bimap.  Suggestions?
EDIT: There's some confusion about my requirement for "ordering". To explain, the objects are streamed in sequentially from a file, and the 'order' of items in the container should match the file order. The order is unrelated to the IDs.

A: boost:bimap is the most obvious choice. bimap is based on boost::multi_index, but bimap has simplified syntax. Personally I will prefer boost::multi_index over boost::bimap because it will allow to easily add more indices to the Person structure in the future.

A: There is no Standard Library container that does what you want - so you will have to use two containers or the Boost solution. If using two containers, I would normally prefer a vector or a deque over a list, in almost all circumstances.

A: Why not to use two maps , one having Person as Key and another one having UniqueId as Key, but that requires updating both of them.
you can create a callback function which updates both the maps whenever there is any change.


text:
Q: How to preselect first image swatch on Product detail page Magento 2 I want to preselect first available option for my configurable product on Magento 2(2.2.4) website.
Note: I am not a developer so when you answer plz reply with file path as well, I know i am asking so much but its really urgent and needed.
Thanks in Advance!

A: You have to copy the file swatch-renderer.js from

\vendor\magento\module-swatches\view\frontend\web\js

and put it in your theme folder like this:

app\design\frontend[THEME][THEME NAME]\Magento_Swatches\web\js\

and add few lines of code under the init function of this function line no. around 285
$.widget('mage.SwatchRenderer', {

so, the new init function should look like this. Note the custom code is inside the comment (custom script to select swatches automatically).
     /**
     * @private
     */
    _init: function () {
        if (_.isEmpty(this.options.jsonConfig.images)) {
            this.options.useAjax = true;
            // creates debounced variant of _LoadProductMedia()
            // to use it in events handlers instead of _LoadProductMedia()
            this._debouncedLoadProductMedia = _.debounce(this._LoadProductMedia.bind(this), 500);
        }

        if (this.options.jsonConfig !== '' && this.options.jsonSwatchConfig !== '') {
            // store unsorted attributes
            this.options.jsonConfig.mappedAttributes = _.clone(this.options.jsonConfig.attributes);
            this._sortAttributes();
            this._RenderControls();

            //custom script to select swatches automatically
            if($('body').hasClass('catalog-product-view')){
                if (this.options.jsonConfig.attributes.length > 0) {
                    var selectswatch = this.element.find('.' + this.options.classes.attributeClass + ' .' + this.options.classes.attributeOptionsWrapper);
                    $.each(selectswatch, function (index, item) {
                        var swatchOption = $(item).find('div.swatch-option').first();
                        if (swatchOption.length && !$(item).find('div.swatch-option').hasClass('selected')) {
                            swatchOption.trigger('click');
                        }
                    });
                }
                var $selectedId = $('.color div.swatch-attribute-options').find('.selected').attr('id');
                localStorage.setItem("selectedId", $selectedId);
            }
            // end of custom script
            this._setPreSelectedGallery();
            $(this.element).trigger('swatch.initialized');
        } else {
            console.log('SwatchRenderer: No input data received');
        }
        this.options.tierPriceTemplate = $(this.options.tierPriceTemplateSelector).html();
    }

It's working for me. Please try this and let me know if it works for you. Sorry for the late reply. I am seeing this query now only.


text:
Q: Tensorflow CPU RAM allocation I experience an incredibly high amount of (CPU) RAM usage with Tensorflow while about every variable is allocated on the GPU device, and all computation runs there. Even then, RAM usage exceeds the VRAM usage by a factor of 2 at least.  I'm trying to understand why so as to see if it can be remedied or if it's inevitable.
Question
So my main question is: Does Tensorflow allocate and maintain a copy of all GPU variables on (CPU) RAM? If yes, what is allocated when (in which phase, see below)? And why is it useful to allocate this in CPU memory?
More info
I have 3 phases in which I see RAM increasing dramatically.

*

*First, when defining the graph (I append VGG-19 with quite large loss functions that iterate over many translated activation maps). This adds 2 GB to RAM usage.

*Second, defining the optimizer (I use Adam) adds 250MB.

*Initialize global variables adds 750MB.

And then it remains stable and runs very fast (all on GPU).
(Amounts of data mentioned here are when I input tiny images of size 8x8x3, batch size of 1. If I do more than 1x16x16x3, the process gets killed because it overflows my 8GB RAM+6GB swap limit).
Note that I recorded variable placement with tf.ConfigProto(log_device_placement=True), and GPU usage using tf.RunMetadata and visualization on tensorboard.
Thank you for any help.
System information

*

*Have I written custom code (as opposed to using a stock example script provided in TensorFlow): Yes

*OS Platform and Distribution: Linux Ubuntu 17.10

*TensorFlow installed from (source or binary): binary

*TensorFlow version (use command below): 1.7

*Python version: 3.6.3

*GCC/Compiler version (if compiling from source): 6.4.0

*CUDA/cuDNN version: 9.0

*GPU model and memory: NVidia GeForce Titan Xp


text:
Q: Json object in C# .net I have a C#.net method as given below
 public string jsonTest()
        {
            List<string> list = new List<string>();
            list.Add("aa");
            list.Add("bb");
            list.Add("cc");
            string output = JsonConvert.SerializeObject(list);
            return output;
        }

Here eventhough Im creating a Json object by using JsonConvert.SerializeObject I am getting a string (since return type is string).
Can I do like below by using a return type JsonResult (or somthing like that) something like what we can do in MVC?
  return Json(new { data = list }, JsonRequestBehavior.AllowGet);

Is it possible to create a Json data in asp.net?
In client side I'm using an ajax call to get data from jsonTest().
  $.ajax({
                type: 'GET',
                url: "test.aspx",  //In test.aspx pageload calling jsonTest()
                dataType: 'json',
                success: function (data) {
                    alert(data);
                },
                error: function (data) {
                    alert("In error");
                }

            });

When I'm giving dataType: 'json', it will go to error part (Since the ajax expects json data but it gets string). Thats why I want to parse it as a json object in server side.

A: If ASP.NET,
string output = JsonConvert.SerializeObject(list);
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(output);
Response.End();

A: There is nothing called a JSON object. The SerializeObject method returns a string because JSON is nothing more than a string value which follows specific rules.
To return JSON to the browser all you need to do is:
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonTest());
Response.End();

A: I'm going to assume you're trying to create a WebMethod for consumption by a JavaScript XHR call or similiar:
ASP.NET will auto-serialize to JSON for POST requests only (using ASMX or so called "Page Methods"). WCF and WebAPI do not require the POST method, but do require some configuration.
[WebMethod]
public static List<Task> TasksGet(string projectId) {
    return MyNamespace.Tasks.GetForProject(projectId);
}

The result your JS call sees would be something like:
{"d": [{
     "__type": "MyNamespace.Task",
     "id": 1,
     "description": "This is my first task"
   }, {
     "__type": "MyNamespace.Task",
     "id": 2,
     "description": "This is my second task"
   }, {
     ....etc etc
   }
]}

No need to mess around w/ the JsonSerializer class directly.
Also make sure your request headers are set correctly:
Content-Accept: application/json;charset=UTF8

A: Json is just string data. It is how that string is interpreted. So the fact that it is returning a string is correct. You mentioned ASP.Net. Are you using ASP.Net webforms and looking for a way to return that JSON to the front side?


text:
Q: From {{a,b},{c,d}}, {1,2} to {{1,a},{1,b},{2,c},{2,d}} . How? Imagine I have these two lists {{a,b},{c,d}}, {1,2},  and I want to produce {{1,a},{1,b},{2,c},{2,d}}.
The problem is that I have big lists, and doing this element by element is too time consuming. I was wondering if I could 'rewrite' this operation by some other in-built mathematica functions.
I was thinking of something like MapIndexed[Tuples, {{a, b}, {c, d}}], but it doesn't work since Tuples receives {a,b},{1} instead of {{a,b},{1}}...
Any help would be appreciated.

A: Thread /@ Thread[{{1, 2}, {{a, b}, {c, d}}}]

But please post a more general example so I could post a better solution, since this might not be enough for your bigger problem.

A: Try this:
    f[{x_, y_}, z_] := {{z, x}, {z, y}};
    Flatten[MapThread[f, {{{a, b}, {c, d}}, {1, 2}}], 1]

  (*   {{1, a}, {1, b}, {2, c}, {2, d}}  *)

Have fun!


text:
Q: ERROR ITMS- 90035 invalid signature I am trying  to upload ipa on apple store but it's giving me "ERROR ITMS- 90035 invalid signature" error.
I have followed below process.
The first step in setting up a distribution profile is to create a certificate signing request. You can do this on your Mac. Launch the Keychain Access.app that is stored in Applications/Utilities.
Then execute the following steps in yourKeychain Access application:

*

*Select Preferences > Certificates and ensure that Online Certificates Status
Protocol (OSCP) and Certificate Revocation List (CRL) are set to Off.

*Select Keychain Access > Certificate Assistant > Request a Certificate From a
Certificate Authority... and ensure that you do not have any of your certificates
highlighted, otherwise the Provisioning Portal will not accept your certificate request.

*Enter your valid e-mail address in the User Email Address field. Ensure that the e-mail
address is the same as the one you used when you registered as an iOS Developer.

*Enter your name in the Common Name field. Ensure that the name you enter is the
same as the one you used when you registered as an iOS Developer.

*A CA Email Address is not required.

*Select the Save to disk radio button and tick Let me specify key pair information,
if it is present.

*Press Continue.

*A dialog appears that allows you to specify where you would like the certificate signing
request to be stored.
Specify a location and select Save.

*Press Continue.

*The certificate is then generated and written to the file you specified under step 8.
After you have generated a certificate signing request, you need to submit your certificate for approval.
Log into the iOS Provisioning Portal that is accessible from:
https://developer.apple.com/account/ios/certificate/certificateList.action.
This link takes you directly to the Certificates, Identifiers & Profiles section of your iOs developer account. Select the "Production" tab and follow these steps:

*

*Select the Add Certificate button.

*Select "App Store and Ad Hoc" as type then press continue

*On next screen press "Continue"

*On next screen select "Choose File" and select the certificate you created in previous step and then press "Generate"
Remain on the same page as the one you were on when you submitted the certificate signing request, then follow these steps to download and install the certificate:

*Download Generated certificate by clicking the "Download" button.

*Double click the downloaded certificate to install (alternatively drag to the keychain utility)
It is important that you backup the keys you created. This allows you to develop on multiple Macs or reinstall the keys after unexpected data loss.
You can export your private keys and certificates through the Keychain Access application:

*

*Open the application Keychain Access.app that is stored in Applications/Utilities.

*Select Keys.

*Highlight the private key associated with the distribution certificate.

*Select File > Export Items.

*A window opens that allows you to specify where you would like to save your certificate.

*Select Personal Information Exchange (.p12) as file format.

*Select the file name.

*Select Save.

*You are prompted for passwords that allow you to access the key in the future
This is the final stage and will create the distribution provisioning profile you need to use when building your iOS standalone.
Start by selecting the "Distribution" tab from "Provisioning Profiles"-

*

*Select New Profile (+)

*Select App Store as the Distribution Method.

*Enter the Profile name.

*Ensure that your Distribution Certificate has been created and is displayed correctly.

*Select the appropriate App ID for your applicatoin

*Select Generate.

*Select the Download button from next to the Distribution Provisioning Profile you created.
This allows you to download the .mobileprovision file.

*Double click the .mobileprovision install the Distribution Provisioning Profile on your computer.

This is the process I am using to generate ipa. Then I want to upload this ipa with application loader , But it's giving me signing code error. Please see attached screenshot .
Please help.
enter image description here

A: There are several reason for such type of error comes.
First of all you need to refer this Troubleshooting Failed Signature Verification
After above guide, you need to check all steps which write in the images like .
1) Make sure you have signed your application with distribution certificate not adhoc or development certificate.
please check what certificate you have used? follow this link
How to tell what profile/signing certificate was used to sign .ipa?
or this link also helpful for you
Maintaining certificate
2) you need to check your codesigning portion(=>provisioning profile) that all certificate selected correctly or not and also check bundle identifier in plist.

Note:- you need to set it at both place -> project and -> target

and at last last check that in all process you have selected [IOS Device] in place of [Simulator]
to check full process please check Submitting an App to the iOS App Store (Xcode) this video.

A: I had emojis in some filenames in a React Native app. After removing emojis now everything works.


text:
Q: Installing WAP 2 for student access with Wireless laptops I want students that have domain user accounts to be able to bring their laptops to school.  I have setup a radius IAS and created a self signed cert.  I have chosen to allow domain users to have access.  Does this mean that the student laptops must be part of the domain?  Or am I missing something.

A: No, the laptops don't have to be part of the domain.  The credential will be supplied when they try to access the service (WAP).  If you have it tied into LDAP or AD, then they supply their domain credentials, and will be given access to the resource.  http://en.wikipedia.org/wiki/RADIUS.


text:
Q: Transform an object into a context in Javascript I have an Object like this:
var context = {
  "myBoolean" : true,
  "myNumber" : 5,
  "myObject" : {
    "attr1" : "value1"
  }
}

I have a String which is a condition:
var condition = "myBoolean == true && myNumber > 3 && myObject.attr1 == 'value1'"

I want to eval the String condition with myBoolean, myNumber, myObject taking their values inside context.
I was close to an answer with these lines :
eval("function doTest() { return " + condition + ";};"
    + "var answer = doTest.apply(context);");

But I need to add this. in front of my variable name. So it's not exactly what I want to do.
I know this doesn't sounds very nice/secure to do something like this, but I think an answer coule be interesting.

A: The with statement does exactly this, appending an object to your scope:
var condition = "myBoolean == true && myNumber > 3 && myObject.attr1 == 'value1'"
var doTest = new Function("context", "with(context){ return "+condition+"; }");
var answer = doTest({
  "myBoolean" : true,
  "myNumber" : 5,
  "myObject" : {
    "attr1" : "value1"
  }
});

Notice that with and eval (or Function) are known for their bad performance, but it seems this is just what you need here.


text:
Q: expectation of number of exactly 3 heads flip in a row lets say I have 400 coin tosses and a probability P for head.
$\{ x_n \}$ the tosses,then X is a random variable which X = {number of times which there where exactly 3 heads}
how can I calculate E[x] and Var[x]?
I tried to get to the solution through recursion by choose where the first 3 exactly heads will be but with no luck.
k=400 ,
P(X=n) = F(n,k) = F(n-1,k-4)+F(n-1,k-5)+F(n-1,k-6)+F(n-1,k-7)