text:
Q: Migrating from jersey to spring boot: manually create security context Trying to migrate implementation from Java EE to spring boot.
In EE implementation we had a filter in which we read the request headers and create a security context. That context was injected in other parts of application:
public class DefaultSecurityFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext ctx) throws IOException {
        final String user = ctx.getHeaderString("app-user");
        if (null == user) {
            return;
        }
        Principal principal = () -> user;
        SecurityContext security = new SecurityContextWrapper(principal, ctx.getSecurityContext());
        ctx.setSecurityContext(security);
    }

    private static class SecurityContextWrapper implements SecurityContext {

        private Principal principal;

        private SecurityContext ctx;

        //constructors and setter removed for brevity
    }
}

In the resource we would inject the security context and use it as following:
@Context
private SecurityContext securityContext;

String userName = securityContext.getUserPrincipal().getName()

What is the equivalence for the same logic in Spring?


text:
Q: How to create a simple left outer join in lambda expression in EF ASP.NET MVC5 I searched hours and hours for this without any luck. I'm trying to create a lambda expression to fetch data from two tables Schedule and Request. But i'm outputting a bool here. How can i do a proper left outer join to fix this?
this is the best i could come up with
ViewBag.RequestList = db.Requests
    .Include(r => r.Department)
    .Select(r => db.Schedules.Any(s => s.RequestId == r.RequestId));

but its a bool not a list.
Assume my table models are as follows
public class Request{
 public virtual int RequestId { get; set; }
 public virtual string Remarks { get; set; }
}

public class Schedule{
 public virtual int ScheduleId{ get; set; }
 public virtual string Name{ get; set; }
 public virtual Request Request { get; set; }
}

I'm trying to see if each and every request has one or more schedules associated with it or not. so if i could attach schedule object to request and output it as a list then thats all i need.
But I want to do it using LINQ and lambda expressions and I've seen queries as below;
var leftList = (from emp in db.Requests
                join d in db.Schedules
                on emp.RequestId equals d.RequestId into output
                from j in output.DefaultIfEmpty()
                select new { RequestId = emp.RequestId,
                             name = emp.Department.Name,
                             route = emp.Route.Name });

But that's not what i want, because i have to specify every field i need in new { RequestId = emp.RequestId, name = emp.Department.Name, route = emp.Route.Name }
Thanks a lot!

A: just list what you want like this:
          var leftList =    from emp in db.Requests
                            join d in db.Schedules
                            on emp.RequestId equals d.RequestId into output
                            from j in output.DefaultIfEmpty()
                            select new
                            {
                               RequestId = emp.RequestId,
                               name = emp.Department.Name,
                               route = emp.Route.Name,
                               ScheduleId=j==null?0:j.ScheduleId,
                               SName=j==null?""j.Name,
                            };

redpajama_set_name: RedPajamaStackExchange


text:
Q: cant float things without interrapting eachothers

*{
    font-family: arial;
}
body{
    margin: 0;
    width: 100%;
    height: 100%;
}
.nav{
    background-color: maroon;
    width: 14%;
    height: 100%;
    float: left;

}
.body{
    background-color: cadetblue;
    width: 66%;
    height: 100%;

}
.login{
    background-color: maroon;
    width: 20%;
    height: 100%;
    float: right;
}
<!DOCTYPE html>

        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="csspart.css">

nav

body

login

I have a problem with floating a 100% height and navbar to left and a 100% sign up div to the right and body between them. i tried some position 's but I believe missing something with positioning. hope somebody knows what I miss.

A: Use float: left on all your 3 div's and change this rule
html, body {
  margin: 0;
  height: 100%;
}

Sample snippet

*{
  font-family: arial;
}
html, body {
  margin: 0;
  height: 100%;
}
.nav{
  background-color: maroon;
  width: 14%;
  height: 100%;
  float: left;

}
.body{
  background-color: cadetblue;
  width: 66%;
  height: 100%;
  float:left;

}
.login{
  background-color: maroon;
  width: 20%;
  height: 100%;
  float:left;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="csspart.css">

If you want to add for example a footer, do like this, using a wrapper, which as well clear the float

*{
  font-family: arial;
}
html, body {
  margin: 0;
  height: 100%;
}
.wrap{
  height: 100%;
}
.wrap:after{
  content: ' ';
  display: table;
  clear: both;
}
.nav{
  background-color: maroon;
  width: 14%;
  height: 100%;
  float: left;
  word-break: break-word;
  padding: 10px;
  box-sizing: border-box;        /* when use padding/border this is needed or else the     */
}                                /* width has to be changed to keep its total size of 14%  */
.body{
  background-color: cadetblue;
  width: 66%;
  height: 100%;
  float:left;

}
.login{
  background-color: maroon;
  width: 20%;
  height: 100%;
  float:left;
}
.footer{
  background-color: green;
  height: 50px;
}

Blablablablablabla bla bla bla bla bla bla bla bla bla bla bla

Now, for equal column size beyond the viewport, float isn't a good choice anymore, flex is, so here is a more practical solution.

*{
  font-family: arial;
}
html, body {
  margin: 0;
  height: 100%;
}
.wrap{
  min-height: 100%;
  display: flex;
}
.nav{
  background-color: maroon;
  width: 14%;
  word-break: break-word;
  padding: 10px;
  box-sizing: border-box;        /* when use padding/border this is needed or else the     */
}                                /* width has to be changed to keep its total size of 14%  */
.body{
  background-color: cadetblue;
  width: 66%;
}
.login{
  background-color: maroon;
  width: 20%;
}
.footer{
  background-color: green;
  height: 50px;
}

Blablablablablabla bla bla bla bla bla bla bla bla bla bla bla

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content last

If you can't use flex, use display: table

*{
  font-family: arial;
}
html, body {
  margin: 0;
  height: 100%;
}
.wrap{
  min-height: 100%;
  width: 100%;
  display: table;
}
.nav{
  display: table-cell;
  background-color: maroon;
  width: 14%;
  word-break: break-word;
  padding: 10px;
  box-sizing: border-box;        /* when use padding/border this is needed or else the     */
}                                /* width has to be changed to keep its total size of 14%  */
.body{
  display: table-cell;
  background-color: cadetblue;
  width: 66%;
}
.login{
  display: table-cell;
  background-color: maroon;
  width: 20%;
}
.footer{
  background-color: green;
  height: 50px;
}

Blablablablablabla bla bla bla bla bla bla bla bla bla bla bla

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content

 Content last


text:
Q: vuejs select default option does not work I have a json data that i've been loading into the <select>
This is a sample json data that I have:
let plans = [{id: 20, name: "test", default: 0},
{id: 19, name: "haha", default: 0},
{id: 18, name: "okok", default: 1}];

This is my select html/vue.
<select id="plans" class="form-control" v-model="company.plan_id">
    <option v-for="plan in plans" :value="plan.id" :selected="plan.default">{{plan.name}}</option>
</select>

It seems it doesn't select the "okok" value even if the default is 1.
Those plans data are coming from my database which is loaded using ajax.
I'm new to VueJS, any help is greatly appreciated!
Thanks.

A: selected attribute no longer makes sense when you using v-model.

A: You can't use selected attribute if you are using v-model on the <select>, Set the v-model value to the default value instead:
<template>
  <div id="app">
    <select id="plans" class="form-control" v-model="company.plan_id">
      <option v-for="plan in plans" :value="plan.id" :key="plan.id" :selected="plan.default">{{plan.name}}</option>
    </select>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      company: {
        plan_id: 18
      },
      plans: [
        { id: 20, name: "test" },
        { id: 19, name: "haha" },
        { id: 18, name: "okok" }
      ]
    };
  }
};
</script>

Demo here: https://codesandbox.io/s/beautiful-sound-gxmzu?file=/src/App.vue


text:
Q: Zend Framework Routing with additional page-param i have a blog with a routing. In my ini it seems like this:
routes.quote.route = :id
routes.quote.defaults.module = default
routes.quote.defaults.controller = posts
routes.quote.defaults.action = single
routes.quote.reqs.id = \d+

Now i want to have a page parameter (for comments) additionally. I only got it by creating a sectond route like this:
routes.quotePage.route = :id/page/:page
routes.quotePage.defaults.module = default
routes.quotePage.defaults.controller = posts
routes.quotePage.defaults.action = single
routes.quotePage.reqs.id = \d+
routes.quotePage.reqs.page = \d+

I want to combine these two into one. How can i do this? the page-parameter should only be additional.
Thank You

A: use Zend_Controller_Router_Route_Regex like this :
routes.quote.route.type = "Zend_Controller_Router_Route_Regex"
routes.quote.route = posts/(\d+)/(\d+)
routes.quote.defaults.module = default
routes.quote.defaults.controller = posts
routes.quote.defaults.action = single
routes.quote.map.1 = "id"
routes.quote.map.1 = "page"

A: You can assign a defaul value to page parameter
routes.quotePage.route = :id/:page
routes.quotePage.defaults.module = default
routes.quotePage.defaults.controller = posts
routes.quotePage.defaults.action = single
routes.quotePage.defaults.page = 1
routes.quotePage.reqs.id = \d+
routes.quotePage.reqs.page = \d+

This will match both http://domain.com/1 and http://domain.com/1/page/1 or http://domain.com/1/page/2


text:
Q: Java GDAX Authenticated REST Request HTTP GET Error 400 I am trying to GET data from GDAX Exchange with an authenticated API request. I'm starting with a simple account balance check.
I've been tweaking my code for about 8 hours and can't seem to get anything other than a 400 response. Can anyone help me understand what I'm doing wrong?
https://docs.gdax.com/#authentication

All REST requests must contain the following headers:

*

*CB-ACCESS-KEY The api key as a string.

*CB-ACCESS-SIGN The base64-encoded signature (see Signing a Message).

*CB-ACCESS-TIMESTAMP A timestamp for your request.

*CB-ACCESS-PASSPHRASE The passphrase you specified when creating the    API key.

  All request bodies should have content type application/json and be
  valid JSON.

~

The CB-ACCESS-SIGN header is generated by creating a sha256 HMAC using
  the base64-decoded secret key on the prehash string timestamp + method
  + requestPath + body (where + represents string concatenation) and base64-encode the output. The timestamp value is the same as the
  CB-ACCESS-TIMESTAMP header.
The body is the request body string or omitted if there is no request
  body (typically for GET requests).
The method should be UPPER CASE.

~
private static JSONObject getAuthenticatedData() {
    try {

        String accessSign = getAccess();

        URL url = new URL("https://api.gdax.com/accounts");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/json");

        con.setRequestProperty("CB-ACCESS-KEY", "d281dc......");
        con.setRequestProperty("CB-ACCESS-SIGN", accessSign);
        con.setRequestProperty("CB-ACCESS-TIMESTAMP", ""+System.currentTimeMillis() / 1000L);
        con.setRequestProperty("CB-ACCESS-PASSPHRASE", "xxxxx.....");

        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);

        int status = con.getResponseCode();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer content = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        System.out.println(content);
        in.close();

        con.disconnect();

    }catch(Exception e) {
        e.printStackTrace();
    }
    return null;

}

~
public static String getAccess() {

    //Set the Secret
    String secret = "xxxxxxx........";
    //Build the PreHash
    String prehash = Instant.now().toEpochMilli()+"GET"+"/accounts";
    String hash = null;
    try {

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        hash = Base64.encodeBase64String(sha256_HMAC.doFinal(prehash.getBytes()));
        System.out.println(hash);
       }
       catch (Exception e){
           e.printStackTrace();
       }
    return hash;
}

A: You need to add request headers and request properties.
Here is and example of exactly what you are trying to do:
Create Signature
Create Headers

A: A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules.
So, something is wrong by your side. In official doc it is mentioned that you should request POST method but you have have request GET method.
 URL url = new URL("https://api.gdax.com/accounts");
 HttpURLConnection con = (HttpURLConnection) url.openConnection();
 con.setRequestMethod("POST");

Hope, this may help!


text:
Q: process HTML files using hadoop map reduce I have a input folder in hdfs which contain thousands of HTML files :
/data/htmls/1/(HTML files)
/data/htmls/2/(HTML files)
.
.
/data/htmls/n/(HTML files)

I have a java function which takes HTML file as input and parse it, I want to read these HTML files in mapper function and feed them as input to parser function. Because Input files are processed line by line by map function, is there a way to work with HTML file?

A: I'm not sure how well it would work, but the Mahout XmlInputFormat is a decent XML reader. You might be able to adapt that to working for HTML.
In the configuration set the following before creating the Job object:
conf.set("xmlinput.start", "<tag>");
conf.set("xmlinput.end", "</tag>");

Then set the input class by the following after creating a job object:
job.setInputFormatClass(XmlInputFormat.class);

This will select everything inside of the specified tag as a single input string.
for instance if you select <html> and </html> (or <body> </body> or any other matched pair of tags) as start and end tags you should get everything inside of that as a single record, passed to the mapper.
Hope this is helpful.


text:
Q: Selenium infinite scrolling an next page | Python my scrolling to the end of the page works, but i would like to follow the next pages too. I get the error:
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".Button__ButtonContainer-sc-3uaafx-0 .RVfyr .Pagination__PaginationButton-zvrf30-1 .iYAkvt"}
import time
from selenium import webdriver
from bs4 import BeautifulSoup
from urllib.parse import urljoin

##### Web scraper for infinite scrolling page #####
driver = webdriver.Chrome()
driver.get("https://www.willhaben.at/iad/gebrauchtwagen/motorrad/ktm-motorrad/790")
time.sleep(2)  # Allow 2 seconds for the web page to open
scroll_pause_time = 1 # You can set your own pause time. My laptop is a bit slow so I use 1 sec
screen_height = driver.execute_script("return window.screen.height;")   # get the screen height of
the web
i = 1

while True:
# scroll one screen height each time
driver.execute_script("window.scrollTo(0, {screen_height}*{i});".format(screen_height=screen_height,
i=i))
i += 1
time.sleep(scroll_pause_time)
# update scroll height each time after scrolled, as the scroll height can change after we scrolled
the page
scroll_height = driver.execute_script("return document.body.scrollHeight;")
# Break the loop when the height we need to scroll to is larger than the total scroll height
if (screen_height) * i > scroll_height:
    break

#Now locate the button & click on it
next_button = driver.find_element_by_class_name('Button__ButtonContainer-sc-3uaafx-0 .RVfyr
.Pagination__PaginationButton-zvrf30-1 .iYAkvt')
next_button.click()

.
##### Extract Datas #####
liste = []
doc = BeautifulSoup(driver.page_source, "html.parser")
for xxx in doc.select(".jjQHPt"):

titel = xxx.select_one(".HOCpr").text
baujahr = xxx.select_one(".eizLtD").text
kilometer = xxx.select(".eizLtD")[1].text
try:
    preis = xxx.select_one(".fiVXiu").text
except:
    preis = 'None'

print(titel)
print(preis)
print("Baujahr: " + baujahr)
print("Kilometer: " + kilometer + " km")
print()


text:
Q: How can we remove an attribute from the xml block in layout file in magento2? I need to remove the ttl attribute value from catalog.topnav block in default.xml file.
I have overrided the file in custom path as follows:

Magento_Theme/layout/default.xml

<referenceBlock name="catalog.topnav">
   <attribute name="ttl" value="" />
</referenceBlock>

Original block is as follows:
 <block class="Magento\Theme\Block\Html\Topmenu" name="catalog.topnav" template="Magento_Theme::html/topmenu.phtml" ttl="3600" before="-">

A: I have overrided the file in custom path as follows:

Magento_Theme/layout/default.xml

<referenceBlock name="catalog.topnav" remove="true"/>
<referenceBlock name="store.menu">
    <block class="Magento\Theme\Block\Html\Topmenu" name="catalog.topnav.without.ttl" template="Magento_Theme::html/topmenu.phtml" before="-"/>
</referenceBlock>

and override also the

Magento_Theme/layout/print.xml

<referenceBlock name="catalog.topnav.without.ttl" remove="true"/>

maybe it works for you too.

A: late but it works for me
   <referenceBlock name="catalog.topnav">
        <action method="unsetData">
            <argument name="key" xsi:type="string">ttl</argument>
        </action>
    </referenceBlock>


text:
Q: MongoDB - Mongoose : Aggregate generation, $match $group $project I'm newbie in the mongoDB world. I'm developping a website on nodeJS with expressJS and mongoose as DB.
I'm studying graphic orientation and I am generated a DB with this modele
:
var userSchema = new Schema({
    profile:{
        sexe:           String, // ('male' or 'female')
        age:            String, // ('kid', 'adult', 'old')
        rank:           String, // ('low', 'middle', 'high')
    },
    design:{
        luminosity:     String, // ('light', 'dark')
        color:          String, // ('blue', 'green', 'pink', 'orange')
        shape:          String, // ('rounded', 'squared')
        font:           String, // ('serif', 'sans serif')
    }
});

On different page, I want to display some statistics, for exemple, on the page luminosity, where user chooses between light or dark. I want to display him what people mostly pick.
For example, with the section sexe : what mostly pick female (68% of them choose light, for example).
I think the best way to get all the numbers to create the statistics is to use aggregate.
As newbie, it destroys my mind to generate the perfect query, I am really lost in this framework !
Would love your advice !

A: Your aggregation operation will be dependant on the $cond operator in the $group pipeline step to evaluate the counts based on the page luminosity and/or page color. Use the $sum accumulator operator to return the sum on each evaluated group, something like the following:
var pipeline = [
    {
        "$group": {
            "_id": "$profile.sexe",
            "light_count": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$design.luminosity", "light" ] }, 1, 0 ]
                }
            },
            "dark_count": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$design.luminosity", "dark" ] }, 1, 0 ]
                }
            },
            "blue_count": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$design.color", "blue" ] }, 1, 0 ]
                }
            },
            "green_count": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$design.color", "green" ] }, 1, 0 ]
                }
            },
            "pink_count": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$design.color", "pink" ] }, 1, 0 ]
                }
            },
            "orange_count": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$design.color", "orange" ] }, 1, 0 ]
                }
            }
        }
    },
    {
        "$project": {
            "_id": 0, "gender": "$_id",
            "luminosity": {
                "light": "$light_count",
                "dark": "$dark_count"
            },
            "color": {
                "blue": "$blue_count",
                "green": "$green_count",
                "pink": "$pink_count",
                "orange": "$orange_count"
            }
        }
    }
];

User.aggregate(pipeline)
    .exec(function (err, result){
        // handle error
        if (err) throw Error;
        console.log(result);
    })


text:
Q: delphi -> sql server query returns empty string but with correct length I have a Delphi program that connects to a sql server database hosted via LocalDB. In this program, I need to run the below query and get the contents of the "Value" field. When I run the query in SQL server, it returns "127.0.0.1" as expected. However, when I run the query from Delphi, it returns a string with the correct length, but mostly null data. In the case of the IP address, it (roughly) returns "#0#0#0#0''#0#0". What is more strange is the Key returns the correct value (defined in sql as nvarchar(128), not null) whereas the Value does not (defined in sql as nvarchar(MAX), null).
Here's my connection string (if relevant): Driver={SQL Server Native Client 11.0};Server=(localdb)\MSSQLLocalDB;Database=TestDb;Uid=dba;Pwd=sql;


text:
Q: Insomnia - HTTP POST method with request body having an integer I'm doing a POST method on insomnia with the following payload
{
    "tag_ids": [
        295
    ]
}

I'm receiving a status 400 bad request with the following error message
{
  "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 2 column 2 (char 3)"
}

When trying on curl I haven't had any issues and it is working as expected.
I'm wondering if it has something to do with the tag_ids being an integer in the request body, or if there is any settings I should change on the client for this to work.
Thanks

A: Looks like your json contains " character instead of " for the property name.
This should be the correct body:
{
    "tag_ids": [
        295
    ]
}


text:
Q: Orientation font problem in QGIS In some maps, the orientation font in the toolbar get messy( I work with Window 7 professional):

I tried to open a new project after i restart the computer- still it as not solved the problem.
I added those 2 pictures for the example, but it occurred also in all other toolbar. Even when i change the style into window (in option--> general) the problem still remain.

A: This looks very weird indeed!
Do you have any language settings that hints that anything should be presented as text reading "right to left" (i.e. Arabic or ...)? Look in the Project settings...
Can't really imagine this could be the only problem though.
Is it only QGIS, or other software as well?


text:
Q: Extracting sentences by matching dictionary words I have a lot of strings but contain words or phrases of interest. For example:
'I like the cherry blossoms when spring is here and I love to click photos for the same '
contains the words/phrases of interest  "cherry blossoms", "love" and "click ".
My job is to find out the sentences with the words/phrases of interest .And if possible score each string so that strings that are composed of two or more words/phrases get a better score than strings that have lower count.
Is this a job for recursive descent parsing, or is there a faster way to be doing this? For this task, I am willing to trade off a little speed for accuracy.
My dictionary is going to consist of about 250,000 words. I can store them on the disk in any fashion I want. Is there any kind of format (perhaps some db file format) that would lend itself well to the kind of lookups that I am going to need to be doing?
Is there a CPAN module that would be a good fit for me? Or is there a simple solution .
Thanks

A: Search for natural language processing (NLP) on cpan; e.g. Lingua::EN::*
Also search for 'bag of words' online/journals for an intro to the field.


text:
Q: I need clear view for dynamically ask "do you want to update your app" when app is opening I need clear view for dynamically ask "do you want to update your app" when android app is opening.
I am looking for yours help.....

A: According to my understanding of your question, this is what you can do:
Create a web service which returns latest App Version. Call that web service every time app gets open and check whether latest version is equal to app version or not. If not, you can show pop-up for app updation.
In web service, you can set latest version hard-coded and Android side, you can check installed app version by following property:
int currentVerion = android.os.Build.VERSION.SDK_INT

A: This how alert dialog is created. For update alert, You could run a web service check for any newest version and if new version available in your server and fire the alert dialog
AlertDialog.Builder alertDialog = new AlertDialog.Builder(yourActivity.this);

        // Setting Dialog Title
        alertDialog.setTitle("Confirm Delete...");

        // Setting Dialog Message
        alertDialog.setMessage("Are you sure you want delete this?");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.delete);

        // Setting Positive "Yes" Button
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {

            // Write your code here to invoke YES event
            Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
            }
        });

        // Setting Negative "NO" Button
        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            // Write your code here to invoke NO event
            Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();


text:
Q: Pandas to excel using XLSX Writer - Constant Memory/In Memory I am using pandas and xlsxwriter to create excel reports in AWS lambda. I have been having an issue where the disk space fills up when a reasonably large excel file in the region of 60MB is created, but there is 512MB of disk space available.
I have been trying to work out what and why this is happening and I came across a promising looking property I could pass, constant_memory, so I tried this out using the following code:
with pd.ExcelWriter(output, options={"constant_memory": True}) as writer:

It seems this actually ensures my lambda runs to completion consistently and if I remove it then it no longer does, but the issue is I get the following warning:
FutureWarning: Use of **kwargs is deprecated, use engine_kwargs instead.
    with pd.ExcelWriter(output, options={"constant_memory": True}) as writer:

I then read a post on SO, which I think is by the author of xlsxwriter suggesting this property doesn't actually work when using pandas. This is sort of evident in that I only get the first column in my excel report and the last row of 360000 rows. I am confused as to how passing this is ensuring my lambda completes0? And why is it that if I do not pass it then my lambda runs out of disk space?
The second strange thing is the documentation for pandas doesn't mention any argument called options at all, and if I try and pass constant_memory using engine_kwargs:
with pd.ExcelWriter(output, engine_kwargs={'constant_memory': True}) as writer:

I get the following error:
TypeError: __init__() got an unexpected keyword argument 'constant_memory'

I hope someone who is more familiar with xlsxwriter can help me out in understanding these few points.
The documentation for xlsxwriter also mentions a property in_memory, which seems like it could resolve my issue but I am unable to pass this to pd.ExcelWriter:
TypeError: __init__() got an unexpected keyword argument 'in_memory'

**Edit: Passing in_memory does actually solve the issues I have but I get a deprecation warning passing it in using the kwargs options.
with pd.ExcelWriter(output, options={"in_memory": True}) as writer:

FutureWarning: Use of **kwargs is deprecated, use engine_kwargs instead.
    with pd.ExcelWriter(output, options={"in_memory": True}) as writer:

How can I pass this property to the xlsxwriter using pandas without getting the deprecation warning as it seems to resolve my issues?

A: I'm not an expert, anyway, have you tried
pd.ExcelWriter(output, engine_kwargs={'options': {"constant_memory": True}})

?

A: The correct syntax to pass xlsxwriter options to Pandas when you get that deprecation notice is:
writer = pd.ExcelWriter('pandas_example.xlsx',
                        engine='xlsxwriter',
                        engine_kwargs={'options': {'strings_to_numbers': True}})

See this section of the XlsxWriter docs.
However, as you pointed our in your question, and from your observation, the constant_memory option won't work with Pandas since it requires data to be written in a row by row order but Pandas uses a column by column order.
But also, just to be clear, the constant_memory option will only reduce the "memory" used by your application. It won't make the size of the file smaller (in fact it generally makes the file bigger if it contains a lot of string data). It may only by "solving" your issue because it is only writing one column of data to the file, and thus the file is much smaller than intended.


text:
Q: Bind specific checkbox to disable specific dropdown in VueJS? I have a table, each row has a checkbox, name, another checkbox, and dropdown. I want to have the dropdown disabled by default, and only enable it when check the first checkbox.
Here's the HTML:

            <input type="checkbox" v-on:click="onSelect($event)" v-model="item.Selected" />

            {{ item.Name }}

            <input type="checkbox" v-model="item.isActive" /><

            <select v-bind:disabled="">
                <option value="foo">foo</option>
                <option value="bar">bar</option>
            </select>

Currently, the onSelect($event) method will check the second checkbox in the same row when checked.
Here's my JavaScript:
var vm = new Vue({
    el: '#app',
    data: {
        items: items
    },
    methods: {
        onSelect: function (event, id) {
            setTimeout(function () {
                var idx = $(event.target).closest('tr').index();
                if (items[idx].Selected) {
                    items[idx].isActive = true;
                }
            }, 100);
        }
    }
});

Is there a way to bind the enabling/disabling of the dropdown to a checkbox with VueJS 2/JavaScript/jQuery?

A: You don't actually need to use jQuery or events for this, rather you can simply use Vue's data binding for this. Simply set v-model="item.Selected" on the first checkbox, and then on the select, set v-bind:disabled="!item.Selected".
HTML:

          <input type="checkbox" v-model="item.Selected"/>

          {{ item.Name }}

          <select v-bind:disabled="!item.Selected">
            <option value="foo">foo</option>
            <option value="bar">bar</option>
          </select>

JavaScript:
// app.js
const vm = new Vue({
  el: '#app',
  data() {
    return {
      items: [
        { ID: 1, Name: 'name 1', isAcitve: false, Selected: false },
        { ID: 2, Name: 'name 2', isAcitve: false, Selected: false },
        { ID: 3, Name: 'name 3', isAcitve: false, Selected: false },
      ]
    }
  },
})

I've attached a pen which displays this.


text:
Q: From .NET developer to SharePoint developer - Can it happen? I am a .NET developer who builds web apps and I'm thinking of learning SharePoint 2010 and change my career to SharPOint development. Why? Because web development is widely focused and I never seem to be an expert in any one technology. There's just too much to learn. At least with SharePoint I can use my existing C# and database skills in one platform.
My question is this: Is it a good career move to focus on one platform such as SharePoint? I sure hope you say yes.

A:
Because web development is widely focused and I never seem to be an expert in any one technology. There's just too much to learn.

On the surface, SharePoint might look like a single platform, but at the heart of it you will need to know a lot more than what SharePoint is. Besides learning SharePoint, you will need to learn Business Intelligence, Active Directory, Exchange, WCF, WWF, Windows Identity, and list goes on. My point is that it is just not enough to learn SharePoint, you will need to learn many other technologies that SP interacts with.
A lot of people give up on SharePoint not because there is big learning curve, but simply because the development process is much more involved than ASP.NET (ex: deploying your solution). SharePoint is ASP.NET plus everything else out there (JQuery, SilverLight, Mobile, etc.). Almost anything you can imagine, there is a way to integrate with SharePoint.
My recommendation is to learn the basics of SharePoint, then specialize in one or two areas. For example, specialize in Enterprise Content Management and Business Intelligence. Each of those areas alone have a steep learning curve. Don't expect to become a SP expert in less than 2 yrs; it may take from 2 to 7 years. Having a good knowledge of ASP.NET, C#, SQL is a plus as well.
I would say yes to your answer if by "good career move" you mean higher salary and better job security.  The problem with many developers is that they get excited on a technology, for example, mobile development. They start learning it. Few months down the road, they lose interest in the technology and they start learning some other technology. As long as you focus on SharePoint and don't give up in the middle of the road (bumpy), you will be fine. :)
Focus, determination, and interest in SP is all you need :)

A: SharePoint is a .NET application on steroids. You can apply most of your .NET programming skills in SharePoint as well but you need to learn a lot new as well. I am sure you will enjoy the new challenges.

A: For what it's worth, I did the reverse. I started in SharePoint and found that I picked up .Net along the way. I guess it really depends. There is plenty to do in SharePoint alone that I feel it is not really going away anytime soon. The other thing to consider is what type of development you want to do and if you can get by with doing only out of the box development. I was doing a lot of .Net stuff in SharePoint and in my current spot it is all jQuery and SharePoint Designer type stuff! I like what I do yes, but still would like to write .Net code! Some places just do not allow that so you have to be careful! Just my 3.14 cents worth (bad pun indeed!)

A: Do it! Do it! Do it!
It's tough, there are concepts to wrap your head around, but once you nail it, it looks awesome on your resume. There is also an awesome community available for support, beginner through advanced techniques, you'll never be alone.
But as @Alexander said, I also have seen people come jumping in just to panic and run away. It can be complex, but once you can wrap your head around the big picture of SharePoint, it comes easier and easier.

A: Yes it's a good career move. If your career is in Enterprise Software.
But think of your long-term career. Always keep on top of latest .NET trends and experiment now and again on stuff that SharePoint doesn't use (like all the new stuff in .NET 4/4.5, and programming for Azure, for example). SharePoint won't be around forever (or, at least, it will evolve tremendously from what we currently know as SharePoint over the next 5 years, I reckon), but it can and will boost your longer term career prospects if you want to go further into Enterprise Software Architecture.

A: "There's just too much to learn."
If this is part of your criteria, do not go to SharePoint. SharePoint has a large learning curve and is a huge platform. I've been doing SharePoint development for five years and I am still investing lots of time to learn more.
The reason why the SharePoint developer market is so good is because a large percentage of the developer market won't invest the time to learn what they need to to become effective.

A: in my practice a lot of people leaved SharePoint development. Because this is a big and hard platform. You should learn many technologies and apply many practices. This platform does not fogive you your mistakes. Some times you should spend a lot of time to find the reason of exceptions that are throwed by code wich should works correctly. But after this platform you can work with any technology that you wish. So, go ahead!

A: SharePoint is very hot and at this point in time, you don't need a lot of experience to get a position in SharePoint, however like all the others suggested, make sure you are completely interested in SharePoint, don't get started than change in 1 or 2 yrs. Work your way up in SharePoint, learn the skills needed with it. We specialize in doing projects for SharePoint, and I am learning everyday something new on SharePoint.

A: I started SharePoint development 14 months ago, not because I wanted to, but because I needed to. SharePoint 2010 is replacing much of the bespoke technical solutions of 5, 10 years ago. Workflows, forms, security, document management, office integration, business intelligence: all these needs can (mostly) be fulfilled with SharePoint.
So, from a developer's perspective:

*

*fun, challenging technology,

*growing, expanding technology.

*in demand. recognized as a cost saver, relative to other start-from-scratch development option.

*industry standard-esque. If your team develops an application X, and that team leaves, there could be support concerns and loss of knowledge. If your team developed in SharePoint, and the team leaves, hire a SharePoint developer.

A: Of course it can happened. As far as I think that how it should happen. Most of the custom designing (especially custom web part, aspx pages, form pages, etc) done in .net (c#). you have to bring you upto speed on the SP classes. (which is not that complicated).
You may want to learn the End user interaction with SharePoint through UI first so you get a good feeling of what all are included.
Also, there are some stuff you can do through Central Admin CA so you can write powershell script to execute those operations.
Hope this helps.

A: As one who has taken the similar steps - I am enjoying it! The best-kept secret is that SharePoint is but an ASP.NET framework and almost everything (skills & code) carries over! I give presentations at Codecamp & SharePoint Saturdays based on the same topic -

*

*SharePoint 2010 Development with Visual Studio 2010 (SharePoint Saturday Online India - June 25 '11)

*SharePoint 2010 Development for .NET Developers (New England CodeCamp - Oct 31 '11)

*SharePoint Development with Visual Studio 11 (SharePoint Saturday Boston - Apr 28 '12)
UPDATE:
In addition to the .NET developer related skills (C#/SQL/ASP.Net), an additional skill that will benefit the SharePoint developer is knowing PowerShell. PowerShell is most useful for the administration, deployment & even some development with SharePoint and all developers need to have a certain level of SharePoint administration knowledge. Here are some useful links -

*

*Windows PowerShell for SharePoint Foundation 2010

*Windows PowerShell for SharePoint Server 2010 Administrators

*Powershell for sharePoint 2010 Tutorial


text:
Q: error MSB4064: The "OverwriteReadOnlyFiles" parameter is not supported by the "Copy" task I am using Msbuild 4.0. When i was using Msbuild 3.5 OverwriteReadonlyfiles worked without any issue.
But today when i was trying to use the copy task i am getting this issue.
error MSB4064:

The "OverwriteReadOnlyFiles" parameter is not supported
  by the "Copy" t ask. Verify the parameter exists on the task, and it
  is a settable public instance property.

This is my target which has copy task
<Target Name="CopyBOM">

    <Copy SourceFiles="@(BOM)" DestinationFolder="%(BOM.Destination)" OverwriteReadOnlyFiles="true">
      <Output TaskParameter="CopiedFiles" ItemName="CopyBOMFiles" />
    </Copy>

    <Message Text="Copied to BOM: @(CopyBOMFiles)"/>

  </Target>

Following is the itemgroup i am using in my properties file
 <BOM Include="..\..\..\Release\CoreDeployment.msi">
      <Destination>..\..\..\Core\BOM\Comp1</Destination>
 </BOM>

I am having multiple properties file, I have verified that in all the place Toolsversion=4.0 is placed.
Has any one faced this? Any way is there to solve this?

A: You are most likely dealing with a ToolsVersion issue, even though you say you've checked all your files and their imports.  Omitting the ToolsVersion from a file will cause it to drop to a lower version, so if all you did was search for "ToolsVersion" you may have missed a file where it wasn't declared on the <Project> node at all.
Run a command line build with diagnostic level logging, with the following additional parameters:
> msbuild My.proj /fl /flp:v=diag;logfile=My.proj.diagnostic.log

After the build fails, open the log file, seach for "MSB4064" then backtrack up the file looking for anything specifying the 2.0 framework.

A: I'm using OverwriteReadOnlyFiles="true" without issues. Try to add ToolsVersion="4.0" into your Project tag:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">


text:
Q: Validation in Ajax From This is my form in the view..
SendCall is the method in controller to sending email..
@using (Html.BeginForm("SendCall", "Home", FormMethod.Post, new { id = "email-form" }))
    {

Name
<input type="text" id="name" value=""/> *
 Email:
<input id="Email" type="text" />

<input type="submit" value="Submit" >
    }

This is the action code..
 [HttpPost]
        public ActionResult SendCall(string Date, string Phone, string Name, string Email)
        {
            string username = "xxxxxx@gmail.com";
            string password = "********";
            NetworkCredential loginInfo = new NetworkCredential(username, password);
            MailMessage msg = new MailMessage();
            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = loginInfo;

            string message =  Name + Email; //I have shortened this line.

            try
            {
                msg.From = new MailAddress("yourname@gmail.com", "My Website");
                msg.To.Add(new MailAddress("email@gmail.com"));
                msg.Subject = "Contact Message";
                msg.Body = message;
                msg.IsBodyHtml = true;

                smtpClient.Send(msg);
                return Content("Your message was sent successfully!");
            }
            catch (Exception)
            {
                return Content("There was an error... please try again.");
            }
        }

Can anyone suggest me how to validate this form? By adding some code in ajax code? I want client side validation and not with unobtrusive..


text:
Q: Geo-tagging in Android I am working on an Application that requires the user to be able to geo-tag picture taken via the camera. The application is to encourage user geo-tag trees to encourage afforestation and reduce global warming.
Is it possible to implement this feature and how can I implement it?
NB: This is my first major project.

A: Creating a comfortable user experience with location is a big task. These are some of the concerns you'll have to address:

*

*The user may have disabled location globally.

*The app may not have the permission to use location.

*You want to ask the user for permission and/or to enable location.

*You don't want to bother the user by asking over and over again.

*Asking for permission means pausing your activity in favor of a system activity that asks for permission. There's a similar but distinct mechanism to ask to enable the location.

*Your activity will resume when the user responds, you need to override a special callback method that receives the result.

*It's not good to try to fetch location just when you need it. It may take time. Instead you have to ask Android at the outset to push location updates to you.

*The user may revoke the location permission while using the app, you must constantly re-check the permissions, be resilient to sudden exceptions, and repeat the request to receive location updates when the location permission comes back.

Here are some snippets from my project that can help you get started:
private val Context.fusedLocationProviderClient get() = getFusedLocationProviderClient(this)

private suspend fun FusedLocationProviderClient.tryFetchLastLocation(): Location? =
    lastLocation.await()
        ?.also { info { "Got response from getLastLocation()" } }
        ?: run { warn { "getLastLocation() returned null" }; null }

suspend fun Context.canUseLocationFg() =
        appHasLocationPermission() &&
        locationSettingsException(locationRequestFg, locationRequestBg) == null

import android.Manifest.permission.ACCESS_FINE_LOCATION
import androidx.core.content.PermissionChecker.PERMISSION_GRANTED

fun Context.appHasLocationPermission() =
        checkSelfPermission(this, ACCESS_FINE_LOCATION) == PERMISSION_GRANTED

suspend fun Context.locationSettingsException(
        vararg locationRequests: LocationRequest
): ApiException? = try {
    getSettingsClient(this)
            .checkLocationSettings(LocationSettingsRequest.Builder()
                    .addAllLocationRequests(locationRequests.asList()).build())
            .await()
    null
} catch (e: ApiException) { e }

const val CODE_REQUEST_FINE_LOCATION = 13
const val CODE_RESOLVE_API_EXCEPTION = 14

suspend fun Fragment.checkAndCorrectPermissionsAndSettings() {
    with(context!!) {
        if (!appHasLocationPermission()) {
            warn { "FG: our app has no permission to access fine location" }
            delay(WAIT_MILLISECONDS_BEFORE_ASKING)
            if (!appHasLocationPermission()) {
                startIntentRequestLocationPermission()
                return
            }
        }
        if (locationSettingsException(locationRequestFg, locationRequestBg) == null) return
        warn { "FG: ResolvableApiException for location request (probably location disabled)" }
        if (!mainPrefs.shouldAskToEnableLocation) return
        delay(WAIT_MILLISECONDS_BEFORE_ASKING)
        locationSettingsException(locationRequestFg, locationRequestBg)
                ?.let { it as? ResolvableApiException }
                ?.also { startIntentResolveException(it) }
    }
}

fun Fragment.startIntentRequestLocationPermission() =
        requestPermissions(arrayOf(ACCESS_FINE_LOCATION), CODE_REQUEST_FINE_LOCATION)

fun Fragment.startIntentResolveException(e: ResolvableApiException) =
        startIntentSenderForResult(e.resolution.intentSender, CODE_RESOLVE_API_EXCEPTION, null, 0, 0, 0, null)

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    if (requestCode != CODE_REQUEST_FINE_LOCATION) return
    permissions.zip(grantResults.asList())
        .find { (perm, _) -> perm == ACCESS_FINE_LOCATION }
        ?.also { (_, result) ->
            if (result == PermissionChecker.PERMISSION_GRANTED) {
                info { "User has granted us the fine location permission" }
            } else {
                warn { "User hasn't granted us the fine location permission (grant result: ${grantResults[0]})" }
            }
        }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (requestCode != CODE_RESOLVE_API_EXCEPTION) return
    if (resultCode == Activity.RESULT_OK) {
        info { "ResolvableApiException is now resolved" }
    } else {
        warn { "ResolvableApiException resolution failed with code $resultCode" }
        activity!!.mainPrefs.applyUpdate { setShouldAskToEnableLocation(false) }
    }
}

val locationRequestFg = LocationRequest().apply {
    interval = 1000
    fastestInterval = 10
    priority = PRIORITY_BALANCED_POWER_ACCURACY
}

suspend fun Context.receiveLocationUpdatesFg(locationState: LocationState) {
    fusedLocationProviderClient.apply {
        tryFetchLastLocation()?.also {
            info { "lastLocation: ${it.description}" }
            locationState.location = it
        }
        LocationCallbackFg.locationState = locationState
        requestLocationUpdates(locationRequestFg, LocationCallbackFg, null).await()
        info(CC_PRIVATE) { "FG: started receiving location updates" }
    }
}

object LocationCallbackFg : LocationCallback() {
    var locationState: LocationState? = null

    override fun onLocationResult(result: LocationResult) {
        val lastLocation = result.lastLocation
        info { "FG: received location ${lastLocation.description}" }
        locationState?.apply { location = lastLocation }
                ?: warn { "LocationCallbackFg received an event while not in use" }
    }
}

The code relies on Task.await(), this is in Kotlin's library kotlinx-coroutines-play-services.


text:
Q: cakephp and containable behaviour I have the following json:
{
   "Companies":[
      {
         "CompanyPersonTask":{
            "company_id":"502d1844-3638-44dc-824c-14f02e0cc009",
            "person_id":"2",
            "task_id":"1"
         },
         "Company":{
            "id":"502d1844-3638-44dc-824c-14f02e0cc009",
            "name":"mostro",
            "Office":[
               {
                  "id":"502d1844-b90c-44f5-84c5-14f02e0cc009",
                  "company_id":"502d1844-3638-44dc-824c-14f02e0cc009",
                  "region":"Emilia-Romagna",
                  "city":"Rozzemilia",
                  "address":"-",
                  "phone":"-",
                  "legal_office":true
               }
            ],
            "CompanyPersonTask":[
               {
                  "company_id":"502d1844-3638-44dc-824c-14f02e0cc009",
                  "person_id":"2",
                  "task_id":"1"
               }
            ]
         },
         "Person":{
            "id":"2",
            "first_name":"Carlo",
            "last_name":"Giusti",
            "home_address":"Russi",
            "job_address":null,
            "phone":null,
            "fax":null,
            "mail":null,
            "full_name":"Giusti Carlo",
            "OfficePersonTask":[

            ],
            "CompanyPersonTask":[
               {
                  "company_id":"502d1844-3638-44dc-824c-14f02e0cc009",
                  "person_id":"2",
                  "task_id":"1"
               }
            ]
         },
         "Task":{
            "id":"1",
            "short_name":"Proprietario",
            "full_name":null,
            "info":null,
            "OfficePersonTask":[

            ],
            "CompanyPersonTask":[
               {
                  "company_id":"502d1844-3638-44dc-824c-14f02e0cc009",
                  "person_id":"2",
                  "task_id":"1"
               }
            ]
         }
      }
   ]
}

That is created by this method, inside CompanyPersonTask model:
public function getCompaniesByRegion($region){
    $this->recursive = 2;
    return $this->find('all');
}

but I want my json to be formatted like this:
{
   "Companies":[
      {
         "Company":{
            "id":"502d1844-3638-44dc-824c-14f02e0cc009",
            "name":"mostro",
            "Office":[
               {
                  "id":"502d1844-b90c-44f5-84c5-14f02e0cc009",
                  "company_id":"502d1844-3638-44dc-824c-14f02e0cc009",
                  "region":"Emilia-Romagna",
                  "city":"Rozzemilia",
                  "address":"-",
                  "phone":"-",
                  "legal_office":true
               }
            ]
         },
         "Person":{
            "id":"2",
            "first_name":"Carlo",
            "last_name":"Giusti",
            "home_address":"Russi",
            "job_address":null,
            "phone":null,
            "fax":null,
            "mail":null,
            "full_name":"Giusti Carlo"
         }
      }
   ]
}

How can I modify my method?

A: Use Containable behavior to filter result data.
For more explanation refer this link.

A: You can check unbindModel in cake php to remove the relation on the fly. This will prevent the data from the unwanted table. Check this.
<?php
$this->Model->unbindModel(
    array('associationType' => array('associatedModelClassName'))
);


text:
Q: Quantile 0.95 or 0.98 in Poisson/Nbinom distribution give value out of distribution (R) I am using R to count quantiles like 0.95, 0.98 etc.
qpois(0.98, f_pois$estimate[[1]])
qnbinom(0.98, size=f_pois$estimate[[1]], mu=f_nbinom$estimate[[2]])

My concern is that I get values 11 and 14 and my discrete distribution is movie rates from 1 to 10... So the quantiles are out of bound... Can it be fixed or is it ok?


text:
Q: Convert Excel cell value type using poi or jxl api I have an Excel file that contains numerical values, but they are stored as labels. So I want to use jxl or poi api to set their values type. However I don't know which method to use.
How can I do this?

A: I use poi library and this is my ExcelParser Class:
public class ExcelParser {

    private HSSFWorkbook wb;

    public ExcelParser(File xlsFile) throws Exception{

        wb = new HSSFWorkbook(new FileInputStream(xlsFile));
    }

    public String getValue(String sheetName, int rowNum, int celNum) throws Exception{
        try{
            HSSFSheet sheet = null;
            for(int i=0; i<wb.getNumberOfSheets();i++){
                if(wb.getSheetName(i).trim().toLowerCase().equals(sheetName.trim().toLowerCase())){
                    sheet = wb.getSheetAt(i);
                    break;
                }
            }
            if(sheet == null){
                throw new Exception("Sheet name '"+sheetName+"' not found.");
            }

            HSSFRow row     = sheet.getRow(rowNum);
            if(row == null){return "";}
            HSSFCell cell   = row.getCell(celNum);
            if(cell== null){return "";}

            if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
                return String.valueOf(cell.getNumericCellValue()).trim();
            } else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING){
                return cell.getStringCellValue().trim();
            }  else if (cell.getCellType() == HSSFCell.CELL_TYPE_ERROR){
                return "";//cell.getErrorCellValue();
            }else if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){
                try{

                    return cell.getStringCellValue().trim();
                } catch (Exception e) {
                    return "";
                }
            } else{
                return cell.getStringCellValue().trim();
            }
        }
        catch (Exception e) {
            throw new Exception(e.getMessage()+" in row:"+rowNum+" col:"+celNum+" sheet:"+sheetName);
        }
    }
}

WARNING, this class is for xls file only, if you use an xlsx file you have to use
XSSF

class rather than
HSSF


text:
Q: How to annotate() ggplot with latex I'd like to add latex text to a ggplot2 plot using annotate(). Using expression(), as described here for adding latex to axis labels, does not seem to work.  To wit:
# Use expression() to create subscripted text
p <- ggplot(mpg, aes(x=cty, y=hwy)) + geom_point() +
  scale_x_continuous(expression(text[subscript]))

# But expression() in annotate adds nothing to the plot
p + annotate("text", x=10, y=40, label=expression(text[subscript]))

# Passing regular text to annotate works fine
p + annotate("text", x=10, y=40, label="foo")

Why are expressions treated differently by annotate than by other ggplot functions? And how can I annotate with latex?

A: There is an R package called latex2exp which may be helpful. It has function TeX which accepts some LaTeX expressions enclosed with dollar sign $ as in this example:
library(latex2exp)
library(ggplot2)

qplot(1, "A")+
     ylab(TeX("Formula: $\\frac{2hc^2}{\\lambda^\\beta}$"))+
     xlab(TeX("$\\alpha$"))

More examples can be found in this vignette.

A: You can use the parse argument, without expression:
p + annotate("text", x=10, y=40, label="text[subscript]", parse=TRUE)

A: The tikzDevice package is back on CRAN (latest version 0.9 published Nov 2015).
Using tikz does require a full LaTeX installation; it may be easiest to do via knitr within a LaTeX document (just set dev="tikz" in the chunk options).  However, you can use it to create a standalone figure as well. Ironically, the hardest part of this question was getting a text subscript, which requires an additional LaTeX package (fixltx2e) for the \textsubscript command ...
library(tikzDevice)
## add a package to the defaults
options(tikzLatexPackages=
            c(getOption("tikzLatexPackages"),"\\usepackage{fixltx2e}"))
tikz("tikz.tex",standAlone=TRUE)
library("ggplot2"); theme_set(theme_bw())
p <- ggplot(mpg, aes(x=cty, y=hwy)) + geom_point() +
  scale_x_continuous(name="text\\textsubscript{subscript}")
p + annotate("text", x=10, y=40, label="text\\textsubscript{subscript}")
dev.off()

system("pdflatex tikz.tex")


text:
Q: Currency and decimal editor in Ultragrid I have to format some of the datatypes for cell values of an ultragrid. I have used the DateTimeEditor for formatting the datetime values.
//Code
private void ultraGrid1_InitializeRow(object sender, InitializeRowEventArgs e)
{
   if (e.ReInitialize == false)
   {
       DefaultEditorOwnerSettings editorSettings;
       DateTimeEditor datetime_editor;
       string condition = e.Row.GetCellValue("Condition").ToString();
       switch (condition)
       {
            case "TEST1":
                editorSettings = new DefaultEditorOwnerSettings()
                editorSettings.DataType = typeof(DateTime);
                editorSettings.MaskInput = "mm/dd/yyyy";
                datetime_editor = new DateTimeEditor(new DefaultEditorOwner(editorSettings));
                e.Row.Cells["DateInfo"].Editor = datetime_editor;
                break;
            case "TEST2":
                editorSettings = new DefaultEditorOwnerSettings()
                editorSettings.DataType = typeof(DateTime);
                editorSettings.MaskInput = "hh:mm:ss";
                datetime_editor = new DateTimeEditor(new DefaultEditorOwner(editorSettings));
                e.Row.Cells["DateInfo"].Editor = datetime_editor;
                break;
       }
   }
}

Now, How can I format the currency and decimal values?
Is there any currencyeditor or decimaleditor?

A: You could use a EditorWithMask, but keep in mind that a column has a datatype and if your column datatype is not compatible with the expected Editor datatype  the results are unpredictable
EditorWithMask currency_editor;
DefaultEditorOwnerSettings editorSettings = new DefaultEditorOwnerSettings();
editorSettings.DataType = typeof(decimal);
currency_editor = new EditorWithMask(new DefaultEditorOwner(editorSettings));
editorSettings.MaskInput = "€ nnn.nn";
e.Row.Cells["decimal_column_name"].Editor = mask_editor;

A: Try this coding
currencyColumn.Format = "##,###,####.00"
Thanks


text:
Q: Why does action button in docked widget when docked with (self.addDockWidget(Qt.RightDockWidgetArea, self.dock) doesn't work in QMdiArea? The button action on dock widget doesn't activate or work when docked on right, left, top or bottom in Mdi but it works without MdiArea.
I tested without MdiArea on a tab widget and it works fine there but with Mdi it doesn't work.


text:
Q: Elementarity of mappings I have a short question regarding elementarity of mappings,
i.e. I am doing some models of set theory and very often one says that a certain mapping is elementary.
I wonder what does it mean?

A: Let $\mathcal L$ be a (first order) language and let $\mathcal{M}, \mathcal{N}$ be $\mathcal{L}$-structures. A map
$$
\pi \colon \mathcal{M} \to \mathcal{N}
$$
is elementary iff for every $\mathcal{L}$-formula $\phi$ and all $x_1, \ldots, x_n \in \mathcal{M}$
$$
\mathcal{M} \models \phi(x_1, \ldots, x_n) \iff \mathcal{N} \models \phi(\pi(x_1), \ldots, \pi(x_n)).
$$
We also say that $\pi$ is an elementary embedding.
[Note that $\pi$ is always injective, since for $x,y \in \mathcal{M}$
$$
\begin{align*}
\pi(x) = \pi(y) & \iff \mathcal N \models \pi(x) = \pi(y) \\
& \iff \mathcal M \models x = y  \\
& \iff x = y,
\end{align*}
$$
which justifies the use of the term embedding in this context.]


text:
Q: Solving Black scholes PDE using Laplace transform I'm trying to obtain the Laplace transform of Call option price with repect to time to maturity under the CEV process.
The well known Black scholes PDE is given by
$$
\frac{1}{2}\sigma(x)^2x^2\frac{\partial^2}{\partial x^2}C(x,\tau)+\mu x\frac{\partial}{\partial x}C(x,\tau)-rC(x,\tau)-\frac{\partial}{\partial \tau}C(x,\tau)=0.
$$
where the initial condition $C(x,0)=max(x-K,0)$ and $\sigma(x)=\delta x^\beta$.
Taking a Lapalce transform with respect to $\tau$, we obtain the following ODE :
$$
\frac{1}{2}\delta x^{2\beta+2}\frac{\partial^2}{\partial x^2}\hat{C}(x,\lambda)+\mu x\frac{\partial}{\partial x}\hat{C}(x,\lambda)-(\lambda+r)\hat{C}(x,\lambda)=-max(x-K,0).
$$
where $\hat{C}(x,\lambda)=\int_0^\infty e^{-\lambda \tau}C(x,\tau)d\tau$.
and the initial condition is transformed to
$$
\hat{C}(x,\lambda)=\int_0^\infty e^{-\lambda \tau}C(x,0) d\tau=max(x-K,0)/\lambda
$$(is this right??? it seems wrong..)
. Then, $\hat{C}(x,\lambda)$ can be analytically formulated by the case $x>K$ and $x\leq K$.
How to get explicit formula for $\hat{C}(x,\tau)$?. I can't proceed from this stage.

A: Firstly, note that by taking Laplace transforms time has been eliminated and as such there are no initial conditions for your ODE anymore. There are only boundary conditions which in this case read $C(\pm \infty, \tau) = 0$.  By the way it is customary to denote the price of the underlying as $S$ whereas you denote it as $x$..
If you look at the ODE you see that it is very similar to the Euler equation. Thus it is useful to substitute for $y := \log(x)$. Having done that we end up with :
\begin{equation}
(i) \frac{\delta}{2} \frac{d^2}{d y^2} \tilde{C}(y,\lambda) + \left(\mu - \frac{\delta}{2} e^{2 \beta y}\right) \frac{d}{d y} \tilde{C}(y,\lambda) - (\lambda + r) \tilde{C}(y,\lambda) = - max(e^y - K,0)
\end{equation}
This is allready a much simpler equation yet since the coefficient at the first derivative is not constant we still have to transform it.  We solve firstly the homogenuous equation. Here let us try the a following ansatz:
\begin{equation}
(ii) \tilde{C}(y,\lambda) := \exp(2 A \beta y) \tilde{\tilde{C}}(\exp(2 \beta y))
\end{equation}
Inserting this ansatz to the above equation  we will obtain another second order equation for the function $\tilde{\tilde{C}}$. The later equation will be grossly simplified if we require the constant term in the coefficient at the zeroth derivative to be zero. This gives:
$-2 A^2 b^2 \delta - 2 \mu A b + r + \lambda =0$ which gives $A = (-\mu + \sqrt{\mu^2 + 2 \delta (\lambda+r)})/(2 \beta \delta)$ . Taking all this into account we get a following ODE:
\begin{equation}
(iii) A \tilde{\tilde{C}}(u,\lambda) + (B_0 - B_1 u )d_u \tilde{\tilde{C}}(u,\lambda)  + C u d^2_{u^2} \tilde{\tilde{C}}(u,\lambda) = 0
\end{equation}
where $A = (\mu - \sqrt{\mu^2+2\delta(\lambda+r)})$ and $B_0 = 2 \beta (2\beta \delta + 2 \sqrt{\mu^2 + 2 \delta(\lambda+r)}$, $B_1 = 2\beta\delta$ and $C = (2 \beta)^2 \delta$  and $u := \exp(2 \beta y)$.  We substitute for $B_1/C u$ and we recognize the generalized Laguerre differential equation, an equation this is easily solved through a power series method. Now, combining (iii) with (ii) we obtain the fundamental solutions of the homogenous ODE (i) . Having done this we solve the inhomogenuous ODE (i) by means of the Green's function method, for example.


text:
Q: How to add Chrome New URL? How to add new custom URL for my chrome (just like picture below)? I am not sure what this feature is called.

A: If you take a look at Google's official documentation here, this is a list of your most visited pages. You used to be able to customize this list via editing a file or manually pinning, but Google removed that ability. There is an extension called Speed Dial 2 that allows you to create your own New Tab page that would achieve what you are looking for.


text:
Q: how to split/partition data set into training and test set when data is in the shape of rows for each group and not one row for each group I have a data frame as following, and I need to split it into training and test set in a way that if I have one specific ID in train it should not be repeated in test set.
   Row  ID  AGE GENDER  TIME  CODE
    0    1   66      M     1     0
    1    1   66      M     2     0
    2    1   66      M     3     1
    3    2   20      F     1     0
    4    2   20      F     2     0
    5    2   20      F     3     0
    6    2   20      F     4     0
    7    3   18      F     1     0
    8    3   18      F     2     0
    9    3   18      F     3     0
    10   3   18      F     4     1

the desired output in training set should be like this
  Row   ID  AGE GENDER  TIME  CODE
    0    1   66      M     1     0
    1    1   66      M     2     0
    2    1   66      M     3     1
    3    2   20      F     1     0
    4    2   20      F     2     0
    5    2   20      F     3     0
    6    2   20      F     4     0

and test set should be like
   Row   ID  AGE GENDER  TIME  CODE
    0    3   18      F     1     0
    1    3   18      F     2     0
    2    3   18      F     3     0
    3    3   18      F     4     1

how is it possible doing this in pandas python?
Thanks in advance

A: try this,
ids=df['ID'].unique()
t= ids[:int(round(len(ids)*0.60))]

train=df[df['ID'].isin(t)]
test=df[~df['ID'].isin(t)]

Input:
    Row  ID  AGE GENDER  TIME  CODE
0     0   1   66      M     1     0
1     1   1   66      M     2     0
2     2   1   66      M     3     1
3     3   2   20      F     1     0
4     4   2   20      F     2     0
5     5   2   20      F     3     0
6     6   2   20      F     4     0
7     7   3   18      F     1     0
8     8   3   18      F     2     0
9     9   3   18      F     3     0
10   10   3   18      F     4     1

Output:
Train:
   Row  ID  AGE GENDER  TIME  CODE  flag
0    0   1   66      M     1     0     0
1    1   1   66      M     2     0     0
2    2   1   66      M     3     1     0
3    3   2   20      F     1     0     1
4    4   2   20      F     2     0     1
5    5   2   20      F     3     0     1
6    6   2   20      F     4     0     1

Test:
   Row  ID  AGE GENDER  TIME  CODE  flag
7     7   3   18      F     1     0     2
8     8   3   18      F     2     0     2
9     9   3   18      F     3     0     2
10   10   3   18      F     4     1     2


text:
Q: Make $dbh1(database handle) available to all php files I have problem making $dbh1 available to all php files that need it for querying. I tried using "global $dbh1" in this file where querying would run.
I have 4 files: testswitchDB3.php(main), testconnect.php, login.php and testnumcards.php
Once database is connected as run  by login.php and testconnect.php.
Both files are working
Thus $dbh1 is created and available by applying "global $dbh1" to testnumcards.php.
But it does not work.  Following are my codes.
testswitchDB3.php
<!DOCTYPE html>

    <title>Test the switching responses between databases using buttons</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../dojo1_8/dijit/themes/soria/soria.css"/>
    <link rel="stylesheet" href="../common.css"/>

Next is testconnect.php
<?php
global $dbh1;
$dbname = $_POST['nameDB'];
require_once '../scripts/login.php';
echo $connect;
?>

Next is login.php
<?php
    global $dbname;
    global $dbh1;

    $dbh1 =  null;
    $dsn ="mysql:host=localhost; dbname=$dbname";
    $user ='root';
    $pswd ='';

 try
    {
     $dbh1 = new PDO($dsn, $user, $pswd, array(PDO::ATTR_TIMEOUT => "10",// 10 seconds
     PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); // connect to DB, declared as global variable!
     $connect = TRUE;
    }

catch(PDOException $err)
    {
     $alertmsg = $err->getMessage();
     $connect = FALSE;
    }

echo $connect;
?>

Next is testnumcards.php
<?php
 global $dbh1;

 $stmt = $dbh1->prepare("select count(distinct mfg_code)as mfg_code from test");

 try
  {
    $stmt->execute();
  }

catch(PDOException $err)
 {
   $alertmsg = $err->getMessage();
 }

$num = $stmt->fetch(PDO::FETCH_ASSOC);
echo $num['mfg_code'];

?>

You can refer to JsFiddle for your reference though it cannot be used without PHP support.

A: You need to start your files with
<?php
require("login.php");

in all of your php scripts for them to be able to use a connection unless those scripts have already been include or required that file.
The connection has to be created every request as when a request ends, the connection is closed. so when you request testnumcards.php there is no $dbh1 to declare global as it has not been set up on that request
EDIT
PHP is a request specific language every time you send a new request to the server it needs to create connections again and set up variables, one page has no knowledge of resources that were created in another page as all resources are closed between requests.
So if I go to page1.php and connect to a database, when I later go to page2.php it has no connection to the database unless I create that connection again. When page1.php has finished and then the connection is closed, You then need to connect again in page2.php
This is why most scripts start by requiring a file that sets up any connections or other resources they need


text:
Q: Outputting the prediction scores from MLP keras inferencing Following the keras tutorial MLP classification here: https://keras.io/examples/nlp/multi_label_classification/.
I am able to successfully train a model and print out the top 3 predicted labels using the code below. I would also like to print out the prediction scores too. I can't seem to find how to do that in the documentation.
# Create a model for inference.
model_for_inference = keras.Sequential([text_vectorizer, shallow_mlp_model])

# Create a small dataset just for demoing inference.
inference_dataset = make_dataset(test_df.sample(100), is_train=False)
text_batch, label_batch = next(iter(inference_dataset))
predicted_probabilities = model_for_inference.predict(text_batch)

# Perform inference.
for i, text in enumerate(text_batch[:5]):
    label = label_batch[i].numpy()[None, ...]
    print(f"Abstract: {text}")
    predicted_proba = [proba for proba in predicted_probabilities[i]]
    top_3_labels = [
        x
        for _, x in sorted(
            zip(predicted_probabilities[i], lookup.get_vocabulary()),
            key=lambda pair: pair[0],
            reverse=True,
        )
    ][:3]
    print(f"Predicted Label(s): ({', '.join([label for label in top_3_labels])})")
    print(" ")

A: To access probabilities change this part:
top_3_labels = [
        x
        for _, x in sorted(
            zip(predicted_probabilities[i], lookup.get_vocabulary()),
            key=lambda pair: pair[0],
            reverse=True,
        )
    ][:3]
    print(f"Predicted Label(s): ({', '.join([label for label in top_3_labels])})")
    print(" ")

to this:
top_3_labels = [
        (p, x)
        for p, x in sorted(
            zip(predicted_probabilities[i], lookup.get_vocabulary()),
            key=lambda pair: pair[0],
            reverse=True,
        )
    ][:3]
    print(f"Predicted Label(s): ({', '.join([l[1] for l in top_3_labels])})")
    print(f"Predicted Probabilities(s): ({', '.join([l[0] for l in top_3_labels])})")
    print(" ")

A: You can predicted the most likely label (change the [:3] to [0]) and use some sklearn function to get the standar accuracy.
Also you can take all the probabilities for the labels and use the top k accuracy from sklearn


text:
Q: How to navigate from nested Fragment to parent fragment using Jetpack Navigation? I have main navigation:
SplashFragment -> RegistrationFragment -> RootFragment

<fragment
    android:id="@+id/splashFragment"
    android:name="com.low6.low6.features.splash.SplashFragment"
    android:label="Splash"
    tools:layout="@layout/fragment_splash" >
    <action
        android:id="@+id/action_next"
        app:clearTask="true"
        app:destination="@id/registrationFragment" />
</fragment>

<fragment
    android:id="@+id/registrationFragment"
    android:name="com.low6.low6.features.registration.RegistrationFragment"
    android:label="Register">
    <action
        android:id="@+id/action_next"
        app:clearTask="true"
        app:destination="@id/rootFragment" />
</fragment>

<fragment
    android:id="@+id/rootFragment"
    android:name="com.low6.low6.core.RootFragment"
    android:label="@string/home"
    tools:layout="@layout/fragment_root" />

And I have nested registration navigation:
RegistrationPersonalFragment -> RegistrationContactFragment -> RegistrationSecurityFragment

<fragment
    android:id="@+id/registrationPersonalFragment"
    android:name="com.low6.low6.features.registration.RegistrationPersonalFragment"
    android:label="Register">

    <action
        android:id="@+id/action_next"
        app:destination="@+id/registrationContactFragment" />
</fragment>

<fragment
    android:id="@+id/registrationContactFragment"
    android:name="com.low6.low6.features.registration.RegistrationContactFragment"
    android:label="Register">

    <action
        android:id="@+id/action_next"
        app:destination="@+id/registrationSecurityFragment" />
</fragment>

<fragment
    android:id="@+id/registrationSecurityFragment"
    android:name="com.low6.low6.features.registration.RegistrationSecurityFragment"
    android:label="Register">

    <action
        android:id="@+id/action_next"
        app:destination="@+id/rootFragment" />
</fragment>

How to redirect from the last nested RegistrationSecurityFragment to RootFragment using Jetpack Navigation component?
Currently
<action
    android:id="@+id/action_next"
    app:destination="@+id/rootFragment" />

And
   navigateTo(R.id.action_next)

Gives me
    java.lang.IllegalArgumentException: navigation destination com.xxx:id/rootFragment referenced from action com.xxx:id/action_next is unknown to this NavController
    at androidx.navigation.NavController.navigate(NavController.java:691)
    at androidx.navigation.NavController.navigate(NavController.java:648)
    at androidx.navigation.NavController.navigate(NavController.java:634)
    at com.xxx.core.BaseFragment.navigateTo(BaseFragment.kt:73)
    at com.xxx.core.BaseFragment.navigateTo$default(BaseFragment.kt:66)
    at com.xxx.features.registration.RegistrationSecurityFragment$epoxyController$1$$special$$inlined$button$lambda$1.onClick(RegistrationSecurityFragment.kt:106)
    at android.view.View.performClick(View.java:6597)
    at android.view.View.performClickInternal(View.java:6574)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25885)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

A: When you have nested NavControllers, findNavController() return only last. To get previous navControllers, you can traverse up using parentFragment property.
Extensions with this approach:
// find all nav controllers from closest to farest
fun Fragment.findAllNavControllers(): List<NavController> {
    val navControllers = mutableListOf<NavController>()
    var parent = parentFragment
    while (parent != null) {
        if (parent is NavHostFragment) {
            navControllers.add(parent.navController)
        }
        parent = parent.parentFragment
    }
    return navControllers
}

// find one nav controller by fragment id
fun Fragment.findNavControllerById(@IdRes id: Int): NavController {
    var parent = parentFragment
    while (parent != null) {
        if (parent is NavHostFragment && parent.id == id) {
            return parent.navController
        }
        parent = parent.parentFragment
    }
    throw RuntimeException("NavController with specified id not found")
}

And usage:
findAllNavControllers()[2]
findNavControllerById(R.id.navHostFragment)

A: If you have more than one navigation graph, please make sure you're using the right navigation controller. Using Navigation.findNavController(view) in some cases you might need to get your root view to get the root's navigation. Hope, this'll help.

A: In your code, you can pass the resource ID of the global action to the navigate() method for each UI element.
your_button.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
       Navigation.findNavController(view).navigate(R.id.main_fragment);
   }
});

A: Thanks to @Vladimir answer I came up with this solution
val mainNavView = requireActivity().findViewById<View>(R.id.mainNavFragment)
Navigation.findNavController(mainNavView).navigate(R.id.action_next)

A: You can do it like this ;
in Child Fragment
// parentFragment = getParentFragment() for java
(parentFragment as MyParentFragment).myNavigationHandler(myArguments)

in Parent Fragment
fun myNavigationHandler(myArguments) {
    Navigation.findNavController(binding.root)
        .navigate(MyFragmentDirections.actionMyAction(myArguments))
}

A: findNavController().navigate(HostFragmentDirections.actionHostToOtherFragment())

HostFragment is just an example, which should be the name of host of your nested fragment.
For everyone struggling with navigating to somewhere from your nested fragment, this works.


text:
Q: Helm error from Jenkins pipeline: "Error: no objects visited" I'm trying to implement a couple subcharts in our CI/CD pipeline but my helm upgrade --install command keeps returning the error message:

Release "testing" does not exists. Installing now.
Error: no objects visisted

It seems like this is a pretty general error message so I'm not quite sure what it's pointing to. Any suggestions/hints/tips etc would be greatly appreciated.
The folder structure of my helm directory is as follows:
  deployment
  |-helm
    |testing
    ||charts
      |application
        |-templates
        | |-deployment.yaml
        |-.helmignore
        |-Chart.yaml
        |-value.yaml
      |configuration
       |-templates
       | |-configmap.yaml
       | |-secrets.yaml
       |-.helmignore
       |-Chart.yaml
       |-values.yaml
    ||-Chart.yaml
    ||-values.yaml

Dependencies are defined as follows:
testing/Chart.yaml
apiVersion: v2
name: testing
description: subchart demo
type: application
version: 0.1.0
appVersion: "1.16.0"

testing/values.yaml
application:
  enabled: true

#disable configuration for easier debugging
configuration:
  enabled: false

configuration/Chart.yaml
apiVersion: v2
name: configuration
description: subchart demo
type: application
version: 0.1.0
appVersion: "1.16.0"

application/Chart.yaml
apiVersion: v2
name: application
description: subchart demo
type: application
version: 0.1.0
appVersion: "1.16.0"

application/deployment.yaml
 {{- range $k, $v := .Values.region }}
  apiVersion: apps.openshift.io/v1
  kind: DeploymentConfig
  metadata:
    labels:
      app: {{ $.Release.Name }}-{{ .countryCode | lower }}-deployment
    name: {{ $.Release.Name }}-{{ .countryCode | lower }}-deployment
    namespace: {{ $.Values.global.namespace }}
  spec:
    replicas: 1
    template:
      metadata:
        labels:
          app: {{ $.Release.Name }}-{{ .countryCode | lower }}-deployment
      spec:
        containers:
          - image: {{ $.Values.image_name }}
            imagePullPolicy: Always
            name: {{ $.Release.Name }}-{{ .countryCode | lower }}-deployment
---
{{- end }}

application/values.yaml
image_name: image_name

config:
  enabled: true

region:
  - countryCode: US

volumeMounts:
  - mountPath: /app/config
    name: app-config-volume

volumes:
  - name: app-config-volume
    configMap:
      defaultMode: 420
      name: app-configmap

Finally below is the command I'm running in the pipeline:
helm upgrade --install testing deployment/helm/testing -f deployment/helm/testing/values.yaml --set known_hosts="***" --set image_name=$DOCKER_TAG


text:
Q: Concucsion? A mash-up, combination of ingredients There is a word I heard somewhere on tv but I cannot find a correct spelling for it. It sounds something like concucsion and means a mash-up, random combination of ingredients.

A: As requested I've made this an answer.

concoction
1A mixture of various ingredients or elements
Oxford Dictionaries

A: I think the word you're seeking is concoction.


text:
Q: Oracle instant client header files are missed I'm using RedHat OS to build a C++ program that is using OCCI to connect with an Oracle DB.
I had to reinstall everything and I found that my make file is adding the header files from the following path

/usr/include/oracle/18.3/client64

Which isn't available anymore
The only installation I remember I need is installing oracle-instantclient-basic
I've downloaded the rpm and installed using the command rpm -i ***.rpm
But the folder /usr/include/oracle isn't there
Note: The path /usr/lib/oracle/18.3/client/lib is found and all libraries I use for linking are there (only header files are missed).
This is my installation file

A: I could investigate and find the solution
The header files are not created by installing oracle-instantclient-basic but you should install oracle-instantclient-devel
/usr/include/oracle/18.3/client64 is the path for 64bit version and the path is /usr/include/oracle/18.3/client for 32bit versions.
All the tools can be downloaded from oracle website


text:
Q: R code not running when using Ruby The commented line below throws an error: unsupported data type on R's end. Can someone tell me why?
require "rinruby"
ck=0
begin
R.eval <<EOF
  eve<-read.csv("RExportWithTotals2015-02-18.csv", sep=",", header=TRUE)
  ck=1
  regModel<-lm(eve$npitotal~eve$extraversion+eve$agreeableness)
  ck=2
  ss<-summary(regModel)
  ck=3
  call<-ss$call
EOF

ck=4
puts "#{R.call}"#-------------------ERROR HERE"
rescue Exception=> ex
puts "#{ex.message}\nerror line: #{ck}"
end

using Ruby version 2.0.0, latest RinRuby gem (gem install rinruby)

A: The solution was to typecast call as a string for Ruby like so:
puts "#{R.pull "toString(call)"}"


text:
Q: Multidimensional records with TArrays, how to set length in Delphi 10.3 i'm having issues when trying to create the third dimension in a data structure with TArrays.
How can length in the TSensorGroupSeries be set? --> SetLength(fSensorValues, fNbrSensors) in the example below;
I'm trying to create a time series, having sensors, where each sensor provides different measurements (8 values, for example: temp, hum, ...), where the type of measurements are identical at each sensor. The number of sensors changes per location: Minimum 2 sensors, max 16 sensors per location. Measurements are taken every 15 minutes.
regards
program Project2;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

const
  cSensDiffData = 8;
  cMinSensors   = 2;
  cMaxSensors   = 16;

type
  TSensorValues = record
    fData : Array[0 .. cSensDiffData-1] of Integer;
  end;
  TSensorGroup = record
    fSensorValues : TArray<TSensorValues>;
    class var
      fNbrSensors : Byte;
    constructor Create (NbrSensors : byte);
  end;
  TSensorGroupSeries = record
    fSensorGroup : TArray<TSensorGroup>;
    class var
      fSeriesLength : Integer;
    constructor Create (SeriesLength : Integer; NbrSensors : Byte);
  end;

{ TSensorGroup }

constructor TSensorGroup.Create (NbrSensors: Byte);
begin
  case NbrSensors of
     cMinSensors .. cMaxSensors :
     begin
       fNbrSensors := NbrSensors;
       SetLength(fSensorValues, fNbrSensors);
     end
  else
    raise Exception.Create('Nbr Sensors outside range: ' + NbrSensors.ToString + ' ' + cMinSensors.ToString + ' .. ' + cMaxSensors.ToString);
  end;
end;

var
  i : integer;
  s : string;
  SensorGroup : TSensorGroup;
  SensorGroupSeries : TSensorGroupSeries;

{ TSensorGroupSeries }

constructor TSensorGroupSeries.Create(SeriesLength : Integer; NbrSensors : Byte);
var
  i, j : integer;
  aSensorGroup : TSensorGroup;

begin
  aSensorGroup  := TSensorGroup.Create(NbrSensors);
  fSeriesLength := SeriesLength;
  SetLength(fSensorGroup, fSeriesLength);  // how is the system knowing the real length
end;

begin
// two dimensional data access is working..
  SensorGroup := TSensorGroup.Create(6);
  SensorGroup.fSensorValues[1].fData[2] := 12;
  writeln('Nbr Sensors defined: ' + SensorGroup.fNbrSensors.ToString);
  writeln('value at 0/0: ' + SensorGroup.fSensorValues[0].fData[0].ToString);
  writeln('value at 1/2: ' + SensorGroup.fSensorValues[1].fData[2].ToString);
  writeln('value at max: ' + SensorGroup.fSensorValues[6-1].fData[cSensDiffData-1].ToString);
  readln;
// three dimensional data is causing access error
  SensorGroupSeries := TSensorGroupSeries.Create(100,4);
  SensorGroupSeries.fSensorGroup[5].fSensorValues[2].fData[2]:=5;   // line, where error occurs
  writeln(SensorGroupSeries.fSensorGroup[5].fSensorValues[2].fData[2].ToString);
  readln;
end.

A: You are initializing ASensorGroup, but not using it. In effect, none of the elements of SensorGroupSeries are initialized and so will all be of zero length.
Here is the corrected constructor:
constructor TSensorGroupSeries.Create(SeriesLength : Integer; NbrSensors : Byte);
var
  i : integer;

begin
  fSeriesLength := SeriesLength;
  SetLength(fSensorGroup, fSeriesLength);  // how is the system knowing the real length
  for i := 0 to fSeriesLength - 1 do
  begin
    fSensorGroup[ i ].Create( NbrSensors );
  end;
end;

I have tested this and it works.

A: The three records above can be declared within one to reduce the memory footprint when having 1 Mio sensors:
      TSensorGroupSeries = record
//        class var --> do not use class var in this context, to prevent resizing, use private or strict private
          fNbrSensors : Byte;
          fSeriesLength : Integer;
        type
          TSensorGroup = record
            type
              TSensorValues = record
                fData : Array[0 .. cSensDiffData-1] of SmallInt;
              end;
            var
            fSensorValues : TArray<TSensorValues>;
            constructor Create (NbrSensors : byte);
          end;
        var
        fSensorGroup : TArray<TSensorGroup>;
        constructor Create (SeriesLength : Integer; NbrSensors : Byte);
      end;


text:
Q: How do I rename the Domain for the Default Directory for a Azure subscription? I signed up for an Azure account with my email address. Just assume it is myemail@mycompany.com. I see the domain for that default directory as Default Directory (myemailmycompany.onmicrosoft.com). I see this at the top right corner of the azure portal.
I have a few questions about this:

*

*How can I rename the domain from myemailmycompany.onmicrosoft.com
to mycompany.onmicrosoft.com?

*Does directory mean Active
Directory?

*How can I navigate to the page which lists all the users in that default directory?

A:
How can I rename the domain from myemailmycompany.onmicrosoft.com to
  mycompany.onmicrosoft.com?

I don't think it is possible to change the name of a directory. Not sure if you want to do this but you can assign a custom domain (e.g. mycompany.com) to your directory. See this link for more details: https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/add-custom-domain.

Does directory mean Active Directory?

Yes.

How can I navigate to the page which lists all the users in that
  default directory?

In Azure Portal, click on Azure AD icon and then "Users".


text:
Q: RESTful web service with apache cxf I've already developed a SOAP web service in Java with apache cxf and now I've to develop the same services in RESTful.
I have some troubles to deploy the web service on my tomcat. In fact, I don't know how should I configure my web.xml or any other XML file.
There are many examples online but everything I've tried so far doesn't work.
To build the project, I use an Ant build tool.
Anyone knows some good tips?

A: Here my service class used to test tutorials
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

@Path("/book")
public class BookService {

@GET
@Path("{id}")
@Produces({"application/xml","application/json"})
public Book getBookForId(@PathParam("id") int id) {
    Book book = null
    book = DB.getBookForId();
    if(book == null){
        return Response.status(Response.Status.BAD_REQUEST).build();
    }else{
        return Response.ok(book).build();
    }
}

}
And my web.xml looks like this most of the time :
<?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_3_0.xsd"
version="3.0">
    <display-name>REST</display-name>

<servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/services/*</url-pattern>
</servlet-mapping>

Apache CXF's example and other examples are "easy" to understand but the fast is that what i've done until now won't work.
My web service is deployed on my tomcat but everytime there is error like this :
 Servlet.service() for servlet [Jersey Web Application] in context with path [/WebServices] threw exception [L''exécution de la servlet a lancé une exception] with root cause
java.lang.AbstractMethodError:     javax.ws.rs.core.UriBuilder.uri(Ljava/lang/String;)Ljavax/ws/rs/core/UriBuilder;
at javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:119)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:669)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)

I know that this kind of error are stupid btu i don't get it Zzz.
I have to use jdk 1.6.0.45 so i can't try example which use jdk 1.7 and higher version. The fact is most of example tell to use Jersey 2.18...


text:
Q: i18n for JavaScript - The Best Practice? What's the current best practice of handling i18n in JavaScript?
I've heard some suggestions involving outputting all the i18n strings using PHP/Rails/etc. into a formatted JavaScript file of thousands of vars, but that simply sounds too rough a solution; moreover, there needs to be a way to detect which i18n strings are actually needed for the JS files that's gonna be loaded on a given page, but I got no idea how to implement this right now.
Some other suggestions I've heard involving setting up some kind of API between backend and frontend, using well-formatted JSON as the carrier of i18n strings, but that still doesn't solve the problem with redundant strings I might not need.
What's some of the best practices regarding i18n in JavaScript currently, that - if possible - also have a solution for detecting and sending only those strings that are actually needed on a given page?

A: The 'best practice' really depends on how you build you application. Two examples:

*

*Single page app. Of course you'd want to just load all of the needed strings for you entire application in one go, as constantly fetching new strings would be a waste of time and resources.

*Page with some JS-based content. If you keep reloading the JS, you probably want to reduce the amount of strings as much as possible, and maybe even integrate the entire i18n dict in your HTML to avoid a AJAX call.

Either way, you'll want to reduce the amount of strings sent to the client to a bare minimum. While there are a lot of approaches, my favorite is to use pre-compiled templates (I like Mustache using Twitter's Hogan.js) with i18n extensions that don't only return a function to generate the HTML, but also a list of all translatable strings.
What you definitely don't want to do is to build a function that checks whether you already have a translation and if you don't then ask the server. This will make everything very slow and you don't want that. Either pre-load all translations, or don't translate those parts.

A: It depends what you mean by "i18n". From your question it seems that you merely mean translatable strings extraction.
In this case, I lean to the single JS script generated from back-end. This may contain all the translatable strings in the array and some look-up method. I don't know if you call it "thousand variables approach", but that's what I am leaning to. I understand that you may dislike having things like alert(tr.getString("some.key")) in your code, but since you asked about the best practice...
I have seen many solutions, but most of them are just reinventing the wheel. The problem is, the wheel is rather squared in most cases...
Having said that, the i18n is way broader than simple string extraction. You have to take care about regional format support, correct collation, support for localizability (extracting strings is just one part) and more.
I can't really talk about "best practice", since the question is too broad. However, what I can say is, it really depends on the platform (i.e. programming language).


text:
Q: Possible to harm app with appsecret? I searched a lot but I can't find simillar question... So, I need to ask you one question about Facebook apps. If someone steal my appsecret (IT IS POSSIBLE) can they do anything with it? Example delete app or change something and how?

A: With client_id and client_secret, one can use the administrative api to change all aspects of the application. So don't share it.


text:
Q: Get facebook page access token to automatically publish to facebook page wall There is a need to publish stories from website to specified facebook page via PHP. Offline access permission is deprecated, so I basically need to get user access token so that I can get page access token (to post as page), but these tokens expire and extending them requires asking user directly to extend permissions in pop-up (correct me if I'm wrong).
So maybe there is a way to login in background so to speak, so that if user access token is expired, i log user in and get new access token? Or maybe there is a way to get never-ending user access token and obtain never-ending page acces token through that?
Don't understand why it's so hard to do, especially if i own website and facebook page to which I'm willing to publish to.

A: I just found out how to do this and searched stackoverflow for the question so that I can answer it :)
First, it's not the user you have to ask for extended access token, it's you. You need to extend your own user's access token. Your user's access token can be found at https://developers.facebook.com/tools/accesstoken/ under the name 'user token'.
Next step is to extend this token's life by making this request:
GET /oauth/access_token?
  grant_type=fb_exchange_token&
  client_id={app-id}&
  client_secret={app-secret}&
  fb_exchange_token={short-lived-token}

Where {app-id} and {app-secret} are the info at the dashboard of you application in developers.facebook.com and the {short-lived-token} is the 'user token' you just found.
You don't have to make this call via php SDK you can just use your browser like requesting the page graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id={app-id}&client_secret={app-secret}&fb_exchange_token={short-lived-token} (Note: It returns the value in the form of access_token={access-token}&expires={seconds}. So don't copy the whole thing.)
Now, when you get your page access token using this extended user token, it will be immortal. Make this API call using the new token (Note: Before making the call, you have to grant the permissions 'manage_pages' for making this call and 'publish_actions' for posting to the page later. The easiest way to do this is to hit the "get access token" button at https://developers.facebook.com/tools/explorer/ the permissions you need to give are under the 'extended permissions' tab.):
GET /me/accounts

You will get the list of your pages and some of their information along with an access token for each of them.
Those access tokens do not expire. You can check at https://developers.facebook.com/tools/debug/

A: You need to create a connector app for your page, then get a permanent access token for your app. You can see the details of this process on the Authenticating as an App page on the Facebook documentation.