text:
Q: ArgumentCountError : Too few arguments to function phpunit I'm trying to create some programmed tests using phpUnit.
I need to use a Data provider, but every time I try, it throws an error.
I'm even using the example given in the documentation of phpUnit.
 /**
 * @dataProvider additionWithNonNegativeNumbersProvider
 */
public function testAdd($a, $b, $expected)
{
    $this->assertSame($expected, $a + $b);
}

public function additionWithNonNegativeNumbersProvider()
{
    return [
        [0, 1, 1],
        [1, 0, 1],
        [1, 1, 3]
    ];
}

I expect the output to be:
There was 1 failure:
1) DataTest::testAdd with data set #3 (1, 1, 3)
Failed asserting that 2 is identical to 3.

But it is:
ArgumentCountError : Too few arguments to function controllerTests::testAdd(), 0 passed in phar://C:/xampp/htdocs/2019-1-qa-grupo1/myss/Tests/phpunit-8.1.2.phar/phpunit/Framework/TestCase.php on line 1172 and exactly 3 expected
 C:\xampp\htdocs\2019-1-qa-grupo1\myss\Tests\controllerTests.php:55

A: You need to pass the optional arguments to the parent constructor.
If you have this in your test class:
<?php
public function __construct() {
    // Some constructor code.
}

Change it to:
<?php
public function __construct($name = null, array $data = [], $dataName = '') {
    parent::__construct($name, $data, $dataName);
    // Some constructor code.
}


text:
Q: Unit Testing - Ignore culture when binding assembly I'm very new to unit testing in C#. I added a test project with Visual Studio, but when I try to run tests, they fail, complaining about assembly binding failures.
So I enabled logging and noticed that the tests are trying to load my DLLs from a culture-specific directory (one that doesn't exist).
E.g. if the test project's DLL exists in C:\MyProject\, it looks for the assembly under test in C:\MyProject\en-GB\.
The only reference anywhere to en-GB is the assembly culture attribute of the assembly under test. If I change that attribute's value to say, en-US, the unit test binder searches for the DLL in /en-US/
Can I somehow specify that I do not want this behaviour?

A: from the documentation,

The attribute is used by compilers to distinguish between a main assembly and a satellite assembly. A main assembly contains code and the neutral culture's resources. A satellite assembly contains only resources for a particular culture, as in [assembly:AssemblyCultureAttribute("de")]. Putting this attribute on an assembly and using something other than the empty string ("") for the culture name will make this assembly look like a satellite assembly, rather than a main assembly that contains executable code. Labeling a traditional code library with this attribute will break it, because no other code will be able to find the library's entry points at runtime.

so basically, don't use that attribute.  are you actually testing a localized satellite assembly?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python thread not listening to flag I'm using a slightly edited example from here. The start button in the GUI starts a thread, the stop button stops it. I've added an x = x+1 and a print(x) to the loop, that works too. But if I try to bring x to the GUI, the stop button stops working. I don't understand why. Can you explain it to me?
The code is below. Running it like this will give you the result after stopping the thread. Uncommenting line 48 will give you the result every 1 second, but the stop button will stop working.
import time
from threading import *
import wx

# Button definitions
ID_START = wx.NewId()
ID_STOP = wx.NewId()

# Define notification event for thread completion
EVT_RESULT_ID = wx.NewId()

def EVT_RESULT(win, func):
    """Define Result Event."""
    win.Connect(-1, -1, EVT_RESULT_ID, func)

class ResultEvent(wx.PyEvent):
    """Simple event to carry arbitrary result data."""
    def __init__(self, data):
        """Init Result Event."""
        wx.PyEvent.__init__(self)
        self.SetEventType(EVT_RESULT_ID)
        self.data = data
        pass

# Thread class that executes processing
class WorkerThread(Thread):
    """Worker Thread Class."""
    def __init__(self, notify_window):
        """Init Worker Thread Class."""
        Thread.__init__(self)
        self._notify_window = notify_window
        self._want_abort = 0
        # This starts the thread running on creation, but you could
        # also make the GUI thread responsible for calling this
        self.start()

    def run(self):
        """Run Worker Thread."""
        # This is the code executing in the new thread. Simulation of
        # a long process (well, 10s here) as a simple loop - you will
        # need to structure your processing so that you periodically
        # peek at the abort variable
        x=0
        for i in range(10):
            x = x + 1
            time.sleep(1)
            print(x)
            #wx.PostEvent(self._notify_window, ResultEvent(x))
            if self._want_abort:
                # Use a result of None to acknowledge the abort (of
                # course you can use whatever you'd like or even
                # a separate event type)
                wx.PostEvent(self._notify_window, ResultEvent('ended with ' + str(x)))
                return
        # Here's where the result would be returned (this is an
        # example fixed result of the number 10, but it could be
        # any Python object)
        wx.PostEvent(self._notify_window, ResultEvent(10))

    def abort(self):
        """abort worker thread."""
        # Method for use by main thread to signal an abort
        self._want_abort = 1

# GUI Frame class that spins off the worker thread
class MainFrame(wx.Frame):
    """Class MainFrame."""
    def __init__(self, parent, id):
        """Create the MainFrame."""
        wx.Frame.__init__(self, parent, id, 'Thread Test')

        # Dumb sample frame with two buttons
        wx.Button(self, ID_START, 'Start', pos=(0,0))
        wx.Button(self, ID_STOP, 'Stop', pos=(0,50))
        self.status = wx.StaticText(self, -1, '', pos=(0,100))

        self.Bind(wx.EVT_BUTTON, self.OnStart, id=ID_START)
        self.Bind(wx.EVT_BUTTON, self.OnStop, id=ID_STOP)

        # Set up event handler for any worker thread results
        EVT_RESULT(self,self.OnResult)

        # And indicate we don't have a worker thread yet
        self.worker = None

    def OnStart(self, event):
        """Start Computation."""
        # Trigger the worker thread unless it's already busy
        if not self.worker:
            self.status.SetLabel('Starting computation')
            self.worker = WorkerThread(self)

    def OnStop(self, event):
        """Stop Computation."""
        # Flag the worker thread to stop if running
        if self.worker:
            self.status.SetLabel('Trying to abort computation')
            self.worker.abort()

    def OnResult(self, event):
        """Show Result status."""
        if event.data is None:
            # Thread aborted (using our convention of None return)
            self.status.SetLabel('Computation aborted')
        else:
            # Process results here
            self.status.SetLabel('Computation Result: %s' % event.data)
        # In either event, the worker is done
        self.worker = None

class MainApp(wx.App):
    """Class Main App."""
    def OnInit(self):
        """Init Main App."""
        self.frame = MainFrame(None, -1)
        self.frame.Show(True)
        self.SetTopWindow(self.frame)
        return True

if __name__ == '__main__':
    app = MainApp(0)
    app.MainLoop()

A: You have found the classic example but it is now very dated. Either look for a modern example or pick the bones out of the following:
import time
import wx
from threading import Thread

import wx.lib.newevent
progress_event, EVT_PROGRESS_EVENT = wx.lib.newevent.NewEvent()

class ThreadFrame(wx.Frame):

    def __init__(self, title, parent=None):
        wx.Frame.__init__(self, parent=parent, title=title)
        panel = wx.Panel(self)
        self.btn = wx.Button(panel,label='Stop Long running process', size=(200,30), pos=(10,10))
        self.btn.Bind(wx.EVT_BUTTON, self.OnExit)
        self.progress = wx.Gauge(panel,size=(240,10), pos=(10,50), range=240)

        #Bind to the progress event issued by the thread
        self.Bind(EVT_PROGRESS_EVENT, self.OnProgress)
        #Bind to Exit on frame close
        self.Bind(wx.EVT_CLOSE, self.OnExit)
        self.Show()

        self.mythread = TestThread(self)
        #Enable the GUI to be responsive by briefly returning control to the main App
        while self.mythread.isAlive():
            time.sleep(0.1)
            wx.GetApp().Yield()
            continue

        try:
            self.OnExit(None)
        except:
            pass

    def OnProgress(self, event):
        self.progress.SetValue(event.count)
        #or for indeterminate progress
        #self.progress.Pulse()

    def OnExit(self, event):
        if self.mythread.isAlive():
            self.mythread.terminate() # Shutdown the thread
            self.mythread.join() # Wait for it to finish
        self.Destroy()

class TestThread(Thread):
    def __init__(self,parent_target):
        Thread.__init__(self)
        self.parent = parent_target
        self.stopthread = False
        self.time = time.time()
        self.start()    # start the thread

    def run(self):
        # A loop that will run for 2 minutes then terminate
        while self.stopthread == False:
            curr_loop = int(time.time() - self.time)
            if curr_loop < 240:
                time.sleep(0.1)
                evt = progress_event(count=curr_loop)
                #Send back current count for the progress bar
                try:
                    wx.PostEvent(self.parent, evt)
                except: # The parent frame has probably been destroyed
                    self.terminate()
            else:
                self.terminate()

    def terminate(self):
        self.stopthread = True

class MyPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.text_count = 0
        self.thread_count = 0
        self.parent=parent
        btn = wx.Button(self, wx.ID_ANY, label='Start Long running process', size=(200,30), pos=(10,10))
        btn.Bind(wx.EVT_BUTTON, self.Thread_Frame)
        btn2 = wx.Button(self, wx.ID_ANY, label='Is the GUI still active?', size=(200,30), pos=(10,50))
        btn2.Bind(wx.EVT_BUTTON, self.AddText)
        self.txt = wx.TextCtrl(self, wx.ID_ANY, style= wx.TE_MULTILINE, pos=(10,90),size=(400,100))

    def Thread_Frame(self, event):
        self.thread_count += 1
        frame = ThreadFrame(title='Threaded Task '+str(self.thread_count), parent=self.parent)

    def AddText(self,event):
        self.text_count += 1
        txt = "Gui is still active " + str(self.text_count)+"\n"
        self.txt.write(txt)

class MainFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Main Frame', size=(600,400))
        panel = MyPanel(self)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()


text:
Q: C# Debug and Release .exe behaving differently because of Long? After reading these questions:
Code is behaving differently in Release vs Debug Mode
C# - Inconsistent math operation result on 32-bit and 64-bit
Double precision problems on .NET
Why does this floating-point calculation give different results on different machines?
I suspect that the reason my method for determining FPS which works while in Debug mode and no longer works in Release mode is because I'm using Long to hold time values. Here's the relevant code:
public void ActualFPS()
    {
        if (Stopwatch.GetTimestamp() >= lastTicks + Stopwatch.Frequency)
        {
            actualFPS = runsThisSecond;
            lastTicks = Stopwatch.GetTimestamp();

            runsThisSecond = 0;
        }
    }

runsThisSecond is incremented by one every time the method I'm tracing is called. Granted this isn't an overly accurate way to determine FPS, but it works for what I need it to.
lastTicks is a variable of type Long, and I believe that Stopwatch.GetTimestamp() is returned as a Long as well(?). Is this my problem? If so: any suggestions as to how to work around this?
EDIT: Stopwatch is using the High Resolution timer.
EDIT2: The problem has resolved itself. Without any changes to any of my code. At all. None. I have no idea what caused it to break, or to fix itself. Perhaps my computer decided to spontaneously consider my feelings?

A: You have a very accurate interval measurement available (gettimestamp - lastticks), but you are not using it all to compute the frame rate.  You assume the interval is a second, it won't be.  It will be more, by a random amount that's determined by how often you call ActualFPS().  In Release mode you'll call ActualFPS() more frequently so the error is less.
Divide runsThisSecond by (gettimestamp - lastticks) converted to seconds.


text:
Q: open binary file of 16 bit integers written by a c program as 1s and 0s in python I have a bitstream file that is comprised of several lines. The c program executable that produces the file outputs the file as a series of "short int" which are actually 16 bit integers. When I open the file in notepad I get the following first few lines:
7E1755EB7909DAC8FF4117BDAA0E86EBD1A8
1C3D47DD6606D812E8862D347288C3A251EB
16D7D02AD908E0083C142C107AB916C55BE0

I need to be able to open this file in Python and convert it to 1s and 0s that represent the original "short int" or in other words an array of 1s and 0s. I think I might also have an issue with the "\n" meaning new line when I read in the file.
I've tried the following code to see which method works best:
import struct

filePathC = "C:\\Working\\Vocoder Sims\\ofile.chan"

fileC = open(filePathC, "rb")

with fileC:

    byteC = fileC.read(8)

    binaryC1 = bin(int(byteC,16))
    binaryC2 = struct.unpack("h" * (len(byteC)/2),byteC)

    print binaryC1
    print binaryC2

The result for when I only read in the first 8 bytes is:
0b1111110000101110101010111101011
(17719, 14129, 13621, 16965)

The issue with the first result is that I should be getting 64 1s and 0s and the problem with the second is that it "tuple" instead of an array of 1s and 0s and I don't believe the integers are 16 bit based. They look more like 15 bit but I'm not sure.
Thanks in advance for any help.

A: Assuming you have binary data that just happens to decode as ascii hex, you could read the file into a python array. Its not much different than your second example of unpacking into a tuple except that its faster and has a lower memory footprint. Depending on what you want to do next, it would be reasonable to read into a numpy array instead.
import os
import array

#filePathC = "C:\\Working\\Vocoder Sims\\ofile.chan"
filePathC = "test.bin"

count = os.stat(filePathC).st_size / 2
with open(filePathC, 'rb') as fp:
    binaryC3 = array.array("h")
    binaryC3.fromfile(fp, count)

print binaryC3
print bin(binaryC3[0])

For your example file, this gave me
array('h', [17719, 14129, 13621, 16965, 14647, 14640, 16708, 14403, 17990, 12596, 14129, 17474, 16705, 17712, 13880, 16965, 12612, 14401, 12554, 13123, 13380, 17463, 13892, 12342, 17462, 12600, 17714, 14392, 12854, 13124, 14132, 14386, 17208, 16691, 13618, 17713, 2626, 13873, 14148, 12356, 16690, 14660, 14384, 12357, 14384, 17203, 13361, 17202, 12337, 16695, 14658, 13873, 13635, 16949, 12357])
0b100010100110111


text:
Q: Go Lambda with Full Access Policy 403 Access Denied on S3 PutObject I'm attempting to upload a file to an S3 bucket via Lambda in Go. I am able to read objects from the bucket with no issues, but I get Access Denied errors whenever I try to upload an object to the bucket.
To debug, I created the following simple Lambda function:
package main

import (
    "bytes"
    "context"
    "log"

    "github.com/aws/aws-lambda-go/lambda"
    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/service/s3"
)

func LambdaMainWrapper() {
    data := []byte("this is some data stored as a byte slice in Go Lang!")

    // convert byte slice to io.Reader
    reader := bytes.NewReader(data)

    // upload to s3
    client := s3.New(s3.Options{Region: "us-east-2"})
    putObjectInput := &s3.PutObjectInput{
        Bucket: aws.String(<MY_BUCKET_NAME>),
        Key:    aws.String("test-file"),
        Body:   reader,
    }
    res, err := client.PutObject(context.Background(), putObjectInput)
    if err != nil {
        log.Fatal("Error uploading object to S3: ", err)
    }

    log.Println("[s3 res]", res)
}

func main() {
    lambda.Start(LambdaMainWrapper)
}

And here is the attached policy on the execution role for the function, which to my understanding grants it all the permissions it would need to upload an object to the bucket:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "ExampleStmt",
            "Action": [
                "s3:GetObject"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::<MY_BUCKET_NAME>/*"
            ]
        },
        {
            "Sid": "ExampleStmt2",
            "Action": [
                "s3:PutObject"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::<MY_BUCKET_NAME>/*"
            ]
        },
        {
            "Sid": "ExampleStmt3",
            "Action": [
                "s3:PutObjectAcl"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::<MY_BUCKET_NAME>/*"
            ]
        }
    ]
}

Lambda reports back:
START RequestId: XXX Version: $LATEST
2022/01/25 16:39:06 Error uploading object to S3: operation error S3: PutObject, https response error StatusCode: 403, RequestID: XXXXXXXXXX, HostID: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX, api error AccessDenied: Access Denied
2022/01/25 16:39:06 unexpected EOF
2022/01/25 16:39:06 unexpected EOF
END RequestId: XXX

I'm struggling to root cause this as an error with my Go S3 client configuration or if I've configured permissions within AWS incorrectly. It could even be that I'm sending the Body of the object incorrectly - which might explain the unexpected EOF messages. Any help is much appreciated, thanks!
e: using local S3 client (no lambda), I was able to succesfully upload and download objects from S3.

A: Turns out the issue was credentials. The bucket I am accessing allows public read access, hence why my GetObject calls were working. However, it does not allow public write access, so PutObject calls were resulting in 403 Access Denied ♂ I assumed my GetObject calls were authenticated, but you know what they say about assuming...
The fix was simply changing
// upload to s3
client := s3.New(s3.Options{Region: "us-east-2"})

to
cfg, err := config.LoadDefaultConfig(context.TODO())
cfg.Region = "us-east-2"
client := s3.NewFromConfig(cfg)

thanks @jarmod for making me realize I should attempt to use the lambda function's local default config, as one does when running on localhost !


text: Q: Разрешить http iframe на https страницах Есть сайт на https, когда iframe подгружает другой сайт с поддержкой https, то отображает нормально, а если http, то браузер пишет смешанный контент. Нужно сделать так, чтобы можно было загружать любые сайты и с http и https на сайте с https. Как это можно сделать?


text:
Q: Why am I consuming so much CPU and none of the GPU? I am working with Houdini (a 3d software) on a computer with an Intel Core i5-8400 2.80GHz and a NVIDIA GeForce GTX 1060 3GB.
My issue is that Houdini is consuming all my CPU but nearly none of my GPU. It also happens when I run other programs like Blender, Unity or any other 3D software.
I've tryed installing the NVIDIA studio-ready drivers, with similar results. I'm sure that using a 3D software, I should be able to speed up the process with my GPU, but I can´t get it working.
Can someone tell me what I need to do to "enable" my GPU, please?
Here is a screenshot of my task manager running a stressful task in Houdini:

A: Only specific parts of 3D app actually use the GPU.  The most obvious part is the 3D viewports but other parts might be optimized to utilize the GPU for simulation and rendering etc.  However 90%+ of Houdini/Maya/3DS Max etc still just uses CPU and most of that is still single threaded so you wont even have full CPU usage.


text:
Q: Mean and variance of Squared Gaussian: $Y=X^2$ where: $X\sim\mathcal{N}(0,\sigma^2)$? What is the mean and variance of Squared Gaussian: $Y=X^2$ where: $X\sim\mathcal{N}(0,\sigma^2)$?
It is interesting to note that Gaussian R.V here is zero-mean and non-central Chi-square Distribution doesn't work.
Thanks.

A: We can avoid using the fact that $X^2\sim\sigma^2\chi_1^2$, where $\chi_1^2$ is the chi-squared distribution with $1$ degree of freedom, and calculate the expected value and the variance just using the definition. We have that
$$
\operatorname E X^2=\operatorname{Var}X=\sigma^2
$$
since $\operatorname EX=0$ (see here).
Also,
$$
\operatorname{Var}X^2=\operatorname EX^4-(\operatorname EX^2)^2.
$$
The fourth moment $\operatorname EX^4$ is equal to $3\sigma^4$ (see here). Hence,
$$
\operatorname{Var}X^2=3\sigma^4-\sigma^4=2\sigma^4.
$$

A: Note that $X^2 \sim \sigma^2 \chi^2_1$ where $\chi^2_1$ is the Chi-squared distribution with 1 degree of freedom. Since $E[\chi^2_1] = 1, \text{Var}[\chi^2_1] = 2$ we have $E[X^2] = \sigma^2, \text{Var}[X^2] = 2 \sigma^4$.


text:
Q: ReactiveVar not re-rendering React component I'm quite new to React in Meteor.
TL;DR : In my data container, changing the value of my ReactiveVar do not rerender my view.
I've got this code :
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';

// Mail composer - interface for generating enews
class MailComposer extends Component {
  constructor(props) {
    super(props);
  }

  handleSubmit( event ) {
    event.preventDefault();

    const text = this.refs.mailText.value.trim(),
          title = this.refs.mailTitle.value.trim(),
          rcpts = this.refs.mailRecpts.value.trim();

    console.log(text, title, rcpts);

    if ( text && title && rcpts ) {
      // ...
      this.props.hasTestedIt.set( true );
    } else {
      // ...
    }
  }

  componentDidMount () {
    console.log(this);
    $( this.refs.textArea ).autosize();
  }

  getBtnText () {
    return ( this.props.hasTestedIt.get() ? "Send it" : "Test it" );
  }

  render() {
    let self = this;
    Tracker.autorun(function(){
      console.log(self.props.hasTestedIt.get());
    });

    return (

Mail composer

          <form className="form-group" onSubmit={this.handleSubmit.bind(this)}>

              Title
              <input type="text" className="form-control" ref="mailTitle" />

            Recipients:
            <select className="form-control" width="width: initial;" id="js-recipients" ref="mailRecpts">
              <option>Admins</option>
              <option>All</option>
            </select>

            Text:
            <textarea className="form-control" rows="5" ref="mailText"></textarea>

            <button className="btn btn-primary" type="submit">
              {this.getBtnText()}
            </button>
          </form>

    );
  }
}

MailComposer.propTypes = {
  hasTestedIt: PropTypes.object.isRequired
};

export default createContainer( () => {
  return {
    hasTestedIt: new ReactiveVar( false )
  };
}, MailComposer);`

But when I set my ReactiveVar prop in my submit handler, the text returned by the getBtnText method in the button do not change. I've tried to put the ternary directly inside the HTML, but I got the same result.
The var is correctly setted to true, as the autorun correctly log me the change.
In another component, from which this one has been copied, I do correctly rerender the component, but using a .fetch() on a find to map the returned array in a renderTasks method which render a list of new components.
What am I missing please ? And how could I fix it ?
Thanks a lot !

A: The component doesn't update because the passed hasTestedIt prop is not changed itself. It's the value it holds that changed.
Watch the value you are actually interested in instead.
// Declare the reactive source somewhere appropriately.
const hasTestedIt = new ReactiveVar( false );

// Watch its value instead.
export default createContainer( () => {
  return {
    hasTestedIt: hasTestedIt.get()
  };
}, MailComposer);`

Note that it is now the value passed to MailComposer, not a ReactiveVar that can be referenced to update the value anymore. How do we update it in this case?
One simplest approach is to pass the hasTestedIt as well as before, though this wouldn't be my personal recommendation.
// Watch its value instead.
export default createContainer( () => {
  return {
    // Reactive source that triggers re-rendering.
    valueOfHasTestedIt: hasTestedIt.get(),
    // Provided for the contained component to reference to set new values.
    // Leaving this alone doesn't trigger re-rendering!
    hasTested
  };
}, MailComposer);

It's not elegant IMO. Another one is to pass a callback function to MailComposer which can be used to update the value.
const updateHasTestedIt = ( value ) => hasTestedIt.set( value );

// Watch its value instead.
export default createContainer( () => {
  return {
    hasTestedIt: hasTestedIt.get(),
    updateHasTestedIt,
  };
}, MailComposer);

class MailComposer extends Component {
  ...
  handleSubmit( event ) {
    ...
    this.props.updateHasTestedIt( true );
    ...
  }
  ...
};

It's better this time.
It is possible to develop more, but it really depends on your preference for your very application. You and only you can make the design decision.


text:
Q: Why isn't my reducer updating my store? I am new to redux and I am trying to create a solely redux app. The problem I am having is that my reducer won't update my store. If I were to mutate the store in the reducer then I would see my change. I know that is bad practice, so I am trying to update it without mutating it, but when I look at the console. I am seeing no change to the state. Can someone help me figure out why the reducer isn't updating the store?
This is my action:
store.subscribe(() => {
  console.log("store changed", store.getState());
});

Here is my reducer:
const fruitReducer = function(state={
  fruits: [
    {
      "itemName": "banana",
      "price": 1.00,
      "quantityRemaining": 10
    },
    {
      "itemName": "apple",
      "price": 2.00,
      "quantityRemaining": 5
    },
    {
      "itemName": "raspberry",
      "price": 5.00,
      "quantityRemaining": 2
    },
    {
      "itemName": "kiwi",
      "price": 3.00,
      "quantityRemaining": 15
    },
    {
      "itemName": "pineapple,
      "price": 7.00,
      "quantityRemaining": 1
    },
    {
      "itemName": "strawberries",
      "price": 2.00,
      "quantityRemaining": 3
    }
  ]
}, action){
  if(action.type === "DEDUCT"){
    return Object.assign({}, state, {
      fruits: state.fruits.map((fruit, index) => {
        action.payload.map((actionFruit) => {
          if(fruit.itemName === actionFruit.itemName){
            let newQuantity = fruit.quantityRemaining - actionFruit.quantityRemaining;
            return Object.assign({}, fruit, {
              quantityRemaining: newQuantity
            });
          }
        });
        return fruit;
      })
    });
  }
  else
    return state;
}

Below is an example of my dispatchers(I created two doing the same thing):
store.dispatch({type: "DEDUCT", payload: [
  {
    "itemName": "banana",
    "quantityRemaining": 1
  },
  {
    "itemName": "apple",
    "quantityRemaining": 1
  },
  {
    "itemName": "strawberries",
    "quantityRemaining": 1
  }
]});

A: One issue I see is that you're not actually returning the result of action.fruits.map().  Arrow functions allow you to omit the return keyword if you don't use curly braces, but once you add curlies, you've started the body of a function just like normal, and it's up to you to explicitly return something.
Also, as a stylistic note, I'd suggest defining the initial state for that reducer as a separate variable:
const initialState = [ /* fruits here */];

const fruitReducer = (state = initialState, action) => {
    // reducer logic here
}

It looks like your nested update logic is on the right track, but you may want to read through the Structuring Reducers - Immutable Update Patterns section of the Redux docs as well.

A: I found that this can happen by the way you compose your middleware.  For instance,  I previously had:
const store = createStore(
  rootReducer,
  applyMiddleware(epicMiddleware),
  composeEnhancers(applyMiddleware(...middleware))
)

However, it seems as though the double apply middleware made redux grumpy, and it wouldn't catch new state updates from the rootReducer, just the epicMiddleware (which is a fancy thing to trigger actions/reducers from side effects).
Moving my epicMiddleware into my applyMiddleware(...middleware) call resolved the issues.  That is, updating to the following worked:
const store = createStore(
  rootReducer,
  composeEnhancers(applyMiddleware(...middleware)) // epicMiddleware is now in the `middleware` array
)

It may not be your problem, but it is one thing that can cause your described symptom.


text:
Q: Multithreaded parsing is slower then sequential I am parsing 4 large XML files through threads and somehow the multithreaded code is slower then the sequential code?
Here is my multithreaded code:
  def parse():
    thread_list = []

    for file_name in cve_file:
        t = CVEParser(file_name)
        t.start()
        thread_list.append(t)

    for t in thread_list:
        t.join()
        result = t.result
        for res in result:
            print res
            PersistenceService.insert_data_from_file(res[0], res[1])
            os.remove(res[0])

and thats the "faster" code:
def parse:
thread_list = []

for file_name in cve_file:
    t = CVEParser(file_name)
    t.start()
    t.join()
    thread_list.append(t)

for t in thread_list:
    result = t.result
    for res in result:
        print res
        PersistenceService.insert_data_from_file(res[0], res[1])
        os.remove(res[0])

The sequential code is faster by 10 whole minutes, how is this possible?

A: Python uses the GIL (Global Interpreter Lock) to ensure only one thread executes Python code at a time. This is done to prevent data races and for some other reasons. That, however, means that multithreading in the default CPython will barely give you any code speedup (if it won't slow it down, as it did in your case).
To efficiently parallelize your workload, look into Python's multiprocessing module, which instead launches separate processes that are not affected by each other's GIL
Here's a SO question on that topic

A: Where did you read that multi-threading or even multi-processing should be always faster that sequential? That is simply wrong. Which one of the 3 modes is faster highly depends on the problem to solve, and where the bottleneck is.

*

*if the algo needs plenty of memory, or if processing multiple parralel operation requires locking, sequential processing is often the best bet

*if the bottleneck is IO, Python multithreading is the way to go: even if only one thread can be active at a time, the others will be waiting for io completion during that time and you will get a much better throughput - even if the really faster way is normally polling io with select when possible

*only if the bottleneck is CPU processing - which IMHO is not the most common use case - parallelization over different cores is the winner. In Python that means multi-processing (*). That mainly concerns heavy computations

In your use case, there is one other potential cause: you wait for the threads in sequence in the join part. That means that if thread2 ends much before thread0, you will only process it after thread0 has ended which is subobtimal.
This kind of code is often more efficient because it allows processing as soon as one thread has finished:
active_list = thread_list[:]
while len(active_list) > 0:
    for t in active_list:
        if not t.is_active():
            t.join()
            active_list.remove[t]
            # process t results
            ...
    time.sleep(0.1)

(*) Some libraries specialized in heavy or parallel computation can allow Python threads to run simultaneously. A well knows example for that is numpy: complex operations using numpy and executed in multiple threads can actually run simultaneously on different cores. Thechnically this means releasing the Global Interpreter Lock.

A: If you're reading these files from a spinning disk, then trying to read 4 at once can really slow down the process.
The disk can only really read one at a time, and will have to physically move the read/write head back and forth between them many many times to service different reading threads.  This takes a lot longer than actually reading the data, and you will have to wait for it.
If you're using an SSD, on the other hand, then you won't have this problem.  You'll probably still be limited by I/O speed, but the 4-thread case should take about the same amount of time as the single-thread case.


text: Q: How to refer bridges connecting two cycles? I would like to ask how to refer bridges connecting two cycles in a graph. I don't know if there is a special name for it, but it would be practical in spectroscopy.


text:
Q: $.post() function not working? I have tried for days and nights to find a solution. Nothing.
I know how $.post works, but for some reason it just doesn't.
This what I'm trying to do.

*

*Call the post function to a PHP page that queries the MySQL for a value (no input required).

*Set a <p> as this value.

Any suggestions? Much appreciated.
function refresh()
{
$.post("check.php",change(data));
}

function change(text)
{
getElementbyId('money').innerHTML=text;
}

A: Definitely not how post works...
$.post("check.php", change);

function change(text)
{
   document.getElementById('money').innerHTML = text;
}

A: Or even more simply...
$.post("check.php",change);

You don't want to call the change function when you're setting up your ajax call.  You want pass your callback function to $.post().

A: The error is calling getElementById without "document", you shoud use:
document.getElementById("money").innerHTML=text;

or (if you are using jQuery)
$("#money").html(text_value);

Try this code:
function refresh()
{
   $.post('check.php', function(data) {
     $("#money").html(data);
   });
}

refresh();

A: This is just a quickly done code up, but what about this?
function change(text)
{
document.getElementbyId('money').innerHTML=text;
}

$.post('check.php', change);

A: If you use a handler function you need to omit the argument and only provide the handler function name, or wrap the handler functionwith argument  in an anonymous function
$.post("check.php",change);

or
$.post("check.php",function(data){
   change(data)
);

A: Try this (test in http://jsfiddle.net/sRZ7z/1/ ):
    function refresh()
    {
         $.ajax({
              //replace your url
              url: '/echo/html/',
              type: 'POST',
              // you can delete "data" parameter if not needed
              // is only for testing ajax on jsfiddle addording to the documentation
              // http://doc.jsfiddle.net/use/echo.html
              data: {
                    html: "Test ajax"
              },
         }).done(function ( data ) {
              $("#money").html(data);
         });
    }

    $(document).ready(function() {
         refresh();
    });


text:
Q: Using geojson in a C# class with in ASP.NET core and MongoDB I'm trying unsuccessfully to create a MongoDB GeoJsonFeatureCollection from JSON in ASP.NET core.
(environment: MongoDB C# driver v2.10.2, ASP.NET core v3.1)
// a C# class which contains my geoJson features and intend to store in MongoDB
public class Route
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    public GeoJsonFeatureCollection<GeoJson2DCoordinates> Data { get; set; }
}

Then in the ASP.NET core controller, I'd like to have incoming JSON auto-converted to the Route class:
[HttpPost]
public ActionResult<Route> Create(Route route)  // FAILS HERE WITH NO PARAMETERLESS CONSTRUCTOR ERROR!
{
    _routeService.Create(route);  // send it off to MongoDB
    ...
}

I understand that this fails because MongoDB's GeoJsonFeatureCollection doesn't have a parameterless constructor,
so the incoming JSON can't be automatically mapped to the C# Route class.
But I can't seem to find an obvious workaround to this situation.
Possibilities I've considered:

*

*Skip trying to map to a C# class and just work with BsonDocuments for everything.
 It seems like querying becomes a bit more complex with this option, and I lose the power of C#.  Seems to be advocated here.

*Somehow add a custom serializer for GeoJsonFeatureCollection.  I have no idea how to do this, but there is a possibly relevant serializer provided in MongoDB:
https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Driver/GeoJsonObjectModel/Serializers/GeoJsonFeatureCollectionSerializer.cs

*Use a string to hold the geoJson Data in my C# class and perform the conversions manually:
public string Data { get; set; }
instead of:
public GeoJsonFeatureCollection<GeoJson2DCoordinates> Data { get; set; }
and then manually convert the string to a GeoJsonGeometryCollection via:
var geoCollection = BsonSerializer.Deserialize<GeoJsonGeometryCollection<TCoordinates>>(json);
but this seems ugly, requiring an extra JSON serialization in my javascript code and manual conversions in every HTTP endpoint.
What to do?


text:
Q: Does VB6 have the ability to "cast" an object as type "Printer"? Private Function SelectAPrinter(myName As String) As Printer

Dim strComputer As String
Dim objWMIService As Object
Dim myPrinter As Object

strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set myPrinter = objWMIService.ExecQuery("Select * from Win32_Printer where Name = '" & myName & "'")

Set SelectAPrinter = myPrinter

End Function

so of course VB6 barks at me with "type mismatch" which is no surprise. I am attempting to set an object
(myPrinter) to type Printer.
I DO NOT Know how to finish this function.
IS THERE a method of "casting" an object to type Printer?

A: If you do not mind setting the default printer temporarily, then perhaps the following will work.

Option Explicit

Private Sub Command1_Click()
    Dim saveme As String
    Dim yourprinter As Printer

    saveme = Printer.DeviceName

    Set yourprinter = SelectAPrinter("Canon iR-ADV C5045/5051 PCL5c")

    Debug.Print "selected", yourprinter.DeviceName ' Microsoft Print to PDF

    Call SelectAPrinter(saveme) ' restore default

    Debug.Print "restored", Printer.DeviceName
End Sub

Private Function SelectAPrinter(myName As String) As Printer

    Dim strComputer As String
    Dim objWMIService As Object
    Dim colInstalledPrinters As Object
    Dim myPrinter As Object

    strComputer = "."
    Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

    Set colInstalledPrinters = objWMIService.ExecQuery("Select * from Win32_Printer where Name = '" & myName & "'")
    For Each myPrinter In colInstalledPrinters
        myPrinter.SetDefaultPrinter
        Exit For
    Next

    Set SelectAPrinter = Printer

End Function

A: You can use a helper method to "cast" the object to a Printer.  However, the helper method does use the Printers collection:
Private Function SelectAPrinter(myName As String) As Printer
   Dim MyWMIService As Object
   Dim MyPrinters As Object
   Dim MyPrinter As Object

   Set MyWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
   Set MyPrinters = MyWMIService.ExecQuery("Select Name from Win32_Printer where Name = '" & myName & "'")

   For Each MyPrinter In MyPrinters
       Set SelectAPrinter = FindPrinter(MyPrinter.Name)
       Exit For
   Next
End Function

Private Function FindPrinter(ByVal DeviceName As String) As Printer
   Dim p As Printer

   For Each p In Printers
      If UCase(p.DeviceName) = UCase(DeviceName) Then
         Set FindPrinter = p
         Exit For
      End If
   Next
End Function


text:
Q: How do I update the entity with the foreign key? I have two entities as follows:
 public class Package
     {
            public int PackageId { get; set; }
            public int BusinessId { get; set; }

             public string Name { get; set; }
     }

And
   public class Business
     {

    public int BusinessId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    }

I want to edit the Package and update the related Business entity.  I've been trying the following:
    [HttpPost]
    public ActionResult Edit(Package package)
    {

        if (ModelState.IsValid)
        {

                db.Packages.Attach(new Package { PackageId=package.PackageId
       });

                db.Entry(package).State = EntityState.Modified;

                db.SaveChanges();

            return RedirectToAction("Index");
        }
        ViewBag.GenreId = new SelectList(db.Businesses , "BusinessId", "Name", package.BusinessId);
        return View(package);
    }

The code stops here with this message:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
I've been trying the example like the one here... http://blogs.msdn.com/b/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx... but I'm not sure what I'm doing wrong.
How do I update the entity with the foreign key?

A: [HttpPost]
public ActionResult Edit(int packageId)
{

    var package = db.Packages.FirstOrDefault(x=>x.Id == packageId);
    if(TryUpdateModel(package))
    {
        ...
        db.SaveChanges();
    }
}


text:
Q: count a very complex select mysql I have a very complex select that union 3 tables to show customer's last activities.
so:
select c.data, p.user, concat(c.user, ' buy your product') as logs from sell c inner join posts p on c.foto = p.id where p.user = ?
union all
select f.data, c.user, concat(c.user, ' asked you a question') as logs from questions f inner join cadastro c ON f.user = c.id where f.nick = ?
union all
select l.data, l.user, concat(l.user, ' like your product') as logs from likes l inner join posts p on l.post = p.id where p.user = ?
order by data desc

well, each of this tables has a row called SEEN. it is a varchar set with 0 or 1 (0 the user has not seen the message, 1 the user has already seen it).
What I want to add in this query is something to count the rows where seen = 0.
I want to show: YOU HAVE 4 new alerts.
select count(*) will not work and will not count right (the seen set to 1).
What can I do to count all this selects where seen = 0?

A: Try this
select a.*, SUM(IF(a.seen='0', 1, 0)) as 'unseen_count' FROM (
    select c.data, p.user, concat(c.user, ' buy your product') as logs, seen from sell c inner join posts p on c.foto = p.id where p.user = ?
    union all
    select f.data, c.user, concat(c.user, ' asked you a question') as logs, seen from questions f inner join cadastro c ON f.user = c.id where f.nick = ?
    union all
    select l.data, l.user, concat(l.user, ' like your product') as logs, seen from likes l inner join posts p on l.post = p.id where p.user = ?
) as a
order by data desc


text:
Q: Internet Explorer reports "content with security certificate errors" but only on one machine Good morning all!
I am a sysadmin with a medium-sized business. I'm in workstation support, not part of the web team or server support. I have a single user who gets an information bar at the bottom of IE every time he opens our own company's homepage:

Internet Explorer blocked this website from displaying content with security certificate errors.

I am pretty sure this is a workstation issue, and not serverside. I cannot replicate the problem on any of our other machines. The browser still navigates out to the site, it doesn't show the "There is a problem with this website's security certificate" page and try to block access.
I have opened the certificate by clicking on the padlock icon in IE and I can't see any warnings about the certificate. Did the same in Chrome and can't find any issues.
I did a Clear SSL State in IE on the user's machine, and the issue still isn't resolved. Other HTTPS sites work appropriately.
As this is our own URL, it is a trusted site in IE by group policy. I have checked that the same is true on the user's machine.
At this point I am not 100% sure that there isn't actually an issue I need to report to the web team. Nothing I have tried seems to be able to clear this single machine of the notion that something is wrong with that certificate but I can't confirm it either way.
The website's URL is https://www.ruffalonl.com/
Assuming nothing is wrong with the site or the certificate, does anyone know a way of suppressing the blasted message in IE? Either I make this message go away, or I am going to get a support ticket from this user that says something is wrong with the website every single day until I die.


text:
Q: Updating a ng-repeat filter after programmatically updating a text input I am using jQuery auto-complete to start filling in values for users who type into a text input.
<input type="text" ng-model="tags" name="tags" id="tags" value="" />

Later on my ng-repeat is filtering things based on that text
<div ng-repeat="ability in abilities | tagsFilter:tags">
 {{ ability }}
</div>

Inside jQuery auto-complete, there is a callback function for when a user selects an item from the auto-complete drop down.
    select: function( event, ui ) {
      var terms = split( this.value );
      // remove the current input
      terms.pop();
      // add the selected item
      terms.push( ui.item.value );
      // add placeholder to get the comma-and-space at the end
      terms.push( "" );
      this.value = terms.join( ", " );

      // I Want to tell angularJS to update

      return false;
    }

How would I tell my ng-repeat to update?
I tried looking into $scope.apply() but $scope is not in scope for the jQuery callback.

A: You should be able to access the scope from there.
Try this:
var scope = angular.element($('#tags')).scope();

scope.$apply(function() {
  // your apply function goes here
})


text:
Q: Importing many files at the same time and adding ID indicator I have 91 files - .log format:
rajectory Log File

Rock type: 2 (0: Sphere, 1: Cuboid, 2: Rock)

Nr of Trajectories: 91
Trajectory-Mode: ON
Average Slope (Degrees): 28.05 / 51.99 / 64.83

Filename: test_tschamut_Pos1.xml

Z-offset: 1.32000
Rock Position X: 696621.38
Rock Position Y: 167730.02
Rock Position Z: 1679.6400

Friction:
Overall Type: Medium

               t (s)               x (m)               y (m)               z (m)               p0 ()               p1 ()               p2 ()               p3 ()          vx (m s-1)          vy (m s-1)          vz (m s-1)        wx (rot s-1)        wy (rot s-1)        wz (rot s-1)           Etot (kJ)           Ekin (kJ)      Ekintrans (kJ)        Ekinrot (kJ)              zt (m)             Fv (kN)             Fh (kN)        Slippage (m)      mu_s (N s m-1)       v_res (m s-1)     w_res (rot s-1)           JumpH (m)        ProjDist (m)               Jc ()           JH_Jc (m)              SD (m)
               0.000          696621.380          167730.020            1680.960               1.000               0.000               0.000               0.000               0.000               0.000               0.000               0.000               0.000               0.000            1192.526               0.000               0.000               0.000            1677.754               0.000               0.000               0.000               0.350               0.000               0.000               3.206               0.000               0.000               0.000               0.000
               0.010          696621.380          167730.020            1680.959               1.000               0.000              -0.000               0.000               0.000               0.000              -0.098               0.000               0.000               0.000            1192.526               0.010               0.010               0.000            1677.754               0.000               0.000               0.000               0.350               0.098               0.000               3.205               0.000               0.000               0.000               0.000
               0.020          696621.380          167730.020            1680.958               1.000               0.000              -0.000               0.000               0.000               0.000              -0.196               0.000               0.000               0.000            1192.526               0.039               0.039               0.000            1677.754               0.000               0.000               0.000               0.350               0.196               0.000               3.204               0.000               0.000               0.000               0.000
               0.040          696621.380          167730.020            1680.952               1.000               0.000              -0.000               0.000               0.000               0.000              -0.392               0.000               0.000               0.000            1192.526               0.158               0.158               0.000            1677.754               0.000               0.000               0.000               0.350               0.392               0.000               3.198               0.000               0.000               0.000               0.000
               0.060          696621.380          167730.020            1680.942               1.000               0.000              -0.000               0.000               0.000               0.000              -0.589               0.000               0.000               0.000            1192.526               0.355               0.355               0.000            1677.754               0.000               0.000               0.000               0.350               0.589               0.000               3.188               0.000               0.000               0.000               0.000

I have managed to import one single file, and to retain only the desired variables which are: x, y, z, Etot:
  trjct <- read.table('trajectory_test_tschamut_Pos1.log', skip = 23)
  trjct <- trjct[,c("V1","V2","V3", "V4", "V15")]
  colnames(trjct) <- c("t", "x", "y", "z", "Etot")

> str(trjct)
'data.frame':   1149 obs. of  5 variables:
 $ t   : num  0 0.01 0.02 0.04 0.06 0.08 0.11 0.13 0.15 0.16 ...
 $ x   : num  696621 696621 696621 696621 696621 ...
 $ y   : num  167730 167730 167730 167730 167730 ...
 $ z   : num  1681 1681 1681 1681 1681 ...
 $ Etot: num  1193 1193 1193 1193 1193 ...

However I have 91 of these files and would like to analyse them simultaneously. Therefore, I want to create one large dataset, that distingishes the data from every file by adding an ID - similiar question has been answered here.
I have applied the code to my data and needs and adjusted it here and there, but I always keep getting some errors.
# importing all files at the same time
  files.list <- list.files(pattern = ".log")
  trjct <- data.frame(t=numeric(),
                      x=numeric(),
                      z=numeric(),
                      Etot=numeric(),
                      stringsAsFactors=FALSE)

  for (i in 1: length(files.list)) {
    df.next <- read.table(files.list[[i]], header=F, skip = 23)
    df.next$ID <- paste0('simu', i)
    df <- rbind(df, df.next)
  }

I am getting an error:
Error in rep(xi, length.out = nvar) :
  attempt to replicate an object of type 'closure'

QUESTIONS:

*

*Where is the problem and how can I fix it?

*Is there a better solution?

A: You could also check out purrr::map_df which behaves like lapply or for loop but returns a data.frame
read_traj <- function(fi) {
    df <- read.table(fi, header=F, skip=23)
    df <- df[, c(1:4, 15)]
    colnames(df) <- c("t", "x", "y", "z", "Etot")
    return(df)
}

files.list <- list.files(pattern = ".log")
library(tidyverse)

map_df has a handy feature .id=... that creates a column, id, with numbers 1...N where N is number of files.
map_df(files.list, ~read_traj(.x), .id="id")

If you want to save the file name instead, use the id column to access files.list
map_df(files.list, ~read_traj(.x), .id="id") %>%
  mutate(id = files.list[as.numeric(id)])

A: First of all, you should encapsulate the reading part in a function :
read_log_file <- function(path) {
  trjct <- read.table(path, skip = 23)
  trjct <- trjct[,c("V1","V2","V3", "V4", "V15")]
  colnames(trjct) <- c("t", "x", "y", "z", "Etot")
  return(trjct)
}

Then, you can create a list of data.frame using mapply (kind of apply which can take two parameters, go to datacamp article on apply family if you want to know more).
files.list <- list.files(pattern = ".log")
ids <- 1:length(files.list)

df_list = mapply(function(path, id) {
    df = read_log_file(path)
    df$ID = id
    return(df)
}, files.list, ids, SIMPLIFY=FALSE)

Note the SIMPLIFY=FALSE part, it avoids mapply to return a kind of data.frame and return a raw list of data.frame instead.
Finally, you can concatenate all your data.frame in one with bind_rows from dplyr package :
df = dplyr::bind_rows(df_list)

Note : in general, in R, it's better to use *apply functions family.


text:
Q: How can Editor Templates / Display Templates recognize any Attributes assigned to them? I want to add a [Required] attribute to my DateTime editor template so that I can add the appropriate validation schemes or a DataType.Date attribute so I know when I should only display dates. But I can't figure out how to get the metadata that says which attributes the Editor Template has assigned to it.

A: The built-in attributes, such as [Required] assign different properties on the metadata (see the blog post I have linked at the end of my answer to learn more). For example:
public class MyViewModel
{
    [Required]
    public string Foo { get; set; }
}

would assign:
@{
    var isRequired = ViewData.ModelMetadata.IsRequired;
}

in the corresponding editor/display template.
And if you had a custom attribute:
public class MyCustomStuffAttribute : Attribute, IMetadataAware
{
    public void OnMetadataCreated(ModelMetadata metadata)
    {
        metadata.AdditionalValues["customStuff"] = "some very custom stuff";
    }
}

and a view model decorated with it:
public class MyViewModel
{
    [MyCustomStuff]
    public string Foo { get; set; }
}

in the corresponding editor/display template you could fetch this:
@{
    var myCustomStuff = ViewData.ModelMetadata.AdditionalValues["customStuff"];
}

Also you should absolutely read Brad Wilson's series of blog posts about what ModelMetadata and templates in ASP.NET MVC is and how to use it.


text:
Q: Carto Builder: No geo reference I'm pretty new with Carto. I have worked with Carto Editor one time in the past, but in Carto Builder I'm missing the "Merge -> column join" option.
I tried to create a map by using the two data sets I have (geodata from my city in Germany) and a dataset with statistics structured by zip codes. I marked both datasets and clicked on "create map". But somehow carto tells me, the dataset with the statistics has no geo reference.
What can I do?

A: In CARTO Builder, table joins (as well as most data manipulation) is done through Analysis. You just have to follow these steps:

*

*Import both datasets to your map. Remember you'll have to do import each dataset one by one! As you pointed out, only one of those has a valid geometry; the statistics dataset will display a yellow warning triangle, meaning it has no geometry and can't be plotted on the map.

*Click on your dataset that does have a geometry column in it and switch to the ANALYSIS tab.

*Click ADD ANALYSIS, then select the Join columns from second layer option.

*Now fill in the wizard with (2) the dataset you mean to join, (3) the columns that match in both datasets, normally a name or code, and (4) the rows you want to keep from each table. When in doubt, just selct all columns from both tables.

*Click APPLY... and you're done!
You can find this and more info about CARTO Builder in the CARTO Guides...
...and see the whole process in action in the following GIF:

Disclaimer: I'm currently working for CARTO's Support Team.

A: The join is still in there! (Just no so obvious;-))
First you have to create a map with your geodata. Within this map you have to add an analysis. The analysis you are looking for is "Join Columns from 2nd layer"


text:
Q: How to reset master password in Odoo v10? how to reset master password in odoo10 to create new database.
issue:- database creation : access denied....

A: You can change it from configuration file.
In configuration file you can set admin_passwd and restart your odoo server.
ex:

[options]
admin_passwd = mysupersecretpassword
db_host = 192.168.1.2
db_port = 5432
db_user = odoo
db_password = pwd
dbfilter = ^mycompany.*$

You can follow odoo below link.
https://www.odoo.com/documentation/10.0/setup/deploy.html
This may help you.


text:
Q: Antlr Missing token error I am using antlr to generate my parser, but I want to override some of the error reporting. At the moment if I give some incorrect syntax, for example a missing token, antlr gives the error "line 1:11 missing TYPE at '.'"
However I can't find in which method this error is outputted. It is not, as I originally thought, in the reportError() method. Does anyone know where the message is generated?
Thanks!

A: A MissingTokenException does pass through reportError(...). Let's say you would like to parse assignments using the grammar below:
grammar T;

parse      : assignment EOF;
assignment : Id '=' Number ';';
Number     : '0'..'9'+ ('.' '0'..'9'+)?;
Id         : ('a'..'z' | 'A'..'Z')+;
Space      : ' ' {skip();};

Now simply override the reportError(...) method like this:
grammar T;

@parser::members {
  @Override
  public void reportError(RecognitionException e) {
    System.out.println("CUSTOM ERROR...\n" + e);
  }
}

parse      : assignment EOF;
assignment : Id '=' Number ';';
Number     : '0'..'9'+ ('.' '0'..'9'+)?;
Id         : ('a'..'z' | 'A'..'Z')+;
Space      : ' ' {skip();};

and then try to parse, say, "= 123;" (a missing Id):
java -cp antlr-3.3.jar org.antlr.Tool T.g
javac -cp antlr-3.3.jar *.java
java -cp .:antlr-3.3.jar Main "= 123;"

CUSTOM ERROR...
MissingTokenException(inserted [@-1,0:0='<missing Id>',<4>,1:0] at =)

As you can see, the custom error message is being printed to the console.
EDIT
And a warning like "no viable alternative ..." is a problem in the lexer, not the parser. This happens when the lexer encounters a character that you did not account for in your grammar (or not as a proper token, at least).
Let's say you parse the input a = 123: (note the : at the end instead of a ;). The lexer will now produce a "no viable alternative ..." warning because I didn't define any token for that :.
An easy solution to account for such mistakes is to add a "catch-all" rule at the end of your lexer grammar that will match any character that is not matched by any lexer rule before it. Whenever such a "catch-all" rule matches, you simply throw an exception (or do something else, of course!) in the @after{...} block of that rule.
Here's a demo:
grammar T;

@parser::members {
  @Override
  public void reportError(RecognitionException e) {
    System.out.println("CUSTOM ERROR...\n" + e);
  }
}

parse      : assignment EOF;
assignment : Id '=' Number ';';
Number     : '0'..'9'+ ('.' '0'..'9'+)?;
Id         : ('a'..'z' | 'A'..'Z')+;
Space      : ' ' {skip();};

FallThrough
@after{
  throw new RuntimeException(String.format(
      "Encountered an illegal char on line \%d, column \%d: '\%s'",
      getLine(), getCharPositionInLine(), getText()
    )
  );
}
  :  . // match any char not matched by Number, Id or Space
  ;

If you now parse a = 123:, you will see the following on your console:
Exception in thread "main" java.lang.RuntimeException:
    Encountered an illegal char on line 1, column 8: ':'
    ...


text:
Q: How to wrap deferred function which returns promise so outer function returns real value not a promise I have deferred function which returns promise for example
function promiseAddition(x,y){
 var defer = deferred();
 // code
 returns defer.promise;
}

I need to to call this function inside outer function and returns result of addition (value not a promise).
How to achieve this ? I am using deferred module from node.js.

A:
I need to to call this function [from somewhere] and return [a] result […] value [that is] not a promise

You cannot. If a value is wrapped in a promise once, it and all the values depending on it will be wrapped in promises forever.
If you are using promises to represent asynchronous results, then it simply is impossible to extract the value - which is not yet there.
Of course various types of promises do allow to extract values, but usually only under certain circumstances - for example, a callback in the future. However, for a transformation (as is an addition) you will need to return another promise. Use its then method for that purpose.

A: If function you're wrapping is returning promise which has not been resolved yet, then as Bergi pointed you can't return resolved value directly, as value is not there yet.
However, if it's about wrapping function that returns promise which in all cases is resolved, then when using deferred, you can easily configure such wrapper:
var getOutOfPromise = function () {
  var value;
  resolvedPromise.done(function (result) { value = result; });
  return value;
};

Still, recommended way is not to unwrap promises, but work with them, pass them across the functions and let them unwrap values whenever they need.
 If you're working with implementation that has promise.done and provides sync access to resolved value, there's no added cost.


text:
Q: Remove gameobject with trigger I want to disable a plane when the camera enters the sphere but can't seem to get it to work. I know the panel1.SetActive(true) works, as I have tried and set it to false, thus making the plane disappear, but I can't seem to get the panel1.SetActive(false) to work. I have made the null object that contains the camera, and is the object being animated to be a trigger. images below.
the script
the gameobject

A: I think it might be that there is nothing colliding with your trigger. The GameObject you try to move into the trigger needs a Collider aswell, if its still the default Camera there is no component attached which knows about how to collide.


text:
Q: Cakephp 2.9 passing a variable from Controller to Layouts View The question  i am asking is very similar and already asked question.But It is working for me.
ViewReportsController.php
class ViewReportsController extends AppController {
public function index() {
$count_table = 10;//sample variable that is available in view
$this->set('count_tablen',$count_table);
}
}

APP/View/Layouts/default.ctp
 pr($count_tablen);

Now i am getting the error says- Undefined variable: count_tablen [APP/View/Layouts/default.ctp, line 228]

A: You are using a variable in your main layout template which is likely used by multiple controller actions. Therefore, the code example you've provided would only work on /view_reports/index. If you want to set variables to be used in the layout templates you need to do this in the beforeRender callback of AppController so that it can be used everywhere:-
public function beforeRender() {
    parent::beforeRender();
    $count_table = 10;
    $this->set('count_tablen', $count_table);
}

If you use multiple layout templates you can check which template will be used in beforeRender before setting the variable:-
public function beforeRender() {
    parent::beforeRender();
    if ($this->layout === 'default') {
        $count_table = 10;
        $this->set('count_tablen', $count_table);
    }
}


text:
Q: Ascending/Descending filter Strings on ng-grid Trying out Ascending and Descending type of sorting in Angular JS with Strings
Here is the Plunker The select box has  two options Ascending and Descending
when Ascending is chosen than the grid should output the values with Importance in order L-M-H stands for Low-Medium-High and similarly for Descending that is H-M-L
I have already asked these questions but sorry can't get my concepts right about sorting and filtering in Angular JS
UPDATE
I had implemented a part of it where I have sorted the contents in same order
Stack Question
 Here i have used a drop down for selection. and the same drop down has two more options of Ascending and Descending for which I am trying to find out answers.

A: I don't know of any non-hackish way of using an external select such as you show in your Plunker.
As for the sorting itself, you can create and use a custom sorting function:
var prioritySort = function(a, b){
    var priority = { L: 1, M: 2, H: 3 };
    if(priority[a] > priority[b]) return 1;
    if(priority[a] < priority[b]) return -1;
    return 0;
};

$scope.gridOptions = {
    data: 'myData',
    enableSorting: true,
    showFilter: true,
    columnDefs: [{ field: 'name', displayName: 'Name'},
    { field: 'age', displayName: 'Age' },
    { field: 'Importance', displayName: 'Importance', sortFn: prioritySort}]
};

Demo


text:
Q: Problem With Hotbar, arrow as web site in .net framework wpf app Image with Problem
This is a WPF application launched with debug of visual studio
I've a window, where show content
<Window x:Class="Test.All"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Test"
    mc:Ignorable="d"
    Title="All" Height="450" Width="800">
<Grid>
</Grid>

and a user control, with the content to show in the window
<UserControl x:Class="Test.ShowContent"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:Test"
         mc:Ignorable="d"
         d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Button x:Name="btnrand" Content="button" HorizontalAlignment="Left" Margin="300,69,0,0" VerticalAlignment="Top" Width="200" RenderTransformOrigin="0.473,0.477" Height="58" Click="btnrand_Click"/>
        <Label x:Name="showblasph" Content="" HorizontalAlignment="Left" Margin="60,169,0,0" VerticalAlignment="Top" Height="163" Width="664" FontSize="24"/>
    </Grid>
</UserControl>

With a WinForms application, I did not have that problem, but with wpf yes, any ideas?
The problem is the arrows at the top

A: You are accidentially using a NavigationWindow instead of a Window. A navigation window has built-in browser-like controls. These controls are not shown in the Visual Studio designer, but at runtime. The black bar at the top are the XAML debugging tools, that you can enable or disable in debug mode.

A navigation window is used automatically, if you specify a UserControl resource as StartupUri. What type of window is used or created depending on the startup URI is documented here.
Types that display a NavigationWindow when set as StartupUri resource:

*

*NavigationWindow

*Page

*UserControl

*FlowDocument

*PageFunction<T>
Therefore, you have to set a Window as StartupUri and set its Content to your UserControl.


text:
Q: Sprite in SDL2 its not shown I have a problem rendering an sprite from a sprite sheet loaded as a texture in SDL2. The exercise consists in showing 2 sprites in the top and bottom corners, and the other 2 where I want, the first three sprites renders well, but strangely the number four doesn't gets rendered and has the same code structure. As a result I get a black screen which gets freezed, and a message in the line 99 where I call SDL_RenderCopy in Xcode 9 in Mac OS Sierra 10.12.6 saying: Thread 1: EXC_BAD_ACCESS code=1. Hope you can help me, below is the code:
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2_image/SDL_image.h>
#include <cstdio>
#include <cstdlib>

using namespace std;

const int SCREEN_WIDTH = 1300;
const int SCREEN_HEIGHT = 700;

class WTexture{//Wrapper class to organize all data from texture

    SDL_Texture * texture;
    int width;
    int height;

public:

    WTexture();
    ~WTexture();
    bool loadFromFile(std::string);//Load texture
    void free();//Frees texture
    void render(SDL_Rect *, SDL_Rect *);
    int getWidth();
    int getHeight();

};

bool init();//Initialize SDL

bool loadMedia();//Load multimedia data, in this case the sprite sheet
//And initializes coordinates for rendering.

void close();//Quit and clean up all

SDL_Window * main_window = NULL;
SDL_Renderer * renderer = NULL;

SDL_Rect sprite_coordinates[3];//The rectangles which contains sprites
//coordinates from the loaded texture (sprite sheet).

SDL_Rect window_coordinates[3];//The rectangles which contains the
//coordinates to render sprites in screen

WTexture texture_wrapper;//An object to store the texture

WTexture::WTexture(){//Constructor

    texture = NULL;
    width = 0;
    height = 0;
}

WTexture::~WTexture(){//Destructor

    free();
}

bool WTexture::loadFromFile(std::string path){

    SDL_Surface * surfaceToTexture = IMG_Load(path.c_str());
    if( surfaceToTexture == NULL )
        fprintf(stderr, "%s\n", IMG_GetError());
    else{

        SDL_SetColorKey(surfaceToTexture, SDL_TRUE, SDL_MapRGB(surfaceToTexture->format, 0xFF, 0xFF, 0xFF));
        SDL_Texture * texture_to_return = SDL_CreateTextureFromSurface(renderer, surfaceToTexture);
        if( texture_to_return == NULL)
            fprintf(stderr, "%s\n", IMG_GetError());
        else{

            texture = texture_to_return;
            width = surfaceToTexture->w;
            height = surfaceToTexture->h;
            SDL_FreeSurface(surfaceToTexture);

        }
    }
    return texture != NULL;

}

void WTexture::free(){
    if( texture != NULL ){

        SDL_DestroyTexture(texture);
        texture = NULL;
        width = 0;
        height = 0;
    }

}

void WTexture::render(SDL_Rect * sprite_coords, SDL_Rect * dest_coords){

    SDL_RenderCopy(renderer, texture, sprite_coords, dest_coords);

}

int WTexture::getWidth(){

    return width;
}

int WTexture::getHeight(){

    return height;
}

bool init(){

    bool success = false;
    if(SDL_Init(SDL_INIT_VIDEO) < 0)
        fprintf(stderr, "%s\n", SDL_GetError());
    else{

        main_window = SDL_CreateWindow("CLip Rendering", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH,
                                       SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        if(main_window == NULL)
            fprintf(stderr, "%s\n", SDL_GetError());
        else{

            renderer = SDL_CreateRenderer(main_window, -1, SDL_RENDERER_ACCELERATED);
            if(renderer == NULL)
                fprintf(stderr, "%s\n", SDL_GetError());
            else{

                SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);

                if(!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
                    fprintf(stderr, "%s\n", "Warning: Couldn't initialize linear filtering");
                else{

                    if(!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG))
                        fprintf(stderr, "%s\n", IMG_GetError());
                    else success = true;

                }

            }

        }

    }
    return success;

}

bool loadMedia(){

    bool success = true;

    if(!texture_wrapper.loadFromFile("/Users/linuxshotgun/Engineering/SDL_tutorial/Sources/spritesheet.png")){
        fprintf(stderr, "%s\n", SDL_GetError());
        success = false;
    }
    else{

        //First sprite coords (in left to righ order)
        sprite_coordinates[0].x = 0;//x coordinate of the top left corner of the sprite
        sprite_coordinates[0].y = 0;//x coordinate of the top left corner of the sprite
        sprite_coordinates[0].w = 214;//Width in pixels
        sprite_coordinates[0].h = 260;//Height in pixels

        //Second sprite coords
        sprite_coordinates[1].x = 268;
        sprite_coordinates[1].y = 0;
        sprite_coordinates[1].w = 192;
        sprite_coordinates[1].h = 260;

        //Third sprite coords
        sprite_coordinates[2].x = 0;
        sprite_coordinates[2].y = 266;
        sprite_coordinates[2].w = 212;
        sprite_coordinates[2].h = 262;

        //Fourth sprite coords, this sprite has the problem
        sprite_coordinates[3].x = 219;
        sprite_coordinates[3].y = 264;
        sprite_coordinates[3].w = 190;
        sprite_coordinates[3].h = 264;

        //Screen coordinates in wich the sprites will be displayed (in order, first sprite, second).

        window_coordinates[0].x=0;
        window_coordinates[0].y=0;
        window_coordinates[0].w=sprite_coordinates[0].w;
        window_coordinates[0].h=sprite_coordinates[0].h;

        window_coordinates[1].x=650;
        window_coordinates[1].y=0;
        window_coordinates[1].w=sprite_coordinates[1].w;
        window_coordinates[1].h=sprite_coordinates[1].h;

        window_coordinates[2].x=0;
        window_coordinates[2].y=350;
        window_coordinates[2].w=sprite_coordinates[2].w;
        window_coordinates[2].h=sprite_coordinates[2].h;

        //fourth sprite display coords: Could have a bug
        window_coordinates[3].x=650;
        window_coordinates[3].y=350;
        window_coordinates[3].w=sprite_coordinates[3].w;
        window_coordinates[3].h=sprite_coordinates[3].h;

    }
    return success;

}

void close(){

    SDL_DestroyRenderer(renderer);
    renderer = NULL;
    SDL_DestroyWindow(main_window);
    main_window = NULL;
    IMG_Quit();
    SDL_Quit();

}

int main(int argc, char *argv[]){

    if(!init()){
        fprintf(stderr, "%s\n", SDL_GetError());
        _Exit(EXIT_FAILURE);
    }
    if(!loadMedia()){
        fprintf(stderr, "%s\n", SDL_GetError());
        _Exit(EXIT_FAILURE);
    }
    bool quit = false;
    SDL_Event event;
    while(!quit){

        while(SDL_PollEvent(&event) != 0 ){

            if(event.type == SDL_QUIT)
                quit = true;
        }

        //Clear screen
        SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
        SDL_RenderClear(renderer);

        //render top left sprite
        texture_wrapper.render(&sprite_coordinates[0], &window_coordinates[0]);
        texture_wrapper.render(&sprite_coordinates[1], &window_coordinates[1]);
        texture_wrapper.render(&sprite_coordinates[2], &window_coordinates[2]);
        texture_wrapper.render(&sprite_coordinates[3], &window_coordinates[3]);

        SDL_RenderPresent(renderer);

    }
    close();
    return EXIT_SUCCESS;

}

A: Arrays sprite_coordinates[3] and window_coordinates[3] have size 3 and so accessing fourth sprite coordinates causes buffer overrun.


text:
Q: Socket is busy when connecting before bind I'm using zeromq to push messages from node.js server to my worker. I create a router socket on the node.js side
var sender = zmq.socket('router');
sender.bind('tcp://127.0.0.1:6633', function(err) {
  if (err) {
    console.log( 'Error binding socket' );
    return;
  }
  console.log('OK!');
}

and connect to this address with a dealer in the worker code.
The problem occurs when the worker connects first, before bind (not always, but very often). This should not be a problem regarding the zeromq documentation, so I think it's a problem in the node.js binding, the question is how can I solve this?
Also a problem that I can catch this exception Socket is busy in process.on('uncaughtException',...), not in the bind function
I should mention that I'm doing this on windows 7 64bit.

A: The problem is probably that you are using bind() where you should in fact be using bindSync(). When you read the sources, you discover that the async bind() in fact locks the socket and checks the lock every time you do anything with it. What you are probably experiencing is that a worker connects before the socket is unlocked and so it throws an exception. Just replacing bind() with bindSync() worked for me. That is, however, not an idea solution I guess, or rather not very node.js-ish. Let's demonstrate what I mean:
var zmq = require('zmq')
  , sender;
sender = zmq.socket('router');
sender.bind('tcp://127.0.0.1:6633', function(err) {
  if (err) {
    console.log( 'Error binding socket' );
    return;
  }
  sender.close(); // This is fine! The socket is ready!
});

sender.close(); // This is wrong! The socket is not ready yet!

So you can either call bindSync() and don't care, or call bind() and continue the work in the callback, but you definitely can't use bind() and continue without waiting for it to finish. bindSync() makes the code simpler to read, but you block the whole node.js instance during the call. So I think that the bind() way is more clean in a way that node.js should be used...
Hope this helped ;-)


text:
Q: scaleability of failing transactions mysql I have a table that stores messages from one user to another. messages(user_id,friend_id,message,created_date). My primary key is (friend_id,created_date). This prevents duplicate messages (AFAIK) because they will fail to insert.
Right now this is ok because my code generates about 20 of these queries at a time per user and I only have one user. But if there were hundreds or thousands of users would this create a bottleneck in my database with all the failed transactions? And if what kinds of things could I do to improve the situation?
EDIT:
The boiled down question is should I use the primary key constraint,check outside of mysql, or use some other mysql functionality to keep duplicates out of the database?

A: Should be fine as mysql will just do a primary key lookup internally and ignore the record (I'm assuming you're using INSERT IGNORE).  If you were checking if they exist before inserting, mysql will still check again when you insert. This means if most inserts are going to succeed, then you're saving an extra check.  If the vast majority of inserts were failing (not likely) then possibly the savings from not sending unnecessary data would outweigh the occasional repeated check.


text:
Q: Can i select my program using processor?
Possible Duplicate:
How Can I Set Processor Affinity in .NET?

I have i7 930x . my computer have cpu 4core.And 8 processor(thread 8)
   so.. processor 1 , 2 ,3 ,4 .... 8.
but i want only number 1 processor. i don't want using other phsycal.
c# is possible?
example) my calc program using cpu No1.
        my sound program using cpu No2.

        my Network A Program using cpu No1.

        my Network B Program using cpu No3.

A: It is possible to set a processor affinity mask for threads/processes to accomplish that. For some high performance programs using thread pools and work queues it can improve performance. In all other cases it is better to let the OS handle the scheduling.


text:
Q: Найти повторяющиеся списки в списке У меня есть массив
mylist = [[1,'a'], [2, 'b'], [[1, 'a'], [3, 'c'], [2, 'b']]

Из него я хочу получить
newlist = [[1, 'a'], [2, 'b']]

То есть найти все повторяющиеся списки и закинуть их в массив, пробовал делать так
from collections import Counter
mylist = [[1,'a'], [2, 'b'], [[1, 'a'], [3, 'c'], [2, 'b']]
[k for k,v in Counter(mylist).items() if v>1]

Но получаю ошибку
unhashable type 'list'

A: Можно сделать вашим способом, если преобразовать list в tuple, которое уже hashable, а после его обработки через Counter - обратно в list:
from collections import Counter
mylist = [[1,'a'], [2, 'b'], [1, 'a'], [3, 'c'], [2, 'b']]
[list(k) for k,v in Counter(map(tuple, mylist)).items() if v>1]

На выходе:
[[1, 'a'], [2, 'b']]

Заметьте, что у вас лишняя [ в середине списка, из-за которой ваша ошибка не воспроизводится, а получается другая ошибка. Ну, либо у вас не хватает завершающей ] и тогда это немного другая задача - надо сначала ещё вложенные списки развернуть.


text:
Q: File Download from Azure Blob Below code is for donwnloading file from azure blob. I have problem with .docx,.xlsx files and that too after deployment only, mean in local machine it is working fine.
The problem is after downloading .xlsx or .docx, when i open that file showing file corrupted popup.
public void DownloadBlob(string blobName)
{
    //You have to get values for below items from azure
    string accountName = "MyAccName";
    string accountPrimaryKey = "MyKey";
    string blobContainer = "ContainerName";
    CloudStorageAccount account = new CloudStorageAccount(new StorageCredentialsAccountAndKey(accountName, accountPrimaryKey), false);
    CloudBlobClient blobClient = account.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference(blobContainer);
    CloudBlob blob = container.GetBlobReference(blobName);
    MemoryStream memStream = new MemoryStream();
    blob.DownloadToStream(memStream);

    Response.ContentType = blob.Properties.ContentType;
    Response.AddHeader("Content-Disposition", "Attachment; filename=" + blobName.ToString());
    Response.AddHeader("Content-Length", (blob.Properties.Length - 1).ToString());
    Response.BinaryWrite(memStream.ToArray());
    Response.End();
}

A: I am sure you have  issue with your code as As Steve suggested you are setting length incorrectly.
I worked on similar issue sometime last year and documented the solution in my blog as below:
http://blogs.msdn.com/b/avkashchauhan/archive/2011/04/05/downloading-word-and-excel-files-from-windows-azure-storage-in-a-asp-net-web-role.aspx


text:
Q: Almost surely limit equals lim sup/lim inf? Suppose $(X_n)_{n\in \mathbb{N}}=\mathbb{X}$ is a sequence of independent random variables with $X_n\to^{\mathbb{P}} X$, that is $X_n$ converges to $X$ in probability.
For $\limsup_nX_n$ and $\liminf_n X_n$, we can use monotonicity to show both are $\mathcal{T}_\infty(\mathbb{X})$ measurable and are constant almost surely.
$X_n \to^{\mathbb{P}} X$ implies there exists a subsequence $(X_{n_k})_{n_k\in\mathbb{N}} \to X$ almost surely.
My question: does this imply $\limsup_{n_k}X_{n_k}=\liminf_{n_k}X_{n_k} =X$? and is $\limsup_{n_k}X_{n_k} \in \mathcal{T_\infty}(\mathbb{X})$?
For $\limsup_{n_k}X_{n_k}=\inf_{n_k}\sup_{m\geq n_k}X_{m}.$   $\sup_{m\geq n_k}X_{m}$ is $\mathcal{T}_\infty(\mathbb{X})$ measurable since all these $X_m$'s are and by monotonicity so is the infimum.
But does this $\limsup_{n_k}X_{n_k}=X?$

A: If $\{a_n\} \subset \mathbb  R$ and $a_n \to a$ then $$\limsup a_n =\liminf a_n =a.$$However there is one point you have to note here. If $X$ is almost surely equal to a $Z$ where $Z$ is measurable w.r.t. some $\sigma$-algebra, say $\mathcal T_{\infty}$ you cannot say $X$ is measurable w.r.t. that sigma-algebra. To make things work you have to complete the $\sigma$-algebra. Once you do this everything works fine, $X$ is indeed almost surely constant and $\limsup X_{n_{k}} =\liminf  X_{n_{k}}=X$ almost surely.


text:
Q: Не обновляются элементы recyclerview после вызова notifyDataSetChanged Создаю адаптер и передаю класс с пустым списком:
@Provides
@Singleton
Posts providesItemsList() {
    Posts posts = new Posts();
    posts.items = new ArrayList<>();
    return posts;
}

После чего идет запрос в сеть и вызывается метод адаптера:
public void setItems(Posts newPosts) {
    Log.i("mytag", "NewPosts items number in the setItems method: " + Integer.toString(newPosts.items.size()));
    posts.items.addAll(newPosts.items);
    Log.i("mytag", "Posts items number in the setItems method: " + Integer.toString(posts.items.size()));
    posts.profiles.addAll(newPosts.profiles);
    posts.groups.addAll(newPosts.groups);
    notifyDataSetChanged();
}

А вот так выглядит getItemCount:
@Override
public int getItemCount() {
    Log.i("mytag", "Posts items number in the getitemcount method: " + Integer.toString(posts.items.size()));
    return posts.items.size();
}

И вот что пишет в логах:
07-15 18:57:41.967 7481-7481/com.ovchinnikovm.android.vktop I/mytag: Posts items number in the getitemcount method: 0
07-15 18:57:41.967 7481-7481/com.ovchinnikovm.android.vktop I/mytag: Posts items number in the getitemcount method: 0
07-15 18:57:42.005 7481-7481/com.ovchinnikovm.android.vktop I/mytag: Posts items number in the getitemcount method: 0
07-15 18:57:42.005 7481-7481/com.ovchinnikovm.android.vktop I/mytag: Posts items number in the getitemcount method: 0
07-15 18:57:42.118 7481-7481/com.ovchinnikovm.android.vktop I/mytag: NewPosts items number in the setItems method: 20
07-15 18:57:42.118 7481-7481/com.ovchinnikovm.android.vktop I/mytag: Posts items number in the setItems method: 20

Как мне правильно обновить мой recyclerview?


text:
Q: Can't access to POST parameters using expressJs with AngularJs POST Request I can't access to my post parameters when I'm doing post request with angular, here is my angular code :
var request = $http({
                method: 'POST',
                url: '/api/login',
                data: {
                    login: 'alex',
                    password: 'test'
                }
            })
            .success(function (res, status, headers) {
                if (res.token != 'undefined'){
                    user.token = res.token;
                    user.login = credentials.login;
                    user.userid = res.userid;
                    user.islogged = true;
                    $cookieStore.put("user", user);
                }
            }).error(function(data, status, headers, config) {
                console.log(data);
            });

Here is my back-end code in my router file :
/************ API ******************/
app.post('/api/login', user.login);

And here is the code of my user controller
exports.login = function(req, res) {

console.log(req);

var user = {
    login: req.query.login,
    password: sha1(req.query.password)
};
...
}

I have nothing in req.query object otherwise if I make my request with Advanced REST Client plugin for chrome everything work fine.
Note: I'm using body-parser module to read parameters of my request.
Here is the github repository : https://github.com/alex3165/numeractive/tree/dev/node

A: Make sure you enables the use of json parser
var bodyParser = require("body-parser");
app.use(bodyParser.json());

Note: you have to install body-parser package, just open your terminal (command prompt in windows), chnage your directory to the root of your project and type the following
$ npm install body-parser --save


text:
Q: Blocking bots by modifying htaccess I am trying to block a couple bots via my htaccess file. On Search Engine Watch it is recommended to use the below.  I did block these bots in the robots.txt file but they are ignoring it.
Here is code from Search Engine Watch:
RewriteEngine on
Options +FollowSymlinks
RewriteBase /
RewriteCond %{HTTP_USER_AGENT} ^Baiduspider [NC,OR"
RewriteCond %{HTTP_USER_AGENT} ^Sogou
RewriteRule ^.*$ - [F"

My current htaccess file is as below. How exactly would I modify my current .htaccess with the above code?  What do I add and where do I add the above?  I assume some of the above is already included in my current htaccess file and does not need to be repeated.
Here is my current .htaccess:
    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>

   # END WordPress

A: Remove the Options line and just add them above your wordpress rules, and also change the " to ]:
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} ^Baiduspider [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Sogou [NC]
RewriteRule ^.*$ - [F]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

If you have other user agents you want to block, just add more conditions above the current ones:
RewriteCond %{HTTP_USER_AGENT} ^dont-want-this-string [NC,OR]


text:
Q: How to omit huge code produces by do.call? I want to build a function additive_glm which will allow user to specify additive arguments to glm function if needed.
Let's consider data:
set.seed(42)
bin_var <- sample(0:1, 125, T)
indep_1 <- rnorm(125)
indep_2 <- rexp(125)
df <- data.frame("Norm" = indep_1, "Exp" = indep_2)

And my function additive_glm:
additive_glm <- function(y, x, glm_args = NULL){
  do.call("glm", c(list(
    formula = y ~ ., data = base::quote(as.data.frame(x)),
    family = binomial(link = 'logit')
  ), glm_args))
}

But now if I want to run my function:
additive(bin_var, df)

I get:
Call:  glm(formula = y ~ ., family = structure(list(family = "binomial",
    link = "logit", linkfun = function (mu)
    .Call(C_logit_link, mu), linkinv = function (eta)
    .Call(C_logit_linkinv, eta), variance = function (mu)
    mu * (1 - mu), dev.resids = function (y, mu, wt)
    .Call(C_binomial_dev_resids, y, mu, wt), aic = function (y,
        n, mu, wt, dev)
    {
        m <- if (any(n > 1))
            n
        else wt
        -2 * sum(ifelse(m > 0, (wt/m), 0) * dbinom(round(m *
            y), round(m), mu, log = TRUE))
    }, mu.eta = function (eta)
    .Call(C_logit_mu_eta, eta), initialize = expression({
        if (NCOL(y) == 1) {
            if (is.factor(y))
                y <- y != levels(y)[1L]
            n <- rep.int(1, nobs)
            y[weights == 0] <- 0
            if (any(y < 0 | y > 1))
                stop("y values must be 0 <= y <= 1")
            mustart <- (weights * y + 0.5)/(weights + 1)
            m <- weights * y
            if (any(abs(m - round(m)) > 0.001))
                warning("non-integer #successes in a binomial glm!")
        }
        else if (NCOL(y) == 2) {
            if (any(abs(y - round(y)) > 0.001))
                warning("non-integer counts in a binomial glm!")
            n <- y[, 1] + y[, 2]
            y <- ifelse(n == 0, 0, y[, 1]/n)
            weights <- weights * n
            mustart <- (n * y + 0.5)/(n + 1)
        }
        else stop("for the 'binomial' family, y must be a vector of 0 and 1's\nor a 2 column matrix where col 1 is no. successes and col 2 is no. failures")
    }), validmu = function (mu)
    all(is.finite(mu)) && all(mu > 0 & mu < 1), valideta = function (eta)
    TRUE, simulate = function (object, nsim)
    {
        ftd <- fitted(object)
        n <- length(ftd)
        ntot <- n * nsim
        wts <- object$prior.weights
        if (any(wts%%1 != 0))
            stop("cannot simulate from non-integer prior.weights")
        if (!is.null(m <- object$model)) {
            y <- model.response(m)
            if (is.factor(y)) {
                yy <- factor(1 + rbinom(ntot, size = 1, prob = ftd),
                  labels = levels(y))
                split(yy, rep(seq_len(nsim), each = n))
            }
            else if (is.matrix(y) && ncol(y) == 2) {
                yy <- vector("list", nsim)
                for (i in seq_len(nsim)) {
                  Y <- rbinom(n, size = wts, prob = ftd)
                  YY <- cbind(Y, wts - Y)
                  colnames(YY) <- colnames(y)
                  yy[[i]] <- YY
                }
                yy
            }
            else rbinom(ntot, size = wts, prob = ftd)/wts
        }
        else rbinom(ntot, size = wts, prob = ftd)/wts
    }), class = "family"), data = as.data.frame(x))

Coefficients:
(Intercept)         Norm          Exp
     0.2235      -0.2501      -0.2612

Degrees of Freedom: 124 Total (i.e. Null);  122 Residual
Null Deviance:      173.2
Residual Deviance: 169.7    AIC: 175.7

So I really get what I want, however - it's preceded by huge Call code. I was looking for some techniques to get rid of it, however I wasn't so successful. Do you know how to omit this huge part of unnecessary code ?

A: 1) Put the family argument within quote(...)  . Only the line marked ## is changed.
additive_glm <- function(y, x, glm_args = NULL){
  do.call("glm", c(list(
    formula = y ~ ., data = base::quote(as.data.frame(x)),
    family = quote(binomial(link = 'logit')) ##
  ), glm_args))
}

additive_glm(bin_var, df)

giving:
Call:  glm(formula = y ~ ., family = binomial(link = "logit"), data = as.data.frame(x))

Coefficients:
(Intercept)         Norm          Exp
    0.32821     -0.06504     -0.05252

Degrees of Freedom: 124 Total (i.e. Null);  122 Residual
Null Deviance:      171
Residual Deviance: 170.7        AIC: 176.7

2) Another possibility is:
additive_glm2 <- function(y, x, ...){
  glm(y ~ ., data = as.data.frame(x), family = binomial(link = "logit"), ...)
}
additive_glm2(bin_var, df)

giving:
Call:  glm(formula = y ~ ., family = binomial(link = "logit"), data = as.data.frame(x))

Coefficients:
(Intercept)         Norm          Exp
    0.32821     -0.06504     -0.05252

Degrees of Freedom: 124 Total (i.e. Null);  122 Residual
Null Deviance:      171
Residual Deviance: 170.7        AIC: 176.7

A: I don't understand why you are using do.call. I would do this:
additive_glm <- function(y, x, family = binomial(link = 'logit'), ...){
  mc <- match.call()
  yname <- mc[["y"]]
  xname <- mc[["x"]]

  x[[as.character(yname)]] <- y
  assign(as.character(xname), x)

  eval(substitute(glm(yname ~ ., data = xname, family = family, ...), env = environment()))
}

additive_glm(bin_var, df)
#Call:  glm(formula = bin_var ~ ., family = binomial(link = "logit"),
#    data = df)
#
#Coefficients:
#(Intercept)         Norm          Exp
#    0.32821     -0.06504     -0.05252
#
#Degrees of Freedom: 124 Total (i.e. Null);  122 Residual
#Null Deviance:     171
#Residual Deviance: 170.7   AIC: 176.7

Note the nicely printed call.


text:
Q: ufraw fatal internal error on ubuntu 16.04 I am trying to use ufraw to convert cr2 images to jpeg on Ubuntu 16.04. When I run the following, from the folder in which my images are located:
ufraw-batch --out-type jpg  *.CR2

I get the following:
ufraw-batch: Fatal internal error
Segmentation fault (core dumped)

The same thing happens in ufraw GUI. Can anyone help?


text:
Q: AngularJs, MVC 4, Nested Models - duplicates being ignored I am trying to enhance the following Angular/MVC 4 example:
  https://github.com/danielcsgomes/AngularJS-NetPonto
The code I am using is identical, save
(1) Changing the Process class name to "Product", and,
(2) Adding a "Vendor" class, as an associated class to Product, (and Vendor having a collection of products).
Everything is fine in the API.
However, if I pass the Product class with its associated Vendor, those Products that have the same Vendor will not appear in the list. But, if I make the API return an anonymous type and pass a variable called VendorName, duplicates will appear. Naturally, I would like NOT to use anonymous types so is there a solution to this?
Exhibit A: Straight forward context.Products.Include("Vendors"):

Exihbit B: As an anonymous type return:

Below are (1) My angular controller to get all products, (2 & 3) The templates to display the data

Template without anonymous type return:

Template with anonymous type return:

So my question is this:
How can I make angular accept duplicate Vendor names for the respective products w/o being required to return the data as an anonymous type?


text:
Q: analytically calculate value of convolution at certain point i'm a computer science student and i'm trying to analytically find the value of the convolution between an ideal step-edge and either a gaussian function or a first order derivative of a gaussian function.
In other words, given an ideal step edge with amplitude $A$ and offset $B$:
$$
i(t)=\left\{
  \begin{array}{l l}
    A+B & \quad \text{if $t \ge t_{0}$}\\
    B & \quad \text{if $t \lt t_{0}$}\\
  \end{array} \right.
$$
and the gaussian function and it's first order derivative
$$
g(t) = \frac{1}{\sigma \sqrt{2\pi}}e^{- \frac{(t - \mu)^2}{2 \sigma^2}}\\
g'(t) = -\frac{t-\mu}{\sigma^3 \sqrt{2\pi}}e^{- \frac{(t - \mu)^2}{2 \sigma^2}}
$$
i'd like to calculate the value of both
$$
o(t) = i(t) \star g(t)\\
o'(t) = i(t) \star g'(t)
$$
at time $t_{0}$ ( i.e. $o(t_{0})$ and $o'(t_{0}) )$.
I tried to solve the convolution integral but unfortunately i'm not so matematically skilled to do it. Can you help me?
Thank you in advance very much.

A: We can write $i(t):=B+A\chi_{[t_0,+\infty)}$. Using the properties of convolution, we can see that
\begin{align}
o(t_0)&=B+A\int_{-\infty}^{+\infty}g(t)\chi_{[t_0,+\infty)}(t_0-t)dt\\
&=B+A\int_{-\infty}^0\frac 1{\sigma\sqrt{2\pi}}\exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)dx.
\end{align}
The integral can be expressed with erf-function.
For the second one, things are easier since we can compute the integrals:
\begin{align}
o'(t_0)&=A\int_{-\infty}^0g'(t)dt=Ag(0).
\end{align}


text:
Q: How to sync playback progress through devices? I have a mobile streaming app that need to save and sync playback progress to the same apps on other platforms.
Most audiobook applications has this feature.
Do they periodically post progress to the server?


text:
Q: Net Core empty project shows Controller Error When I start a new empty project there is an error in the  .net core project:

Controller is a namespace but is used like a type.

Am I missing some packages?

A: You're right, you've missed Microsoft.AspNetCore.Mvc package. Just add it to project.json and things will be OK.