text:
Q: Three questions in order to create a TCP server - socket, Linux with C I'm going to write a TCP server (Socket - Linux - C). I have three questions:
1) For know if the network (or connectivity) is down, have I use the option SO_KEEPALIVE?
For instance:
int optval = 1;
socklen_t optlen = sizeof(optval);

if (setsockopt(file_descriptor,SOL_SOCKET,SO_KEEPALIVE,&optval,optlen)<0) {
Close(file_descriptor);
Print_error("setsockopt() failed");

2) I want that my server contacts other server. How my server know if the remote server shutdown?
3) I want write an concurrent server and so I use fork() in order to create child:
3.1) I have to handle concurrent access to shared variables even if they are only for read     purpose?
3.2) I won't have zombie in my process list...Can this code be right?
void sigchld_h (int signum);

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

void sigchld_h (int signum){
    pid_t pid;
    int status;
    while ( (pid = waitpid(-1,&status,WNOHANG)) > 0)
        printf("(%s) INFO - child %d terminated with exit status %d", nome_programma, pid, status);
}

Thank you very much for the consulting.

A:
For know if the network (or connectivity) is down, have I use the option SO_KEEPALIVE?

You can do that. Alternatively, you may implement your own "heartbeat" mechanism on top of TCP/IP.

I want that my server contacts other server. How my server know if the remote server shutdown?

A server cannot connect to another server. The one who connects is a client. The one who accepts is a server. At any rate, you have to use a heartbeat mechanism and handle errors to determine when server goes down (unexpectedly).

I want write an concurrent server and so I use fork() in order to create child

This is the worst idea ever in nearly every case. The best way to do this is to use asynchronous I/O with considerably low number of threads.

I have to handle concurrent access to shared variables even if they are only for read purpose?

If you use fork(), each process receives its own copy of memory, which includes variables, so no synchronization is necessary. In case of threads, you do not need to lock when accessing read-only memory.

I won't have zombie in my process list...Can this code be right?

No, you are not allowed to call printf() from a signal handler. Only async/reentrance safe functions are permitted.

A: *

*SO_KEEPALIVE helps you determine that given TCP connection is dead, meaning the other side had no activity for given time (usually 2 hours). It also helps maintain idle TCP connections through intermediate routers that might just time out connection state due to inactivity. See, for example, here for lengthier explanation.
Much more useful and convenient way of knowing state of your connected peer is building periodic heartbeat exchange into your application-level protocol.

*In this case your server acts as a client. Connect to the remote end and exchange data.  You will know the other side is down if you a) cannot connect, or b) receive zero bytes (graceful closing of the socket by the peer), or c) get an error from send(2) saying the pipe is broken. Again, remote server crash is the trickiest to detect. SO_KEEPALIVE would eventually tell you there's a problem, but application heartbeats will tell you much sooner.

*fork(2) is the heaviest of the concurrency tools available on modern Unix. Designs based on child process per client connection (and even thread per connection) quickly lead to resource problems, and are generally slow. Explore thread pools and non-blocking sockets along with polling mechanisms like select(2), poll(2), and epoll(7).


text:
Q: wpf custom control get/set not firing I'm learning WPF and, coming from Flex and AS, it seems overly complicated at times. Opinions aside, my problem is the following.
I've created a custom control, ToolBarButton which is basically an image button that is destined to be included in a custom toolbar. I've added some properties to this control and I'd like to be able to set them from the XAML. Though the property appears in AutoCompletion on the XAML side, the Set method is never fired and the property stays null. So here's the ToolBarButton Code Behind :
    public static readonly DependencyProperty ImgSrcProperty = DependencyProperty.RegisterAttached("ImgSource", typeof(string), typeof(ToolBarButton));

    public static readonly DependencyProperty OnClickProperty = DependencyProperty.Register("OnClick", typeof(RoutedEventHandler), typeof(ToolBarButton));

    public ToolBarButton(RoutedEventHandler OnClick, string imgSrc, Map map = null, string ConfigFile = null) :
        base(ConfigFile, map)
    {
        if (OnClick != null) SetValue(OnClickProperty, OnClick);

        if (imgSrc != null) SetValue(ImgSrcProperty, imgSrc);

        this.AddChild(CreateButton());

        InitializeComponent();
    }

    public ToolBarButton() : this(null, null) { }

    private Button CreateButton()
    {
        BitmapImage icon = new BitmapImage();
        icon.BeginInit();
        icon.UriSource = new Uri(ImgSource, UriKind.Relative);
        icon.EndInit();

        Image img = new Image();
        img.Stretch = Stretch.Fill;
        img.Source = icon;

        Button BtnToAdd = new Button();
        BtnToAdd.Width = 35;
        BtnToAdd.Height = 35;
        BtnToAdd.Content = img;
        BtnToAdd.Background = new ImageBrush(icon);

        BtnToAdd.Click += OnClick;

        return BtnToAdd;
    }

    public string ImgSource
    {
        get { return (string)GetValue(ImgSrcProperty); }
        set { SetValue(ImgSrcProperty, value); }
    }

    public RoutedEventHandler OnClick
    {
        get { return (RoutedEventHandler)GetValue(OnClickProperty); }
        set { SetValue(OnClickProperty, value); }
    }

You'll notice two constructors, one to create the control at runtime, the other to create it from XAML.
And here's the XAML code that uses the custom control but doesn't fire the set method :
<BaseControls:ToolBar
         x:Class="Basic_Mapping.Widgets.NavigationToolBar"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:BaseControls="clr-namespace:Basic_Mapping.Base_Controls"
         mc:Ignorable="d" >

<BaseControls:ToolBarButton Width="35" Height="35" ImgSource="Assets/i_zoomin.png"  ConfigFileName="ZoomIn.xml" />

Any help would be appreciated!
Ggilmann
EDIT :
Here's the Base Class used for the ToolBarButton, it also has the same problem with it's properties.
public partial class ConfigurableUserControl : UserControl
{
    private XmlDocument configXML;

    public static readonly DependencyProperty XmlProperty = DependencyProperty.Register("ConfigFileName", typeof(string), typeof(ConfigurableUserControl));

    public static readonly DependencyProperty MapProperty = DependencyProperty.Register("Map", typeof(Map), typeof(ConfigurableUserControl));

    public ConfigurableUserControl(string configFile, Map map)
    {
        if (configFile != null) SetValue(XmlProperty, configFile);

        if (map != null) SetValue(MapProperty, map);

        string file = (string)GetValue(XmlProperty);

        if (file != null)
        {
            configXML = new XmlDocument();

            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\Config\\" + configFile);

            if (File.Exists(path)) configXML.Load(path);
        }
    }

    public ConfigurableUserControl() : this(null, null) { }

    public string ConfigFileName
    {
        //get { return (string)GetValue(XmlProperty); }
        set { SetValue(XmlProperty, value); }
    }

    public Map Map
    {
        get { return (Map)GetValue(MapProperty); }
        set { SetValue(MapProperty, value); }
    }

    public XmlDocument ConfigXML
    {
        get { return configXML; }
    }
}

A: Try putting InitializeComponent(); at the beginning of the constructor as opposed to at the end where it currently is.

A: My guess is that this problem, and your problems with the base class, are due to the fact that you're not implementing INotifyPropertyChanged and making the appropriate calls.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Subscribe to redis channel (pubsub) using lettuce reactive commands I am using the io.lettuce.core library and I am having trouble subscribing to a channel using the RedisPubSubReactiveCommands interface.
I have a StatefulRedisPubSubConnection and an active redis cluster which I am attempting to subscribe to.
connection.sync().subscribe("channel") works fine, as does connection.async().subscribe("channel"). However, when I use the reactive 'hot observable' interface provided by lettuce like so:
connection.reactive().subscribe(channels).subscribe();
connection.reactive().observeChannels().doOnNext(this::notifyObservers).subscribe();

It will not register as a subscription action on redis. I feel like I'm following the example given in the lettuce documentation closely.
I'm programming for an interface that accepts a hot Flux Observable and I'm getting close to wrapping the sync or async connection interfaces with my own reactive wrapper and throwing them in the pipe. What am I doing wrong here?

A: In case anyone else runs into this same problem, it turns out I was passing in a Set<String> Object into a function that accepts a varargs Object... and didn't realize it was treating the entire collection as a single element instead of parsing it as a varargs array.
I'll leave this up for others to learn from my dumb mistake.


text:
Q: c++ OpenGL Multithreading with buffer resource I have an OpenGL program that needs to periodically update the textures. But at the same time I want the program to be responsive (specifically, to continue running the draw/display code) while it's updating these textures.
But this seems impossible: If I make thread1 do the draw/display code and thread2 to the texture moving, then they will conflict under the resource GL_ARRAY_BUFFER_ARB because thread2 has to keep that resource to move some textures over to a vbo. And I need GL_ARRAY_BUFFER_ARB to do the draw/display code for thread1 because that uses different vbo's.
For example this code
glBindBufferARB(GL_ARRAY_BUFFER_ARB, tVboId);
    glBufferDataARB(GL_ARRAY_BUFFER_ARB, numVertices*2*sizeof(GLfloat), texCoords, GL_DYNAMIC_DRAW_ARB);
    glBindBufferARB(GL_ARRAY_BUFFER_ARB,0);

will move some textures over but it will take a while. During that time the display code is supposed to run many times but it will instead crash, because GL_ARRAY_BUFFER_ARB is in use.
I thought I could do something like GL_ARRAY_BUFFER_ARB2 but there is no such thing, I think.

A: Use PBOs they allow you to do asynchronous transfers, read more here.

A: This should help: http://hacksoflife.blogspot.com/2008/02/creating-opengl-objects-in-second.html


text:
Q: Nested foreach loops java for (Comment mc : relevant) {
    for (GitItem gi : tree) {
      bb.buildBody(gi.getHash(), mc.getBody());
      MutableComment mutable = commentManager.getMutableComment(mc.getId());
      mutable.setBody(bb.sb.toString());
      commentManager.update(mutable, true);
    }
}

So I've made this nested foreach loop with the hopes that I'll add the 1st item from tree(which is a TreeSet of GitItems) to the first comment from relevant (which is a List of Comments whose size is equal to the size of tree) and so on (In this example I have 2 comments and 2 items). But what it does right now is, that it adds only the 2nd item from tree to each of the two comments. What am I doing wrong?

A: Your inner loop iterates always over all the items in tree, so the body is set to the last tree item for all comments. If I understood you right, what you want is stepping the iterators in sync (in pseudocode, since I don't know what your relevant and tree etc are:
Iterator<Comment> commentIter = relevant.iterator();
Iterator<GitItem> itemIter = tree.iterator();
while (commentIter.hasNext() && itemIter.hasNext()) {
    Comment mc = commentIter.next();
    GitItem gi = itemIter.next();

    bb.buildBody(gi.getHash(), mc.getBody());
    MutableComment mutable = commentManager.getMutableComment(mc.getId());
    mutable.setBody(bb.sb.toString());
    commentManager.update(mutable, true);
}


text:
Q: Generating uniform random numbers with antithetic sampling From a uniform random number(RN) U1~U(0,1), I can generate a total of two RNs using antithetic reasoning, i.e. (U1,1-U1).
I go further and generate 2 more random like this:
If U1<0.5, Then (U1,1-U1,0.5-U1,0.5+U1).
If U1>0.5, Then (U1,1-U1,U1-0.5,1.5-U1).
What are the finer implication of this?


text:
Q: Reading Excel fails using for loops multithreading I would like to loop through the columns and rows of an excel spreadsheet and put the values into a list. The spreadsheet is 70 columns and 850+ rows. No matter what I try it fails to loop through a 2nd time. It actually jumps out of the sub routine all together. Weirdly it doesn't error out, which makes it really hard. The spreadsheet cells can contain anything from formulas to static text, numbers, etc. I'm not sure if that matters or helps. I am so frazzled at this point that I hope I make sense. I can post more info if you need it. Any ideas?
Ps. My code has commented lines of failed attempts. I hope that helps show what I've tried.
Private Sub GetSpreadsheetList(ByVal HeaderRowIndex As Integer)
    g_SpreadsheetList = New List(Of ListOfValuePair)
    Try
        Dim XlSh As Excel.Worksheet = Xlbook.ActiveSheet
        'Dim LastRowIndex As Long = XlSh.Range("A4000").End(Excel.XlDirection.xlUp).Row + 1
        'Dim LastColIndex As Long = XlSh.Range(ToolBox.RemoveCharAndSpaces("AAA" & Str(HeaderRowIndex), True)).End(Excel.XlDirection.xlToLeft).Column + 1
        Dim LastRowIndex As Long = XlSh.UsedRange.Rows.Count
        Dim LastColIndex As Long = XlSh.UsedRange.Columns.Count
        Dim Cntr As Integer = 1

        For ColIndex As Integer = 1 To LastColIndex
            Dim NewFNO As New ListOfValuePair
            For RowIndex As Integer = HeaderRowIndex To LastRowIndex ' - HeaderRowIndex

                If RowIndex = HeaderRowIndex Then
                    Dim XlRange As Excel.Range = CType(XlSh.Cells(RowIndex, ColIndex), Excel.Range)
                    'Dim CellVal As String = RemoveCharAndSpaces(CType(XlRange.Text, String))

                    'Dim CellVal As String = "Tito's"

                    'NewFNO.Key = CellVal
                    NewFNO.Key = XlRange.Text.ToString

                ElseIf RowIndex > HeaderRowIndex Then
                    'Dim XlRange As Excel.Range = CType(XlSh.Cells(RowIndex, ColIndex), Excel.Range)
                    'Dim XlObj As Object = XlSh.Cells(RowIndex, ColIndex)
                    'Dim CellVal As String = CType(XlRange.Text, String)

                    'Dim CellVal As String = "String Taco"
                    'Try : CellVal = RemoveCharAndSpaces(CType(XlRange.Text, String))
                    'Catch ex As Exception : CellVal = "ERROR VAL" : End Try
                    'MessageBox.Show(CellVal & vbNewLine & "Column: " & ColIndex & " | Row: " & RowIndex)

                    'NewFNO.ListOfValues.Add(CellVal)
                    NewFNO.ListOfValues.Add(XlSh.Cells(RowIndex, ColIndex).Value2)

                Else
                    MessageBox.Show("Faillure!!!")
                End If
            Next
            g_SpreadsheetList.Add(NewFNO)
        Next
        Stop
    Catch ex As Exception
        MessageBox.Show("Modules | Column_Compare_Family_Table | GetSpreadsheetList" & vbNewLine & "Problems getting spreadsheet cell values.", "Error!")
    End Try
End Sub

**Edit
This program has many threads, and many global variables. The memory being used during debugging shows 102(MB). That seems like a lot so I copy and pasted this code into a different solution. It worked like it should. Could memory be an issue here?
**Edit 2
Since the code worked in a different solution, I tried running the original solution again but without initiating a new thread. It worked! So I don't think the code or excel. I think it has something to do with the thread.

A: Assuming you are using VSTO, you can do: Xlbook.ActiveSheet.UsedRange.Value which will return a 2D array of the values within range.
Not only this is fast, but also you then do not need to worry about Excel any more: work on your 2D array.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.range.value?view=excel-pia
If you do not specify RangeValueDataType then

If the specified Range object is empty, returns the value Empty (use the IsEmpty function to test for this case). If the Range object contains more than one cell, returns an array of values (use the IsArray function to test for this case)


text:
Q: Could not GET 'https://giphy.bintray.com/giphy-sdk/dev/dworks/libs/volleyplus/maven-metadata.xml'. Received status code 502 from server: Bad Gateway I am getting this error when I am trying to build the app,

I have tried Disable Gradle 'offline mode' and sync project and it didn't work.


text: Q: Определить состоит ли строка из набора других строк Есть длинная строка без пробелов (текст) и несколько строк короче (допустимые слова). Нужно по длинной строке и набору допустимых слов определить, можно ли разбить текст на отдельные слова из набора. Сначала сделал так: отсортировал допустимые слова по длине и начал убирать из исходной строки все вхождения. Потом следующую и тд. Но нет. Не работает. В какую сторону еще подумать?


text:
Q: How to get access to the firebase Authentication part In my app I've 2 login methods(google&facebook) and all the users appear in the Authentication part inside my firebase project, and I haven't list/collection of my users in my database.
I want to display in my app list of users with some personal data.
My question is how do i get access to the users from the Authentication part(to get all the users for example)?
Is it good approach that the users appear only in the Authentication and not inside my database?

A: You can't list user accounts with the Firebase Authentication client SDK.  You can only do that with the Firebase Admin SDK on a backend you control.
If you think it's OK for your users to be able to know all other users, then you should store that information in your database to make it queryable directly from the client, or create some sort of API endpoint where you can invoke the Admin SDK from your app.


text:
Q: How can I fix "sqlite3 has text relocations" warning in android? I required to have sqlite3 in my Nexus 5, so I installed SQLite Installer for root from the market, I looked like it did not work, so I decided to do it manually, I pasted the sqlite3 file in system/xbin and gave permissions, It works fine, however, I always get this error:
Warning: linker: sqlite3 has text relocations. This is wasting memory and is a security risk. Please fix.

I'd like to fix it, but there's no information on the web about it,could you help me out please? thank you!

A: This would appear to be a result of two ndk-gcc bugs mentioned at
 https://code.google.com/p/android/issues/detail?id=23203
and stated there to have been fixed as of ndk-r8c.
It would appear that the check for libraries with the issue has been added only recently.


text:
Q: Bootstrap tagsinput not working I just came across Bootstrap tagsinput and I am trying it out, but I cant seem to get it working.
I added the following at the top of my layout :
<link rel="stylesheet" href="~/Scripts/bootstrap_tagsinput/bootstrap-tagsinput.css">

And I added the following at the bottom of my layout :
<script src="~/Scripts/bootstrap_tagsinput/bootstrap-tagsinput.js"></script>

Then in my partial page I added the following :
<input type="text" value="" data-role="tagsinput" id="tags" class="form-control">

Below is an image of what is happening, instead of the tags showing:

To my understanding, this should work. What am I missing ?

A: I think that because it's a partial view and it appears after the library is loaded, it doesn't get applied.
I had exactly the same problem. My Index page had all the libraries included but the partial view never used them.
I had to add this to the partial view Razor to force it to apply after load.
<script>
    $(function () {
        $('input[data-role=tagsinput]').tagsinput();
    }
    );
</script>

A: Add this links in your page
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

DEMO
Bootstrap - tagsinput , Github - Reference

A: did you initialized your input like
$('input').tagsinput({
  typeaheadjs: {
    name: 'citynames',
    displayKey: 'name',
    valueKey: 'name',
    source: citynames.ttAdapter()
  }
});


text:
Q: Change mouse cursor when dragging a floating QDockWidget Is it possible to use a different mouse cursor when dragging a floating QDockWidget? Neither QWidget::setCursor nor QApplication::setOverrideCursor have any effect.

A: A floating QDockWidget is a window, so you need to ask the OS to change the cursor when it's on the non-client area.
A little buggy example for windows:
#define WINVER 0x0500
#include <windows.h>
#include <windowsx.h>
#include <winuser.h>
bool DockWidget::winEvent(MSG * message, long * result)
{
    switch(message->message)
    {
        case WM_NCMOUSEMOVE:
            if(message->wParam == HTCAPTION)
            {
                qDebug() << "WM_NCMOUSEMOVE";
                if(!cursorHasBeenChanged && !cursorHasBeenClosed)
                {
                    cursorHasBeenChanged = true;
                    QApplication::setOverrideCursor(Qt::OpenHandCursor);
                }
            }
            else
                if(cursorHasBeenChanged)
                {
                    cursorHasBeenChanged = false;
                    QApplication::restoreOverrideCursor();
                }
            break;
        case WM_NCMOUSELEAVE:
            qDebug() << "WM_NCMOUSELEAVE";
            if(cursorHasBeenChanged && !cursorHasBeenClosed)
            {
                cursorHasBeenChanged = false;
                QApplication::restoreOverrideCursor();
            }
            break;
        case WM_NCLBUTTONDOWN:
            if(message->wParam == HTCAPTION)
            {
                qDebug() << "WM_NCLBUTTONDOWN";
                cursorHasBeenClosed = true;
                QApplication::setOverrideCursor(Qt::ClosedHandCursor);
            }
            break;
        case WM_NCLBUTTONUP:
            qDebug() << "WM_NCLBUTTONUP";
            if(cursorHasBeenClosed)
            {
                cursorHasBeenClosed = false;
                QApplication::restoreOverrideCursor();
            }
            break;
        default:
            ;
    }

    return QDockWidget::winEvent(message, result);
}

I think the code is self-explanatory, byut don't hesitate to ask if there something you don't understand.
The buggy part, is that I never receive WM_NCLBUTTONUP messages and I don't know why (I get WM_NCMOUSEMOVE instead) neither WM_NCMOUSEHOVER (which is the "enter event" for non-client area).


text:
Q: How does Nuget track package versions when building in VS2010? I've noticed for a few times now that Nuget pack will reset the package version, effectively starting from scratch and giving the package a lower version than the previous one.
I am using the asterisk * feature in VS2010 and AssemblyInfo.cs to generate versions:
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.*")]
//[assembly: AssemblyFileVersion("1.0.*")]

Now, I might have a build numbered 1.0.0.32334, then suddenly and randomly the build will become for instance 1.0.0.16272 and the same happens to the package that builds from it.
This happens completely at random (haven't figured it out yet when exactly or under what condition) but it's pretty annoying because it kills the update mechanisms for Nuget - because it finds no new versions.
Has anyone else spotted this?

A: Short answer: Nuget just uses the assembly version by default, but you can override in the nuspec or on the command line..
According to MSDN the format of version numbers is this:

major.minor.build.revision

And auto-incremented build numbers behave like this:

The default build number increments daily. The default revision number is random.

When you use auto build numbering you should allow VS to auto increment the both the build and revision numbers, like the commented out example shows.  Although the documentation claims randomness for revision number, in my observation it is not random.  In fact, it seems to increase throughout the day and is likely to reset the next day.  However, I wouldn't bank on that since it's likely an implemenation detail that could change.
By not letting VS choose the build number, you are essentially reducing it to a random number, so its not suprising that sometimes the revison number is less than the the previous revision number.  Unless overriden in the nuspec or from the command line, NuGet just takes the assembly version and uses the same version for the package.  So your root cause is likely the way you are choosing assembly version numbers.
If you can, just change your versioning scheme to this:
[assembly: AssemblyVersion("1.0.*")]

But if that is not acceptable, then you will have to maintain version numbers in the Nuspec or provide them on the command line when calling Nuget pack.


text:
Q: On increasing the penalty term in convex optimization with regularization Given the two strictly convex (unique solution) optimization problems as:
$$Problem\:1:\min_{X} f(X)+\|X\|_{F}^2 \hspace{2cm}Problem \:2:\min_{X}f(X)+n\|X\|_2^2$$
where $X\in\mathbf{S}_{++}^{n}$ (being positive definite), $f(X)$ is strictly convex, $\|\cdot\|_{F}$ is the frobenius norm, and $\|\cdot\|_2$ is the spectral norm. Let $X_1$ and $X_2$ denote the solutions to problem 1 and 2, respectively.
Question: Prove that $f(X_1)\leq f(X_2)$ (or please provide a counterexample if you believe that this does not always hold). I highly appreciate any help or suggestions. Thanks.


text:
Q: Sequelize.define() is not a function? Trying to play around with Sequelize in a node.js webserver.
I have initialised the Sequelize connection pool in index.js like so
index.js
const config = require('./config/config');
const app = require('./config/express');
const Sequelize = require('sequelize');

const sequelize = new Sequelize(config.mysql.database, config.mysql.user, config.mysql.pass, {
  host: config.mysql.host,
  dialect: 'mysql',
  operatorsAliases: false,

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },
});

sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.'); // eslint-disable-line no-console
  })
  .catch((err) => {
    console.error('Unable to connect to the database:', err); // eslint-disable-line no-console
  });

module.exports = { app, sequelize };

user.js model
const sequelize = require('sequelize');
const DataTypes = require('mysql');
/**
 * User model
 */
const User = sequelize.define('user', {

  id: {
    type: DataTypes.INTEGER,
  },
  name: {
    type: DataTypes.STRING,
  },
  email: {
    type: DataTypes.STRING,
  },
  lastEmail: {
    type: DataTypes.TIME,
  }
});

When trying to start the server I get the following error

TypeError: sequelize.define is not a function ... user.js

I am guessing the sequelize object is not being made global, however I tested the connection before creating the model and it was fine.

A: In user.js you are trying to use an instance method .define() on something that is not an instance. In index.js you do create an instance by calling the constructor, but that is not available in user.js. The solution here really depends on what you are trying to accomplish and how you want to organize your code. Normally index.js is the entry point to your application, so it is a little unusual to be exporting app and sequelize from there, but if that is what you want to do, then in your user.js file you could require index.js, and use the sequelize instance that you defined there. In that case, your index.js would stay the same and User.js might just have a change in the first require:
const sequelize = require('index.js').sequelize;
const DataTypes = require('mysql');

/**
 * User model
 */
const User = sequelize.define('user', {

  id: {
    type: DataTypes.INTEGER,
  },
  name: {
    type: DataTypes.STRING,
  },
  email: {
    type: DataTypes.STRING,
  },
  lastEmail: {
    type: DataTypes.TIME,
  }
});

I'm not necessarily recommending this approach, because, again, it really depends on what you are trying to do (I think maybe you are leaving out some of your code?), but it does show one way to use the instantiated sequelize object from index.js in user.js

A: I was having the same problem..and It works for me..
module.exports = (DataTypes , sequelize) => {
const User = sequelize.define('user', {
  id: {
    type: DataTypes.INTEGER,
  },
  name: {
    type: DataTypes.STRING,
  },
  email: {
    type: DataTypes.STRING,
  },
  lastEmail: {
    type: DataTypes.TIME,
  }
})
return User;
};


text:
Q: setframe in subclassed uibutton not adjusting frame I made a subclass of UIButton, and I want to set a "padding".  I want the button's frame to always be 15 pixels wider on each side, than the text.
In the drawRect method, I set the frame of the button to be 30 px wider than the text's width.  But when I try to do this the frame does not get adjusted at all.  Is this frame getting adjusted after I change the frame of my uibutton?  How can I adjust the frame to set a padding?
Here is my code:
- (void)drawRect:(CGRect)rect{
[self setBackgroundImage:[[UIImage imageNamed:@"submitBtn.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:0] forState:UIControlStateNormal];
[self setFrame:CGRectMake(rect.origin.x, rect.origin.y-90, self.titleLabel.frame.size.width + 30, self.frame.size.height)];
}

Thanks for the answers!!

A: You should override the setTitle:forState: method and adjust the frame there. You should also set the background image somewhere other than drawRect:. A good place would be the initXXX method.
The only thing you should do in drawRect: is actually render content for the view based on its current state. No state should be changed in drawRect:.


text:
Q: Office365 API: get current user email using oauth2 token? I'm working on authentication for Outlook (office365) users in our web app through ouath2. Mainly I was followed this example: https://dev.outlook.com/RestGettingStarted/Tutorial/python . I managed to get response with access_token in it; also article from the link above, states that response should contain token_id which in turn will contain encoded user email. In my case response with access token is something like this:
{
u'token_type': u'Bearer',
u'scope': u'https://outlook.office.com/mail.readwrite',
u'access_token': u'EwB4Aul3BAA...ZQE=',
u'expires_in': u'3600'
}

Apparently no token_id here. I've googled a bit for some Office365 API which will allow to fetch user info (and email) using access_token but no luck.
Any suggestions?

A: So, the answer is pretty simple: I forget to add openid to scopes before requesting access token.

A: I followed the PHP example at https://dev.outlook.com/RestGettingStarted/Tutorial/php
However, I was unable to get the email address of the signed in user, even with the openid scope.
After about 24 hours of searching and testing, I eventually found that I needed to add profile as a scope.  I only discovered this via the OAuth Sandbox https://oauthplay.azurewebsites.net/ by examining request headers.
Hopefully, this helps someone.
This really should be better documented.


text:
Q: Patterns for the x and y values for linear, natural log, exponential, and power I know that the pattern for linear function is +/+ for the x and y values respectively. Basically, when you add to the x value, you add to the y value assuming it is an increasing function.
I was wondering if someone could tell we what it is for natural log, exponential and power.
Thank you very much.

A: You are asking whether these functions are increasing. A linear function is not always increasing though. The natural log $\ln(x)$ and the exponential function $e^x$ are strictly increasing, but the function $x^2$ is not: it is decreasing on the negative axis, and increasing on the positive axis.
However, as @Eric-Towers mentioned, it is not as straight forward as you might initially think.


text:
Q: hiding a previous input button I have php code which executes a loop, inside which it generates the following:
echo "<input type=\"button\" event='$eventID' id=\"sendsomeone\" value=\"Send a family member\"/>";
echo "";

Later, I have javascript which follows:
$('input:button').click(function() {
   $(this).next("span").append('You clicked this button!');
}

This code works fine.  But I want it to also hide the button (but not all the buttons on the page)
I've tried fooling with code like
$(this).parent("input").hide();

and $(this).prev("input").hide();
But I can't puzzle out how to make it work.

A: It looks like you're already in the buttons selector by using $('input:button'), so have you tried doing this?
$(this).hide();

A: You might also want to look at toggle which is helpful as it swill hide it if it's visible, and show it if it's not:
$(this).toggle();


text:
Q: Magento 2 - editing module structure and functions in Magento 1.x you could duplicate the extensions to app/design/frontend/themeName/default/template/or/layout and then modify it's layout or functionality via xml or phtml files.
How do we duplicate and edit certain modules now in M2? I have looked over the docs but couldn't find this info. For example i wish to edit phtml of module-catalog/view/frontend/templates/product/gallery.phtml correct way by having theme based module overwrite and now edit core modules within vendor/magento*/ folder.
Thanks for the help.

A: With version 2.0.0 release(not Github), You should do as below
Copy templates need to make override in:
vendor/magento/<module_name>/view/frontend/templates
Location contain templates using to override:
app/design/frontend/<Vendor_Theme>/<name_theme>/Magento_<module_name>/templates
Example
You want override a template in: vendor/magento/module-catalog/view/frontend/templates/product/list.phtml
You create a file have path as: app/design/frontend/<Vendor_Theme>/<name_theme>/Magento_Catalog/templates/product/list.phtml


text:
Q: WPF DataGrid: Reordering and Editing Rows with GongSolutions.WPF.DragDrop I'm using GongSolutions.WPF.DragDrop. What I want is to load a List into a DataGrid, be able to add rows, delete rows, edit rows, and drag drop reorder rows. Then read every item from the list in the new order back into a database.
When I give an item source to a DataGrid, I can't drag drop reorder the rows.
If I add the items through DataGrid.Items.Add to the DataGrid, I can't edit the rows.
Source Code;
MainWindow.xaml
<Window
    x:Class="WPFDragDropControls.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:dd="urn:gong-wpf-dragdrop"
    xmlns:local="clr-namespace:WPFDragDropControls"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="MainWindow"
    Width="800"
    Height="450"
    Loaded="Window_Loaded"
    mc:Ignorable="d">
    <Grid>
        <DataGrid
            Name="DataGrid_DD_Test"
            dd:DragDrop.IsDragSource="True"
            dd:DragDrop.IsDropTarget="True"
            AutoGenerateColumns="False"
            CanUserAddRows="True"
            CanUserDeleteRows="True">
            <DataGrid.Columns>
                <DataGridTextColumn
                    Binding="{Binding ColumnName}"
                    Header="ColumnName"
                    IsReadOnly="False" />
                <DataGridTextColumn
                    Binding="{Binding SystemName}"
                    Header="SystemName"
                    IsReadOnly="False" />
                <DataGridTextColumn
                    Width="*"
                    Binding="{Binding Format}"
                    Header="Format"
                    IsReadOnly="False" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

MainWindow.xaml.cs
using System.Collections.Generic;
using System.Windows;

namespace WPFDragDropControls{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            List<TestItems> TestCollection = new();

            TestCollection.Add(new TestItems() { ColumnName = "EmployerSig", SystemName = "Form9061_1a", Format = "trim[32]" });
            TestCollection.Add(new TestItems() { ColumnName = "StartDate", SystemName = "Form9061_6a", Format = "dt:yyyyMMdd" });
            TestCollection.Add(new TestItems() { ColumnName = "State", SystemName = "Form9061_4ga", Format = "trim[2]" });

            DataGrid_DD_Test.ItemsSource = TestCollection;

            //DataGrid_DD_Test.Items.Add(new TestItems() { ColumnName = "StartDate", SystemName = "Form9061_6a", Format = "dt:yyyyMMdd" });
            //DataGrid_DD_Test.Items.Add(new TestItems() { ColumnName = "State", SystemName = "Form9061_4ga", Format = "trim[2]" });
            //DataGrid_DD_Test.Items.Add(new TestItems() { ColumnName = "EmployerSig", SystemName = "Form9061_1a", Format = "trim[32]" });
        }

        class TestItems
        {
            public string ColumnName { get; set; }
            public string SystemName { get; set; }
            public string Format { get; set; }
        }
    }
}

How can I have my cake and eat it too?


text:
Q: Generate Date Ranges in MYSQL and UNION I'm trying to generate a report base on pre defined dates(cutoff dates). I have two tables, the in and out and overtime table.
IN and OUT table

Overtime Table

Expected Result

Using UNION, it doubles the dates, but that can be solve supposedly by group by, but group seems not to work in UNION.
And the tricky part is to show the BLANK 6-Jan and 5-Jan. I need to show this coz its a timesheet report.
Any help or clue will be greatly appreciated
CODE:
SELECT emp_id,in,out,null
FROM normal
WHERE date >= '1-Jan'
  AND date <= '10-Jan'
  AND emp_id = '10001'
UNION
SELECT emp_id,null,null,minutes
FROM overtime
WHERE date >= '1-Jan'
  AND date <= '10-Jan'
  AND emp_id = '10001'

A: Something like this should do what you want(if i weel understood the question) :
SELECT n.date, n.emp_id, n.in, n.out, o.minutes
FROM normal n
JOIN overtime o USING(emp_id)
WHERE n.date BETWEEN '2012-01-01' AND '2012-01-10'

Keep in mind that if you want to show even the dates with no matches, you have to create a table with the list of this dates :
dates
+------------+
| timestamp  |
|------------+
| 2012-01-01 |
| 2012-01-02 |
| ....       |

Then you can change the query in this way to get the result set you want :
SELECT d.timestamp AS date, b.emp_id, b.in, b.out, b.minutes
FROM dates d
LEFT JOIN
(SELECT n.date AS timestamp, n.emp_id AS emp_id, n.in AS in, n.out AS out, o.minutes AS minutes
 FROM normal n
 JOIN overtime o USING(emp_id)
 ) b
 USING(timestamp)
 WHERE d.timestamp BETWEEN '2012-01-01' AND '2012-01-10'

If you want to avoid the dates table you can try with this more complex query, should give you the same result, without the needs of a third table that store the range of dates :
SELECT d.timestamp AS date, b.emp_id, b.in, b.out, b.minutes
FROM (
SELECT '2012-01-01' + INTERVAL a + b DAY AS timestamp
FROM
(SELECT 0 a UNION SELECT 1 a UNION SELECT 2 UNION SELECT 3
UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7
UNION SELECT 8 UNION SELECT 9 ) d,
(SELECT 0 b UNION SELECT 10 UNION SELECT 20
UNION SELECT 30 UNION SELECT 40) m
WHERE '2012-01-01' + INTERVAL a + b DAY  <  '2012-01-11'
ORDER BY a + b
) d
LEFT JOIN
(SELECT n.date AS timestamp, n.emp_id AS emp_id, n.in AS in, n.out AS out, o.minutes AS minutes
 FROM normal n
 JOIN overtime o USING(emp_id)
 ) b
 USING(timestamp)


text:
Q: How do I track down where event listener is getting added? I have a fairly good sized javascript (with react/redux but no jquery) codebase for a webapp I'm building, and I've noticed that when I repeatedly open and close a certain panel within the UI, the number of listeners according to Chrome's performance timeline keeps increasing.
The graph looks like this:

I have allowed the chrome's performance monitor run for a good minute or two with the page sitting idle (just after opening/closing the panel a bunch), hoping that perhaps the listeners will get garbage collected, but they are not. I've switched to other tabs during this process, also hoping that the listeners will get garbage collected when the tab is backgrounded, but they unfortunately are not.
I therefore suspect that some listeners are getting registered that are never unregistered.
This leads me to two main questions:

*

*Does my hypothesis that listeners are getting added and never
unbound seems sensible, or is there more I could be doing to confirm
this suspicion?

*Assuming my suspicion is correct, how can I best go
about tracking down the code where the event listener(s) is/are
being added? I have already tried the following:

*

*Looked at the code that is responsible for opening the panel in question,  seeing where it adds any listeners, and commenting out those portions to see if there's any change in the performance graph. There is not a change.

*Overridden the addEventListener prototype like so:

var f = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(type, fn, capture) {
    this.f = f;
    this.f(type, fn, capture);
    console.trace("Added event listener on" + type);
}

Even after doing this, then commenting out all code portions that cause this console.trace to be executed (see #1) such that the console.trace is no longer printed upon open/close of the panel, I notice the same increase in listeners in the performance graph. Something else is causing the listeners to increase. I understand that there are other ways that listeners can be added, but it's not clear to me how to intercept all of those possibilities or cause them to be logged in Chrome's debugger in such a way that I can tell which code is responsible for adding them.
Edit:
 - At the suggestion of cowbert in the comments, I took a look at this page:
https://developers.google.com/web/tools/chrome-devtools/console/events
I then made the following function:
function printListenerCount() {
    var eles = document.getElementsByTagName("*");
    var numListeners = 0;
    for (idx in eles) { let listeners = getEventListeners(eles[idx]);
        for(eIdx in listeners)
        {
            numListeners += listeners[eIdx].length;
        }
        console.log("ele", eles[idx], "listeners", getEventListeners(eles[idx]));
    }
    console.log("numListeners", numListeners)
}

I execute this function after having opened/closed the panel a bunch of times, but unfortunately the "numListeners" figure doesn't change.
If the numListeners figure changed, I would be able to diff the results before/after having open/closed the panel to discover which element
has the extra event listener registered to it, but unfortunately numListeners does not change.
There is also a monitorEvents() API described on https://developers.google.com/web/tools/chrome-devtools/console/events, but the function
call requires that you specify a DOM element that you wish to monitor. In this situation, I'm not sure which DOM element has the extra
listeners, so I'm not sure how the monitorEvents() call will really help me. I could attach it to all DOM elements, similar to how I've
written the printListenerCount function above, but I presume I'd run into a similar problem that I ran into with printListenerCount() --
for whatever reason, it's not accounting for the listener(s) in question.
Other notes:
This is a somewhat complicated reactjs (preact, technically) based application. Like most reactjs based apps, components get mounted/unmounted (inserted into and removed from the DOM) on the fly. I'm finding that this makes tracking down "stray event handler registrations" like this a bit tricky. So what I'm really hoping for is some general debugging advice about how to track down "Stray event handlers" in large/complex projects such as this. As a C programmer, I would open gdb and set a breakpoint on everything that can possibly cause the "listeners" number in the performance graph to increase. I'm not sure if there's an analog of that in the javascript world, and even if it there, I'm just not sure how to do it. Any advice would be much appreciated!

A: Thanks for your comments, everyone. I ended up figuring this out.
From my OP:

*

*Does my hypothesis that listeners are getting added and never unbound seems sensible, or is there more I could be doing to confirm this suspicion?

It turns out that the answer to this question is: The hypothesis is not sensible. The listeners simply haven't had a chance to get garbage collected yet. It can take some more time than you might think.
Here's how I figured it out:
I failed to realize that while recording a performance timeline, it's possible to force a garbage collection by clicking on the trash can icon in the Performance tab (same tab used to start the timeline recording). By clicking this icon after repeated closings/openings of the UI panel, the extra listeners completely went away. The graph now looks like this, with the dips being moments where I clicked the trash icon:

Apparently, backgrounding the tab and waiting a couple of minutes like I mentioned in the OP is simply not enough time for garbage collection to occur on its own; It takes some more time than that.
I wasn't aware of the ability to manually collect garbage with the trash can icon when I wrote the OP... I strongly recommend using it before going on any wild goose chases hunting down what might at first look like a performance problem.


text:
Q: Jquery code not working in IE but working in all other browsers Does anyone see why this code wouldn't work in IE? Works in all other browsers.
jQuery(document).ready(function($) {
  $("#rss-east").rss("http://example.com/rss/waittime_east_rss.php",
  {
    ssl: true,
    entryTemplate:'{title}'
  }),
  $("#rss-west").rss("http://example.com/rss/waittime_west_rss.php",
  {
    ssl: true,
    entryTemplate:'{title}'
  })
})

A: Ended up being a conflict with another jquery library. Thanks everyone for the help and suggestions.


text:
Q: Unused argument in a nested ifelse statement I cannot figure out what is wrong with the following ifelse statement
ifelse(test = (size == "small"), yes = (config(toImageButtonOptions = list(format = "png", width = 601, height = 500)))
       , no = (ifelse(test = (size == "medium"), yes = (config(toImageButtonOptions = list(format = "png", width = 1241, height = 750))),
                no = (config(toImageButtonOptions = list(format = "png", width = 1698, height = 900))))))

Where size is an input to the function below.
I receive the following error
Error in ifelse(., test = (size == "small"), yes = (config(toImageButtonOptions = list(format = "png",  :
  unused argument (.)

The entire function
fPlotPricefloat <- function(mData, dDate, dY, dGroup, dtitle_name, dYLab ,dYmin, dYmax, dBreak, dateBreak, spreadin, size = c("small", "medium", "large")){

  #Define Names in legend
  dNames <- sort(unique(mData[,dGroup]))

  ## Define Date interval
  dateLab <- c("%h%Y")
  dateBreak <- dateBreak

  #Define plotb
  p <- ggplotly(ggplot(data=mData, mapping = aes(x=as.Date(mData[,dDate]), y=mData[,dY],
                                   color=mData[,dGroup],
                                   text = paste0("Tradedate:, ", as.Date(mData[,dDate]),"
",
                                                 paste0("Spread to ", spreadin, ": "), round(mData[,dY],2), "
",
                                                 "AssetID: ", mData[,dGroup]),
                                   group = 1)) +
    labs(x=NULL, y=dYLab, title = dtitle_name,
         caption = "Source: Jyske Bank") +
    geom_line(size=1) +
    geom_hline(yintercept = 0) +
    scale_colour_manual(name="",values=setNames(c(vRGB_Large[1:length(dNames)]),c(dNames[1:length(dNames)]))) +
    scale_x_date(date_breaks = dateBreak, date_labels = dateLab) +
    scale_y_continuous(breaks = seq(dYmin, dYmax, by = dBreak)) +
    theme_bw()+
    theme(plot.title=element_text(hjust=0,size=8,face="bold"),
          plot.caption = element_text(size=6, face = "italic"),
          axis.text.x = element_text(angle = 90,vjust = 0.01, hjust=1),legend.position = "bottom",
          legend.title = element_blank(),
          legend.text=element_text(size=6),
          legend.key.width = unit(0.5,"cm"),
          legend.key.height = unit(0.1,"cm"),
          panel.border = element_blank(),
          panel.grid.major.x = element_blank(),
          panel.grid.minor.x = element_blank(),
          axis.line.y = element_line(),
          axis.title.y = element_text(size = 7),
          axis.text = element_text(size = 8)), tooltip = "text") %>%
layout(legend = list(orientation = "h", x = 0.4, y = -0.2),
             annotations = list(x = 1, y = -0.3,
                                text = "Source: Jyske Bank",
                                showarrow = F,
                                xref = 'paper',
                                yref = 'paper',
                                xanchor = 'right',
                                yanchor = 'auto',
                                xshift = 0,
                                yshift = 0,
                                font = list(size = 10))) %>%
    ifelse(test = (size == "small"), yes = (config(toImageButtonOptions = list(format = "png", width = 601, height = 500)))
           , no = (ifelse(test = (size == "medium"), yes = (config(toImageButtonOptions = list(format = "png", width = 1241, height = 750))),
                    no = (config(toImageButtonOptions = list(format = "png", width = 1698, height = 900))))))

p}

The ifelse statement is used to configure the size of the downloaded image of ggplotly. The function is to be used in RShiny.


text:
Q: How to estimate the centroid of clustered sequences? I have run a sequence analaysis using the Optimal Matching algorithm. Afterwards, I have clustered the resulting distance matrice using the Ward algorithm and calculated silhouettes as measures of cluster quality and to identify representative sequences.
Now, I am curious whether it is possible to estimate the sequences of the cluster centroids which, to my knowledege, must not be an original data point. How can I estimate the sequence of a centroid?
To get an idea of the different steps of the analysis, consider this manual example[1]:
library(TraMineR)
library(WeightedCluster)
data(mvad)
mvad.alphabet <- c("employment", "FE", "HE", "joblessness", "school", "training")
mvad.labels <- c("Employment", "Further Education", "Higher Education", "Joblessness", "School", "Training")
mvad.scodes <- c("EM", "FE", "HE", "JL", "SC", "TR")

## Define sequence objects
mvad.seq <- seqdef(mvad[, 17:86], alphabet = mvad.alphabet, states = mvad.scodes, labels = mvad.labels, weights = mvad$weight, xtstep = 6)

## Computing OM dissimilarities
mvad.dist <- seqdist(mvad.seq, method="HAM", sm="CONSTANT")

## Clustering
wardCluster <- hclust(as.dist(mvad.dist), method = "ward", members = mvad$weight)
clust4 <- cutree(wardCluster, k = 4)

## Silhouettes
sil <- wcSilhouetteObs(mvad.dist, clust4, weights = mvad$weight, measure = "ASWw")

## Sequence index plots ordered by representativeness
seqIplot(mvad.seq, group = clust4, sortv = sil)

In this example, it would be for example interesting to see whether the sequence of third cluster's centroid differes from the most representative, original sequences in the cluster which are printed at the very top of the sequence index plot. In other cases, the centroid sequence may even have a more idealtype character which does not exist in the original dataset but reflects certain typical structures.
[1] See for the example Studer, Matthias (2013). WeightedCluster Library Manual: A practical guide to creating typologies of trajectories in the social sciences with R. LIVES Working Papers, 24.

A: The cluster centroid, i.e., the theoretical true center sequence which minimizes the sum of distances to all sequences in the cluster, is generally something virtual which would be defined as a mix of states at each position (similarly as the average between integer values can take non integer values).
TraMineR does not compute such virtual centers. However, it can compute the distance to the virtual center (for the used formula, see Studer, Ritschard, Gabadinho and Muller, 2011, Discrepancy analysis of state sequences, Sociological Methods and Research, Vol. 40(3), pp. 471-510).
The distance to the center is returned by the disscenter function. To get the distance to the center from the sequence with highest silhouette in each cluster, we first retrieve the indexes of those sequences.
## Looking for the index of the first sequence with max
## silhouette in each cluster
fclust <- factor(clust4)
levclust <- levels(factor(clust4))
imax.sil <- rep(NA,length(levclust))
for (i in 1:length(levclust)){
  max.sil <- max(sil[fclust==levclust[i]])
  imax.sil[i] <-
    which(sil == max.sil & fclust == levclust[i])[1]
}
## computing distance to center
d.to.ctr <- disscenter(mvad.dist, group=fclust,
           weights = mvad$weight)[imax.sil]
names(d.to.ctr) <- fclust[imax.sil]
d.to.ctr

Now, you may also consider comparing the sequence with maximum silhouette value to the medoid, i.e., the the sequence in the data with the smallest sum of distances to the other sequences in the cluster.
You get a plot of the medoid of each cluster with seqrplot
seqrplot(mvad.seq, group = fclust, dist.matrix = mvad.dist,
         criteria = "centrality", nrep=1)

Alternatively, you can retrieve the index number of the medoids, and then print or plot the medoids as follows
icenter <- disscenter(mvad.dist, group = clust4,
            medoids.index="first", weights = mvad$weight)
print(mvad.seq[icenter,], format="SPS")
seqiplot(mvad.seq[icenter,])

You could indeed also compute the distances to the medoids by setting for instance refseq = icenter[1] in seqdist, for the distance to the medoid of the first cluster.
Using the seqrep.grp function from TraMineRextras package, you get representativeness quality measures of the medoids (see Gabadinho, Ritschard, Studer, Muller, 2011, "Extracting and Rendering Representative Sequences", In Fred, A., Dietz, J.L.G., Liu, K. & Filipe, J. (eds) Knowledge Discovery, Knowledge Engineering and Knowledge Management. Series: Communications in Computer and Information Science (CCIS). Volume 128, pp. 94-106. Springer-Verlag)
library(TraMineRextras)
seqrep.grp(mvad.seq, group = fclust, mdis = mvad.dist,
           criteria = "centrality", nrep=1, ret = "both")

Hope this helps.


text:
Q: declare bind variables in script I have script that uses this variables
with
TIME_DATA  as ( select $$D:=:DA$$ td from dual),

GROUP_INFO as (select $$N:=:GR_ID$$ gr_id_number from dual),

and uses them like this
 A_PLUS_TEK as(select point_id, ml_id, ml_name, val a_plus_month, DA
from VALUE_DATA, TIME_DATA
where ml_id = 381 and DA = trunc(td, 'MM'))

I want to know how to initialize this variables, now when I run script I have this ouput:
Bind Variable "DA$$" is NOT DECLARED

EDIT: Usually users enter this values on website, I have access only to database, where I got script from reports table. Also I want to know how to initialize this variables from c#.
EIDT2: I took this for example (How do I use variables in Oracle SQL Developer?). It works.
variable v_count number;
variable v_emp_id number;
exec :v_emp_id := 1234;
exec select count(1) into :v_count from emp;
select *
  from emp
 where empno = :v_emp_id
exec print :v_count;

my code:
    declare
    variable DA$$ VARCHAR2(80);
    variable gr_id$$ number;
    begin
    exec :DA$$ := to_date('2011-09-13 09:00:00', 'YYYY-MM-DD HH24:MI:SS');
    exec :gr_id$$ := '1341';
BEGIN

and then with statement :
   WITH
    TIME_DATA  as ( select $$D:=:DA$$ td from dual),

    GROUP_INFO as (select $$N:=:GR_ID$$ gr_id_number from dual),

 ....
END;

But still have this
 Bind Variable "DA$$" is NOT DECLARED
anonymous block completed

This also change nothing
exec :DA$$ := '2011-09-13 09:00:00';
I think that DA$$ is date, because it used in trunc() DA = trunc(td, 'MM'))
When I select Run Statement(trl+Enter), Sql Developer offers to enter bind variables, but I don't know how to enter date.
EDIT3: Finally I do this without Declare, Begin, End and it works :
    variable DA$$ VARCHAR2(80);
    variable gr_id$$ number;
    exec :DA$$ := to_date('2011-09-13 09:00:00', 'YYYY-MM-DD HH24:MI:SS');
    exec  DBMS_OUTPUT.PUT_LINE(:DA$$);
    exec :gr_id$$ := '1341';
    with
    TIME_DATA  as ( select $$D:=DA$$; td from dual),
    GROUP_INFO as (select $$N:=:GR_ID$$ gr_id_number from dual),
...

A: From C# you can do this:
// using Oracle.DataAccess.Client
using(OracleCommand command = new OracleCommand(commandText, dbConnection))
{
    command.CommandType = CommandType.Text;
    command.Parameters.Add("DA$$", OracleDbType.Int32, valueDA, ParameterDirection.Input);
    command.Parameters.Add("GR_ID$$", OracleDbType.Int32, valueGR_ID, ParameterDirection.Input);
}

But review your comand text. Because you will probably face syntax errors due to "$$D:" and "$$N:"


text:
Q: Utilizar un and logico para la condicion de if con Strings Hola quería saber si hay alguna forma de poner en una condición esto:
if((vector[i]="hola") && (op == 1)){
...
}

Se que esta mal, solo quiero sabe si hay una forma de ponerlo. Me da este error
:The operator && is undefined for the argument type(s) String, boolean
Tampoco puedo cambiar && por and, tambien me sale error. Gracias de antemano.

A: introducir el código aquíFijate capas que te da el error porque tenes un solo = alado de vector[i]
if((vector[i] == "hola") && (op == 1)){
...
}

Quedaria algo asi...


text:
Q: Editing XML file with Data passed from AJAX - XML data is being deleted I am working on a project where I will read data from google maps API and convert it to XML for each object and then store that XML in an array slot (This will happen multiple times until all of the data is read) I will then make an Ajax POST request to a PHP file sending the array full of XML and a boolean (to let the server know which request it is). The PHP will then use SimpleXML to load, edit the XML with the data received, and then save it.
My problem is when I make the ajax request Firebug will recognize a POST request and it is sending all of the correct data. It throws a 302 (error?) saying Moved Temporarily Then a GET request happens (which I think is initated by the server) which outputs an error saying Undefined inded: ajax on the line where I ask if the boolean (which is called ajax) is true. And then when I check my XML file all data is deleted (the file still exists but there is no longer any XML in it) I am very confused as to how to troubleshoot this problem and I'm not really sure what to do. Here is some of my relevant code.
Thank you in advanced for any help that you can provide. Any assistance would be extremely helpful!
Also, please feel free to comment if you need me to clarify on anything.
javascript
function sendData(result)
{
    $.ajax(
    {
        type:'POST',
        url:'getXML.php',
        traditional: false,
        data:
        {
            //Result is an array full of XML
            'myXML': result,
            //The ajax boolean is for letting the PHP know that it is this request
            'ajax' : true
        },
        success: function(data)
        {
            $('#output').text(data);
        }
    })
}

PHP
<?php
    //Set error reporting
    ini_set('display_errors', 1);
    ini_set('log_errors', 1);
    ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
    error_reporting(E_ALL);

    //Checks if the get request is from the AJAX call
    if($_POST['ajax'])
    {
        //////////////////////////////Code for editing XML/////////////////////////////////////////
        //Checks to see if the xml file exists.
        if (file_exists('business.xml'))
        {
            //Loads the XML file
            $xml = simplexml_load_file('business.xml');
            $result = $_POST['myXML'];
            //Append XML to existing file using data loaded in from AJAX request
            appendXML($xml, $result);
        }
        else
        {
            //Loading XML has failed
            exit('Failed to open business.xml.');
        }
    }

    function appendXML($xml, $xmlResult)
    {
        foreach($xmlResult as $result)
        {
            //Creates new business node
            $business = $xml ->addChild('business');

            //Adds XML to business node (Please oh dear god let this work)
            $business ->addChild($result);

            file_put_contents("business.xml", $xml);
            header('Location: getXML.php');

        }
    }
?>

A: The issue you're having is with this line:
header('Location: getXML.php');

On the first run through of the page, things are working fine, and the appendXML codeblock is being called.  When that happens though, you're doing a header redirect to the same page (I'm not sure why).  When THIS happens, the page reloads, but in the new page non of the post data that you had set before is set.  As a result $_POST is empty and your if statement fails, further $_POST['myXML'] is also empty, which would blank out your XML.
If you need to do this reload of the page for some reason, consider creating a session and storing your values in a session variable.  You should also look at sanitizing the data you're passing in, as your current code has a vulnerability where someone can inject whatever information passed in from the browser into an XML file on your server.  This might not be a big deal but I'm always worried about letting someone write anything unescaped into a file on my system directly.  If nothing else someone could maliciously max out the space on your drive with this.


text:
Q: Missing Push Notification Entitlement Warning in email After uploading the App to AppStore, I am getting the following warning in an email, where as there are no Push Notifications in my App but there are some third party SDKs like Chartboost, Applovin, Revmob, Crashlytics etc. Has someone else also encountered this problem? If so, have you reached to some solution?

Dear developer,
We have discovered one or more issues with your recent delivery for "Jigsaw App". Your delivery was successful, but you may wish to
  correct the following issues in your next delivery:
Missing Push Notification Entitlement - Your app appears to include
  API used to register with the Apple Push Notification service, but the
  app signature's entitlements do not include the "aps-environment"
  entitlement. If your app uses the Apple Push Notification service,
  make sure your App ID is enabled for Push Notification in the
  Provisioning Portal, and resubmit after signing your app with a
  Distribution provisioning profile that includes the "aps-environment"
  entitlement. See "Provisioning and Development" in the Local and Push
  Notification Programming Guide for more information. If your app does
  not use the Apple Push Notification service, no action is required.
  You may remove the API from future submissions to stop this warning.
  If you use a third-party framework, you may need to contact the
  developer for information on removing the API.
After you've corrected the issues, you can use Xcode or Application
  Loader to upload a new binary to iTunes Connect.
Regards,
The App Store team

A: It means your provisioning profile does not support apns. create a provisioning profile with push notifications enabled and upload.

A: Check out for third party frameworks like

*

*airpush

*urbanship
etc...
These frameworks can register your app even though you don't register it in app delegate
Make sure push notification is disabled in these frameworks


text:
Q: dev server global cache (Python) I hope someone can clarify this for me:
Does the GAE dev server also cache the Python global scope like the production server does?
I'm under the impression that it does not.
I can't find anything about this in the docs.
Thanks
Quint

A: Yes, it does. But when you change code, the development server restarting and you have brand new namespace for your modules.
Python doesn't have "global scope" (like e.g. PHP has) between modules. It has namespaces. They are mostly modules namespaces (created when you do imports) and, as you know, GAE caching imports. This cache is alive while the instance is running. Instance in general is a python's process and python keep variables values in memory until there is at least one reference to them.
Since the development server simulates the production service, it works in the same way, but the difference is that devserver watches for changes you make to your files (and I notice not only files) and reloads them if needed. To guaranteed reset module import caching you also need to restart server like in production.


text:
Q: Too many IF statements Excel / VBA I have added some sample data in this file to explain my problem a bit better. I have blended out the columns which have no relevance to the formula: https://docs.google.com/spreadsheets/d/1_lq0mYPF2ICiFgehQz_YkOa28JUyamG4G8ObV957onY/edit?usp=sharing
My initial file has one row per contract. I want to end up with one row per customer ID. I need to only keep the most recent contract, so the contract with the end date closest to Now(). If one customer ID has two contracts ending at the same time, I would like to keep the row with the higher monthly invoice amount.
I have been doing this with IF statements but there must be a more efficient way. At the moment the highest number of contracts a customer has with 3, but this will increase in the coming months and my if statement method will no longer be viable.
Here is my current formula.
Range("P2").Select
    ActiveCell.FormulaR1C1 = _
        "=IF(OR(Status=""in renewing process"",Status=""first contract still running""),""Not Eligable"",IF(Count_of_ID=1,""keep"",IF(Count_of_ID=2,(IF(AND(RC[-15]=R[1]C[-15],MIN(RC[-1],R[1]C[-1])=RC[-1]),""keep"",""delete"")),IF(Count_of_ID=3,IF(AND(RC[-15]=R[1]C[-15],RC[-15]=R[2]C[-15],MIN(RC[-1],R[1]C[-1],R[2]C[-1])=RC[-1]),""keep"",""delete"")))))"

Range("P3").Select
    ActiveCell.FormulaR1C1 = _
        "=IF(OR(Status=""in renewing process"",Status=""first contract still running""),""Not Eligable"",IF(Count_of_ID=1,""keep"",IF(Count_of_ID=2,(IF(AND(RC[-15]=R[1]C[-15],MIN(RC[-15],R[1]C[-15])=RC[-15]),""keep"",IF(Count_of_ID=2,(IF(AND(RC[-15]=R[-1]C[-15],MIN(RC[-15],R[-1]C[-15])=RC[-15]),""keep"",""delete"")))),IF(Count_of_ID=3,IF(AND(RC[-15]=R[1]C[-15],RC[-15]=R[2]C[" & _
        "-15],MIN(RC[-15],R[1]C[-15],R[2]C[-15])=RC[-15]),""keep"",IF(Count_of_ID=3,IF(AND(RC[-15]=R[1]C[-15],RC[-15]=R[-1]C[-15],MIN(RC[-15],R[1]C[-15],R[-1]C[-15])=RC[-15]),""keep"",""delete""))))))))" & _
        ""

Range("P4").Select
    ActiveCell.FormulaR1C1 = _
        "=IF(OR(Status=""in renewing process"",Status=""first contract still running""),""Not Eligable"",IF(Count_of_ID=1,""keep"",(IF(AND(Count_of_ID=2,RC[-15]=R[1]C[-15],MIN(RC[-1],R[1]C[-1])=RC[-1]),""keep"",IF(AND(Count_of_ID=2,RC[-15]=R[-1]C[-15],MIN(RC[-1],R[-1]C[-1])=RC[-1]),""keep"",IF(AND(Count_of_ID=3,RC[-15]=R[1]C[-15],RC[-15]=R[2]C[-15],MIN(RC[-1],R[1]C[-1],R[2]C" & _
        "[-1])=RC[-1]),""keep"",IF(AND(Count_of_ID=3,RC[-15]=R[1]C[-15],RC[-15]=R[-1]C[-15],MIN(RC[-1],R[1]C[-1],R[-1]C[-1])=RC[-1]),""keep"",IF(AND(Count_of_ID=3,RC[-15]=R[-1]C[-15],RC[-15]=R[-2]C[-15],MIN(RC[-1],R[-1]C[-1],R[-2]C[-1])=RC[-1]),""keep"",""delete""))))))))" & _
        ""
    Range("P4").Select
    Selection.AutoFill Destination:=Range("P4:P" & Lastrow)

Any help much appreciated!

A: I would use Named Formulae. They are not widely used in Excel but very powerful. As an example I reduced
=IF(OR(Status=""in renewing process"",Status=""first contract still running"")

to a single word returning true or false using a named formula. I have used relative addressing, excel handles this for you. The attached image should give you all the information you need to use it. I clicked on B2 and built the formula as normal, tested it then copied it, right clicked >DefineName, gave it a name and pasted the formula into 'refers to'.
To use it then just add the Name into the cell and Excel handles all the relative addressing stuff.


text:
Q: Php decoding function in PHP This is a function that I use in my Jquery code.
function atou(str) {
        return decodeURIComponent(escape(window.atob(str)));
}

Can someone write here a similar PHP function with the same functionality?
Thanks

A: function atou($str) {
    return urldecode(urlencode(base64_decode($str)));
}


text:
Q: Is there a way to get the google chrome script debugger to break on exception? I'd like to automatically break when an exception occurs.

A: In newest Chrome it's possible.  I use 9.0.587.0 and in developer tools, scripts tab in left bottom corner is an icon that says click to pause on all exceptions.


text:
Q: Indefinite integral of rational polynomial function How do I integrate
$\int \frac {(x-3)}{(x^2-2x+4)^2} dx $
I know that I have to integrate via recursion. But doing so I get to a point where I have to find $\int \frac {x^2}{(x^2-2x+4)^2} dx $ which seems even harder than the first one.

A: Hint: Write $$\int\frac{2x-2}{2(x^2-2x+4)^2}-\frac{2}{(x^2-2x+4)^2}dx$$
then substitute $$u=x^2-2x+4$$,$$s=x-1,ds=dx$$ and then $$s=\sqrt{3}\tan(p),ds=\sqrt{3}\sec^2(p)dp$$

A: Observe that $$\dfrac{d\left(\dfrac{ax+b}{x^2-2x+4}\right)}{dx}=\dfrac{-ax^2-2bx+4a+2b}{(x^2-2x+4)^2}$$
Let $-ax^2-2bx+4a+2b=A(x^2-2x+4)+x-3$
Compare the coefficients of $x^2,x$ and the constants  to find $a,b,A$
$$\implies\dfrac{x-3}{(x^2-2x+4)^2}=\dfrac{d\left(\dfrac{ax+b}{x^2-2x+4}\right)}{dx}-\dfrac A{x^2-2x+4}$$
Integrate both sides wrt $x$


text:
Q: Rails override id on create controller with user specified id in forms in new.html.erb To change an id in rails
its like
Invoice.create(id: 25)
works
but in my new.html.erb, i have user specify an id (:invoiceid) and i want that id to be linked to that id.
so how do you do it?
Invocie.create(id: invoiceid) wont work.

A: Why do you even want to change primary id, please read these responses here
link1
link2, and still if you want to edit that then you will have to permit that field in strong params, like this
params.require(:my_model).permit(:id)


text:
Q: Deployed Loki grafana,but not be able to run on a public url I have deployed Loki grafana stack with persistent 5GB storage in a gcp cloud. Then i have create ingress, and point loadbalancer IP to subdomain. when I hit the url,it will automatic redirect to https. Note that i haven't apply ssl so it will give me an error "ERR_CONNECTION_CLOSED".I have also changed url in "grafana,ini". I have deployed using https://grafana.com/docs/loki/latest/installation/helm/ . If anyone have face this issue please guide me.
I am using GKE, and deploy helm using the tutorial after that i use the following ingress:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  labels:
    app.kubernetes.io/instance: loki
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: grafana
    app.kubernetes.io/version: 8.3.5
    helm.sh/chart: grafana-6.21.3
  name: ingress-loki
  namespace: loki
spec:
  rules:
  - host: loki.*****.com
    http:
      paths:
      - backend:
          service:
            name: loki-grafana
            port:
              number: 80
        path: /*
        pathType: ImplementationSpecific


text:
Q: Group data in intervals without 0 I have got following table:
+---------------------+--------+----------+
| MeasureInterval     | Car_id | Distance |
+---------------------+--------+----------+
| 2020-12-15 17:00:00 | 1      | 20       |
+---------------------+--------+----------+
| 2020-12-15 17:05:00 | 1      | 30       |
+---------------------+--------+----------+
| 2020-12-15 17:10:00 | 1      | 17       |
+---------------------+--------+----------+
| 2020-12-15 17:15:00 | 1      | 0        |
+---------------------+--------+----------+
| 2020-12-15 17:20:00 | 1      | 0        |
+---------------------+--------+----------+
| 2020-12-15 17:25:00 | 1      | 10       |
+---------------------+--------+----------+
| 2020-12-15 17:30:00 | 1      | 15       |
+---------------------+--------+----------+
| 2020-12-15 17:35:00 | 1      | 0        |
+---------------------+--------+----------+
| 2020-12-15 17:40:00 | 1      | 0        |
+---------------------+--------+----------+
| 2020-12-15 17:45:00 | 1      | 0        |
+---------------------+--------+----------+

I am trying to select the continous intervals where the car was moving (ignoring the intervals where Distance=0), so it this the results would be something like:
+---------------------+---------------------+--------+--------------+
|                     |                     |        |              |
| MeasureInterval_min | MeasureInterval_max | Car_id | Distance_sum |
+---------------------+---------------------+--------+--------------+
| 2020-12-15 17:00:00 | 2020-12-15 17:10:00 | 1      | 67           |
+---------------------+---------------------+--------+--------------+
| 2020-12-15 17:25:00 | 2020-12-15 17:30:00 | 1      | 25           |
+---------------------+---------------------+--------+--------------+

Any idea how to achieve this?

A: This is a gaps-and-island problem. Islands are adjacent records with non-zero distances.
Here is an approach that uses the difference between row numbers to identify the groups:
select
    min(measureinterval) as measureinterval_min,
    max(measureinterval) as measureinterval_max,
    car_id,
    sum(distance) as distance
from (
    select t.*,
        row_number() over(partition by carid order by measureinterval) rn1,
        row_number() over(partition by carid, (distance = 0) order by measureinterval) rn2
    from mytable t
) t
where distance > 0
group by car_id, rn1 - rn2


text:
Q: Check if a process is running as Administrator/Elevated from another application - Windows 10 Is there a way to check if an existing process is already running as Administrator/Elevated from a VB .Net WinForm application? I have a utility which connects to the Main application via API. This was all working fine on Windows 7 but on Windows 10, my utility was unable to connect to the main program via API. I tired lots of things but nothing worked. Finally I found that if I run the main program As Administrator, the my API utility worked/connected just like that. I reviewed the documentation for Process class (https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process?view=netframework-4.7.2) but can't find anything obvious to elevated execution property. Any advise or code snippet would be appreciated.
In Windows 10 Task Manager, you can see if the process is running as Elevated or Not. I just need something to capture this in the code.

A: After some testing around I found that after adding app.manifest file with below settings and adding a property IsElevated in the code, I could see if the exe is running as Elevated or not in Task manager. Hope this can help anyone looking for similar matter.
from app.manifest file:

<security>
  <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
    <!-- UAC Manifest Options
         If you want to change the Windows User Account Control level replace the
         requestedExecutionLevel node with one of the following.

    <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
    <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
    <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />

        Specifying requestedExecutionLevel element will disable file and registry virtualization.
        Remove this element if your application requires this virtualization for backwards
        compatibility.
    -->
    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
  </requestedPrivileges>
</security>

Public ReadOnly Property IsElevated As Boolean
    Get
        Return New WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)
    End Get
End Property

When using in the code:
If IsElevated = True Then
                Me.Text = "TEST Utility - Administrator (Elevated)"
            End If
            If IsElevated = False Then
                Me.Text = "TEST Utility - Normal (Non-Elevated)"
            End If


text:
Q: Javascript :checked function with a repeater in ASP.NET I am currently working on a project that needs to forward an email to every selected customer inside a repeater. I am working with a checkbox that I assign the email-address as value inside an asp repeater.
                <ItemTemplate>
                    <div class="odd">
                     <asp:label ID="lblT" runat="server" style="visibility:collapse; margin-left:9999px;" Text='<%# Eval("exposantID") %>'></asp:label>

                     <input runat="server" type="checkbox" class="chkExpo"  id="chkExpo" value='<%# Eval("exposantMail") %>'  />

Now I'm using jQuery :checked statement to get every checked checkbox inside the repeater.
    var n;
    function countChecked() {
         n = $("input:checked").length;

     }
     $(":checkbox").click(countChecked);

    countChecked();

    $("input").click(function () {

        for (var i = 0; i < n; i++) {
            alert($("input:checked").val());
        }

    });

The problem is I can only get the first checked value...I tried working with an index value but that didn't solve the problem. Does anyone have an idea how to get the value for each checkbox that is checked using this method?
Thanks,
Arnoud

A: $("input[type='checkbox']").click(function () {
    $("input[type='checkbox']:checked").each(function(){
        alert($(this).val());
    });
});


text:
Q: Get absolute_url with Django signal I would like to get the absolute url from my saved object. My model has a method named get_absolute_url and I would like to call this method with my django post_save signal.
I receive a post_save signal when a new entry is added inside a specific table named Thread. This post_save signal executes my Celery task.
My Thread model is :
class Thread(models.Model):
    """ A thread with a title """

    topic = models.ForeignKey('Topic')
    title = models.CharField(max_length=200)
    sticky = models.BooleanField(default=False)
    slug = models.SlugField()
    time_created = models.DateTimeField(default=timezone.now)
    time_last_activity = models.DateTimeField(default=timezone.now)

    def __init__(self, *args, **kwargs):
        """ Initialize 'time_last_activity' to 'time_created' """
        super(Thread, self).__init__(*args, **kwargs)

        self.time_last_activity = self.time_created

    def __str__(self):
        """ Return the thread's title """
        return self.title

    def get_absolute_url(self):
        """ Return the url of the instance's detail view """
        url_kwargs = {
            'topic_pk': self.topic.pk,
            'topic_slug': self.topic.slug,
            'thread_pk': self.pk,
            'thread_slug': self.slug,
        }
        return reverse('simple-forums:thread-detail', kwargs=url_kwargs)

In my model, I have a celery.py file :
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db.models.signals import post_save
from django.dispatch import receiver
from simple_forums.models import Thread

from ..tasks import thread_notification

@receiver(post_save, sender=Thread)
def get_new_thread(sender, instance, **kwargs):
    """ Post_save method which start Celery task to notify forum subscribers that a new thread has been created """
    url = Thread.get_absolute_url()
    print(url)
    thread_title = instance.title
    thread_id = instance.id
    topic_id = instance.topic_id
    topic_slug = instance.topic.slug
    topic_title = instance.topic.title
    thread_notification.delay(thread_id=thread_id, thread_title=thread_title, topic_id=topic_id, topic_slug=topic_slug,
                              topic_title=topic_title)

And in my tasks.py file :
# -*- coding: utf-8 -*-

from celery import shared_task
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext_lazy as _

User = get_user_model()

@shared_task(bind=True, time_limit=3600, soft_time_limit=3600)
def thread_notification(self):
    print('Celery task executed')
    return ['success_message', _('Celery task ended')]

I would like to get the absolute_url in order to send an email with the new Thread path.
My question is : How I can pick up get_absolute_url or use request.build_absolute_uri if I don't have a specific view (not necessary) ?

A: Here:
@receiver(post_save, sender=Thread)
def get_new_thread(sender, instance, **kwargs):
    url = Thread.get_absolute_url()

the saved Thread instance is (suprise, surprise) your instance argument, so you want:
    url = instance.get_absolute_url()

calling an instance method on a class makes no sense (nb: except for a couple specific corner cases, and then you have to pass the instance as first argument, but let's not get further with this, when you'll need it you'll know how it works).
Now since you're in the same app, using a signal here makes no sense either and is actually an antipattern. The point of signals is to allow an app to react to events emitted by other apps. Here, your code should quite simply be in Thread.save().


text:
Q: Preventing threads from unnecessary exit and keep the pool alive Suppose I call a program with OMP_NUM_THREADS=16.
The first function calls #pragma omp parallel for num_threads(16).
The second function calls #pragma omp parallel for num_threads(2).
The third function calls #pragma omp parallel for num_threads(16).
Debugging with gdb shows me that on the second call 14 threads exit. And on the third call, 14 new threads are spawned.
Is it possible to prevent 14 threads from exiting on the second call? Thank you.
The proof listings are below.
$ cat a.cpp
#include <omp.h>

void func(int thr) {
    int count = 0;

    #pragma omp parallel for num_threads(thr)
    for(int i = 0; i < 10000000; ++i) {
        count += i;
    }
}

int main() {
    func(16);

    func(2);

    func(16);

    return 0;
}

$ g++ -o a a.cpp -fopenmp -g

$ ldd a
...
libgomp.so.1 => ... gcc-9.3.0/lib64/libgomp.so.1
...

$ OMP_NUM_THREADS=16 gdb a

...

Breakpoint 1, main () at a.cpp:13
13          func(16);
(gdb) n
[New Thread 0xffffbe24f160 (LWP 27216)]
[New Thread 0xffffbda3f160 (LWP 27217)]
[New Thread 0xffffbd22f160 (LWP 27218)]
[New Thread 0xffffbca1f160 (LWP 27219)]
[New Thread 0xffffbc20f160 (LWP 27220)]
[New Thread 0xffffbb9ff160 (LWP 27221)]
[New Thread 0xffffbb1ef160 (LWP 27222)]
[New Thread 0xffffba9df160 (LWP 27223)]
[New Thread 0xffffba1cf160 (LWP 27224)]
[New Thread 0xffffb99bf160 (LWP 27225)]
[New Thread 0xffffb91af160 (LWP 27226)]
[New Thread 0xffffb899f160 (LWP 27227)]
[New Thread 0xffffb818f160 (LWP 27228)]
[New Thread 0xffffb797f160 (LWP 27229)]
[New Thread 0xffffb716f160 (LWP 27230)]
15          func(2);
(gdb)
[Thread 0xffffba9df160 (LWP 27223) exited]
[Thread 0xffffb716f160 (LWP 27230) exited]
[Thread 0xffffbca1f160 (LWP 27219) exited]
[Thread 0xffffb797f160 (LWP 27229) exited]
[Thread 0xffffb818f160 (LWP 27228) exited]
[Thread 0xffffbd22f160 (LWP 27218) exited]
[Thread 0xffffb899f160 (LWP 27227) exited]
[Thread 0xffffbda3f160 (LWP 27217) exited]
[Thread 0xffffbb1ef160 (LWP 27222) exited]
[Thread 0xffffb91af160 (LWP 27226) exited]
[Thread 0xffffba1cf160 (LWP 27224) exited]
[Thread 0xffffb99bf160 (LWP 27225) exited]
[Thread 0xffffbb9ff160 (LWP 27221) exited]
[Thread 0xffffbc20f160 (LWP 27220) exited]
17          func(16);
(gdb)
[New Thread 0xffffbb9ff160 (LWP 27231)]
[New Thread 0xffffbc20f160 (LWP 27232)]
[New Thread 0xffffb99bf160 (LWP 27233)]
[New Thread 0xffffba1cf160 (LWP 27234)]
[New Thread 0xffffbda3f160 (LWP 27235)]
[New Thread 0xffffbd22f160 (LWP 27236)]
[New Thread 0xffffbca1f160 (LWP 27237)]
[New Thread 0xffffbb1ef160 (LWP 27238)]
[New Thread 0xffffba9df160 (LWP 27239)]
[New Thread 0xffffb91af160 (LWP 27240)]
[New Thread 0xffffb899f160 (LWP 27241)]
[New Thread 0xffffb818f160 (LWP 27242)]
[New Thread 0xffffb797f160 (LWP 27243)]
[New Thread 0xffffb716f160 (LWP 27244)]
19          return 0;

A: The simple answer is that it isn't possible with GCC to force the runtime to keep the threads around. From cursory reading the source code of libgomp, there are no ICVs, portable or vendor-specific, that prevent the termination of excess idle threads in consecutive regions. (someone correct me if I'm wrong)
If you really need to rely on the unportable requirement that the OpenMP runtime uses persistent threads across regions with varying team sizes in between, then use Clang or Intel C++ instead of GCC. Clang's (actually LLVM's) OpenMP runtime is based on the open-source version of Intel's and they both behave the way you want. Again, this is not portable and the behaviour may change in future versions. It is instead advisable to not write your code in such a way that its performance depends on the particularities of the OpenMP implementation. For example, if the loop takes several orders of magnitude more time than the creation of a thread team (which is on the order of tens of microseconds on modern systems), it won't really matter whether the runtime uses persistent threads or not.
If OpenMP overhead is really a problem, e.g., if the work done in the loop is not enough to amortise the overhead, a portable solution is to lift the parallel region and then either re-implement the for worksharing construct like in @dreamcrash's answer or (ab)use OpenMP's loop scheduling by setting a chunk size that will only result in the desired number of threads working on the problem:
#include <omp.h>

void func(int thr) {
    static int count;
    const int N = 10000000;

    int rem = N % thr;
    int chunk_size = N / thr;

    #pragma omp single
    count = 0;

    #pragma omp for schedule(static,chunk_size) reduction(+:count)
    for(int i = 0; i < N-rem; ++i) {
        count += i;
    }

    if (rem > 0) {
        #pragma omp for schedule(static,1) reduction(+:count)
        for(int i = N-rem; i < N; ++i) {
            count += i;
        }
    }

    #pragma omp barrier
}

int main() {
    int nthreads = max of {16, 2, other values of thr};

    #pragma omp parallel num_threads(nthreads)
    {
        func(16);

        func(2);

        func(16);
    }

    return 0;
}

You need chunks of exactly equal sizes in all threads. The second loop is there to take care of the case when thr does not divide the number of iterations. Also, one cannot simply sum across private variables, hence count has to be shared, e.g., by making it static. This is ugly and drags along a bunch of synchronisation necessities that may have overhead comparable with spawning new threads and make the entire exercise pointless.

A: One approach would be to create a single parallel region, filter out the threads that will be executing the for, and manually distribute the loop iterations per thread. For simplicity sake, I will assume a parallel for schedule(static, 1):
include <omp.h>

void func(int total_threads) {
    int count = 0;
    int thread_id = omp_get_thread_num();
    if (thread_id < total_threads)
    {
       for(int i = thread_id; i < 10000000; i += total_threads) {
           count += i;
    }
    #pragma omp barrier
}

int main() {
    ...
    #pragma omp parallel num_threads(max_threads_to_be_used)
    {
        func(16);
        func(2);
        func(16);
    }
    return 0;
}

Bear in mind that there is a race condition count += i; that would have to be fixed. In the original code, you could easily fix it by using the reduction clause, namely #pragma omp parallel for num_threads(thr) reduction(sum:count). In the code with the manual for you could solved it as follows:
#include <omp.h>
#include<stdio.h>
#include <stdlib.h>

int func(int total_threads) {
    int count = 0;
    int thread_id = omp_get_thread_num();
    if (thread_id < total_threads)
    {
       for(int i = thread_id; i < 10000000; i += total_threads)
           count += i;
    }
    return count;
}

int main() {
    int max_threads_to_be_used = // the max that you want;
    int* count_array = malloc(max_threads_to_be_used * sizeof(int));
    #pragma omp parallel num_threads(max_threads_to_be_used)
    {
        int count = func(16);
        count += func(2);
        count += func(16);
        count_array[omp_get_thread_num()] = count;
    }
    int count = 0;
    for(int i = 0; i < max_threads_to_be_used; i++)
        count += count_array[i];
    printf("Count = %d\n", count);
    return 0;
}

I would say that most of the time, one will have the same number of thread used in each parallel region. So such type of pattern should not be much of an occurrent issue.


text:
Q: What is the correct way to configure grails maven authentication to Artifactory? What is the correct way to configure authentication to Artifactory using the Maven resolver?
Currently I'm using:
grails.project.ivy.authentication = {
    repositories {
        mavenRepo "http://SERVER:8081/artifactory/remote-repos"

    }
    credentials {
        realm = "Artifactory Realm"
        host = "SERVER"
        username = "USER"
        password = "PASSWORD"
    }
}

grails.project.dependency.resolver = "maven" // or ivy

grails.project.dependency.resolution = {
    // inherit Grails' default dependencies
    inherits("global") {
        // specify dependency exclusions here; for example, uncomment this to disable ehcache:
        // excludes 'ehcache'
    }
    log "warn" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
    checksums true // Whether to verify checksums on resolve
    legacyResolve false // whether to do a secondary resolve on plugin installation, not advised and here for backwards compatibility

    repositories {
        inherits true // Whether to inherit repository definitions from plugins

//        mavenLocal()

        mavenRepo id: 'Artifactory', url: "http://SERVER:8081/artifactory/remote-repos"

    }

If I change the resolver to "ivy" dependencies are downloaded.
With maven resolver Artifactory request log shows 401 errors
Relevant Grails documentation: http://grails.org/doc/latest/guide/conf.html#dependencyRepositories
Perhaps it has not yet been updated for Maven.

A: Our shop is currently using Grails 2.3.8, and each developer keeps a external build config in our home directory that contains the following:
artifactory.username = 'username'
artifactory.password = 'password'
artifactory.repo = 'http://our.artifactory.server.com:8080/artifactory/central'
artifactory.repositoryLocation = "http://our.artifactory.server.com:8080/artifactory/libs-release-local"

Here is how we configure all of our Grails projects in our BuildConfig.groovy:
def config = new ConfigSlurper(grailsSettings.grailsEnv).parse(new File("$home/my_build_config.groovy").toURI().toURL())

grails.project.dependency.resolver = "maven"

grails.project.dependency.resolution = {

    inherits("global") {
    }

    log "error"
    checksums true
    legacyResolve false

    repositories {

        String artifactoryUrl = config.artifactory.repo
        mavenRepo(artifactoryUrl) {

            auth([
                    username: config.artifactory.username,
                    password: config.artifactory.password
            ])

            updatePolicy "always"
        }
        mavenLocal()
    }

    dependencies {

        // ...
    }

    plugins {

        // ...
    }
}

If that doesn't work, I would suggest looking at the Artifactory permission settings for your virtual repositories and user permissions in general.

A: In BuildConfig.groovy, use:
grails.project.repos.default = "AT"

grails {
    project {
        repos {
            AT {
                url = "http://localhost:8081/artifactory/AT/"
                username = "bob"
                password = "MyUnguessablePassword"
            }
        }
    }
}

The doco is a bit hidden away, see: http://grails-plugins.github.io/grails-release/docs/manual/guide/single.html#repositories
A worked example is at: http://wordpress.transentia.com.au/wordpress/

A: One alternative is to put the following into ~/.grails/settings.groovy
myArtifactory{
    username = 'some_user'
    password = 'some_pass'
}

and than maven repository is configured like
mavenRepo("http://my-artifactory") {
        auth([
                username: grailsSettings.config.myArtifactory.username,
                password: grailsSettings.config.myArtifactory.password
        ])

        updatePolicy "always"
    }


text:
Q: Cxf Failure Interceptor for one service bean in multi-bean service I've a declaration in spring two services which are deployed on the same address. I would like to declare failure interceptor for only one of them, but is there a easy way to do that without changing address for two services? I would like to have them on the same address.
   <jaxrs:server id="service" address="http://0.0.0.0:${service.port:7070}/">
        <jaxrs:serviceBeans>
            <ref bean="firstService"/>
            <ref bean="secondService"/>
        </jaxrs:serviceBeans>

        <jaxrs:outInterceptors>
            <ref bean="failureInterceptor" />
        </jaxrs:outInterceptors>

        <jaxrs:features>
            <cxf:logging/>
            <ref bean="commonValidationFeature"/>
        </jaxrs:features>
        <jaxrs:providers>
            <ref bean="jsonProvider"/>
        </jaxrs:providers>
    </jaxrs:server>

A: You can declare two jax-rs server, each one with its own interceptor if you could adapt slightly the relative path of the services
For example, you can use both equivalently
<jaxrs:server id="ServiceAImpl" address="/test/a">
<jaxrs:server id="ServiceBImpl" address="/test/b">

<jaxrs:server id="serviceImpl" address="/test">
    <jaxrs:serviceBeans>
        <ref bean="serviceABean"/>  <!--  /test/a service -->
        <ref bean="serviceBBean"/>   <!--  /test/b service -->

but it is not allowed
<jaxrs:server id="ServiceAImpl" address="/test">
<jaxrs:server id="ServiceBImpl" address="/test">

If it is not possible for you, you could determine at interceptor which is the source service bean ( analysing method name or uri) and fire the especific interceptor manager


text:
Q: Switching to python 2.7 from 2.6 I am using MacOSX 10.6.8
I switched from python version 2.6 to python 2.7
But the modules I have downloaded for python 2.6 like sympy numpy doesn't work for 2.7
Do I need to install these things separately again?

A: As discussed in the comments, there are many issues associated with just moving the contents of your site-packages directory from Python 2.6 to 2.7. If there is any bytecode present (.pyc files) there's a chance they won't work with the new version. The ABI may also have changed. Additionally, modules like NumPy have compiled C extensions that rely on the source/headers of the version of Python being used to generate them, and that can change between minor versions (2.6 and 2.7). In general, you can use packages compiled with 2.7.3 with 2.7.6 (only the micro version has changed), but seeing as there were a large number of changes between 2.6 and 2.7 (2.7 has quite a few features backported from the 3.X line), using 2.6 modules with 2.7 just probably isn't a good idea.
If you have pure Python modules (no C extensions, any .pyc or .pyo files removed) you may be able to use them with 2.7, but it would be just as easy to reinstall them with pip-2.7. Modules with compiled libraries like NumPy will definitely need to be reinstalled. Finally, some modules may have different versions for use with 2.6 vs. 2.7 that take advantage of 2.7's new features, so in that case it'd definitely be worthwhile to reinstall.


text:
Q: How to validate against a different Mongoid collection? Background:
We need to throw away existing data and import new data each day. The import takes ~15 min, and we don't want the site to be without data during that time. My coworker's solution is to import the new data into a temporary collection, and, once it's done importing, rename the temporary to the production collection name. We save the new data one record at a time, not in a bulk save (as the second related question does).
However, I want to know if an object I'm trying to save to the temporary collection fails uniqueness with another object in that collection (disregarding uniqueness with the production collection). Currently when I call valid? it validates against the production collection, not the temporary collection. I'd like to scope my validations to a particular collection. (As in, if I check uniqueness on name I only want to check against the records in a given collection.)
Question:
How can I pass a collection name through for use with valid?? Or is there another way to validate objects against a non-default collection?
Related questions:

*

*Using collection-level operations in Mongoid

*Validating against a collection (array) in Mongoid