text:
Q: How to calculate Hamming distance in matlab for two vectors? I need  to calculate the hamming distance between two vectors in octave. Searching in the internet, I found that Hamming distance by just using this function: pdist (), But it doesn't give me any result, because pdist() is a missing function in octave.
w= pdist([208    15   217   252   128    35    50   252   209   120    97   140   235   220    32   251],
       [231   174   143    43   125    66    49   143    48   139    81   103   154   229    93   229],1)

I would be very grateful if you could help me please.

A: *

*Hamming distance is a metric for comparing two binary data strings.

*While comparing two binary strings of equal length, Hamming distance is the     number of bit positions in which the two bits are different.

Hamming distance with xor and sum

a = [1, 1, 0, 0];
b = [1, 0, 1, 0];
diff = xor(a,b)
d = sum(diff)

answer will be :

d = 2

A: In matlab we can do it like this:
function dist = ham_dist(a,b,min_length)
%hamming distance of a, b. a and b are strings of decimal numbers respectively.
a = a*1-48;
b = b*1-48;
dist = sum(bitxor(a,b),2);
end

basically it is used a*1-48 is converting a binary string to row vector so that we can use bitxor. bitxor gives 1 at the positions they (a,b) differ, and 0 elsewhere.
taking sum of those gives hamming distance which is the count of no. of places where two binary numbers differ.


text:
Q: How to fix 'Unable to lookup in current state: Shutdown' error I'm new in macOs and whenever I try to run my app I get this error

hg@0.0.1 ios
react-native run-ios

info Found Xcode workspace "hg.xcworkspace"
info Launching iPhone 12 (iOS 14.4)
info Building (using "xcodebuild -workspace hg.xcworkspace -configuration Debug -scheme hg -destination id=70F98FFE-B73E-4E70-9856-4FB635F7B6BD")
success Successfully built the app
info Installing "/Users/mu/Library/Developer/Xcode/DerivedData/hg-dalmerybpbcohpexdotdxpbbxxeh/Build/Products/Debug-iphonesimulator/hg.app"
An error was encountered processing the command (domain=com.apple.CoreSimulator.SimError, code=405):
Unable to lookup in current state: Shutdown
info Launching "org.reactjs.native.example.hg"
error Failed to launch the app on simulator, An error was encountered processing the command (domain=com.apple.CoreSimulator.SimError, code=405):
Unable to lookup in current state: Shutdown

As i mentioned earlier I'm fairly new to macOS and whenever I try to run my project I'm getting this error.I have tried deleting and creating a new project but same error occurs.

A: This problem still arises from time to time due to the Xcode caches. You need to clear out the DerivedData folder for the simulator to launch again.
Navigate to >YOUR_USER_FOLDER>/Library/Developer/Xcode and delete the DerivedData folder. That should be enough to resolve the problem but you can also clean the project in Xcode as a final step as well before trying to build again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I browse Git Logs without Tig? I have a new server provider and they have no tig installed, I am pretty sure the guys have some good reasons for that. How do you browse git logs without tig?
Not really what I am looking for:

*

*$ git log --graph --color --oneline --all --decorate   # how can I browse things with this?

*$ git log -p   # more like diff-less -combo, not really browsing.

*$ gitk  # I am on console, although I could sshfs things but I want to browse things like with tig

A: The output of the git log will be passed through less which will allow you to go up and down to view earlier or later history. less has a lot of functionality such as searching for certain strings, etc: http://unixhelp.ed.ac.uk/CGI/man-cgi?less
You should be able to use gitk --all to see everything as well.

A: From what you've said, I'd suggest one of these:

*

*git clone (maybe with --mirror) then just use tig. Advantages: it's all local, tig will be fast. Disadvantages: you have to keep your mirror copy up-to-date.

*sshfs, then just use tig. Advantages: you are using your local tig, configured exactly how you want it, directly on the remote repository. Disadvantages: it might run a bit slow depending on sshfs network performance & caching.

A: you could try this, my personal config alias.lp
git log --graph --pretty=format:'%Cgreen%h%Creset -%C(yellow)%d%Creset %s %Cred(%cr)%Creset%C(yellow)<%an>'


text:
Q: Distribuição eletrônica em PHP sem passar do limite de eletróns Estou querendo criar um programinha que faz a distribuição eletrônica de acordo com o diagrama de Pauling.
Antes de começar, eu tenho uma dúvida:
Como posso limitar, em PHP, a quantidade de eletróns que cada subnível pode ter?
Exemplo: Subnível "s" o máximo de elétrons é 2 (Mas pode ter menos que isso), subnível "p" o máximo de elétrons é 6 (Mas pode ter menos que isso), etc...
Tem como eu fazer esse limite?


text:
Q: When using plotly in R with "hovermode = 'x'" enabled, is it possible to skip hoverinfo when y = 0 or y = NA? I'm using R/plotly to create a stacked filled area plot summarizing several accounts opened at different times, whose balances sometimes go to zero.  Here's a simplified example using three accounts ("X", "Y", and "Z"):
df <- data.frame(cbind(
    year <- c("2022-01-01","2022-02-01","2022-03-01","2022-04-01","2022-05-01","2022-06-01","2022-07-01","2022-08-01","2022-09-01","2022-10-01","2022-11-01","2022-12-01"),
    x <- c(NA,NA,NA,1,2,3,2,3,4,5,3,4),
    y <- c(1,2,2,1,2,4,3,2,NA,NA,NA,NA),
    z <- c(NA,NA,NA,1,2,5,6,5,5,NA,NA,NA)
)) %>%
    setNames(c("DATE","X","Y","Z")) %>%
    mutate(DATE = as.Date(DATE, format = "%Y-%m-%d")) %>%
    mutate(X = as.numeric(X), Y = as.numeric(Y), Z = as.numeric(Z)) %>%
    pivot_longer(., -DATE, names_to = "LEGEND", values_to = "QUANTITY") %>%
    mutate(LEGEND = factor(LEGEND, levels = c("X","Y","Z")))

When I create a graph using plotly, I prefer to use the hovermode = "x" parameter to compare all quantities at a given time at once.  However, when hovering over periods when an account is empty (i.e., QUANTITY = NA), I still get a tooltip box with hoverinfo showing y = 0.  With lots of accounts, this can clutter things up pretty quickly.
dfplot <- plot_ly(data = df, x = ~DATE, y = ~QUANTITY, color = ~LEGEND, type = "scatter", mode = "none", stackgroup = "one", fill = "tonexty") %>%
    layout(
        autosize = TRUE,
        yaxis = list(range = c(0,15)),
        hovermode = "x",
        showlegend = TRUE
    )
dfplot

X and Z are given values of "0", despite being NA
Is there a way to get rid of these extra tooltips?  Or to conditionally skip hoverinfo if y = 0 or NA?
I've been able to skip hoverinfo for entire traces, and I have been able to get the behavior I want with simple scatter traces (y = 0 is ignored in these situations).  I'm not sure if this is something that is specific to stacked filled area plots or not.  Any help would be greatly appreciated!

A: Update
As I stated in my comment. I thought you meant the Y trace, not y for each trace. Here is my update.
plot_ly(data = df, x = ~DATE, y = ~QUANTITY, color = ~LEGEND, type = "scatter",
        mode = "none", stackgroup = "one", fill = "tonexty") %>%
  layout(autosize = TRUE, yaxis = list(range = c(0, 15)), hovermode = "x",
         showlegend = TRUE) %>%
  htmlwidgets::onRender("function(el){
    el.on('plotly_hover', function(d) {
      out = [];          /* traces to drop from hover */
      keep = [];         /* traces to keep in the hover */
      fixer = [2, 1, 0]; /* data order Z, X, Y; trace order X, Y, Z */
      for(i = 0; i < 3; i++) {  /* which traces stay? which go? */
        j = fixer[i];
        if(d.points[i].y == 0) {out.push(j);}
        else {keep.push(j);}
      }
      if(out.length != 0) {                    /* drop from hover */
        Plotly.restyle(el.id, {hoverinfo: 'none', hovertemplate: null}, out);
      }
      if(keep.length > 0 && keep.length < 3) { /* keep */
        Plotly.restyle(el.id, {hoverinfo: 'all', hovertemplate: '%{y}'}, keep);
      } else if(keep.length == 3) {             /* keep */
        Plotly.restyle(el.id, {hoverinfo: 'all'}, keep);
      }
    })
  }")

originally
I can drop the 'Y' trace from the x-unified hover, but it also drops the x-axis. I tried many different ways to get the x-axis back, but I haven't found a way that works.
This uses the library htmlwidgets. However, since it's only for one function, I just appended it to the function. (I didn't call the library.)
I've piped the function from the graph but did not change any of your code.
Here's what you can do to drop the Y trace where there is no or a 0 value.
plot_ly(data = df, x = ~DATE, y = ~QUANTITY, color = ~LEGEND, type = "scatter",
        mode = "none", stackgroup = "one", fill = "tonexty") %>%
  layout(autosize = TRUE, yaxis = list(range = c(0, 15)), hovermode = "x",
         showlegend = TRUE) %>%
  htmlwidgets::onRender("function(el){
    el.on('plotly_hover', function(d) {
      if(d.points[1].y == 0) {
          hinfo = {hoverinfo: 'none'};
      } else {
          hinfo = {hoverinfo: 'all'};
      }
      Plotly.restyle(el.id, hinfo, 1);
      Plotly.restyle(el.id, {hoverinfo: 'all', hovertemplate: '%{y}'}, [0, 2]);
    })
  }")

You had assigned the graph to dfplot. You can always just pipe the function I provided to the plot after you named it like this (it does the same thing).
dfplot %>%
  htmlwidgets::onRender("function(el){
    el.on('plotly_hover', function(d) {
      if(d.points[1].y == 0) {
          hinfo = {hoverinfo: 'none'};
      } else {
          hinfo = {hoverinfo: 'all'};
      }
      Plotly.restyle(el.id, hinfo, 1);
      Plotly.restyle(el.id, {hoverinfo: 'all', hovertemplate: '%{y}'}, [0, 2]);
    })
  }")

By the way, I noticed a few things in your data creation that might make things a bit easier for you. If you already know this, just ignore me!
Odd things happen when you use <- inside of a function. When creating an object, use either; assignment inside a function use =.
In my example, note that cbind and setNames weren't used. Additionally, X, Y, and Z were transformed to numeric in one call. ., isn't in pivot_longer. Lastly, the last mutate was replaced with the argument names_transform in pivot_longer.
df1 <- data.frame(
  DATE = c("2022-01-01","2022-02-01","2022-03-01","2022-04-01","2022-05-01",
           "2022-06-01","2022-07-01","2022-08-01","2022-09-01","2022-10-01",
           "2022-11-01","2022-12-01"),
  X = c(NA,NA,NA,1,2,3,2,3,4,5,3,4),
  Y = c(1,2,2,1,2,4,3,2,NA,NA,NA,NA),
  Z = c(NA,NA,NA,1,2,5,6,5,5,NA,NA,NA)) %>%
  mutate(DATE = as.Date(DATE, format = "%Y-%m-%d"),
         across(X:Z, as.numeric)) %>%
  pivot_longer(-DATE, names_to = "LEGEND", values_to = "QUANTITY",
               names_transform = list(LEGEND = as.factor))
all.equal(df, df1) # [1] TRUE


text:
Q: Adding a new js file to my lambda function using Serverless I'm trying to create an API on AWS Lambda, and using Serverless framework for deployment.
I'm a complete noob at it, so I'm not sure I'm doing the right thing. So here's the old favorite, hello world (index.js):
const serverless = require('serverless-http');
const express = require('express');
const app = express();
const Promise = require('promise');

app.get('/', function (req, res) {
    res.send('Hello World!')
})

That works fine as is. But when I add the following:
const serverless = require('serverless-http');
const express = require('express')
const app = express()
const Register = require('./controller/registryController');

app.get('/', function (req, res) {
    res.send('Hello World!')
})

app.get('/createUserName', function (req, res) {
    var prom = Register.createUser();
    prom.then((message) => {
        res.status(201).json(message);
    })
    .catch((message) => {
        res.status(400).json(message);
    });
})

module.exports.handler = serverless(app);

I get:

"Cannot find module './controller/registryController'"

Which is strange, cause the file is right there, when I look in lambda. Here's its contents:
const dbConnMysql = require('./dbMngrMysql');

var methods = {
    createUser: function() {
        return new Promise((resolve, reject) => {
            let connection = dbConnMysql.createConnection();
            dbConnMysql.startConnection(connection)
            .then((fulfilled) => {
                let table = 'userNamePool';
                return dbConnMysql.selectFrom(connection, table, null);
            })
            .then((fulfilled) => {
                return dbConnMysql.closeConnection(connection).then(function() {
                    let result = fulfilled;
                    let response = {
                        "statusCode": 200,
                        "headers": {"my_header": "my_value"},
                        "body": JSON.stringify(result),
                        "isBase64Encoded": false
                    };

                    resolve(response);
                });
            })
            .catch((error) => {
                let response = {
                    "statusCode": 404,
                    "headers": {"my_header": "my_value"},
                    "body": JSON.stringify(error),
                    "isBase64Encoded": false
                };

                resolve(response);
            });
        });
    }
};

module.exports = methods;

Here's the project structure / directory:

And here's my serverless.yml for good measure:
service: sample-api
provider:
  name: aws
  runtime: nodejs8.10
  stage: dev
  region: yapyap
  deploymentBucket: yadayada
  role: blahblahblah

functions:
  app:
    handler: index.handler
    events:
      - http: ANY /
      - http: 'ANY {proxy+}'
  createUserName:
    handler: index.handler
    events:
      - http: 'GET /createUserName'

What am I doing wrong? Anything I can do to fix this?

A: Sorry, I can't comment because of the reputation restriction.
The problem may be because you haven't created controller folder.
To create it properly
create a folder. Name it controller. Create your registryController.js and put your code in it.
now you will be able to call it as
const Register = require('./controller/registryController');

Also on a side note, if you want to use a serverless architecture, separate your server side and client side code completely. Put your HTML files and client-side scripts in an S3 bucket. put your server-side code in lambda function and connect it with API Gateway. then use a JavaScript function to call the API. Keep server-side calls as less as possible.

A: There's a typo:
controller instead of controllers.


text:
Q: What is the relation between the stator current and motor rpm for an AC motor? A 3 phase AC motor is rated values are: 970 rpm, 50Hz, 380V delta 47A.
A VFD drives this motor for obtaining a constant wind-speed which rpm is proportional.
The thing is when 885 rpm the stator drives 35A and when at 840 rpm the stator drives 33A.
The wind-speed is not regulated well enough.
Doesn't current supposed to be same in this application for a constant torque?

A: Relating a motor's current to a fan output airflow requires you to know details about the motor, the fan, the mechanical system surrounding the fan, and the ambient atmosphere.

*

*The motor current depends on the motor speed, as shown by a speed vs. current curve.

*The motor speed depends on the motor's speed-torque curve vs. the fan's speed-torque curve.

*The fan's speed-torque curve depends on the inlet air density.

*The speed of the air exiting the fan presumably depends on mechanical details such as - the pressure drop in the fan's duct work, the open/closed position of air dampers, and so on.
It should be evident there is no 'simple' relation between fan motor current and fan output airflow!
I will add two useful pieces of information.

*

*The "Fans and Blowers Energy Efficiency Reference Guide" (published under the branding of BC Hydro, Manitoba Hydro, and others) is an excellent introduction to fan and blower design. This is required reading for all electrical engineers dealing with fans and blowers.

*Contrary to your statement that fans have constant torque: Some loads have a constant torque, but fans aren't one of them. From a book by Schneider Electric we have the following table:

Here is an example of a motor's torque-speed curve and speed vs. current curve.

Here is an example of a centrifugal fan's load-torque curve.

Here is an example of a centrifugal fan's power vs. airflow curve (note - power = torque × speed.) Note that the relationship is non-linear.

A: In addition to the above very thorough answer, I need to add a few points.
Point 1: Stator current has nothing to do with RPM in an induction motor.  The only thing that controls speed (as long as the motor is not overloaded) is the applied frequency, and the motors inherent slip.  The current drawn is what is needed (again, up to the limit of the motor) to provide sufficient torque to drive the load.
Point 2: When you are dealing with a Variable Frequency Drive, you need to specify what mode the drive is running in before even considering relating measured current to the load.  In simple Volts/Hz operation, the stator current measurement is generally accurate.  Most modern drives though run in Sensorless Vector (no feedback element) or Flux Vector (with a speed feedback device).  In either of those modes, and some manufacturers differently named but similar modes, you cannot actually measure the stator current with any degree of accuracy.  In SSV or FV mode, the stator often draws just about full load current all the time if you just use a clamp on ammeter.  The only way to measure the actual torque producing current is to use the diagnostics on the drive itself (if provided).  They use the magnetic model of the motor to display the actual torque producing current and flux producing current as separate vector values.


text:
Q: How to use ::v-deep selector for nested classes in vue I know the ::v-deep selector has been changed in vue 3. I understood how to use it with one class but I can't find any sources about nested classnames.
For example:

vue2

::v-deep {
    .table-footer-container {
      display: none ;
    }
  }

vue 3

:deep(.table-footer-container) {
    display: none
  }

But how can I transform this code block to vue 3 version ?
::v-deep {
      .v-select {
        .vs__dropdown-toggle {
          background: #fff;
          border-color: #ddd;
        }
        &.vs--open {
          .vs__dropdown-toggle {
            border-color: #ff6000;
          }
        }
      }
    }

A: Wrap both nested selectors in :deep():

<style scoped lang="scss">
.v-select {
  color: green;

  &:deep(.vs__dropdown-toggle) {
    background: #fff;
    border-color: #ddd;
    color: red;
  }

  &:deep(.vs--open) {
    .vs__dropdown-toggle {
      border-color: #ff6000;
      color: blue;
    }
  }
}
</style>

demo

A: If you want to keep the code changes simple, you can also undermine the obligation to use a child selector very easily by allowing the changes to all child  elements through the asterisk operator:
:deep(*) {
  .v-select {
    .vs__dropdown-toggle {
      background: #fff;
      border-color: #ddd;
    }
    &.vs--open {
      .vs__dropdown-toggle {
        border-color: #ff6000;
      }
    }
  }
}

This solution makes more sense in many cases, because the old structure of your (BEM) notation is not lost this way. For example, the following code...
.paragraph {
  &__headline {
    margin-bottom: 2rem;
  }
  &__text {
    margin-bottom: 20px;
  }
  ::v-deep &__link {
    text-decoration-color: red;
  }
}

... can be converted to this...
.paragraph {
  &__headline {
    margin-bottom: 2rem;
  }
  &__text {
    margin-bottom: 20px;
  }
  :deep(*) &__link{
    text-decoration-color: red;
  }
}

...without changing any structure.


text:
Q: Как группировать по столбцу с Unix time и подсчитать среднее для другого столбца в этой группе? timestamp,value
1586166810,0
1586166840,0
1586166920,0
1586167120,0

df = pd.read_csv('g.csv')
for index, row in df.iterrows():
    prev_data = row['timestamp']
    new_data = row['timestamp']
    while (new_data - prev_data) <= 3600:
        new_data = row['timestamp'] # + 1
        continue
    # скорее всего - этот момент продуман в pandas как брать блоки данных по условию, но не знаю куда читать.

Даны даты в формате Unix time.
Как группировать по столбцу timestamp по 1 часу и подсчитать среднее по этому часу для столбца value?

A: Попробуйте так:
In [8]: df = pd.read_csv(r"c:\temp\data.csv")

In [9]: df["timestamp"] = pd.to_datetime(df["timestamp"], unit="s")

In [10]: res = df.groupby(pd.Grouper(key="timestamp", freq="1H"))["value"].mean()

In [11]: res
Out[11]:
timestamp
2020-04-06 09:00:00    0
Freq: H, Name: value, dtype: int64

A: Наверное, можно еще и так:
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="s")
df['group_mean'] = df.groupby(df['timestamp'].dt.hour)['value'].transform('mean')
print(df)

результат:
            timestamp  value  group_mean
0 2020-04-06 09:53:30      0           0
1 2020-04-06 09:54:00      0           0
2 2020-04-06 09:55:20      0           0
3 2020-04-06 09:58:40      0           0


text:
Q: TypeError: $(...).progressbar is not a function I got TypeError: $(...).progressbar is not a function when Gentelella - Bootstrap Admin Template Page Load. Its affect many Jquery process. How to Fixed it.
My Error Line : (custom.js)
// Progressbar
if ($(".progress .progress-bar")[0]) {
    $('.progress .progress-bar').progressbar();
}

Footer Jquery Files
 <!-- jQuery -->

    <script src="{{url('vendors/jquery/dist/jquery.min.js')}}"></script>
    <!-- Bootstrap -->
    <script src="{{url('vendors/bootstrap/dist/js/bootstrap.min.js')}}"></script>
    <!-- FastClick -->
    <script src="{{url('vendors/fastclick/lib/fastclick.js')}}"></script>
    <!-- NProgress -->
    <script src="{{url('vendors/nprogress/nprogress.js')}}"></script>
    <!-- bootstrap-wysiwyg -->
    <script src="{{url('vendors/bootstrap-wysiwyg/js/bootstrap-wysiwyg.min.js')}}"></script>
    <script src="{{url('vendors/jquery.hotkeys/jquery.hotkeys.js')}}"></script>
    <script src="{{url('vendors/google-code-prettify/src/prettify.js')}}"></script>

    <!-- Custom Theme Scripts -->
    <script src="{{url('build/js/custom.min.js')}}"></script>

A: You need to use the below code
NProgress.start();
NProgress.done();

Reference document https://github.com/rstacruz/nprogress
I guess you are using nprogress.

A: try to order how jquery javascript etc are loaded... change order and moving it from bottom to head...

A: // Progressbar
$(document).ready(function(){
if ($(".progress .progress-bar")[0]) {
    $('.progress .progress-bar').progressbar();
}
})


text:
Q: In JavaFX, How to gradient fill multiple objects on canvas as one object? I'm trying to draw three separate round rectangles and then fill all three with a linear gradient, but have the gradient traverse all three objects. I can't seem to find any information on drawing objects onto a canvas and linking them together.
I'm very new at using canvas in general.
Here is what I have so far:
final Canvas          canvas  = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT);
final GraphicsContext gc      = canvas.getGraphicsContext2D();
double                offset1 = .1;
double                offset2 = .9;
Color                 color1  = Color.rgb(0,0,255);
Color                 color2  = Color.rgb(0,200,255);
Stop[]                stops1  = new Stop[] {new Stop(offset1, color1), new Stop(offset2, color2)};
gc.setFill(new LinearGradient(0, 0, .2, 1.4, true, CycleMethod.NO_CYCLE, stops1));
double third = CANVAS_HEIGHT / 3.0;
double thirdM2 = third - 10;
double h2 = CANVAS_HEIGHT - (2 * third);
double h3 = CANVAS_HEIGHT - third;
gc.fillRoundRect(0,0,CANVAS_WIDTH,thirdM2,thirdM2,thirdM2);
gc.fillRoundRect(0,h2,CANVAS_WIDTH,thirdM2,thirdM2,thirdM2);
gc.fillRoundRect(0,h3,CANVAS_WIDTH,thirdM2,thirdM2,thirdM2);

This makes an image that looks like this

However, I need it to end up looking like this:

Is there any way to accomplish this in JavaFX with canvas?
Thank you,
Mike Sims

A: Yes.  There are a couple ways to do this.  You could render all three rounded rectangles as a single path (using path rendering instead of fillRoundedRect, e.g. moveTo, arcTo etc.), or you could change the render blend mode to SRC_ATOP and paint a rectangle over all three rounded rects.  That's what I've done in the code below:
    final Canvas          canvas  = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT);
    final GraphicsContext gc      = canvas.getGraphicsContext2D();
    double                offset1 = .5;
    double                offset2 = .9;
    Color                 color1  = Color.rgb(0,0,255);
    Color                 color2  = Color.rgb(0,200,255);
    Stop[]                stops1  = new Stop[] {new Stop(offset1, color1), new Stop(offset2, color2)};
    double third = CANVAS_HEIGHT / 3.0;
    double thirdM2 = third - 10;
    double h2 = CANVAS_HEIGHT - (2 * third);
    double h3 = CANVAS_HEIGHT - third;

    gc.fillRoundRect(0,0,CANVAS_WIDTH,thirdM2,thirdM2,thirdM2);
    gc.fillRoundRect(0,h2,CANVAS_WIDTH,thirdM2,thirdM2,thirdM2);
    gc.fillRoundRect(0,h3,CANVAS_WIDTH,thirdM2,thirdM2,thirdM2);

    gc.setGlobalBlendMode(BlendMode.SRC_ATOP); // preserves the alpha channel set above

    gc.setFill(new LinearGradient(0, 0, .6, .5, true, CycleMethod.NO_CYCLE, stops1));
    gc.fillRect(0, 0, CANVAS_WIDTH, h3+thirdM2);

If you don't want to muck around directly on the canvas (because there may be other elements that get in the way that you can't paint over), you can do this trick to a writeable image and then stamp that onto the canvas.


text:
Q: Is facade design pattern similar to MVC? I am overall confused over the use of the facade design pattern. Is facade similar to MVC. I am asking this because I used facade in a project that helped to separate the front end interface from the back end internals.

A: I would say that probably you are overlooking many things, MVC is a whole framework that helps you separate concerns like controllers (which handle infrastructure of web requests) and the models (which is the info that you pass to the Views) and the View (which is only interested in presenting information).
The way I think about facades, could apply to everything in which you want to provide a simpler interface of a system component whenever this needs to talk to another system component, this is to avoid complicated APIs that are too cumbersome or too complex.
In relation to facades, there is the adapter pattern, which works exaclty as the facade, trying to simplify the API from a system component, but the difference is that one of the components is not under your control, is something that you cannot modify its behavior. ASP.Net cache might be an example, you will create an ADAPTER to satisfy your requirements, and you will need to update your adapter if the ASP.Net CAche is altered dramatically.
So overall, both are patterns, but I think of MVC as somthing like Framework+Pattern, whereas FAcade is just a simple function to ease your job whenever you work with complex software components.
Hope it helps,

A: In Simplest Words - Facade is used to hide the internal details of System/Sub-System/Layers from the client, while MVC is an architecture to decouple business, presentation and controller.

A: Facade Pattern Provide a unified interface to a set of interfaces in a subsystem.
Facade defines a higher-level interface that makes the subsystem easier to use. This can be used to simplify a number of complicated object interactions into a single interface.
Facade Pattern can be used in MVC Application to enhance the Layered Architecture of Complex MVC Application.


text:
Q: Run Android NDK .so library in normal Java How Can I call methods .so shared object compiled to Android NDK in normal Java?

A: If by "normal Java" you mean on your regular machine and not an Android device, you can't. Even if you build x86 NDK libraries, those libraries have many dependencies on the Android system libraries.


text:
Q: Setting a Model variable from jQuery in asp.net I have a jQuery script which let's me search/filter through a list of people and select them. Using this, it allows me to set a div based on that person's traits.
However, I need to be able to use this variable later on (after I post the form.)
Is there a way to set the model variable for the personID in the jQuery? i.e.:
<%: Model.PersonId == ui.item.id; %>
Or is there another way to do this?
Also - I am posting the form using a submit button, so if there was a way I could set Html.Hidden(), then that would work also.

A: You can create a hidden field using javascript, set its value with whatever value you need and then submit it along with the form. You can then access this hidden field value in your controller.
$("form").append("<input type='hidden' name='hiddenPersonId' value='"+ui.item.id+"' />");

Alternatively
$("form").append($("<input type='hidden' name='hiddenPersonId'/>").val(ui.item.id));

On the server side you can get this value using
Request.Form["hiddenPersonId"];

A: The model is on the server and jquery is on the client, so the code you posted won't work.  There are a number of ways to do this.  Your javascript could set a hidden form field, or post an ajax request to the server which would fetch an updated model.
    <html>
    <head>
    <script>
    $(document).ready(function() {
    $("#submit-button").click(function(){
      $("#hidden-input").val(new Date()); //set the value to the current date
    });
    });
    </script>
    </head>
    <body>
     <form>
      <input type="hidden" id="hidden-input" name="hidden-input" />
      <input type="submit" id="submit-button" value="submit" />
     </form>

    <body>
</html>


text:
Q: When I have use "on", and "in"? My native language is Spanish

*

*When I have that to use "on"?, I read some message like "On my server", "On skype", And more.. But I cannot understand it, why "on"?.

I need know it, thanks!.

A: I'm afraid there is no answer to "Why". Prepositions are often one of the most idiosyncratic part of a language.
There are some partial answers (we usually use "on" for a method of transport or medium of communication - on a boat, a train, a TV channel, Skype, Facebook, the Internet) but they are only partial (we use "in" for a car or a newspaper). I'm afraid you just have to learn them - I don't believe there's any other way.


text:
Q: How to get the size of struct and its contents in bytes in golang? I have a struct, say:
type ASDF struct {
    A   uint64
    B   uint64
    C   uint64
    D   uint64
    E   uint64
    F   string
}

I create a slice of that struct: a := []ASDF{}
I do operations on that slice of the struct (adding/removing/updating structs that vary in contents); how can I get the total size in bytes (for memory) of the slice and its contents? Is there a built-in to do this or do I need to manually run a calculation using unsafe.Sizeof and then len each string?

A: Sum the size of all memory, excluding garbage collector and other overhead. For example,
package main

import (
    "fmt"
    "unsafe"
)

type ASDF struct {
    A uint64
    B uint64
    C uint64
    D uint64
    E uint64
    F string
}

func (s *ASDF) size() int {
    size := int(unsafe.Sizeof(*s))
    size += len(s.F)
    return size
}

func sizeASDF(s []ASDF) int {
    size := 0
    s = s[:cap(s)]
    size += cap(s) * int(unsafe.Sizeof(s))
    for i := range s {
        size += (&s[i]).size()
    }
    return size
}

func main() {
    a := []ASDF{}

    b := ASDF{}
    b.A = 1
    b.B = 2
    b.C = 3
    b.D = 4
    b.E = 5
    b.F = "ASrtertetetetetetetDF"
    fmt.Println((&b).size())
    a = append(a, b)

    c := ASDF{}
    c.A = 10
    c.B = 20
    c.C = 30
    c.D = 40
    c.E = 50
    c.F = "ASetDF"
    fmt.Println((&c).size())
    a = append(a, c)

    fmt.Println(len(a))
    fmt.Println(cap(a))
    fmt.Println(sizeASDF(a))
}

Output:
69
54
2
2
147

http://play.golang.org/p/5z30vkyuNM

A: I'm afraid to say that unsafe.Sizeof is the way to go here if you want to get any result at all. The in-memory size of a structure is nothing you should rely on. Notice that even the result of unsafe.Sizeof is inaccurate: The runtime may add headers to the data that you cannot observe to aid with garbage collection.
For your particular example (finding a cache size) I suggest you to go with a static size that is sensible for many processors. In almost all cases doing such micro-optimizations is not going to pay itself off.


text:
Q: botframework V4 - Package on Nuget is older than the one on GitHub I'm exploring the Microsoft Bot Framework V4 and I'm currently checking the CafeBot Sample found at BotFramework Samples. When moving it locally, I can't build it because it seems that the preview version of the Bot.Builder package on nuget is older than the one with the changes committed on GitHub.
One particular line of code that is failing is the OnTurnError option in the BotFrameworkOptions which does not exist in the current nuget package but can be found in the source code on GitHub.
In addition, the version used within the sample is a stable 4.0 one, which cannot be found If I create a new project from within Visual Studio following this guide.

Therefore, how can I use the newer version of botframework with my own project and compile it as well? Should I include a new nuget source somehow to get newer prerelease packages?

A: This issue got solved with the release of the Bot Framework V4 Stable release.
Issue on GitHub: https://github.com/Microsoft/BotFramework-Samples/issues/41


text:
Q: Brezis's Functional Analysis Exercise 1.14 - Why is there no closed hyperplane separating $Y$ and $Z$? Consider Exercise 1.14 in Brezis' Functional Analysis, Sobolev Spaces and Partial Differential Equations below. My question regards item 3.. How to solve this? I am trying to show that there is no such hyperplane, by supposing that there is and arriving at a contradiction:

Let $Z = X - c = \{x - c \ : \ x \in X\} = \{z \in \ell^1 \ : \ z_{2n} = -1/2^n \}$. Suppose there is $u \in Y \cap Z$. Then $y_{2n - 1} = -1$ for all $n \geq 1$ and therefore $y \notin \ell^1$, a contradiction. Hence $Y  \cap Z = \emptyset$.
Suppose now that there is a closed hyperplane separating $Y$ and $Z$. Then there is some $f \in (\ell^1)^*$ such that
$$
f(y) \leq \alpha \leq f(z) \quad \forall y \in Y, z \in Z,
$$
where $[f = \alpha]$ is the hyperplane. Then there is $u \in \ell^\infty$ such that
$$
\sum_{n = 1}^\infty u_n y_n \leq \alpha \leq \sum_{n = 1}^\infty u_n z_n, \quad \forall y \in Y, z \in Z.
$$
But $Y$ is a subspace, so $f$ can only be bounded in $Y$ if $Y \subset \ker f$.

Here I am stuck. Any hints will be the most appreciated. Thanks in advance and kind regards.


text:
Q: Recovering lost files due to ntfs-3g from an ntfs partition I mounted my Windows partition on my Mac using the steps outlined here:
https://github.com/osxfuse/osxfuse/wiki/NTFS-3G
Then, moved a folder (CMD-OPT-V) from NTFS partition to my OS X partition. It asked me for my administrator password. It created the folder, however it did not move the files. The files in the original location were also deleted.
The files are no longer in the Windows partition nor the OS X partition. I have run chkdsk by logging in Windows, and the files are not there.
I ran percuva to find deleted files, but it could not find any.
Is there a way to recover deleted files from NTFS?
PS: Later on, I tried to reproduce if the problem exists if I just simply copy the folder. I was able to. The folder structure was copied, but none of the files were for other folders on the disk.


text:
Q: background color works in index.html but not user-interface.css In the index.html file I am able to do this an it works as designed:
 <!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Demo</title>

My partner would like to keep the background-color in our css file  user-interface.css.  Which makes sense to me but it is not working as I would expect.
When I enter the background-color it doesn't show up and leaves my background-color as white.
What am I missing?
* Universal Settings */
    .body{
            background-color : AE8E4A0;
            font-family: Arial;
    }
    /* Search bar */
    .heading {
            font-size: 30px;
            padding: 16px 0;
            color: #444;
            text-align: center;
    }/*Container*/`enter code here`

Thanks
Scott

A: You have a minor error on your code. You should not put the dot (.) in front of body as it is not a class name, it's an element. Same for the heading. So your code should be like:

/* Universal Settings */
    body{
            background-color : #AE8E4A0;
            font-family: Arial;
    }
    /* Search bar */
    heading {
            font-size: 30px;
            padding: 16px 0;
            color: #444;
            text-align: center;
    }/*Container*/
<!DOCTYPE html>

    <link href="cssfilename.css">

    <meta charset="utf-8" />
    <title>Demo</title>

Also, you would need to link your CSS to your HTML file. Not that the "cssfilename.css" need to be replaced by the filename of your css file, and they need to be in the same directory.

A: added to CSS background-color: #A8E4A0; and verified the link in my htlm was correct

A: Try this:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>My first Website!</title>

This is a paragraph!

If you want the style in a seperate .css file, try this:

/* style.css */

/* Needs to be in the same folder/directory as the .html file is. */

body {
    background-color: #A8E4A0;
    font-family: arial;
}

p {
    color: green;
}

<!DOCTYPE html>

     <link rel="stylesheet" href="style.css" />
     <meta charset="UTF-8" />
     <title>My first Website!</title>

This is a paragraph!


text:
Q: Is this the right way to detect connection to a WiFi network? I'm making an application for Android that needs to react to when the device gets connected to a WiFi network, I'm currently trying to implement it using a BroadcastReceiver to monitor android.net.ConnectivityManager.CONNECTIVITY_ACTION - is this way correct, or is there a way that would be more appropriate?

A: @Jase, You need to register to receive WifiManager.NETWORK_STATE_CHANGED_ACTION. The intent has a NetworkInfo extra. Examine it to find its state. If the state is NetworkInfo.State.CONNECTED, then you are connected to a network.
For sample code on achieving this, look here.

A: Take a look at WifiManager.WIFI_STATE_CHANGED_ACTION

Broadcast intent action indicating
  that Wi-Fi has been enabled, disabled,
  enabling, disabling, or unknown. One
  extra provides this state as an int.
  Another extra provides the previous
  state, if available.

and WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION

Broadcast intent action indicating
  that a connection to the supplicant
  has been established (and it is now
  possible to perform Wi-Fi operations)
  or the connection to the supplicant
  has been lost. One extra provides the
  connection state as a boolean, where
  true means CONNECTED.

Read from the broadcast or do a check when you get any of them like:
WifiManager wifi=(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int state=wifi.getWifiState();

Now you can check state, it will be one of

*

*WIFI_STATE_DISABLED

*WIFI_STATE_DISABLING

*WIFI_STATE_ENABLED  <-- With this you can send/receive data

*WIFI_STATE_ENABLING

*WIFI_STATE_UNKNOWN


text:
Q: How can I connect central and decentral databases? I am working in computational science and we are frequently producing large amounts of highly-structured data that depends on various input parameters. Right now, storing the data is managed via files, but analyzing and querying the data by using relational databases and SQL seems way superior to me.
I am suggesting to use a central database server (i.e. PostgreSQL), which is especially helpful when it comes to reproducably reporting and "backing up" the data or making it accessible to others. However, sometimes the data we produce is "worthless" and known that it can be immediatly discarded after quick inspection, thus, it makes only sense to store the data (if at all) on a central server if it has any worth. Each of this data-production runs can generate data usually from 100s of KB to 10s of GB, so depending on the amount, transfer through the network to the server can be expensive. While it is no problem when querying data (as you can decide what you need on server side), when filling the database, large amounts of data have to be moved.
What I would like to do is to locally generate the data (i.e. written to a local hard drive) and then explicitly (or implictly during night times) commit the data to the real SQL server if it is good. It would be nice if the codes that generate this data don't have to be adapted for each case where the data is determined for the local database or to be directly sent to the remote server, somewhat similar to git where I can push a local repository to the remote one (and vice-versa, if required).
I was thinking of combining SQLite and PostgreSQL, such that local SQLite databases are migrated to the server if required. However, if done like this, only features supported by both systems can be used (which is not bad, but a limitation). Also, migrating databases and table structures from SQLite to PostgreSQL is surely not trivial, I guess it requires some additional scripting.
The other option would be to install local PostgreSQL servers on each computer (which seems overkill to me), but they would be more compatible with the server + I could use features like pg_dump to migrate the data + its table structure.
As I am pretty unexperienced on the possibilities, is there already some kind of (Open source) software available that can approximately do this or do I have to come up with a complete home-brew solution?


text:
Q: SSH to EC2 instance using boto on private IP through bastion server I am trying to execute some bash script on EC2 instance using boto. Boto provides a way SSH to EC2 instance on public IP but in my case the instances have only private IP. The way SSH is done on these instance is using a host which can SSH on all the instance using private IP (Bastion host).
Following is the script to connect to instance on public IP:
s3_client = boto3.client('s3')
s3_client.download_file('mybucket','key/mykey.pem', '/tmp/mykey.pem')
k = paramiko.RSAKey.from_private_key_file("/tmp/mykey.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host=event
print "Connecting to " + host
c.connect( hostname = host, username = "ec2-user", pkey = k )

How to connect to instances if host have private IP instead of public key if we want to connect through bastion host with public IP P.P.P.P

A: If your requirement is to trigger execution of some code on an Amazon EC2 instance, then it would be better to use the Amazon EC2 Run Command rather than try to automate an SSH connection.

Amazon EC2 Run Command provides a simple way of automating common administrative tasks like executing Shell scripts and commands on Linux, running PowerShell commands on Windows, installing software or patches, and more. Amazon EC2 Run Command allows you to execute these commands across multiple instances and provides visibility into the results, making it easy to manage configuration change across fleets of instances.

Your instances would need the Amazon EC2 Systems Manager (SSM) agent installed. See: Installing SSM Agent
You would then run commands on Amazon EC2 instances from the management console, AWS Command-Line Interface (CLI) or via an API call.
The send command does not accept tags as input. However, you could first perform a list-instances command to search for instances by tag, then pass the instance-ids to the send command. See: AWS CLI send-command


text:
Q: Derive the partial of cost function for logistic regression. I'm not sure how to derive the formula for updating the parameters vector $\theta$ in logistic regression with cost function $$J(\theta)=\frac{-1}{m}[\sum_{i=1}^{m}y^{(i)}\log h_{\theta}(x^{(i)})+(1-y^{(i)})\log(1-h_{\theta}(x^{(i)}))]$$
Here, $h_{\theta}=\frac{1}{1+e^{-\theta^{T}*x}}$ and $x^{(i)}, y^{(i)}$ is the $i^{th}$ observation in the sample of $m$ observations.
In the lecture, they say that we update each $\theta_j$ by substracting from it the learning rate times the partial of $J(\theta)$ with respect to $\theta_j$. Which gives $$\theta_j:=\theta_j-\alpha\sum_{i=1}^m(h_\theta(x^{(i)})-y^{(i)})x_j^{(i)}$$
Also, in one of the assignment, they gave option for
$$\theta_j:=\theta_j-\alpha\frac{1}{m}\sum_{i=1}^m(h_\theta(x^{(i)})-y^{(i)})x_j^{(i)}$$
But I wasn't able to get the partial of $J(\theta)$.
Here is what I get:
$$ \frac{\partial J}{\partial \theta_j}=\frac{-1}{m}\sum_{i=1}^mx_j^{(i)}(-h_{\theta}(x^{(i)})y^{(i)}-h_{\theta}(x^{(i)})^2(1-y^{(i)})e^{\theta^T*x^{(i)}})$$

A: Just to remove a little of indices, let me consider the case with $m=1$ and $x,y$ are scalars and not vectors. In this case $J$ becomes:
$$J(\theta,x,y) = -y \log(h_\theta(x)) - (1-y) \log(1-h_\theta(x))$$
$$\frac{\partial h_\theta}{\partial \theta}(\theta,x) = \frac{\partial}{\partial \theta}((1+e^{-\theta x})^{-1}) = x e^{-\theta x} h_\theta^2(x)$$
$$\frac{\partial J}{\partial \theta}(\theta,x,y) = -y\frac{x e^{-\theta x} h_\theta^2(x)}{h_\theta(x)} + (1-y)\frac{x e^{-\theta x} h_\theta^2(x)}{1-h_\theta(x)} = x e^{-\theta x} h_\theta^2(x)(\frac{1-y}{1-h_{\theta}(x)}-\frac{y}{h_\theta(x)})=$$
$$= \frac{x e^{-\theta x} h_\theta(x)}{1-h_\theta (x)}((1-y)h_\theta (x) - y(1-h_\theta (x))) = \frac{x e^{-\theta x} h_\theta(x)}{1-h_\theta (x)} (h_\theta(x) - y)$$
Noticing that $e^{-\theta x} h_\theta(x) = 1-h_\theta(x)$, $\frac{\partial J}{\partial \theta}(\theta,x,y) = x(h_\theta(x) -y)$.


text:
Q: Is openssl wrongly rejecting this session request? I have OpenSSL 1.1.1n on a Debian11 server, configured to use MinProtocol = TLSv1.2
When the server receives a ClientHello as below:
TLSv1.2 Record Layer: Handshake Protocol: Client Hello
    Content Type: Handshake (22)
    Version: TLS 1.0 (0x0301)
    Length: 142
    Handshake Protocol: Client Hello
        Handshake Type: Client Hello (1)
        Length: 138
        Version: TLS 1.2 (0x0303)

with Record Layer Version set to TLSv.1 but with Handshake Version set to TLSv1.2 it rejects it with a Protocol Version alert and closes the connection, when according to https://datatracker.ietf.org/doc/html/rfc5246#appendix-E this looks like an accepted behavior and should not be rejected.
Is openssl breaching the RFC here, or am I missing a configuration parameter that I can adjust to fix this?
On the other hand, when I decrease the MinProtocol to TLSv1, the server accepts the ClientHello and responds with a TLSv1 Handshake, which causes the entire session to be over TLSv1 and is not accepted by the other party.

A: I have found out that setting both MinProtocol and MaxProtocol as below:
MinProtocol = TLSv1
MaxProtocol = TLSv1.2

fixes the both issues.


text:
Q: How do I upgrade my west of loathing stats how do you up your stats in west of loathing? As in what button do I use for it if tried the arrows and stuff but I cant find it out

A: By default, your character will be upgraded automatically as soon as you accumulated enough XP for the next upgrade the algorithm considers appropriate.  If you prefer to manage your character progression yourself, you can switch that off by unchecking "Automatically Spend XP" in the options menu.
You can increase your stats in your character menu (C) by clicking on the crosses (red circles). Note that in order to do that, you need enough unspent XP points (green circle). You gain XP mostly by winning battles and completing quests, but there are also various other activities in the game which give you small amounts of XP.


text:
Q: Java 8 - Initialising List (List) I have a question concerning Java 8 and Lists. Is it possible to initialise a List easier than my code below is?
final List<List<ScheduleIntervalContainer>> weekScheduler = new ArrayList<>();

weekScheduler.add(0, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(1, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(2, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(3, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(4, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(5, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(6, new ArrayList<ScheduleIntervalContainer>());

A: You can use:
List<List<ScheduleIntervalContainer>> weekScheduler =
     IntStream.rangeClosed(0, 6).mapToObj(i -> new ArrayList<ScheduleIntervalContainer>())
                                .collect(Collectors.toList());

This will create a Stream of int values going from 0 to 6 (included), map each of those ints to a new ArrayList of your class and collect the result to a List.

A: You can use a loop or an IntStream.
final List<List<ScheduleIntervalContainer>> weekScheduler = new ArrayList<>();
IntStream.range(0, 7).forEach(day -> weekScheduler.add(new ArrayList<>()));

A: Personally I would just use a for loop:
List<List<ScheduleIntervalContainer>> weekScheduler = new ArrayList<>();
for (int i = 0; i < 7; i++)
    weekScheduler.add(new ArrayList<>());

However, if you want a Java 8 solution:
List<List<ScheduleIntervalContainer>> weekScheduler
        = Stream.generate(ArrayList<ScheduleIntervalContainer>::new)
                .limit(7)
                .collect(Collectors.toList());

A: Whenever I code with lists, I use a for loop to speed up the declaration. In your case, I would heavily suggest a loop of any kind, but a for loop would probably be the easiest.


text:
Q: Insert from multiple rows and update some static values at the same time? I am trying to insert some rows form a select statement. The select statement returns multiple rows but with each row insert I want to update a few other columns.
This is what I have so far
INSERT INTO {$this->db->dbprefix('term_response')}
SET `Crs Code` = (
   SELECT `Crs Code`
   FROM {$this->db->dbprefix('EnrolmentsList')}
   WHERE `Person ID` = ?
),`term_id` = ?, `st_id` = ?

I'm getting 'Subquery returns more than 1 row'. Can I not do what I'm trying?
Thanks

A: If you want to insert static values for other fields you could do something like this:
INSERT INTO {$this->db->dbprefix('term_response')}
SELECT `Crs Code`, 'my term_id value', 'my st_id value'
FROM {$this->db->dbprefix('EnrolmentsList')}
WHERE `Person ID` = 12345;


text:
Q: javascript facebook check if user is fan of a page This is my code:

But I have returned Error String... what I am doing wrong?

A: To get if the user is fan of the page or not you can do this :
FB.api({
    method:     'fql.query',
    query:  'SELECT uid FROM page_fan WHERE uid=user_id AND page_id=page_id'
}, function(resp) {
    if (resp.length) {
        alert('A fan!')
    } else {
        alert('Not a fan!');
    }
}
);

You can read more about this here : http://www.masteringapi.com/tutorials/facebook-api-check-if-a-user-is-fan-of-a-facebook-page/20/
Similar Question :
Facebook Javascript, How to detect if user is a fan of my facebook page? While on my site?

A: I wasn't performing the login and token access!
https://developers.facebook.com/docs/howtos/login/getting-started/


text:
Q: Facebook like button stopped working I started having problems a couple of days ago with the Like button on my Facebook application page. It has been working for almost 6 months but stopped working yesterday. When I am logged into my own Facebook account I see the 'Like' count, but if I am logged out or logged in as anyone who hasn't already 'Liked' my app, it doesn't work. They see the button as if nobody has 'liked' it yet and when they click it, it seems to reset every time.
The URL I am trying to like is an APP URL. My code is pasted below.
<iframe src="http://www.facebook.com/plugins/like.php?app_id={myAppId}&href={myAppURL}&send=false&layout=button_count&width=450&show_faces=false&action=like&colorscheme=dark&font&height=21"
        scrolling="no" frameborder="0"
        style="border:none; overflow:hidden; width:450px; height:21px;"
        allowTransparency="true">
</iframe>

I've tried a few variants of this code, but I can't seem to get it to work. Even when I go to the page that generates 'Like' button code on Facebook and give it my URL, I see the same problem. When I click the button I get the text "Error" in red to the right of the button. I've seen an article on Mashable that this same problem happened about a year ago for some people...

A: Try replacing the http:// part of the src attribute with //
So it should look like this:
<iframe src="//www.facebook.com/plugins/like.php?app_id={myAppId}&href={myAppURL}&send=false&layout=button_count&width=450&show_faces=false&action=like&colorscheme=dark&font&height=21"
  scrolling="no" frameborder="0"
  style="border:none; overflow:hidden; width:450px; height:21px;"
  allowTransparency="true">
</iframe>


text:
Q: AWS SQS pricing with JPM Listeners Reference: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/getting-started.html
In AWS documentation, they have suggested approach with JMS listener under "Receiving messages asynchronously" section. After 1 million request aws sqs costs 0.4$ per request usually. Under the hood, listener is polling only. Will AWS charge us for each poll request it makes internally when we use listener or for each received message?
Could not find this information on AWS billing page.

A: Polling SQS also count towards request. Receiving a message or not is another metric and is called size of payload. So 1 million free requests in SQS also include polling (both long and short).
ref: https://aws.amazon.com/sqs/pricing/
API Actions    Every Amazon SQS action counts as a request.


text:
Q: Transform a locale-aware unicode string in a valid Decimal number in Python/Django In my Django 1.7.11 app, I get data formatted with a spanish locale via HTTP. So, in my view, I get a unicode string representing a decimal number in spanish locale:
spanish_number = request.GET.get('some_post_value', 0)
# spanish_number may be u'12,542' now, for example. And may come via POST. This is not important. Just the value itself is important: it contains commas as decimal separator.

And I want to store that in a Django Model's field of type DecimalField:
class MyModel(models.Model):
    my_number = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True)

In my settings.py, I have
USE_L10N=True
USE_I18N=True

If I try something like
m = MyModel()
m.my_number = spanish_number # This is, u'12,542'
m.save()

It fails with a ValidationError because
u'12,542' must be a decimal number

What would be the right way to deal with this? I mean, with the fact that my application is going to receive numbers (and dates...) formatted this way (spanish locale)
P.S.: I know Django has a DecimalField for forms, with a localize=True option, but I'm directly dealing with Models, not with Forms.

A: You're on the right track looking at form DecimalField. If you check its source, you'll see that when set to localize it runs the string through formats.sanitize_separators. You can call this directly to convert to the format Decimal() expects:
import django.utils.formats
m.my_number = formats.sanitize_separators(spanish_number)


text:
Q: Fatal error: Call to a member function find() on a non-object I am new to php.
I getting

Fatal error: Call to a member function find() on a non-object error,

I included simple_html_dom.php
<?php
include 'simple_html_dom.php';
$htm = file_get_html('http://www.thatscricket.com');

$es = $htm->find('div[class=score_card_display_below_links]');

$value = $es[0]->href;

$link = "http://www.thatscricket.com/$value";

$html = file_get_html('$link');

$scr = $html->find('span');

echo "$scr";
?>

A: $html = file_get_html('$link');

This will try to get the literal string '$link' (variables aren't expanded inside single quoted strings). Which means $html will be null or false.
Since $html isn't an object you can't call methods on it.
Use:
$html = file_get_html($link);

You should also always check return types that may be false or null due to failure so that you can fail gracefully.

A: $htm = file_get_html('http://www.thatscricket.com');

check var_dump($htm);
I think it returns bool(false)
$html = file_get_html('$link');

should be
$html = file_get_html($link);

A: check the var_dump($htm) first, it must be returning null

A: I had also the same error I found it solution from php count function like this
if( $htm ){
     $score_card_count = count($htm->find('div[class=score_card_display_below_links]'));
     $score_card_count = trim($score_card_count);
         if( $score_card_count > 0 )
         {
              $es = $htm->find('div[class=score_card_display_below_links]');
              $value = $es[0]->href;
         }
}

I hope it will work fine from this approach my error is fixed.


text:
Q: Sending data from html.index to functions.js file Currently, I am stuck on working with a .html file which needs to send over data to a javascript file with functions. It looks as follows:
Data
let data = [
    ["ID1", "URL1"],
    ["ID2", "URL2"],
    ["ID3", "URL3"],
]

HTML part calling javascript functions file with
<!DOCTYPE html>
<html>
  <head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="utf-8" http-equiv="encoding">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
    <title>Metabase Dashboard Carousel</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="./src/carousel.js"></script>
  </head>
  <body onLoad="createFrames('test!')">
    <button class="btn btn-primary " onclick=autoRun()>Start</button>
    <button class="btn btn-primary " onclick=pause()>Pause</button>
  </body>
</html>

Function which is called
function createFrames(text) {
    console.log(text);
    for(var i in data)
        prepareFrame(data[i][0], data[i][1]);
};

Calling the function does give me a print of test! on the .html console with Mozilla inspector. However, running the rest of the script or actually using the data variable as input in the body onLoad function does not work.

*

*How does this come and what would be a fix?

*Also, not directly related what is a good way to load files between related .js / .yml / .json as when running the code in .html gives back that require is not defined?

Thanks for the help!

A: If you are able to modify your approach and are wanting to define the runtime data that will be used by the onload function you might try an approach like this. This uses an anonymous self executing function to run the prepareFrame commands once the DOM has been fully loaded. The data is supplied as an argument to the anonymous function and other functions can be defined within this scope so as to keep the whole thing neat.

(function(data){
  const d=document;

  // emulate actual functions with simple console cmds for testing only
  const prepareFrame=(a,b)=>{
    console.log('prepareFrame(%s,%s)',a,b)
  };
  const autoRun=(e)=>{console.log(e.target);return true};
  const pause=(e)=>{console.log(e.target);return true}

  d.addEventListener('DOMContentLoaded',()=>{
     data.forEach(a=>{
      prepareFrame(a[0],a[1])
     });

     d.querySelectorAll('button[data-task]').forEach(bttn=>bttn.addEventListener('click',function(e){
      switch(this.dataset.task){
        case 'start':return autoRun(e);
        case 'pause':return pause(e);
      }
     }))
  })
})([
  ["ID1", "URL1"],
  ["ID2", "URL2"],
  ["ID3", "URL3"],
]);
<button class='btn btn-primary' data-task='start'>Start</button>
<button class='btn btn-primary' data-task='pause'>Pause</button>

For instance:
<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html;charset=utf-8' http-equiv='Content-Type' />
    <meta content='utf-8' http-equiv='encoding' />

    <title>Metabase Dashboard Carousel</title>
    <link href='//cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We' crossorigin='anonymous' />

    <script src='//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
    <script src='./src/carousel.js'></script>
  </head>

  <body>
    <button class='btn btn-primary' data-task='start'>Start</button>
    <button class='btn btn-primary' data-task='pause'>Pause</button>
  </body>

  <script>
    (function(data){
      const d=document;

      // emulate actual functions with simple console cmds for testing only
      const prepareFrame=(a,b)=>{
        console.log('prepareFrame(%s,%s)',a,b)
      };
      const autoRun=(e)=>{console.log(e.target);return true};
      const pause=(e)=>{console.log(e.target);return true}

      d.addEventListener('DOMContentLoaded',()=>{
         data.forEach(a=>{
          prepareFrame(a[0],a[1])
         });

         d.querySelectorAll('button[data-task]').forEach(bttn=>bttn.addEventListener('click',function(e){
          switch(this.dataset.task){
            case 'start':return autoRun(e);
            case 'pause':return pause(e);
          }
         }))
      })
    })([
      ["ID1", "URL1"],
      ["ID2", "URL2"],
      ["ID3", "URL3"],
    ]);
  </script>
</html>


text:
Q: Azure Devops send closed work items to slack I am having a release pipeline in Azure Devops which will send my generated .msi file to a slack channel. This is a good way to give a running testable installation to my testers. The problem here is, that they don't know which User Stories are resolved and which they need to test. So is there a way to also send the closed User Stories / Tasks since the last Pull Request?

A: There are several ways to send the closed User Stories/Task to the testers.
For example you can create a query to get all the closed workitems. Query supports to email the query results. Please check the tutorial to create a query.

You can also send the query from the pipeline using Scheduled Work Item Query extenstion. Install this extension and then add Scheduled Work Item Query task in your pipeline.
If you want to retrieve the closed workitems by adding a script task in the pipeline to call rest api. You can refer to this thread.
You can also check out integration Azure Boards with Slack or Azure devops with Slack, which will send notifications for update workitem events in to Slack channel.


text:
Q: How to improve okhttp3 performance during cold startup I've run nimbledroid profiler and I've came across many ocurrences following method chain:

Is there a way to cache or bypass systemDefaultTrustManager?

A:
I've came across many ocurrences following method chain

You are creating many instances of OkHttpClient.

Is there a way to cache or bypass systemDefaultTrustManager?

Cache the instance of OkHttpClient.

Many libraries are creating in internally, so those calls are piling up

Then do one of the following:

*

*Find a means of supplying an OkHttpClient instance to the library, so that you can create the OkHttpClient instance yourself and cache it, or

*Work with the developers of that library to provide a means of supplying an OkHttpClient instance to the library, or

*Fork the library, if it is open source, and add a means of supplying an OkHttpClient instance to the library, or

*Switch to a different library


text:
Q: Selenium Chrome WebDriver - How to login in "your connection is not private" on redirect login site I want to test a website in a private network. When I go to "http://www.crazysite.com" the proxy redirects me to "http://login.craxysite.com/?aLotOfParams=true". This site opens the "your connection is not private" popup.

I tried to skip the authorization with ChromeOptions without success.
Can I log in on it? How?
WebDriver driver = new ChromeDriver();
driver.get("http://www.crazysite.com");
System.out.println(driver.getPageSource());

getPageSource() Give me the page under the popup.
I use Chrome e ChromeDriver Version 88.0.4324.


text:
Q: Why do Fibonacci Digits always return to either 11 or 14? I recently posed a question on Code Golf on what I'm terming "Fibonacci Digits", where each number is the sum of the previous two digits, not necessarily the previous two numbers. So, for instance, the series beginning $1,1$ is $1,1,2,3,5,8,13,4,7,11,2\dots$ and cycles from there.
As I note in the various examples I bring there, unless something in the series manages to add to either $0$ or $14$, the series seems to always loop to some rotation of $2,3,5,8,13,4,7,11$. Further, it always reaches $0$ or $14$ no later than the third entry in the series. For instance, $S_1=7,7,14,5,9\dots$, $S_2=14,5,9\dots$, $S_3=68,14,5,9\dots$.
In other words, it seems that for $0\le(a,b)\le9$, then, for $a+b=c$:

*

*If $c<10$, let $d=b+c$

*If $c\ge10$, $c=10x+y$ for some integers $0\le(x,y)\le9$. Let $d=x+y$.

*Repeat the above using $c$ and $d$.

Eventually, assuming that you don't start with $0$, this algorithm will yield either $11$ or $14$. Seemingly.
My question is two parts:

*

*Is my assessment correct?

*If so, why?

A: I'll assume you do not allow negative starting values (it makes sense not to, since we're interested in digits).
Let's start with the second question: Why are 0 and 14 always reached early?
Let's start with 14. How can we reach 14? Let's start with 14, and reconstruct the sequence backwards, digit by digit.
The only two-digit numbers possible are $10$ to $18$, so we need to take care of the case of having two-digit numbers only if the digit-by-digit reconstruction generates a one after a digit 0-8 (remember, we're reconstructing backwards).

*

*$14, 9, 5, 4, 1$. This makes two options

*

*The 4, 1 actually comes from 14 (backwards), so the forward sequence is $14, 5, 9, 14$ and we're already in a cycle.

*The sequence is $14, 9, 5, 4, 1, 3$. We can't continue beyond the 3 unless we allow negative numbers.

*$14, 8, 6, 2, 4$. We can't proceed without allowing negative numbers.

*$14, 7, 7, 0, 7$

*$14, 6, 8$

*$14, 5, 9$
So 14 can't come later than position 6.
The only way to get 0 is if you start with 0, 0. Otherwise you can get 10, but then you have 10, 1, 1, 2, and you get into the standard sequence.
Now, to the first question. Again, we have only 9 possible 2-digit numbers that we can reach, so we can easily confirm that each eventually sends us to the standard sequence $1, 1, 2, \dots$:

*

*$10, 1, 1$

*$11$ done :)

*$12$ done :)

*$13, 4, 7, 11$

*$15, 6, 11$

*$16, 7, 13$ and we know $13$ sends us to 11

*$17, 8, 15$ and we know $15$ sends us to 11

*$18, 9, 17$ and we already know 17

*$19, 10, 1, 1$.

Now, this brute force check is simple enough, but it's boring. That said, there is some intuition behind why (almost) all Fibonacci digit sequences eventually send us to the standard sequence 1, 1, 2... And it's because 10 and 11 send us there. If you consider sums of digits, then there's only 1 way to get 0: 0 + 0. Similarly, we have only 1 way to get 19. However, we many more ways to get 10 and 11 as a sum of two digits. In fact, if you take 2 random digits, the most likely outcome is 10, followed shortly by 11 (and 9). So, eventually, you're very likely to reach either 10 or 11.

A: From the second entry on, no entry can be larger than $9+9=18$.  As an entry only depends on the previous two entries, there must be one or more cycles that can be created.  I have found $(2,3,5,8,13,4,7,11)$, $(5,9,14)$, and $0$ as cycles.  We can just try all $100$ pairs of single digits to start the sequence.  Starting with a two digit number is the same as starting with the two individual digits, so we don't have to try that.
$0$ only comes from starting $(0,0)$
$5,9,14$ comes from $ (0,7),(1,4),(2,6),(3,1),(4,2),(4,5),(5,9),(6,8),(7,0),(7,7),(8,6),(9,5)$
Note that $(3,1)$ only gets to $14$ at the sixth term.
All other starting pairs go to $2,3,5,8,13,4,7,11$ eventually.  The latest $11$ comes up is the sixteenth term starting from $(0,2)$


text:
Q: Using websockets with Alexa skills kit I have an hello world alexa skill written in node js and deployed it in heroku.
I have to use websockets to send the response to a web ui(say a html page in my local machine).Is this possible?
my server code-server.js
'use strict';

var AlexaAppServer = require( 'alexa-app-server' );

var server = new AlexaAppServer( {
 httpsEnabled: false,
 port: 8080
} );

server.start();

below is index.js
 module.change_code = 1;
  'use strict';

var alexa = require( 'alexa-app' );
var app = new alexa.app('Helloworld');

 app.launch( function( request, response ) {
console.log(app);
//console.log(request);
response.say( 'Welcome to Welcome to helloworld.' );

});

app.error = function( exception, request, response ) {
 console.log(exception)
 console.log(request);
 console.log(response);
 response.say( 'Sorry an error occured ' + error.message);
};

app.intent('Helloworld',
{
 "slots":[]
 ,"utterances":[
    "hello alexa",
    "hi alexa",
    "how are you?"]
},
function(request,response) {

  response.say("welcome user");
//send this same response to a webpage using socket

}
);

module.exports = app;

A: are you trying todo html page interactive with alexa . if yes you are right you have to use websocket , But you can try API gateway provided in AWS itself, In API gateway you can invoke it to your html page ,This link may help you somewhat .
https://blog.prototypr.io/using-voice-commands-to-control-a-website-with-amazon-echo-alexa-part-1-6-a35edbfef405


text:
Q: Define fields only once I'm looking for a method to describe fields in a structured way, so I am able to reuse it in various languages and levels of my application.
For instance, if I'm developing an Android application about food items, I might be dealing with fields like Name, Description, Price and Kcal. However, these fields will appear multiple times: In the viewholder of my Android application, in the C++ server which handles the messages, in my SQL database which stores them, etc. Imo, this violates the DRY principle, and if I also want to save the barcode of a food item for example, I need to add it to all these places.
I've been thinking about using XML or TDL, but I'm not sure if those languages are intended for this goal. Preferably, I would have a file like this:
Fieldname   Type        Lower bound Upper bound May be NULL
-----------------------------------------------------------
Name        string      3           100         No
Price       float       0           *           Yes
...

Of course I could create such a thing myself, but would that be a good way to go? Or is there something out there which is used for this purpose (I want to avoid beginners mistakes). Preferably, I would have these definitions been read out at compile-time because the definition won't be altered at runtime anyway.

A: There are already frameworks like this, for example the ORM ones. This will ensure that you don't have to define the SQL structure too. I'm more familiar with the Java ones, like DataNucleus or Hibernate.
Based on the same code annotations, you can generate the domain model for the Android application.
But, in my experience, maintaining such a framework, will soon become very expensive, as most probably you will need a lot of exceptions, like different constraints (URL, all lowercase, list etc).
If you would use Java on the server side, you can actually use the same classes for the domain model on both client and server. But, there could also be the case that you want a thinner model on the client side (the Android app) than on the server side (Java or C++ server).

A: A few of thoughts:

*

*The problem with fields is that they are a code abstraction rather than a business domain abstraction.

*Treating name, price, kcal, etc. as types rather than fields [e.g. using typedef in C++ and wrapper classes for primitives in Java] focuses on what is common and black boxes implementation details such as the differences between the representation of strings in Java and C++ and their immutable/mutable natures respectively.

*Aspects of the system which boil down to typechecking such as validation requirements (along the lines of name.length being between 3 and 50) can live on their own layers behind API's.
Implicitly, the direction you're heading is toward a Domain Specific Language. Thinking about types and type-checking is a foundation upon which one might be built.


text:
Q: Why is "None" value In clientIDArray? openPyxl places a None value if cell is blank but I would think my logic prevents the None value from being populated into array.
from openpyxl import Workbook

from openpyxl import load_workbook

wb = load_workbook("sample.xlsx")

sheetArray = []

for sheetName in wb.sheetnames:
    sheetArray.append(sheetName)
    # print(sheetName)

sheet_1 = wb[sheetArray[0]]

lastRow = sheet_1.max_row

# print(lastRow)

clientIDArray = []

for row in sheet_1.iter_rows(min_row=1, max_row=lastRow, min_col=1, max_col=1):
    if [row[0].value] != "None":
        clientIDArray.append(row[0].value)

for id in clientIDArray:
    print(id)

wb.close()

A: First, if [row[0].value] != "None": is comparing a list whose single element is row[0].value. That list can never be equal to None or "None" or anything else but a list. You probably wanted to just compare row[0].value.
Second, the values you're trying to filter out are presumably None values, not string values whose characters are "None".
Third, if the last one is right, you almost always want to use is, not ==, to compare with None.
So:
if row[0].value is not None:

A: You should change the code like this. None is built-in object.
https://docs.python.org/3.6/library/constants.html#None
if row[0].value is not None:

A: Where you have put
if [row[0].value] != "None":
    clientIDArray.append(row[0].value)

the [row[0].value] is creating a list with the row[0].value as its item. This means that as a list, it will never be None, hence your if statement always executes, and the None value gets put into the array.
If row[0].value is None then your if statement becomes
if [None] != "None":

and a list can never be None.
Also, you should use None over "None"


text:
Q: Sorting dataframe by one column based on other column I am trying to sort the Sex column. When I try to sort, I get all Male and all Female together. But I want to sort the Sex column between the countries. Also, please note the IND should be at the bottom of the country.
Suppose, the dataset is
Country<- c("France","France", "Germnay", "Germnay", "UK", "UK", "IND", "IND")
Sex <-c("Female", "Male", "Female", "Male", "Female", "Male", "Female", "Male")
A<- c(10, 20, 30 ,40 ,50 ,60 ,70 ,80)
B <- c(20, 30, 40, 50, 56, 84, 75, 85)
dt <- data.frame(Country, Sex, A, B)

When I try sorting with order(), I get the below output (screenshot is an example not with the same dataset)
dt <-dt[with(dt, order(dt$sex, decreasing = TRUE)),]

The desired output is
Country<- c("France","France", "Germnay", "Germnay", "UK", "UK", "IND", "IND")
Sex <-c("Male", "Female", "Male", "Female", "Male", "Female", "Male", "Female)
A<- c(10, 20, 30 ,40 ,50 ,60 ,70 ,80)
B <- c(20, 30, 40, 50, 56, 84, 75, 85)
output <- data.frame(Country, Sex, A, B)

A: You have to sort both on country and sex. However, if you don't want the country variable to be sorted alfabatically, you can convert it to a factor variable first and define its levels in the order you want.
#Sample data
Country<- c("France","France", "Germnay", "Germnay", "UK", "UK", "IND", "IND")
Sex <-c("Female", "Male", "Female", "Male", "Female", "Male", "Female", "Male")
A<- c(10, 20, 30 ,40 ,50 ,60 ,70 ,80)
B <- c(20, 30, 40, 50, 56, 84, 75, 85)
dt <- data.frame(Country, Sex, A, B)

#Convert country to factor variables and define its levels in desired order
dt$Country <- factor(Country, levels = c("France", "Germnay", "UK", "IND"))

Using the data.table:
library(data.table)
dt[with(dt, order(Country, desc(Sex))),]

  Country    Sex  A  B
2  France   Male 20 30
1  France Female 10 20
4 Germnay   Male 40 50
3 Germnay Female 30 40
6      UK   Male 60 84
5      UK Female 50 56
8     IND   Male 80 85
7     IND Female 70 75

Using the dplyr package:
library(dplyr)
dt %>% arrange(Country, Sex)

Output:
 Country Sex        A     B
  <fct>   <chr>  <dbl> <dbl>
1 France  Male      20    30
2 France  Female    10    20
3 Germnay Male      40    50
4 Germnay Female    30    40
5 UK      Male      60    84
6 UK      Female    50    56
7 IND     Male      80    85
8 IND     Female    70    75


text:
Q: How to read email using Python 3 Now I am here
 import imaplib
 mail = imaplib.IMAP4_SSL('imap.gmail.com')
 mail.login('login@gmail.com', 'password')
 mail.list()
 # Out: list of "folders" aka labels in gmail.
 mail.select("inbox") # connect to inbox.
 #Get an email
 result, data = mail.uid('fetch', b'1', '(RFC822)')
    raw_email = data[0][1]
    email_message = email.message_from_bytes(raw_email)
    maintype = email_message.get_content_maintype()
    #HERE COMES TROUBLES - if hmtl will be base64 string
    if maintype == 'multipart':
        for part in email_message.get_payload():
            print(part.get_content_maintype())
            if part.get_content_maintype() == 'text':
                html = str(part.get_payload())
    elif maintype == 'text':
        html = str(email_message.get_payload())

    #Now I Can parse HTML
    if html is not None:
        soup = BeautifulSoup(html, 'html.parser')

some letters come with base64 coding. how decode it?
base64.b64encode(some_string) - doesn't help

A: import email

raw_email = data[0][1]
email_message = email.message_from_string(raw_email)

print email_message['To']

print email.utils.parseaddr(email_message['From']) # for parsing "Yuji Tomita" <yuji@grovemade.com>

print email_message.items() # print all headers

def get_first_text_block(self, email_message_instance):
maintype = email_message_instance.get_content_maintype()
if maintype == 'multipart':
    for part in email_message_instance.get_payload():
        if part.get_content_maintype() == 'text':
            return part.get_payload()
elif maintype == 'text':
    return email_message_instance.get_payload()

**I did not write this taken from https://yuji.wordpress.com/2011/06/22/python-imaplib-imap-example-with-gmail/


text:
Q: Boot problems (UEFI) I have two drives, one is a HDD, it has windows 7 and an EFI partition
the second is an SSD it has some EFI files and the BCD.
Whenever I plug the SSD in, the PC always boots from the SSD, in which case it fails.
If I select the 'boot from EFI' file  I can select the EFI file on the SSD which points to windows 7 on the HDD. Some of the EFI files have been moved elsewhere now.
If I select other options such as 'notebook hard drive' it boots from the CD drive if there is a CD in the drive.
If I turn on legacy mode booting from the HDD boots from PXE and then the network adapter.
If I remove the SSD the HDD is automatically found and it boots windows 7, no messing with 'select boot device' menus.
So how can I plug the SSD in but have it so it boots from the HDD.
In the BIOS there is no option for the HDD, there is 'OS boot manager' and 'SSD' but nothing else that resembles a hard disk.

A: I sounds as though your SSD is being plugged into a port with a higher boot priority. If you can give us some screen shots of your current BIOS/UEFI Boot setup, we may be able to help more.
Is there information on the SSD that must be saved? Formatting the drive should also resolve your issue.


text:
Q: A result about Characters of F-algebra groups Let G be an F-algebra group(G=1+J , where J is the jacobson radical of a finite dimensional F-algebra ,where F is a field of prime characteristic)
In a paper of Isaacs ("Characters of groups associated with finite algebras" from 1995) there is a claim of Gutkin with a wrong proof.It says:
Let x be an irreducible character of G ,then $ x=a^G $ ,where a is a linear character of some subgroup H<=G of the form : H=1+U where U is multiplicativly closed F-subspace of J.
This result would be a generalisation of the result of Isaacs paper,but its unclear to me if it has been proven until today.Does someone know if the result is true and can recommand me a paper/link for more information?

A: I think the result you are referring to is over a finite field $F$ (Gutkin's claim was also stated over local fields, however).
The result over finite fields was proved by Z. Halasi in On the characters and commutators of finite algebra groups, J. Algebra 275 (2004), 481-487. Halasi's proof uses some results from the paper by Isaacs in a counting argument, and therefore only proves Gutkin's claim for algebra groups over finite fields.
Recently, M. Boyarchenko has freed Halasi's proof from its dependence on Isaacs's results, and has proved Gutkin's claim also for algebra groups over local fields (see Representations of unipotent groups over local fields and Gutkin's conjecture,     arXiv:1003.2742v1).


text:
Q: Verifying the Bakry-Émery criterion on spheres Suppose that I am interested in a probability measure $\mu$ defined on the sphere $\mathbb{S}^{d-1} \subseteq \mathbb{R}^d$, whose density with respect to the normalised surface measure can be written as $\exp(-V(x))$, with $V: \mathbb{R}^d \to \mathbb{R}$.
My question is: concretely, what matrices do I need to write down in order to verify that $\mu$ satisfies the Bakry-Émery criterion with a given constant $\rho \geqslant 0$?
Assume that I have little background in differential geometry, and don't yet want to subject myself to carefully understanding things like Ricci curvature etc. (perhaps another day!). I am fairly sure that this task reduces to explicitly computing a few derivatives of $V$ (which I insist on writing as a map with domain $\mathbb{R}^d$), and then verifying that a related matrix is positive semidefinite, and so I am looking for concrete instructions which will allow me to do so efficiently.

A: The criterion you have to check is
$$
\mathrm{Hess}_x V[v,v]+\mathrm{Ric}_x(v,v)\geq \rho g_x(v,v)
$$
for all $x\in S^{d-1}$ and unit vectors $v\in T_x S^{d-1}$.
In the case of the round metric on $S^{d-1}$, things get considerably simpler. First, $T_x S^{d-1}=\{x\}^\perp\subset \mathbb R^d$ and $g_x(v,v)=\lvert v\rvert^2$, the Euclidean norm squared. Moreover, the Ricci curvature is just $\mathrm{Ric}_x(v,v)=(d-1)g_x(v,v)$.
Finally, the Hessian can be computed as follows: If $\gamma$ is the (locally unique) geodesic with starting point $x$ and starting velocity $v$, then
$$
\mathrm{Hess}_x V[v,v]=\frac{d^2}{dt^2}\bigg|_{t=0}V(\gamma_t).
$$
In the case of the sphere, the geodesic is given by $\gamma_t=(\cos t)x+(\sin t)v$. More explicitly, this amounts to
$$
\mathrm{Hess}_x V[v,v]=\langle v,\nabla^2 V(x)v\rangle-\langle x,\nabla V(x)\rangle,
$$
where $\nabla V$ and $\nabla^2 V$ are the "Euclidean" gradient and Hessian of $V$ as function on $\mathbb R^d$.


text:
Q: Allowing Facebook login through Firebase on Cordova I am attempting to implement social Facebook login (managed through firebase) on a Cordova app, by using the cordova in-app-browser plugin. When I try to login on my device (iOS), the in-app-browser correctly brings up the Facebook login, but I receive the Facebook error:
"Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains."
I've seen this error before and I know it's because I need to whitelist a domain in order for it to access my Facebook app, but what do I whitelist if the request is coming from a cordova app on a mobile device?
I've browsed other posts that suggested using the cordova Facebook plugin, but this would then login directly on the app, and not register that the user is facebook-logged-in on Firebase (which I need for data and user management).
Any thoughts?
Thank you!
Here is the code:
      var login =  function(provider) {
ref.authWithOAuthPopup(provider, function(error, authData) {
  if (error) {
    // an error occurred while attempting login
console.log(JSON.stringify(error));
  } else {
    // user authenticated with Firebase
    // var message = 'User ID: ' + authData.uid + ', Provider: ' + authData.provider;
  }
});

}

A: High five for finding my own answer by reading the documentation.
From: https://www.firebase.com/docs/web/guide/login/facebook.html#section-configure

In your Facebook app configuration, click on the Settings tab on the
  left-hand navigation menu. Then go to the Advanced tab at the top and
  scroll down to the Client OAuth Settings section. At the bottom of
  that section, add
  https://auth.firebase.com/v2/(YOUR-FIREBASE-APP)/auth/facebook/callback
  to your Valid OAuth redirect URIs and click Save Changes at the bottom
  of the page.


text:
Q: how to match a field name with another field name I have two fields that run throughout a website that I would like to match so that when a user inputs a value either of the fields, it will match the other field. I'm using Sitecore Rocks and am trying to use a query to do this.
 select @#h1#, @#Title#
 from /sitecore/Content/Home//*[@#h1# !="@#Title#"];

 update set @#h1# = @#Title# from /sitecore/Content/Home//*[@#Title# = "<id>"];

What am I missing here?

A: This article talks about tapping in to the item:saving event which allows you to compare the fields values of the item before and after the changes:
http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/11/Intercepting-Item-Updates-with-Sitecore.aspx
Using this, you can determine which field has been amended, then change the other to match.

A: I've had to do something similar to this when a new field was added, and we wanted to set the initial value equal to an existing field.  It may be a bug in Sitecore Rocks, but I found it would only update a field when a static value was part of the query.
When I ran @#h1# = @#Title#, the query analyzer would return the correct number of items updated, but no values were actually updated. However, @#h1# = '<id>' worked perfectly. After trying a number of things, I found this did what I wanted.
update set @#h1# = '' + @#Title# from /sitecore/Content/Home//*[@#Title# = "<id>"];

I hope that helps.


text:
Q: Need to modify content of Lookuphoverdetail popup in visualforce Actually i have achieved to show the contact detail with Lookupoverdetail popup on my visualforce page. It shows default values as Contact Name, Account Name and Email.
Here i want to add/remove somehow contact detail.
Anyone help me to do that.

A: These popups make use of the "Mini Page Layout". You will see a link to this by using Setup ->  Contacts -> Page Layouts and editing a page layout. The "Mini Page Layout" link is in the title bar of the WYSIWYG layout editor. You can add and remove (most) fields and change the order of the fields.


text:
Q: Changing Javascript variable value after onclick action Pretty new to this Javascript thing.
I want to change a Javascript variable when a user inserts a number into an input field in my HTML document and clicks a button.
I'm assuming you'd use a function, but how do you gather the data and change the variable?
The stuff I tried to make looks a little something like this.
HTML
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>

Javascript
var a = 0;
function changeTheVariable() {
   a = document.getElementById("inputField").value;
}

but it's not working!
Edit 1:
Wow. I didn't think I'd get this kind of attention. I also found it a bit strange it didn't work at first.
The question I'm asking is partly for a calculator here: https://titomagic.com/debug
It's simple, you type in a number, click the button and it calculates (based on other variables) to a result on the bottom.
Here's a link to the Javascript file, if you wanna have a look: https://titomagic.com/js/bursdagskalkulator.js
To those of you asking; yes, I've been testing with a console.log and the variable is not changing. It's not affecting the other variables (as it should?).
Also I've never heard of JSfiddle.

A: I discovered few things in the summarizeGjester() function. First of all I moved all the Javascript code in the bursdagskalkulator.js file inside the summarizeGjester() function.  Also I converted var antallGjester to integer using parseInt() function, because it was treated as string before.
 var antallGjester = document.getElementById("gjesterAntallInput").value;
 antallGjester = parseInt(antallGjester);  //integer conversion

Also the first Boolean comparison was changed to
if ((antallGjester < 10) && (antallGjester > 0)), so that the second one would work if there's 0 value: else if (antallGjester === 0).

 function summarizeGjester() {

    var antallGjester = document.getElementById("gjesterAntallInput").value;

    antallGjester = parseInt(antallGjester);

    var fastPris = 1500;

    var fastPrisDifferanse = 10;

    var gjestePris = 120;

    var gjesteDifferanse = antallGjester - fastPrisDifferanse;

    var gjesteSum = gjestePris * gjesteDifferanse;

    var gjesterTotalt = 0;

    if ((antallGjester < 10) && (antallGjester > 0)) {
      console.log("antallGjester < 10");
      gjesterTotalt = 1500;
    } else if (antallGjester === 0) {
      console.log("antallGjester === 0");
      gjesterTotalt = 0;
    } else {
      console.log("else");
      gjesterTotalt = fastPris + gjesteSum;
    }

    document.querySelector('#results').innerHTML = gjesterTotalt;
  }
<form>

    Antall barn:
    <input type="number" class="form-control" id="gjesterAntallInput">

  <button class="btn btn-lg btn-warning" onclick="summarizeGjester()" type="button" id="sumGjester">Legg sammen</button>
</form>

0,-

I hope this helps :-)

A: HTML
<input type="number" id="inputField" ClientIDMode="static">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>

Javascript
var a = 0;
function changeTheVariable() {
   a = document.getElementById('inputField').value;
   alert(a);
}

Use Static ClientIDMode for stable id and access after page rendering
PlaceHolders canh change childe's id

A: I suppose this will work for you

var a = 0;
function changeTheVariable() {
   a = document.getElementById("inputField").value || a;
   document.getElementById("result").innerText = parseFloat(a);
}
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe">Click me</button>

Result:

Edited:
The reason behind this code is not running in jsfiddle is here.

After making the changeTheVariable() global variable this code will work in jsfiddle also. Here https://jsfiddle.net/1b9cfmje/
Use the following javascript code:
window.onload = function(){ var a = 0; window.changeTheVariable = function() {  a = document.getElementById("inputField").value || a; document.getElementById("result").innerText = parseFloat(a); }}


text:
Q: bootstrap 3 how to close modal from external content I'm trying to close the modal window from the contents of my external link.
Log in

I don't want to put the button
Close

in there because the external content logic in there where it is supposed to close the window based on some actions.

A: You should be able to close the modal programmatically, e.g.
$('#modalLogin').modal('hide');

That way if you have something else on the page (for instance an $.async() call with a .done() function, you can execute the above to close the modal.
This will only hide the modal, not remove it from the DOM, if you want to perform certain actions when a modal is being hidden you can bind a function to the bootstrap events that are triggered and associated with the modal, e.g.
$('#modalLogin').on('hidden.bs.modal', function (e) {
  // do something...
})

See http://getbootstrap.com/javascript/#modals-usage for more details.


text:
Q: CakePHP - unit testing admin view How can I do CakePHP unit testing for views that is password protected?
I see an article about admin controller but not views http://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way
So basically right now my assert is failing because of the password page.
$this->get($this->baseurl . '/admin/items');
$this->assertText('Title');

Thanks,
Tee

A: You may have to mock or stub the authcomponent for your tests to always authenticate users. A bit of googling turns this up
Real-world testing of CakePHP controllers?


text:
Q: Word for people who ask to be treated but never accept when offered I'd like to apologize in advance if I don't make sense. I'm not a native English speaker.
Anyway, here's the background: Back home, it is common that your friends ask you for a treat for every little thing, just another reason to celebrate. By treat, I mean treating someone to food and drink/hosting a (dinner) party just for a person or two. However, there are a few people who ONLY ASK for a treat but never really accept it. And that is not the end of the story, they then complain that we never treat them.
I know its not a very common scenario, but I'd like to know if there's a word for such people or such a behavior?
For example, I'd like to use it in such a sentence:

Just invite him. He'll not join us anyway, he is a _________.

A: I'll take the liberty of slightly altering your sentence:
"Just invite him. He'll not join us anyway, he is [a bit] X"
X being:

*

*reserved (Probably Likes - Possibly won't come)

*withdrawn (May Like - Won't Come)

*reclusive (May not like - Certainly won't come)

*noncommittal (Likes - Won't Say Whether or not will attend)

*uncompanionable (May not like - Won't come)

*solitary (Likes - May not come)

all those would fit into your example sentence to convey that the person may not come to the event, but not all of the persons will like being asked, because some like no interaction (not even the asking).

A: I thought of two closely-related words that have almost opposite meanings:
(1) "ingratiate" - trying to get into someone's favour, but having also the sense of insincerity, and (2) "ingrate" - someone who is ungrateful for the favour or kindness shown.
Perhaps the person you are trying to describe is an "ingratiating ingrate"!!

A: Adding "a bit" makes the sentence more conversational.
Just invite him. He'll not join us anyway, he is a bit standoffish.
Definition of standoffish - Merriam-Webster

: somewhat cold and reserved
She tends to be a bit standoffish with strangers.
She proved to be simply shy, not standoffish.

Aloof works equally well:
Just invite him. He'll not join us anyway, he is a bit aloof.
Definition of aloof - Merriam-Webster

: removed or distant either physically or emotionally an aloof, unfriendly manner
He stood aloof from worldly success. —John Buchan

Aloof also works without "a bit," but sans "a"
Just invite him. He'll not join us anyway, he is aloof.
For other nouns, "recluse" and "hermit" also work with your sentence. The other answer covered "reclusive."


text:
Q: How to send message from Website To Telegram direct 1 number target? i add the form message (html standart) and button(submit) from website to telegram APP, direct number precise: +00 123 456 789 (this is example number TARGET A).
this is for mobile (iOS,android) who has installed telegram app.
If users (any people) have not it the number contact "TARGET A" then add new contact..
If users (any people) have it the number contact "TARGET A" then send it direct in telegram app mobile..
If users (any people) have not the telegram app then re-direct other page: www.company.com/miss-telegram.html
i will write the message : sorry, you have not the app Telegram, if want to add the app telegram then click, go to link: https://play.google.com/store/apps/details?id=org.telegram.messenger for andorid or https://itunes.apple.com/it/app/telegram-messenger/id686449807 for Ios..
can you help me how build it?
note: i'm base html build and not expert.. i'm newbie..
note: i dont know what is best code language: javascript, html5,php,..
you can try different code for javascript, for html5, for php..to see what is best solution (easy)..
thank you
so i dont know how builds it from html standart for send to telegram direct target number..


text:
Q: Generating random samples from a density function How does a computer algorithm set up to take as input an arbirary bivariate probability density function, generate pairs of numbers from that distribution? I have found a routine called simcontour that is part of LearnBayes in R that performs that operation.

A: Denote the joint density you want to sample from by $p_{XY}(x,y)$. Then the marginal densities are easily obtainable:
$$ p_{X}(x) = \int_{D_{Y}} p_{XY}(x,y) dy, \ \ \ \ \ \ \ \ \ p_{Y}(y) = \int_{D_{X}} p_{XY}(x,y) dx $$
where $D_X, D_Y$ denote the support of $X, Y$, respectively. From this you can calculate each of the conditional density functions:
$$ p_{X|Y=y}(x) = \frac{ p_{XY}(x,y) }{ p_{Y}(y) }, \ \ \ \ \ \ \ \ p_{Y|X=x}(y) = \frac{ p_{XY}(x,y) }{ p_{X}(x) } $$
From here you can execute Gibbs' sampling to sample from $p_{XY}$. That is, start with some arbitrary starting value in the $(x_{0}, y_{0})$. Then, at step $i$,
(1) Sample from $p_{X|Y=y_{i}}(x)$ to obtain $x_{i+1}$
(2) Sample from $p_{Y|X=x_{i+1}}(y)$ to obtain $y_{i+1}$
(3) Repeat a number of times equal to the desired sample size
Each $(x_{i}, y_{i})$ is an approximate draw from the joint distribution of $X$ and $Y$. The conditional densities can be sampled from in steps (1) and (2) using, for example, rejection sampling assuming they do not come from one of the "standard" distributions, in which case you can use a pre-existing function to generate from them.

A: You can use rejection sampling.
Let $f$ be the probability density we want to sample from
(it does not matter if it is 1- or 2-dimensional).
If we can find a probability distribution $g$,
from which we can easily sample from,
e.g., a uniform distribution (a good choice, if the support of $f$ is bounded),
a Gaussian distribution,
or a Cauchy distribution (a last-resort choice, inefficient but useful if $f$ has fat tails),
such that there exists a constant $c$ with $f \leq c g$,
then we can sample from $f$ as follows.
Take a random sample $x$ from $g$, take a random number $\lambda$ uniformly in $[0,1]$;
if $\lambda c g(x) < f(x)$, keep the sample, otherwise reject it and try again.
Repeat until you have the desired number of samples.
The reason why it works is easily seen on a picture: $(x,\lambda c g(x))$ is a point sampled uniformly in the area under the curve $x \mapsto c g(x)$, and the condition $\lambda c g(x) < f(x)$ asks that it be under the curve $x\mapsto f(x)$.