text:
Q: Array to Object First and Last I need to take the first and last element in a given array and return an object with the first element as the key and the last as the value.
Here's my code:
function transformFirstAndLast(array) {
    array=[];
    var object={};
    object[key]=value;// make object
    var key=array[0];
    var value=array[array.length-1];

    return object;} // return object

for whatever reason, it's returning undefined inside the object. I swear it was working this morning...
I've always tried:
 function  transformFirstAndLast(array) {
     array=[];
     var object = {};
     object[array[0]] = array[array.length-1];}

but that's returning undefined without so much as an object being built.

A: This is straightforward using computed property names:
function transformFirstAndLast(array) {
  return {[array[0]]: array[array.length - 1]};
}

Or if you prefer:
const transformFirstAndLast = ([head, ...tail]) => ({[head]: tail.pop()});

A: You're redeclaring array at the beggining of your function.
Besides, in my opinion, using "array" and "object" as variable names is a bad idea. Just a typo could get you messing up with Array and Object. And that might have side effects.
Here's a functional fiddle for your use case using array.shift() and array.pop() methods.

var myArray=['one','two','three','four'];

function buildObject(arr) {
  var myObject={},
      key=arr.shift(),
      val=arr.pop();

  myObject[key]=val;
  return myObject;
}

console.log(buildObject(myArray));


text:
Q: How to marshal struct as if it were an anonymous struct? The documentation states:

Anonymous struct fields are usually marshaled as if their inner exported fields were fields in the outer struct.

For examble:
type foo struct {
    Foo1 string `json:"foo1"`
    Foo2 string `json:"foo2"`
}

type boo struct {
    Boo1 string `json:"boo1"`
    foo
}

and I do this:
s := boo{
    Boo: "boo1",
    foo: foo{
        Foo1: "foo1",
        Foo2: "foo2",
    },
}

b, err := json.MarshalIndent(s, "", "   ")
fmt.Println(string(b))

I get this:
{
    "boo1": "boo1",
    "foo1": "foo1",
    "foo2": "foo2"
}

But how can I achieve the same result when the foo is Not an anonymous struct? Meaning:
type boo struct {
    Boo string `json:"boo"`
    Foo foo
}

And also unmarshaling the json.

A: You have to implement a custom json.Marshaler for that.
type boo struct {
    Boo1 string `json:"boo1"`
    // "-" will tell encoding/json to ignore this field during (un)marshaling
    Foo foo `json:"-"`
}

func (b boo) MarshalJSON() ([]byte, error) {
    // Declare a new type using boo's definition, this
    // "copies" boo's structure but not its behaviour,
    // i.e. B has same fields as boo, but zero methods,
    // not even MarshalJSON -- this is necessary to avoid
    // infinite recursive calls to MarshalJSON.
    type B boo

    // Declare a new type that *embeds* those structs whose
    // fields you want to be at the same level.
    type T struct {
        B
        foo
    }

    // Create an instance of the new type with its fields
    // set from the source boo instance and marshal it.
    return json.Marshal(T{B: B(b), foo: b.Foo})
}

https://play.golang.org/p/Go1w9quPkMa

A note on "anonymous"
The label anonymous as you're using it, and as it is used in the documentation you quoted, is outdated and imprecise. The proper label for a field without an explicit name is embedded.
https://golang.org/ref/spec#Struct_types

A field declared with a type but no explicit field name is called an
embedded field. An embedded field must be specified as a type name T
or as a pointer to a non-interface type name *T, and T itself may not
be a pointer type. The unqualified type name acts as the field name.

The distinction is important because there is such a thing as "anonymous struct fields" in Go, it's used quite often but it is different from embedded fields. For example:
type T struct {
    // F is an anonymous struct field, or
    // a field of an anonymous struct type.
    // F is not embedded however.
    F struct {
        foo string
        bar int
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Filter SharePoint Data To InfoPath Based on Username Basically I have an InfoPath form which recieves some data from a SharePoint list, the problem is I would like to filter this data based on the username of the current user.
So I have an Author field in SharePoint which is a 'Person/Group' field.
So when I filter the data in InfoPath by saying
where Author is equal to UserName()

I also tried contains
But it still doesnt work, does anyone have any ideas on a solution?
Note that using code is not an option in this case!

A: Sorted this issue by using just the username in the SharePoint column as opposed to the full person/group structure, this way I can match the two username in InfoPath.


text:
Q: send json response to client when i activated raspberry gpio I have a face detection project that i want to activate one of the raspberry pi gpio ports when a face is detected, which I can do without any problems.
Now I want to have an API that when a port is activated, the true response as json is sent to the client. I use the tornado web server.
import cv2
import sys
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18,GPIO.HIGH)

cascPath = sys.argv[1]
faceCascade = cv2.CascadeClassifier(cascPath)

video_capture = cv2.VideoCapture(0)

while True:
    # Capture frame-by-frame
    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        flags=cv2.cv.CV_HAAR_SCALE_IMAGE
    )

    if  len(faces)>0:
        GPIO.output(18,GPIO.LOW)
        sleep(1)
        GPIO.output(18 ,GPIO.HIGH)
    else:
        GPIO.output(18,GPIO.HIGH)

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # Display the resulting frame
    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows(

)
this is my tornado code:
import face_detection
import tornado.ioloop
import tornado.web
import json
class MainHandler(tornado.web.RequestHandler):
    def get(self):

        '''face detection code'''

        self.write(json.dumps({'response':True}))

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

but i can't to send json response to client.wahts wrong in my code?

A: You're not sending the correct header. For a JSON response you need to send the Content-Type header to tell the client know that this is a JSON response, like this: Content-Type: application/json.
You've two options now:
1. Give self.write the raw dict instead of json data
If you give self.write a dictionary, it will automatically convert it to JSON and set the appropirate Content-Type header. You won't have to worry about that.
self.write({'reponse': True}) # pass the dict, not JSON

2. OR set the header yourself
If you want to send the json manually, you can set the header yourself, like this:
self.set_header('Content-Type', 'application/json')
self.write(json.dumps({'response': True}))


text: Q: geodesic submanifolds I have a question to find all geodesic submanifolds of the hyperbolic space in n-dim. I did an exercise that all geodesics must be either lines perpendicular to the boundary of the hyperbolic space (under half space model) or great circles of spheres centered at the boundary. But I am not sure how to prove that only planes perpendicular to the boundary and spheres perpendicular to the boundary the only manifolds. Could you please help?


text:
Q: How to check if property is an object with property "__deferred" I am trying to find out if a property has only 1 object with property "__deferred",
Here is how it looks like in chrome developer tools,

Update to make it clear
I might have dynamic objects, what I really want is
if(property.Object.hasOnlyProperty == '__deferred') <-- I know this doesn't work, but I want something similar..
I don't want property to be added to my expandedChildResults array if it is a object like in the picture, exactly same.

A: the hasOwnProperty("propertyName") method should be able to tell you if the __deferred  exists in the object

A: If you don't care about non-enumerable properties and properties inherited from prototype (see Enumerability and ownership of properties), you can used Object.keys
function isPropertyAnObjectWithJustSingle__deferred(property) {
    var keys;
    return typeof property === 'object' && // test if it's and object
        (keys = Object.keys(property)).length === 1 && // test if it has just sibgle property
        keys[0] === '__deferred'; // test if that property is '__deferred'
}


text:
Q: I keep getting Null check operator used on a null value error I keep getting null check operator used on a null value within these lines of code below and I can't seem to fathom why. I have referenced quite a number of materials on this platform but none of them seems to be helping. Assist if you can please?
AuthServices authServices = AuthServices();

void checkRegistration() {
final isValid = registerKey.currentState!.validate();
if (!isValid) {
  return;
}
registerKey.currentState!.save();

authServices.auth
    .createUserWithEmailAndPassword(
  email: registerEmailController.text.trim(),
  password: registerPasswordController.text.trim(),
)
    .then((value) {
  FirebaseFirestore.instance.collection("users").doc(value.user!.uid).set({
    "uid": value.user!.uid,
    "email": value.user!.email,
    "name": value.user!.displayName,
    "phone": value.user!.phoneNumber,
    "time": Timestamp.now(),
  });
});

}

A: Add a condition to check if the user is null before saving it to the document. I think that's where it's being null and checks other value
AuthServices authServices = AuthServices();

void checkRegistration() {
if(registerKey.currentState != null)
{
    final isValid = registerKey.currentState!.validate();
    if (!isValid) {
      return;
    }

    registerKey.currentState!.save();
}
authServices.auth
    .createUserWithEmailAndPassword(
  email: registerEmailController.text.trim(),
  password: registerPasswordController.text.trim(),
)
    .then((value) {
if(value.user != null)// check if the user is recived in value before assigning
{
  FirebaseFirestore.instance.collection("users").doc(value.user!.uid).set({
    "uid": value.user!.uid,
    "email": value.user!.email,
    "name": value.user!.displayName,
    "phone": value.user!.phoneNumber,
    "time": Timestamp.now(),
  });
});
}
}


text:
Q: Trying to solve this first-order nonlinear DE I am really struggling with the next differential equation:
$$\dfrac{dy}{dx}=\dfrac{y-xy}{x^2-x+y+e^y}.$$
So far I know it's a first-order nonlinear DE, but I cannot find a way to solve this. Any tip or help would be appreciated.


text: Q: How to dynamically define each hyperlink as the linked slides change in PowerPoint 2016 There is a hyperlink on the first slide to another slide in the same presentation. The other slides contain detail, and since the size of the detail changes, the position of the slide changes as well. One time the hyperlink would need to go to slide 8 the next time to slide 9. The detail slides are a cut and paste from a pdf, and the current fix is to manually adjust each hyperlink. The text on the hyperlink is the same as the header for the detail slide, so I'm hoping there is a way to dynamically define each hyperlink as the linked slides change. Any help would be greatly appreciated!


text:
Q: Controlling when boost mode is used in HighCharts? I have included boost.js module in my app. This enables boost mode by default based on certain thresholds. I want to control when the boost mode kicks in for a heatmap. I found below 3 options. The documentation is a bit confusing. What is the difference between these options? Which one(s) should I use if want boost mode to be always enabled irrespective of number of data points?

*

*plotOptions.series.turboThreshold

*boost.seriesThreshold

*plotOptions.series.boostThreshold

A: 1. plotOptions.series.turboThreshold
This setting has nothing to do with the boost module, as the API states, this only applies to series where data is configured as an array. And will speed up those cases without needing the boost module:

When a series contains a data array that is longer than this, only one dimensional arrays of numbers, or two dimensional arrays with x and y values are allowed. Also, only the first point is tested, and the rest are assumed to be the same format. This saves expensive data checking and indexing in long series. Set it to 0 disable.

2. boost.seriesThreshold
This setting enables boost mode based on number of series present. Regardless of how many points are in each series.

Set the series threshold for when the boost should kick in globally.
Setting to e.g. 20 will cause the whole chart to enter boost mode if there are 20 or more series active. When the chart is in boost mode, every series in it will be rendered to a common canvas. This offers a significant speed improvment in charts with a very high amount of series.

3. plotOptions.series.boostThreshold
This is the series type specific or global setting. You can make this apply to one series type, or all series types.

Set the point threshold for when a series should enter boost mode.
Setting it to e.g. 2000 will cause the series to enter boost mode when there are 2000 or more points in the series.
To disable boosting on the series, set the boostThreshold to 0. Setting it to 1 will force boosting.

4. series.seriesType.boostThreshold
This is the local version of 3. Here you can apply boost to a specific series.

If you want to always use boost mode you set 3. like stated in the API:
Highcharts.chart('container', {
  plotOptions: {
    series: {
      boostThreshold: 1
    }
  },
  ...
}

JSFiddle example: https://jsfiddle.net/ewolden/bxkqv38a/1/


text:
Q: How to add an icon in a search box Questions to cover:
How to add an icon in a search box / form
How to add an icon in an input field
I had the following issue whereby I could't get the FontAwesome fa-search icon to sit to the right of the input field / search box.
Here is an image of the form:
A HTML search form on a website's header
Link to the form here (not evergreen):
https://www.themirrorman.co
Here is my original code:

@media screen and (min-width: 800px) {
  #header-search-desktop-div {
      position: absolute;
      left: 180px;
      width: 450px;
      margin-top: 0;
      margin-bottom: 0;
      border: 1px solid #881d98;
      border-radius: 24px;
  }
  #header-search-desktop-div #header-search-fa {
      position: absolute;
      color: #7E7E7E;
      z-index: 100;
      font-size: 27px;
  }
  #header-search-desktop-div .fa-search {
      top: 5%;
      left: 1.5%;
      line-height: 0.8em;
  }
}

    <form role="search" method="get" class="searchform" action="https://themirrorman.co/">

                <input id="header-search-desktop-input" name="product-search" type="text" value="" placeholder="Product Search…">
                <input type="hidden" name="post_type" value="product" />

    </form>

The following code I received answers on and changed, it now works like in the above image link:

#header-search-submit {
position: absolute;
z-index: 1;
padding: 0;
right: 15px;
top: 6px;
font-size: 24px;
font-family: FontAwesome;
color: #7B7B7B;
cursor: pointer;
background: 0;
border: 0;
}

<form id="header-search-form" role="search" action="https://themirrorman.co/" method="get">
<fieldset>

        <input id="header-search-desktop-span" style="border-radius: 24px;" type="text" value="" name="s" class="s" placeholder="I am looking for..." />
        <input id="header-search-submit" type="submit" value="" name="post_type" />

</fieldset>
</form>

A: Check the code below which is inspired by this link:
How do I add a Font Awesome icon to input field?

input[type="search"] {
    font-family: FontAwesome;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>

<input type="search"  placeholder="&#xf002 Search" >

Edit: 07/23/2020
I recently visited this question again and wanted to add an alternative solution. I basically copied the code for the Google search bar and added my own tweaks to it. From left to right the search bar consists of a label, an input and a button.

body {
  height: 100%;
  background-color: rgb(230, 230, 230);
}

/* -----search-container styles----- */

.search-container {
  --searchbox-height: 44px;
  margin: 0 auto 0 auto;
  min-width: 410px;
  width: var(--content-width);
}

/* -----searchbar styles----- */

.searchbar {
  background: white;
  cursor: text;
  margin: 0 auto;
  max-width: 584px;
  box-shadow: 0 1px 6px 0 rgba(32, 33, 36, .28);
  border-radius: 22px;
  box-sizing: border-box;
  font-size: 16px;
  height: var(--searchbox-height);
  position: relative;
}

/* -----search-input styles----- */

.search-input {
  box-sizing: border-box;
  margin: 0;
  height: 100%;
  width: calc(100% - 80px);
  border-color: transparent;
  color: rgb(117, 117, 117);
  font-size: 16px;
  line-height: 44px;
  margin: auto 0;
  overflow: hidden;
  text-align: initial;
  text-overflow: ellipsis;
  user-select: none;
  vertical-align: middle;
  white-space: nowrap;
}

.search-input:focus {
  outline: transparent;
}

.search-input:focus::placeholder {
  color: transparent;
}

/* -----search-icon styles---- */

.search-icon-wrapper {
  padding: 0 24px;
  /* margin-right: 48px; */
}

.search-icon {
  -webkit-mask-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgZmlsbD0iIzVGNjM2OCI+PHBhdGggZD0iTTE1LjUgMTRoLS43OWwtLjI4LS4yN0E2LjQ3MSA2LjQ3MSAwIDAgMCAxNiA5LjUgNi41IDYuNSAwIDEgMCA5LjUgMTZjMS42MSAwIDMuMDktLjU5IDQuMjMtMS41N2wuMjcuMjh2Ljc5bDUgNC45OUwyMC40OSAxOWwtNC45OS01em0tNiAwQzcuMDEgMTQgNSAxMS45OSA1IDkuNVM3LjAxIDUgOS41IDUgMTQgNy4wMSAxNCA5LjUgMTEuOTkgMTQgOS41IDE0eiIvPjwvc3ZnPg==);
  -webkit-mask-position: center;
  -webkit-mask-repeat: no-repeat;
  -webkit-mask-size: 20px;
  background-color: rgb(117, 117, 117);
  bottom: 0;
  left: 16px;
  margin: auto;
  position: absolute;
  top: 0;
  width: 24px;
}

/* -----search-microphone styles----- */

.search-microphone {
  background: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCI+PHBhdGggZmlsbD0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIvPjxwYXRoIGZpbGw9IiM0Mjg1RjQiIGQ9Ik0xMiAxNWMxLjY2IDAgMi45OS0xLjM0IDIuOTktM0wxNSA1YzAtMS42Ni0xLjM0LTMtMy0zUzkgMy4zNCA5IDV2N2MwIDEuNjYgMS4zNCAzIDMgM3oiLz48cGF0aCBmaWxsPSIjMzRBODUzIiBkPSJNMTEgMTguOTJoMlYyMmgtMnoiLz48cGF0aCBmaWxsPSIjRjRCNDAwIiBkPSJNNyAxMkg1YzAgMS45My43OCAzLjY4IDIuMDUgNC45NWwxLjQxLTEuNDFDNy41NiAxNC42MyA3IDEzLjM4IDcgMTJ6Ii8+PHBhdGggZmlsbD0iI0VBNDMzNSIgZD0iTTEyIDE3Yy0xLjM4IDAtMi42My0uNTYtMy41NC0xLjQ3bC0xLjQxIDEuNDFBNi45OSA2Ljk5IDAgMCAwIDEyLjAxIDE5YzMuODcgMCA2Ljk4LTMuMTQgNi45OC03aC0yYzAgMi43Ni0yLjIzIDUtNC45OSA1eiIvPjwvc3ZnPg==) no-repeat center;
  background-size: 21px 21px;
  bottom: 0;
  cursor: pointer;
  margin-inline-end: 16px;
  padding: 22px 12px 0;
  position: absolute;
  right: 0;
  top: 0;
  width: 21px;
  border-color: transparent;
}

    <input type="text" class="search-input" id="search-input" placeholder="Search Google or type a URL">
    <button class="search-microphone"></button>


text:
Q: Insert com datatime Postgresql e c# Gostaria de tirar uma duvida, porque a primeira data não funciona?

Cmd.Parameters.AddWithValue("@dtUltAcesso", "2017-01-01 01:01:01+09");

Erro que retorna:

Erro ao inserer usuario - Erro: 42804: column "usu_dataacesso" is of
  type timestamp without time zone but expression is of type text

E ja essa funciona certo

Cmd.Parameters.AddWithValue("@dtCadastro",
  NpgsqlTypes.NpgsqlDateTime.Now);

 public void insere()
                {
                    try
                    {
                        //Abre a conexao para insercao
                        abrirConexao();
                        Cmd = new NpgsqlCommand("insert into \"Cadastro\".\"usuario\" (usu_nome,usu_cargo,usu_cpf,usu_dataAcesso,usu_dataCadastro,usu_status,usu_login,usu_senha) values (@nome,@cargo,@cpf,@dtUltAcesso,@dtCadastro,@status,@login,@senha)", Con);
                        Cmd.Parameters.AddWithValue("@nome", "Flavio");
                        Cmd.Parameters.AddWithValue("@cargo","TI");
                        Cmd.Parameters.AddWithValue("@cpf", "0101010101");
                        Cmd.Parameters.AddWithValue("@dtUltAcesso", "2017-01-01 01:01:01+09");
                        Cmd.Parameters.AddWithValue("@dtCadastro", NpgsqlTypes.NpgsqlDateTime.Now);
                        Cmd.Parameters.AddWithValue("@status", "A");
                        Cmd.Parameters.AddWithValue("@login", "fla");
                        Cmd.Parameters.AddWithValue("@senha", "123");

                        Cmd.ExecuteNonQuery();

                        MessageBox.Show("Usuario Inserido com Sucesso");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro ao inserer usuario - Erro: " + ex.Message);

                    }

Mas gostaria de passar uma string coma data, como poderia fazer isso?
Obrigado

A: Quando você passa a data entre " " ela vai como string e não uma data em si,
o segundo caso funcionou por que foi passado uma data como parametro!
converta sua string para data e tudo ira ocorrer como esperado
 Cmd.Parameters.AddWithValue("@dtUltAcesso",
                  DateTime.ParseExact("2017-01-01 01:01:01+09", "yyyy-MM-dd HH:mm:ss",
                                   System.Globalization.CultureInfo.InvariantCulture) );


text:
Q: Heroku redis/sidekiq Connection timed out - user specified timeout error This is an issue that happened after upgrading my Redis instance version on Heroku using heroku redis:upgrade
The error happened when Sidekiq tried to connect to Redis:
Connection timed out - user specified timeout

After reading this guide:
https://github.com/mperham/sidekiq/wiki/Using-Redis#life-in-the-cloud
I thought the problem might be in the network connection, so I tried increasing the network timeout in config/initializers/sidekiq.rb like this:
config.redis = { network_timeout: 5 }
Unfortunately this did not help, it only increased the time that it takes to create the connection, but the same error was still occurring in the end.

A: I noticed that after upgrading the Redis instance version, Heroku had not updated the REDIS_URL config var to match the new redis url.
So, the URL in the config var:
heroku config:get REDIS_URL

was different from the one returned by:
heroku redis:credentials

So my solution was as per the following guide:
https://devcenter.heroku.com/articles/managing-heroku-redis-using-cli#redis-credentials
to reset Redis the credentials:
heroku redis:credentials --reset

With this command, new credentials are created for the Redis instance and the related config vars on the Heroku application are automatically updated.


text:
Q: Использование команд в MVVM Только начал изучать WPF и паттерн MVVM и возникло непонимание связанное с использованием команд, как в MVVM, так и вне его.
Нужно сделать, чтобы пользователь смог передвигать некий объект на форме.
При реализации через события мне нужно было бы обрабатывать событие MouseMove,  MouseLeftButtonDown и MouseLeftButtonUp, чтобы объект перемещался только когда ЛКМ нажата на нем.
Но как это делается при реализации через команды?


text:
Q: C# equivalent to VB.NET 'Handles button1.Click, button2.Click' In VB.NET I can do

private sub button_click(sender, e) handles Button1.Click, Button2.Click etc...
do something...
end sub

Is there a method for this in C# .NET? I have roughly 16 buttons that all call the same function, just passing the text of the button to the function. I would rather not have 16 private void button_clicks calling one function.
I am not sure how to do this though (not familiar with C# to much.)

A: Manually, you can do this:
button1.Click += button_Click;
button2.Click += button_Click;
...

In the Designer, the Click event property is actually a drop-down menu where you can choose among existing methods that have the appropriate signature.

A: C# does not have the Handles keyword.
Instead, you need to add the handlers explicitly:
something.Click += button_click;
somethingElse.Click += button_click;

A: Try this:
button1.Click += button_click;
button2.Click += button_click;

A: If you want to keep it maintainable, I would go with something like this:
//btnArray can also be populated by traversing relevant Controls collection(s)
Button[] btnArray = new Button[] {button1, button2};
foreach(Button btn in btnArray) {
  btn.Click += button_Click;
}

Any refactoring to this code is done via a single point of maintenance. For example:

*

*You decide to bind to a custom button class with a custom event, i.e. MyClick.

*You decide to change logic of how buttons are collected, add or remove buttons.

*You figure button_Click is a bad name, or need to have conditional event binding.

A: Button1.Click += button_click;
Button2.Click += button_click;

A: btn1.Click += button_click;
btn2.Click += button_click;

is the answer


text:
Q: javascript serialize on appended divs Is it possible to serialize appended forms in jquery? I tried both button.on(click) and form.on(submit), but got a problem. When I use the onclick button it gives me an undefined serialization. When I use form submit, it gives me nothing.
Here's my JS Code:
function main_login(){

$('.main-login').click(function(){
var adpas = prompt("Enter password: ");
if(adpas !== null){
    $.ajax({
        type: 'post',
        url: 'init.php',
        data: {data: adpas},
        success: function(data){
    if(data == "success"){
            $('#main-note').css('display', 'initial');
            $('#main-note').append(''+
'
'+
'
X
'+
'<form action="" id="formmsg" method="post"><input type="text" id="note-title" style="width: 98%; height: 20px; font-size:16px"/>'+
'<textarea id="note-texts" style="width: 98%; height: 400px; resize: none;"></textarea>'+
'<input type="submit" value="Encode Lecture" name="btn-lecture" id="btn-lecture"></form>
');

    $('#formmsg').on('submit', function() {
        alert($(this).serialize());
    });

    }

    else{
        alert('You don\'t have any administrative rights to open this link.');
    }

        }
    });

}
});

}

Another question:
It seems that every time I  successfully click "main-login class", it gives me the same number of divs it is clicked. Is there anyway to make the button trigger only once, only if the password was accepted and successful?
Tried jQuery.one(); it worked but both for successful and failed login.
Thanks in advance.

A: Basically you are trying to attach an event to an element which was created dynamically! So here event delegation helps you and instead of keeping event inside success of ajax, which is obviously not a good thing, put it outside! Following will be the changes you need to do!!
$('.main-login').click(function(){
   var adpas = prompt("Enter password: ");
   if(adpas !== null){
       $.ajax({
          type: 'post',
          url: 'init.php',
          data: {data: adpas},
          success: function(data){
            if(data == "success"){
               $('#main-note').css('display', 'initial');
               $('#main-note').append(''+
'
'+
'
X
'+
'<form action="" id="formmsg" method="post"><input type="text" id="note-title" style="width: 98%; height: 20px; font-size:16px"/>'+
'<textarea id="note-texts" style="width: 98%; height: 400px; resize: none;"></textarea>'+
'<input type="submit" value="Encode Lecture" name="btn-lecture" id="btn-lecture"></form>
');
             }
             else{
                alert('You don\'t have any administrative rights to open this link.');
             }
         }
       });
    }
});

Now your form submit event:
$('#main-note').on('submit','#formmsg', function() {
    console.log($(this).serialize());
});

That should work now.


text:
Q: template non-type template parameter? I'm trying to use a non-type template parameter which type is a template instance like this:
template<size_t num> class BitValue { ... };
class Foo {
  // works
  template<template<size_t> class BitValue, size_t num>
  bool get(BitValue<num> && t) { ... }

  // fails
  template<typename T> bool
  template<Bitvalue<num> bit> bool get() { ... };
  template<template <size_t> Bitvalue bit> bool get() { ... };
  template<template <size_t> class Bitvalue bit> bool get() { ... };
  template<template <size_t> BitValue, size_t num, Bitvalue<num> bit> bool get() { ... };
};

You might say: Why not use the foo.get(value)? Foo represents a kind of bitfield that has multi-bit values and single-big values. I want foo.get<...>() for all members of the bitfield for consistency.
Why not use `foo.get<typeof(value)>'?
foo.get<MultiBitType>() returns the value of the multi-bit field. foo.get<SingleBitType>() returns the raw value of the single-bit type. But unfortunately some of the bits are negated. So foo.get<NegatedValue>() should return !foo.get<typeof(NegatedValue)>().
Any ideas if it is possible to have a template non-type template parameter at all? And if so how?

A: It is impossible to have a non-type template parameter of type BitValue<size_t> since the allowed types are [temp.param]:

A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
(4.1) — integral or enumeration type,
  (4.2) — pointer to object or pointer to function,
  (4.3) — lvalue reference to object or lvalue reference to function,
  (4.4) — pointer to member,
  (4.5) — std::nullptr_t.

But you can just template on any type and delegate to a metafunction:
template <typename T>
bool get() {
    size_t bit = bit_number<T>::value;
    ...
}

where:
template <typename T> struct bit_number;
template <size_t N>
struct bit_number<BitValue<N>> : std::integral_constant<size_t, N> { };
// other specializations


text:
Q: Ionic Webview not syncing cookies on first launch IOS Please help!! I'm using Ionic 5 with Angular and Cordova. My app works perfect when testing on browsers and Android devices but when it's first installed on my device (iphone) through Xcode the cookies are not received or sent properly. My app uses cookie based authentication so when I get my login response it will have a cookie that should be sent with all subsequent requests. However, on the first launch after install I cannot login at all. When I exit and relaunch my app it works perfectly. I believe this is due to the webview not syncing cookies correctly. I have tried all the solutions in this post: https://github.com/Telerik-Verified-Plugins/WKWebView/issues/247 but the plugins are so outdated I can't get it to work properly.
I have been looking for a solution for weeks and am completely stuck and exhausted at this point. I'm new to Ionic and development in general so any help would be greatly appreciated! I will provide whatever code or screenshots is helpful, just let me know what I should share.

A: I don't know if you have solved this since it's been 24 days since you asked, but:
I was having a similar issue. I'm using the cordova-plugin-wkwebview-cookie-sync plugin
and even though the cookie was set, the page was loading as it wasn't. All I had to do was
update $('body').append(_return); to $('body').html(_return); and the content showed up
using the cookie.
This is my code:
function loadApp() {
  $.ajax({
    // this url sets the cookie when called
    url: "example.com",
    success: function (_return) {
      if (_return) {
        // the _return value uses the cookie to display custom data
        // I previously used the append() method here
        $("body").html(_return);
      }
    },
  });
}

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
  wkWebView.injectCookie(
    "www.example.com/index",
    function () {
      // success callback
      loadApp();
    },
    function () {
      // error callback
      //alert('error');
    }
  );
}


text:
Q: Law of cosine in spherical trigonometry I found from a book of mine the formula $\cos a=\cos b\cos c+\sin b\sin c\cos\alpha.$ Can this be true? If for example $a=1m,b=1m,c=1m,\alpha=1$, $m$ denotes by meter, then $\cos m=\cos^2 m+\sin^2m\cos 1.$ There seems to be some mistake in units if cosine meters are sum of cosine square meters and sine square meters.

A: Aloha Curious,
This formula is the law of cosines for spherical triangles.  If you stick three dots on a sphere, and connect the three dots with the shortest segments you can, you get a spherical triangle.  The interior angles $\alpha$, $\beta$, and $\gamma$ are similar to the angles in a flat triangle; they're just the angles between the sides.  The sides to a spherical triangle can be represented by distances, since they are arcs of a great circle on the Earth, so they can have units of meters, nautical miles, or any other distance unit.  Since they are arcs, you could also represent them as angles.  $a$ is probably the "side" between points labeled $B$ and $C$ in the triangle.  If you imagine a line from Earth's center all the way to point $B$, and another line from Earth's center all the way to point $C$, then $a$ is the angle between those two lines where they touch at the center of the Earth.
So $\alpha$, $\beta$, and $\gamma$ are angles on the surface of the Earth, between the sides of the spherical triangle.  And $a$, $b$, and $c$ are angles inside the Earth, or arc lengths on the surface of the Earth, the sides of the spherical triangle.
If you want to use this formula you posted, make sure you put $a$, $b$, and $c$ in either degrees or radians though.  You can get the distance by multiplying $a$ in radians times the radius of the Earth.  An even faster way is to multiply $a$ in degrees times 60 nautical miles per degree of a great circle arc.  This is very close to how a nautical mile was originally defined.


text:
Q: Plot a 3-D Triangle in the cartesian coordinate system with vertices A(6,-1,2), B(-2,3,-4), C(-3,1,5) in matlab I have already managed to plot the 3-D Triangle using Matlab by calling the fill3 function.
This is what i used
         **declare and initialize variables**
         X=[6,-1,2];Y=[-2,3,-4],Z=[-3,1,5], C=[00001];

         **Call fill3 function so that all vertices are mapped**
           fill3=(X,Y,Z,C)

However, i have failed to indicate the vertices A,B,C on the actual 3D figure. Find below the image;

How do i indicate the vertices ABC on the 3D-Triangle?

A: Just add this line below your code
text(X,Y,Z,['A';'B';'C'],'fontsize',18); % change font size at will

And this is the result

If you don't want the labels to overlap the triangle, you can modify the coordinates of the labels. For instance, define some suitably modified coordinates X1, Y1 and Z1 and replace the above line with
text(X1,Y1,Z1,['A';'B';'C'],'fontsize',18);


text:
Q: Buffering characteristics of Unix Sockets Does anyone know the buffering characteristics of Unix sockets when sending small chunks of data (a few bytes)?
When I am using TCP sockets, I can disable the Nagle algorithm to prevent latency in data transit. But there's no equivalent functionality (that I know of) for Unix Domain sockets.

A: There is no nagle algorithm available on unix domain sockets.
Unix sockets are normally implemented as a memory buffer in the operating system kernel. Once you've written/sent data on the socket, it is copied into that buffer, and becomes immediately available to the peer.


text:
Q: Change matrix environments to use parenthesis from specific font Here is what I tried:
\documentclass{article}
\usepackage{amsmath,mathtools}
\usepackage{environ,scalerel}

\usepackage{unicode-math}
\setmathfont{Latin Modern Math}
\setmathfont{OldStandard-Regular.otf}[range={"0028,"0029},]

\let\pmatrix\relax
\let\endpmatrix\relax
\NewEnviron{pmatrix}{\scaleleftright[.8ex]{(}{\begin{matrix}\BODY\end{matrix}}{)}}

\begin{document}
    \begin{align*}
        \scaleleftright[2ex]{(}{a^{\dfrac{n^{k}}{2}}}{)}\\
        \begin{pmatrix}
            ajsbdjkhfbv & \mbox{ where}\\
            \alpha,\beta,\Omega & \mbox{ otherwise}
        \end{pmatrix}
    \end{align*}
\end{document}

The scalerel package is supposed to help with using the parenthesis from said font and adjusting with the size. But I keep getting this error:
Argument of \pmatrix has an extra }. ^^I\end{align*}
Paragraph ended before \pmatrix was complete. ^^I\end{align*}
Note: there is no restriction, any solution that can handle this will do.

A: Here is a solution. It avoids to take the whole body of the environment as a argument by composing the body of that environment in a box (\l_masum_box). That box is then used in the second mandatory argument of \scaleleftright.
\documentclass{article}
\usepackage{mathtools}
\usepackage{scalerel}

\usepackage{unicode-math}
\setmathfont{Latin Modern Math}
\setmathfont{OldStandard-Regular.otf}[range={"0028,"0029},]

\ExplSyntaxOn
\box_new:N \l_masum_box
\RenewDocumentEnvironment{pmatrix}{}
   {
     \hbox_set:Nw \l_masum_box
     \c_math_toggle_token
     \begin{matrix}
   }
   {
     \end{matrix}
     \c_math_toggle_token
     \hbox_set_end:
     \scaleleftright[.8ex]{(}{\box_use:N \l_masum_box}{)}
   }
\ExplSyntaxOff

\begin{document}
    \begin{align*}
        \scaleleftright[2ex]{(}{a^{\dfrac{n^{k}}{2}}}{)}\\
        \begin{pmatrix}
            ajsbdjkhfbv & \mbox{ where}\\
            \alpha,\beta,\Omega & \mbox{ otherwise}
        \end{pmatrix}
     \end{align*}
\end{document}

This code must be compiled with xelatex or lualatex (since it uses unicode-math).


text:
Q: Writing to file from subprocess doesn't always work, unless I include file.write() My code looks like this:
for i in range(5):
    with open(file_path, 'a') as some_file:
        subprocess.Popen("command_to_run", stdout=some_file, stderr=subprocess.stdout).wait()

When I run this, some_file only contains the output of 'command_to_run' once. I'm pretty sure it's only the final iteration of the loop.
If i modify the code to looks like this:
for i in range(5):
    with open(file_path, 'a') as some_file:
        some_file.writelines("iteration: " + str(i))
        subprocess.Popen("command_to_run", stdout=some_file, stderr=subprocess.stdout).wait()
        some_file.writelines("iteration: " + str(i))

then suddenly everything works! I can't figure out why though. I'm pretty unfamiliar with files/subprocesses, so maybe it's something obvious, but I haven't been able to find anything online. Any ideas?


text:
Q: Call controller from aspx This is my first time trying to implement a project using MVC, and I am kind of lost.
I have a view, named chart.aspx
and a controller which has the function
public ActionResult GetChartImage()
    {
        var key = new Chart(width: 300, height: 300)
            .AddTitle("Employee Chart")
            .AddSeries(
            chartType: "Bubble",
            name: "Employee",
            xValue: new[] { "Peter", "Andrew", "Julie", "Dave" },
            yValues: new[] { "2", "7", "5", "3" });

        return File(key.ToWebImage().GetBytes(), "image/jpeg");
    }

I want to call that from my aspx page, in order to show a chart.
How I can do that?

A: In your view add the following:
<img src="<%= Html.Action("GetChartImage", "YourControllerName") %>" />

A: Try this,Use Url.action in your img tag src
and also need to change ActionResult to FileContentResult . But it does not a matter .


text:
Q: SOAP::Lite connection to SSL Server I am completely new to Perl. I have written a web service in C# running on a Windows box and am calling it from a Perl script on a Linux box using SOAP::Lite. My code works fine using the http:// handler. I'm now trying to get it to work with https://
The code is:
    use SOAP::Lite;
    use POSIX;

    #Tell Perl to trust the testserver's cert
    #$ENV{HTTPS_CA_DIR} = '/usr/local/share/ca-certificates';
    $ENV{HTTPS_CA_FILE} = '/home/myusername/TestServer_CA_Cert.cer';
    #$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;

    my $uri = 'http://Automation/';
    my $proxy = 'https://TestServer/ToolsAutomation/AutomationInterface.asmx';
    my $method = SOAP::Data->name('SubmitAutomationJob')->attr({xmlns => $uri});

    #-Code that sets us @params deleted for readability-

    my $myServer = SOAP::Lite
        -> on_action(sub {join '', $uri, $_[1]})
        -> proxy($proxy)
    #        -> proxy($proxy, ssl_opts => [ SSL_verify_mode => 0 ] )
    #        -> proxy($proxy, ssl_opts => [SSL_ca_file => $ServerCACert])
            ;

    my $myCALL = $myServer #This is line 36 in the original script
                -> call($method => @params);

    print 'Result: ' . $myCALL->result;

When I run the code as posted, I get error "500 Can't connect to TestServer:443 at line 36." A network trace on the server side shows the client sends a SYN, server sends a SYN/ACK, client sends and ACK, then the client immediately sends a FIN/ACK.
I have tried various things to get this to work. I have tried:

*

*Uncommenting the line #$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0; results in "500 Can't connect to TestServer:443 (certificate verify failed). Network trace shows that at least part of HTTPS negotiation is working.

*Uncommenting the line proxy($proxy, ssl_opts => [ SSL_verify_mode => 0 ] ) works, but of course this doesn't verify the server's identity.

*Uncommenting the line -> proxy($proxy, ssl_opts => [SSL_ca_file => $ServerCACert]) also gives a "certificate verify failed" error.

*Changing the path to $ENV{HTTPS_CA_FILE} gives an error "SSL_ca_file /home/myusername/TestServer_CA_cert.ceeer does not exist" at the line 36. I take this as a good sign; the code is finding the certificate I tell it to use for server auth.

*Uncommenting both the $ENV{HTTPS_CA_DIR} and the $ENV{HTTPS_CA_FILE} lines gives the error "only SSL_ca_path or SSL_ca_file should be given."

I have imported my CA's cert into Firefox on the Linux machine and have successfully browsed to my testserver without getting an SSL warning, and then removed the cert from Firefox and browsed back and received the SSL warning, so I'm reasonably confident that the cert file I have is good.
Does anyone have any ideas on how to fix this code? Is there some attribute of the CA's cert itself that I should check? I find it puzzling that Firefox has no problem trusting a server whose SSL cert is signed with this CA's cert, but I can't convince Perl to do the same.
Any feedback is appreciated. And do remember: I'm an absolute Perl n00b. Before I Googled how to call a web service from Perl, the only think I knew about Perl was "Larry Wall."
Thanks!
UPDATE:
At the request of  Steffen Ullrich below, I ran the following:
perl -MIO::Socket::SSL=debug4 program.pl

The output I received is:
me@myMachine:~$ perl -MIO::Socket::SSL=debug4 ./program.pl
DEBUG: .../IO/Socket/SSL.pm:402: socket not yet connected
DEBUG: .../IO/Socket/SSL.pm:404: socket connected
DEBUG: .../IO/Socket/SSL.pm:422: ssl handshake not started
DEBUG: .../IO/Socket/SSL.pm:1388: SSL structure creation failed

A:
When I run the code as posted, I get error "500 Can't connect to TestServer:443 at line 36." A network trace on the server side shows the client sends a SYN, server sends a SYN/ACK, client sends and ACK, then the client immediately sends a FIN/ACK.

If this is really like you describe it then no data gets exchanged which means th client does not even attempt to do an SSL handshake. This means that probably the way you called it is wrong:
#        -> proxy($proxy, ssl_opts => [ SSL_verify_mode => 0 ] )
#        -> proxy($proxy, ssl_opts => [SSL_ca_file => $ServerCACert])

I'm pretty sure that ssl_opts does not need an array ([...]) but a hash ({...}).
EDIT:
It looks like you need an array and not a hash because ssl_opts are handled in a special way by SOAP::Lite, i.e. they are not directly given to the constructor of LWP::UserAgent as the documentation would imply. I've filed a bug about it.

DEBUG: .../IO/Socket/SSL.pm:1388: SSL structure creation failed

Based on the code I got from you I could reproduce the problem, but only if the given CA file was corrupt. I expect that this is the case for you. Note that the file must look like this:
-----BEGIN CERTIFICATE-----
MIIDKDCCApGgAwIBAgIJAOetiwdVihcnMA0GCSqGSIb3DQEBBQUAMGwxCzAJBgNV
.... more base64 encoded stuff ...
M0LUhtV8z6OcURDEfnQBsgLCPODc9Mg4FEViDGVaZ1i233ZeAlLzXSZeXL8=
-----END CERTIFICATE-----

A: Steffen provided the correct solution to the problem. When I originally exported the CA cert from the Windows CA, I exported it in "DER encoded binary X.509" format. This is what failed.
I re-exported the certificate in "Base-64 encoded X.509" format and used that in my Perl script and now things are working properly.


text:
Q: Python defining a list of large query strings vs reading in from a file I'm curious about best practices and also performance to be gained when working with lists of large strings in python. Specifically, I have a list that contains different postgreSQL queries as strings, and I'm wondering on best practices on how to initialize the list. Consider the following 2 methods:
Method 1 - Creating the list in code:
query_load = [("SELECT val_1, COUNT(*) as frequency "
     "FROM table "
     "GROUP BY val_1 "
     "ORDER BY val_1 ASC"),

     ("SELECT val_2, COUNT(*) as frequency "
     "FROM table "
     "GROUP BY val_2 "
     "ORDER BY val_2 ASC"),

     ("SELECT val_3, COUNT(*) as frequency "
     "FROM table "
     "GROUP BY val_3 "
     "ORDER BY val_3 ASC"),

     ("SELECT val_4, COUNT(*) as frequency "
     "FROM table "
     "GROUP BY val_4 "
     "ORDER BY val_4 ASC"),
     ...
      ]

Method 2 - Reading queries into list from file
my_list = [line.rstrip('\n') for line in open("..Desktop/my_queries.txt")]

As far as readability and less lines of code, Method 2 appears to be the better choice, but I'd like to stay in line with best practices. Additionally, will reading a file line-by-line into a list give worse performance (by a non-trivial amount)?

A: Just use a triple-quoted string; SQL won't care about the whitespace used to make your Python source readable.
query_load = [
    """
    SELECT val_1, COUNT(*) as frequency
    FROM table
    GROUP BY val_1
    ORDER BY val_1 ASC
    """,

    """
    SELECT val_2, COUNT(*) as frequency
    FROM table
    GROUP BY val_2
    ORDER BY val_2 ASC
    """,

    # etc
]

Whether you hard-code the queries or read them from external files is really a separate question that is only marginally related to the appearance of your source code.


text:
Q: Open web page on windows CE? I need to create a batch file to open a web page from handheld computer.
I use this instruction on Windows 7:
start iexplore http://www.google.com

But it doesn't works on Windows CE. How can I do that?

A: You can use iesample (IESMAPLE.exe) ...

A: With me knowing nothing about Win CE - try this.
start http://www.google.com


text:
Q: cannot find document just created in a trigger I have the following issue.
We use the OBI framework of MarkLogic
I use a trigger in the database to monitor incomming sensor data.
As soon as a new OBI source is loaded I check some stuff.
If I find something I create an "Alert" object.
Then I would like to use that object the generate a"payload" message to send out to mobile devices...
Now trigger works.
In the trigger I use a xdmp:eval with a different transcaction to make sure I can use the document created in the same trigger code...
BUT if I search for the newly created object it cannot be found...
Can I create a document and use it in the same trigger code?
I am afraid it is hard to create a minimal working example here but this is a try:
Relevant trigger code:
(: fire trigger ALWAYS :)
let $_ := xdmp:log(fn:concat('TP-SENSORTRIGGER-ACTION : Source ', $trgr:uri, ' triggers base rule...'))
(: create alert object plus link to source :)
let $object-id := xdmp:eval(concat('
    xquery version "1.0-ml";
    import module namespace scl = "http://example.com/sccs/lib" at "/lib/sccss-lib.xqy";

    declare variable $source-id external;

    let $object-id := scl:create-alert-object($source-id)
    let $_ := xdmp:log("***** test *****")
    return $object-id
    '), (xs:QName('source-id'), $source-id),
    <options xmlns="xdmp:eval"><isolation>different-transaction</isolation></options>)
let $_ := xdmp:log($object-id)
(: create payload from alert object :)
(:let $payload := scl:create-payload-from-alert-object($object-id)
:)
let $object := obj:find-object($object-id)
let $_ := xdmp:log($object)

The function to create the OBI object is in a lib. I can share if needed.
I have added aa log line "test" and "test B" to make sure I use the proper triggers. And to make sure they are rebuild on deploy in app-specific.rb.
Then from the logs it is clear the object cannot be found:
2015-10-20 15:33:02.860 Info: example-app: ******** Ingest transform Started ***************
2015-10-20 15:33:04.196 Info: TaskServer: TP-SENSORTRIGGER /marklogic.solutions.obi/source/81a3591a-a885-4f85-a781-b066e706ff41.xml was created, start trigger action...
2015-10-20 15:33:04.291 Info: TaskServer: TP-SENSORTRIGGER-ACTION : Source /marklogic.solutions.obi/source/81a3591a-a885-4f85-a781-b066e706ff41.xml triggers base rule...
2015-10-20 15:33:07.267 Info: TaskServer: ***** test B *****
2015-10-20 15:33:07.268 Info: TaskServer: ***** test *****
2015-10-20 15:33:07.273 Info: TaskServer: 4d1fd4e4-2911-40b0-848c-ccf8eaa39229
2015-10-20 15:33:07.277 Info: TaskServer:

After the trigger has run I can of course find the object with id 4d1fd4e4-2911-40b0-848c-ccf8eaa39229 from the QC.
So this has to do with the transaction model of MarkLogic I guess.
So again the question: Why cant I find the object I just created in a xdmp:eval ?

A: SOLUTION
It turned out you have to wrap ALL functions downstream in a xdmp:eval() for this to work.
(: fire trigger ALWAYS :)
let $_ := xdmp:log(fn:concat('TP-SENSORTRIGGER-ACTION : Source ', $trgr:uri, ' triggers base rule...'))
(: create alert object plus link to source :)
let $object-id := xdmp:eval(concat('
    xquery version "1.0-ml";
    import module namespace scl = "http://example.com/sccs/lib" at "/lib/example-lib.xqy";

    declare variable $source-id external;
    declare variable $actions external;
    declare variable $lastseen external;

    let $object-id := scl:create-alert-object($source-id,$actions,$lastseen)

    return $object-id
    '), (xs:QName('source-id'), $source-id,xs:QName('actions'), $actions,xs:QName('lastseen'), $lastseen),
    <options xmlns="xdmp:eval"><isolation>different-transaction</isolation></options>)
let $_ := xdmp:log($object-id)
(: create payload from alert object :)
(:let $payload := scl:create-payload-from-alert-object($object-id)
:)
let $payload := xdmp:eval(concat('
    xquery version "1.0-ml";
    import module namespace scl = "http://example.com/sccs/lib" at "/lib/sccss-lib.xqy";

    declare variable $object-id external;

    let $payload := scl:create-payload-from-alert-object($object-id)

    return $payload
    '), (xs:QName('object-id'), $object-id),
    <options xmlns="xdmp:eval"><isolation>different-transaction</isolation></options>)
let $_ := xdmp:log("************* PAYLOAD ****************")
let $_ := xdmp:log($payload)
(: send alert to middletier :)

let $result := xdmp:eval(concat('
    xquery version "1.0-ml";
    import module namespace scl = "http://example.com/sccs/lib" at "/lib/sccss-lib.xqy";

    declare variable $payload external;

    let $res := scl:send-alert-notification($payload)

    return $res
    '), (xs:QName('payload'), $payload),
    <options xmlns="xdmp:eval"><isolation>different-transaction</isolation></options>)
let $_ := xdmp:log("************* RESULT ****************")
let $_ := xdmp:log($result)

This is not clear from the documentation of the xdmp:eval() function :

" When set to different-transaction, the statement is evaluated in a
  separate transaction from the one in which it is called, making those
  updates available to subsequent expressions in the calling statement
  (assuming the calling statement is an update statement; if the calling
  statement is not an update, then subsequent expressions will see the
  version of the database at the system timestamp when the calling
  statement begins its evaluation)."


text:
Q: Python Multiprocessing Question My program has 2 parts divided into the core and downloader. The core handles all the app logic while the downloader just downloads urls. Right now, I am trying to use the python multiprocessing module to accomplish the task of the core as a process and the downloader as a process.
The first problem I noticed was that if I spawn the downloader process from the core process so that the downloader is the child process and the core is the parent, the core process(parent) is blocked until the child is finished. I do not want this behaivor though. I would like to have a core process and a downloader process that are both able to execute their code and communicate between each other.
example
...
def main():
    jobQueue = Queue()
    jobQueue.put("http://google.com)
    d = Downloader(jobQueue)
    p = Process(target=d.start())
    p.start()

if __name__ == '__main__':
    freeze_support()
    main()

where Downloader's start() just takes the url out of the queue and downloads it.
In order to have the 2 processes unblocked, would I need to create 2 processes from the parent process and then share something between them?

A: On the p = Process(target=d.start()) line, you're calling d.start().  Remove the parens, like below:
...
def main():
    jobQueue = Queue()
    jobQueue.put("http://google.com")
    d = Downloader(jobQueue)
    p = Process(target=d.start)
    p.start()

if __name__ == '__main__':
    freeze_support()
    main()


text:
Q: PID lookup to recall and kill task I'd like to create the below two separate lines of cmd script into a bat file. The PID changes so I'm having a hard time figuring out how to set this service PID to be dynamic.
Any help would be welcomed thank you!!
sc queryex DWDesktopService
taskkill /f /pid ####

A: You just need to scrape the PID value out of the sc output. It is awkward in cmd scripting. Change the service name to yours. When you are satisfied that the correct PID will be killed, remove the echo from the TASKKILL line.
FOR /F "usebackq delims=: tokens=1,2" %%a IN (`sc queryex "BITS" ^| FIND /I " PID "`) DO (
    SET "PID=%%b"
)
echo TASKKILL /F /PID %PID%


text:
Q: pylint warnings regarding global variables and invalid names I've written some python code that has some global constants and global variables (global within a module).  Some of the global variables get changed later in the module by functions (e.g., a func that gets command line arguments).  The code works just fine, but pylint complains:
(1) the global variables are invalid names because it is outside a function and expects it to be all caps.
(2) pylint complains about using the global keyword
Here's an example:
DEFAULT_GLOBAL_VAR1 = some value

global_var1 = DEFAULT_GLOBAL_VAR1

def get_cmd_line_args():

    global global_var1
    global_var1 = <cmd line value>

... more defs follow that change some of the other global variables.
(1) Why does Python/pylint not recognize lowercase global module variable names?  I know that global variables are frowned upon, but sometimes they are necessary.  What's the Pythonic way to deal with the pylint warnings about invalid names on global variables?
(2) I dislike the idea of disabling pylint warnings; is there another way, a better way to handle this scenario?


text:
Q: Using apt-get to remove packages and dependencies I've recently been reading through a lot of questions/answers/opinions about removing packages and dependencies.  There's a lot of different ways to do it, some being overly convoluted and some being insufficient/incomplete.  I want to ask here in one place what others think is the best ways to do go about clearing out a package and everything including configs, dependencies, and the dependencies' configs.  I'll offer my method as well that came from a lot of trial and error and hair-pulling.

A: I also use aptitude purge for that:
sudo aptitude purge <PACKAGENAME>

This command

*

*removes the dependencies

*without removing the dependencies which are also dependencies of some other installed package,

*but i'm not sure if it removes the dependencies' configs.

A: Warning:  This can remove packages that you might still want.  If this happens just reinstall them.  But honestly when you're installing/uninstalling something that's gonna make big changes to your system...why not go ahead and backup first.
The most thorough, method I've ever come up with to completely remove a package PLUS its dependencies PLUS all configs including those configs of dependencies and do a little housecleaning is this where PACKAGENAME is the main package to be removed:

*

*Log out from the desktop and press Ctrl+Alt+F1 then login to TTY1 and run the following commands:
sudo apt-get purge <PACKAGENAME>
sudo apt-get purge $(apt-cache depends <PACKAGENAME> | awk '{ print $2 }' | tr '\n' ' ')
sudo apt-get autoremove
sudo apt-get update
sudo apt-get check
sudo apt-get -f install
sudo apt-get autoclean

*Restart if needed
sudo shutdown -r now

So what's going on in the second line? The pipes take the output from apt-cache depends  and reformat it.   The first pipe awk '{ print $2 }'  takes the output of apt-cache depends  and prints, or "echoes", only the second column.  Without it you'd also have in the list another column which is the dependency type, i.e. "depends", "recommends", etc.  Then the second pipe tr '\n' ' ' takes that result and removes, or truncates (hence tr), the newline(s) and replaces them with a space that separates the names.  All of this returns a "space-delimited" list of the names of all dependency packages of PACKAGENAME that's format-friendly for use with multiple package input to purge command-option.
This works especially well for meta packages. I run the last command "sudo apt-get -f install" at the end to check for possible broken packages and fix them after making so many changes all at once.  I especially do this anytime I add a "DE" and want to go back. Just recently I used this after installing GNOME and it even fixed the fact that only purging Gnome with autoremove after still left my GRUB changed and left the login option in the DM.  When I had tried out lubuntu-desktop it fixed some conflicts and removed the entries from the DM login that were left by purge and autoremove.
A similar method which works well, is probably safer, but still doesn't always get everything is:
sudo apt-get --purge autoremove PACKAGENAME

Which may or may not need to be followed up with:
sudo apt-get update
sudo apt-get check
sudo apt-get -f install
sudo apt-get autoclean

A: autoremove is probably what you want.
For example, with remove, only one package is to be removed:
$ sudo apt remove nvidia-cuda-toolkit
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  g++-8 javascript-common libaccinj64-10.1 libcublas10 libcublaslt10 libcudart10.1 libcufft10 libcufftw10 libcuinj64-10.1 libcupti-dev libcupti-doc libcupti10.1 libcurand10 libcusolver10 libcusolvermg10
  libcusparse10 libegl-dev libgl-dev libgl1-mesa-dev libgles-dev libgles1 libglvnd-dev libglx-dev libjs-jquery libjs-underscore libncurses5 libnppc10 libnppial10 libnppicc10 libnppicom10 libnppidei10
  libnppif10 libnppig10 libnppim10 libnppist10 libnppisu10 libnppitc10 libnpps10 libnvblas10 libnvgraph10 libnvidia-common-510 libnvidia-ml-dev libnvjpeg10 libnvrtc10.1 libnvtoolsext1 libnvvm3 libopengl-dev
  libpthread-stubs0-dev libstdc++-8-dev libthrust-dev libvdpau-dev libx11-dev libxau-dev libxcb1-dev libxdmcp-dev node-html5shiv nsight-compute nsight-systems nvidia-cuda-dev nvidia-cuda-doc nvidia-cuda-gdb
  nvidia-opencl-dev nvidia-profiler nvidia-visual-profiler ocl-icd-libopencl1 ocl-icd-opencl-dev opencl-c-headers openjdk-8-jre x11proto-core-dev x11proto-dev xorg-sgml-doctools xtrans-dev
Use 'sudo apt autoremove' to remove them.
The following packages will be REMOVED:
  nvidia-cuda-toolkit
0 upgraded, 0 newly installed, 1 to remove and 95 not upgraded.
After this operation, 67.1 MB disk space will be freed.

with autoremote:
$ sudo apt autoremove nvidia-cuda-toolkit
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED:
  g++-8 javascript-common libaccinj64-10.1 libcublas10 libcublaslt10 libcudart10.1 libcufft10 libcufftw10 libcuinj64-10.1 libcupti-dev libcupti-doc libcupti10.1 libcurand10 libcusolver10 libcusolvermg10
  libcusparse10 libegl-dev libgl-dev libgl1-mesa-dev libgles-dev libgles1 libglvnd-dev libglx-dev libjs-jquery libjs-underscore libncurses5 libnppc10 libnppial10 libnppicc10 libnppicom10 libnppidei10
  libnppif10 libnppig10 libnppim10 libnppist10 libnppisu10 libnppitc10 libnpps10 libnvblas10 libnvgraph10 libnvidia-common-510 libnvidia-ml-dev libnvjpeg10 libnvrtc10.1 libnvtoolsext1 libnvvm3 libopengl-dev
  libpthread-stubs0-dev libstdc++-8-dev libthrust-dev libvdpau-dev libx11-dev libxau-dev libxcb1-dev libxdmcp-dev node-html5shiv nsight-compute nsight-systems nvidia-cuda-dev nvidia-cuda-doc nvidia-cuda-gdb
  nvidia-cuda-toolkit nvidia-opencl-dev nvidia-profiler nvidia-visual-profiler ocl-icd-libopencl1 ocl-icd-opencl-dev opencl-c-headers openjdk-8-jre x11proto-core-dev x11proto-dev xorg-sgml-doctools xtrans-dev
0 upgraded, 0 newly installed, 73 to remove and 95 not upgraded.
After this operation, 3,654 MB disk space will be freed.

A: This will remove specified package(s), all auto-installed packages and all their configs:
sudo apt-get -s purge <PKG> | grep '^ ' | tr -d '*' | xargs -o sudo apt-get purge

Or as root:
apt-get purge `apt-get -s purge <PKG> | grep '^ ' | tr -d '*'`

Substitute <PKG> with package or packages you want to remove completely.


text:
Q: ¿Cómo definir tamaño de recorte por defecto en una imagen usando Jcrop? Espero me puedan orientar, he estado intentando que inicie por defecto el tamaño de selección de recorte 400x400 px de una imagen usando Jcrop, pero no logro hacer que el área de recorte inicie y se quede en 400x400 px, he estado buscando pero no logro realizarlo espero me orienten soy nuevo en js, esto es lo que llevo. Lo que busco es que ya se inicie el área de recorte por default de tamaño 400px x 400 px. Y solo se seleccione en que coordenadas quiere el usuario recortar la imagen, un saludo muchas gracias.
<script type="text/javascript">
      $(document).ready(function(){
            var size;
            $('#RecortarImagen').Jcrop({
              aspectRatio: 1,
              onSelect: function(c){
               size = {x:c.x,y:c.y,w:c.w,h:c.h};
               $("#recortar").css("visibility", "visible");
               $("#descargar").css("visibility", "visible");
              }
            });

            $("#recortar").click(function(){
                var img = $("#RecortarImagen").attr('src');
                $("#imgrecortada_img").show();
                $("#descargar").show();
                $("#imgrecortada_img").attr('src','ImagenRecortada.php?x='+size.x+'&y='+size.y+'&w='+size.w+'&h='+size.h+'&img='+img);
            });
      });
    </script>

A: size = {x:c.x,y:c.y,w:'400',h:'400'};


text:
Q: Jpeg module in Python (on Raspbian Jessie) I tried to compress captured image (saved into file) by using jpeg module in Python 2.7.9. I know it's deprecated since version 2.6 and not available in Python 3.x and now I also know that it was (just?) for IRIX. I would just like to know whether there is some comparable module available for Python? Before I learned about that IRIX module I wrote a program using it (in "zlib fashion"). Here's a part of the program so that you'll see what comparable module I have in mind:
from __future__ import print_function
import sys, time
import jpeg

unencoded = open('image_Y.data','rb').read()
print ('Size of unencoded Y:',sys.getsizeof(unencoded))

start = time.time()

jpeg.setoption('quality', 70)
comprim = open('image_Y_comprim_jpeg.data','wb')
comprim.write(jpeg.compress(unencoded, 100, 100, 1))
t_compress = time.time() - start

comprim = open('image_Y_comprim_jpeg.data','rb').read()
decomprim = jpeg.decompress(comprim)
decompr = open('image_Y_decomprim_jpeg.data','wb')
decompr.write(decomprim)

t_decompress = time.time() - start
t_all = t_compress + t_decompress

CR = sys.getsizeof(unencoded)/sys.getsizeof(comprim)

The emphasis is on being able to compress the unencoded image (mine has only luma component), like the one in 'image_Y.data', and to choose the quality of compression, and then to decompress the image. Thank you for suggestions.


text:
Q: Weird Perl SIGPIPE behavior ("IGNORE" works, sub doesn't) As noted in comments to these questions:

*

*Weird error after Perl upgrade: Unable to flush stdout

*How to cause "Unable to flush stdout: Broken pipe" in Perl?
perl -e '$SIG{PIPE} = "IGNORE"; sleep(1); print "foo\n";' | echo -n
produces error message Unable to flush stdout: Broken pipe.
But weirdly
perl -e '$SIG{PIPE} = sub { print STDERR "XXX\n"; }; sleep(1); print "foo\n";' | echo -n
does not produce any message.
Why the second command does not produce a message? How to catch that SIGPIPE event?
The thing I really need is (for an experiment to answer this question) to catch SIGPIPE and when it happens output something to a log file.

A: When writing into a pipe like in your example STDOUT is buffered by default. This means the print "foo\n" in your code does not immediately write to STDOUT but writes into a buffer and the buffer will only be flushed (written to STDOUT) when it is full or as part of the program cleanup. Using strace to see what your program is actually doing shows that it first restores the signal handlers as part of the program cleanup and then writes to STDOUT, resulting in a SIGPIPE which is no longer handled by your sub and thus results in a kill of the program.
When making sure that the output is done immediately and not at the cleanup of the program then your signal handler gets successfully triggered. This can be done by making STDOUT unbuffered using $|=1:
$ perl -e \
   '$|=1; $SIG{PIPE} = sub { print STDERR "XXX\n"; }; sleep(1); print "foo\n";' \
   | echo -n

output: XXX

In other words: if active your signal handler works perfectly and it was only an artefact of your specific use that it got not triggered. On why it does not reset the signal handler from ignore (SIG_IGN) to  default (SIG_DFL) on exit and thus shows the same problem with IGNORE I don't know.


text:
Q: In a multithreaded app, can 2+ threads access the same function if the function does not modify/read data or modifies/reads temporary data? I can't seem to find an answer anywhere on Google. I basically want to know if 2 threads can access normal/member functions like these at the same time and not result in undefined behavior or do I have to use a mutex?
void foo(void)
{
  float x(133.7);
  float y(10);
  std::cout << std::endl << (x * y);
}

void foobar(void)
{
  std::cout << std::endl << 1/1;
}

A: I am pretty sure your code doesn't have undefined behaviour.
That said, you are using shared data, namely std::cout.
So if you expect std::cout << std::endl << (x * y) to be executed as a single operation (e.g. to prevent bits of output from different threads getting interleaved on stdout), you are going to have to use locks.

A:
I basically want to know if 2 threads can access normal/member functions like these at the same time and not result in undefined behavior or do I have to use a mutex?

Yes.  You only need the synchronization if the threads will be using shared data.  Synchronization is more about protecting the state, not the code itself.


text:
Q: In Cypress, how to create a stub of inner component and invoke its update:modelValue to check if the parent component has correctly received it? I have a complex inner component in my parent component (parent component is one of steps in a wizard, inner component displays a dynamic subform and collects inputs.
I have my inner component fully tested. It emits onUpdate:modelValue.
Now I want to test the wizard step component - the parent component.
I want to abstract that so I stub the inner component with ... well, currently a div but I am willing to substitute that with anything that will work.
My goal is to trigger the onUpdate:modelValue in the inner component to check that the parent component is in fact handing this event and triggers its own (parent component is one step in a wizard so it will bubble it up to the wizard aka. stepper to decide if the "next" button should be activated or stay disabled.
This is my helper function for binding component for cypress test:
function mountAndBind(values: any) {
    const modelValueEventSpy = cy.spy().as("modelUpdate");
    const validityEventSpy = cy.spy().as("validityUpdate");
    const internalModelValueEventSpy = cy.spy().as("internalModelUpdate");
    const internalValidityEventSpy = cy.spy().as("internalValidityUpdate");

    cy.mount(ParrentCompoenent, {
      global: {
        stubs: {
          InnerComponent: h(
            "div",
            {
              class: "internal",
              "onUpdate:modelValue": internalModelValueEventSpy
            },
            "metadata details"
          ),
        },
      },
      props: {
        "onUpdate:modelValue": modelValueEventSpy,
        modelValue: values,
      },
    });
  }

And this is the test that fails on the last assertion:
 it("shows the step, and when option chosen, shows details.", () => {
    mountAndBind({});
    cy.contains("metadata details").should("not.exist");
    // that's a custom cypress command - a helper.
    cy.selectChooseOption("parentSelectOptions", "abc");
    cy.wait("@webapirequest_for_details");
    cy.contains("metadata details").should("exist");
    cy.get(".internal").trigger("onUpdate:modelValue", { someField: "value" });
    cy.get("@modelUpdate").should("have.been.calledWith", { someField: "value" });
  });


text:
Q: Stopping function on event in javascript i'd like to include three image galleries on one page. one is running two are paused.
On event should the running gallery stop and the clicked one be running.
How do I bring the "return (function().." be stopped?
cheers
mate
var delay = 2500;
var start_frame = 0;
var container = "willkommen";

function fokus(container) {0.5
    new Effect.Appear('willkommen', { duration:, to: 0.3 });
    new Effect.Appear('eintreten', { duration:0.5, to: 0.3 });
    new Effect.Appear('reservieren', { duration:0.5, to: 0.3 });

    new Effect.Appear( container, { duration:1, to: 1 });

    var lis = $(container).getElementsByTagName('li');
    for( i=0; i < lis.length; i++){
        if(i!=0){
            lis[i].style.display = 'none';
        }
    }
    end_frame = lis.length -1;
    setTimeout(fadeInOut(container, start_frame, start_frame,end_frame, delay, lis), delay);
}

function fadeInOut(container, frame, start_frame, end_frame, delay, lis) {
        return (function() {
        lis = $(container).getElementsByTagName('li');
        Effect.Fade(lis[frame]);
        if (frame == end_frame) { frame = start_frame; } else { frame++; }
        lisAppear = lis[frame];
        setTimeout("Effect.Appear(lisAppear);", { duration:0.5, from:0.5, to:1 } );
        setTimeout(fadeInOut(container, frame, start_frame, end_frame, delay), delay + 3500);
    })
}

A: You need to store the timeout id returned from setTimeout and pass it into the clearTimeout function.
I'm not sure exacly how you're invoking the fokus function, but if you want it to encapsulate logic in multiple places on one page you should use it as a constructor function.
function Fokus (container) {
  ...
  this.timeout_id = setTimeout(fadeInOut(container, start_frame, start_frame,end_frame, delay, lis), delay);
  this.cancel = function () {
    clearTimeout(this.timeout_id);
  }
}

var gallery = new fokus("willkommen");
gallery.cancel();

There's not a whole lot of context given with your code, but it looks like you're using global variables for everything; I urge you to look into anonymous, self-executing closures to prevent global namespace pollution.


text:
Q: Updating ASP.NET label after button click, using UpdatePanel I'm trying to have two things happen when I click on a button in an ASP.NET page:

*

*Change the text in an ASP:Label.

*Disable the button.

I've done a lot of research on this, but I've had difficulties doing either.
For #1, I thought that this should work, but it doesn't:
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Test Page</title>

    <form id="form1" runat="server">
    <ajaxToolkit:ToolkitScriptManager runat="server" />

        <asp:ListBox runat="server" Height="100px" />

        <asp:UpdatePanel runat="server">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="BtnSubmit" EventName="Click" />
            </Triggers>
            <ContentTemplate>
                <asp:Label ID="Label1" runat="server" Text="Press the button" />
            </ContentTemplate>
        </asp:UpdatePanel>

        <asp:Button runat="server" ID="BtnSubmit" OnClick="BtnSubmit_Click" Text="Submit Me!" />

    </form>

The "Working..." message is never displayed.
As for #2, I added this to the button (I forget where I found it):
OnClientClick="this.disabled = true; this.value = 'Working...';"
            UseSubmitBehavior="false"

That had the desired effect of disabling the button and changing its text (value), but it wasn't possible to change it back using Text and Enabled properties.

A: I just found a solution on msdn (http://msdn.microsoft.com/en-us/library/bb386518.aspx). Added some code and remove some unnecessary parts.
<%@ Page Language="C#"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title></title>

<form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server" />

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Label ID="Label1" runat="server" Text="Hello World!"></asp:Label>

        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnDoWork" />
        </Triggers>
    </asp:UpdatePanel>
    <asp:Button ID="btnDoWork" runat="server" Text="Start!" OnClick="btnDoWork_Click" />

</form>

What you basically do, is you register some eventHandler for Initialize_ and End_Request - in those you disable and enable your button!
HTH

A: The Working message is never displayed because you are executing the script on the server, which doesn't respond to the client until the method exits.
ASP.NET AJAX has a built in control for displaying messages like this while the UpdatePanel is waiting on the server.
Check out the UpdateProgress Control:
<asp:UpdateProgress runat="server" id="progress" ><ProgressTemplate>Working...</ProgressTemplate></asp:UpdateProgress>

You can disable the button by setting the Enabled property to false in your server-side method.
BtnSubmit.Enabled = false

A: ASP will not flush the result to the browser while working even if you use an UpdatePanel. It will finish the jobb (including the sleep) before flushing.
You can use a UpdateProgress to show the "Working.." text.
<asp:UpdateProgress>

This will show its content while the UpdatePanel is working. Once the UpdatePanel is finished, the content will disappear.
What you need in you ClickEvent is:
Label1.Text = "Done."
btnSubmit.Enabled = false

This will show the Done text and disable the button. And tell the UpdateProgress to disappear.

A: @1: You will never see the message "Working" as you stopped the thread .... Every Message will be shown when your process has "ended".
@2: you coded clientSide to disable the button, there is no code to re-enable your button
hth

A: First off, "working" never appears because the final value of the label at the time of post-back is "Done." Think about what is happening here - you click the button which causes a post-back to the server. It processes the post-back which includes running the button click code, the result of which is then sent back to the browser. Your 'working' text never makes it back over the wire.
I am not clear on what you're trying to accomplish with the client-side code, but to do what you describe you're almsot there server-side:
Protected Sub BtnSubmit_Click(sender As Object, e As System.EventArgs)
    Label1.Text = "Done."
    btnSubmit.Enabled = false
End Sub

Also, but your button inside your update panel template tags so it participates in the ajax-postback.


text:
Q: Firebase Function: can not read 'user_id' of undefined I am trying to implement to send push notification from one device to another device function with my mobile app. By referring video tutorials. This is my current javascript code:
'use-strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.firestore.document("users/{user_id}/notification/{notification_id}").onWrite(event=> {

const user_id = event.params.user_id;
const notification_id = event.params.notification_id;
return admin.firestore().collection("users").doc(notification_id).get().then(queryResult=> {

        const from_user_id = queryResult.data();
        const from_data = admin.firestore().collection("users").doc(from_user_id).get();
        const to_data = admin.firestore().collection("users").doc(user_id).get();
        return Promise.all([from_data, to_data]).the(results =>{
            const from_name = results[0].data().name;
            const to_name = results[1].data().name;
            console.log("from :"+ from_name+" To "+ to_name);
        });

    });
});

This shows following error
TypeError: Cannot read property 'user_id' of undefined at exports.sendNotification.functions.firestore.document.onWrite.event (/user_code/index.js:9:30)
at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)
    at /var/tmp/worker/worker.js:733:24
    at process._tickDomainCallback (internal/process/next_tick.js:135:7

Please help me.


text:
Q: How to add Category names in search in Nopcommerce 3.8 Hi there i would like to let customers type a category name and get some search results. Currently when you type a category name it says no results.
   public ActionResult AdvanceSearch(SearchModel model, CatalogPagingFilteringModel command)
    {
        //'Continue shopping' URL
        _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
            SystemCustomerAttributeNames.LastContinueShoppingPage,
            _webHelper.GetThisPageUrl(false),
            _storeContext.CurrentStore.Id);

        if (model == null)
            model = new SearchModel();

        var searchTerms = model.q;
        if (searchTerms == null)
            searchTerms = "";
        searchTerms = searchTerms.Trim();

        //sorting
        PrepareSortingOptions(model.PagingFilteringContext, command);
        //view mode
        PrepareViewModes(model.PagingFilteringContext, command);
        //page size
        PreparePageSizeOptions(model.PagingFilteringContext, command,
            _catalogSettings.SearchPageAllowCustomersToSelectPageSize,
            _catalogSettings.SearchPagePageSizeOptions,
            _catalogSettings.SearchPageProductsPerPage);

        string cacheKey = string.Format(ModelCacheEventConsumer.SEARCH_CATEGORIES_MODEL_KEY,
            _workContext.WorkingLanguage.Id,
            string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()),
            _storeContext.CurrentStore.Id);
        var categories = _cacheManager.Get(cacheKey, () =>
        {
            var categoriesModel = new List<SearchModel.CategoryModel>();
            //all categories
            var allCategories = _categoryService.GetAllCategories(storeId: _storeContext.CurrentStore.Id);
            foreach (var c in allCategories)
            {
                //generate full category name (breadcrumb)
                string categoryBreadcrumb = "";
                var breadcrumb = c.GetCategoryBreadCrumb(allCategories, _aclService, _storeMappingService);
                for (int i = 0; i <= breadcrumb.Count - 1; i++)
                {
                    categoryBreadcrumb += breadcrumb[i].GetLocalized(x => x.Name);
                    if (i != breadcrumb.Count - 1)
                        categoryBreadcrumb += " >> ";
                }
                categoriesModel.Add(new SearchModel.CategoryModel
                {
                    Id = c.Id,
                    Breadcrumb = categoryBreadcrumb
                });
            }
            return categoriesModel;
        });
        if (categories.Any())
        {
            //first empty entry
            model.AvailableCategories.Add(new SelectListItem
            {
                Value = "0",
                Text = _localizationService.GetResource("Common.All")
            });
            //all other categories
            foreach (var c in categories)
            {
                model.AvailableCategories.Add(new SelectListItem
                {
                    Value = c.Id.ToString(),
                    Text = c.Breadcrumb,
                    Selected = model.cid == c.Id
                });
            }
        }

        IPagedList<Product> products = new PagedList<Product>(new List<Product>(), 0, 1);
        // only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load)
        if (Request.Params["q"] != null)
        {
            if (searchTerms.Length < _catalogSettings.ProductSearchTermMinimumLength)
            {
                model.Warning = string.Format(_localizationService.GetResource("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength);
            }
            else
            {
                var categoryIds = new List<int>();
                int manufacturerId = 0;
                decimal? minPriceConverted = null;
                decimal? maxPriceConverted = null;
                bool searchInDescriptions = false;
                int vendorId = 0;
                if (model.adv)
                {
                    //advanced search
                    var categoryId = model.cid;
                    if (categoryId > 0)
                    {
                        categoryIds.Add(categoryId);
                        if (model.isc)
                        {
                            //include subcategories
                            categoryIds.AddRange(GetChildCategoryIds(categoryId));
                        }
                    }

                    manufacturerId = model.mid;

                    //min price
                    if (!string.IsNullOrEmpty(model.pf))
                    {
                        decimal minPrice;
                        if (decimal.TryParse(model.pf, out minPrice))
                            minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency);
                    }
                    //max price
                    if (!string.IsNullOrEmpty(model.pt))
                    {
                        decimal maxPrice;
                        if (decimal.TryParse(model.pt, out maxPrice))
                            maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency);
                    }

                    if (model.asv)
                        vendorId = model.vid;

                    searchInDescriptions = model.sid;
                }

                //var searchInProductTags = false;
                var searchInProductTags = searchInDescriptions;

                //products
                products = _productService.SearchProducts(
                    categoryIds: categoryIds,
                    manufacturerId: manufacturerId,
                    storeId: _storeContext.CurrentStore.Id,
                    visibleIndividuallyOnly: true,
                    priceMin: minPriceConverted,
                    priceMax: maxPriceConverted,
                    keywords: searchTerms,
                    //searchDescriptions: searchInDescriptions,
                    searchProductTags: searchInProductTags,
                    searchSku: true,
                    languageId: _workContext.WorkingLanguage.Id,
                    orderBy: (ProductSortingEnum)command.OrderBy,
                    pageIndex: command.PageNumber - 1,
                    pageSize: command.PageSize,
                    vendorId: vendorId);
                model.Products = PrepareProductOverviewModels(products).ToList();

                model.NoResults = !model.Products.Any();

                //search term statistics
                if (!String.IsNullOrEmpty(searchTerms))
                {
                    var searchTerm = _searchTermService.GetSearchTermByKeyword(searchTerms, _storeContext.CurrentStore.Id);
                    if (searchTerm != null)
                    {
                        searchTerm.Count++;
                        _searchTermService.UpdateSearchTerm(searchTerm);
                    }
                    else
                    {
                        searchTerm = new SearchTerm
                        {
                            Keyword = searchTerms,
                            StoreId = _storeContext.CurrentStore.Id,
                            Count = 1
                        };
                        _searchTermService.InsertSearchTerm(searchTerm);
                    }
                }

                //event
                _eventPublisher.Publish(new ProductSearchEvent
                {
                    SearchTerm = searchTerms,
                    SearchInDescriptions = searchInDescriptions,
                    CategoryIds = categoryIds,
                    ManufacturerId = manufacturerId,
                    WorkingLanguageId = _workContext.WorkingLanguage.Id,
                    VendorId = vendorId
                });
            }
        }

        model.PagingFilteringContext.LoadPagedList(products);
        return View(model);
    }

A public action method 'AdvanceSearch' was not found on controller 'Nop.Web.Controllers.CatalogController'.


text:
Q: Problemas com sql no access, tipos de dados incompatíveis Imagem do teste/erro:

Pretendo apenas buscar os dados entre uma data e outra, usando:
SELECT * FROM tblTRAZA
WHERE FECMOV >= '2013-01-03'
AND FECMOV <= '2013-01-09';

Mas já tentei outros formatos de data para consulta como yyyy/mm/dd, tentei usar apenas a data sem às horas, e como na imagem, tentei usar uma data específica que já tinha cadastrada, porém esse erro me persegue. É possível que tenha que alterar a estrutura da data da tabela?

A: Quebrei a cabeça um pouco e consegui descobrir o formato de data usado pelo access no caso desse banco, e ficou assim:

SELECT *
      FROM tblTRAZA
      WHERE (tblTRAZA.FECMOV BETWEEN #5/20/2014 00:00:00# And #5/31/2014 23:59:59#)

Os campos de datas são entendidos pelo sql do access quando se coloca a data completa entre '#' (jogo da velha kkk), e o formato de data foi colocado como MM/DD/YYYY.
OBS: o banco está em MDB (formato ACCESS 2002)


text:
Q: What do I need to return from __repr__ to have multiple lines when printing custom object wrapped in a pandas object consider my custom class Cube
class Cube(object):
    def __init__(self):
        pass

    def __repr__(self):
        return "⧉ ⟦x⨯y⟧\nCUBE"

cube = Cube()

cube

⧉ ⟦x⨯y⟧
CUBE

The string representation was printed on multiple lines.
However, when I wrap it in a pandas pd.Series it prints on one line
pd.Series(cube)

0    ⧉ ⟦x⨯y⟧\nCUBE
dtype: object

Same thing with a pd.DataFrame
pd.DataFrame([cube])

I don't want \n to be printed.  I want a newline.

A: I don't have a good answer for your actual question, but in the past when I've wanted to change some of the visuals of a DataFrame's HTML table, I've used a combination of IPython.display.display_html() and pd.DataFrame.to_html(). Not ideal, but at least one potential workaround for you.
from IPython.display import display_html
display_html(pd.DataFrame([cube]).to_html().replace("\\n", "\n
").replace("CUBE", 'CUBE'), raw=True)


text:
Q: Solve the system of equations $\begin{cases}x^3-3x=y \\ y^3-3y=z \\ z^3-3z=x \end{cases}$
Find the number of real solutions to the system of equations
  $$\begin{cases}x^3-3x=y \\ y^3-3y=z \\ z^3-3z=x \end{cases}$$

Let $f(x) = x^3-3x$ then for $x\in \mathbb{R}-(-2,2)$ we have $x_1 < x_2 \Rightarrow f(x_1) < f(x_2)$. Thus
WLOG $x\le y\le z \qquad (1)$ $$\Rightarrow f(x) \le f(y) \le f(z) \\ \Rightarrow y\le z\le x\qquad (2)$$
Hence by (1) and (2) we conclude that $x=y=z$ which yields that $x=y=z= \{-2,0,2\}$
So there are 3 solutions, but this is not the correct answer.

A: Let $f(x):=x^3-3x$ and $g(x):=f(f(f(x)))$.
We will look at possible values for variable $x$, values for $y$ and $z$ being computable from $x$ which are roots of the following equation
$$h(x):=g(x)-x =0\ \ \ (*)$$
See curve at the bottom of this page.
We are going to show that the set of (strictly) positive roots of (*) is in two parts:
$$\left\{\begin{matrix}
x=2\cos(k \pi/13) \ \ \ k=1 \cdots 12\\
x=2\cos(k \pi/14) \ \ \ k=0 \cdots 14
\end{matrix}\right. \ \ \ \ (**)$$
Remark: one can check that the two sets in (**) have no common root.
In this way, polynomial $h$ (which has degree 27) has $27$ real roots.
If we establish that all these $x$ are roots, we will have exhausted all of them.
Here is the proof. Let $x$ be a root of (*) in $[-2,2]$ (in fact, all of them are in this interval). Let:
$$x=2 \cos(a)  \ \ \ (1)$$
(a change of variable advised by @achille hui)
Multiplying trigonometry formula: $\cos(3a)=4\cos^3(a)-3\cos(a)$ by $2$, we obtain $2\cos(3a)=(2\cos(a))^3-3(2\cos(a))$, permitting to write $y$ as a function of $a$ in this way:
$$y=2 \cos(3a) \ \ $$
Along the same lines, we have: $ \ \ z=2 \cos(9a), \ \ \ $ and:
$$x=2 \cos(27a) \ \ \ (2)$$
Let us write that (1) and (2) have to be compatible, i.e., $a$ must satisfy $\cos(27a)=\cos(a)$.
Two angles with the same cosine are either the same or are opposite (up to $k2 \pi$):
$$\left\{\begin{matrix}
27a=a+k 2 \pi & \ \text{giving} \ & a=k \pi/13\\
27a=-a+k 2 \pi & \ \text{giving} \ & a=k \pi/14
\end{matrix}\right. \ \ \ \ $$
which establishes (**).
The curve of $y=h(x)$:


text:
Q: using fork() , execlp() and dup2() I am writing a C program which will run Linux commands, like:
ls -al | grep "main" | sort

I used just the children to do that.  (it work when I use the parent to execute the last one but I want to use just the children )
I have a problem that is the last fork execute before the second fork.
and that will run this command ls -al | sort | grep "main"
in  this example the result is the same but with others is wrong.
how can I wait the second fork in the last fork ?.
code :

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>

#define READ 0
#define WRITE 1

int main(int argc, char *argv[])
{
    pid_t pid;
    int fd[2],fd1[2];

    pipe(fd);pipe(fd1);
    pid = fork();

    if (pid == 0)
    {
        close(fd1[READ]);close(fd1[WRITE]);close(fd[READ]);
        printf("i'm the child used for ls \n");
        dup2(fd[WRITE], STDOUT_FILENO);
        close(fd[WRITE]);
        execlp("ls", "ls", "-al", NULL);
    }
    else
    {
        pid = fork();
        if (pid == 0)
        {
            close(fd1[READ]);close(fd[WRITE]);
            printf("i'm in the second child, which will be used to run grep\n");
            dup2(fd[READ], STDIN_FILENO);
            close(fd[READ]);
            close(fd1[READ]);close(fd[WRITE]);
            dup2(fd1[WRITE], STDOUT_FILENO);
            close(fd1[WRITE]);
            execlp("grep", "grep", "main", NULL);
        }
        else
        {
            pid = fork();
            if (pid == 0)
            {
                /* code */
                close(fd[READ]);close(fd[WRITE]);close(fd1[WRITE]);
                printf("i'm in the third child, which will be used to run (sort)\n");
                dup2(fd1[READ], STDIN_FILENO);
                close(fd1[READ]);
                execlp("sort", "sort", NULL);
            }
        }
    }
    return 0;
}


text:
Q: Prove by using Pigeon Hole Principle Let $k \in \mathbb Z^+ $. Prove that there exists a positive integer $n $ such that $k|n$ and the only digits in $n$ are 0's and 3's

A: HINT: Let $$m_n=\underbrace{3\dots3}_{n\text{ threes}}\;.$$ Let $r_n$ be the remainder when you divide $m_n$ by $k$. Use the fact that if $r_n=r_\ell$ with $n>\ell$, then $k\mid m_n-m_\ell$.


text:
Q: Send from free Gmail account via PHP I want to send email via PHP script using my free Gmail as the From sender. How can this be done such that the SPF records will be valid (as if the mail was actually sent from Gmail)?

A: There are many other libraries as well. Some of them are :

*

*http://phpmailer.worxware.com/

*http://pear.php.net/package/Mail (This is Pear package)

*https://github.com/denvertimothy/ThriveSMTP

*http://swiftmailer.org/
You can send the mail from PHP using SMTP using any of these libraries
An example of sending mail using your Gmail account with PHPMailer library  will be :
//include the file
require_once('class.phpmailer.php');

$phpmailer          = new PHPMailer();

$phpmailer->IsSMTP(); // telling the class to use SMTP
$phpmailer->Host       = "ssl://smtp.gmail.com"; // SMTP server
$phpmailer->SMTPAuth   = true;                  // enable SMTP authentication
$phpmailer->Port       = 465;          // set the SMTP port for the GMAIL server; 465 for ssl and 587 for tls
$phpmailer->Username   = "yourname@yourdomain"; // Gmail account username
$phpmailer->Password   = "yourpassword";        // Gmail account password

$phpmailer->SetFrom('name@yourdomain.com', 'First Last'); //set from name

$phpmailer->Subject    = "Subject";
$phpmailer->MsgHTML($body);

$phpmailer->AddAddress($to, "To Name");

if(!$phpmailer->Send()) {
  echo "Mailer Error: " . $phpmailer->ErrorInfo;
} else {
  echo "Message sent!";
}

Hope this helps you

A: As one of the solutions, you can use Zend Framework Zend_Mail class
    $email_conf = array(
        'auth' => 'login',
        'username' => 'your_login',
        'password' => 'your_password',
        'ssl' => 'tls',
        'port' => '587'
    );
    $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $email_conf);
    Zend_Mail::setDefaultTransport($transport);

    $mailer = new Zend_Mail('utf-8');
    $mail->addTo($recipientEmail);
    $mail->setSubject($subject);
    $mailer->setBodyHtml($html);
    $mail->send();

A: You will have to send the message through Google's SMTP servers. If you need pure PHP, find a SMTP library (I only know of Net_SMTP from PEAR) and configure it for smtp.gmail.com with the usual settings that Gmail gives you.


text: Q: Last N Quarter, Month, Week, Date in Tableau I want to show Last 2 Quarters, 2 Months, 2 Weeks and 2 days in one chart (As Columns). Dates are in a proddate. Any idea if this is possible. Right now im using separate charts and just putting them side by side.


text:
Q: Scraping elements from a Youtube video I want to take some tags from youtube videos like the title, the number of views etc.I use BeautifulSoup for that but I want to make it faster.Here is my code:
#for the title
from BeautifulSoup import BeautifulSoup
html = re.findall('content=.*>\n\n',urllib2.urlopen(link).read())
soup = BeautifulSoup(html)
print soup.prettify()

#for the number of views
soup0 = BeautifulSoup(urllib2.urlopen(link).read())
for items in soup0.findAll('strong'):
    if re.match("^[0-9]*$", str(items).strip("").rstrip("")):
        viewcount=str(strongs).strip("").rstrip("")

A: Use google's youtube api.
Part of their example:
def PrintEntryDetails(entry):
   print 'Video title: %s' % entry.media.title.text
   print 'Video published on: %s ' % entry.published.text
   print 'Video description: %s' % entry.media.description.text
   print 'Video category: %s' % entry.media.category[0].text
   print 'Video tags: %s' % entry.media.keywords.text
   print 'Video watch page: %s' % entry.media.player.url
   print 'Video flash player URL: %s' % entry.GetSwfUrl()
   print 'Video duration: %s' % entry.media.duration.seconds


text:
Q: Duvida Socket Server Estou com uma dúvida no comportamento do trecho de um código que esta criando um socket server, segue o código do servidor:
public class Server {

public static void main(String args[]){
    try {
        ServerSocket server = new ServerSocket(3322);
        System.out.println("Servidor iniciado na porta 3322");

        Socket cliente = server.accept();
        System.out.println("Cliente conectado do IP "+cliente.getInetAddress().
                getHostAddress());
        Scanner entrada = new Scanner(cliente.getInputStream());
        while(entrada.hasNextLine()){
            System.out.println(entrada.nextLine());
        }

        entrada.close();
        server.close();

    } catch (IOException ex) {
        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
    }

}

Após o cliente se conectar ao server e por exemplo não digitar nada... o método entrada.hasNextLine() não deveria retornar false encerrando assim o while e fechando o socket? por que isso não acontece e o código fica "eternamente" esperando receber mensagens digitadas pelo cliente?

A: Porque uma operação envolvendo digitação via teclado é um input de dados infinito, ou seja, o sistema fica eternamente em estado de espera pela próxima linha a ser digitada, mesmo que ela nunca de fato o seja. Em outras palavras, esse método tem a capacidade de bloquear a execução do resto do programa enquanto espera pelo próximo input, que pode nunca acontecer se o usuário resolver não digitar mais nada. A documentação deixa isso explícito:

public boolean hasNextLine()
Returns true if there is another line in
the input of this scanner. This method may block while waiting for
input. The scanner does not advance past any input.

Você, no caso, poderia checar se a linha está vazia como condição de saída do while.