text:
Q: Can I change rendering of responsive datatables plugin I have the following datatable which has some columns grouping.

And with the responsive plugin for datables when resizes  Iget this display.

However the 2 first column titles are lost, is this possible with jquery datatables to change this behavior??
This is the html template I am using
tableVistaEjecucionPendientes: "
" +
                                        "
" +
                                            "
" +
                                              "<button type=\"button\" id=\"btnVistaIniciativas\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaEjecucionPendientes('Iniciativas')\">Iniciativas</button>" +
                                              "<button type=\"button\" id=\"btnVistaResponsables\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaEjecucionPendientes('Responsables')\">Responsables</button>" +
                                            "
" +
                                        "
" +
                                        "
" +
                                            "
" +
                                                "
" +
                                                    "
" +
                                                        "" +
                                                            "{0}" +
                                                        "	" +
                                                        "" +
                                                            "En Ejecución" +
                                                        "	" +
                                                        "" +
                                                            "Pendientes" +
                                                        "	" +
                                                    "
" +
                                                    "
" +
                                                        "" +
                                                            "A tiempo" +
                                                        "	" +
                                                        "" +
                                                            "Desfasadas" +
                                                        "	" +
                                                        "" +
                                                            "A tiempo" +
                                                        "	" +
                                                        "" +
                                                            "Atrasadas" +
                                                        "	" +
                                                    "
" +
                                                    "
" +
                                                        "" +
                                                            "Porcentaje" +
                                                        "	" +
                                                        "" +
                                                            "Cantidad" +
                                                        "	" +
                                                        "" +
                                                            "Porcentaje" +
                                                        "	" +
                                                        "" +
                                                            "Cantidad" +
                                                        "	" +
                                                        "" +
                                                            "Porcentaje" +
                                                        "	" +
                                                        "" +
                                                            "Cantidad" +
                                                        "	" +
                                                        "" +
                                                            "Porcentaje" +
                                                        "	" +
                                                        "" +
                                                            "Cantidad" +
                                                        "	" +
                                                    "
" +
                                                "
" +
                                                "
" +
                                                    "{1}" +
                                                "
" +
                                            "
" +
                                        "
" +
                                    "
",

and thiis how I draw the datatable using the template
  function drawVistaEjecucionPendientes(data, filter) {
        resetBreadCrumb();
        var html = "";
        for (var i = 0; i < data.length; i++) {
            html += template.rowVistaEjecucionPendientes.replace("{0}", data[i].Nombre)
                .replace("{1}", data[i].ATiempoEjecucionPorcentaje != null ? data[i].ATiempoEjecucionPorcentaje + "%" : "0%")
                .replace("{2}", data[i].ATiempoEjecucionCantidad)
                .replace("{3}", data[i].DesfasadasEjecucionPorcentaje != null ? data[i].DesfasadasEjecucionPorcentaje + "%" : "0%")
                .replace("{4}", data[i].DesfasadasEjecucionCantidad)
                .replace("{5}", data[i].ATiempoPendientesPorcentaje != null ? data[i].ATiempoPendientesPorcentaje + "%" : "0%")
                .replace("{6}", data[i].ATiempoPendientesCantidad)
                .replace("{7}", data[i].DesfasadasPendientesPorcentaje != null ? data[i].DesfasadasPendientesPorcentaje + "%" : "0%")
                .replace("{8}", data[i].DesfasadasPendientesCantidad);
        }
        $("#tab_iniciativasTiempos").html("
" + "
" + template.tableVistaEjecucionPendientes.replace("{0}", filter).replace("{1}", html));
        $(".tableVistaEjecucionPendientes").DataTable({
            responsive: {
                details: {
                    type: "inline"
                }
            }
        });
    }


text:
Q: How to add image background in only one widget I want to add image background in only one widget. For example, like this homepage on website: http://www.goldenrama.com/. For each widget, this is filling in different background. I don't know to modify CSS and html.
I am using wordpress with BookYourTravel theme.
I'll be lucky if i get solution of this problem.
Regards,
Erwan

A: G'day Erwan,
To alter just one particular widget, use the firefox inspect element tool:
1. Right click on the widget
2. Go to inspect element
You will then see that each widget has a unique id. For example when I inspect a widget on one of my clients sites I get:

In this case the id is "wpp-2"
So then to add a background image you would just do this via CSS as follows:
#wpp-2 {
background-image: url('images/foo.jpg');
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does my image lose its gradient in flutter? So I was trying to create a welcome page when I got this problem. At first, everything was fine, but when I insert an image using DecorationImage, it looks like my image has an error in the color gradient. The real image look like this:
But when i run my app, i get this:

I use PageView.Builder in Scaffold to show my images. My code look like this:
return Scaffold(
      body: PageView.builder(
          scrollDirection: Axis.vertical,
          itemCount: img.length,
          itemBuilder: (_,index){
            return Container(
              width: double.maxFinite,
              height: double.maxFinite,
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage(
                          "assets/image/"+img[index]
                      ),
                      fit: BoxFit.cover
                  )
              ),

I put all my image names in a list and use the index to call each images.
The goldfish looks pretty much the same but the gradient at the bottom is disturbed. At first, I thought it was because I was using a low spec virtual device, but then I tried with a different virtual device and still got the same result. Why this happened? Does anyone know where I went wrong?
Edit: i try to add FilterQuality
return Container(
              width: double.maxFinite,
              height: double.maxFinite,
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage(
                          "assets/image/"+img[index]
                      ),
                      fit: BoxFit.cover,
                      filterQuality:FilterQuality.high
                  )
              ),

But nothing happen. Did I put it wrong?

A: i tried using real device and it works, but i don't know why


text:
Q: Bibliotecas, interface, classes e métodos Qual a diferença de bibliotecas e interfaces?
Por exemplo, na linha:
import java.util.Scanner;

O util seria a interface e Scanner a classe? Ou o util seria a biblioteca e o Scanner continuaria sendo a classe?
No caso dos métodos com @Override só faz sentido quando trabalhamos com interfaces? Em caso com herança não sei se tem tanto motivo.

A: Os termos estão completamente errados e misturados.
Há uma relação entre classe e interface.
Biblioteca é um termo genérico que não é usado no código em si. O que você provavelmente está falando são dos pacotes (packages).
Então no exemplo o java.util é o pacote. E Scanner é a classe.
Em nenhum momento está usando interface aí. Mais informações. Quando usar.
Veja como usar o  @override. Mais informações.


text:
Q: Field is not setting to NULL value via DataStage There is an interface between Salesforce and DataStage for User object and Users are updated in Salesforce via DataStage job. There is a text field "District" on User object which has no special attributes, just a normal text field. DataStage is trying to update a particular User's District from some value 'ABC' district to NULL value. However, the field "District" still shows the same value "ABC" and not blank/null value. The success file from DataStage does say that it updated the item successfully, however when it enters Salesforce zone, the field is not updated on the user record.
Please advise what can be the issue and how we can resolve this to set the field to null value.

A: I'm not familiar with DataStage, but when updating records through the API, you need to explicitly set fields to null using the fieldsToNull property. In my experience with other integration tools, just setting a null on the field won't work.

A: EDIT :
Additionally, it is worth checking for any before Triggers / workflows which could be resetting the District to the incumbent value.
Also worth checking if setting it to null via the UI manually works.

What does the interface comprise of ? Is it DataLoader scheduled using Windows Task Scheduler, or a Cron ?
What is the value that the interface is inserting to the set the value to NULL?
If it is the DataLoader, then check your settings to see if the field "Insert Null Values" is checked.
To insert null values using bulk api instead of leaving that cell empty in the csv file you need to populate"#N/A" in that.
Reference :
http://www.interactiveties.com/b_bulk_api_nulls.php

A: vimal are you sure there are no triggers/formulas updating the field?
I would try to
1) See in the dev console if there are any workflows/formulas/triggers updating
2) Brute method : try to delete the field in a sandbox and it won't let u delete in case the trigger/workflow is updating the field.
Than that I would be curious to know why a null value would not be updated!!!
Hope this helps!!!


text:
Q: Cannot list or download files from AWS EC2 FTP server from Heroku app I have an AWS EC2 instance acting an FTP server as described here:
https://www.xadmin.net/how-to-setup-ftp-on-aws-ec2-instance/
The EC2 instance has a security group with custom TCP rules to allow connections from any IP.

Connections via FileZilla and other FTP clients are successful.
I have a Spring Boot app that connects to this EC2 FTP server and it works locally. However, when deployed to Heroku, attempts at listing files or getting specific files hangs without any error.
The Spring Boot app uses the full public URL to the EC2 instance as the FTP host (ec2-xx-xxx-xxx-xxx.compute-1.amazonaws.com).
How do I allow the Heroku app to access the EC2 FTP server?

A: Most probably the server is misconfigured and sends its internal IP address in the FTP PASV command response.
While FileZilla and many other FTP clients can workaround that, Heroku probably cannot.
Check FileZilla log file for:
Server sent passive reply with unroutable address in FileZilla.
If this is the case, you will need to fix your FTP server.


text:
Q: Discord bot - Purge command not working discord.js-commando I have created a discord bot recently using node js which when I do !purge, responds with Unknown command, do !help to view a list of command but after saying it, it is purging the messages. That is, it works well but posting that error message. I don't know what's the problem please help me
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix = '!';

bot.on('message', message => {

    let msg = message.content.toUpperCase();
    let sender = message.author;
    let cont = message.content.slice(prefix.length).split(" ");
    let args = cont.slice(1);

    if (msg.startsWith(prefix + 'PURGE')) {
        async function purge() {
            message.delete();

            if (isNaN(args[0])) {
                message.channel.send('Please input a number of messages to be deleted \n Syntax: ' + prefix + 'purge <amount>');
                return;
            }

            const fetched = await message.channel.fetchMessages({limit: args[0]});
            console.log(fetched.size + ' messages found, deleting...');

            // Deleting the messages
            message.channel.bulkDelete(fetched)
                .catch(error => message.channel.send(`Error: ${error}`));

        }
        purge();
    }
});

bot.login('MY BOT TOKEN HERE');

A: Right now you're using the discord.js-commando library. Any reason you decided to use that library? It looks like you're just using standard discord.js functions like bot.on, message.channel.send, message.channel.fetchMessages, message.channel.bulkDelete...
You should be good just useing the standard discord.js library, starting your code with this:
const Discord = require('discord.js');
const bot = new Discord.Client();

You can find this code on the main "Welcome" page of Discord.js
Edit:
I'm still not sure why you're using discord.js-commando, but that doesn't matter. Here's an example command I came up with using the discord.js-commando library:
const commando = require('discord.js-commando');

class PurgeCommand extends commando.Command {
    constructor(client) {
        super(client, {
            name: 'purge',
            group: 'random', // like your !roll command
            memberName: 'purge',
            description: 'Purge some messages from a Text Channel.',
            examples: ['purge 5'],

            args: [
                {
                    key: 'numToPurge',
                    label: 'number',
                    prompt: 'Please input a number ( > 0) of messages to be deleted.',
                    type: 'integer'
                }
            ]
        });
    }

    run(msg, { numToPurge }) {
        let channel = msg.channel;

        // fail if number of messages to purge is invalid
        if (numToPurge <= 0) {
            return msg.reply('Purge number must be greater than 0');
        }

        // channel type must be text for .bulkDelete to be available
        else if (channel.type === 'text') {
            return channel.fetchMessages({limit: numToPurge})
                .then(msgs => channel.bulkDelete(msgs))
                .then(msgs => msg.reply(`Purge deleted ${msgs.size} message(s)`))
                .catch(console.error);
        }
        else {
            return msg.reply('Purge command only available in Text Channels');
        }
    }
};

module.exports = PurgeCommand

I'd also recommend using a new type instead of integer so you can validate the user's response and make sure they enter a number greater than 0.
If you need help setting up an initial discord.js-commando script, I'd take a look at this repo provided by the Discord team: https://github.com/discordjs/Commando/tree/master/test

A: You might wanna use this. This purge command is intended for discord.js v11.5.1 and I haven't tested to see if it works on v12, but I think this might work for you. I should say that THIS DELETES ALL THE CONTENT INSIDE THE CHANNEL (Nested command)
exports.run = (bot, message, args) => {
  let filter = m => message.author.id === message.author.id;

  message.channel.send("Are you sure you wanna delete all messages? (y/n)").then(() => {
      message.channel.awaitMessages(filter, {
        max: 1,
        time: 30000,
        errors: ['time']
      })
        .then(message => {
          message = message.first();

          if (message.content.toUpperCase() == "YES" || message.content.toUpperCase() == "Y") {
            message.channel.bulkDelete(100);
          } else if (message.content.toUpperCase() == "NO" || message.content.toUpperCase() == "N") {
            message.channel.send("Terminated").then(() => {message.delete(2000)});
          } else {
            message.delete();
          }
        })
        .catch(collected => {
        message.channel.send("Timeout").then(() => {message.delete(2000)});
      });
    }).catch(error => {
    message.channel.send(error);
  });
};


text:
Q: In Chrome DevTools How to prevent script from executing I have a page not on my server, where a particular is running during page-loading
...other stuff...
<script src="http://someserver.com/script.js"></script>
...other stuff...

and causing some problems.
I need to debug this so first I'd like to prevent that script from loading.
How can I do this? All I've found is that I can delete, edit or add a script after the page has loaded. But that is not what I need. I need to load the whole page but skip loading this very script.

A: Google Chrome can now do this for you.

*

*Open developer tools

*Open the network tab

*Navigate to the site

*Find the request that loads the script

*Right-click on the request and select "Block request URL"

Chrome will now block the request that loads that script.  To remove the block:

*

*Open the console at the bottom of developer tools, fyi the "Esc" (escape) key will toggle it.

*Open the "Request Blocking" tab (you'll find it in the 3 dot menu next to the "Console" tab if you don't have the tab available)

*Click the stop looking icon with the title of "Remove all patterns"

A: There are a couple of approaches to this... the first being the old school way of handling ad blocking (which this is similar to), which is simply create a dns entry in your hosts file (C:\windows\system32\drivers\etc\hosts on windows) and alias someserver.com to localhost 127.0.0.1:
someserver.com  127.0.0.1

This, however, has the unfortunate side-effect of not loading ANYTHING from someserver.com.
Another option is to use something like adblock plus, and just add the script to the "Add your own filters" tab, where the syntax for your filter will be:
http://someserver.com/script.js

Hope that helps!


text:
Q: Attaching drag behaviour without using data().enter() in D3 v4.0.0-alpha.40 I have a project with a draggable circle. In the process of upgrading from D3 v3 > v4.0.0-alpha.40 the drag behaviour broke. It only seems to work when the draggable element is created using data([1]).enter().append('circle'). See the simple jsfiddle example for a simplified version
Can someone explain what I'm doing wrong?
Edit 1: Github issue opened
Edit 2: Working jsfiddle as per accepted answer

A: [This is copied from my response to your issue.] This is the expected behavior, though perhaps it could be improved. As the documentation for drag.subject says:

The default subject is the datum of the element in the originating selection (see drag) that received the initiating input event. When dragging circle elements in SVG, the default subject is the datum of the circle being dragged…

And:

If the subject is null or undefined, no drag gesture is started for this pointer; however, other starting touches may yet start drag gestures.

In your failing example, the datum of your circle is undefined, so it can't initiate a drag gesture. Giving the circle a non-null datum, such as 1, fixes it.
Yet even your non-failing example isn't ideal because the drag gesture can't infer the x- and y-coordinates of the circle, and so when you start a drag gesture, the circle center will jump to the mouse (or touch) position, rather than maintaining the relative position of the circle and pointer. A better way of creating a single, draggable circle would be:
d3.select("svg").append("circle")
    .datum({x: 4 * 30, y: 4* 30})
    .attr("r", 30)
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; });

It's possible we should change the default subject to be something else if the element's datum is undefined… such as the element itself. That would make the drag behavior work as you expect, although the above code is a better solution in my opinion.

A: When first tackling this problem I encountered two problems, which thwarted my plans of attack. But as the development of v4 progresses Mike Bostock has cleared the way:

*

*The first problem was the missing fallback to the element itself if there is no data present (removed by commit 8b25a53). My originial answer (see below) solved this by explicitely setting the element to be the subject of the drag. This was addressed by issue #18 and was reverted by commit 4e4855f, thus eliminating the need to set the subject.

*Looking at it again, I realized that the properties dx and dy got removed from the DragEvent. I opened issue #21 asking Mike if we could have them back. Fortunately, he agreed and brought them back with commit 24e9583.
The missing links are now available in the latest build for version v4.0.0-alpha.44.
That said, I was ready to implement the no data approach I thought of in the first place:

d3.selectAll("circle")
    .call(d3.drag()
            .on("drag", function() {
              this.transform.baseVal
                .appendItem(this.ownerSVGElement.createSVGTransform())
                .setTranslate(d3.event.dx, d3.event.dy);
              this.transform.baseVal.consolidate();
            })
    );
<script src="https://d3js.org/d3.v4.0.0-alpha.44.js"></script>

<svg width="300" height="300">
  <circle cx="50" cy="50" r="10" fill="blue"/>
  <circle cx="100" cy="100" r="10" fill="red"/>
</svg>

The solution uses standard SVG transformations to translate the elements which got the drag behavior attached to them. It creates a new SVGTransform, appends it to the elements SVGTransformList, sets the translation's values to the DragEvents relative dx and dy coordinates and consolidates the transformation list for the sake of brevity.
This even circumvents the the jumps Mike Bostock mentioned in the second part of his answer, which are caused since the position of the element relative to the mouse pointer could not be inferred.

Obsolete: As the development of v4.0 evolves, the original answer is no longer valid. It was meant for versions 4.0.0-alpha.40 and below.
As Mike Bostock mentioned the handling of the drag's subject was changed by commit 8b25a53. The commit's comment states:

Simpler default subject.
Don't fallback to the originating element if the datum is undefined. If you want to use the originating element
  as the subject, make it explicit.

And, of course, you are free to "make it explicit" to get a solution for your problem. Because the drag's subject no longer defaults to the element if there is no data bound to it, you need to explicitely set the subject yourself by calling drag.subject(). If you want it to always refer to the element rather than to the data you could simply use a callback returning this.
d3
  .select("svg")
  .selectAll("circle")
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended)
    .subject(function(d) { return this; }))  // Explicitely set the subject to the element

Or, if you want it to default to any data bound and fallback to the element if no such data is available, you would be using:
d3
  .select("svg")
  .selectAll("circle")
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended)
    .subject(function(d) { return d == null ? this : d; }))

This is actually the same logic as it was before it got removed. Have a look at updated JSFiddle for a working example.


text:
Q: Behavior of SMS Notifications rite now i am trying to send SMS programmatically using following code , but i don't understand the behavior of SMS SENT Receiver.

1) for example if i send one SMS then Activity.RESULT_OK  inside
  registerReceiver is being called 3 times. and if i send 3 SMS using
  for loopby calling sendSMS then  Activity.RESULT_OK is being
  called 9 times. now i really don't know for one sms to send why this
  registerReceiver is being called so many times?
2) Moreover , when i run this code over emulator i passed emulator
  port to send SMS to other emulators which is natural but when i try to
  send SMS to a real number then i am not getting SMS delivery failure
  notification , as it notifies Activity.RESULT_OK only

code to send SMS
private void sendSMS(String phoneNumber, String message)
        {

            String SENT = "SMS_SENT";
            String DELIVERED = "SMS_DELIVERED";

            PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
                new Intent(SENT), 0);

            PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);
            Log.d("SMS Service", "SMS SEND CALLED");
            //---when the SMS has been sent---
            registerReceiver(new BroadcastReceiver(){
                @Override
                public void onReceive(Context arg0, Intent arg1) {

                    Log.d("SMS Service", "RECEIVE CALLED");
                    switch (getResultCode())
                    {
                        case Activity.RESULT_OK:
                            Toast.makeText(SMSService.this, "SMS sent",
                                    Toast.LENGTH_SHORT).show();
                            System.out.println("SMSService " + "SMS SENT");
                            break;
                        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                            Toast.makeText(SMSService.this, "Generic failure",
                                    Toast.LENGTH_SHORT).show();
                            System.out.println("SMSService " + "GENERIC FAILURE");
                            break;
                        case SmsManager.RESULT_ERROR_NO_SERVICE:
                            Toast.makeText(SMSService.this, "No service",
                                    Toast.LENGTH_SHORT).show();
                            System.out.println("SMSService " + "NO SERVICE");
                            break;
                        case SmsManager.RESULT_ERROR_NULL_PDU:
                            Toast.makeText(SMSService.this, "Null PDU",
                                    Toast.LENGTH_SHORT).show();
                            System.out.println("SMSService " + "Null PDU");
                            break;
                        case SmsManager.RESULT_ERROR_RADIO_OFF:
                            Toast.makeText(SMSService.this, "Radio off",
                                    Toast.LENGTH_SHORT).show();
                            System.out.println("SMSService " + "Radio Off");
                            break;

                    }
                }
            }, new IntentFilter(SENT));

            //---when the SMS has been delivered---
            registerReceiver(new BroadcastReceiver(){
                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    switch (getResultCode())
                    {
                        case Activity.RESULT_OK:
                            Toast.makeText(getBaseContext(), "SMS delivered",
                                    Toast.LENGTH_SHORT).show();
                            System.out.println("SMSService " + "SMS Delivered");
                            break;
                        case Activity.RESULT_CANCELED:
                            Toast.makeText(getBaseContext(), "SMS not delivered",
                                    Toast.LENGTH_SHORT).show();
                            System.out.println("SMSService " + "SMS not delivered");
                            break;
                    }
                }
            }, new IntentFilter(DELIVERED));

            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
        }

A: In general it depends on the size of message you are sending - if the message exceeds the single message limit (and in your case it sounds like it is about 3 times the single message limit) then you'll get a send and delivery report for each part of the message. Because you're not manually splitting the message you can't specify a different intent for each part.
It's worth taking a look at SmsManager.divideMessage() to split the message yourself and then at SmsManager.sendMultiPartTextMessage() to do the actual sending. This allows you to specify different pending intents for different parts of the message and so you can determine when the message has been finally sent.
I think the emulator is treating all message destinations as accurate and since there's no network to come back and say otherwise you probably won't get a failure to send from the emulator (unless you did something like put the emulator in airplane mode). From experience you certainly do get those error codes on a real device.
Edit:
Thinking about it you're also registering the receiver each time you send the message, the code I use has a manifest registered receiver. There's a possibility that you've registered it multiple times (it lives as long as the context you're registering against) which would give it to you multiple times - this would also make it repeat probably 9 times for 3 messages (assuming the registration for the 3rd time made it before the send was completed for the first) - possible but I don't know how likely. You can test relatively well by logging the object in the registered receiver.
This is a cut down version of the code I use to send sms messages, it doesn't get repeated responses for messages:
ArrayList<String> split = SmsManager.getDefault().divideMessage(message);
ArrayList<PendingIntent> success = new ArrayList<PendingIntent>(partInfo.length);
Intent sendInt = null;
for (int i = 0; i < partInfo.length; i++)
{
   sendInt = new Intent(context.getPackageName() + RELAY_INTERNAL_RESPONSE);
   sendInt.putExtra(KEY_MESSAGEID, messageID);
   sendInt.putExtra(KEY_PART_NUMBER, i);
   sendInt.putExtra(KEY_REPLY_SEND_INTENT, sendIntAction);
   sendInt.putExtra(KEY_NUMBER, number);
   PendingIntent sendResult = PendingIntent.getBroadcast(context, i, sendInt, PendingIntent.FLAG_ONE_SHOT); //You have to use an incrementing request code to ensure you don't just get the same pending intent.
   success.add(sendResult);
}
ArrayList<PendingIntent> receipt = new ArrayList<PendingIntent>(partInfo.length);
sendInt = new Intent(context.getPackageName() + RELAY_INTERNAL_RECEIPT);
sendInt.putExtra(KEY_MESSAGEID, messageID);
sendInt.putExtra(KEY_REPLY_RECEIPT_INTENT, receiptIntAction);
sendInt.putExtra(KEY_NUMBER, number);
PendingIntent sendResult = PendingIntent.getBroadcast(context, nextReceiptCounter(context), sendInt, PendingIntent.FLAG_ONE_SHOT);
for (int i = 0; i < partInfo.length; i++)
{
   receipt.add(sendResult);
}
SmsManager sm = SmsManager.getDefault();
sm.sendMultipartTextMessage(target, null, split, success, receipt);

And my receiver definition:
<receiver android:name="<package>.SMSBroadcastModule"
      android:enabled="true"
      android:exported="false">
      <intent-filter>
                <action android:name="<package>.RELAY_INTERNAL_RESPONSE" />
                <action android:name="<package>.RELAY_INTERNAL_RESPONSE_RECEIPT" />
      </intent-filter>
</receiver>

A: Or you can do a singleton Class for the register:
public class RegisterReceiverSingleton {
private static RegisterReceiverSingleton rrS;
public static final String SENT = "SMS_SENT";
public static final String DELIVERED = "SMS_DELIVERED";
private RegisterReceiverSingleton(final Context ctx){
    //when the SMS has been sent
            ctx.registerReceiver(new BroadcastReceiver(){
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        switch (getResultCode())
                        {
                            case Activity.RESULT_OK:
                                Toast.makeText(ctx, "SMS Enviado",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                                Toast.makeText(ctx, "Generic failure",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_NO_SERVICE:
                                Toast.makeText(ctx, "No service",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_NULL_PDU:
                                Toast.makeText(ctx, "Null PDU",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_RADIO_OFF:
                                Toast.makeText(ctx, "Radio off",
                                        Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                }, new IntentFilter(SENT));

            //when the SMS has been delivered
            ctx.registerReceiver(new BroadcastReceiver(){
                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    switch (getResultCode())
                    {
                        case Activity.RESULT_OK:
                            Toast.makeText(ctx, "SMS Entregado",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case Activity.RESULT_CANCELED:
                            Toast.makeText(ctx, "SMS No Entregado",
                                    Toast.LENGTH_SHORT).show();
                            break;
                    }
                }
            }, new IntentFilter(DELIVERED));
}

public static RegisterReceiverSingleton getInstance(final Context ctx){
    if(rrS==null){
        rrS = new RegisterReceiverSingleton(ctx);
    }
    return rrS;
}

}


text:
Q: Apply date filter multiple times In my angular application I'm calling a WCF REST service, which returns an array ob objects, where one of the property is of type DateTime, which gets serialized in JSON in such a form
[{"date":"\/Date(1295164800000-0800)\/",...
to display it nicely in my template I created a filter to convert that JSON representation into JavaScript Date object.
eventsApp.filter("fromMSDate", function(){
   return function (jsonDate) {
       var D, dtime, T, tz, off,
           dobj = jsonDate.match(/(\d+)|([+-])|(\d{4})/g);
       T = parseInt(dobj[0]);
       tz = dobj[1];
       off = dobj[2];
       if (off) {
           off = (parseInt(off.substring(0, 2), 10) * 3600000) +
               (parseInt(off.substring(2), 10) * 60000);
           if (tz == '-') off *= -1;
       }
       else off = 0;
       return new Date(T + off).toUTCString();
   }
});

I'm using it this way
            Date:
            {{event.date | fromMSDate}}

All works as needed, I do have a JS Date object shown in the page, but I don't like the format, so I tried to apply the 'date' filter but it had no success.
            Date:
            {{event.date | fromMSDate | date:'medium'}}

the date filter is ignored for some reason and the date is shown as Fri, 15 Mar 2013 00:00:00 GMT.
What am I doing wrong here?
Thx

A: Date.prototype.toUTCString returns date in a format ("Mon, 03 Jul 2006 21:44:38 GMT") which is not recognised by Angular's date filter.
From date filter docs:

[Param date:] Date to format either as Date object, milliseconds
  (string or number) or various ISO 8601 datetime string formats (e.g.
  yyyy-MM-ddTHH:mm:ss.SSSZ and its shorter versions like
  yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  specified in the string input, the time is considered to be in the
  local timezone.

So, to produce a format that date filter can understand use Date.prototype.toISOString which produces date in date filter compatible format ("2013-10-31T08:36:14.601Z").
app.controller('AppCtrl', function($scope){
  $scope.jsonDate = "\/Date(1295164800000-0800)\/";
});

app.filter("fromMSDate", function(){
 return function (jsonDate) {
   var D, dtime, T, tz, off,
   dobj = jsonDate.match(/(\d+)|([+-])|(\d{4})/g);
   T = parseInt(dobj[0]);
   tz = dobj[1];
   off = dobj[2];
   if (off) {
     off = (parseInt(off.substring(0, 2), 10) * 3600000) +
           (parseInt(off.substring(2), 10) * 60000);
     if (tz == '-') off *= -1;
   }
   else off = 0;
   return new Date(T + off).toISOString();
 }
});

date json: {{jsonDate}}

date fromMSDate: {{jsonDate | fromMSDate}}

date medium: {{jsonDate | fromMSDate | date:'medium'}}

date short: {{jsonDate | fromMSDate | date:'short'}}


text:
Q: How does openssl construct the derived key from password with PBKDF2? I'm working on a Java module to decrypt messages encrypted by openssl,
openssl aes-256-cbc -k *** -a -pbkdf2 -iter 1 -md sha256

but without success.
After some investigation, the problem was found that I can't get the correct KEY and IV from a given passphrase and the salt.
Here is the code:
$ openssl aes-256-cbc -k hi -a -S 4142434445464748 -md sha256 -pbkdf2 -iter 1 -P
salt=4142434445464748
key=187DC06E1AF1278348E5EFE761FDE3133DF42B03CF64E1B286E50E58238AEFB5
iv =1949A8BB58205A5C04BB28AD1947016C

$ echo hiABCDEFGH | hd
00000000  68 69 41 42 43 44 45 46  47 48 0a                 |hiABCDEFGH.|
0000000b

$ echo -n hiABCDEFGH | sha256sum
8c8a825dbab83fbe7fb58552e26bb98aa3af20e7e6294e04ae6422a86906606b  -

According to EVP_BytesToKey function,

Key Derivation Algorithm
The key and IV is derived by concatenating D_1, D_2, etc until enough data is available for the key and IV . D_i is defined as:
D_i = HASH^count(D_(i-1) || data || salt)
where || denotes concatentaion, D_0 is empty, HASH is the digest algorithm in use, HASH^1(data) is simply HASH (data), HASH^2(data) is HASH ( HASH (data)) and so on.

so, for a single iteration, the key should be:
KEY = SHA256(password || salt)

that is 8c8a825d... However, the result from openssl is 187DC06E...
So, how does openssl compute the derived key?

A: You used the "-pbkdf2" flag which means you are using the PBKDF2 a key derivation function (KDF) not the legacy KDF implemented EVP_BytesToKey.
PBKDF2 is defined in RFC 2898 here:
https://www.ietf.org/rfc/rfc2898.txt
The relevant OpenSSL function is documented here:
https://www.openssl.org/docs/man1.1.1/man3/PKCS5_PBKDF2_HMAC.html
The RFC above refers to a pseudo-random function (PRF). Since you have specified a digest of SHA256, the PRF used is HMAC-SHA256 with the password as the key.


text:
Q: Find Marginal CDF probability from PDF (2 random variables) Given the following PDF of continuous 2 random variables:
$$
f_{X,Y}(x,y)=\begin{cases}
       y^2 & 0\le y\le x\le 1;\newline
       0 & \text{otherwise}.
\end{cases}
$$
Graph showing the region of integration with x and y random variables:

Question is to find the marginal CDF $F_{Y}(y)$ and $P[Y > x]$
My attempt to find joint CDF: $F_{X,Y}(x,y)$
$$
\begin{alignedat}{0}
F_{X,Y}(x,y)&=\int_{-\infty}^{x}\int_{-\infty}^{x}y^2 dydx \newline
&=\int_{0}^{x}\int_{0}^{x}y^2 dy dx\newline
&=\int_{0}^{x}\frac{y^3}{3}\Bigg|_{0}^{x} dx=\int_{0}^{x}\frac{x^3}{3}dx\newline
&=\frac{x^4}{12}\Bigg|_{0}^{x}=\frac{x^4}{12}
\end{alignedat}
$$
And then to find marginal CDF of: $F_{Y}(y)=F_{X,Y}(x,y)$
$$
F_{Y}(y)=F_{X,Y}(\infty,y)=
$$
But where do I go from there? What does setting x to $\infty$ even mean?
And the question to find $P[Y>X]$, shouldn't it be 0 since $0\leq y\leq x\leq 1$?
UPDATE 12/17/2022
Based on @Xi'an's tip,
$$
\int_{0}^{1}\int_{0}^{1}cy^2dydx=1\\
\text{ implies } c = 3\\
$$
The original PDF must have been:
$$f_{X,Y}(x,y)=\begin{cases}
  3y^2 & 0\le y\le x\le1 \newline
   0   & otherwise
\end{cases}
$$
Find PDF between $0\le y\le x\le1$
$$
\begin{alignedat}{0}
F_{X,Y}(x,y)&=\int_{0}^{x}\int_{0}^{y}3y^2dy_0dx_0\\
&= y^3x
\end{alignedat}
$$
Therefore, the joint CDF is
$$
F_{X,Y}(x,y)=
\begin{cases}
0 & y\le0,x\le0,\\
y^3x & 0\le y\le x\le1,\\
1 & y\ge1, x\ge1.
\end{cases}
$$
How do I compute for other conditions, for example $y>=1, 0<=x<=1$
$$
F_{X,Y}(x,y)=\int_0^x\int_1^\infty 3y^2 dydx\\
$$
y goes to infinity?

A: Warning: The density $f_{X,Y}$ does not integrate to one (1). This error can be easily corrected and the proper multiplying constant $$c=1\Big/\iint y^2 \mathbb I_{0\le y\le x\le 1}\text dy\text dx$$ derived.
Hint: Writing
\begin{alignedat}{0}
F_{X,Y}(x,y)&=\int_{-\infty}^{x}\int_{-\infty}^{x} cy^2 \text dy\text dx
\end{alignedat}
is not correct, because the symbol $x$ takes two different meanings in this expression, namely upper bound value and integrand symbol. The upper bound $y$ is furthermore missing.
The correct entry is, for $x_0,y_0\ge 0$,
\begin{alignedat}{0}
F_{X,Y}(x_0,y_0)&=\int_{-\infty}^{x_0}\int_{-\infty}^{y_0} cy^2 \mathbb I_{0\le y\le x\le 1}\text dy\text dx\\
&= \int_{0}^{x_0\wedge 1}\left\{\int_{0}^{y_0\wedge x} cy^2 \text dy\right\}\text dx
\end{alignedat}
where $a\wedge b=\min\{a,b\}$. Once the computation of $F_{X,Y}(x,y)$ is correctly completed,
$$F_Y(y)=F_{X,Y}(1,y)$$
since $1$ is the maximal possible value of $X$.
Note: The same care must be taken when computing $P(Y>X)$ [if I assume there is a typo in the question about $P(Y>x)$].


text:
Q: Coda Slider stop on vimeo and youtube videos playback I am using the Coda Slider link to show the latest posts of embedded youtube and vimeo videos, but the slider continues on sliding when you press play on a video, how can i make the slider stop when a uses plays a video on the home page?
Thanks


text:
Q: Read from another process' output stream i wanted to read the output-stream of a c-Application in my Java program. iremoted (available here: Link) is a C-Application that puts out seperate lines like "0x19 pressed" if a button on my Apple Remote is pressed. If i start the iremoted program everything is doing well and these separate lines are shown on my screen everytime I pressed a button.
Now I wanted to read the output-stream of the c-application in my Java application to process inputs of the Apple Remote in Java projects.
Unfortunately i don't know why no input is regocnized?
I tried it with a simple HelloWorld.c program and my program responded as intended in this case (prints out  HelloWorld).
Why doensn't it work with the iremoted program?
public class RemoteListener {

public void listen(String command) throws IOException {

    String line;
    Process process = null;
    try {
        process = Runtime.getRuntime().exec(command);
    } catch (Exception e) {
        System.err.println("Could not execute program. Shut down now.");
        System.exit(-1);
    }

    Reader inStreamReader = new InputStreamReader(process.getInputStream());
    BufferedReader in = new BufferedReader(inStreamReader);

    System.out.println("Stream started");
    while((line = in.readLine()) != null) {
        System.out.println(line);
    }
    in.close();
    System.out.println("Stream Closed");
}

public static void main(String args[]) {
    RemoteListener r = new RemoteListener();
    try {
        r.listen("./iremoted"); /* not working... why?*/
        // r.listen("./HelloWorld"); /* working fine */
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

A: stdout is buffered and it's not automatically flushed if you are not writing to screen. Add:
fflush(stdout);

after:
printf("%#lx %s\n", (UInt32)event.elementCookie,
    (event.value == 0) ? "depressed" : "pressed");

A: iremoted is likely writing to stderr if a hello world program works.  You would want the error stream in that case.  I'm not sure how this works for your hello world case - I think you're doing the wrong thing here:
 new InputStreamReader(process.getInputStream());

should be
 new InputStreamReader(process.getOutputStream());

or
 new InputStreamReader(process.getErrorStream());


text:
Q: Should cl (windows visual studio compiler) work from any command prompt? I installed visual studio 2012 on my D drive since my C is full and was wondering if cl command should work from any command line or does it specifically have to be from the visual studio command line tool? I am wondering this because I am trying to build the boost library and in the bootstrap.bat file to do all the building for me is currently giving me an error saying the cl command isn't recognized.Clearly its not finding the cl.exe file in visual studios bin. I know adding an environmental variable ("PATH" variable) will fix my issue but should there already be a PATH variable?

A: There's always a PATH environment variable.  It however isn't preset to include the Visual Studio bin directories.  After all, you are normally running the compiler from the IDE, it takes care of setting up the environment correctly.  It is not the only variable that matters, the INCLUDE and LIB variables are very important as well.  Respectively to find .h and .lib files.
Programs on Windows in general avoid depending on the environment, it is very brittle since it is in effect a massive machine-wide global variable that any installer can screw up.  They often do.  True for most programs, not for the C++ tool chain since it still relies on the way it was done in the 1970s.  Nothing much has changed since then as far as building C and C++ programs go.
So, sure, you can run CL.EXE from any command prompt, you'll just spend a lot of time setting the environment correctly.  The provided Visual Studio Command Prompt shortcut just makes it fast, easy and avoids mistakes.
The Boost getting started web page is a bit of a tragedy.  But follow the recommendations, its says to use the Visual Studio Command Prompt if you want to build from the command line so of course that's what you ought to do.  How to build from the IDE is also described, just more ways to keep you out of trouble.


text:
Q: Oracle: are objects created by sys in a schema the same as objects created by that user? For example, are there any differences between:
SCOTT@ORCL> create index a_idx on a(x);

and
SYS@ORCL> create index scott.a.idx on scott.a(x);

A: Apart form all the DOs and DONTs about using SYS in this case is  that "if you connect as sysdba, your schema name will appear to be SYS".
Phil's answer demonstrates it. A nice quote by Thomas Kyte on a similar question -

In general, unless the documentation tells you, you will NEVER LOG IN
  as sys or system, they are our internal data dictionary accounts and
  not for your use. You will be best served by forgetting they exist.
sysdba and sysoper are ROLES - they are not users, not schemas. The
  SYSDBA role is like "root" on unix or "Administrator" on Windows. It
  sees all, can do all. Internally, if you connect as sysdba, your
  schema name will appear to be SYS.
In real life, you hardly EVER need sysdba - typically only during an
  upgrade or patch.

We keep saying the following so many times -

*

*Never ever use SYS (or SYSDBA) but for maintenance purpose (startup, shutdown, backup, recover)

*SYS/SYSDBA is special

*SYS/SYSDBA is Oracle proprietary (try to open a SR/TAR starting with "i did that with SYS/SYSDBA" and you'll see the immediate answer)

*SYS/SYSDBA does not act like any other user

*When you use SYS/SYSDBA Oracle deactivates some code path and activates others

*Whatever you do with SYS/SYSDBA will neither validate nor invalidate the same thing with any other user.

  NEVER EVER use SYS/SYSDBA for anything that can be done by another
  user.  Use SYS/SYSDBA ONLY for something that can't be done by someone
  else.

You might also like to read this.

A: I'll start my answer with this:
As a general rule: Never, ever, create objects as the user SYS/SYSTEM (or any other  "internal" Oracle user) unless directed to do so by Oracle support.
A simple test case shows that there's a big difference, due to ownership.
As SCOTT:
SQL> create table a ( b number );

Table created.

SQL> create index a_idx on scott.a ( b ) ;

Index created.

SQL> show user
USER is "SCOTT"
SQL> select owner from all_indexes where table_name = 'A';

OWNER
------------------------------
SCOTT

SQL> drop index a_idx;

Index dropped.

As SYS:
SQL> conn / as sysdba
Connected.
SQL> create index a_idx on scott.a ( b ) ;

Index created.

SQL> show user
USER is "SYS"
SQL> select owner from all_indexes where table_name = 'A';

OWNER
------------------------------
SYS

SQL>

This obviously causes problems due to ownership etc, as well as the data residing in a tablespace that you don't want user objects belonging in (from above example, because we didn't specify a TABLESPACE clause:
SQL> select owner, tablespace_name from all_indexes where table_name = 'A';

OWNER                          TABLESPACE_NAME
------------------------------ ------------------------------
SYS                            SYSTEM

SQL>


text:
Q: How to add a character in a string after each vowel using python 3 I'm trying to write a program that takes in a string(sentence) and after each vowel it adds a letter for example: "Jon" becomes "Jofon". I thought doing it with for loops maybe(certainly) there is a better way.
Here it's what I tried so far:
sen="Jon"
newString=""

for letter in sen:
    if letter == "a" or letter == "e" or letter == "i" or letter == "o" \
    or letter == "u" or letter == "y":
        newString+=letter+"f"+letter

print(newString)

It seems to add the letter "f" only to vowels leaving consonants out giving me this result:
 ofo

A: Of course, since there's no fallback for when it's not a vowel... You need an else:
for letter in sen:
    if letter in "aeiouy":
        newString+=letter+"f"+letter
    else:
        newString+=letter

(doesn't handle the case where the letters are uppercased BTW)
But there are more efficient (and pythonic ways) of doing it. Concatenating strings is underperformant, and this kind of problem is better solved using comprehensions or regular expressions.
In one line, using ternary and list comprehension, passed to "".join:
newstring = "".join(["{0}f{0}".format(letter) if letter.lower() in "aeiouy" else letter for letter in sen])

Alternative with regular expressions, capturing the vowel as a group and using it twice to wrap the f char against recalled group (\1) using raw prefix or \1 is interpreted as ASCII character \x01 instead:
re.sub("([aeiouy])",r"\1f\1","Jon",flags=re.IGNORECASE)

that finds a vowel, and replaces it by this vowel + f + this vowel again.


text:
Q: Collapse/Combine Date Ranges by Grouped Rows in R I have a dataframe that looks like this:
ID    Group    Start Date    End Date
1     A        2018-08-08    2018-08-09
1     A        2018-08-07    2018-08-08
1     A        2018-08-05    2018-08-07
1     B        2018-08-08    2018-08-09
1     B        2018-08-07    2018-08-08
2     A        2018-08-08    2018-08-09
2     A        2018-08-07    2018-08-08
2     A        2018-08-01    2018-08-07
2     B        2018-08-08    2018-08-09
2     B        2018-08-07    2018-08-08
3     B        2018-08-07    2018-08-08
4     B        2018-08-07    2018-08-08
4     B        2018-08-01    2018-08-07

And I'd like collapse it so that if the Start Date variable in one row matches the End Date variable in the next row, the rows are combined while grouping by the ID and Group variables:
ID    Group    Start Date    End Date
1     A        2018-08-05    2018-08-09
1     B        2018-08-07    2018-08-09
2     A        2018-08-01    2018-08-09
2     B        2018-08-07    2018-08-09
3     B        2018-08-07    2018-08-08
4     B        2018-08-01    2018-08-08

In dplyr, I know it's possible to do this through something similar to the following:
df %>%
group_by(ID, Group) %>%
rowwise() %>%
do(somefunction(x){})

But I need help in writing the function. Or if there's a for loop or other implementation that could accomplish this, it would be much appreciated.
Edit
I've modified the example data for more clarity.

A: I've found a more flexible solution using the IRanges package from BioConducter. This works well for cases which are not necessarily consecutive to their neighbors:
source("http://bioconductor.org/biocLite.R")
biocLite("IRanges")
require(IRanges)
library(data.table)
library(lubridate)

setDT(df)

df[, , as.data.table(reduce(
       IRanges(as.numeric(`Start Date`),
               as.numeric(`End Date`)),
               min.gapwidth=1L))[, lapply(.SD, as_date), .SDcols = -"width"],
                                 .(`ID`, `Group`)]

In the snippet above, I'm using the reduce function from IRanges on each of the date ranges, which collapses adjacent ranges within a given tolerance, min.gapwidth. In this case, I've specified date ranges to be combined if they're within one day of each other (min.gapwidth=1L). You can set this to 0L to combine strictly consecutive dates.
IRanges only takes numeric values, so I convert the dates to numeric and then I apply the as_date function from the lubridate package to convert them back to dates. I've also removed the width column which would tell me how many days are within each range.


text:
Q: Is it possible to call a dictionary value if the key is within the set key? (the dictionary keys are sets) Let's say "foo" and "bar" are equal to 1.
 my_dict = { ("foo", "bar") : 1 }
Is there a way to call my_dict["foo"] and get the value of 1 or is my only option to remake my input variable into the full set?
I couldn't figure out a way to just call the dictionary straight up, without first transforming the key into the set, and then I could call the dictionary.

A: Yes. You can look through the keys one by one
my_dict = { ("foo", "bar") : 1 }

def find_subkey(subkey):
    for key in my_dict:
        if subkey in key:
            return my_dict[key]
    raise ValueError("foo not found")

If you do this often, you can index the dictionary once and, assuming it doesn't change, use the index instead.
my_dict_index = {}
for k, v in my_dict.items():
    for sk in k:
        my_dict_index[sk] = v

print(my_dict_index["foo"])

If you have duplicate subkeys, this will only return one of them.


text:
Q: Default values of textarea missing after using ng-model i have an angular app in which i am using a textbox as follows:
    <div class="panel-body text-center">
        <textarea id="mytext" class="form-control" rows="4">John,2
    Jane,3
    John,4
    Jane,5
        </textarea>
    </div>

Here the values John,2...etc are loaded by default. However when i introduce an ng-model to access this data as follows, the default values do not show up anymore. What might be happening?
<textarea id="mytext" ng-model="mytextvalue" class="form-control" rows="4">

A: A cleaner way to go about it(using only angular):

On your controllers:

$scope.item = {'mytextvalue' : 'John,2 Jane,3 John,4 Jane,5'};

on your view:

<textarea ng-model="item.mytextvalue"></textarea>

Hope that helps!

A: From the docs:

ngModel will try to bind to the property given by evaluating the expression on the current scope. If the property doesn't already exist on this scope, it will be created implicitly and added to the scope.

So what's happening here with the following code:
<textarea ng-model="mytextvalue" >...</texarea>

When the ng-model directive is processed, it will look for a property mytextvalue on $scope.  When it doesn't find one, it will create an empty value and then proceed to assign that empty value to your element.
If you want to default the value, you'll have to explicicly specify a value for mytextvalue
You can do that in HTML with ng-init
ng-init="mytextvalue='John,2\nJane,3\nJohn,4\nJane,5'"

Or you can do it with JavaScript on your controller:
$scope.mytextvalue = 'John,2\nJane,3\nJohn,4\nJane,5';


text:
Q: How to redirect Hard Coded Urls to hard coded Urls without hitting errorAction? I have almost one thousand links which I want to redirect when a request is made specifically to those URLs. e.g
Redirect http://serverAddress/app/2017/06/09/8-20-taraweeh/ http://serverAddress/app/prayer/8-or-20-Rakat-for-Taraweeh

I am trying this code in .htaccess file but the problem is that when I enter the Url, instead of hitting the .htaccess code it first hits the Yii app and check if the Url exists, if not exists(definitely does not exist) it takes me to the error page.
Now I cannot define a rule because as you can see the URL after the app is changing, I cannot define a generic rule. So I have to hard code in my yii2 app.

Question:
How to Hard code Url redirections in yii2?

A: You could define a rule something similar:
'<year:\d+>/<month:\d+>/<day:\d+>/<title>' => 'site/redirect'

Then in your SiteController use can use redirect in the controller action:
public function redirectAction($year, $month, $day, $title) {
    $newUrl = ....  // compute new URL based on the parameters
    return $this->redirect($newUrl, 301);
}


text:
Q: Computing $\lim\limits_{n\to \infty}\frac1n\left((n+1)(n+2)...(n+n)\right)^{\frac1n}$ The question asks to find the following limit.
$$\lim_{n\to \infty}\left[\frac{\left((n+1)(n+2)...(n+n)\right)^{1/n}}{n}\right]$$
I tried taking $\log$ but I do not think that we get an L' Hopital form after that.
There is another approach that I tried. I rewrote the expression as
$$\lim_{n\to \infty}\left[\left(\frac{n+1}{n}\frac{n+2}{n}...\frac{n+n}{n}\right)^{1/n}\right]$$
If I take $\log$ now, won't the limit be 0? The answer in my book is $4/e$.

A: Take logarithm and you get a Riemann sum for
$$\ln(S)=\int_0^1\ln(1+x)dx$$
Which on evaluation yields
$$\ln(S)=2\ln(2)-1$$

A: Note that
$$\frac{\left((n+1)(n+2)...(n+n)\right)^{1/n}}{n}=\left[\frac{(2n)!}{ n^nn!}\right]^{\frac1n}=a_n^\frac1n$$
and by ratio-root criteria $$\frac{a_{n+1}}{a_n} \rightarrow L\implies a_n^{\frac{1}{n}} \rightarrow L$$
we have
$$\frac{a_{n+1}}{a_n}=\frac{(2n+2)!}{ (n+1)^{n+1}(n+1)!}\cdot \frac{n^nn!}{(2n)!}=\frac{(2n+2)(2n+1)}{(n+1)^2}\cdot\frac{1}{\left(1+\frac1n\right)^n}\to \frac4e$$
therefore
$$\lim_{n\to \infty}\left[\frac{\left((n+1)(n+2)...(n+n)\right)^{1/n}}{n}\right]=\frac4e$$

A: By Riemann sum we have $$\left[\left(\frac{n+1}{n}\frac{n+2}{n}...\frac{n+n}{n}\right)^{1/n}\right] =\exp\left[\frac{1}{n}\sum_{k=1}^{n}\ln\left(1+\frac{k}{n} \right)\right] \to \exp\left[\int_0^1 \ln\left(1+x\right)dx\right] \\= \exp\left[ 2\ln2 -1\right] =\color{red}{\frac{4}{e}} $$
since $$((x+1)\ln(x+1) -(x+1))' =\ln(x+1)$$

A: Yet another idea: take $\log$ and apply Stolz-Cesàro:
$$
\log L =
\lim_{n\to\infty}\frac{\log(n+1) + \cdots + \log(n+n) - n\log n}{n} = \cdots
$$


text:
Q: Date parsing and formating in Python 2.7 I'm looking to do what may seem like an easy task but I find it to be an awful nightmare in Python 2.7.
I have a date string such as Sat, 13 Dec 2014 13:52:00 -0500 to Dec 13 2014, 13:52 am EST
Any idea how I could achieve this, preferably without doing to much coding and logic implementation, but rather using a built in functionality or a popular 3rd party lib?
Note: my timezone is not EST.
The closest I've come to is:
import time
import email.utils

observationTime = email.utils.parsedate('Sat, 13 Dec 2014 13:52:00 -0500')
print time.strftime('%b %d %Y %H:%M %p %Z', observationTime)

But it produces:
Dec 13 2014 13:52 PM GMT Daylight Time

A: You could use dateutil to parse the date string into a timezone-aware datetime:
import dateutil.parser as DP
observationTime = DP.parse('Sat, 13 Dec 2014 13:52:00 -0500')
# datetime.datetime(2014, 12, 13, 13, 52, tzinfo=tzoffset(None, -18000))

Now, to print the timezone abbreviation EST requires that you convert the
timezone-aware datetime to the 'US/Eastern' timezone. This can be done using pytz.
This can not be done
automatically since there are other timezones, such as 'America/Bogota', which have the same utcoffset.
import pytz
eastern = pytz.timezone('US/Eastern')
observationTime = observationTime.astimezone(eastern)
print(observationTime.strftime('%b %d %Y %H:%M %p %Z'))
# Dec 13 2014 13:52 PM EST
print(observationTime.strftime('%b %d %Y %H:%M %z'))
# Dec 13 2014 13:52 -0500

bogota = pytz.timezone('America/Bogota')
observationTime = observationTime.astimezone(bogota)
print(observationTime.strftime('%b %d %Y %H:%M %p %Z'))
# Dec 13 2014 13:52 PM COT
print(observationTime.strftime('%b %d %Y %H:%M %z'))
# Dec 13 2014 13:52 -0500

(Note 13:52 is PM, not AM...)


text:
Q: Amazon account linking using firebase authentication Is there any option to implement amazon account linking using firebase,
We know we can implement account linking for google, facebook and twitter using firebase auth provider.
I am implementing account linking for google, twitter, facebook using firebase auth. The below code shows
firebase.auth.GoogleAuthProvider()
firebase.auth.FacebookAuthProvider()
firebase.auth.TwitterAuthProvider()

then i am getting result using
firebase.auth().signInWithRedirect(provider)
firebase.auth().getRedirectResult()

I want to link account using amazon login page.Is there any way to do it or please provide any suggestion to show amazon login page then user enter email and password i want to get user data

A: Firebase Authentication has no built-in provider for Amazon sign-in. That means that, to allow signing in to Firebase with Amazon accounts, you'll have to create a custom provider.
Linking custom provider accounts into existing accounts (from built-in providers) is not currently supported. But if you look at this Github thread, there's some good info on how to accomplish the same by using custom claims or another mechanism.


text:
Q: Setting metadata/header at GetObjectRequest at Amazon S3 Java v2 SDK I'm looking for an option for setting metadata header while calling getObject method. I would expect that GetObjectRequest would have metadata method, but it does not.
In the end, my goal is to download single file from zip using S3 Java v2 SDK from min.io. To do that, I would need to set x-minio-extract header with true value - https://blog.min.io/small-file-archives/. The issue is that I can't find out option to set that header.


text:
Q: Is $f:X\to X$, $f(x,y)=(2x,3y)$ continuous with $X=\mathbb{R}^2$ and the topology $\mathcal{T}=\{\text{Open disks centered at the origin}\}$
Is $f:X\to X$, $f(x,y)=(2x,3y)$ continuous with $X=\mathbb{R}^2$ and the topology $\mathcal{T}=\{\text{Open disks centered at the origin}\}\cup\{\emptyset\}\cup\{X\}$

So I want to prove this by showing the preimage of any open set is open.
Let $U\in \mathcal{T}$
then if $(x,y)\in f^{-1}(U)$
then $f(x,y)=(2x,3y)\in U$
then there exists an $\epsilon >0$ such that $B_{\epsilon}((2x,3y))\subseteq U$
Not sure how to continue from here. I want to show that there is a ball $B_r((x,y))$ such that if $(p,q)\in B_r((x,y))$ then $(p,q)\in B_\epsilon(f(x,y))$

A: Hint: Take any open disk in $(X,\mathcal{T})$ and compute its preimage under $f$. Is it again a disk?


text:
Q: Using Twitter's Bootstrap in Joomla 3 is it possible to use in xml structure of a form bootsraps input-prepend class in case of joomla 3? I mean I have the following xml structure
      <field name="subject" type="text"
        label="COM_UNIS_FIELDSET_SUBJECT_TITLE_LABEL"
        description="COM_UNIS_FIELDSET_SUBJECT_TITLE_DESC"
        class="inputbox"
        size="30"
    />

would be possible to use in this case the bootstrap class for input prepender

my-icon
<input class="span2" id="prependedInput" type="text" placeholder="subject">

A: It seems you have to look to: http://docs.joomla.org/Creating_a_custom_form_field_type. You could define a custom field by extending the Jform class:
<?php
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

jimport('joomla.form.formfield');

// The class name must always be the same as the filename (in camel case)
class JFormField<FieldName> extends JFormField {

        //The field class must know its own type through the variable $type.
        protected $type = '<FieldName>';

        public function getLabel() {
                // code that returns HTML that will be shown as the label
        }

        public function getInput() {
                // code that returns HTML that will be shown as the form field
        }
}

With the getInput() function you could return any html.
Or try to use jQuery to style your forms (eample):

    <input type="text" name="subject">


text:
Q: django can't save model choices selected values I want to save selected choice in model charfield
My models.py:
qobj = Model1.objects.all()

CHOICE = (
    (x.id, x.name) for x in qobj
)

class Model2(models.Model):
    choice_field = models.CharField(max_length=77, choices=CHOICE)

class Model2Form(ModelForm):
    class Meta:
        model = Model2
        fields = ['choice_field']

When I try to save model2 I got error:

"Select a valid choice. 5 is not one of the available choices.".

I was trying forms.ModelChoiceField but I can't get Model2.get_choice_field_display(), forms.ChoiceField and widget Select to work.
May be someone know how to solve this problem?

A: I think the problem is that you were defining choice_field as CharField, but your choices are using id as keys, which are integers. You need to change the choice_field to be models.IntegerField.
Also, sounds like your choice_field is based on another model's entries. Your way of populating data might not work because your CHOICES variable would get evaluated only once. You should use ForeignKey for choice_field instead:
class Model2(models.Model):
    choice_field = models.ForeignKey(Model1)

If you use django default way of rendering form, ForeignKey would be rendered as a dropdown just like choices, so you should definitely use that.


text:
Q: How do I modify my JSON object? Here is my JSFiddle
On click of "+" button bordered form elements are cloned and dynamically appended.
"Save Rules" button generates the JSON object of form field labels and values.
This is the JSON object being created on click of "Save Rules" button.
{
        "nameRules": "",
        "typeRules": "Type1",
        "descriptionRules": "XYZ\n                    ",
        "elhs": "",
        "op": "<=",
        "erhs": "",
        "datatype": "",
        "joinop0": "",
        "elhs0": "",
        "op0": "",
        "erhs0": "",
        "datatype0": ""
    }

How do I make it create the JSON object in the following format?
{
    "nameRules": "",
    "typeRules": "Type1",
    "descriptionRules": "XYZ\n                    ",
    "expressions": [{
                 "elhs": "",
                 "op": "<=",
                 "erhs": "",
                 "datatype": ""
                  },
                 {
                 "joinop0": "",
                 "elhs0": "",
                 "op0": "",
                 "erhs0": "",
                 "datatype0": ""
                 }]
}

Any help would be much appreciated.
Thank you

A: Hmm, code might not be pretty as I'm not expert in jquery, but it should work as expected: FIDDLE
  $('button.btn:contains("Save Rules")').on('click', function(e) {
  console.log('hhh', $('form.form-horizontal#rules').find(':input:not(button):not(#joinop)').get());
    var jsonData = $('form.form-horizontal#rules')
      .find(':input:not(button):not(#joinop)').get()
      .reduce(function(acc, ele) {
        acc.expressions = acc.expressions||[];
        if (ele.closest( "#container" ) || ele.closest('.parent-border')) {
          if (ele.closest('.parent-border')) var i = 0;
          else var i = $( "#container .child-border" ).index( ele.closest( ".child-border" )) +1
          acc.expressions[i] = acc.expressions[i]||{};
          acc.expressions[i][ele.name || ele.id] = ele.value;
        }
        else acc[ele.name || ele.id] = ele.value;
        return acc;
      }, {});
    console.log(jsonData);
    alert(JSON.stringify(jsonData, null, 4));
  });


text:
Q: Why does this process not execute whenever I type a discord command? In the following code it's a very simple discord bot which is supposed to start a loop when someone's message starts with ".loop". However with the command being typed the loop or the process does not start. What is the reasoning for this?
import discord
import random
import time
import multiprocessing
def boop():
  while True:
    time.sleep(1)
    print("I am looping.")

client = discord.Client()

@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
  if message.author == client.user:
    return
  if message.content.startswith(".loop"):
    if __name__ == '__main__':
      time.sleep(1)
      p1 = multiprocessing.Process(target=boop)
      p1.start()

client.run("bruh im not sharing token")


text:
Q: conditional expectation brownian motion $B=(B_t,t\in[0,1])$ a standard brownian motion on $[0,1]$.
For $t\in[0,1]$, we define $$\mathcal{F}_t=\sigma(B_s,s\in[0,t]),$$ $$\mathcal{G}_t=\mathcal{F}_t\,\vee\,\sigma(B_1).$$
How can we show $$\mathbb{E}[B_t-B_s|\mathcal{G}_s]=\frac{t-s}{1-s}(B_1-B_s)$$

A: (I'm changing your notations a bit, because I want to call $B$ a Brownian bridge.)
Fix $0<s\leq1$, and let $W$ be a standard Brownian motion indexed by $[0,1]$. I call the (law of the) random variable $u\in[0,s]\mapsto W_u-\frac usW_s$ a Brownian bridge of size $s$. It is but the Brownian motion modified to be $0$ at $s$, by subtracting a linear function.
I claim that the "superposition" of a Brownian bridge $B$ of size $s$ and a normal variable $N$ of variance $1$ is a Brownian motion on $[0,1]$: here, superposition means the process
$$u\mapsto B_u+uN\text.$$
One can prove this fact by noting that such a process is Gaussian, and has the desired finite dimensional covariances.
Now for what you're asking: the Brownian motion $W$ can be decomposed in for independent variables (see image below):

*

*two bridges $B$ and $B'$ of sizes $s$ and $1-s$;

*two Gaussian variables $N$ and $N'$ of variances $s$ and $1-s$.

(To prove this, I would go the other way around and show that given such random independent variables, the "superposition" is Gaussian and has the required covariance.)

Once this is done, we see that
$$\mathcal{G}_t = \sigma(N,N',B)$$
and so
$$
   \mathbb{E}[W_t-W_s|\mathcal{G}_s]
 = \mathbb{E}\left[B'_{t_s} + \frac{t-s}{1-s}N'\middle|\mathcal{G}_s\right]
 = \frac{t-s}{1-s}N'
 = \frac{t-s}{1-s}(B_{1-s}-B_s)\text.
$$


text:
Q: TSL2591 sensor value calculation I bought an TSL2591 breakout board and wanted to write driver for my board.
After looking at the documentation, i found that i cannot calculate the illuminance value (in Lux) as their was algorithm not given.
I tried the Adafruit TSL2591 Arduino code but no description.
I tried for App note on how to use the device or some physics description, Nothing.
I also tried Adafruit forum (no acceptable answer  ~2 days) and emailing AMS (no reply   ~ 2 days).
uint32_t Adafruit_TSL2591::calculateLux(uint16_t ch0, uint16_t ch1)
{
  uint16_t atime, again;
  float    cpl, lux1, lux2, lux;
  uint32_t chan0, chan1;

  // Check for overflow conditions first
  if ((ch0 == 0xFFFF) | (ch1 == 0xFFFF))
  {
    // Signal an overflow
    return 0;
  }

  // Note: This algorithm is based on preliminary coefficients
  // provided by AMS and may need to be updated in the future

  switch (_integration)
  {
    case TSL2591_INTEGRATIONTIME_100MS :
      atime = 100.0F;
      break;
    case TSL2591_INTEGRATIONTIME_200MS :
      atime = 200.0F;
      break;
    case TSL2591_INTEGRATIONTIME_300MS :
      atime = 300.0F;
      break;
    case TSL2591_INTEGRATIONTIME_400MS :
      atime = 400.0F;
      break;
    case TSL2591_INTEGRATIONTIME_500MS :
      atime = 500.0F;
      break;
    case TSL2591_INTEGRATIONTIME_600MS :
      atime = 600.0F;
      break;
    default: // 100ms
      atime = 100.0F;
      break;
  }

  switch (_gain)
  {
    case TSL2591_GAIN_LOW :
      again = 1.0F;
      break;
    case TSL2591_GAIN_MED :
      again = 25.0F;
      break;
    case TSL2591_GAIN_HIGH :
      again = 428.0F;
      break;
    case TSL2591_GAIN_MAX :
      again = 9876.0F;
      break;
    default:
      again = 1.0F;
      break;
  }

  // cpl = (ATIME * AGAIN) / DF
  cpl = (atime * again) / TSL2591_LUX_DF;

  lux1 = ( (float)ch0 - (TSL2591_LUX_COEFB * (float)ch1) ) / cpl;
  lux2 = ( ( TSL2591_LUX_COEFC * (float)ch0 ) - ( TSL2591_LUX_COEFD * (float)ch1 ) ) / cpl;

  // The highest value is the approximate lux equivalent
  lux = lux1 > lux2 ? lux1 : lux2;

  // Signal I2C had no errors
  return (uint32_t)lux;
}

query is:

*

*what is "cpl"

*why calculating cpl (though, related to above)

*what is "TSL2591_LUX_DF"

*what is "lux1", "lux2"    (is related to infrared? and visible?).

*why the comparision between "lux1", "lux2"

any pointers of algorithm or the actual physics behind the calculation would be helpful (i would love to read/know the physics behind the sensor).

A: This sensor has two integrating light sensors with different wavelength responses.  The purpose for this setup is to allow the sensor to simulate the spectral response of the human eye.  The first chart below is the human eye's response, the second is the response from the sensor datasheet.  The calculation at the end with the coefficients is to convert the sensor outputs to lux.  Lux is lumens per m^2, and a lumen is defined according to the response of the human eye.

cpl -
The general idea is that you set the gain for the input, then set the amount of time the sensor collects light. The longer time you select, the more light you will get.  Once this is complete this, you will have a certain number of ADC counts.  This has to be scaled by that gain and integration time. cpl appears to be that "counts per lux" scaling.
TSL2691_LUX_DF - This is hard to say for certain given the information, but it appears to simply be the default lux per count given a gain of 1 and an integration time of 1 ms.
If you want more info about the sensor, go to the AMS website and find white papers there.  They are under the sensors themselves.
For radiometric physics, the Georgia State University Hyperphysics resources are fantastic:  http://hyperphysics.phy-astr.gsu.edu/hbase/ligcon.html#c1


text:
Q: Core Data : No NSValueTransformer with class name XXX was found for attribute YYYY on entity ZZZZ I have my CoreData model set in a xcdatamodel file.
My attribute YYYY has a type transformable and I set the tranformer name in the Data model inspector.
I my case I was storing a [CLLocation] in my model.
class LocationArrayTransformer : NSValueTransformer {

    override func transformedValue(value: AnyObject?) -> AnyObject? {

        let locations = value as! [CLLocation]

        return NSKeyedArchiver.archivedDataWithRootObject(locations)
    }

    override func reverseTransformedValue(value: AnyObject?) -> AnyObject? {

        let data = value as! NSData

        return NSKeyedUnarchiver.unarchiveObjectWithData(data)
    }

}

That's my value transformer.
But somehow I'm still getting the warning in the console : No NSValueTransformer with class name XXX was found for attribute YYYY on entity ZZZZ
Any Idea why ?

A: I spent way to much time on this to not share the solution I found :
I had to make the NSValueTransformer subclass available to Objc.
@objc(LocationArrayTransformer)
class LocationArrayTransformer : NSValueTransformer {
 ....
}

Simple as that.

As @Sbooth points out, Swift classes are namespaced. Using @objc makes the class available without namespacing. So setting the transformer name as MyApp.Mytransformer works well too !


text:
Q: TypeError: an integer is required (got type str) - Python I'm trying to make a connection with an external websocket.
I copied the message my browser is sending to this websocket but unfortunately python is giving me this error.
I hope someone can figure it out..
from websocket import create_connection

link = "wss://sbapi.sbtech.com/bet777/sportscontent/sportsbook/v1/Websocket?jwt=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NjA4MTU3OTUsImlzcyI6ImFnZW50X0JldDc3NyIsIlNpdGVJZCI6NzIsIklzQW5vbnltb3VzIjp0cnVlLCJTZXNzaW9uSWQiOiI4NmJjNmMzOS0wMmNkLTQyZDctOTg5OC03MjBhZGFhYmM5OGEiLCJuYmYiOjE2NjA4MDg1OTUsImlhdCI6MTY2MDgwODU5NX0.f9T1bPsuMNYETXUhy-K9rmdmdQ_p2lQIvJmFGsveZ2H2DeA6_-tEE_83oFgDqVihuFHBdTe69rXir2rgoKjWcJxMR49cD7fixpWhJ0s4JFfc2VQIscNaVzGO-q7EAPZlWpYJe91WOXM-kcaPPtRYpcZkjcy7_D6vuEZKdlRGD5kA0TKt7DGSsA1dNgdZ1Hvw0JwDMxcNKJ9LFnJjz4v2mFMwozVL79T6mQSTQwR4HFiid4vH6STIzZ_dejxp86PDe68mj_e7Vko4eGX3vl9ihYyqUXeVePI0Yqac9fysiHCrrYJ2Cs4Z4_fCi1CrW3Ft2VIXQkJ_6Ls8vD9crmtreA&locale=nl"

message_to_send = {"jsonrpc": "2.0",
                   "params": {"eventState": "Mixed", "eventTypes": ["Fixture", "AggregateFixture"], "ids": ["40815"],
                              "regionIds": ["20"], "pagination": {"top": 100, "skip": 0}, "marketTypeRequests": [
                           {"sportIds": 1,
                            "marketTypeIds": ["1_39", "2_39", "3_39", "1_169", "1707", "1_0", "2_0", "3_0"],
                            "statement": "Include"}]}, "method": "GetEventsByLeagueId",
                   "meta": {"blockId": "eventsWrapper-Center_LeagueViewResponsiveBlock_17829"},
                   "id": "e0621fd8-e7b0-4458-8aaf-d4a83b6e90a9"}

ws = create_connection(link)
ws.send(message_to_send)
result = ws.recv()
print(result)
ws.close()

Is giving me TypeError: an integer is required (got type str)
Thanks a lot already for the effort!


text:
Q: Unable to print variable value inside string using Write-Output This is how my input string ($inputStr) looks like:
{
    "CloudId" : "67f8f457-1c4a-4622-a743-638318af04e3",
    "ComputerName" : "Computer1",
    "DeploymentErrorInfo" : {
        "IsConditionallyTerminating" : null,
        "MomAlertSeverity" : null,
        "DisplayableErrorCode" : null,
        "IsSuccess" : null,
        "DetailedCode" : null,
        "IsMomAlert" : null,
        "DetailedSource" : null,
        "CloudProblem" : null,
        "IsTerminating" : null,
        "DetailedErrorCode" : null,
        "ExceptionDetails" : null,
        "Code" : null,
        "ShowDetailedError" : null,
        "RecommendedActionCLI" : null,
        "ErrorCodeString" : null,
        "IsDeploymentBlocker" : null,
        "ErrorType" : null,
        "RecommendedAction" : null,
        "Problem" : null,
        "MessageParameters" : null
    },
    "GrantedToList" : [],
    "ID" : "00000000-0000-0000-0000-000000000000",
    "LocalAdminUserName" : "administrator",
    "Name" : "Computer1",
    "NewVirtualNetworkAdapterInput" : [],
    "OperatingSystemInstance" : {
        "Architecture" : null,
        "Edition" : null,
        "Description" : null,
        "Version" : null,
        "Name" : null,
        "OSType" : null,
        "ProductType" : null
    },
    "Owner" : {
        "UserName" : null,
        "RoleID" : null,
        "RoleName" : null
    },
    "StampId" : "23e6799c-33d4-45ea-8e4f-49ec7d5f26e0",
    "StartVM" : true,
    "VMNetworkAssignments" : [],
    "VMTemplateId" : "fdc73f71-1c6d-4e8f-9d02-21c7f4756c2d"
}

I am converting this to an object using ConvertFrom-Json command.
$paramObject = ConvertFrom-Json -InputObject $inputStr

I want it to print 'VM Computer1 is ready' but it does not work and it actually prints the whole string:
Write-Host "VM $paramObject.Name is ready" # prints the entire thing
Write-Host 'VM $paramObject.Name is ready' # prints command
Write-Host $paramObject.Name # prints VM Name so I know I am able to get the VM Name.

A: When using string interpolation, you need to use a sub-expression $(...) whenever you want to access a member of an object:
Write-Host "VM $($paramObject.Name) is ready"

Otherwise, PowerShell will treat the .Name part as just normal text.


text:
Q: JQuery Mobile on Symbian^1 device I want to use JQuery Mobile to create an html page.
As they told in their site, N97 can handle JQuery Mobile as B-grade. I have a 5530 XpressMusic smartphone, it has same CPU and RAM as N97 and both have Symbian^1.
But when I try to open my JQueryMobile simple html page from memory card, browser opens and then closes immediately... I mean, I can't have at least C-grade functionality of JQuery Mobile.
What is the problem? Why the mobile's default web browser closes? Why can't I have B-grade or at least C-grade experience of JQuery Mobile on my phone?
And how to solve this problem?
EDIT: another place on their website tells that my phone should get A-grade experience (here) - 5530 and N97 are both S60v5 phones... But what is the problem?!??
EDIT 2: I'm using the latest firmware version.

A: Nokia's browser is notoriously crap. Try Opera for Symbian.


text:
Q: How to update_index for haystack from a external script? I am using Django Haystack with ElasticSearch backend for my search page.
I am using MongoDB as my Database.
Everything was working fine in my search page.
PROBLEM
My web-application uses an external script for changing a field in the backend database using pymongo
My database has 2 fields (Files , Analysis).
The third party script runs and changes the Analysis field to True or False.
After the script has been run , when I search for the filename , it is showing me the updated Analysis in the results.
But when I search for the Analysis Field , (say I search for True/False ) It is not listing out this currently updated Analysis, though it has been updated.
For example
Search : filename
Result : filename True
Search : True
Result : No results found
It is working only after I update_index
WHAT I TRIED
So I figured out that I have to update_index. But I don't know how to update from an external python script.
I tried running
os.system("python /myapp/manage.py update_index")

I get the error
Unknown command: 'update_index'

When I checked for the management command available from the external script , it is not listing the haystack commands.
os.system("python /myapp/manage.py")

Available subcommands:

[auth]
    #Things under [auth]

[contenttypes]
    #Things under [contenttypes]

[django]
    #Things under [django]

[sessions]
    #Things under [sessions]

[staticfiles]
    #Things under [staticfiles]

No haystack subcommands are being shown here , contrary to what I run in the terminal.
If I run on the terminal
#other subcommands
[haystack]
    build_solr_schema
    clear_index
    haystack_info
    rebuild_index
    update_index

So I expect the result
Search :True
Results : filename True
How Do I achieve this ?
How do I update_index from an external script?
Any Other IDEAS ?

A: This is how you execute management command from within your code:
from django.core.management import call_command

call_command('update_index', *args, **options)  # args and opions are optional.

Read more in django docs: https://docs.djangoproject.com/en/dev/ref/django-admin/#running-management-commands-from-your-code

A: You can enable real time updating by adding this to settings.py:
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

It will as similar as ruinning update command, automatically trigger if any update in mapped indexes.
More details here:
http://django-haystack.readthedocs.io/en/v2.4.1/signal_processors.html#realtime-realtimesignalprocessor
Where the re-indexing is likely to take some time you should use a queue to prevent the request/response cycle being impeded, possible solutions such as celery are suggested here:
http://django-haystack.readthedocs.io/en/v2.4.1/other_apps.html#ref-other-apps

A: The most possible case is that you are trying to call command not from the virtual environment, where django is.
The answers below are right. But if you want to call command your way, you should run something like:
os.system("/path/to/your/venv/bin/python /myapp/manage.py")


text:
Q: Sorting in PostgreSQL with UTF-8 I have a funny sorting problem with a UTF-8 database in PostgreSQL 9.4
My DB settings are:
Collation   en_US.utf8
Character type  en_US.utf8
Encoding    UTF8

I create a simple table with one text column:
CREATE TABLE testtable
(
  testfield character varying(333) COLLATE pg_catalog."en_US.utf8"
);

I insert data:
insert into testtable values('bla,')
insert into testtable values('bla.')
insert into testtable values('bla f')
insert into testtable values('bla, f')
insert into testtable values('blaf.')

I select the data ordered:
select * from testtable order by testfield asc

I get this wrong order:
'bla,'     <--
'bla.'
'bla f'
'bla, f'   <--
'blaf.'

When I use:
select * from testtable order by convert_to(testfield, 'UTF-8') asc

It is right:
'bla f'
'bla,'     <--
'bla, f'   <--
'bla.'
'blaf.'

Does anybody know why?
Thanks.


text:
Q: Unable to run tests in Visual Studio I created a solution with 2 projects, FSharpCalled (which contains a method "disBonjour", transforming a string in another), an F# library,  and FSharpTest shown below :

Here's FSharpCalled :

The problem is that I can't run the tests; as shown in the first screenshot, I get an error message saying the "principal module is empty, so nothing will happen at execution".
I tried to modify some properties but without success.
EDIT:
here's the result... damn!

A: Classes
When you use a let binding inside of a class, the let binding is private (i.e. not publicly accessible). Therefore, you can't use it as a test method.
If you want to use NUnit with a class in F#, you'll have to adorn a method with the [<Test>] attribute:
[<TestFixture>]
type TestClass() =
    [<Test>]
    member this.SomeTest () =
        // Test goes here
        ()

Last time I used NUnit, you also had to add the [<TestFixture>] attribute to the class itself, so I added that as well. Normally, I don't use NUnit, so I don't know if it's still required.
Modules
You can also write your tests in modules, in which case you can adorn a let bound function with the [<Test>] attribute, since in that case it compiles to a public, static member:
module MyTests =
    [<Test>]
    let ``a function in a module that works as a test`` () =
        // Test goes here
        ()

At least, the test runner that I use (TestDriven.net) discovers and runs that test as well. I don't know if all other test runners will also do that.
For a general introduction to unit testing with F#, plus much more, you may consider watching my Pluralsight course called Unit Testing with F#.

A:
principal module is empty, so nothing will happen at execution

occurs when you have a console project without an [<EntryPoint>]. So you'd need to either declare such a main method or change the project to be a library project.
Update
Do you use any 3rd party test runner (TestDriven, ReSharper with nUnit integration, ...) or the nUnit VS Test Adapter? VS won't recognize nUnit tests out of the box.


text:
Q: Weird behavior of UpdatePanel with Session vs. ViewState Good morning,
This is much more of a WTF is going type question than anything else.
My application is using ViewState. I have placed a UpdatePanel on my app that is solely for testing purposes. All it does is hits my log table each second and generates a real time log console for me to see how the app is processing things.
This morning i decided to switch my use of ViewState to Session. Now my UpdatePanel no longer is running synchronously and "pauses" till the operation is done to update the UpdatePanel/Console.
Switching back to ViewState makes things run normally...
Also, the functions that my UpdatePanel is invoking has no relation to ViewState or SessionState and is not calling on either...
I have been able to reproduce this behavior in  small test sample:
TestUpdatePanelWithSession.Master
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="TestUpdatePanelWithSession.master.cs" Inherits="Tester2._0.TestUpdatePanelWithSession1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:Timer ID="Timer1" runat="server" Enabled="True" Interval="1000"></asp:Timer>
        <div>
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>
        </div>
        <asp:UpdatePanel ID="UpdatePanel1"
            UpdateMode="Always"
            runat="server">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
            </Triggers>
            <ContentTemplate>

                <%= System.DateTime.Now.ToString("mm:ss") %>

                    </div>
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

TestUpdatePanelWithSession.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/TestUpdatePanelWithSession.Master" AutoEventWireup="true" CodeBehind="TestUpdatePanelWithSession.aspx.cs" Inherits="Tester2._0.TestUpdatePanelWithSession" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
    <asp:Button ID="btnStartTest" runat="server" Text="Test" OnClick="btnStartTest_Click" />
</asp:Content>

TestUpdatePanelWithSession.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Tester2._0
{
    public partial class TestUpdatePanelWithSession : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Session["SomeIndex"] = 50000;
            }
        }

        protected void btnStartTest_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 1000000; i++)
            {
                System.Threading.Thread.Sleep(500);
                Session["SomeOtherIndex"] = i;

                lblTest.Text = ((int)Session["SomeIndex"] + (int)Session["SomeOtherIndex"]).ToString();
            }
        }
    }
}

The above code works fine if you change all the Session to ViewState. What the heck is going on??
Thanks in advance for the lesson...

A: After testing the example it's clear that the problem comes from the readwrite lock from the session.
Removing the session use from the Page_Load avoids this behavior, but that's a bit strange as the code is not being hit when the updatepanel calls the page. Even moving the code to other function, calling it on another thread or using a task does not prevent this behavior.
It seems that ASP .net is analyzing the code and when there is code using the session, even if it's not executed, it blocks the session what prevents the normal execution of the callbacks. Leaving only session manipulation on control events seems to work fine.
Only solution to this for what I have tested is to remove the Page_Load session manipulation, what in some scenarios can be unavoidable.


text:
Q: Transitioning namespaces/module containers with the same name causes a conflict I'm trying to transition some code that was namespaced incorrectly into it's own namespace without losing current functionality (during the transition).
Original Code:
// (org)
module General.Admin.Dialogs {
  export class LoginDialog {
    // details
  }
}

After final transition:
// (new)
namespace Admin {
  export module Dialogs{
    export class Login {
    }
  }
}

However I need to keep some of the current functionality working by aliasing the objects in one namespace/module, however the compiler (TypeScript 2.3) isn't happy because of the naming collision (it assumes because I haven't specified the root namespace, it uses the current root namespace:
namespace Admin {
  export module Dialogs{
    export class Login {
    }
  }
}

module General.Admin.Dialogs {
  export var LoginDialog = Admin.Dialogs.Login;
}

Admin.Dialogs.Login  is assumed by the compiler to be in General (old) module/namespace and not the Admin.Dialogs (new) declared above.  Is there some magic I could use to get this working?

A: I actually solved it while writing the Quesiton, but I thought there may be other better ways or this might help someone else who is having the same difficultly so here is my answer.  Since I have to touch this file again when the transition is done, I just added another intermediate module to resolve the naming conflict (hacky, but the intermediate module will be delete too so no big deal).
namespace Admin {
  export module Dialogs{
    export class Login {
    }
  }
}

module AdminTransition {
  export var LoginDialog = Admin.Dialogs.Login
}

module General.Admin.Dialogs {
  export var LoginDialog = AdminTransition.LoginDialog;
}


text:
Q: How you do you create a bash script that will run automatically when Unity startups as a user instead of root? I have a shell script that is being run automatically under ~/.config/autostart/mining.desktop
I have it setup so that the script runs after Unity is loaded.
It seems to work at startup but if i close the bash window, the process continues to run in the bg as root. How do I setup my desktop file so that the mining script closes as soon as I close the bash window?
My desktop file is:
[Desktop Entry]
   Exec=gnome-terminal --command "/user/local/claymore/mine.sh"
   Hidden=false
   NoDisplay=false
   X-GNOME-Autostart-enabled=true

"Top" reports the ethdcrimer is running as user root.

A: To make this happen use the cron tool to create a cron job for particular user:

*

*Run:
crontab -u <useranme> -e

*Then add this line or similar based on your code:
@reboot /user/local/claymore/mine.sh > /dev/null 2>&1


text:
Q: Overlap graphs with figurefactory I am trying to plot some finance graphs and I used the plotly libraries for it.
I am quite new to this, so had to look for a way to do it, and wanted to do it offline, so I found this way:
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
from pandas_datareader import data as web
import datetime
import fix_yahoo_finance as yf
import plotly
from plotly import figure_factory as ff
import os

yf.pdr_override()

class Stock:
    #We need a constructor to get all the data when we create the class
    def __init__(self, name): #This needs a string as argument to work
        self.name = name
        #If we already have the sotcks data we don't download it again
        if os.path.exists('stock_prices_yahoo/' + name + '.csv'):
            self.df = pd.read_csv('stock_prices_yahoo/' + name + '.csv')
        else:
            start_date = '1950-01-01'
            end_date = datetime.date.today()
            df = web.get_data_yahoo(name, start_date, end_date)
            df.to_csv('stock_prices_yahoo/' + name + '.csv')

    def plot_stock(self): #This will print a plot of the stock prices
        fig = ff.create_candlestick(self.df.Open, self.df.High, self.df.Low, self.df.Close, dates = self.df.Date)
        fig['layout'].update({
        'title': self.name + ' prices',
        'yaxis': {'title': 'Price'},
        'xaxis': {'title': 'Date'},
        })
        plotly.offline.plot(fig, filename = self.name + '-candlestick.html', validate = True)
AAPL = Stock('AAPL')
AAPL.plot_stock()

The point is I want to overlap some moving averages on it, and, after looking for it around the whole internet, peaple always do it via matplotlib.
Is there any way to do it with figure_factory?


text:
Q: Developing Higher Rank Weapons Having started to higher rank weapons and armor, I'm looking to upgrade my arsenal. I've got a few rank 2 weapons researched and ready to develop (e.g. the Pathfinder Observer II), but when I try to develop them, the game insists on developing the rank 1 version instead.
Pathfinder Observer II, ready to craft:

Hitting "CRAFT":

If I confirm the choice, the game really does craft the Observer I. I've developed one myself already, and also received one from the Deluxe version of the game. Both are sitting in my inventory, but I'd like a rank 2... Am I doing something wrong, or is this a bug in the game? (This is on the PC, if relevant.)
I've tried renaming the project to "Pathfinder Observer II" in case that did anything, but no dice. It creates an Observer I, called "Pathfinder Observer II".
I'm tempted to call this a bug, because if I craft the weapon as shown above, I get one with a rather useless clip size and max ammo:

If this is indeed a bug, and anyone's encountered this — is there a way around it? Or am I stuck with whatever weapons I can find?

Edit: Seems like this only affects the Pathfinder weapons. I'm able to craft higher-rank weapons and armors, just not the Pathfinder weapons. I've tried doing this both on the Tempest and at the research center on Prodromos, but no luck.

A: After some further searching online, looks like this may indeed be a bug. For some it appears that crafting a higher rank weapon produces the weapon with the wrong name but right stats, but not always. Seems to happen on PC, Xbox, and PS4. Hopefully it'll get fixed soon.


text: Q: Method Illuminate\Database\Eloquent\Collection::getConnectionName does not exist where comes from this bugg  ?  after having done a php artisan route:list showing that a 'navbar.index' route exists, I try to use it in a <a href= '{{route('navbar.index'}}> but I have the following error