text:
Q: custom EAV model saving attributes I have a custom EAV model that uses custom tables for comments that can be set on either products or categories. I have created an admin for these using the standard EAV admin form.
In my controller, I have a save action:
public function saveAction()
{
    if ($data = $this->getRequest()->getPost()) {
        try {
            $model = Mage::getModel('module/comment');
            $model->setData($data)->setId($this->getRequest()->getParam('id'));
            $model->save();

            $this->_getSession()->addSuccess(
                Mage::helper('module')->__('The comment has been saved.'));

            $this->_redirect('*/*/edit',
                array('id' => $this->getRequest()->getParam('id')));
        }
        catch (Exception $e) {
            Mage::logException($e);
            $this->_getSession()->addError(Mage::helper('module')->__('There was an error saving the comment'));
        }
    }
    $this->_redirect('*/*/index');
}

When I save the form with a new comment, the grid page shows the new comment. But, when I look in the database with the following query:
SELECT * FROM eav_comment_text WHERE entity_id = 1;

I see the following:
+----------+----------------+--------------+----------+-----------+-------------------------+
| value_id | entity_type_id | attribute_id | store_id | entity_id | value                   |
+----------+----------------+--------------+----------+-----------+-------------------------+
|        1 |             31 |          964 |        0 |         1 | test                    |
|        4 |             31 |          964 |        0 |         1 | test adding another one |
+----------+----------------+--------------+----------+-----------+-------------------------+

Can anyone explain why (a) Magento does not replace the existing value and (b) how Magento knows which one to show in the grid?

A: TL;DR: you need a unique index on the following combination of columns: entity_id,attribute_id,store_id.
Long answer:
On an EAV entity (let's take products for example) your table could never look like that.
You have 2 records for the same combination of attribute_id | store_id | entity_id.
On the product tables (catalog_product_entity_varchar for example but it's the same for _int and others) there is a unique constraint on these 3 columns.
UNIQUE KEY `UNQ_CAT_PRD_ENTT_VCHR_ENTT_ID_ATTR_ID_STORE_ID` (`entity_id`,`attribute_id`,`store_id`),

This is created in the install script (see install-1.6.0.0.php)
->addIndex(
    $installer->getIdxName(
        array('catalog/product', 'varchar'),
        array('entity_id', 'attribute_id', 'store_id'),
        Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE
    ),
    array('entity_id', 'attribute_id', 'store_id'),
    array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE))

And when saving an attribute value (insert or update) a call to the method insertOnDuplicate is made.
This method tries to insert the values you provide to it and if there is a unique key duplicate it just updates the values you specify. In the case of the EAV tables only the value field is updated.
Since you don't have that unique constraint on the table it just inserts an other row.
Try adding that constraint and I have a feeling the problem will go away.


text:
Q: Cast string to date and change year 0001 to 1900 I receive a string with following value:
0001-01-01T12:30:00

I only need the time portion when saving to the database.
But I can't save 0001 year in MSSQL Server (field is SmallDateTime type) as it requires 1900+.
Currently I check what the year is and recreate the date using the following code:
...
DateTime i = Convert.ToDateTime("0001-01-01T12:30:00");
DateTime d = new DateTime(1900, 1, 1, i.hour, i.minute, i.seconds);

Is there an easier way to use a date format where year is set to 0001?
I don't know all of the fields I'm importing that might have this value and I don't want to add this code for all of the fields.

A: You can use the DateTime.Add() method in conjunction with the DateTime.TimeOfDay property.
If this were a regular SQL datetime you could use the SqlDateTime.MinValue helper, and add your DateTime to it.
SqlDateTime.MinValue.Value.Add(Convert.ToDateTime("0001-01-01T12:30:00").TimeOfDay)

For the smalldatetime you can create your own.
new DateTime(1900, 1, 1).Add(Convert.ToDateTime("0001-01-01T12:30:00").TimeOfDay)

A: If the time portion is all you care about then what you have is the best thing to do.  Even the regular DateTime data type in SQL Server only goes back to 1753 due to calendar issues.
If you want an essentially unconstrained date datatype that will accept years starting at 0001 then use DateTime2

A: If you don't care about the date component, this should do you :
public static DateTime String2SqlAcceptableDateTimeValue( string iso8601DateTimeValue )
{
  CultureInfo ci = CultureInfo.InvariantCulture ;
  DateTime timestamp ;
  bool converted = DateTime.TryParseExact( iso8601DateTimeValue , "yyyy-MM-ddTHH:mm:ss" , ci ,DateTimeStyles.None, out timestamp ) ;

  if ( !converted ) throw new ArgumentException("Not an ISO 8601 Date/Time value" , "iso8601DateTimeValue");

  DateTime epoch = new DateTime(1900,1,1) ;
  DateTime sqlAcceptableValue = epoch + timestamp.TimeOfDay ;

  return sqlAcceptableValue ;
}

It might easier to just toss exclude the date component from the conversion to DateTime. That makes it a 1-liner (well, 2-liner):
CultureInfo ci = CultureInfo.InvariantCulture ;
string tod = "0001-01-01T12:34:56".Substring(11) ;
DateTime dtx = new DateTime(1900,1,1) + DateTime.ParseExact(tod,"HH:mm:ss",ci).TimeOfDay ;

I think that makes the intent much clearer ;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unix domain socket: A socket operation encountered a dead network I'm using Unix Domain Socket for the first time,
I have created the following console application using .NET 5.0 to learn about Unix Domain Sockets.
I found the code here (https://medium.com/codex/unix-domain-sockets-in-net-6-basics-and-real-world-examples-8982898ab293)
My expectation is that similar to TCP/IP socket connection, i will be able to talk between the client and server but using Unix Domain sockets instead.
Following is the code:
class Program
{
    static void Main(string[] args)
    {

        const string Hostname = "localhost";
        const string UnixSocketPath = "/tmp/foo.sock";

        using var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);

        var endpoint = new UnixDomainSocketEndPoint(UnixSocketPath);
        socket.Connect(endpoint);

        var requestBytes = System.Text.Encoding.UTF8.GetBytes($"GET / HTTP/1.0\r\nHost: {Hostname}\r\nAccept: */*\r\n\r\n");
        socket.Send(requestBytes);

        byte[] receivedBytes = new byte[1024];
        socket.Receive(receivedBytes, 1024, SocketFlags.None);

        Console.WriteLine(System.Text.Encoding.UTF8.GetString(receivedBytes));
    }
}

I get the following error when i try to run my application:
"A socket operation encountered a dead network" at socket.Connect(endpoint) line.
I have the following questions:

*

*Is it expected for the above console application to run in a windows system?

*After reading couple of articles i understand that the "UnixSocketPath" is the file based path which is followed in a Unix machine. What does it refer to in case of a Windows machine? Or is it just a temporary file created in the output directory of the application.

I tried the following to resolve the error "A socket operation encountered a dead network" after reading up a bit on this:

*

*Try to run the application in admin mode - does not work, same error

*Switch to .net core 3.0 (even though i was not facing any compile time errors with .net 5.0)

*

*does not work, same error.

*Tried to change the "UnixSocketPath" to a local path (Eg: C:/Test/foo.sock ) - does not work, error : "No connection could be made because the target machine actively refused it. C:/Test/foo.sock"

Excuse me for these noob level questions, the entire socket level programming is new to me and i'm quite confused now .
Any suggestions are appreciated. Thanks

A: From your posted link:

To run the example on Windows-based systems, I can recommend WSL 2. Visual Studio and Visual Studio Code come with excellent remote integrations so you can run the code directly from the development environment.

WSL is "Windows subsystems for linux", i.e. a linux virtual machine that has some integrations with the windows host.
So you would need to run your program in this WSL environment, and have this configured correctly.  See Debug .NET Apps in WSL with Visual Studio
However, if you just want your server and client to talk to each other I would consider if this really is the right approach. While unix domain sockets might have some performance advantages, you require both applications to be run on the same computer. I would just use some message based protocol and instead try to minimize the number and size of messages.


text:
Q: Kendo Angular Combobox breaks click event We have had a Kendo Angular implementation in place for several years now. We recently updated Kendo and Angular and we found that a click event we placed on a  is now broken.
We have an outer div which contains our combobox and another div with an icon containing a click event that is broken. See the screenshot with the red arrow pointing to the broken div icon.

Below is the HTML and the css governing the div.
<div *ngIf="values.length < maxCardinality"
     class="editor-row">
    <kendo-combobox #selectBox
                    [data]="connectionCandidates$ | async"
                    [textField]="'_id'"
                    [valueField]="'name'"
                    [filterable]="true"
                    [placeholder]="'Search...'"
                    (selectionChange)="handleComboBoxValueChange($event)"
                    (filterChange)="handleFilter($event)"
                    class="reference-combobox">
        <ng-template *ngIf="resultCount >= 50" kendoComboBoxNoDataTemplate>
            50+ partial matches. Type more.
        </ng-template>

        <ng-template *ngIf="resultCount == 0" kendoComboBoxNoDataTemplate>
            No results found.
        </ng-template>

        <ng-template kendoComboBoxItemTemplate let-dataItem>

                    {{ dataItem.name }}

        </ng-template>
    </kendo-combobox>
    <div
        class="picker-button"
        *ngIf="values.length < maxCardinality"
        (click)="handleClickReferencePicker($event)">

The Div at the end of this with the class "picker-button" is the broken click event.
CSS for the picker-button
.picker-button {
        position: absolute;
        top: 6px;
        right: 32px;
        cursor: pointer;
        user-select: none;
        outline: none;
        display: flex;
        flex: 0 0 auto;
        align-content: center;
        justify-content: center;
        width: 24px;
        height: 20px;
        background-size: 20px 20px;
        background: url($assets-dir + '/picker_multiple_blue.svg') 3px 2px no-repeat transparent;

        &.disabled {
            background: url($assets-dir + '/picker_multiple_grey.svg') 3px 2px no-repeat transparent;
        }
    }

I omitted the rest of the CSS file as I don't think its relevant.
I have moved the div outside of the div containing the combobox and I can get the click event to work. I have tinkered with removing some CSS elements as an experiment to no avail. Its worth nothing this is all within a kendo grid cell. Anyone that can toss any help would be great.

A: I was able to fix this by adding a z-index: 2; to the picker-button class. The Combobox updates added a z-index of 1 causing it to overwrite our click event.


text:
Q: Get Session From /app/Config/email.php I want to send an email using CakeEmail, but I need to take from Session the user email and the password from email.php. How can I do this?
email.php:
public $smtp = array(
            'host' => 'ssl://smtp.gmail.com',
            'port' => 465,
            'from' => array($_SESSION['UserLogged']['User']['email'] => $_SESSION['UserLogged']['User']['name']),
            'username' => $_SESSION['UserLogged']['User']['email'],
            'password' => $_SESSION['UserLogged']['User']['password'],
            'transport' => 'Smtp',
            'tls' => false // As of 2.3.0 you can also enable TLS SMTP
    );

I can't take this values from Session because it can't be read in email.php and I can't set password from controller...

A: You didn't explain much around what is happening before and what happens after. I make a guess, a user is added, changed or sending new generated password.
You should look into CakeMail: http://book.cakephp.org/2.0/en/core-utility-libraries/email.html.
This example might help:
<?php
    //UsersController.php

        if ($this->request->is('post')){
            $pwBeforeHash = $this->request->data['User']['password'];
            // Uncomment the line below if its a new inserted row in table
            //$this->User->create();
            if($this->User->save($this->request->data)){

                $Email = new CakeEmail();
                $Email->from(array('me@example.com' => 'My Site'));
                $Email->to('you@example.com');
                $Email->subject('New password');
                $Email->send('Hi. This is your new password: ' . $pwBeforeHash);

                $this->Session->setFlash(__('Password is sent to your email'));
            } else {
                $this->Session->setFlash(__('Due to an unknown error, the new password could not be sent. Try again.'));
            }
        }
        ?>

If you really need to get value from session you should read this: http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html.
Password should not be saved in a session.
If you need to read a session, use: $stringToMySession = $this->Session->read('mySession');

A: Solve..
In my Controller:
$email = new CakeEmail('smtp');
                $email->config(array(
                        // 'port' => 465,
                        'from' => array($this->Session->read('UserLogged')['User']['email'] => $this->Session->read('UserLogged')['User']['name']),
                        'username' => $this->Session->read('UserLogged')['User']['email'],
                        'password' => $this->Session->read('UserLogged')['User']['password']
                ));
                $email->to($this->request->data['BlogPosts']['to']);
                $email->subject($this->request->data['BlogPosts']['subject']);
                $email->send($this->request->data['BlogPosts']['message']);


text:
Q: set a href attribute on svg path I have this code
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" viewBox="20 0 970 960" enable-background="new 20 0 970 960" xml:space="preserve">
    <g class="border">
        <path class="City1" d="......" />
        <path class="City2" d="......" />
        <path class="City3" d="......" />
        <path class="City4" d="......" />
    </g>
</svg>

I need that set a href attribute  on every patch .
like this

    <path class="City1" d="......" />

    <path class="City2" d="......" />

    <path class="City3" d="......" />

    <path class="City4" d="......" />

but doesn't work . So what do u guys suggest I should do ?

A: For SVG  elements, you need to use xlink:href instead of just href.
<path class="City1" d="......" />


text:
Q: Does Aero manipulate the DPI and Screen Size? Why? In my application, I get the screen resolution with this code:
SystemInformation.PrimaryMonitorSize

And I get the DPI with this code:
    using (Graphics g = Graphics.FromHdc(NativeMethods.GetDC(IntPtr.Zero)))
    {
        dpiX = g.DpiX;
        dpiY = g.DpiY;
    }

This works fine in most situations. But when the code runs on a Vista machine with Aero turned on, and the user has set the monitor to use a high DPI, bizarre results come back.
Lets say the user has set the machine to run at 1024 x 768 and has the DPI at 144, the code above will return a resolution of 683 x 512 and a DPI of 96.
However, if Aero is turned off, the results come back as I would expect them. What is Aero doing and how can I get the true resolution and DPI?

A: You need to declare your application as DPI-aware, either in the manifest (preferred), or by using SetProcessDPIAware Win32 API function. Because so many applications are not written properly, Vista added "DPI virtualization", which lets applications pretend that they're working with a "standard" 96dpi screen, and then does the scaling itself - DWM, being a compositing window manager, can do the scaling. If your application handles varying DPI properly, you have to say so explicitly.
On a side note, you shouldn't muck with HWND_DESKTOP (which is what (HWND)0 is). When compositing ("Aero") is off, it does indeed represent the physical screen, so if you get its DC and draw on it, you draw directly into the framebuffer. With a compositing window manager, this is impossible by definition. I'm not sure if this affects DPI measurement, but it might be a better idea to use the DC for your application window instead anyway - it won't hurt/

A: These links also provide useful information:
http://msdn.microsoft.com/en-us/library/dd464660(VS.85).aspx
http://blogs.msdn.com/greg_schechter/archive/2006/08/07/690704.aspx


text:
Q: How to apply styles dynamically from startIndex to endIndex on strings that change positions I will try to be very clear in explaining this.
I am fetching some strings from an API like this:
@TEST^1@ this is a string for $@test@$

Every special character in this definition means something. @text@ means text between @ is bolded style, $ is for italic, and so on. I create the following enum defining the regex and the corresponding style
enum class RegexStyleEnum(val regex: Regex, val style: SpanStyle) {
    BOLD(
        Regex("(?<!\\\\\\\\)@(.*?)(?<!\\\\\\\\)@"),
        SpanStyle(fontWeight = FontWeight.Bold)
    ),
    ITALIC(
        Regex("(?<!\\\\\\\\)\\$(.*?)(?<!\\\\\\\\)\\$"),
        SpanStyle(fontStyle = FontStyle.Italic)
    ),
    SUPERSCRIPT(
        Regex("(?<!\\\\\\\\)\\^(\\d)"),
        SpanStyle(baselineShift = BaselineShift.Superscript)
    ),
    UNDERLINE(
        Regex("(?<!\\\\\\\\)#(.*?)(?<!\\\\\\\\)#"),
        SpanStyle(textDecoration = TextDecoration.Underline)
    )
}

Now, I created an algorithm (that is not correct) that does this:

*

*Iterate through all the regex and find all the matches inside a string.

*Order all the matches ascending by the first position of the character found in regex.

*Iterate through results from step 2, apply only the regex I am iterating & replace the old value with the new value and apply the style. Replace the old string with the new one

The real problem:
If I have a word with markup like this: $@test@$ (length of 8, chars from pos 0..7)
The algorithm would take first the $$ and the resulting string would be @test@. The style is Italic from index 0 to index 5.
Now the second iteration would take @@ and the resulting string would be test (correct) and the style would be Bold from index 0 to 3.
When these styles would apple to the word, the program would give IndexOutOfBounds.
The example is for a simple case with only 1 word, I have sentences with multiple wards that need to have a style.
I know there would be a better solution which I haven't yet figured out but I'm losing my mind on this for over a week.


text:
Q: C implemenation of Producer-Consumer While Reading Richard Stevens' "Advanced programming in the unix environment", I tried to add a snippet of producer-consumer problem with POSIX pthread interface, but found problem implment it. Could anybody help make the following code work ?
#include <stdio.h>
#include <pthread.h>

struct msg{
    int num;
    struct msg *next;
};

struct msg *queue;

pthread_cond_t  condition = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void produce(struct msg * temp){
    pthread_mutex_lock(&mutex);
    temp->next = queue;
    queue = temp;
    printf("Produce: %d\n", queue->num);
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&condition);
}

void* consume(void * args){
    struct msg * temp;

    for(;;){
        pthread_mutex_lock(&mutex);
        while (queue == NULL) {
            pthread_cond_wait(&condition, &mutex);
        }
        printf("consume: %d\n", queue->num);
        temp = queue;
        queue = temp->next;
        pthread_mutex_unlock(&mutex);
    }
}

void* thread_run(void *arg){
    int i = 0;
    for(; i < 5; i++){
        struct msg m = {i + 1};
        produce(&m);
    }
}

int main(void){
    pthread_t p, consumer;

    int err = pthread_create(&p, NULL, thread_run, NULL);
    if (err != 0){
        printf("error on creating thread...\n");
    }

    err = pthread_create(&consumer, NULL, consume, NULL);
    if (err != 0){
        printf("error on creating thread...\n");
    }

    pthread_join(p, NULL);
    pthread_join(consumer, NULL);
}


text: Q: Netbeans 8.2 No reconoce libreria Descargue el plugin Java EE Base para Netbeans 8.2, pero cuando intento crear un proyecto Web Aplication, me pide la librería "javaee-endorsed-api-7.0" La descargué y la agregue al Netbeans,pero nada, incluso la agregué directamente desde el proyecto Web pero aún así no reconoce la libreria, muchas gracias.


text:
Q: Causes for bluebird's promisify not working I have an API which implements bluebird.js.
I've got two methods with basically the same flow, one works, the other doesn't. Looking for ideas on what could be wrong.
The flow in words is as follows:

*

*Promisify an api.

*Create an array of promises that utilise the API.

*use .join.apply to call all of the promises in the array.

Some code:
_Promise = require('bluebird');
this.getDataFromSomewhere = function getDataFromSomewhere(array, cb) {
    _Promise.promisifyAll(this);
    let promiseArray = [];
    let keyPrefix = 'some prefix';
    let output = [];

    array.forEach(function(obj, i) {
        promiseArray.push(that.foo(keyPrefix + i, function(err, data) {
            output.push({ data });
        }));
    });

    _Promise.join.apply(null, promiseArray);

    cb(null, output);
});

Now, I've got a couple of methods doing so - 'getDataFromSomewhere_1' & 'getDataFromSomewhere_2'.
The thing is that 1 works as expected, but 2 doesn't work synchronously.
In 1, the cb isn't called until _Promise.join.apply(...) has finished.
In 2, the cb is called immediately afterwards.
I'm trying to figure out what could cause this behaviour.
Maybe an internal library that is being used makes it async?
How would you debug it?
Is there other tools in bluebird's api that could help?
(I went over a bunch of documentation and couldn't find anything).
Please help :)


text:
Q: javascript_include_tag throws unsupported method I recently created a new project with Rails 4.2.0 and created a controller called Land for the landing page. So, I ran into this error upon visting http://localhost:3000/land/home:
Started GET "/" for ::1 at 2015-02-27 15:56:23 -0600
Processing by LandController#home as HTML
Rendered land/home.html.erb within layouts/application (0.0ms)
Completed 500 Internal Server Error in 5526ms

ActionView::Template::Error (TypeError: Object doesn't support this property or method
(in C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/turbolinks-2.5.3/lib/assets/javascripts/turbolinks.js.coffee)):
3: <head>
4:   <title>Course</title>
5:   <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
6:   <%= javascript_include_tag 'application' %>
7:   <%= csrf_meta_tags %>
8: </head>
9: <body>
app/views/layouts/application.html.erb:6:in `_app_views_layouts_application_html_erb__1279127835_98590860'

Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_source.erb (5.0ms)

Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_trace.html.erb (10.0ms)

Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_request_and_response.html.erb (1.0ms)

Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_web_console.html.erb (2.0ms)

Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/template_error.html.erb within rescues/layout (72.0ms)

Is there a way of getting rid of this error? Or is it a bug?

A: Ahh, it seems that you are missing
//= require turbolinks

in your application.js
See this on removing turbolinks (and obviously make sure it's all in place if you want it running).

A: I am running Windows 10, Ruby 2.1.7p400 and Rails 4.2.4.  I could not get gem coffee-script-source '1.8.0' to install as gem insisted on version 1.9.1.1.  I tried changing ExecJS to use UTF-8 encoding and running cscript without the //U switch as in this post without any luck as well.
I ended up placing nodejs.exe in the Ruby\bin folder and the issue was resolved.

A: I recently found another solution for this problem. gem 'coffee-script-source' in 1.9.0 has some issues with Rails on Windows. I reverted to the previous version using gem 'coffee-script-source', '1.8.0' in the Gemfile, this will resolve your problem.
Another way of solving this exception is installing Node.js onto your machine and the error should go away after installing & restarting rails server. Make sure that you add Node.js into your PATH before restarting the terminal(s) and rerun the server.


text:
Q: The i/p col features must be either string or numeric type, but got org.apache.spark.ml.linalg.VectorUDT I am very new to Spark Machine Learning just an 3 day old novice and I'm basically trying to predict some data using Logistic Regression algorithm in spark via Java. I have referred few sites and documentation and came up with the code and i am trying to execute it but facing an issue.
        So i have pre-processed the data and have used vector assembler to club all the relevant columns into one and i am trying to fit the model and facing an issue.
public class Sparkdemo {

static SparkSession session = SparkSession.builder().appName("spark_demo")
        .master("local[*]").getOrCreate();

@SuppressWarnings("empty-statement")
public static void getData() {
    Dataset<Row> inputFile = session.read()
            .option("header", true)
            .format("csv")
            .option("inferschema", true)
            .csv("C:\\Users\\WildJasmine\\Downloads\\NKI_cleaned.csv");
    inputFile.show();
    String[] columns = inputFile.columns();
    int beg = 16, end = columns.length - 1;
    String[] featuresToDrop = new String[end - beg + 1];
    System.arraycopy(columns, beg, featuresToDrop, 0, featuresToDrop.length);
    System.out.println("rows are\n " + Arrays.toString(featuresToDrop));
    Dataset<Row> dataSubset = inputFile.drop(featuresToDrop);
    String[] arr = {"Patient", "ID", "eventdeath"};
    Dataset<Row> X = dataSubset.drop(arr);
    X.show();
    Dataset<Row> y = dataSubset.select("eventdeath");
    y.show();

    //Vector Assembler concept for merging all the cols into a single col
    VectorAssembler assembler = new VectorAssembler()
            .setInputCols(X.columns())
            .setOutputCol("features");

    Dataset<Row> dataset = assembler.transform(X);
    dataset.show();

    StringIndexer labelSplit = new StringIndexer().setInputCol("features").setOutputCol("label");
    Dataset<Row> data = labelSplit.fit(dataset)
            .transform(dataset);
    data.show();

    Dataset<Row>[] splitsX = data.randomSplit(new double[]{0.8, 0.2}, 42);
    Dataset<Row> trainingX = splitsX[0];
    Dataset<Row> testX = splitsX[1];

    LogisticRegression lr = new LogisticRegression()
            .setMaxIter(10)
            .setRegParam(0.3)
            .setElasticNetParam(0.8);

    LogisticRegressionModel lrModel = lr.fit(trainingX);
    Dataset<Row> prediction = lrModel.transform(testX);
    prediction.show();

}

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

}}

Below image is my dataset,
dataset
Error message:
Exception in thread "main" java.lang.IllegalArgumentException: requirement failed: The input column features must be either string type or numeric type, but got org.apache.spark.ml.linalg.VectorUDT@3bfc3ba7.
at scala.Predef$.require(Predef.scala:224)
at org.apache.spark.ml.feature.StringIndexerBase$class.validateAndTransformSchema(StringIndexer.scala:86)
at org.apache.spark.ml.feature.StringIndexer.validateAndTransformSchema(StringIndexer.scala:109)
at org.apache.spark.ml.feature.StringIndexer.transformSchema(StringIndexer.scala:152)
at org.apache.spark.ml.PipelineStage.transformSchema(Pipeline.scala:74)
at org.apache.spark.ml.feature.StringIndexer.fit(StringIndexer.scala:135)

My end result is I need a predicted value using the features column.
Thanks in advance.

A: That error occurs when the input field of your dataframe for which you want to apply the StringIndexer transformation is a Vector. In the Spark documentation https://spark.apache.org/docs/latest/ml-features#stringindexer you can see that the input column is a string. This transformer performs a distinct to that column and creates a new column with integers that correspond to each different string value. It does not work for vectors.


text:
Q: How can i column width with datagrid I have a datagrid in an angular 5 app:
<clr-datagrid>
  <clr-dg-column>a</clr-dg-column>
  <clr-dg-column>b</clr-dg-column>
  <clr-dg-column>b</clr-dg-column>
  <clr-dg-column>b</clr-dg-column>

  <clr-dg-row>
    <clr-dg-cell>1</clr-dg-cell>
    <clr-dg-cell>2</clr-dg-cell>
    <clr-dg-cell>3</clr-dg-cell>
    <clr-dg-cell>4</clr-dg-cell>
  </clr-dg-row>
</clr-datagrid>

On a mobile display, this table is wider than the screen, how can I set the width of the columns so it shrinks.
EDIT:
What I'm trying to acomplish is to recreate this scoresheet: https://boardgamegeek.com/image/3360178/clans-caledonia
I belive it should be possible to create something close to it for input on a mobile device.

A: You can set column width by using a css class on the column
HTML
<clr-datagrid>
  <clr-dg-column class="width1">a</clr-dg-column>
  <clr-dg-column class="width2">b</clr-dg-column>
  <clr-dg-column class="width3">b</clr-dg-column>
  <clr-dg-column>b</clr-dg-column>

  <clr-dg-row *ngFor="let i of [1,2,3,4,5]">
    <clr-dg-cell >1</clr-dg-cell>
    <clr-dg-cell >2</clr-dg-cell>
    <clr-dg-cell >3</clr-dg-cell>
    <clr-dg-cell>4</clr-dg-cell>
  </clr-dg-row>
</clr-datagrid>

CSS
.width1 {
  width: 15%;
}

.width2 {
  width: 25%;
}

.width3 {
  width: 35%;
}

Update
After looking at the StackBlitz it occurs to me that perhaps you could just use a simple table. Overriding the default input styles with
td > input {
  width: 1.5rem;
  min-width: 1.5rem;
}

And using a standard table element

            B
            C
            D
            E

            Type {{item}}
            <input type="number">
            <input type="number">
            <input type="number">
            <input type="number">

It looks like it will collapse down on narrow width viewport.
Here is your modified StackBlitz: https://stackblitz.com/edit/angular-dbzvmg

A: This seems to work, although having to add a class to all columns and all cell's seems less than ideal.
<clr-datagrid>
  <clr-dg-column class="width">a</clr-dg-column>
  <clr-dg-column class="width">b</clr-dg-column>
  <clr-dg-column class="width">b</clr-dg-column>
  <clr-dg-column class="width">b</clr-dg-column>

  <clr-dg-row *ngFor="let i of [1,2,3,4,5]">
    <clr-dg-cell class="width">1</clr-dg-cell>
    <clr-dg-cell class="width">2</clr-dg-cell>
    <clr-dg-cell class="width">3</clr-dg-cell>
    <clr-dg-cell class="width">4</clr-dg-cell>
  </clr-dg-row>
</clr-datagrid>

style
.width {
  width: 25%;
  min-width: 20%;
}


text:
Q: linq to entities throwing some error hi i am using this controller
public ActionResult gridview()
        {

  var jsonData = new {
    total = 1, //todo: calculate
    page = 1,
    records = db.TestModels.Count(),
    rows = (
      from question in db.TestModels
      select new {
        id = question.Dataid,
        cell = new string[] {
          question.Dataid, question.Name, question.Emailid
        }
      }).ToArray()
  };
  return Json(jsonData, JsonRequestBehavior.AllowGet);
}
    }

am getting this error
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
can any body help

A: You are trying to use new string[] in a SQL query, but that cannot be translated to SQL. You need to get the data you need from the model, and perform the conversion in-memory. Use .AsEnumerable() to indicate you want to do the following in-memory, and not in the SQL statement.
Something like this:
var jsonData = new {
    total = 1, //todo: calculate
    page = 1,
    records = db.TestModels.Count(),
    rows = db.TestModels
        .Select(x => new { x.Dataid, x.Name, x.Emailid })
        .AsEnumerable()
        .Select(x => new {
            id = x.DataId,
            cell = new string[3] { x.Dataid, x.Name, x.Emailid }
        })
        .ToArray();
};


text:
Q: How to report usernames by date_joined? I am trying to write a report where usernames must be listed grouped by date(date_joined)?
For example:
2015-12-03
    - User1
    - User2
2015-12-04
    - User3
    - User4
How do I approach this problem?
I tried https://coderwall.com/p/z126aa/django-count-user-growth-each-month but it gives only the count but what I need is usernames by date.

A: Presumably you want to output this report in the template. In which case the easiest thing is just to get all Users sorted by date, then use the regroup tag in the template to do the grouping.
View:
users = User.objects.all().order_by('date_joined')

Template:
{% regroup users by date_joined as user_date_list %}

{% for date in user_date_list %}

{{ date.grouper }}

        {% for item in date.list %}

{{ item.username }}

        {% endfor %}

{% endfor %}


text:
Q: Bash Script pipe multiple commands to one email I wanna write the output of various commands as an email.
I tried this:
#!/bin/bash

(echo $(date); echo $(top);sudo apt-get update && sudo apt-get upgrade -y)  | mail -s "Updated!" xxxxxxxxxxx@gmail.com -a "From: UpdateNotify<xxxxxxxx@gmail.com>";

The script is infinite. :/
How can I do that? I need the date,top output and the update logs in one email.

A: That's the right way to do it, the issue is with echo $(top). top is an interactive application so never returns.
You should look to use ps instead to list the current processes running.

A: jas_raj answer is correct, however if you like top's output you can run in batch mode: top -bn 1 this will make top exit right after it runs once.

A: have a look at cron-apt and nullmailer to send mails after system update.


text:
Q: structs, enums, classes, interfaces, anything else? I was pondering of this while I was writing some helper functions dealing with reflection. Is there anything else besides classes, structs, enums and interfaces in C#? If I write a function that checks for class, struct, enum and interface, would that be the all encompassing function?
I read that delegates are classes anyway here and here.
Help me make my idea on this kind of hierarchy perfect:
   reference type                   value type
         |                               |
  ---------------                   ----------
  |             |                   |        |
interface    class                struct    enum

// the all encompassing function - pseudo code:
public static bool IsC#Stuff(this Type type)
{
    return type.IsEnum || type.IsStruct || type.IsClass || type.IsInterface;
}

Am I missing something?

A: There are also arrays and delegates, although those are actually classes.
There are also references (ref parameters to methods) and generic type parameters in definitions of generic methods or types.
In unsafe code, there are also pointers.

A: Not sure is this is a direct answer to your question but .NET has 5 types:
class, struct, interface, delegate, and enum
Common Type System


text:
Q: The purpose of capacitors C1, C2 and C3 in this audio amplifier I am trying to analyse this amplifier circuit and I can not understand what the purpose of the 3 capacitors C1, C2 and C3 are if anyone could explain that would be much appreciated.
Thanks in advance.

A: The capacitors on the output are to remove any DC from the signal and provide some high-pass filtering.
C1, is a feedback capacitor and it can reduce the phase shift in the feedback that can be caused by the input capacitance and series resistance from the signal.  It can add some stability to the amp.


text:
Q: How do I get emacs to reconise my python 3 virtual environment My system is a Mac and I have both python 2 and 3 installed. I am currently working on a side project for which I want to use django 1.8 and python 3.4.
I have created a virtual environment with the python 3 command pyvenv venv in the parent folder of my project (I prefer to have my python project folders to be self contained).
At the moment, I cannot get emacs to recognise and therefore limit all code related assist to the virtual environment.
In addition, is it possible to setup a per project settings such that I can have different projects use different python versions and environment? The ideal scenario will be, when I change into a project directory and start emacs, it will pick all it's environment settings from that project directory according to some local settings file.
I've been seeking help on google and irc for a while now without success.


text:
Q: problems with javafx canvas.setOnKeyPress() detecting keys I'm trying to create a snake game in javafx using canvas and set up onkeypressed on it and noticed that if i press UP arrow the RIGHT arrow cant be detected and sometimes when i press LEFT arrow the DOWN arrow doesnt get detected. The keys work in random sequences but if i press left then up the right key dont work
Here is the part where i set up the keys (they dont do anything other than print on console):
        canvas.requestFocus();
        canvas.setFocusTraversable(true);
        canvas.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent keyEvent) {
                switch (keyEvent.getCode())
                {
                    case UP:
                    case DOWN:
                    case LEFT:
                    case RIGHT:
                        System.out.println(keyEvent.getCode()); break;
                }
            }
        });

Here is the entire class:
public class GUI extends Application{
    private static Text scoreText;
    private static Canvas canvas;
    private int width = 600, height = 400;
    @Override
    public void start(Stage stage) {

        BorderPane borderPane = new BorderPane();
        // holder for canvas
        StackPane holder = new StackPane(addCanvas());
        holder.setStyle("-fx-background-color:#3d494a");
        //add the layouts to the borderpane
        borderPane.setTop(addAnchorPane());
        borderPane.setCenter(holder);
        //the scene
        Scene scene = new Scene(borderPane, width, height);
        scene.getStylesheets().add("/res/style.css");
        //set the stage
        stage.setResizable(false);
        stage.initStyle(StageStyle.TRANSPARENT);
        stage.setTitle("Snake");
        stage.setScene(scene);
        //draws the initial snake at the centre
        new Thread(new SnakeDraw()).start();
        new Thread(new FruitDraw()).start();
        stage.show();
    }

    public AnchorPane addAnchorPane() {
        AnchorPane anchorpane = new AnchorPane();
        anchorpane.setId("anchorpane");
        anchorpane.getStyleClass().add("anchorpane");

        //reset Button
        Button buttonReset = new Button("reset");
        buttonReset.setStyle("-fx-font: 22 arial; -fx-base: #b6e7c9;");
        buttonReset.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                Main.setScore(0);
                GUI.scoreText.setText(String.format("Score: %d", Main.getScore()));
                canvas.getGraphicsContext2D().clearRect(0,0,1000, 1000);
                Main.resetSnake();
                new Thread(new SnakeDraw()).start();
                new Thread(new FruitDraw()).start();
            }
        });

        //Quit Button
        Button buttonQuit = new Button("Quit");
        buttonQuit.setStyle("-fx-font: 22 arial; -fx-base: #b6e7c9;");
        buttonQuit.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                System.exit(0);
            }
        });

        scoreText = new Text(10, 10, String.format("Score: %d", Main.getScore()));
        scoreText.setFont(Font.font("arial", 34));
        HBox scoreBox = new HBox(scoreText);
        HBox hb = new HBox();
        hb.setPadding(new Insets(2, 2, 2, 2));
        hb.setSpacing(10);
        hb.getChildren().addAll(buttonReset, buttonQuit);

        anchorpane.getChildren().addAll(scoreBox, hb);
        AnchorPane.setBottomAnchor(hb, 8.0);
        AnchorPane.setRightAnchor(hb, 5.0);

        AnchorPane.setLeftAnchor(scoreBox, 5.0);
        AnchorPane.setBottomAnchor(scoreBox, 8.0);
        AnchorPane.setTopAnchor(scoreBox, 4.0);

        return anchorpane;
    }

    public Canvas addCanvas() {
        canvas = new Canvas(600,400);
        return canvas;
    }

    public static Canvas getCanvas() {
        //Button mapping
        canvas.requestFocus();
        canvas.setFocusTraversable(true);
        canvas.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent keyEvent) {
                switch (keyEvent.getCode())
                {
                    case UP:
                    case DOWN:
                    case LEFT:
                    case RIGHT:
                    default: System.out.println(keyEvent.getCode()); break;
                }
            }
        });
        return canvas;
    }
}

Also the GraphicsContext of the canvas get called from 2 threads to draw objects onto the canvas:
public class SnakeDraw implements Runnable {
    @Override
    public void run() {
        GraphicsContext gc = GUI.getCanvas().getGraphicsContext2D();
        for (int i = 0; i < Main.getSnakeBlocksSize(); i++) {
            SnakeBlock snakeBlock = Main.getSnakeBlock(i);
            System.out.println(snakeBlock);
            gc.setFill(Color.BLACK);
            gc.fillRect(snakeBlock.getX(), snakeBlock.getY(), snakeBlock.getSizex(), snakeBlock.getSizey());
            System.out.println("Created a snake at: " + snakeBlock.getX() + ", " + snakeBlock.getY());
        }
    }
}

I tried WASD and any other keys and they all seem fine. It's only the arrow keys that are showing this problem, could it be my keyboard thats faulty or something in my code?


text:
Q: how to find $A^{-1}$ in a matrix I have been given this matrix
$$A=\begin{pmatrix} 3 & 9 & 4 \\ 5 & 6 & 8 \\ 1 & 0 & 2 \end{pmatrix}$$
and I have to find $A^{-1}$, how would I go about doing this?

A: One of the first methods commonly taught is to row reduce $\left[\begin{array}{ccc|ccc}3&9&4&1&0&0\\5&6&8&0&1&0\\1&0&2&0&0&1\end{array}\right]$ and put this into reduced row echelon form
Assuming the inverse actually exists where initially we begin with $[A\mid I]$ the result of the row reduction will be $[I\mid A^{-1}]$.  If it is impossible to row reduce in such a way that the left-half of the augmented matrix reduces to the identity then the matrix is not invertible.
Other methods exist as well and can be found on the wiki page.

A: As pointed out by @JMoravitz, one strategy is to use elementary operations to reduce the  augmented matrix
$$
\left[ \begin{array}{c|c} \mathbf{A} & \mathbf{I} \end{array} \right] \to \left[ \begin{array}{c|c} \mathbf{I} & \mathbf{A}^{-1} \end{array} \right].
$$

*

*Swap the first and third rows, this makes the top row look more like the target identity matrix.
2  Row 2: subtract 5 $\times$ row 1. Row 3: subtract 3 $\times$ row 1.

*Normalize rows 2 and 3.

*Subtract row 2 from row 3.

*Normalize row 3.

*Row 1: subtract 2 $\times$ row  3. Row 2: add one third of row  3.

$$
\left[
\begin{array}{rrr|rrr}
 3 & 9 & 4 & 1 & 0 & 0 \\
 5 & 6 & 8 & 0 & 1 & 0 \\
 1 & 0 & 2 & 0 & 0 & 1 \\
\end{array}
\right]
%
\overset{1}{\longrightarrow}
%
\left[
\begin{array}{rrr|rrr}
 1 & 0 & 2 & 0 & 0 & 1 \\
 5 & 6 & 8 & 0 & 1 & 0 \\
 3 & 9 & 4 & 1 & 0 & 0 \\
\end{array}
\right]
%
\overset{2}{\longrightarrow}
%
\left[
\begin{array}{rrr|rrr}
 1 & 0 & 2 & 0 & 0 & 1 \\
 0 & 6 & -2 & 0 & 1 & -5 \\
 0 & 9 & -2 & 1 & 0 & -3 \\
\end{array}
\right]
%
\overset{3}{\longrightarrow}
%
\left[
\begin{array}{rrr|rrr}
 1 & 0 & 2 & 0 & 0 & 1 \\
 0 & 1 & -\frac{1}{3} & 0 & \frac{1}{6} & -\frac{5}{6} \\
 0 & 1 & -\frac{2}{9} & \frac{1}{9} & 0 & -\frac{1}{3} \\
\end{array}
\right]
%
\overset{4}{\longrightarrow}
%
\left[
\begin{array}{rrr|rrr}
 1 & 0 & 2 & 0 & 0 & 1 \\
 0 & 1 & -\frac{1}{3} & 0 & \frac{1}{6} & -\frac{5}{6} \\
 0 & 0 & \frac{1}{9} & \frac{1}{9} & -\frac{1}{6} &
   \frac{1}{2} \\
\end{array}
\right]
%
\overset{5}{\longrightarrow}
%
\left[
\begin{array}{rrr|rrr}
 1 & 0 & 2 & 0 & 0 & 1 \\
 0 & 1 & -\frac{1}{3} & 0 & \frac{1}{6} & -\frac{5}{6} \\
 0 & 0 & 1 & 1 & -\frac{3}{2} & \frac{9}{2} \\
\end{array}
\right]
%
\overset{6}{\longrightarrow}
%
\left[
\begin{array}{rrr|rrr}
 1 & 0 & 0 & -2 & 3 & -8 \\
 0 & 1 & 0 & \frac{1}{3} & -\frac{1}{3} & \frac{2}{3} \\
 0 & 0 & 1 & 1 & -\frac{3}{2} & \frac{9}{2} \\
\end{array}
\right]
$$
Harvest the matrix inverse
$$
  \mathbf{A}^{-1} =
\frac{1}{6}
\left[
\begin{array}{rrr}
 -12 & 18 & -48 \\
 2 & -2 & 4 \\
 6 & -9 & 27 \\
\end{array}
\right]
$$
You should verify that $\mathbf{A} \, \mathbf{A}^{-1}= \mathbf{A}^{-1}\, \mathbf{A}=\mathbf{I}_{3}.$


text:
Q: How can one make a conditional regex replacement in Matcher.replaceAll()? I have a file path that I break into groups (using a regex statement). Each group is separated by a _. Many of the groups are optional groups. It looks like this:
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(path.toLowerCase());

if (matcher.find())
{
    String type = matcher.replaceAll("$2_$3");
    return type.replaceAll("-","_");
}

So, let's say I have a path: hello_world_20190221.xml.json.
Let us also say this is my regex:
(.*?)_(ce)?_?(.*)_([0-9]{8})\.([A-Za-z]{1,20})?\.([A-Za-z]{1,20})?.
Currently, the matcher.replaceAll("$2_$3") statement will return to me type=_world. I need the replacement string to have condition logic. If $2 is empty, return only $3. Otherwise, return $2_$3. Does the replaceAll() function support condition regex logic? I have not had any success with it.
The purpose of this particular piece of code is to consume a path, a regex, and an expression for the replaceAll() function. It returns a group or some concatenation of groups. I cannot change this code to include if statements and the like. but I can change the code in any other way, I think. So, if using a different function all together will do what I want, please suggest one. This piece of code has many different scenarios running through it, so I cannot plan for just one scenario (such as putting an if-statement to check if group 2 is empty or not). All that conditional logic must come through one of those three strings: path, regex, or the replacementString. I can change the function all together, but cannot make it explicitly (through the source code) check to see if thing condition or that condition is met.
Am I making any sense?

A: You can modify your regex to combine optional $2 and $3 in same captured group like this:
^([^_]*)_((?:ce_)?[^_]*)_([0-9]{8})\.([A-Za-z]{1,20})?\.([A-Za-z]{1,20})?

Then you just need to use:
if (matcher.find()) {
    String type = matcher.replaceAll("$2");
    return type.replaceAll("-","_");
}

RegEx Demo

Java code based solution:

need the replacement string to have condition logic. If $2 is empty, return only $3. Otherwise, return $2_$3

Since you already have a matcher, you can do this:
if (matcher.find()) {
    String type = (matcher.group(2) == null || matcher.group(2).isEmpty() ?
       matcher.replaceAll("$2") :
       matcher.replaceAll("$2_$3"));
    return type.replaceAll("-","_");
}

A: Use simply (ce_?)?(.*), and replace by $2$3. If $2 is empty, $2$3 will be $3, else, it will be like $2_$3 :
(.*?)_(ce_?)?(.*)_([0-9]{8})\.([A-Za-z]{1,20})?\.([A-Za-z]{1,20})?

hello_ce_world_20190221.xml.json // ce_world
hello_world_20190221.xml.json    // world


text:
Q: Concatenation of weights in Neural Networks I'm training a special neural network for Natural Language Processing which has an embedding layer (this layer takes a one-hot vector of each word and output it's embedding vector through an embedding matrix). So, what I want to use is two embedding matrix for the same input. Formally, if we have $x \in \mathbb{R}^{1 \times n}$ as input and two embedding matrix $w_1 \in \mathbb{R}^{n \times d1}$ and $w_2 \in \mathbb{R}^{n \times d2}$ I want an output $e \in \mathbb{R}^{1 \times (d1+d2)}$ that contents the two embedding vectors. To do so, we can $x \cdot w_1$ and concatenate it with $x \cdot w_2$ and thus the NN can learn the weights separately. But what I thought is that I can create a "super"-embedding matrix $\in \mathbb{R}^{2n \times (d1+d2)}$ filling with 0's as: \begin{bmatrix} w_1 & 0\\ 0 & w_2\\ \end{bmatrix} and do the dot product with the concatenation of [$x$; $x$]. Finally, I got the same result but I have twice questions:

*

*Which is the most complex (computationally)? The second is bigger but only require one dot product and the concatenation is before the layer.

*Does the weight filled with zeros change its value in the NN learning phase?

Thanks in advance!

A: Multiplying two matrices $A \in R^{m \times n}$ and $B \in R^{n \times p}$ includes $mnp$ scalar multiplications and $m(n-1)p$ additions. In total, it is $mp(2n-1)$ scalar operations.
In your first case you perform two matrix multiplications, which results in $d_1(2n-1)+d_2(2n-1)=(d_1+d_2)(2n-1)$ operations. In the second case, you perform only one matrix multiplication, but the involved matrices are bigger, and so there are $(d_1+d_2)(4n-1)$ operations. Roughly speaking and taking only computational steps into account, the first way is two times faster. However, it requires concatenation and the decision which way to choose depends on the cost of concatenating two vectors. Not knowing how it is implemented in your NN and the programming language that you use, I can say that in general, concatenation is of linear complexity ($O(n)$) and that copying $n$ variables from one array to another should not be as expensive as performing mathematical operations on them, so you should probably be going for the first way. But, if you can, try to avoid allocating new memory when concatenating. It would be wiser to allocate space for one array of size $2n$ and simply copy its first $n$ elements to its second half, than to allocate memory once for an array of size $n$ and other time for an array of size $2n$. Also, if you control allocation, avoid allocating memory for concatenating in each step of your NN. Allocation requires  calls to the operating system, and it slows down your program. Take the memory you need before the NN starts and ensure that it is properly used. The C programming language gives you this level of control, but if these details are out of your control, the first way should still be faster.
The weights with zeros would change during training, but you can always postprocess this super-embedding matrix and ensure that it contains zeros in appropriate positions.


text:
Q: source currently evaluates to an error excel I have two workbooks:

*

*Source.xlsx

*Book1.xlsm
The data in Book1.xlsm is linked to the Source.xlsx via a drop down box in Book1.xlsm reading data from Source.xlsx.
In Source.xlsx the column I referring is Column C. with defined name of Branch
In Book1.xlsm I define the name BT and refers to Source.xlsx!Branch
And data validation it to =BT
Everything runs well until I save, close and reopen it, the error message shows up "source currently evaluates to an error Excel, do you want to continue?"
Where have I gone wrong?

EDIT: I realised that if my Source.xlsx is not open up together with my file, Book1.xlsm drop down list doesn't work Any suggestion on this?
Excel version 2010.

A: The problem could be that it can't find the file once the target is no longer open.
You can add the path to the filename in the formula.
For example instead of:
=Source.xlsx!Branch!$A$1

you would use:
='c:\pathToYourFile\[Source.xlsx]Branch'!$A$1

You can learn more about external cell references at this link and this link.

A: Solve: Remove space from your header and use underscore(_).
wallahu aalam


text:
Q: How to view input based on if condition in PHP MySQLi How to make the if statement, if the the post belongs to the user, then only the owner of the post has a like/view/edit/delete button available. If the post does not belong to the user, it only displays like and view buttons.
<?php
$get_post = "SELECT * FROM posts";
$run_post = mysqli_query($connect, $get_post);
if($run_post && mysqli_num_rows($run_post) > 0)
{
    while($row_post = mysqli_fetch_array($run_post))
    {
        $post_title  = $row_post['post_title'];
        $get_user    = "SELECT * FROM users WHERE user_id='$user_id'";
        $run_user    = mysqli_query($connect, $get_user);
        $check_user  = mysqli_fetch_array($run_user);
        $user_name   = $check_user['name'];
        $user_images = $check_user['images'];

        echo "

$post_title

            <button>Like</button>
            <button>View</button>
            <button>Delete</button>
            <button>Edit</button>

";
    }
    mysqli_free_result($run_post);
}
else
{
    echo "No post yet";
}
?>

A: You have to store user_id as a session value. Then you can checked current user posts this way, $_SESSION['user_id'] == $row_post['user_id']
 echo "

$post_title

           <button>Like</button>
           <button>View</button>";
           if($_SESSION['user_id'] == $row_post['user_id']){
                  echo "<button>Delete</button>
                        <button>Edit</button>";
            }

     echo "
";

A: Please check following answer.
                 $html = "<button>Like</button>
                            <button>View</button>";
                if($user_id == $row_post['user_id']){
                   $html .= "<button>Delete</button>
                         <button>Edit</button>"
                }
  echo $html;

A: Use Following, check if user id and database id are same so that will add extra HTML in $login_user else will be empty. And echo $login_user in your View.
<?php

    $get_post = "SELECT * FROM posts";
    $run_post = mysqli_query($connect, $get_post);
        if($run_post && mysqli_num_rows($run_post) > 0 )
        {
            while($row_post = mysqli_fetch_array($run_post))
            {
                $post_title      = $row_post['post_title'];

                $get_user   =  "SELECT * FROM users WHERE user_id='$user_id'";
                $run_user   = mysqli_query($connect, $get_user);
                $check_user = mysqli_fetch_array($run_user);

                    $user_name  = $check_user['name'];
                    $user_images = $check_user['images'];

                    $login_user = ($user_id == $row_post['user_id'])? "<button>Delete</button>
                                    <button>Edit</button>": "";
                        echo "

$post_title

                                    <button>Like</button>
                                    <button>View</button>".
                                $login_user . "

";
            }
            mysqli_free_result($run_post);
        }
    else
    {
        echo "No post yet";
    }
?>


text:
Q: Does using socket io mean giving up PHP and apache? So I've started working a little with Node JS and socket io for building fast and stable real time web applications (I'm pretty newbie to those).
The thing is that up until now I've been using LAMP and I don't think I am ready to abandon apache and php for developing a website completely with node js.
Can anyone please tell me what is the standard structure of integrating socket io with apache?

A: For any Socket.IO web app you still need:

*

*an HTTP server

*a Socket.IO server

Node.js can do both those, but can't serve PHP content.
Apache can only do the HTTP / PHP parts.
It's perfectly possible to mix and match, but it's down to you do decide whether it's appropriate.

A: You can use multiple technologies on the same Server using different ports,
with no further configuration needed.
If you however want to have PHP and node.js apps on the same port, maybe 80,
you need a proxy.
Using node.s on port 80 with the node-http-proxy module also works like a charm with websockets.
I was searching for a solutions for such a setup recently an ended up with what i wrote down here: http://nerdpress.org/2012/04/20/hosting-multiple-express-node-js-apps-on-port-80/


text:
Q: Upper bounds for $\sum_{i=1}^n |a_i|$, with $a=(a_1,\dots, a_n)$ Let $n\ge 1$ and $a=(a_1,\dots, a_n)\in\mathbb{R}^n$ be a nonnull vector. There is an upper bound for the sum of the magnitude of each component of the vector $a$? I mean, for
$$\sum_{i=1}^n |a_i|?$$
I would say that
$$\sum_{i=1}^n |a_i|\le |a|$$
but I am not sure about that. Here $|a|$ denotes the magnitude of the vector $a$, which is given by
$$|a|=\sqrt{\sum_{i=1}^n |a_i|^2}.$$
Also, I am interested other bounds (maybe finer, if any).
Thank you in advance.

A: This is wrong. Let $a = (3, 4)^\top$:
$$
\sum_{k=1}^2 \lvert a_k \rvert = 7 > \sqrt{\sum_{k=1}^2 \lvert a_k\rvert^2} = 5
$$
What you can do for any $x \in \mathbb{R}^n$. Let $\lvert x_i \rvert = \max_{k \in \lbrace 1, ..., n \rbrace} \lvert x_k \rvert$ is the following:
$$
\sum_{k=1}^n \lvert x_k \rvert \leq n \lvert x_i \rvert = n \sqrt{\lvert x_i \rvert^2} \leq n \sqrt{ \sum_{k=1}^n \lvert x_k \rvert^2 } = n \lvert x \rvert
$$


text:
Q: SlickGrid cell styling lost on Sort When sorting the rows in SlickGrid, it seems that they are all destroyed and recreated, thus losing the CSS classes that may have been added at run-time.
For example, I want rows that are "dirty" (that is, have been edited but not yet saved)((I don't auto-commit, but use a Save button on the grid to persist data)) to display differently, specifically displaying a "dirty" icon.
So, when a row is "dirty", one of its cells (an icon column) gains a CSS class to display the proper icon. This however is then lost when rows are sorted. Is there a way to avoid the creation of brand new rows on a sort? Or a different method to accomplish this task?
Thanks!

A: SlickGrid explicitly forbids direct manipulation of the DOM elements it creates with the exception of editors.  If you need to decorate a cell/row with a CSS class, do so using the APIs provided by SlickGrid (custom formatters, row/cell metadata, addCellCssStyles, etc.).  That way, they will persist across re-renders.


text:
Q: Tool for selectively undo'ing changes to a file managed by SVN I need to selectively revert a few lines in a massive file (to be specific, Xcode changed some settings in a project file that I need to revert before committing). I was told there is a tool that will interactively go through the file, diff by diff, and allow you to make changes.
I think it was called svn-view-diffs but I can't find any reference to it.
How may I accomplish this task?
thanks

A: Something like SCPlugin for Finder will be able to help you
For the exact purpose of seeing diffs though, there is Diffly which is not really a full blown SVN client but will be suitable for what you want.
I think SVNX is the most popular Mac OS client for SVN and it has FileMerge integration
Just look at these tools or search for Mac OS diff or SVN client. There are quite a few around and I think there should be some integration with Xcode as well.

A: I have used tool called svn-view which works similar to CVS view and web module. And i just found web module can be downloaded : http://public.e-tunity.com/web-svn-view/web-svn-view.html
In mean time, Atlassian tools also avialble for that. If you can use Windows environment TortoiseSVN client also help you do that. You can browse repository and see the changes for each files too. http://tortoisesvn.tigris.org/

A: Here's a few choices for 'merge' tools, all of which are also used for showing differences between files. Most allow you to edit one file inside the tool, either by editing directly or clicking on differences.


text:
Q: target the  tag for the dynamically created divs using jquery I am a total beginner to jquery. and am badly stuck. i would really appreciate if i could get some help with my code.
The scenario is,
  - I have a drop down list for the names.
  - When i select a name from the list, it should display in the div which is placed beneath the drop down menu. The div will be created automatically via jquery. every item selected from the list will be displayed in its own respective div. The name Sarah should not be included in the drop down list.Its like a stand alone thing. However, when i select an item in the list, the name Sarah is replaced with the selected item.
What i was able to code was --
  - I could get the divs with some names associated with it. However, i am unable to target the selected item to its respective div.
  I hope it makes sense. I am posting the link to my jsFiddle. Please help.
http://jsfiddle.net/zohana28/0akosx2a/

    <select id="sel">
        <option value="Cheese">Cheese</option>
        <option value="Olives">Olives</option>
        <option value="Pepperoni">Pepperoni</option>
        <option value="Oregano">Oregano</option>
        <option value="Thyme">Thyme</option>
    </select>

sarah

jQuery is:
     $(document).ready(function () {
      $(document).on('change', '#sel', function (e) {

        $('.part-3').html($('.part-2').html());

       $('.main').append('

');

       var str = $('select option:selected').text();
        $('#name').text(str);
        console.log(str);

      });
  return false;

  });

thank you in advance.

A: I've adjusted your Fiddle a bit.
 $(document).ready(function () {
  $(document).on('change', '#sel', function (e) {
      var nameTempl = '
'
          + '
'
          + '
{name}

';
      var str = $('select option:selected').text();
      $('.main').append(nameTempl.replace(/{name}/, str));
  });
  return true;
});

For the HTML: I removed the inline-style cursor:pointer; and added it as style for the class .click-1 - previously click-1 and name were ids, I've changed both to be classes. ids have to be unique, so you have to use classes instead.
Though it would be possible to clone() the
 and then change the name to the current selected option, I just preferred to use the target div as template in the function, with {name} as placeholder to be replaced with the current selected option: nameTempl.replace(/{name}/, str).
Another adjustment that you can change back is - I've set the height:200px; of the .main div to  min-height: 200px;, so this container grows when necessary. You can just change this back to height:200px; in case you prefer the yellow div to have a static height like before.
As reference for replace(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace


text:
Q: Using getline consecutively causes segmentation fault I'm trying to read two consecutive lines of input from stdin using getline. This minimal code causes a segmentation fault and I'm not sure why:
int main() {
    char *ln1 = NULL;
    char *ln2 = NULL;
    size_t lnsz1;
    size_t lnsz2;

    getline(&ln1,&lnsz1,stdin);
    getline(&ln2,&lnsz2,stdin);

}

Can someone explain what I'm doing wrong?

A: I said in a comment that setting the size to zero (as well as the pointer to a null pointer) should fix the observed crash.
Lurking in the background is a hypothesis that the specific implementation of getline() causing the crash is somewhat faulty.  One possible way in which it could be faulty is if it uses the size argument when allocating space because the pointer is null.  That is somewhat improbable, but the question gives no information on which platform yields the crash.
The POSIX specification of getline() says:

ssize_t getline(char **restrict lineptr, size_t *restrict n, FILE *restrict stream);
…
The application shall ensure that *lineptr is a valid argument that could be passed to the free() function. If *n is non-zero, the application shall ensure that *lineptr either points to an object of size at least *n bytes, or is a null pointer.
If *lineptr is a null pointer or if the object pointed to by *lineptr is of insufficient size, an object shall be allocated as if by malloc() or the object shall be reallocated as if by realloc(), respectively, such that the object is large enough to hold the characters to be written to it, including the terminating NUL, and *n shall be set to the new size. If the object was allocated, or if the reallocation operation moved the object, *lineptr shall be updated to point to the new object or new location.
…
Upon successful completion, the getline() and getdelim() functions shall return the number of bytes written into the buffer, including the delimiter character if one was encountered before EOF, but excluding the terminating NUL character. If the end-of-file indicator for the stream is set, or if no characters were read and the stream is at end-of-file, the end-of-file indicator for the stream shall be set and the function shall return -1. If an error occurs, the error indicator for the stream shall be set, and the function shall return -1 and set errno to indicate the error.

The code in the question is not self-evidently abusing those rules.  The application ensures that *lineptr is a null pointer — which is a value that can be passed to free().  It doesn't much matter what the value of *n is because *lineptr is a null pointer.
One way to experiment is to try printing the value in the uninitialized variables (lnsz1 and lnsz2), but such experimentation is arguably invoking undefined behaviour.  Another is to initialize the variables to some large values — such as SIZE_MAX or SIZE_MAX / 2 (where SIZE_MAX defined in C11 <stdint.h> but not in earlier versions of the C standard) or other similar inflated values.  You should also test with a value of 0, of course, and some testing could be done with other small values such as 1, 8, 16 etc.  All of these tests would be conducted with the pointers set to a null pointer.  If you can use a memory allocation package such that a debugging version of malloc() (or realloc()) is called, you may be able to log the requested size of the memory.  You may get some information from printing the value of lnsz1 after the first call to getline() if the crash occurs on the second call.
Such an investigation is barely worth the effort, though.  Setting both the pointers and the sizes to zero should resolve the problem.  If it doesn't, there is more to investigate.  That is, however, unlikely to be the problem.
//#define _XOPEN_SOURCE 700 // Explicitly request POSIX support
#include <stdio.h>

int main(void)
{
    char *ln1 = NULL;
    char *ln2 = NULL;
    size_t lnsz1 = 0;
    size_t lnsz2 = 0;
    ssize_t len1 = -1;
    ssize_t len2 = -1;

    if ((len1 = getline(&ln1, &lnsz1, stdin)) != -1)
    {
        printf("%zd (%zu: %p) [%s]\n", len1, lnsz1, (void *)ln1, ln1);
        if ((len2 = getline(&ln2, &lnsz2, stdin)) != -1)
            printf("%zd (%zu: %p) [%s]\n", len2, lnsz2, (void *)ln2, ln2);
    }
    free(ln1);
    free(ln2);

    return 0;
}

Note that getline() specifically returns -1 and not EOF when it detects an error or end-of-file.  On most systems, the two values are the same, but the C standard only requires that EOF is negative — it does not require that it is -1.  I cannot determine any circumstance under which a return value of 0 is valid for getline().


text:
Q: My computer slows down gradually after running this .py file I am trying to get random 100K songs from musicbrainz database which is locally saved. I'm new to programming and want to know what is the reason behind my computer slowing down (probably ram filled). I'm running ubuntu on virtual machine. Please suggest some changes so I can go to sleep after running this.
import psycopg2
import random
import MySQLdb
from contextlib import closing

conn = psycopg2.connect("dbname='musicbrainz' user='musicbrainz' host='localhost' password='musicbrainz'")
conn1 = MySQLdb.connect(host = "localhost", user = "root", passwd = "40OZlike", db = "plalyst")
print("connections and cursors made...")
cur= conn1.cursor()
conn1.set_character_set('utf8')
cur.execute('SET NAMES utf8;')
cur.execute('SET CHARACTER SET utf8;')
cur.execute('SET character_set_connection=utf8;')
cur.close()

def migrateSongDB():
    try:
        cur1 = conn1.cursor()
        cur1.execute("select count(*) from Song")
        numberOfSongs = cur1.fetchall()[0][0]
        cur1.close()
        print("number of songs in our database is ")
        print(numberOfSongs)
        rnumbers = random.sample(range(1, 22660511), 100000-numberOfSongs)
        print("random numbers generated....")
        for eachnum in rnumbers:
            cur = conn.cursor()
            cur1 = conn1.cursor()
            print(eachnum)
            songName=""
            while(songName==""):
                cur.execute("""select name from track where id = %s """, (eachnum,))
                rows = cur.fetchall()
                print(rows)
                if not len(rows)==0:
                    songName = rows[0][0]
                eachnum+=1
            print("Got the track name:")
            print(songName)
            sql = 'INSERT into Song (name) values ( "'+songName+'")'
            print(sql)
            cur1.execute(sql)
            cur1.execute('commit')
            print("inserted into the song table....")
            cur.close()
            cur1.close()

        print("Songs Saved into new Data Base...")
        conn.close()
        conn1.close()
        print("Connections Closed")
    except:
        with conn1 as cursor:
            cursor.execute('select 1;')
            result = cursor.fetchall()
            for cur in result:
                print(cur)
        migrateSongDB()

def main():
    migrateSongDB()
    conn.close()
    conn1.close()

if __name__ == "__main__": main()

Thank you for your time to read this code.
Also, if you guys have any suggestions for me to improve my coding style I would love to learn.
Thank you once again.

A: My hunch is that the IDs you pull out of a hat are eventually going to wander into territory in which the ID doesn't exist.  This means that you're going to run an perpetually long* loop, which is inefficient.
Instead of this approach, why not just pull the IDs out of the database which are known and select on that, instead?
You can accomplish that with this.  I've borrowed a list flattening operation from this Stack Overflow answer which will make working with the ID list a cinch.
cur1.execute("select id from Song")
result = cur1.fetchall()
result = [item for sublist in result for item in sublist]
# result holds the total amount of elements in your Song DB
# use len() to get the total number of rows from here
rnumbers = random.sample(result, 100000-len(result))

You can then get rid of the while loop, since you're guaranteed to have an ID that actually exists in your database.


text:
Q: How to set the sorting order (asc/desc) of an array based on dynamically selected property I have an an array of movie objects of the following structure:
$scope.movies = [
  {title: "some title", rank: 13, imdbRating: 828},
  // ...
];

and I would like to sort them by the property title, rank or imdbRating - selected with <select>, and by asc/desc ordering - selected with buttons. This is what I did, however, the ordering seems to get reset.
<select ng-model="orderProp" id="input">
    <option  value="title">Alphabetical</option>
    <option  value="rank">Rank</option>
    <option  value="imdbRating">Rating</option>
  </select>
  <button ng-click="orderProp='+'-orderProp;orderProp='-'-orderProp; orderProp='+'+orderProp " >Asc
  </button>
  <button ng-click="orderProp='+'-orderProp;orderProp='-'-orderProp;orderProp='-'+orderProp" >Desc
  </button>

What I want to do is to choose an option to select the sorting property orderProp and if user clicks "asc" or "desc" buttons to re-order the list.
However, ordering does not know what categories I am sorting by so it can not do asc or desc correctly. Option get deleted as well visually if i click the asc / desc buttons.
Is there good solution to this?

A: The orderBy filter accepts two parameters: 1) the property, and 2) the order:

So, in your case, you need to set the isReverse in the ng-click of a "Asc"/"Desc" buttons accordingly. You are already setting the property correctly with <select>.
<select ng-model="orderProp">

</select>

<button ng-click="isReverse = false">Asc</button>
<button ng-click="isReverse = true">Desc</button>

It's also a good idea to set the initial value of these in the controller:
$scope.isReverse = false; // for ascending order
$scope.orderProp = "title";

plunker - for illustration


text:
Q: Equal variables - Batch So, I've the following batch script:
@echo off
 set /p name=
 rem a random number, don't care about it.
 set complete_name=%name%.Creepy
 Goto STEP1
:STEP1
 echo %complete_name%|findstr /C:"9000" >nul 2>&1
 if not errorlevel 1 (
 goto 9000
 ) else (
 GOTO CHECK2
 )
 :CHECK2
 echo %complete_name%|findstr /C:"930" >nul 2>&1
 if not errorlevel 1 (
 goto 930
 ) else (
 GOTO CHECK3
 )
 :CHECK3
 echo %complete_name%|findstr /C:"310" >nul 2>&1
 if not errorlevel 1 (
 goto 310
 ) else (
 ECHO PROBLEM
 )
 :9000
 ECHO 9000
 PAUSE
 :930
 ECHO 930
 PAUSE
 :310
 ECHO 310
 PAUSE

I want it to check if "9000" is in the variable or not, same for "930" and "310". And if none of these numbers are in the variable Echo problem. But everytime i run this script it goes to ECHO PROBLEM even if 9000/920/310 is in %complete_name%. So, is this the right way to check if a variable is in another one or there is an easier way to do it?
So I've tried this code:
@echo off
set name=310
set complete_name=%name%.Creepy
Goto STEP1
:STEP1
 setlocal
    if "%complete_name:9000=%"=="%complete_name%" (
      if "%complete_name:930=%"=="%complete_name%" (
        if "%complete_name:310=%"=="%complete_name%" (
        echo PROBLEM
        ) else (
        goto 9000
        )
      ) else (
      goto 930
      )
    ) else (
    goto 310
    )
    goto :eof

but I'm stuck at echo problem...

A: Save next code snippet, possibly named blabla.bat:
@Echo OFF
setlocal
set complete_name=%1
if "%complete_name:9000=%"=="%complete_name%" (
  if "%complete_name:930=%"=="%complete_name%" (
    if "%complete_name:310=%"=="%complete_name%" (
      echo problem
    ) else (
      echo valid 310
    )
  ) else (
    echo valid 930
  )
) else (
  echo valid 9000
)
Exit /B

and watch the output from
blabla x9000y
blabla x930y
blabla x310y
blabla x9a0b0c0y

That's a way of 1. nested IF ... ( ... ) ELSE ( ... ) and 2. using "Edit/Replace" a variable
Or, if GOTOs considered necessary, there is something similar with For loop (a good thought topic as well..).
@Echo OFF
setlocal EnableDelayedExpansion
set complete_name=%1
for %%G in (9000 930 310) DO (
  if /I "!complete_name:%%G=!" neq "%complete_name%" GOTO :%%G
)
echo problem %complete_name%
GOTO :commonEnd
:9000
  Echo valid 9000 %complete_name%
  GOTO :commonEnd
:930
  Echo valid 930 %complete_name%
  GOTO :commonEnd
:310
  Echo valid 310 %complete_name%
  GOTO :commonEnd
:commonEnd


text:
Q: How to authorize snapshots for gcloud I have:

*

*Initialized gcloud.
gcloud init

*Generated a key for a service account from the IAM console. (web interface)
-> The service account has "Editor" privileges for my project.

*Authorized the service account.
gcloud auth activate-service-account --key-file mykeyfile
However, when I try to access the snapshots management features:
$  gcloud compute snapshots list
ERROR: (gcloud.compute.snapshots.list) Some requests did not succeed:
 - Insufficient Permission

I can't find anywhere in the documentation specifically how I grant permission to gcloud to allow it to do this.
Any tips?

A: The solution is to not use the default service account, but to create a new one.  I posted this question to the gce forum and got an answer there:
https://groups.google.com/forum/#!topic/gce-discussion/3QIjjawlqkY
1)  From the GCE web console, create a new service account.
   a)  Give the new account 'Editor' permissions.
   b)  Download the key for the new account.
2)  Authorize the account:
gcloud auth activate-service-account --key-file  some_key_file

Note:  The key file may download with spaces in the name.  The gcloud command line does not like spaces, even if you wrap the name with "".  Rename it without spaces and then try the above command.
3) Make sure the account is selected:
gcloud auth list

Note:  If it isn't 'ACTIVE', you can set the service account being used with:
gcloud config set account someaccount@someproject-iam.gserviceaccount.com

4) That is it, you should be good to go now.


text:
Q: Where do you keep your Stubs? One of the JUnit best practices is : same package, separate directories. I am wondering what is the equivalent for Mock classes ? Do you keep them in the same package as classes they are supposed to mock, but in the test directory ? or elsewhere ?

A: Like many things in programming, "it depends."  Here are some rules of thumb I use:

*

*If I have a stub that is only used by one test and is small - create an inner class

*If I have a stub that is only used by one test and is large - put in same package/folder as test

*If I have a stub that is used by multiple tests in the same package - put in same package/folder as test

*If I have a stub that is used in many places in the same application - put in a test.util package

*If I have a stub that is used across applications, put it in a jar.

I have instances of all of these in my code.


text:
Q: Database and server triggers on DDL statements CREATE, ALTER and DROP are not supported with memory optimized tables I am getting this error when i try to drop a memory optimized table.  i am using a sql server 2016 sp1
Database and server triggers on DDL statements CREATE, ALTER and DROP are not supported with memory optimized tables.
I have dropped the sec policy and the 2nd index.  I can't drop the spidfilter as you have to have 1 index for the MOT.  Just to see if that made a difference. it did not.
code is below:
create table dbo.MOT_tmpTableName
    (
    Col1    int,
    Col2    int,
    Col3    smalldatetime,
    Col4    smalldatetime,
    Col5    varchar(25),
    Col6    date,
    Col7    smallint,
    Col8    smallint,
    Col9    smallint,
    Col10    smallint,

    SpidFilter          smallint    not null   DEFAULT (@@spid),

    index nIX_SpidFilter nonclustered (SpidFilter),
    index nIX_Col1_Col2_Col3 nonclustered (Col1, Col2, Col3),

    CONSTRAINT CHK_MOT_tmpTableName_SpidFilter
        CHECK ( SpidFilter = @@spid ),
)
WITH
    (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_ONLY);
go

create security policy dbo.MOT_tmpTableName_SpidFilter_Policy
    ADD FILTER PREDICATE dbo.fn_SpidFilter(SpidFilter)  ON dbo.MOT_tmpTableName
    WITH (STATE = ON);
go

i have asked around and other environments do not have this issue.  I can't get the "Database and server triggers..." out of my head.  What trigger is firing that is causing an error?

A: No, databases with In-Memory OLTP enabled do not support DDL triggers.
Both database-level and server-level DDL triggers are not supported with In-Memory OLTP tables and natively compiled modules.
You cannot create DDL triggers in a database where In-Memory OLTP is enabled since the code path required to run the trigger would interfere with the In-Memory functionality. The workaround is to put all your In-Memory OLTP tables in a single database without a DDL trigger, and the rest of your tables into a separate database without memory-optimized tables, and enable the DDL Trigger there.

A: There is probably DDL trigger active in your Database or your Server.
If you are using SQL Server Managment studio, these could be found under "Databases" -> "Database_name" -> "Programmability" -> "Database triggers" folder for database trigger and under "Server objects" -> "Triggers" folders in Object Explorer.
Pure t-SQL search:
SELECT
  *
FROM
  database_name.sys.triggers AS T
WHERE
  T.parent_class = 0;

SELECT
  *
FROM
  sys.server_triggers AS ST;


text:
Q: Can this powerful version of inverse function theorem be extended to $\mathbb C^n$? I'm reading inverse function theorem (IVT) at page 306 of Amann's Analysis I, i.e.,

Amann's IVT: Let $X$ be an open subset of $\mathbb{K} \in \{\mathbb{C}, \mathbb{R}\}, f: X \rightarrow \mathbb{K}$, and $Y:=f(X)$. Let $f$ be injective and consider the inverse $f^{-1}: Y \rightarrow X$ of $f$. Suppose that $f$ is differentiable at $a \in X$, and $f^{-1}$ is continuous at $b:=f(a) \in Y$. Then $f^{-1}$ is differentiable at $b$ if and only if $f^{\prime}(a) \neq 0$. In this case, $\left(f^{-1}\right)^{\prime}(b)=1 / f^{\prime}(a)$.

This version does not require $f'$ to be continuous, which distinguishes itself from the standard version. Moreover, a continuous bijection $f:\mathbb C \to Y \subset\mathbb C$ is a homeomorphism by invariance of domain theorem. So Amann's IVT is indeed powerful.
I would like to ask if Amann's version can be extended to multivariate setting, i.e.,

Let $X$ be an open subset of $\mathbb{K}^n$ where $\mathbb{K} \in \{\mathbb{C}, \mathbb{R}\}, f: X \rightarrow \mathbb{K}^n$, and $Y:=f(X)$. Let $f$ be injective and consider the inverse $f^{-1}: Y \rightarrow X$ of $f$. Suppose that $f$ is differentiable at $a \in X$, and $f^{-1}$ is continuous at $b:=f(a) \in Y$. Then $f^{-1}$ is differentiable at $b$ if and only if $f^{\prime}(a)$ is invertible. In this case, $\left(f^{-1}\right)^{\prime}(b)=[f^{\prime}(a)]^{-1}$.

Thank you so much for your help!


text:
Q: Definition of 'term t is free for v in $\phi$' in predicate logic I'm trying to get my head around the expression "term $t$ is free for variable $v$ in formula $\phi$". This is defined in many sources as:
(Def 1)"$t$ is free for $v$ in $\phi$ if there is no variable $v_1$ in $t$ such that $v$ has a free occurrence in the scope of a quantifier $\forall v_1$ or $\exists v_1$.
In other sources it is introduced (informally) as:
(Def 2)"If no variable capture occurs during the substitution of $t$ into free occurrences of $v$ in $\phi$, then $t$ is free for $v$ in $\phi$."
Question 1: After substituting $t$ into every free occurrence of $v$ in $\phi$, if every variable of $t$ is a free variable in the resulting formula, then $t$ is free for $v$ in $\phi$. Is this correct? I don't understand why.
Question 2: Consider the formula $\phi : \forall v, \  (v \doteq v_1)$. Is $v_1$ free for $v$ in $\phi$? According to definition 1, it is not, as $(v \doteq v_1)$ has a free occurrence of $v$. However, according to definition 2, it is, as $\phi[v_1/v] = \forall v, \  (v \doteq v_1)$ (as we are only concerned with free occurrences of $v$ when doing substitution), and no variable capture has occurred. Where have I gone wrong?
Is (non-appearing in $\phi$) variable $v_2$ free for variable $v_3$ in $\phi$? There is no variable capture after substitution, because substitution $\phi[v_2/v_3]$ in this case does nothing.
Question 3: Is the following true? $v$ is free for $v$ in $\psi$, no matter what the formula $\psi$ is.
Question 4: $v$ is not a free variable of sentence $\theta$ and $v$ is a free variable in $\phi(v)$.  Then $v$ is free for $v$ in the formula $\theta\to \phi(v)$.
I'm finding this concept so confusing. Can anyone help clarify this? Thanks.


text:
Q: How to automatically add text to inserted rows Below is some code I have to automatically insert 6 lines below each pre-existing row item on a sheet. Is there a way to populate each of the 6 lines with prerendered text? The text can just be, respectively per line, 'item1', 'item2', 'item3'...
Dim lastRow As Long
lastRow = Range("B" & Rows.Count).End(xlUp).Row

Dim rowCnt As Long
For rowCnt = lastRow To 2 Step -1

Range("B" & rowCnt).Resize(6, 1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

Next

Thanks in advance for the assistance!

A: Try adding the text as a transposed array.
dim itms as variant

itms = array("item1", "item2", "item3", "item4", "item5", "item6")

...

For rowCnt = lastRow + 1 To 2 Step -1

    Range("B" & rowCnt).Resize(6, 1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("B" & rowCnt).Resize(6, 1) = application.transpose(itms)

Next

A: Here is one way.
Sub x()

Dim lastRow As Long

lastRow = Range("B" & Rows.Count).End(xlUp).Row

Dim rowCnt As Long, i As Long

For rowCnt = lastRow To 2 Step -1
    Range("B" & rowCnt).Resize(6, 1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("B" & rowCnt + 7).Resize(6).Value = Application.Transpose(Array("Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"))
Next

End Sub


text:
Q: Mpchart float value not showing in array list I am using mpandroid chart library, I want to show float value in line graph but it shows normal value.
Screenshot.
My code:
if (cursor != null) {

            for (int h = 0; h < cursor.getCount(); h++) {

                cursor.moveToNext();

                ans = cursor.getString(cursor.getColumnIndex("pnt_triiodothyronine"));

                entry1.add( new Entry(cursor.getFloat(cursor.getColumnIndex("pnt_triiodothyronine")),h));
                entry2.add( new Entry(cursor.getFloat(cursor.getColumnIndex("pnt_thyroxine")),h));
                entry3.add( new Entry(cursor.getFloat(cursor.getColumnIndex("pnt_tsh")),h));
                entry4.add( new Entry(cursor.getFloat(cursor.getColumnIndex("pnt_weight")),h));
                entry5.add((cursor.getString(cursor.getColumnIndex("date"))));

                ansText.setText(ans);
            }

            cursor.close();

        }

lDataSet1 = new LineDataSet(entry1, "T3");
        //lDataSet1.setDrawFilled(true);
        lDataSet1.setColors(new int[]{getResources().getColor(R.color.purple)}); //resolved color
        lDataSet1.setCircleColor(Color.parseColor("#ffffff"));
        lDataSet1.setLineWidth(1.5f);
        lDataSet1.setCircleColorHole(Color.parseColor("#9c27b0"));
        lDataSet1.setHighLightColor(Color.rgb(190, 190, 190));
        lDataSet1.setDrawCubic(true);
        //lDataSet1.setDrawFilled(true);
        lines.add(lDataSet1);

A: look into ValueFormatter
As described there in the wiki, create your own ValueFormatter and set the format you wish.
public class MyValueFormatter implements IValueFormatter {

    private DecimalFormat mFormat;

    public MyValueFormatter() {
        mFormat = new DecimalFormat("###,###,##0.0"); // use one decimal
    }

    @Override
    public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
        // write your logic here
        return mFormat.format(value) + " $"; // e.g. append a dollar-sign
    }
}

Then apply your Formatter to the ChartData or DataSet object:
// usage on whole data object
lineData.setValueFormatter(new MyValueFormatter());

// usage on individual dataset object
lineDataSet.setValueFormatter(new MyValueFormatter());


text:
Q: Pressing tab doesn't change between textboxes I have the following class called "PlaceholderTextBox" which to act as a textbox with a placeholder text:
internal class PlaceholderTextBox : TextBox
{
    private bool isPlaceHolder = true;
    private bool isPassword;
    private string _PlaceholderText;
    private string _InputText;

    public string PlacehoderText
    {
        get { return _PlaceholderText; }
        set { _PlaceholderText = value; setPlaceholder(); }
    }

    public string InputText
    {
        get { return _InputText; }
        set { _InputText = value; }
    }

    public bool IsPassword
    {
        get { return isPassword; }
        set { isPassword = value; }
    }

    private void setPlaceholder()
    {
        if (string.IsNullOrEmpty(this.Text))
        {
            this.Text = PlacehoderText;
            InputText = "";
            this.ForeColor = System.Drawing.Color.Gray;
            isPlaceHolder = true;
            if (isPassword) this.UseSystemPasswordChar = false;
        }
    }

    private void removePlaceHolder()
    {
        if (isPlaceHolder)
        {
            this.Text = "";
            this.ForeColor = System.Drawing.SystemColors.WindowText;
            isPlaceHolder = false;
            if (isPassword) this.UseSystemPasswordChar = true;
        }
    }

    public void resetText()
    {
        isPlaceHolder = true;
        this.Text = null;
        setPlaceholder();
    }

    public PlaceholderTextBox()
    {
        Enter += removePlaceHolder;
        Leave += setPlaceholder;
        TextChanged += addText;
    }

    private void setPlaceholder(object sender, EventArgs e)
    {
        setPlaceholder();
    }

    private void removePlaceHolder(object sender, EventArgs e)
    {
        removePlaceHolder();
    }

    private void addText(object sender, EventArgs e)
    {
        InputText = this.Text;
    }
}

In my main Form, I have two of these PlaceholderTextBoxes, one for "Username" and the other for "Password", which also has bullets cover for protecting the text entered. The problem I found is that, if I want to switch from the password textbox to the other one using "Tab" key, it doesn't work. It works fine if it has some text or if I want to switch from Username to Password, but if I don't have any text in the Password box and I want to switch to Username, it doesn't work.
I have absolutely no idea why is not working, my guess would be it has something to do with the password cover system. Any insights on this issue?


text:
Q: How can I intercept all calls to methods in a WCF .svc service? Ive got a WCF service which has multiple web methods in it. I want to be able to intercept the request on all methods and look at the Ip address. Id rather not put the logic into a method call at the top of each called web method is there a way to intercept all calls to these methods from one place?
If it was a page I would write a base page object but im nout sure if there are events raised on a wcf call?

A: WCF allows you to implement interceptors that are added to the stack. See this link for an example. I´m not sure whether this allows you the extract the senders IP but I think it´s worth a try.

A: You can implement IDispatchMessageInspector and do something like this.
public object AfterReceiveRequest(ref Message request,
IClientChannel channel, InstanceContext instanceContext)
    {
        RemoteEndpointMessageProperty remoteEndpoint = request.Properties
    [RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

        //remoteEndpoint.Address will give you the address.

        return null;
    }

A: You can use Custom Behaviors, they are part of WCF Extensibility features. Here's more information: Extending WCF with Custom Behaviors

A: There's a clever way to do this with the ServiceAuthorizationManager, and it's far easier than all the seriously hard work of the IDispatchMessageInspector.
Create a class in your WCF Service project like so:
public class MyServiceAuthorizationManager : ServiceAuthorizationManager
{
  protected override bool CheckAccessCore(OperationContext operationContext)
  {
    string classMethod = operationContext.RequestContext.RequestMessage.Headers.Action;
    if (classMethod.Contains("/transfer/Get"))
    {
      return true; // because someone is simply updating a client service reference
    }
    Console.WriteLine("Class Method Call: {0}",classMethod);
    // do something with operationContext here as you need to inspect stuff
    // return true if you want this class method call to succeed and go through
    // return false if you want this class method to fail on the client
    return true;
  }
}

Then, in your service, right before your host.Open() call, add the link to MyServiceAuthorizationManager.
ServiceHost host = new ServiceHost(typeof(MyProject.Service1));
host.Authorization.ServiceAuthorizationManager = new MyServiceAuthorizationManager();
host.Open();

Now when you test your client connections, you'll notice that the console outputs what class method was called. You can also work against all the stuff in the operationContext object.
One way I use this is for a security header check. In my client, I add a header. Then, in the service, in this CheckAccessCore() call, I verify that this custom header exists. If it doesn't, then I return false. This is one more layer of protection that keeps the hackers out, and is great for the limited security in Named Pipes configurations too. If you're wanting to also do that, then click here for more information on how to add custom headers that automatically get sent on every client's method call on the service.
And note, among all this, I didn't have to mess with behaviors, claims, listeners, or message dispatches. I also didn't need to edit my WCF Configuration.
Note the string check for /transfer/Get above. This is important if you're doing header checks as a security mechanism like I was. If you don't have that condition and return true, then your WCF client IDE can't update its ServiceReference because the IDE doesn't know about that extra header (if you're adding a custom header and not specifying that header in the WCF client's app.config). Otherwise, you'll get an error The URI prefix is not recognized.


text:
Q: What is cfinteractive process in Yocto? I am facing a problem with my Camera image fetching program stop working. When the program has no response, I captured the following info by ps command:

What is the first process cfinteractive?

A: cfinteractive is a kernel thread for the Interactive governor of the CPUFreq driver.  You can verify that your system is using this governor with:
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
And you can temporarily disable CPU frequency scaling with the command:
echo performance > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
You need to do that for each of your CPUs.


text:
Q: What is the structure of "dorm room door"? Is it genitive? I wonder where we can make genitive without 's or of. I know that using "of" in "dorm room door" might be complicated but the question is when we are allowed to make such phrases.

A: Swan in Practical English Usage  has an entry called noun + noun: advanced points. In the parts section (p360) he states:

We use the 's structure to talk about parts of people's and animals'
bodies.

*

*a man's leg -- an elephant's trunk -- a sheep's heart.

But to talk about parts of non-living things, we usually use the noun + noun
structure.

*

*a table leg (NOT a table's leg)

*a car door (NOT USUALLY a car's door)

This is not a hard-and-fast rule, as indicated by the not usually in the last example. Nevertheless, it is a useful guideline for English language learners.


text:
Q: The sudden change of the gauge in dojox.dgauges. not like in dojox.gauges Is there a possibility that the needle is gradually changing value when is updating like in dojox.gauges
You can see in this example, when you press the button set 15
 the value changed directly to 15.
Is that a possibility to make it gradual passing by intermediate values ?

A: The property you're looking for is animationDuration, per the API docs on dojox/dgauges/CircularRangeIndicator:

The duration of the value change animation in milliseconds. Default is
  0. The animation occurs on both user interactions and programmatic value changes. Set this property to 0 to disable animation.

I created a test jsfiddle  to demonstrate this:
Markup:

Code:
require(['dojo/parser', 'dojox/dgauges/components/default/CircularLinearGauge', 'dojo/domReady!'], function (parser, CircularLinearGauge) {
    parser.parse();
    console.log('parsed');
    setInterval(function () {
        var newVal = Math.ceil(Math.random() * (100) - 50);
        console.log('setting value to', newVal);
        gauge.set('value', newVal);
    }, 1000);
});


text:
Q: How do I have Ruby YAML dump a Hash subclass as a simple Hash? I have a class Foo that is a subclass of Hash.
class Foo < Hash
  # whatever Foo-specific methods/etc
end

When I dump it to a file with YAML, it is written with a tag indicating the class.
> f = Foo.new
> f[:bar] = "baz"
> puts YAML.dump(f)
--- !ruby/hash:Foo
:bar: baz

I would like it to just be written as a plain old hash (not !ruby/hash:Foo)
> puts YAML.dump({bar:"baz"})
---
:bar: baz

...so that consumers of my data don't need to know about Foo. Is there a magic method to add to my class to convert itself for serialization, or a magic option to pass to YAML.dump?
Of course it is easy to convert one Foo object to a hash, but they may show up nested at any level inside the actual hash I'd like to dump, and I'd rather not have to do a search and replace.

A: You can achieve this with the (poorly documented) encode_with and represent_map methods. To customise the YAML serialisation of an object you provide it with an encode_with method which accepts a coder object, one of the methods on which is represent_map.
class Foo < Hash

  # other methods ...

  def encode_with coder
    coder.represent_map nil, self
  end

end

Now YAML.dump will just output your object as a normal hash.
However
There is a bit of a problem because there is a bug that will cause this to fail and is only fixed in the latest Gem version of Psych. It is not fixed in the current latest Ruby version (ruby 2.0.0p247). It is fixed in Ruby trunk so later patch releases should be okay.
In order to use this you will have to make sure you are using the latest Psych Gem, rather than the version bundled with Ruby. This should be as easy as
gem 'psych', '2.0.0'

before you require Yaml, but it seems that in Ruby 2.0 this doesn't work for some reason that I can't figure out. Using Bundler to specify the Gem versions does work though, so you might need to create a Gemfile and specify Psych in there if you're not already using it.

A: Search and replace was actually not too bad:
# Convert Hash/Array subclasses into plain hashes/arrays for YAML dump.
# Assumptions:
#   Hash keys will be simple objects - don't need to clear them
#   No custom objects containing Hash/Array subclass instances
def deep_clear_subclasses(obj, dedup = {})
  case obj
  when Hash
    return dedup[obj] if dedup.has_key? obj
    dedup[obj] = copy = {}
    obj.each {|k,v| copy[k] = deep_clear_subclasses(v, dedup)}
    copy
  when Array
    return dedup[obj] if dedup.has_key? obj
    obj.inject(dedup[obj] = []) {|a,v| a << deep_clear_subclasses(v,dedup)}
  else
    obj # not going to operate on other kinds of objects
  end
end