text:
Q: How to make an XML-RCP request through Fiddler? I am using Fiddler to troubleshoot an XMLRCP connection to MiniBlog. Here is the MiniBlog Api: http://bigfont-miniblog.azurewebsites.net/metaweblog. How would I request for the blogger.getUsersBlogs FROM Fiddler? Here is my initial attempt:

A: If you're really troubleshooting a connection to the service in question, you should use Fiddler to capture the request from the client to the server. If you then wish to play around with modifications to that request, drag/drop the Session from the Web Sessions list to the Composer tab and modify to your liking.
It's pretty likely that you need to use a POST request whose body contains one or more parameters, including a username parameter specifying which user's list to return.


text:
Q: Html/php email send I am about to write a little html/php script. But I am not able to send data from the HTML form input to any email address or into any text file. I was already searching for possible solutions but nothing worked for me. The Browser replayed the php script. But no mail has been send. Any help will be appreciated. Thank you.

A: I recommend you use PHPMailer his use is very easy

A: I think your issue is how to handle form data with some code, so you may be able to send an email or write form data to a file. This is where you see the difference between client-side and server-side. HTML is a language to describe documents, here your form: the text input name is going to describe a name, the form will send its data within the POST method, and so on. The file describing HTML is processed in your browser. And your browser don't send an email or write data... That's why you should use a server-side language such as PHP to get things done. PHP is great to help you process data and behave on different event... In your case, great for receiving data, analyze data and then send data through mails or save data into a file.
So now you may want to understand how to do so... Mail are a little tricky since you may need to configure things such as mail server, authentification and so one. Maybe a good solution is to try mails with a Google account or something like that... When it will be done, you may simply send an email like so:
<?php

$to      = 'your@email.here';
$subject = 'Mail test';
$data    = $_POST['name']; // if a `name` field exist and your form send its data through POST method
mail($to, $subject, $data);

Writing things to a file is simpler, it only request permissions to read and/or write a file.
<?php

$file = 'path/to/file';
file_put_contents($file, $_POST['name'] . ' for example');

So this is globally everything:
index.html HTML file:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Form</title>
    </head>
    <body>
        <form action="process.php" method="post">
            <input name="name" type="text" placeholder="Name" />
            <input type="submit" value="Process">
        </form>
    </body>
</html>

and process.php PHP file
<?php

/**
 * Testing data
 */

if (!isset($_POST['name'])) {
    die('No value `name` found');
}

/**
 * Configuring process
 */

$to      = 'your@email.here';
$subject = 'Mail test';
$data    = $_POST['name'];

/**
 * Saving data
 */

$res = file_put_contents(
    'data.txt',
    $data."\r\n"
);

if ($res !== false) {
    echo 'data saved'.PHP_EOL;
} else {
    echo 'error while saving data'.PHP_EOL;
}

/**
 * Sending email
 */

$res = mail(
    $to,
    $subject,
    $data
);

if ($res === true) {
    echo 'mail sent';
} else {
    echo 'error while sending mail'.PHP_EOL;
}

I suggest you to read mail() and file_put_contents() documentations to understand their behavior in case there are errors... :)

A: Do not forget the action and method attributes in the <form> tag.
contents of html file
<form action="send.php" method="POST">
    <input type="text" name="name" placeholder="Typ your name..." />
    <input type="email" name="from" placeholder="Typ your e-mailaddress..." />
    <textarea name="message" placeholder="Typ your message..."></textarea>
    <button type="submit">Send E-mail</button>
</form>

contents of send.php
<?
if(isset($_POST)) {
    $name = $_POST['name'];
    $message = $_POST['message'];
    $from = $_POSST['from'];

    if(!empty($name) && !empty($message) {
        $subject = 'message from '.$name;

        $headers = "From: " . strip_tags($from) . "\r\n";
        $headers .= "Reply-To: ". strip_tags($from) . "\r\n";
        //$headers .= "CC: susan@example.com\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

        // @SEE: http://php.net/manual/en/function.mail.php
        if(mail('[YOUR-ADDRESS]', $subject, $message, $headers)) {
            echo 'Thx 4 msg!';
        }
        else {
            echo 'Oh nooos, The msg was not send.';
        }
    }
    else {
        echo 'You should provide the fields with some data..';
    }
}
?>

One should first sanitize the user input obviously.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ggplot: two lines on one graph with breaks in date (y-axis) Okay so this is a bit of a follow up question to this:
How to format date on x-axis to month and year in R
I know there are a lot of questions about plotting two lines on one graph, but I can't seem to make one work with my data. I have data from May-Nov for 11 years. I am trying to plot data for two zones on the same graph while still showing the breaks/gaps in months for each year.
I can get it to plot both lines, however this makes it look like I have data for all 12 months and does not show the gaps.
using this code:

ggplot(Rainmean, aes(x= Date , y= mean_rain, group = Zone, color = Zone))+
  geom_line()+
  geom_point()+
  labs(title = "Average Monthly Rainfall", y = "Rainfall (in)", x = "Date") +
  theme_bw() +
  theme(panel.border = element_blank(), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
        axis.text.x = element_text(angle = 0)) +
  scale_x_date(date_breaks = '1 year', date_labels = "%Y")

I get this:

Using the same code and adding in group= year(Date) to try and break up the y axis using this code:
ggplot(Rainmean, aes(x= Date , y= mean_rain, group = year(Date), group = Zone, color = Zone))+
  geom_line()+
  geom_point()+
  labs(title = "Average Monthly Rainfall", y = "Rainfall (in)", x = "Date") +
  theme_bw() +
  theme(panel.border = element_blank(), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
        axis.text.x = element_text(angle = 0)) +
  scale_x_date(date_breaks = '1 year', date_labels = "%Y")

this one is a bit closer, but it looks like it is just merging the lines for my zones instead of showing two distinct lines.

So just to be clear, I am trying to take these two plots and merge them into one figure with two lines.. one for zone B and one for zone D.

I have this data:
structure(list(Date = structure(c(14000, 14000, 14031, 14031,
14061, 14061, 14092, 14092, 14123, 14123, 14153, 14153, 14184,
14184, 14365, 14365, 14396, 14396, 14426, 14426, 14457, 14457,
14488, 14488, 14518, 14518, 14549, 14549, 14730, 14730, 14761,
14761, 14791, 14791, 14822, 14822, 14853, 14853, 14883, 14883,
14914, 14914, 15095, 15095, 15126, 15126, 15156, 15156, 15187,
15187, 15218, 15218, 15248, 15248, 15279, 15279, 15461, 15461,
15492, 15492, 15522, 15522, 15553, 15553, 15584, 15584, 15614,
15614, 15645, 15645, 15826, 15826, 15857, 15857, 15887, 15887,
15918, 15918, 15949, 15949, 15979, 15979, 16010, 16010, 16191,
16191, 16222, 16222, 16252, 16252, 16283, 16283, 16314, 16314,
16344, 16344, 16375, 16375, 16556, 16556, 16587, 16587, 16617,
16617, 16648, 16648, 16679, 16679, 16709, 16709, 16740, 16740,
16953, 16953, 16983, 16983, 17014, 17014, 17045, 17045, 17075,
17075, 17106, 17106, 17318, 17318, 17348, 17348, 17379, 17379,
17410, 17410, 17440, 17440, 17471, 17471, 17683, 17683, 17713,
17713, 17744, 17744, 17775, 17775, 17805, 17805, 17836, 17836
), class = "Date"), Zone = structure(c(1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("B",
"D"), class = "factor"), mean_rain = c(0.0287096774193548, 0.0464516129032258,
0.182333333333333, 0.206333333333333, 0.175806451612903, 0.112258064516129,
0.529354838709677, 0.431612903225806, 0.0463333333333333, 0.104333333333333,
0.077741935483871, 0.0570967741935484, 0.0816666666666667, 0.0483333333333333,
0.143225806451613, 0.143225806451613, 0.126666666666667, 0.219,
0.197741935483871, 0.253548387096774, 0.221290322580645, 0.231290322580645,
0.254, 0.105, 0.0609677419354839, 0.0629032258064516, 0.0556666666666667,
0.0573333333333333, 0.16258064516129, 0.211935483870968, 0.213666666666667,
0.297333333333333, 0.106129032258065, 0.18, 0.180967741935484,
0.252903225806452, 0.162333333333333, 0.104666666666667, 0.00548387096774194,
0.00483870967741936, 0.0316666666666667, 0.051, 0.0196774193548387,
0.0167741935483871, 0.300666666666667, 0.0813333333333333, 0.160967741935484,
0.12, 0.111612903225806, 0.10741935483871, 0.180666666666667,
0.171, 0.0793548387096774, 0.087741935483871, 0.0383333333333333,
0.0803333333333333, 0.271935483870968, 0.31258064516129, 0.579333333333333,
0.754, 0.369677419354839, 0.351612903225806, 0.344193548387097,
0.368064516129032, 0.136666666666667, 0.233666666666667, 0.08,
0.082258064516129, 0.008, 0.00766666666666667, 0.0774193548387097,
0.05, 0.315333333333333, 0.277, 0.41258064516129, 0.49, 0.4,
0.364193548387097, 0.140666666666667, 0.120666666666667, 0.0190322580645161,
0.0158064516129032, 0.15, 0.137333333333333, 0.224516129032258,
0.294838709677419, 0.113666666666667, 0.189, 0.119677419354839,
0.105483870967742, 0.234193548387097, 0.205806451612903, 0.421666666666667,
0.262, 0.0370967741935484, 0.0338709677419355, 0.127, 0.0933333333333333,
0.118064516129032, 0.151612903225806, 0.127333333333333, 0.237666666666667,
0.233548387096774, 0.325161290322581, 0.203548387096774, 0.255161290322581,
0.118333333333333, 0.132, 0.150967741935484, 0.0667741935483871,
0.114333333333333, 0.0746666666666667, 0.207333333333333, 0.153666666666667,
0.121935483870968, 0.2, 0.360645161290323, 0.543548387096774,
0.220666666666667, 0.258333333333333, 0.105161290322581, 0.00258064516129032,
0.00333333333333333, 0.00166666666666667, 0.328666666666667,
0.345666666666667, 0.0787096774193548, 0.249677419354839, 0.211612903225806,
0.179677419354839, 0.169666666666667, 0.135333333333333, 0.0796774193548387,
0.0441935483870968, 0.0343333333333333, 0.0603333333333333, 0.338333333333333,
0.223, 0.311612903225806, 0.350645161290323, 0.491935483870968,
0.239032258064516, 0.083, 0.088, 0.107741935483871, 0.105161290322581,
0.215, 0.131666666666667)), row.names = c(NA, -148L), class = c("tbl_df",
"tbl", "data.frame"))

Can anyone help point me in the right direction for this?

A: You could achieve your desired result by mapping the interaction of year(Date) and Zone on group:
library(ggplot2)
library(lubridate)

ggplot(Rainmean, aes(x= Date , y= mean_rain, group = interaction(lubridate::year(Date), Zone), color = Zone))+
  geom_line()+
  geom_point()+
  labs(title = "Average Monthly Rainfall", y = "Rainfall (in)", x = "Date") +
  theme_bw() +
  theme(panel.border = element_blank(), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
        axis.text.x = element_text(angle = 0)) +
  scale_x_date(date_breaks = '1 year', date_labels = "%Y")


text:
Q: Convert sparse matrix (csc_matrix) to pandas dataframe I want to convert this matrix into a pandas dataframe.
csc_matrix
The first number in the bracket should be the index, the second number being columns and the number in the end being the data.
I want to do this to do feature selection in text analysis, the first number represents the document, the second being the feature of word and the last number being the TFIDF score.
Getting a dataframe helps me to transform the text analysis problem into data analysis.

A: from scipy.sparse import csc_matrix

csc = csc_matrix(np.array(
    [[0, 0, 4, 0, 0, 0],
     [1, 0, 0, 0, 2, 0],
     [2, 0, 0, 1, 0, 0],
     [0, 0, 0, 0, 0, 1],
     [4, 0, 3, 2, 0, 0]]))

# Return a Coordinate (coo) representation of the Compresses-Sparse-Column (csc) matrix.
coo = csc.tocoo(copy=False)

# Access `row`, `col` and `data` properties of coo matrix.
>>> pd.DataFrame({'index': coo.row, 'col': coo.col, 'data': coo.data}
                 )[['index', 'col', 'data']].sort_values(['index', 'col']
                 ).reset_index(drop=True)
   index  col  data
0      0    2     4
1      1    0     1
2      1    4     2
3      2    0     2
4      2    3     1
5      3    5     1
6      4    0     4
7      4    2     3
8      4    3     2


text:
Q: What is the suggested method of playing video indefinitely in a browser? (for weeks or months a time) I'm working on a system with few devices and screens that should be able to run indefinitely, or at least 2-3 days. One of those is a promotional screen that runs in a fullscreen browser and has some text and a video playlist that should loop forever.
Currently I'm using jquery jPlayer as my playlist video solution and I'm having a problem that it crashes after longer period of time. I'm not quite sure how to test it, but I left it running over the weekend just to find it not loaded today.
So my question is:

*

*Which solution would be best for a video playlist that has to loop forever?

A: So here's the code that worked
<video id="videoPlayer" src="../../Content/data/video_01.m4v" style="width: 1280px; height: 720px;" autoplay controls />

<script type="text/javascript">
  var videoArray = [ "../../Content/data/video_01.m4v",  "../../Content/data/video_02.m4v", "../../Content/data/video_03.m4v" ];
  var videoPlayer = document.getElementById('videoPlayer');
  var videoIndex = 0;

  videoPlayer.onended = function () {
    videoIndex++;

    if (videoIndex >= videoArray.length) {
        videoIndex = 0;
    }

    videoPlayer.src = videoArray[videoIndex];
  }

</script>

Note: It crashes after +/- 14hours on Opera on a Sony TV, but works perfectly on a PC that runs Chrome in fullscreen (which I'll have running on site).
EDIT 1:
Also added at the end of the script in case a video fails to load (which happened once).
  videoPlayer.addEventListener('error', function (err) {
      err.preventDefault();
      videoPlayer.onended();
  });

EDIT 2:
this last part (adding eventlistener on error) is the key for everything. Apparently when it crashed it crashed only because it couldn't load a video and stoped. So I'd suggest having this.


text:
Q: Show progress while loading FXML file JavaFX application has a tree menu and clicking on a menu item loads an fxml file  image attached
Some of the FXMLs are nested and are taking up to 2-3 seconds to load. I would like to show a progress indicator while FXMLs are getting loaded and initialized. Controller's initialization code can be executed as a Task and bind it's progress to a progress bar control, but the problem is that some of code needs to be executed in FX Application thread using Platform.runLater(). If I do that, there is no way to know when the initialization is completed.
Is there a way to handle this seemingly simple task ?
I cannot share the controller code which is taking long time to load, but for the purpose of this question, please assume the following initialization code is the culprit. I cannot execute this block of code in a Task thread as UI changes cannot be made from threads other than JavaFX Application thread. If I wrap the part of code that changes UI inside Platform.runLater(), task may finish it's execution even before the UI changes are completed.
public void initialize(URL url, ResourceBundle rb) {
    if (webEngine == null) {
        webEngine = helpView.getEngine();
    }
    try {
        Path filepath = Paths.get("docs/index.html");
        webEngine.load(filepath.toUri().toString());

    } catch (Exception ex) {
        Alert alert = new Alert(Alert.AlertType.WARNING, "Failed to read doc files", ButtonType.OK);
        alert.show();
    }
}

Raj


text:
Q: Recording video with AVCaptureSession I'm trying to record a video using AVCaptureSession and AVCaptureMovieFileOutput but whenever I try to start recording I get this error in the didFinishRecordingToOutputFileAtURL AVCaptureFileOutputRecordingDelegate method.
Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo=0x15de7c40 {AVErrorRecordingSuccessfullyFinishedKey=false, NSLocalizedDescription=The operation could not be completed, NSLocalizedFailureReason=An unknown error occurred (-12673), NSUnderlyingError=0x15d88aa0 "The operation couldn't be completed. (OSStatus error -12673.)"}

This is the code I'm using to add the AVCaptureMovieFileOutput and initialise my AVCaptureSession
- (AVCaptureSession *)session {
    if (!_session) {
        _session = [[AVCaptureSession alloc] init];

        // ADD CAMERA DEVICE
        NSError *error = nil;
        AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:self.videoDevice error:&error];
        if (!videoInput) {
            NSLog(@"ERROR: trying to open camera: %@", error);
        } else {
            [_session addInput:videoInput];
        }

        // ADD AUDIO DEVICE
        error = nil;
        AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:self.audioDevice error:&error];
        if (!audioInput)
        {
            NSLog(@"ERROR: trying to open mic: %@", error);
        } else {
            [_session addInput:audioInput];
        }

        // ADD OUTPUT FILE
        if ([_session canAddOutput:self.movieFileOutput]) {
            [_session addOutput:self.movieFileOutput];
        }

        [_session startRunning];
    }

    return _session;
}

My AVCaptureMovieFileOutput is lazy loaded like this
- (AVCaptureMovieFileOutput *)movieFileOutput {
    if (!_movieFileOutput) {
        _movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];

        Float64 TotalSeconds = 60;          //Total seconds
        int32_t preferredTimeScale = 30;    //Frames per second
        CMTime maxDuration = CMTimeMakeWithSeconds(TotalSeconds, preferredTimeScale);
        _movieFileOutput.maxRecordedDuration = maxDuration;
        _movieFileOutput.minFreeDiskSpaceLimit = 1024 * 1024;
    }

    return _movieFileOutput;
}

I'm not sure what I'm doing wrong as most of the tutorials I've seen do it this way.
Thanks

A: Underlying error code is -12673, which is usually caused by attempt to write into unwritable directory or file. Try to write using this code:
NSString *documentsDirPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSURL *documentsDirUrl = [NSURL fileURLWithPath:documentsDirPath isDirectory:YES];
NSURL *url = [NSURL URLWithString:@"out.mp4" relativeToURL:documentsDirUrl];
[self.movieFileOutput startRecordingToOutputFileURL:url recordingDelegate:self];


text:
Q: NServiceBus 4 with Windows 8 and Azure WebRole Issue Running a webrole that is using NServiceBus 4 hangs when running in the local emulator. I have duplicated this on several windows 8 machines. Works fine on Windows 7. It appears that the only way to get it to run is to change the azure project (web settings) to "Use IIS Web Server."  I am running Windows 8 and Visual Studio 2012 and Azure 2.0 SDK.
Here is how you can duplicate the problem by working with the PubSub sample from here:
http://particular.net/articles/windows-azure-transport

*

*Build the project and run it to verify that it works out of the box

*Now change the Web settings by right clicking on the azure project and Selecting the "Use IIS Express" option on the web tab.

*Run the project now

The web role will simply hang. Any ideas? Running under IIS Express is preferred for many reasons.

A: there seem to be some known issues with IISExpress and Azure. Could you have a look at these pages and see if they help

*

*Can't get azure web role to run locally using the emulator

*Workaround for IIS Express Crashing When Running Windows Azure Cloud Service Web Role


text:
Q: when requiring my mongoose model into utlit.js file I am getting a Object prototype may only be an Object or null: undefined I am using React along with mongoose to generate a new user via a form. Everything is find until I try to require const CreateUser = require('../models/users.js'); into my file. I get this error. Further google searches have pointed me toward a webpack error, however not sure what to edit to make it function. Everything works fine if I just comment out the require, but with it, my server compiles without error, but doesn't load the page.

bundle.js:60371 Uncaught TypeError: Object prototype may only be an Object or null: undefined
    at Function.create (<anonymous>)
    at Object.<anonymous> (bundle.js:60371)
    at Object.<anonymous> (bundle.js:60568)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:60257)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:59882)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:59036)
    at Object.<anonymous> (bundle.js:59870)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:59015)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:67877)
    at Object.<anonymous> (bundle.js:68087)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:67000)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:66600)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:65573)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:62495)
    at Object.<anonymous> (bundle.js:62503)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:47664)
    at Object.module.exports (bundle.js:50288)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:47628)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:45470)
    at Object.<anonymous> (bundle.js:45598)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:45431)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:45406)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:45156)
    at __webpack_require__ (bundle.js:20)
    at Object.defineProperty.value (bundle.js:20595)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:57)
    at __webpack_require__ (bundle.js:20)
    at bundle.js:40
    at bundle.js:43

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  username: {
    type: String,
    required: true,
    trim: true,
    lowercase: true
  },
  history: [{type: Schema.Types.ObjectId, ref: 'Trips'}]
});

const CreateUser = mongoose.model('Users', UserSchema);

module.exports = CreateUser;

const CreateUser = require('../models/users.js');
const axios = require('axios');

module.exports = {
  postSignupInfo: (firstname, lastname, email, password, username) => {
    const newSignup = new CreateUser({
      firstName: firstname,
      lastName: lastname,
      email: email,
      password: password,
      username: username
    });

    newSignup.save().then(function() {
      console.log('new user was saved!');
    })
  }
};

const path = require('path');
const webpack = require('webpack');

//NPM Install that "tells the plugin to add any JavaScript into the bootom of the page...
// just before the closing body tag"
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: './src/client/index.html',
  filename: 'index.html',
  inject: 'body'
})

module.exports = {
  entry: './index.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.(png|jpg|gif)$/, loader: 'file-loader' }
    ]
  },
  plugins: [HtmlWebpackPluginConfig,
    new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify('production')
    }
  })]
}

  "devDependencies": {
    "webpack-dev-server": "^1.16.2"
  },
  "dependencies": {
    "axios": "^0.17.1",
    "babel-core": "^6.21.0",
    "babel-loader": "^6.2.10",
    "babel-preset-latest": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "bcrypt-nodejs": "0.0.3",
    "body-parser": "^1.18.2",
    "file-loader": "^1.1.5",
    "html-webpack-plugin": "^2.26.0",
    "mongoose": "^4.13.2",
    "passport": "^0.4.0",
    "react": "^15.4.1",
    "react-bootstrap": "^0.31.5",
    "react-dom": "^15.4.1",
    "react-redux": "^5.0.6",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "react-router-redux": "^4.0.8",
    "redux": "^3.7.2",
    "webpack": "^1.14.0"
  }
}

A: I ran into a similar problem when I started to learn react.js.  I was trying to access the database from the front end, when I moved the code server side the problem disappeared.


text:
Q: How can I run my Spring apps offline? I have a Spring application (not a web app) that should be possible to run offline. However, when I try to do that, it crashes with this error message:
- Loading XML bean definitions from class path resource [applicationContext.xml]
21220 [main] WARN  org.springframework.beans.factory.xml.XmlBeanDefinitionReader
 - Ignored XML validation warning
org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'http://www.springframework.org/schema/tool/spring-tool-3.0.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.warning(Unknown Source)
...

This is caused by Spring not being able to find the schemas, as they are online and Spring is offline. How can I run my Spring apps offline?

A: Spring jars contain META-INF/spring.handlers and META-INF/spring.schemas files. To avoid overwriting the files when aggregating dependencies to one jar you can use the Maven Shade plugin.

A: Here what I did.
I manually edited the jar file.
First extracted META-INF/spring.schemas file.
Added there schemes which spring tries to download from internet.
In my case it was spring-beans.xsd and spring-tool.xsd.
Like this:

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans.xsd

And another spring-tool.xsd schema I've downloaded and added to the root of project. Then also added this line to spring.schemas, like this:

http://www.springframework.org/schema/tool/spring-tool.xsd=spring-tool.xsd
  One minus is every time when you rebuild your project you have to edit the jar file.

In the internet people say you have to add corresponding dependencies to project. For example spring-beans. But it didn't help me.


text:
Q: Could not find function "cbind.na" I am using R:
library(qpcR)
final<-cbind.na(datum_seq, amb.temp)
Error: could not find function "cbind.na"

I have looked on the internet, and it suggests that I need to have the up to date version of R and qpcr package.
Confirmed in the sessionInfo(), I have the latest version. Could there another reason why it cannot find the function?
R version 3.1.2 (2014-10-31)
Platform: i386-w64-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] plyr_1.8.1        qpcR_1.4-0        Matrix_1.1-4      robustbase_0.92-3 rgl_0.95.1201
[6] minpack.lm_1.1-8  MASS_7.3-35

loaded via a namespace (and not attached):
[1] DEoptimR_1.0-2  grid_3.1.2      lattice_0.20-29 Rcpp_0.11.2     tools_3.1.2

A: cbind.na is an internal variable to the qpcR package. If you must call this function directly, you can do so using qpcR:::cbind.na.
See help(':::') for details on internal and external variables.
Before using this, note the following (from the help page):
"It is typically a design mistake to use ::: in your code since the corresponding object has probably been kept internal for a good reason. Consider contacting the package maintainer if you feel the need to access the object for anything but mere inspection."


text:
Q: FormBuilder is not rendering initial values on select boxes I created dialog component for editing an address. I pass the details to the dialog component using the 'address' variable. As soon as the dialog component shows up, I get the initial values in my input fields but not in my select boxes. Please see my code below:
.ts
export class EditaddressDialogComponent implements OnInit {
  personId: any;
  editAddressForm: FormGroup;
  barangays: any[] = [];
  municipals: any[] = [];
  provinces: any[] = [];
  regions: any[] = [];

  addressToEdit: any;

  addressTypes: any = [
    {value: 'Home Address', name: 'Home Address'},
    {value: 'Permanent Address', name: 'Permanent Address'},
    {value: 'Billing Address', name: 'Billing Address'}
  ];

  constructor(
    public dialogRef: MatDialogRef<EditaddressDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private fb: FormBuilder,
    private addressService: AddressService
  ) { }

  ngOnInit() {
    this.getRegions();
    this.addressToEdit = this.data;
    this.editAddressForm = this.fb.group({
      addresstype: [this.data.address.AddressType, Validators.required],
      unitnumber: [this.data.address.UnitNumber],
      housenumber: [this.data.address.HouseNumber],
      streetname: [this.data.address.StreetName],
      villagesubdivision: [this.data.address.VillageSubdivision],
      barangaycode: [this.data.address.BarangayCode],
      municipalcode: [this.data.address.MunicipalCode],
      provincecode: [this.data.address.ProvinceCode],
      regioncode: [this.data.address.RegionCode],
    });
    console.log(this.addressToEdit.address.RegionCode);

  }

  getRegions() {
    this.addressService.getRegions().subscribe((data: any) => {this.regions = data; });
  }

  onRegionChange(event: MatOptionSelectionChange, region: any) {
    this.provinces = null;
    if (event.source.selected) {
      this.addressService.getProvinces(region)
        .subscribe((data: any) => {
          this.provinces = data;
        });
    }
  }

  onProvinceChange(event: MatOptionSelectionChange, province: any) {
    this.municipals = null;
    if (event.source.selected) {
      this.addressService.getMunicipals(province)
        .subscribe((data: any) => {
          this.municipals = data;
        });
    }
  }

  onMunicipalChange(event: MatOptionSelectionChange, municipal: any) {
    this.barangays = null;
    if (event.source.selected) {
      this.addressService.getBarangays(municipal)
        .subscribe((data: any) => {
          this.barangays = data;
        });
    }
  }

   // ============== getters ==================
   get addresstype() {
    return this.editAddressForm.get('addresstype');
  }
  addressTypeError() {
    return this.addresstype.hasError('required') ? 'This field is required' : '';
  }
  get unitnumber() {
    return this.editAddressForm.get('unitnumber');
  }
  get housenumber() {
    return this.editAddressForm.get('housenumber');
  }
  get streetname() {
    return this.editAddressForm.get('streetname');
  }
  get villagesubdivision() {
    return this.editAddressForm.get('villagesubdivision');
  }
  get barangaycode() {
    return this.editAddressForm.get('barangaycode');
  }
  get municipalcode() {
    return this.editAddressForm.get('municipalcode');
  }
  get provincecode() {
    return this.provincecode.get('provincecode');
  }
  get regioncode() {
    return this.editAddressForm.get('regioncode');
  }
}

.html
<form [formGroup]="editAddressForm">

            <mat-form-field>
              <mat-select placeholder="Address Type" formControlName="addresstype">
                <mat-option>--</mat-option>
                <mat-option *ngFor="let type of addressTypes" [value]="type.value">
                  {{type.name}}
                </mat-option>
              </mat-select>
              <mat-error *ngIf="addresstype.invalid">
                <mat-icon matSuffix>block</mat-icon>   {{ addressTypeError() }}</mat-error>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Unit Number</mat-label>
              <input type="text" matInput formControlName="unitnumber">
            </mat-form-field>
            <mat-form-field>
              <mat-label>House Number</mat-label>
              <input type="text" matInput formControlName="housenumber">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Street Name</mat-label>
              <input type="text" matInput formControlName="streetname">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Village / Subdivision</mat-label>
              <input type="text" matInput formControlName="villagesubdivision">
            </mat-form-field>

            <mat-form-field>
              <mat-select placeholder="Region" formControlName="regioncode">
                <mat-option>--</mat-option>
                <mat-option *ngFor="let region of regions" [value]="region.RegionCode" (onSelectionChange)="onRegionChange($event, region.RegionCode)">
                  {{region.Region}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-select placeholder="Province" formControlName="provincecode">
                <mat-option>--</mat-option>
                <mat-option *ngFor="let province of provinces" [value]="province.ProvinceCode" (onSelectionChange)="onProvinceChange($event, province.ProvinceCode)">
                  {{province.ProvinceName}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-select placeholder="Municipal" formControlName="municipalcode">
                <mat-option>--</mat-option>
                <mat-option *ngFor="let municipal of municipals" [value]="municipal.MunicipalCode" (onSelectionChange)="onMunicipalChange($event, municipal.MunicipalCode)">
                  {{municipal.MunicipalName}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-select placeholder="Barangay" formControlName="barangaycode">
                <mat-option>--</mat-option>
                <mat-option *ngFor="let barangay of barangays" [value]="barangay.BarangayCode">
                  {{barangay.BarangayName}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <button mat-raised-button color="accent" style="display: block; width: 100%;" (click)="onSubmit()">Submit</button>

      </form>

When I use the console log during the OnInit, I get the values that I am supposed to  use in my input boxes and select boxes. In fact, like what I said, I get it in my input boxes. But in the select boxes, I don't get any. Although, when I change the 'region' box, the onchange event is triggered. Can you please help with this? Thank you.

A: I would use a compareWith function in your mat-select's.  This method (defined in your ts file) will be used for the comparison.
Example HTML:
<mat-select placeholder="Address Type" formControlName="addresstype" [compareWith]="compareById">
   <mat-option *ngFor="let type of addressTypes" [value]="type"> {{ type.name }} </md-option>
</mat-select>

Example TS comapreWithFunction:
addressTypes: any = [
    {id: 1, value: 'Home Address', name: 'Home Address'},
    {id: 2, value: 'Permanent Address', name: 'Permanent Address'},
    {id: 3, value: 'Billing Address', name: 'Billing Address'}
  ];

compareById(obj1, obj2) {
   return obj1.id === obj2.id;
}

Then the formcontroll for addresstype will need to take an addresstype object instead of just the value.


text:
Q: Upper bound $\int_0^\infty \exp\left(-\alpha(x(x+\beta+1))^2\right)$ I am looking for an upper bound as tight as possible going to $0$ as $\alpha\to\infty$ of
$$\int_0^\infty \exp\left(-\alpha(x(x+\beta+1))^2\right).$$

A: Hint
Let $\beta >0$. Remark that $$\int_0^\infty e^{-a\big(x(x+\beta +1)\big)^2}\,\mathrm d x\leq \int_0^\infty e^{-a(\beta +1)^2x^2}\,\mathrm d x,$$ and use the fact that $$\int_0^\infty e^{-x^2}\,\mathrm d x=\frac{\sqrt\pi}{2}.$$


text:
Q: How to use filter for ng-repeat loop in AngularJS? I'm working on an ng-repeat that it will fill a div from a collction o object I have field called videos.description in those object with a large value so i want to change his value to a short value using filter this my code  :

{{video.name}}

        <video width="100%" height="190" controls style="margin:auto">
            <source src="test.mp4" type="video/mp4"> Your browser does not support the video tag.
        </video>
        <input id="input-7-xs" class="rating rating-loading" value="1" data-min="0" data-max="5" data-step="0.5" data-size="xs">

{{video.description}}

And this my filter :
app.filter('shortDescription', function() {
  return function(items, field) {
        var result = [];
        length=40;
        angular.forEach(items, function(value, key) {
            items[key].value=value.description.substring(0, length);
            console.log(field);
            result.push(items[key]);
        });
        return result;
    };
});

using this filter I still have a large value in the field description can someone help me thanks in advance

A: The problem is this line:
items[key].value=value.description.substring(0, length);

You have to update the description:
items[key].description=value.description.substring(0, length);

For this functionality, you can use map method, which accepts a callback function.
return items.map(function(item){
   return {"name":item.name,"description":item.description.substring(0,length)};
});


text:
Q: solr: curl delete command silently fails I am trying to delete all data before reindexing.
Here is my command (I am on windows):
curl -X POST -H "Content-Type: application/json" --data-binary "{\"delete\":{\"query\":\"*:*\" }}" http://localhost:8983/solr/mycollection/update

I get a successful response, but the data is still there afterwards. What could be the problem?

A: Your curl command is missing the commit=true
Please use the below command with commit in it.
curl -X POST -H 'Content-Type: application/json' \
    'http://<host>:<port>/solr/<core>/update?commit=true' \
    -d '{ "delete": {"query":"*:*"} }'

If you are using the curl on the windows then it would be like
curl -X POST -H "Content-Type: application/json" --data-binary "{\"delete\":{\"query\":\"*:*\" }}" "http://localhost:8983/solr/mycollection/update?commit=true"

Below one can be used through browser :
http://host:port/solr/collection_name/update?commit=true&stream.body=<delete><query>*:*</query></delete>


text:
Q: Inheritance and abstract parmater passing I have the following classes:
Abstract class A
Abstract class B extends A
class C1 extends B
class C2 extends B
class C3 extends B

The classes C1, C2, C3 implements the same abstract method:
public MyItem getItem()

In other class (say class X) I have (want to have...) function:
void testFunction(A classA)
{
   MyItem myItem = classA.getItem();
   ...
}

But when I'm doing that I'm getting compilation error.
I cant understand why ?  why cant I write the void testFunction(A classA) as I want ?
(I know that in c++ I can do it)
Thanks

A: The problem is that probably you did not define the method getItem() in the class A.
You can define it (without necessarily specifying a concrete implementation of it, if you don't want/can) by simply adding this line in the class A:
abstract public MyItem getItem();

In this way the method signature is defined in the class A, and you can therefore call it when you have an object declared of class A.
Then all concrete classes extending A (such as classes C1, C2 and C3), must mandatory implement the method getItem() by overriding it. You may also add an @Override notation before the method implementation, for instance:
class C1 extends B {

   @Override
   public MyItem getItem() {
      //concrete implementation
   }
}


text:
Q: Почему алгоритм Дейкстры не работает для графов с отрицательными ребрами? Условно есть такой граф, .
Вот код поиска кратчайшего пути по алгоритму Дейкстры.
`
def find_lowest_cost_node(costs):
    lowest_cost = float("inf")
    lowest_cost_node = None
    for node in costs:
        cost = costs[node]
        if (cost < lowest_cost) and (node not in processed):
            lowest_cost = cost
            lowest_cost_node = node
    return lowest_cost_node

graph = {}
graph["Start"] = {}
graph["Start"]["a"] = 5
graph["Start"]["b"] = 0
graph["a"] = {}
graph["a"]["b"] = -7
graph["b"] = {}
graph["b"]["fin"] = 35
graph["fin"] = {}

costs = {}
costs["a"] = 5
costs["b"] = 0
costs["fin"] = float("inf")

parents = {}
parents["a"] = "Start"
parents["b"] = "Start"
parents["fin"] = None

processed = []
node = find_lowest_cost_node(costs)
while node is not None:
    cost = costs[node]
    neighborts = graph[node]
    for n in neighborts.keys():
        new_cost = cost + neighborts[n]
        if costs[n] > new_cost:
            costs[n] = new_cost
            parents[n] = node
    processed.append(node)
    node = find_lowest_cost_node(costs)

print(costs["fin"])
print(parents)

`
Я так полагаю, что  по идеи алгоритма, стоимость fin - равняется 35, т.к узел C был выбран первым, после чего был обработан узел D, где в хеш таблице costs по ключу fin было записано 35. Следующим узлом был выбран B, где мы обновили стоимость С, но не D. Поэтому стоимость D по прежнему осталась 35. Но мы же обновили родителя для узла C, и в итоге получилось вот так .
И на сколько я понимаю, мы можем правильно восстановить по таблице родителей стоимость? Или я где-то что-то путаю?


text:
Q: Hard drive, CPU, or other issue? It seems my computer has crashed but not sure what the problem is. I have an HP Pavillion p6310f with Windows 7 home edition. I bought it less than 2 years ago. 6GB RAM, 1TB Western Digital (green version) hard drive, AMD Athlon II X4 630 Quadcore.
I was just working like normal on my computer, didn't even have a browser open, when all of a sudden a message pops up that an error occurred and that for the safety of the computer it would shutdown.
After it shut off, I tried starting it back up. There weren't any boot loaders detected so I went into the BIOS to point them. No drives were detected at all. I had no option to boot from.
So I gave it a good power cycle. After that I was able to detect the right boot driver and get started up. I chose to start Windows in safe mode. Once the computer is started up its really slow, unresponsive, completely freezes up and sometimes just shuts right back off.
Seems to me like its a hard drive but I don't want to go buying a new one if its sounds like its something else. Just thought I'd check with you guys before taking it into the computer store where they will probably charge me just to look at it.
Ideas? Advice?
CONCLUSION:
In the end its the hard drive. I was able to run diagnostics on the CPU, RAM, Power Supply and they came back fine. When it tried to run the diag on the hard drive, it froze and wouldn't run. So, safe enough to say, its the hard drive.

A: If you have no solid ideas, and no spare parts/computers to test with, then perhaps it's worth paying someone who knows what they're doing to tell you what's wrong?
Having said that, then based on your description and experience, it sounds like your harddrive is dying.
Head over to Western Digital's site and grab their diagnostics utility.
You can test your memory using Windows built in memory test, or something like Memtest86+.
Otherwise, you're going to have to go try and few things and then come back with more specific questions, so that we're not guessing at what's wrong. :)
Also check out these other SU questions (plus I'm sure there are MANY more) for some ideas on what/how to test:

*

*https://superuser.com/questions/43846/recommendations-for-hardware-diagnostic-software-bootable

*https://superuser.com/questions/104235/what-is-the-best-hardware-diagnostic-for-a-pc

*Computer locking up, looking for bootable hardware diagnostic tool

*When to stop using a hard drive? What rules/software apply?

A: If you suspect a PSU issue, HP has a nice doc on troubleshooting, there is a diagnostic light of sorts on the PSU.
Other Startup troubleshooters here
.


text:
Q: Get pointer to struct by pointer to its member Is there a portable way to get a pointer to a structure if you have a pointer to a member of that structure?
There is a linked list implementation in Linux kernel (1):
struct list_head {
    struct list_head *next, *prev;
};

static inline void __list_add(struct list_head *new,
                  struct list_head *prev,
                  struct list_head *next)
{
    next->prev = new;
    new->next = next;
    new->prev = prev;
    prev->next = new;
}

static inline void list_add(struct list_head *new, struct list_head *head)
{
     __list_add(new, head, head->next);
}

#define list_entry(ptr, type, member) \
    container_of(ptr, type, member)

The idea is that this implementation is generic. You can use it with any struct type:
struct my_struct {
    int my_data;

    struct list_head node;
};

void example()
{
    struct list_head head;
    struct my_struct element1 = { 1 };
    struct my_struct element2 = { 2 };

    head.next = head.prev = &head;   // head <-> head
    list_add(&element1.node, &head); // head <-> {1} <-> head
    list_add(&element2.node, &head); // head <-> {2} <-> {1} <-> head

    struct my_struct *front_element = list_entry(&head.next, struct my_struct, node);

    printf("front element data: %d\n", front_element->my_data); // will print "2"
}

Elements of list_head are linked with each other, but there are only pointers to list_head and there are no pointers to my_struct (that contains list_head inside). However having a pointer to the node member of my_struct, you can convert this pointer to a pointer to my_struct itself using the list_entry macro. This is done using tricky pointer arithmetic (the offset of the member in the struct is subtracted from the address of the member).
But the implementation of the container_of macro is not portable because it uses gcc extensions and deferencing of null pointer (which is generally UB):
#define container_of(ptr, type, member) ({          \
    const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
    (type *)( (char *)__mptr - offsetof(type,member) );})

Is there a way to make a portable implementation of this macro?


text:
Q: when using WEBRTC to stream video between peers, ontrack function is never called I am doing a video chat, and in the first steps i am trying to deeply understand WEBRTC. I'm not to the signalling part yet, so I am doing it 'by hand' as shown here https://www.youtube.com/watch?v=FExZvpVvYxA&t=3626s&ab_channel=HusseinNasser ,Then i get a stream from the navigator and create an offer which I manually paste in the other peer. Then I create an answer and repeat the process the other way around. The add track function seems to work without a problem, but the function ontrack is never called in the other peer.
here is the code I wrote for the 'main' peer, even looping in the streams tracks and adding them one by one doesn't work
navigator.mediaDevices.getUserMedia(
    { video: true, audio: true }).then(stream => {
        document.getElementById('video').srcObject = stream;
        document.getElementById('video').play()
        localConnection.addTrack(stream.getTracks()[0])
        return localConnection.createOffer();
    }).then(() => {
        offer => applicationCache.setLocalDescription(new RTCSessionDescription(offer));
        console.log(JSON.stringify(localConnection.localDescription))
    })

here the code for the answering peer who should get the video and play it
remoteConnection.ontrack = e => {
       document.getElementById('video1').srcObject = e.streams[0];
       document.getElementById('video1').play();
       console.log('i'm triggered');
};

thanks for any help :)


text:
Q: Spreadsheet failed to open after updating a worksheet table in Excel using openpyxl Python package I have a spreadsheet that contains several defined tables. My goal is to use Python to update the data in one of those tables. Each time, the number of records (rows) is subject to change, so based on this thread, I need to adjust tableRef and tableStyleInfo if table size and style are changed. After those changes have been made and the Excel has been saved, I was not able to open the spreadsheet anymore.
The error message the COM Interface gives is com_error: (-2147023170, 'The remote procedure call failed.', None, None). When I open the spreadsheet manually, the Excel window just disappeared after it finishes loading.
Below is the code I used update the spreadsheet. A1:D2500 is the original table range including the header. My code simply starts with clearing all existing data in the table.
for row in mysheet_LT['A2:D2500']:
    for cell in row:
        cell.value = None

r=1

for per in ['AM' ,'PM']:
    for link in all_veh_attributes:
        r+=1
        ID=int(link[0])
        length=float(link[1])
        if link[2]==None:
            demand=0
        else:
            demand=int(link[2])

        mysheet_LT.cell(r,1).value=ID
        mysheet_LT.cell(r,2).value=per
        mysheet_LT.cell(r,3).value=length
        mysheet_LT.cell(r,4).value=demand
    print(per+" finished.")

style=TableStyleInfo(name="TableStyleMedium2", showFirstColumn=False,
                   showLastColumn=False, showRowStripes=True, showColumnStripes=False)
for i, table in enumerate(mysheet_LT._tables):
    if table.name=="LinkTable":
        tableRef=i
        break

resTable = Table(displayName="LinkTable", ref="A1:{}{}".format("D",r))
resTable.tableStyleInfo = style

mysheet_LT._tables[tableRef] = resTable
f_excel.save(filepath.replace(".xlsx","_copy.xlsx"))
del f_excel

I also checked the source xml files saved in xl\tables to figure out what was changed behind the scene other that the data values.
Before I ran the script and spreadsheet is still loadable, the table1.xml is shown below.
<?xml version="1.0" encoding="UTF-8" standalone="true"?>

-<table totalsRowShown="0" ref="A1:D2500" displayName="LinkTable" name="LinkTable" xr:uid="{ED5889A4-4026-48FE-85A0-F3DC88F0CD25}" id="6" xmlns:xr3="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3" xmlns:xr="http://schemas.microsoft.com/office/spreadsheetml/2014/revision" mc:Ignorable="xr xr3" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<autoFilter ref="A1:D2500" xr:uid="{ED5889A4-4026-48FE-85A0-F3DC88F0CD25}"/>
-<tableColumns count="4">
<tableColumn name="Link" xr3:uid="{D25FAC3E-75B1-47FF-B538-B5AAC2E676D2}" id="1"/>
<tableColumn name="Period" xr3:uid="{FB8F2531-3D44-4F33-8013-7EBE0D747A16}" id="2"/>
<tableColumn name="Length" xr3:uid="{F726E2D7-F77C-46B7-A5E5-1A7BFF89FD6F}" id="3"/>
<tableColumn name="Demand" xr3:uid="{5A968ACB-7F4B-4E5D-9480-E4DDCAD39B79}" id="4"/>
</tableColumns>
<tableStyleInfo name="TableStyleMedium2" showColumnStripes="0" showRowStripes="1" showLastColumn="0" showFirstColumn="0"/>
</table>

Below is the same file in the same folder after the Python script was run and the spreadsheet failed to open. I noticed that all the xr3:uids are missing here, but I am not sure if that's what caused the issue. If that's the problem, could someone tell me how I can properly defined them in openpyxl.
-
<autoFilter ref="A1:D1835"/>
-<tableColumns count="4">
<tableColumn name="Link ID" id="1"/>
<tableColumn name="Period" id="2"/>
<tableColumn name="Length" id="3"/>
<tableColumn name="Demand" id="4"/>
</tableColumns>
<tableStyleInfo name="TableStyleMedium2" showColumnStripes="0" showRowStripes="1" showLastColumn="0" showFirstColumn="0"/>
</table>


text:
Q: Regenerate Docusign emails I need to regenerate all of the DocuSign emails that have been sent out over the last couple of years.
I understand I cannot perfectly regenerate these due to some of the links involved in the email, but I think I should be able to come close.
So far in our demo account, I've received all the recipients for our envelopes, identified the sender and created records for all the initial sent emails as well as any completed emails.
For completed records, I can generate a viewLink. I need some assistance in generating a link for those that are not completed at this time. Also, should I be concerned about the viewLinks not expiring or can I secure these with an access code?

A: You can use the API to resend the email to a recipient if the recipient has not yet signed.
See the resend_envelope query parameter for the EnvelopeRecipients: update method.


text:
Q: how to get the value of the textinnput when submit button is pressed I just started learning react native, after i learned reactJs. I was wondering how to set the value of the TextInput when the button is pressed as the state value "message", and not to have it hard coded as i have it at the moment...
export default class Writing extends Component {
    constructor() {
      super();
      this.state={
        message: "",
      };
    }

    onSend = () => {
      this.setState({ message: "Hello world!" });
      alert(this.state.message)
    }

    render(){
      return (
        <View>
          <TextInput
            style={styles.input}
            placeholder="Your message"
            onChangeText={this.state.message}
          />
          <Button
            title="Submit"
            onPress={this.onSend}
          />
        </View>
      )
    }
}```

A: It is the same in react-native as in react. So you should do the same things i.e:
      <TextInput
        style={styles.input}
        placeholder="Your message"
        onChangeText={(text)=>this.setState({message:text})}
      />

A: You need value props for TextInput. You may refer to the document written by React Native.
https://reactnative.dev/docs/textinput
You can modify your code like this.
constructor() {
  super();
  this.state={
    message: "",         //This stores what you want to replace when button is pressed
    textInputValue: "",  //This stores textinput value
  };
}

onSend = () => {
  //Set text input value by state 'message'
  this.setState({ textInputValue : this.state.message});
}

<TextInput
    value={this.state.textInputValue}   //This controls textinput value
    style={styles.input}
    placeholder="Your message"
    onChangeText={(text)=>{this.setState({textInputValue: text}}
/>

A: Replace your onSend with the below code. onChangeText never holds the state, it is used to change the state. So, please replace your TextInput component with the below code.

TextInput

<TextInput
   value = {this.state.message}
   style={styles.input}
   placeholder="Your message"
   onChangeText={(result) => {
      this.setState({ message: result })
    }}
 />

onSend

onSend = () => {
    alert(this.state.message)
}


text:
Q: WCF data services (OData), query with inheritance limitation? Project: WCF Data service using internally EF4 CTP5 Code-First approach.
I configured entities with inheritance (TPH).
See previous question on this topic:
 Previous question about multiple entities- same table
The mapping works well, and unit test over EF4 confirms that queries runs smoothly.
My entities looks like this:

*

*ContactBase (abstract)

*Customer (inherits from ContactBase), this entity has also several Navigation properties toward other entities

*Resource (inherits from ContactBase)

I have configured a discriminator, so both Customer and Resource map to the same table.
Again, everythings works fine on the Ef4 point of view (unit tests all greens!)
However, when exposing this DBContext over WCF Data services, I get:
- CustomerBases sets exposed (Customers and Resources sets seems hidden, is it by design?)
- When I query over Odata on Customers, I get this error:
Navigation Properties are not supported on derived entity types. Entity Set 'ContactBases' has a instance of type 'CodeFirstNamespace.Customer', which is an derived entity type and has navigation properties. Please remove all the navigation properties from type 'CodeFirstNamespace.Customer'.

Stacktrace:
at System.Data.Services.Serializers.SyndicationSerializer.WriteObjectProperties(IExpandedResult expanded, Object customObject, ResourceType resourceType, Uri absoluteUri, String relativeUri, SyndicationItem item, DictionaryContent content, EpmSourcePathSegment currentSourceRoot)
at System.Data.Services.Serializers.SyndicationSerializer.WriteEntryElement(IExpandedResult expanded, Object element, ResourceType expectedType, Uri absoluteUri, String relativeUri, SyndicationItem target)
at System.Data.Services.Serializers.SyndicationSerializer.<DeferredFeedItems>d__b.MoveNext()
at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteItems(XmlWriter writer, IEnumerable`1 items, Uri feedBaseUri)
at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeedTo(XmlWriter writer, SyndicationFeed feed, Boolean isSourceFeed)
at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeed(XmlWriter writer)
at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteTo(XmlWriter writer)
at System.Data.Services.Serializers.SyndicationSerializer.WriteTopLevelElements(IExpandedResult expanded, IEnumerator elements, Boolean hasMoved)
at System.Data.Services.Serializers.Serializer.WriteRequest(IEnumerator queryResults, Boolean hasMoved)
at System.Data.Services.ResponseBodyWriter.Write(Stream stream)

Seems like a limitation of WCF Data services... is it?
Not much documentation can be found on the web about WCF Data services (OData) and inheritance specifications.
How can I overpass this exception? I need these navigation properties on derived entities, and inheritance seems the only way to provide mapping of 2 entites on the same table with Ef4 CTP5...
Any thoughts?

A: Currently, WCF data services does not support navigation properties on derived types. This is a known limitation and we are currently working on enabling this for our next release.
Currently, the work around is that you put all the navigation properties to the type refered by the set. In your example, can you make the entity set type be customer, instead of ContactBase?
Hope this helps.
Thanks
Pratik


text:
Q: Why do I get list index out of range in my twitter weather bot application I have created a bot that interacts with users tweets and reply with the weather of the location the user tweets with in the # e.g. "Whats the weather like in #London". The bot will then reply with what the weather is currently in London.
When i run the bot, it runs fine and finds the URL to get the data of the weather and stores the tweet, but when it needs to reply with the weather, i get a list index out of range.
the code:
def get_location(tweet):
    #takes tweet and returns only the substring attached to hashtag
    tweet_location = [i.strip("#") for i in tweet.split() if i.startswith("#")][0]
    tweet_location += " today weather.com"
    return tweet_location

def get_weather(query):
    for url in search(query, stop=1):
        print("Results is " + url)

    #this code sends a request and reads the webpage enclsed to the request
    request = Request(url, headers={"User-Agent": "Mozilla/5.0"})

    webpage = urlopen(request).read()
    soup = BeautifulSoup(webpage, "html.parser")

    try:
        title = soup.findAll("span", "today-daypart-title")[0].string
        phrase = soup.findAll("span", "today-daypart-wxphrase")[0].string
    except IndexError as e:
        forecast = (" could not find the weather, check back later")
        print(e)
    else:
        forecast = (" forecast for " + title + " is " + phrase)
        print(forecast)

    return forecast

def reply_to_tweet():
    print("retrieving and replying to tweets...")
    last_seen_tweet = read_last_seen(FILE_NAME)
    # mentions_timeline() returns a list of 20 most recent mentions
    mentions = api.mentions_timeline(last_seen_tweet, tweet_mode="extended")

    # reversing to read old tweets first
    for mention in reversed(mentions):
        print(str(mention.id) + " - " + mention.full_text)
        last_seen_tweet = mention.id
        store_last_seen(FILE_NAME, last_seen_tweet)
        if "#" in mention.full_text.lower():
            print("found #")

            location = get_location(mention.full_text)
            weather = get_weather(location)

            # responding to tweet mention
            api.update_status("@" + mention.user.screen_name + weather, mention.id)

The output from running the code:
retrieving and replying to tweets...
1386417114316169219 - @UniProjectbot #Birmingham
found #
Results is https://weather.com/en-GB/weather/today/l/Birmingham+England?canonicalCityId=de781cf30dc9d9dbea1ed33096e3729fe38d4023bb06259589d311d034072b9d
list index out of range


text:
Q: What tools are there for functional programming in C? I've been thinking a lot lately about how to go about doing functional programming in C (not C++).  Obviously, C is a procedural language and doesn't really support functional programming natively.
Are there any compiler/language extensions that add some functional programming constructs to the language?  GCC provides nested functions as a language extension; nested functions can access variables from the parent stack frame, but this is still a long way away from mature closures.
For example, one thing that I think could be really useful in C is that anywhere where a function pointer is expected, you could be able to pass a lambda expression, creating a closure which decays into a function pointer.  C++0x is going to include lambda expressions (which I think is awesome); however, I'm looking for tools applicable to straight C.
[Edit] To clarify, I'm not trying to solve a particular problem in C that would be more suited to functional programming; I'm merely curious about what tools are out there if I wanted to do so.

A: You can use GCC's nested functions to simulate lambda expressions, in fact, I have a macro to do it for me:
#define lambda(return_type, function_body) \
  ({ \
    return_type anon_func_name_ function_body \
    anon_func_name_; \
  })

Use like this:
int (*max)(int, int) = lambda (int, (int x, int y) { return x > y ? x : y; });

A: Functional programming is not about lambdas, it is all about pure functions.  So the following broadly promote functional style:

*

*Only use function arguments, do not use global state.

*Minimise side effects i.e. printf, or any IO.  Return data describing IO which can be executed instead of causing the side effects directly in all functions.
This can be achieved in plain c, no need for magic.

A: The main thing that comes to mind is the use of code generators.  Would you be willing to program in a different language that provided the functional programming and then generate the C code from that?
If that's not an attractive option, then you could abuse CPP to get part of the way there.  The macro system should let you emulate some functional programming ideas.  I've heard tell that gcc is implemented this way but I've never checked.
C can of course pass functions around using function pointers, the main problems are lack of closures and the type system tends to get in the way.  You could explore more powerful macro systems than CPP such as M4.  I guess ultimately, what I'm suggesting is that true C isn't up to the task without great effort but you could extend C to make it be up to the task.  That extension would look the most like C if you use CPP or you could go to the other end of the spectrum and generate C code from some other language.

A: The way I went about doing functional programming in C was to write a functional language interpreter in C.  I named it Fexl, which is short for "Function EXpression Language."
The interpreter is very small, compiling down to 68K on my system with -O3 enabled.  It's not a toy either - I'm using it for all the new production code I write for my business (web-based accounting for investment partnerships.)
Now I write C code only to (1) add a built-in function that calls a system routine (e.g. fork, exec, setrlimit, etc.), or (2) optimize a function that could otherwise be written in Fexl (e.g. search for a substring).
The module mechanism is based on the concept of a "context".  A context is a function (written in Fexl) which maps a symbol to its definition.  When you read a Fexl file, you can resolve it with any context you like.  This allows you to create custom environments, or run code in a restricted "sandbox."
http://fexl.com

A: If you want to implement closures, you'll have to get groady with assembly language and stack swapping/management. Not recommending against it, just saying that's what you'll have to do.
Not sure how you'll handle anonymous functions in C. On a von Neumann machine, you could do anonymous functions in asm, though.

A: FFCALL lets you build closures in C -- callback = alloc_callback(&function, data) returns a function pointer such that callback(arg1, ...) is equivalent to calling function(data, arg1, ...).  You will have to handle garbage collection manually, though.
Relatedly, blocks have been added to Apple's fork of GCC; they're not function pointers, but they let you pass around lambdas while avoiding the need to build and free storage for captured variables by hand (effectively, some copying and reference counting happens, hidden behind some syntactic sugar and runtime libraries).

A: Look at Hartel & Muller's book, Functional C
http://www.ub.utwente.nl/webdocs/ctit/1/00000084.pdf
http://www.cs.bris.ac.uk/~henkm/f2c/index.html

A: The Felix language compiles to C++. Maybe that could be a step stone, if you don't mind C++.

A: Hartel & Muller's book, Functional C, can nowadays (2012-01-02) be found at: http://eprints.eemcs.utwente.nl/1077/ (there is a link to PDF version).

A: Prerequisite for functional programming style is a first class function.
It could be simulated in portable C if you tolerate next:

*

*manual management of lexical scope bindings, aka closures.

*manual management of function variables lifetime.

*alternative syntax of function application/call.

/*
 * with constraints desribed above we could have
 * good approximation of FP style in plain C
 */

int increment_int(int x) {
  return x + 1;
}

WRAP_PLAIN_FUNCTION_TO_FIRST_CLASS(increment, increment_int);

map(increment, list(number(0), number(1)); // --> list(1, 2)

/* composition of first class function is also possible */

function_t* computation = compose(
  increment,
  increment,
  increment
);

*(int*) call(computation, number(1)) == 4;

runtime for such code could be as small as one below

struct list_t {
  void* head;
  struct list_t* tail;
};

struct function_t {
   void* (*thunk)(list_t*);
   struct list_t* arguments;
}

void* apply(struct function_t* fn, struct list_t* arguments) {
  return fn->thunk(concat(fn->arguments, arguments));
}

/* expansion of WRAP_PLAIN_FUNCTION_TO_FIRST_CLASS */
void* increment_thunk(struct list_t* arguments) {
  int x_arg = *(int*) arguments->head;
  int value = increment_int(x_arg);
  int* number = malloc(sizeof *number);

  return number ? (*number = value, number) : NULL;
}

struct function_t* increment = &(struct function_t) {
  increment_thunk,
  NULL
};

/* call(increment, number(1)) expands to */
apply(increment, &(struct list_t) { number(1), NULL });

In essence we imitate first class function with closures represented as pair of function/arguments plus bunch of macroses. Complete code could be found here.

A: Well quite a few programming languages are written in C. And some of them support functions as first class citizens, languages in that area are ecl (embbedabble common lisp IIRC), Gnu Smalltalk (gst) (Smalltalk has blocks), then there are libraries for "closures" e.g in glib2 http://library.gnome.org/devel/gobject/unstable/chapter-signal.html#closure
which at least got near functional programming. So maybe using some of those implementations to do functional programming may be an option.
Well  or you can go learning Ocaml, Haskell, Mozart/Oz or the like ;-)
Regards

A: Dont Know about C. There are some functional features in Objective-C though, GCC on the OSX also supports some features, however I would again recommend to start using a functional language, there are plenty mentioned above. I personally started off with scheme, there are some excellent books such as The Little Schemer that can help you do so.

A: What is it about C that you want to make functional, the syntax or the semantics? The semantics of functional programming could certainly be added to the C compiler, but by the time you were done, you'd essentially have the equivalent of one of the existing functional languages, such as Scheme, Haskell, etc.
It would be a better use of time to just learn the syntax of those languages which directly support those semantics.


text:
Q: Previous information still present within Object I'm a little confused. So I have a JavaScript game build in JS, HTML5 canvas, and Firebase. The weird thing I'm experiencing is when I play a game there isn't a problem as it sends the information to the backend. But if I refresh it's as if the previous score still is present so when information gets send, it gets sent twice. If I refresh again then it's 3X etc. In the image, you can see the name and score are present from previous rounds.
Backend showing repetition
The block of code where the information gets sent is
  showInput() {
    document.getElementById("inputName").type = "text";
    document.getElementById("inputName").addEventListener("keyup", e => {
      e.preventDefault();
      if (e.keyCode === 13) {
        const scores = firebase.database().ref("scores/");
        let name = document.getElementById("inputName").value;
        let score = this.score;
        let highScore = { name, score };
        scores.push(highScore);

        document.getElementById("inputName").type = "hidden";
        this.showLeaderBoard();
      }
    });
  }

But it is strange since when a new game gets created. The information in it, for example, the score says this.score = 0 and it shows that. Can someone explain why a previous score still persist?
Thanks for all your help and explanation.
** Remove Listener **
  showInput() {
    document.getElementById("inputName").type = "text";
    document.getElementById("inputName").addEventListener("keyup", e => {
      console.log("event added");
      e.preventDefault();
      if (e.keyCode === 13) {
        const scores = firebase.database().ref("scores/");
        let name = document.getElementById("inputName").value;
        let score = this.score;
        let highScore = { name, score };
        scores.push(highScore);

        document.getElementById("inputName").type = "hidden";
        this.showLeaderBoard();
      }
    });

    document.getElementById("inputName").removeEventListener("keyup", e => {
      console.log("event removed");
      e.preventDefault();
      if (e.keyCode === 13) {
        const scores = firebase.database().ref("scores/");
        let name = document.getElementById("inputName").value;
        let score = this.score;
        let highScore = { name, score };
        scores.push(highScore);

        document.getElementById("inputName").type = "hidden";
        this.showLeaderBoard();
      }
    });
  }

** Reset Function **
    const Game = require("./game");
const Background = require("./background");
var GameInstance = null;

document.addEventListener("DOMContentLoaded", () => {
  let preGame = () => {
    const canvasStart = document.getElementById("start");
    if (canvasStart.getContext) {
      const ctxStart = canvasStart.getContext("2d");

      ctxStart.font = "30px games";
      ctxStart.fillStyle = "red";
      ctxStart.fillText(
        "Press R to Start!",
        canvasStart.width / 2 - 110,
        canvasStart.height / 2
      );
    }
  };

  document.getElementById("inputName").addEventListener("keyup", e => {
    e.preventDefault();
    if (e.keyCode === 13 && GameInstance) {
      const scores = firebase.database().ref("scores/");
      let name = document.getElementById("inputName").value;
      let score = GameInstance.score;
      let highScore = { name, score };
      scores.push(highScore);

      document.getElementById("inputName").type = "hidden";
      GameInstance.showLeaderBoard();
    }
  });

  preGame();
  document.addEventListener("keypress", e => {
    if (
      e.key === "r" &&
      document.getElementById("inputName").type === "hidden"
    ) {
      let score = 0;
      const canvasStart = document.getElementById("start");
      if (canvasStart.getContext) {
        const ctxStart = canvasStart.getContext("2d");
        ctxStart.clearRect(0, 0, canvasStart.width, canvasStart.height);
      }
      const canvas = document.getElementById("canvas");
      const canvasEnemy = document.getElementById("enemy");
      const canvasScore = document.getElementById("scoreBoard");
      const canvasGameOver = document.getElementById("gameOver");
      if (canvas.getContext) {
        const ctx = canvas.getContext("2d");
        const ctxEnemy = canvasEnemy.getContext("2d");
        const ctxScore = canvasScore.getContext("2d");
        const ctxGameOver = canvasGameOver.getContext("2d");
        GameInstance = new Game(
          ctx,
          canvas,
          ctxEnemy,
          canvasEnemy,
          ctxScore,
          canvasScore,
          ctxGameOver,
          canvasGameOver,
          score
        ).start();
      }
    }
  });

A: Your code need to be slightely refactored as the way it is now is causing some very serious problems:

*

*Each instance of the game creates its own event listener for the input. That will send more and more requests with each new instance.

*The instances you think are destroyed are still alive. They are trapped in the closures created by the multiple event listeners. That is a major memory leak.

Remove the event listener from showInput function. Define it only once. It should just check the current game instance and sends its score to the server when an input happens:
var gameInstance = null;

document.getElementById("inputName").addEventListener("keyup", function(e) {
  e.preventDefault();
  if (e.keyCode === 13 && gameInstance) {                             // check if there is a game instance
    const scores = firebase.database().ref("scores/");
    let name = this.value;                                            // this is the input now
    let score = gameInstance.score;                                   // use gameInstance
    let highScore = { name, score };
    scores.push(highScore);

    this.type = "hidden";                                             // here too
    gameInstance.showLeaderBoard();                                   // ...
  }
});

document.addEventListener("keypress", e => {
  // ...
  gameInstance = new Game(/* ... */);                                 // don't forget to store the gameInstance so the event listener will have access to it
  // ...
});

showInput should look like this:
showInput() {
  document.getElementById("inputName").type = "text";
}

Which just shows the input as it supposed to be.


text:
Q: Looking for a fast library to render PDF's files with PHP Does anyone knows about a fast library to render PDF's files with PHP?
I'm trying with dompdf but it's really slow, it takes about 5 minutes to render a PDF of 23 sheets.
Dompdf is amazing and really useful, but when you've to render large pdf's files is worthless.
I'm using dompdf 0.6.0 beta 3.
Has anyone experimented with larges pdfs in php using another library?
Could I improve this with dompdf? Here is the html file which dompdf renders:
http://dl.dropbox.com/u/15451865/pdf.html
I'm thinking about to write a service with openoffice library but I don't like to use another technology only for this.

A: In terms of performance wkhtmltopdf seems to be doing well.
It does not rely on PHP to do the heavy lifting, but instead it uses the webkit-engine to render the page.
The downside is that it has not been updated in a while.

A: Have you tried FPDF ?
FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs.
FPDF : class which allows to generate PDF files
You can also use FPDI with FPDF. With FPDI you will be able to import single pages of existing PDF documents into templates.

A: Try http://www.fpdf.org/
I use it and its very good, flexible, you can set size of a page, you can also use template (fpdi - works with fpdf). You can put images, text, set position of each element.

A: Some benchmark results:
To renderer this file (with only plain divs) http://dl.dropbox.com/u/15451865/notables_dompdf.html on Intel(R) Core(TM) i7-2600K CPU @ 3.40GHz, 8 GB RAM memory (Ubuntu 12.04):
Dompdf: 35 seconds with a CPU rate of 100%
Google Chrome PDF printer: 1 seconds
So I think DOMPDF is an amazing library but for a service which needs high performance I need another library (I'll try FPDF).


text:
Q: Sacar promedios de un array multidimensional javascript Tengo el siguiente array multidimensional

Imprime los siguientes datos:
filtrados = [
[],
[{"edad":40,"sexo":"hombre","partido":"PRI"},{"edad":30,"sexo":"hombre","partido":"PRI"}],
[{"edad":35,"sexo":"mujer","partido":"PAN"},{"edad":25,"sexo":"hombre","partido":"PAN"}],
[{"edad":10,"sexo":"mujer","partido":"PT"}],
[],
[],
[],
[],
[],
];

Tengo que sacar el promedio de edad y sexo por partido, ya estan filtrados por partidos porque un array representa un partido pero no logro realizar los promedios. Actualmente este es mi fragmento de codigo:
this.politicians.forEach((politicos) => {
      this.politico = politicos;

      this.partidosBD.forEach((partidos) => {
        this.partidos = partidos;

        var filtrados = [];

        for (let i = 0; i < this.partidos.length; i++) {
//FILTRADO POR PARTIDOS
          filtrados.push(this.politico.filter((a) => this.partidos[i].name.includes(a.partidoPolitico)));

        }

        console.log(filtrados);

    //RECORRO EL ARRAY
        for (let i = 0; i < filtrados.length; i++) {
          console.log("Arreglo #" + i);
          for (let j = 0; j < filtrados[i].length; j++) {
    //COMPRUEBO SI EL ARRAY NO ESTA VACIO, ENTIENDO AQUI SE DEBE APLICAR LOS PROMEDIOS
            if (filtrados[i].length > 0) {
              console.log("Edad #" + JSON.stringify(j) + " " + JSON.stringify(filtrados[i][j].age));

            }
          }
        }

      });
    });

El sacar promedio entiendo es la suma de los valores en edad entre edad.length y sexo es el total de hombres y mujeres pero no logro plasmar la funciòn. Los resultados deben ser guardados en un array unidimensional del mismo tamaño del array multidimensional como este ejemplo que es de 9 elementos. Resultado esperado:
prom_edad = [
    0,
    70,
    60,
    10,
    0,
    0,
    0,
    0,
    0,
        ]
prom_sexo_h = [
        0,
        2,
        1,
        0,
        0,
        0,
        0,
        0,
        0,
            ]
prom_sexo_m = [
        0,
        0,
        1,
        1,
        0,
        0,
        0,
        0,
        0,
            ]

A: El calculo del promedio seria el siguiente:
promedio = suma de los elementos / la cantidad de esos elementos.
Prueba con el siguiente código:
sustituye tu código //RECORRO EL ARRAY por este código
    let prom_edad = [];
    let prom_sexo_h = [];
    let prom_sexo_m= [];
    let suma_edades;
    let cont_sexo_h;
    let cont_sexo_m;

    filtrados.forEach( item => {
      console.log("Arreglo #" + item);
      item.forEach(elemento => {
        // sumas las edades
        suma_edades = suma_edades + elemento['age'];
        // verificas si es hombre o mujer
        if (elemento['sexo'] === 'hombre') {
          // en caso de ser hombre incrementas el contador de hombres
          cont_sexo_h++;
        } else {
          // en caso de ser mujer incrementas el contador de mujeres
          cont_sexo_m++;
        }
      });
      //se agrega el promedio con push(dentro de push se calcula el promedio)
      prom_edad.push(suma_edades / elemento.length);
      prom_sexo_h.push(cont_sexo_h / elemento.length);
      prom_sexo_m.push(cont_sexo_h / elemento.length);
      console.log('El promedio de edad es de: ', prom_edad);
      console.log('El promedio de hombres es de: ', prom_sexo_h);
      console.log('El promedio de mujeres es de: ', prom_sexo_m);
    });


text:
Q: Incosistent behaviour of List property public class Foo
{
    public static List<long> myList = new List<long>() { 1,2,3 }
}

In another method:
var testList = Foo.myList;

If I put a breakpoint at the last line and inspect testList it gives me different lengths from time to time.
When I use ToList() on Foo.myList it seems to behave correctly. But why?
Edit:
My problem was that I made an ajax call > modified Foo.myList > new ajax call > fetched Foo.myList again and got the modified value.

A: Race condition on shared state. The static field member means there's one copy, so if you manipulate the list in your code, it changes for ALL threads using the property. ToList() works because it creates a copy of the list which won't alter the original list, but note that this copy also points to the same objects as the original list if the objects are reference types. Therefore altering the reference types in the copy would also alter the values in the original list... but since long is a value type that won't apply here.
If you want your list to be read-only http://msdn.microsoft.com/en-us/library/e78dcd75.aspx

A: It sounds like you're modifying Foo.myList or a reference to it somewhere. Note that assigning the list to a local variable does not make a copy. Thus:
var list = new List<long> { 1, 2, 3 };
var testList = list;
testList.Add(4); // list is now [1, 2, 3, 4]
list.Add(5); // testList is now [1, 2, 3, 4, 5]

ToList(), on the other hand, makes a copy. In general, it's probably safest to make any static lists read only (if that's the semantics you want) to prevent this from happening accidentally:
public class Foo {
    // pre .NET 4.5, use ReadOnlyCollection<T> (which implements IList<T>)
    public static readonly IReadOnlyList<long> myList = new List<long> { 1, 2, 3 }.AsReadOnly();
}

var testList = Foo.myList.ToList(); // get an editable copy
var testList2 = Foo.myList; // get a reference to the immutable static list


text:
Q: How to design a smooth UI scroll inside Update() for a Unity VR application? I am developing a VR application in Unity and I am struggling to develop a smooth UI scroll using my VR controller's joystick. So far what I have looks like this...
private void Update()
{
    float joyStickDirection = globals.menuInteraction_Scroll.GetAxis(SteamVR_Input_Sources.Any).y; // this is either 1 for up or -1 for down
    if (joyStickDirection != 0)
    {
        float multiplier = joyStickDirection * 5f;
        scrollRect.verticalNormalizedPosition = scrollRect.verticalNormalizedPosition + (multiplier * Time.deltaTime);
    }
}

...this works, but has two problems. Firstly, it scrolls at different speeds depending how big the scrolling container is. Secondly, the scrolling is not very smooth, as it is clearly just skipping varying gaps between 0 and 1.
I think I know what's wrong but I don't have enough experience working inside Update() to figure out the correct approach. Can anyone advise?

A: Actually you don't necessarily go through the ScrollRect component itself.
I usually would simply do
public class ScrollExample : MonoBehaviour
{
    public float speed = 5f;

    public Transform ScrollContent;

    void Update()
    {
        // this is either 1 for up or -1 for down
        var joyStickDirection = globals.menuInteraction_Scroll.GetAxis(SteamVR_Input_Sources.Any).y;
        if (joyStickDirection != 0)
        {
            var multiplier = joyStickDirection * speed;

            // You want to invert the direction since scrolling down actually means
            // moving the content up
            ScrollContent.position -= Vector3.up * multiplier * Time.deltaTime;
        }
    }
}

The ScrollRect then updates and handles the rest itself. The speed is in Units/seconds or in a Screenspace Overlay canvas in pixels per seconds regardless of how big the content is.
Usually you would want to adjust the elasticity of the ScrollRect or simply set the Movement Type to Clamped right away.


text:
Q: How to create a data analysis template (lavaan parameter table) using simsem package R? I am unfamiliar with simsem package for SEM simulations, and would like some help with it.
I would like to create a data analysis template (lavaan parameter table) for simulations with structural equation models and then perform simulation with real data.
I have found the example for this:
loading <- matrix(0, 9, 3)
loading[1:3, 1] <- NA
loading[4:6, 2] <- NA
loading[7:9, 3] <- NA
cfamodel <- estmodel(LY=loading, modelType="CFA", indLab=paste("x", 1:9, sep=""))

out <- analyze(cfamodel, HolzingerSwineford1939)

datamodel.nomis <- model.lavaan(out, std=TRUE)

output.nomis <- sim(1000, n=nrow(HolzingerSwineford1939), datamodel.nomis)
summary(output.nomis)

However, the creation of lavaan parameter table is a bit confusing (the definition of 'cfamodel' variable), especially, if for example exogenous variables or regressions are included in SEM model.
My SEM model is as per below. It includes 23 free parameters (5 factor loadings, 9 covariances between latent variable indicators, 3 regressions, 6 variances) and two defined (variance of the latent variable and indirect effect).
graphical representation of SEM model
FullModel=
  "
# Latent variable definition
IWB =~ NOVE+EXPL+TEST+SUPP+IMPL

#Direct effects
IWB ~ OSE

#Medation
IWB ~ g*WE
WE ~ h*OSE

#Indirect effect
gh:=g*h

#Covariances
NOVE ~~ EXPL + SUPP + IMPL
EXPL ~~ TEST + SUPP + IMPL
TEST ~~  SUPP + IMPL
SUPP ~~ IMPL
"

As by the example I would start with:
loading <- matrix(0, 5, 1)
loading[1:5, 1] <- NA
cfamodel <- estmodel(LY=loading, modelType="CFA")

But then I have no idea, how to define the rest of the parameters?


text:
Q: Why does this array destructuring not work when assigning to 'this'? I have a class that runs a function cloneButtons during construction. The cloneButtons function takes an array oldButtons and returns an array newButtons of the same exact elements. My problem is that I'm encountering weird behavior when I try to deconstruct the array. Whenever I use this to make a class assignment, things just stop working.
I'm new to JS but can't find any documentation about limitations of using this and why it wouldn't work when destructuring the return value of a function.
Here are some examples of what works and what doesn't. The following code works as intended: the elements in cloneButtons deconstructs without issue.
constructor () {

    const oldButtons = document.querySelectorAll('#hero-action-btn-cont button')
    const [attackBtn, healBtn, specialBtn] = Utils.cloneButtons(oldButtons)
    attackBtn.addEventListener('click', this.attackHandler.bind(this))

// this works perfectly

}

However, if I try to assign the array elements using this while destructuring at any step in the process I get a variety of errors, all stemming from the fact that whatever variable has this remains undefined. This throws an initialization error:
  constructor () {

    const oldButtons = document.querySelectorAll('#hero-action-btn-cont button')
    [this.attackBtn, this.healBtn, this.specialBtn] = Utils.cloneButtons(oldButtons)
    this.attackBtn.addEventListener('click', this.attackHandler.bind(this))

// cannot access oldButtons before initialization
  }

Another method that does not work:
  constructor () {

    const oldButtons = document.querySelectorAll('#hero-action-btn-cont button')
    this.newButtons = Utils.cloneButtons(oldButtons)
    [this.attackBtn, this.healBtn, this.specialBtn] = this.newButtons
    this.attackBtn.addEventListener('click', this.attackHandler.bind(this))

// this.attackBtn is undefined
  }

To help id what going wrong here's another scenario that works perfectly, which involves no destructuring:
constructor () {

    const oldButtons = document.querySelectorAll('#hero-action-btn-cont button')
    this.newButtons = Utils.cloneButtons(oldButtons)
    this.newButtons[0].addEventListener('click', this.attackHandler.bind(this))

//works but does not use destructuring

  }

Additionally, I cannot even run this.oldButtons = document.querySelectorAll(#id) as this for some reason returns undefined. What am I missing here?!


text:
Q: OpenCV - Two completely different images are having more matches using BFMatcher I have a picture of some cups
and a picture of a cat
I want to compare these two pictures in OpenCV using surf and match them using BFMatcher.
Here is the code:
//read the image
cv::Mat image1= cv::imread("C:\\Users\\The\\Desktop\\cub.jpg");
cv::Mat image2= cv::imread("C:\\Users\\The\\Desktop\\cat.jpg");
//detect the key points using surf
cv::SurfFeatureDetector surf(300,4,2,true,false);
   //image 1 key points
vector<cv::KeyPoint> image1Keypoints;
//detect the key points in image 1 using surf
surf.detect(image1,image1Keypoints);
//draw the keypoints of image1
cv::drawKeypoints(image1,image1Keypoints,image1,
  cv::Scalar(255,255,255),cv::DrawMatchesFlags::DRAW_OVER_OUTIMG);
cv::namedWindow("Original image 1 with keypoints");
cv::imshow("Original image 1 with keypoints",image1);
// image 2 key points
std::vector<cv::KeyPoint> image2keypoints;
//detect the key points in image 1 using surf
 surf.detect(image2,image2keypoints);
 //draw the key points
 cv::drawKeypoints(image2,keypoints1,image2,
      cv::Scalar(255,255,255),cv::DrawMatchesFlags::DRAW_OVER_OUTIMG);
 //the extracted image display
cv::namedWindow("image 2 with keypoints");
cv::imshow("image 2 with keypoints",image2);

From the above code this the cups image features
and the cat image features:
cv::SiftDescriptorExtractor sift;
cv::Mat image1Descriptor;
cv::Mat image2Desccriptor;
sift.compute(image1,
             image1Keypoints,
             image1Descriptor);
sift.compute(image2,
             keypoints1,
             image2Desccriptor);
 cv::BFMatcher matcher(cv::NORM_L2,true);
std::vector<cv::DMatch> matches;
matcher.match(image2Desccriptor,image1Descriptor,matches);
cout<<"match=";
//the number of matched features between the two images
cout<<matches.size()<<endl;
cv::Mat imageMatches;
cv::drawMatches(image2,keypoints1,image1,image1Keypoints,
   matches,imageMatches,cv::DrawMatchesFlags::DRAW_OVER_OUTIMG);
cv::namedWindow("matches");
cv::imshow("matches",imageMatches);
cv::waitKey(0);

What really confused me is the matched picture:
There are around 833 matched features but the images are completely different.
What is wrong with my code & how can i decrease the number of matches. I was able to decrease the number of matches by changing the surf parameters but it is because it detect small number of features. For example by changing the siftFeature detector to this:
cv::SurfFeatureDetector surf(1000,4,2,true,false);
I was able to get matches=77 but still it is a high number of matches and the matches are decreased because I was getting small number of features compared to the above numbers.

A: You should check this answer.
Typically, BruteForce will return the distance between two matches. The lower the distance between two features, the similar they are. By applying a threshold onto these distances will help you remove false positive matches.
However, feature matches by itself will not guarantee that the objects in two images will be the same. To do this kind of verification you need to go a bit further on your implementation and (for instance) geometrically verify the positive matches with an Homography.


text:
Q: TypeError: not all arguments converted during string formatting - sqlite Python 3.7.3
I cannot format output of result function. For example, if you just only use print result, you will see all data of come back. If you use a loop to get all types of values to identifying is or not strings values:
for i in result:
    print(type(result))

You will see all values as str:
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

I've tried to print each number of position of a tuple but It's does not work. I get this error when I trying do it:
print(Messages.issue_found + "ID : %s o %s" % result[0], result[1])

Traceback (most recent call last):
  File "/home/sincorchetes/Projects/PyArea/sqlite/run.py", line 16, in <module>
    print(Messages.issue_found + "ID : %s o %s" % result[0], result[1])
TypeError: not enough arguments for format string

This is code:
Ops.py
import sqlite

def search_a_object(type_request):
        conn = connection()
        run = conn.cursor()
        try:
                type_request = (type_request,)
                query = run.execute('SELECT * FROM Object WHERE id=?', type_request)
                get_results = query.fetchone()
                if get_results is None:
                       print("Sorry, This object was not found")
                else:
                        #print(get_results)
                        return get_results
        except:
                print("Sorry, something was wrong :(")

run.py
import ops as Ops
import msg as Messages
request_id = input(Messages.get_request_id)
        if (request_id is not None and request_id):
            result = Ops.search_a_object(request_id)
            print(Messages.issue_found + "ID : %s o %s" % result)
#   I have problems with this line formatting ^
        else:
            print(Messages.need_more_data)

If I use code as up I get:
Traceback (most recent call last):
  File "/home/sincorchetes/Projects/PyArea/sqlite/run.py", line 16, in <module>
    print(Messages.issue_found + "ID : %s o %s" % result)
TypeError: not all arguments converted during string formatting

Although all values are strings inside tuple.

A: use
print(Messages.issue_found + "ID : %s o %s" % (result[0], result[1]))

or
print( "ID : {} o {}".format(result[0], result[1]))


text:
Q: Type mismatch in variable assignment to generics based variable Does anyone know why C# doesn't seem to like the following bit of code?
The issue is that MyContext cannot be assigned to the _context variable due to its type mismatch, however MyContext derives (inherits?) from DbContext, so that should satisfy the generics where clause, surely?
public class UnitOfWork<TContext> : IUnitOfWork<TContext> where TContext : DbContext
{
    private TContext _context;

    public UnitOfWork()
    {
        _context = new MyContext(Common.ConfigurationProvider.DatabaseConnectionString);
    }
...

}

A: This is not allowed because where TContext : DbContext constraint promises that TContext will be of DbContext and not MyContext.
In other words TContext may be MyContext2 which have no inheritance relationship with MyContext. So compiler is not happy with that :(
If you're going to use specific context MyContext then IMO you don't need generics.

Edit: If you're sure that your context will be descendant of type argument(TContext) then you can play a trick to make it work,

public UnitOfWork()
{
    _context = (TContext)(object)new MyContext(...);
}

but, I will think twice before using this in production code. This will fail if MyContext is not TContext or descendant of it.

A: TContext could be another type inheriting from DbContext incompatible with the type of MyContext.