Q:

NSTextView inside NSTableView Blocks Scrolling

I have an NSTableView and within each table row there is an NSTextView. I have disabled scrolling on the NSTextView in my storyboard. I can scroll my NSTableView just fine, but when my mouse cursor is over the top of the NSTextView, the scrolling stops. I assume this is because the NSTextView is intercepting the scroll behavior.
The arrow points to the NSTextView:

Keep in mind that the NSTextView is in a subclassed NSTableViewCell.
class AnnouncementsVC: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
  @IBOutlet weak var tableView: NSTableView!

  override func viewDidLoad() {
    //...
  }
  func numberOfRows(in tableView: NSTableView) -> Int {
    //...
  }
  func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
    //...
  }
}

class AnnouncementTableCell: NSTableCellView{
  @IBOutlet weak var message: NSTextView!
}

How do I make the NSTextView pass its scroll events up to its parent NSTableView? My guess is I will need scrollWheel(with event: NSEvent) but I'm unsure where it goes since I have two different classes at play here.

A:

One way to achieve this would be to subclass NSScrollView and implement scrollWheel: to conditionally (1) either consume scroll-events in your subclass-instance as needed, or (2) forward them to an enclosing scrollview, based on your instances' current scrollposition.
Here's a rather rudimentary implementation (Obj-C) that i've used in the past:
- (void)scrollWheel:(NSEvent *)e {

    if(self.enclosingScrollView) {

        NSSize
        contSize = self.contentSize,
        docSize = [self.documentView bounds].size,
        scrollSize = NSMakeSize(MAX(docSize.width  - contSize.width, 0.0f),
                                MAX(docSize.height - contSize.height,0.0f) );

        NSPoint
        scrollPos = self.documentVisibleRect.origin,
        normPos = NSMakePoint(scrollSize.width  ? scrollPos.x/scrollSize.width  : 0.0,
                              scrollSize.height ? scrollPos.y/scrollSize.height : 0.0 );

        if( ((NSView*)self.documentView).isFlipped ) normPos.y = 1.0 - normPos.y;

        if(   ( e.scrollingDeltaX>0.0f && normPos.x>0.0f)
           || ( e.scrollingDeltaX<0.0f && normPos.x<1.0f)
           || ( e.scrollingDeltaY<0.0f && normPos.y>0.0f)
           || ( e.scrollingDeltaY>0.0f && normPos.y<1.0f) ) {

            [super scrollWheel:e];

        }
        else

            [self.nextResponder scrollWheel:e];

    }
    else
        // Don't bother when not nested inside another NSScrollView
        [super scrollWheel:e];
}

It still leaves much to be desired, like handling the deltaX and deltaY components independantly, but perhaps it's sufficient for your case.


Q:

RcppArmadillo: failing to install on Ubuntu16.04

I am trying to install Rcpp on Ubuntu. Here are some environment details:
R version:3.4.0
g++ --version: Ubuntu 5.4.0-6ubuntu1~16.04.4

If I have a blank Makevars file, RcppArmadillo can be installed but with some warnings about OpenMp
g++  -I/usr/share/R/include -DNDEBUG  -I"/home/march/R/x86_64-pc-linux-gnu-library/3.4/Rcpp/include"   -I../inst/include -fopenmp  -fpic  -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g  -c RcppArmadillo.cpp -o RcppArmadillo.o
In file included from ../inst/include/armadillo:52:0,
                 from ../inst/include/RcppArmadilloForward.h:46,
                 from ../inst/include/RcppArmadillo.h:31,
                 from RcppArmadillo.cpp:22:
../inst/include/armadillo_bits/compiler_setup.hpp:487:118: note: #pragma message: WARNING: support for OpenMP requires C++11/C++14; add -std=c++11 or -std=c++14 to compiler flags
   #pragma message ("WARNING: support for OpenMP requires C++11/C++14; add -std=c++11 or -std=c++14 to compiler flags")
                                                                                ^
g++  -I/usr/share/R/include -DNDEBUG  -I"/home/march/R/x86_64-pc-linux-gnu-library/3.4/Rcpp/include"   -I../inst/include -fopenmp  -fpic  -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g  -c RcppExports.cpp -o RcppExports.o
In file included from ../inst/include/armadillo:52:0,
                 from ../inst/include/RcppArmadilloForward.h:46,
                 from ../inst/include/RcppArmadillo.h:31,
                 from RcppExports.cpp:4:
../inst/include/armadillo_bits/compiler_setup.hpp:487:118: note: #pragma message: WARNING: support for OpenMP requires C++11/C++14; add -std=c++11 or -std=c++14 to compiler flags
   #pragma message ("WARNING: support for OpenMP requires C++11/C++14; add -std=c++11 or -std=c++14 to compiler flags")
                                                                                ^
g++  -I/usr/share/R/include -DNDEBUG  -I"/home/march/R/x86_64-pc-linux-gnu-library/3.4/Rcpp/include"   -I../inst/include -fopenmp  -fpic  -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g  -c fastLm.cpp -o fastLm.o
In file included from ../inst/include/armadillo:52:0,
                 from ../inst/include/RcppArmadilloForward.h:46,
                 from ../inst/include/RcppArmadillo.h:31,
                 from fastLm.cpp:22:
../inst/include/armadillo_bits/compiler_setup.hpp:487:118: note: #pragma message: WARNING: support for OpenMP requires C++11/C++14; add -std=c++11 or -std=c++14 to compiler flags
   #pragma message ("WARNING: support for OpenMP requires C++11/C++14; add -std=c++11 or -std=c++14 to compiler flags")
                                                                                ^
g++ -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o RcppArmadillo.so RcppArmadillo.o RcppExports.o fastLm.o -fopenmp -llapack -lblas -lgfortran -lm -lquadmath -L/usr/lib/R/lib -lR
installing to /home/march/R/x86_64-pc-linux-gnu-library/3.4/RcppArmadillo/libs
** R
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** installing vignettes
** testing if installed package can be loaded
* DONE (RcppArmadillo)

After I added PKG_CXXFLAGS=-std=c++11 to Makevars, I got a error message as following:
g++  -I/usr/share/R/include -DNDEBUG  -I"/home/march/R/x86_64-pc-linux-gnu-library/3.4/Rcpp/include"   -std=c++11 -fpic  -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g  -c RcppArmadillo.cpp -o RcppArmadillo.o
RcppArmadillo.cpp:22:27: fatal error: RcppArmadillo.h: No such file or directory
compilation terminated.
/usr/lib/R/etc/Makeconf:168: recipe for target 'RcppArmadillo.o' failed
make: *** [RcppArmadillo.o] Error 1
ERROR: compilation failed for package ‘RcppArmadillo’
* removing ‘/home/march/R/x86_64-pc-linux-gnu-library/3.4/RcppArmadillo’
* restoring previous ‘/home/march/R/x86_64-pc-linux-gnu-library/3.4/RcppArmadillo’
Warning in install.packages :
  installation of package ‘RcppArmadillo’ had non-zero exit status

The wield thing is that when I tried to re-install RcppArmadillo on my mac(10.11), the same problem occurred. Could anybody enlighten me?

A:

This is 16.10 which I have here at hone, if you wish I can repeat it at work tomorrow with 16.04:
edd@bud:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.10
Release:    16.10
Codename:   yakkety
edd@bud:~$ Rscript -e 'install.packages("RcppArmadillo")'
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/src/contrib/RcppArmadillo_0.7.960.1.1.tar.gz'
Content type 'application/x-gzip' length 1115539 bytes (1.1 MB)
==================================================
downloaded 1.1 MB

* installing *source* package ‘RcppArmadillo’ ...
** package ‘RcppArmadillo’ successfully unpacked and MD5 sums checked
checking whether the C++ compiler works... yes
checking for C++ compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C++ compiler... yes
checking whether ccache g++ accepts -g... yes
checking how to run the C++ preprocessor... ccache g++ -E
checking whether we are using the GNU C++ compiler... (cached) yes
checking whether ccache g++ accepts -g... (cached) yes
checking whether g++ version is sufficient... (6.2.0) yes
checking LAPACK_LIBS... system LAPACK found
checking for OpenMP... found
configure: creating ./config.status
config.status: creating inst/include/RcppArmadilloLapack.h
** libs
ccache g++ -I/usr/share/R/include -DNDEBUG  -I"/usr/local/lib/R/site-library/Rcpp/include"   -I../inst/include -fopenmp  -fpic  -g -O3 -Wall -pipe -Wno-unused -pedantic -Werror -march=native -c RcppArmadillo.cpp -o RcppArmadillo.o
ccache g++ -I/usr/share/R/include -DNDEBUG  -I"/usr/local/lib/R/site-library/Rcpp/include"   -I../inst/include -fopenmp  -fpic  -g -O3 -Wall -pipe -Wno-unused -pedantic -Werror -march=native -c RcppExports.cpp -o RcppExports.o
ccache g++ -I/usr/share/R/include -DNDEBUG  -I"/usr/local/lib/R/site-library/Rcpp/include"   -I../inst/include -fopenmp  -fpic  -g -O3 -Wall -pipe -Wno-unused -pedantic -Werror -march=native -c fastLm.cpp -o fastLm.o
ccache g++ -Wl,-S -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o RcppArmadillo.so RcppArmadillo.o RcppExports.o fastLm.o -fopenmp -llapack -lblas -lgfortran -lm -lquadmath -L/usr/lib/R/lib -lR
installing to /usr/local/lib/R/site-library/RcppArmadillo/libs
** R
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** installing vignettes
** testing if installed package can be loaded
* DONE (RcppArmadillo)

The downloaded source packages are in
    ‘/tmp/Rtmp2hQNrn/downloaded_packages’
edd@bud:~$

That I usee ccache is not material.  This. Just. Works.


Q:

How can I issue store credits in Magento CE?

I want to know, is there anyway that customers can have funds added to an account balance and then use their balance for shopping?
Don’t need buy coupon, gift or some things like these…
I want they add an amount, for example $50 in the field and then redirect to bank(for example paypal) , pay and after that their balance show :
Your Balance : $50
How can I go about this in Magento CE?

A:

Magento doesn't do this out of the box. What you want is somehow a gift card extension but the giftcard is not sent but used by oneself.
Implementing this is a lot of work, because you have to pay attention to a lot of things:

Buying funds (should be a product)
Not paying for them, so they don't get processed to the customers balance
Buying something with the funds
The amount is not high enough, so you have to mix different payment methods
This is the part where you want to implement distributed transaction, because of the below described case*
People send the things back, so you have to refund part to the customers balance and part to the creditcart/bank account/whatever second payment method (s)he used

Bad case
Order1: Customer has 50$ fund and buys something 100$ worth, he choose paypal to pay with, he is redirected to the paypal site to pay 50$.
Order2: In the same moment, he opens a second order, shops something for 49$, pays with his fund, everything is fine
Order1: The customer pays the 50$ with paypal, he comes backend and the order is flagged as paid ... ERROR.
In this case, you want to rollback the whole transaction, refund the 50$ paid via paypal and refund the maybe decreased 50$ on the funds.
This is technological a mess and I don't think it is worth to implement it correctly. Often companies decide, it is not needed to cover the above case, then it is not soo much work, but still a lot. Be careful with this.

A:

Explaining how to build an extension like this would be a bit too much for one answer cause, as Fabian explained, it involves a lot of work. One way to go about it is work something out with coupon codes per user (there are extensions for that) or a virtual product that doubles as a coupon code but this will require you to either write some code to create the coupon when someone purchases the product or manually add the code.
For this one I would advice to look at the already existing extensions. First of all because since it's such a tricky thing to build yourself better get something that has been proven to work and second because they're not that expensive. Probably the hours you'll spent on building itself won't weigh up to the cost of the extension.
Both Mageworx and Mageworld offer an extension for this


Q:

spring profiles in .yaml. How do you set up configuration properties?

I am a spring newbie and a .yaml newbie as well and I´m starting to get cross eyed googling answers(a lot of them are very outdated or just confusing).
Currently I have a application.yaml that looks like this
spring:
  profiles.active: TEST
---
spring:
  profiles: DEV
logging:
  level:
    org.springframework.web: INFO
    se.some.url: DEBUG
api:
  url:
     one: test.url
    two : test.url
certification:
  policies:
      one : 0.0.0.0.0
      two : 0.0.30.0

---
spring:
  profiles: TEST
logging:
  level:
    org.springframework.web: INFO
    se.some.url: DEBUG
api:
  url:
     one: test.url
    two : test.url
certification:
  policies:
      one : 0.0.0.0.0
      two : 0.0.30.0

I need to be able to use the values of the certification.policies and api.url in my code and make sure everything loads depending on with profile is active.
I do get that a config class needs to be created.
But what annotation should be used?
How do I set the profile?
How do I get the value?
Grateful for any help!

A:

You should read this documentation about externalized configuration.
With @ConfigurationProperties("some-property") you tell Spring to initialize the fields with the values configured in your .yml file.
The active profile can be specified when starting your jar. You can e.g. specify the active profile via command line: --spring.profiles.active=dev,hsqldb. See the documentation for more information.


Q:

General tutorial on OS X audio programming

I would like to do some fairly simple audio programming on OS X (using Lion and Xcode 4.3) -- synthesizing tones with given frequencies, mainly.  Trouble is, Apple's documentation on the subject is way too high-level for my current knowledge of the subject.  I've searched for weeks now for something that will get me started, to no avail.
Does anyone know of some Core Audio basic tutorial, or even some sample code, that will help me do fairly simple Core Audio tasks so that I can progress to understanding the Apple documentation?

A:

I would suggest the book Learning Core Audio There is also sample code from the book at that site.


Q:

Java threads without affecting performance

Long story short; I've written a program that contains an infinite loop, in which a function is run continuously, and must run as quickly as is possible.
However, whilst this function completes in a microsecond time scale, I need to spawn another thread that will take considerably longer to run, but it must not affect the previous thread.
Hopefully this example will help explain things:
while (updateGUI == true) { //So, forever until terminated

        final String tableContents = parser.readTable(location, header);
        if (tableContents.length() == 0) {//No table there, nothing to do
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
                    //updateTable updates a JTable
                    updateTable(tableContents, TableModel);
                    TableColumnModel tcm = guiTable.getColumnModel();
                }
            });
        }
     ***New thread is needed here!
    }

So what I need is for the readTable function to run an infinite number of times, however I then need to start a second thread that will also run an infinite number of times, however it will take milliseconds/seconds to complete, as it has to perform some file I/O and can take a bit of time to complete.
I've played around with extending the Thread class, and using the Executors.newCacheThreadPool to try spawning a new thread.  However, anything I do causes the readTable function to slow down, and results in the table not being updated correctly, as it cannot read the data fast enough.
Chances are I need to redesign the way this loop runs, or possible just start two new threads and put the infinite looping within them instead.
The reason for it being designed this way was due to the fact that once the updateTable function runs, it returns a string that is used to update a JTable, which (as far as I know), must be done on Java's Main Dispatch Thread, as that is where the GUI's table was created.
If anyone has any suggestions I'd greatly appreciate them.
Thanks

A:

As you are updating a JTable, SwingWorker will be convenient. In this case, one worker can coexist with another, as suggested here.

A:

You have to be very careful to avoid overloading your machine.  You long running task need to be made independent of you thread which must be fast.  You also need to put a cap on how many of these are running at once.  I would put a cap of one to start with.
Also you screen can only update so fast, and you can only see the screen updating so fast.  I would limit the number of updates per second to 20 to start with.
BTW Setting the priority only helps if your machine is overloaded.  Your goal should be to ensure it is not overloaded in the first place and then the priority shouldn't matter.


Q:

rails model test validate_uniqueness scoped

I trying to do rspec model test on validation with scope but do not understand why i have error
my model
class EcrPortMapping < ActiveRecord::Base
  belongs_to :ecr
  validates :ecr_id,presence: true
  validates :ecr_id, :uniqueness => {:scope => [:port_source, :port_target]}
  validates :ecr_id, :uniqueness => {:scope => :port_source}
  validates :ecr_id, :uniqueness => {:scope => :port_target}
end

my rspec test
    require 'rails_helper'

RSpec.describe EcrPortMapping, type: :model do
  describe 'uniqueness of ecr_id for port & target' do

    it 'should validate uniqueness of ecr_id scoped to port_target & port_source' do
      ecr = FactoryGirl.create(:ecr)
      FactoryGirl.create(:ecr_port_mapping, ecr_id: ecr.id)
      should validate_uniqueness_of(:ecr_id).scoped_to([:port_source, :port_target])
      should validate_uniqueness_of(:ecr_id).scoped_to(:port_source)
      should validate_uniqueness_of(:ecr_id).scoped_to(:port_target)

 end
end

i have error
Failure/Error: should validate_uniqueness_of(:ecr_id).scoped_to([:port_source, :port_target])
   Did not expect errors to include "already exists" when ecr_id is set to 4,
   got errors:
   * "already exists" (attribute: ecr_id, value: 4) (with different value of port_source)

I need this type of validations
Where I made a mistake?

A:

Change that ports should be unique in scope of ecr
validate :port_source, : uniqueness => { :scope => :ecr_id }
validate :port_target, : uniqueness => { :scope => :ecr_id }


Q:

How to select the max int value of a TEXT column in SQLite

Given a TABLE mytable with a column of TEXT name containing VALUES 1, 2, 2b, 2c, 3. How do you select the maximum INT value in SQLite?
-- Does not work in SQLite
SELECT MAX(VAL(textcol)) FROM mytable;

Took me some time to find as I kept falling on instructions for other SQL syntaxes.

A:

SELECT MAX(CAST(name AS INT)) FROM mytable;

SQLite uses CAST(expr AS type-name) similar to MySQL


Q:

How to add Excel File name in all rows exists in that excel in C#

I have more than 100 excel files.My job is to merge to all the excel files into one excel. I did easily by writing the C# program for merging excels. Now I need to Identify the records as per the excel file name.I mean I need to add the actual Excel file name to the new columns for all rows exists.
For Example:
I have excel Dom.xls having 2 rows in that excel.
   Name   SSN   Address
    1      0923  1 winter st
    2      0924  2 winter st

Now I need the excel should create new column named"Excel File Name"
and should write the file name like beow
   Name   SSN   Address         Excel File Name
    1      0923  1 winter st     dom.xls
    2      0924  2 winter st     dom.xls

How Do I achieve this.
Either I need this requirement before merging all the excels or after merging the excels.
Below code I used to merge all excels.
class Program
{
    static void Main(string[] args)
    {
        MergeExcel.DoMerge(new string[]
       {
          @"C:\Users\dom\Desktop\Reim Account\032 - dom_AMESBURY.xlsx",
          @"C:\Users\dom\Desktop\Reim Account\128 - dom_BRAINTREE.xlsx",
          @"C:\Users\dom\Desktop\Reim Account\960 - dom_RETIREMENT.xlsx"....etc
       },
          @"D:\MyExcel\dom.xlsx", "V", 2);
    }
}

public class MergeExcel
{
    Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();

    //initialize the object of saved target
    Excel.Workbook bookDest = null;
    Excel.Worksheet sheetDest = null;

    //initialize the object of read data
    Excel.Workbook bookSource = null;
    Excel.Worksheet sheetSource = null;
    string[] _sourceFiles = null;
    string _destFile = string.Empty;
    string _columnEnd = string.Empty;
    int _headerRowCount = 0;
    int _currentRowCount = 0;
    public MergeExcel(string[] sourceFiles, string destFile, string columnEnd, int headerRowCount)
    {

        //Use class Missing case to indicate the missing value. e.g. when you call the method that has default parameter value
        bookDest = (Excel.WorkbookClass)app.Workbooks.Add(Missing.Value);
        sheetDest = bookDest.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value) as Excel.Worksheet;
        sheetDest.Name = "Data";
        _sourceFiles = sourceFiles;
        _destFile = destFile;
        _columnEnd = columnEnd;
        _headerRowCount = headerRowCount;
    }

    //open worksheet
    void OpenBook(string fileName)
    {
        bookSource = app.Workbooks._Open(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
        sheetSource = bookSource.Worksheets[1] as Excel.Worksheet;
    }

    //close worksheet
    void CloseBook()
    {
        bookSource.Close(false, Missing.Value, Missing.Value);
    }

    //copy table header
    void CopyHeader()
    {
        Excel.Range range = sheetSource.get_Range("A1", _columnEnd + _headerRowCount.ToString());
        range.Copy(sheetDest.get_Range("A1", Missing.Value));
        _currentRowCount += _headerRowCount;
    }

    //copy data
    void CopyData()
    {
        int sheetRowCount = sheetSource.UsedRange.Rows.Count;
        Excel.Range range = sheetSource.get_Range(string.Format("A{0}", _headerRowCount), _columnEnd + sheetRowCount.ToString());
        range.Copy(sheetDest.get_Range(string.Format("A{0}", _currentRowCount), Missing.Value));
        _currentRowCount += range.Rows.Count;
    }

    //save the result
    void Save()
    {
        bookDest.Saved = true;
        bookDest.SaveCopyAs(_destFile);
    }

    //exit the process
    void Quit()
    {
        app.Quit();
    }
    void DoMerge()
    {

        //declare variate bool to judge if copy table header
        bool b = false;
        foreach (string strFile in _sourceFiles)
        {
            OpenBook(strFile);
            if (b == false)
            {
                CopyHeader();
                b = true;
            }
            CopyData();
            CloseBook();
        }
        Save();
        Quit();
    }
    /// merge table
    /// source file
    /// object file
    /// the sign of the last column
    /// the number of rows of table header
    public static void DoMerge(string[] sourceFiles, string destFile, string columnEnd, int headerRowCount)
    {
        new MergeExcel(sourceFiles, destFile, columnEnd, headerRowCount).DoMerge();
    }
}

A:

You could do something like this in CopyData. Send the filename to CopyData void CopyData(string strFile). Then after range.Copy add the following lines.
Excel.Range range_name = sheetDest.get_Range(string.Format("E{0}", _currentRowCount), string.Format("E{0}", _currentRowCount + sheetRowCount));
range_name.Value = strFile;

This will add the filename to column E. Maybe some tweaking is necessary since I'm not that familiar with Excel Interop.


Q:

R: Finding the location of tick marks when plotting dates

I'm running an R script which plots data over time using plot and some data taken as.Date. I am then adding using grid to add guidelines like so:
plot(as.Date(data[["Date"]]), -data[["dbns"]], lwd=1, col = colours[i], type="l",ylim=ylimit, xlim=xlimit, xlab="", ylab =ylabel)

grid(NULL,NULL,lwd=1)

Below is an example of how this comes out (actually example is after this plot is looped over 3 times to add each line)

The problem I am having is that the guidelines added with grid do not line up with the default tick marks added by plot. The plot function by default adds tick every 10 years, which is what I want. Looking at axTicks(1) gives me 0  5000 10000 15000 which is the locations of guidelines in units of days after 1/1/1970.
Is there a way to find out the location of the tickmarks that have been added? And more importantly, is there then a way to set the guidelines to match these locations?
I realise that for this example the ticks are [0, 365.25*10, 365.25*20 etc.] but an answer which solves a general case would be nice.
Thanks
JP
EDIT:
Here is a reproducible example to show exactly what I mean.
data <- read.csv("test.csv"), header =TRUE)
data[["Date"]] <- as.Date(data[["Date"]], format = "%d/%m/%Y")

data<-data[order(as.Date(data$Date)),]

plot(as.Date(data[["Date"]]), -data[["dbns"]], type="l", xlim=xlimit)
grid(NULL,NULL,lwd=3)

Where the file test.csv looks like this (extract of actual data)
bore    Date    dbns
42230210A   20/01/2009  13.13
42230210A   8/05/2009   13.21
42230210A   18/06/2009  13.19
42230210A   3/08/2009   13.2
42230210A   2/09/2009   13.25
42230210A   1/10/2009   13.3
42230210A   3/12/2009   13.32
42230210A   24/02/2010  13.3
42230210A   18/05/2010  13.3
42230210A   25/04/2012  11.45
42230210A   27/09/1966  11.18
42230210A   28/10/1969  11.14
42230210A   6/01/1970   11.03
42230210A   5/06/1973   10.68
42230210A   28/08/1973  10.63
42230210A   2/10/1973   10.73
42230210A   4/12/1973   10.7
42230210A   20/02/1980  11.39
42230210A   29/04/1980  11.45
42230210A   27/08/1980  11.45
42230210A   22/06/1988  11.14
42230210A   27/02/1996  11.78
42230210A   6/08/1996   11.68
42230210A   8/02/2000   11.64
42230210A   8/06/2000   11.71
42230210A   7/09/2000   11.75
42230210A   15/07/2008  13.01

The output of which is below. The guidelines are offset from the tick marks?

A:

So checking ?grid suggests that what's going on is that it is placing the grid lines based on the "default" tick mark locations, but since you plotted a date object, R didn't use the "default" (in the sense of treating the date as a numeric variable) to place the tick marks.
The documentation further notes that if you need finer control, you should use abline to place them directly.
So you probably want to do this:
plot(as.Date(data[["Date"]]), -data[["dbns"]], type="l")
grid(NA,NULL,lwd=3)
v <- as.numeric(as.Date(paste0(c(1970,1980,1990,2000,2010),'-01-01')))
abline(v = v,lty = "dotted",col = "lightgray",lwd = 3)

A:

There is a function Axis.Date which creates appropriately pretty axis tick locations for an axis for a Date object. This does not change par('xaxp') which grid uses to find the locations of the tick marks.
We can get around  by creating the axis manually (and saving the values)
# assuming your data is called DD
DD$Date <- as.Date(as.character(DD$Date), format = '%d/%m/%Y')
# don't plot the x axis (xaxt = 'n')
plot(-dbns~Date,data = DD[order(DD$Date),], type="l", xaxt = 'n')
# create the axis and  save the tick locations
at <- as.numeric(Axis(side = 1, x = DD$Date))
grid(NA,NULL,lwd=3)
abline(v = at,lty = "dotted",col = "lightgray",lwd = 3)


Q:

centOS 7 - difficulties with installing Python 3

I have a brand new centOS 7 VM that am trying to install Python 3 (currently 3.6.0) on. I am following a guide from Daniel Eriksson (https://danieleriksson.net/2017/02/08/how-to-install-latest-python-on-centos/)
but I'm running into an Pemission denied error when running the make && make altinstall command.
The last section of the error I'm getting is here:
gcc -pthread -c -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes    -std=c99 -Wextra -Wno-unused-result -Wno-unused-parameter -Wno-missing-field-initializers   -I. -I./Include   -fPIC -DPy_BUILD_CORE -o Programs/_testembed.o ./Programs/_testembed.c
gcc -pthread -Wl,-rpath /usr/local/lib  -Xlinker -export-dynamic -o Programs/_testembed Programs/_testembed.o -L. -lpython3.6m -lpthread -ldl  -lutil   -lm
# Substitution happens here, as the completely-expanded BINDIR
# is not available in configure
sed -e "s,@EXENAME@,/usr/local/bin/python3.6m," < ./Misc/python-config.in >python-config.py
# Replace makefile compat. variable references with shell script compat. ones;  ->
LC_ALL=C sed -e 's,\$(\([A-Za-z0-9_]*\)),\$\{\1\},g' < Misc/python-config.sh >python-config
# On Darwin, always use the python version of the script, the shell
# version doesn't use the compiler customizations that are provided
# in python (_osx_support.py).
if test `uname -s` = Darwin; then \
    cp python-config.py python-config; \
fi
if test "no-framework" = "no-framework" ; then \
    /bin/install -c python /usr/local/bin/python3.6m; \
else \
    /bin/install -c -s Mac/pythonw /usr/local/bin/python3.6m; \
fi
/bin/install: cannot create regular file ‘/usr/local/bin/python3.6m’: Permission denied
make: *** [altbininstall] Error 1

I don't usually work with Linux, so I'm not exactly sure where to look for or what to try next. Any help on this appreciated. Thank you

A:

The issue is with the permission required when running the command to install the package.
Use
sudo make && sudo make altinstall
instead of:
sudo make && make altinstall


Q:

Given a family of hash functions in table form, how can I know whether it's universal?

I've been given the following two families of hash functions:
H

and
G

Each family has three functions $\{0,1,2,3,4\} \to \{0,1,2\}$ that can be seen in the tables above. For each family I need to decide whether it's universal. I know that a family of hash functions $F$ is called universal if for every $x \neq y$, $\text{Pr}(f(x) = f(y)) \le \frac{1}{m}$ ($f$ is a function in $F$).
However, I don't understand how to calculate this probability. Should I calculate it for any one of the functions or for the whole family?

A:

As you have stated, given a family $H$ of hash functions, the condition for universality is $\forall x,y, x \neq y: \text{P}_{h \in H}(h(x) \neq h(y)) \le \frac{1}{m}$. The probability is taken over $h \in H$, which is picked following a uniform distribution.
If you think for a while about what that means, you'll realize you need simply check whether there is at most one collision (i.e., equal entries) for any two distinct columns (i.e., every pair of $x$ and $y$) in the respective family's table. Hence, $G$ is universal, but $H$ is not; I'll let you figure out why.


Q:

free() does not work in C

I am trying to free up the memory after using the malloc() function but its not working for me.
    //This becomes my header file
    char* staticIP;
    char* start = NULL;
    char* ende = NULL;

    char* splitString(char* start, char* ende) {
    size_t len = ende-start;
    char* result = (char*)malloc(sizeof(char)*(len+1));
    strncpy(result,start,len);
    result[len] = '\0';
    return result;
    }

    //TO free memory
    void freePointer(char* pointer) {
      if (pointer != NULL) {
      free(pointer);
      pointer=NULL;
     }
    }

    //Function uses splitString which does the malloc
    void extractIP(char* buffer) {
     char* start = strstr(buffer,"IP=")+3;
     char* ende = strstr(start,":");
     freePointer(staticIP);
     staticIP = splitString(start,ende);
   }

    void setupWifi() {
     char* result = WIFI.getIPString();
     extractIP(result);
     #ifdef DEBUG
     USB.print("NEW IP: ");
     USB.println(staticIP);
     #endif
    }

Unfortunately this does not works for me, suggestions/corrections would be appreciated
This the possible use case of my code :
    #include<modwifi.h>
    void setup() {
     setupWifi();
    }

This code is repetitively called after some time interval, static IP gets updated each time which requires that the old static ip gets freed but does not works. I have tried logging the memory after each call but it keeps decreasing till it reaches 0.
This is the possible meaningful code which I could extract out of the big file.
Note: I believe there might be some issue with the start and end as it is declared as pointer but does not uses malloc.

A:

Alas on many system logging the available memory of a process doesn't give the expected results. malloc/free logically allocates/deallocates memory and does not means that the corresponding memory of the process in the system grows or shrinks accordingly. For efficiency, the system do not behave such because in would be too costly.
Think about a binder with pages. When your process needs space, then the necessary space is searched in the blank pages set currently in the binder, if there is some then your process will used them (logical allocation), if not then you need to add new blank pages to your binder and then use them (physical allocation then logical). When you free memory, corresponding pages are just logically erased (with a logical rubber), but are not returned nor removed.
When you log the memory of a process what you log is the number of pages in your binder...
While it is not impossible to remove the pages from the process space (it depends on the OS), it is not done by standard memory allocation libraries.


Q:

Django i18n not working on python files

Django newbie here,
I'm using Django's i18n to translate my website.
My templates get translated just fine using the trans template tag
However, when I try to translate strings in my python files, for instance this form field's label:
from django.utils.translation import gettext as _

class RegForm(forms.Form):
    form_field = forms.CharField(label=_('My field'))

It does not get translated.
The same page contains other template strings that do get translated..
Any ideas?

A:

The solution is to use ugettext_lazy instead of gettext


Q:

how can i speed up copy/paste into a shared workbook using vba

I have a macro that runs on a shared workbook. it copy/pastes from an un-shared workbook into the shared workbook, closes the un-shared workbook, and then does a series of lookups. I find that while shared, the update hangs a bit when it performs the open/copy/paste/close of the un-shared workbook. Is there any way to speed this up?
I have set displayupdate = false and calculations = manual and that did help the lookups but it has not solved the delay on the open/copy/paste/close operation. Any advice?
I know that shared workbooks aren't the best, but my users are keen on it...

A:

If you're correct in concluding that the open/copy/paste/close process time while having a shared workbook open is increased exponentially, but otherwise is only increased marginally, then I think the best method for improving performance would be to copy/paste all the un-shared workbooks into another un-shared workbook that will serve as a buffer. Then use your code to open the shared workbook and copy/paste code from the buffer into said shared workbook.
This will help if the hangup is occurring in the open/close and not in the copy/paste--which I suspect is the case.


Q:

C# add event handler to class that has been loaded from an assembly at run time

As part of evaluating a 3rd party DLL called "GemBox.document", i want to be able to run this assembly during run time. However in order to get it to run in trial mode, i need to use this:
ComponentInfo.FreeLimitReached +=
    (sender, e) => e.FreeLimitReachedAction = FreeLimitReachedAction.ContinueAsTrial;

This is the standard way if you directly reference the DLL in the application. However, i want to be able to do this by calling the DLL at runtime. What is the correct syntax for this?
Edit: ComponentInfo is a public static class of GemBox.Document

A:

For future reference, here is how we can load GemBox.Document assembly at run-time and set it in a Trial mode through reflection:
using System;
using System.Reflection;

class Program
{
    // Load GemBox.Document assembly.
    static Assembly gemboxAssembly = Assembly.LoadFrom(@"C:\GemBox.Document.dll");

    // Create method for handling FreeLimitReached event.
    static void HandleFreeLimit(object sender, EventArgs e)
    {
        // Call: e.FreeLimitReachedAction = FreeLimitReachedAction.ContinueAsTrial
        dynamic freeLimitArgs = e;
        freeLimitArgs.FreeLimitReachedAction =
            (dynamic)Enum.Parse(
                gemboxAssembly.GetType("GemBox.Document.FreeLimitReachedAction"),
                "ContinueAsTrial");
    }

    static void Main(string[] args)
    {
        // Call: ComponentInfo.SetLicense("FREE-LIMITED-KEY")
        Type componentInfo = gemboxAssembly.GetType("GemBox.Document.ComponentInfo");
        componentInfo.GetMethod("SetLicense", BindingFlags.Public | BindingFlags.Static)
            .Invoke(null, new object[] {"FREE-LIMITED-KEY"});

        // Get HandleFreeLimit as MethodInfo.
        MethodInfo handleFreeLimitMethod =
            typeof(Program).GetMethod("HandleFreeLimit",
                BindingFlags.NonPublic | BindingFlags.Static);

        // Call: ComponentInfo.FreeLimitReached += HandleFreeLimit
        EventInfo freeLimitReached = componentInfo.GetEvent("FreeLimitReached");
        freeLimitReached.AddEventHandler(null,
            Delegate.CreateDelegate(freeLimitReached.EventHandlerType,
                handleFreeLimitMethod));

        // Call: DocumentModel document = DocumentModel.Load(@"C:\Sample.docx")
        Type documentModel = gemboxAssembly.GetType("GemBox.Document.DocumentModel");
        dynamic document = documentModel.GetMethod("Load", new Type[]{ typeof(string)})
            .Invoke(null, new object[] { @"C:\Sample.docx" });

        // TODO: Use "document" object as needed ...
        document.Save(@"C:\Sample.pdf");
    }
}


Q:

Commutation of abstract $O(3)$ generators and vectors

I've been given the following problem, and I'm quite lost with it.

Let $L_1$, $L_2$, and $L_3$ denote the abstract $o(3)$ algebras. You are given that $\vec{A} = (A_1, A_2, A_3)$ and $\vec{B} = (B_1, B_2, B_3)$ transform as vector operators of $o(3)$.
Show that $[L_j, \vec{A} \cdot \vec{B}] = 0$

I know that $L_j = \varepsilon_{jlm} q_l p_m$, and I can obviously determine the dot product, but I'm not sure where to go from there.
I do, however, know that $\vec{A} = \frac{1}{Ze^{2}\mu}(\vec{L} \times \vec{p}) + (\frac{1}{r})\vec{r}$, but I'm not sure how to integrate that into this problem.

A:

A collection $\{V_1, V_2, V_3\}$ of operators on a vector space $V$ is called an $\mathfrak{o}(3)$ vector operator with respect to a representation $\rho$ of $\mathfrak{o}(3)$ acting on $V$ provided
\begin{align}
  [V_i, L_j] = i\epsilon_{ijk}V_k
\end{align}
where $L_1, L_2, L_3$ are the representatives of the standard basis on $\mathfrak{o}(3)$.  This means, in your case, that merely knowing that $A_i$ and $B_i$ are the components of vector operators tells us that
\begin{align}
  [A_i, L_j]=i\epsilon_{ijk}A_k, \qquad  [B_i, L_j]=i\epsilon_{ijk}B_k
\end{align}
These commutation relations alone are sufficient to demonstrate the desired result using commutator identities.
As a tangential note, you will probably find the Wikipedia page on tensor operators to be generally, conceptually helpful for understanding this stuff.  Also, a while back I asked the following question on physics.SE dealing with how to generalize and formalize the notion of tensor operators in a less basis-dependent way than how I defined them at the beginning of this answer.  In case you're interested in math, here is that question:
Tensor Operators


Q:

Как работают указатели?

Как работают указатели?
Что будет в итоге, если я напишу так?
HANDLE * VariableHandle;
DWORD * VariableDword;

или так?
HANDLE VariableHandle;
DWORD VariableDword;

Пример из исходных кодов других программ.
Почему так?
int chSizeOfArray(char *chArray);
int iSizeOfArray(int *iArray);

А не так?
int chSizeOfArray(char chArray);
int iSizeOfArray(int iArray);

A:

Когда вы пишете HANDLE * VariableHandle;, вы объявляете, что в переменной VariableHandle будет содержаться указатель на HANDLE. А объявление HANDLE VariableHandle; означает, что в переменной VariableHandle будет содержаться сам HANDLE.
В языках типа C указатель используется во многих смыслах. Один из них — это массив элементов. Функции int f1(char *chArray); и int f2(char ch); обе возможны, но при этом f1 принимает в качестве аргумента массив char'ов (или указатель на один char, это уж как в документации написано), а f2 — один char.

Как верно подсказывает @ixSci, лучше всего думать про указатель как про адрес объекта. Если представить себе всю память как огромный массив байт, адрес — это просто номер начального байта, занимаемого данными, в этом массиве. (Это несколько упрощённая картина, но для начала то, что нужно.)


Q:

Google indexed pages for one page site

I have created a one page site with wordpress. The basic idea used was to combine pages and their templates into index.php.
The problem is that when crawlers work on the site, they get the links for the pages which is good, but they display the page as single item and not part of the one page site.
How can I redirect these pages into the main site? Is there a plugin or a way to achieve it?

A:

This is not wordpress related question but I will answer it without any special reason.
First of all... all pages from old website are indexed on google and those indexed pages can not be deindexed at the same moment when you change the website. That is the reason why all pages show on google... so you have to wait or you have to play around in Google webmaster tools in order to speed up that process.
You can create redirections simply with this plugin:
http://wordpress.org/plugins/simple-redirect/
I hope that this will help you to understand what is going on.
But... as experienced SEM guru I would never combine all those pages into one page because of many reasons.... but that is not important now.


Q:

Symfony 2 generate:bundle - with or without namespace /Bundle/

I'm new to Symfony. I went through the documentation and recent tutorials about Symfony 2. When creating a bundle, documentation always tells use to "Vendor/Bundle/BlogBundle" like path (including middle 'Bundle'folder). But when I'm reading most of the tutorials they have used 'Vendor/BlogBundle' like path (not include a 'Bundle' folder). So can anybody explain the purpose of using separate 'Bundle' folder to store bundles under the Vendor folder.
Thanks

A:

If you take a look at How to use Best Practices for Structuring Bundles you can see, both methods are common. An extra Bundle in the namespace if mostly used for structuring if you have Components, Bridges or any other libraries under the same vendor name space. E.g. like symfony framework itself.


Q:

How can I rewrite a specific URL?

I want to rewrite the following urls:

node/add
node/edit
etc

To be something like
 - content/add
 - content/edit
I also use the prepopulation model, and would love to able to rewrite this URL:

node/add/single-gallery-image?edit[field_gallery_node_reference][0][nid]=48

To something like this:

content/add/image?n=48

Is this possible? If so, do I need some Drupal module for this, or will I have to take on the htaccess file?

A:

With the pathauto module you are able create aliases for your urls. You can setup a lot of rules and should be able to get quite far with it. I'm not certain how well it integrates with the prepopulation model. But the rest should be quite easy.


Q:

Undo/Redo implementation for an edit-control, based on stacks

I'm trying to implement a simple undo/redo mechanism (based on stacks) for some events of a textbox.
Before asking this, I've seen a lot of undo/redo implementations like these, but more or less they are incomplete and showing things that I already knew (on the other hand, the profesional way using rare interfaces scapes from my compehenssion, so I want to follow this stack-based way), because those examples more than a undo/redo example for edit-controls, are a push/pop examples for stacks, but a undo/redo is a little more than writting a method to pop the last item of a "undo stack" and another method to pop the last item of a "redo stack", because in some point while the user is interacting with the control, the stacks should be cleared/resetted.
I mean that in a real undo/redo mechanism for edit-controls, the "redo stack" should be cleared when the user undoes and the user makes a text modification in the control while the "undo stack" still contain items, so in that point there is nothing to redo because a change occured while undoing.
I didn't seen any complete example of a undo-redo mechanism in this way bearing in mind how must act the undo/redo stacks when changes occur in the control.
I need help to properlly implement the logic of my undo/redo stacks, I started trying it by my own for days with a couple of trial and erros, but always escapes me some detail, because when I get one (undo or redo)stack to work properly, the other one stops working as expected undoing what it should not undo or redoing what it should not redo,
so I discarded out (again) all the conditional logic that I written because my logic always is wrong, I should start from zero again with a proper conditional algorithm, I mean the proper conditionals to push or pop the stack items at the right moment.
Then, more than words or suggestions, I need a working code that can solve the problem with my algorithm, I need to complete the algorithm logic of the AddUndoRedoItem method in the code below, this is a specific question about this.
If I am missing a simpler solution following the same principles (a undo and redo stacks), I will accept that solution too.
In C# or Vb.Net, no matter.
PD:
If because my poor English I didin't explained some thing prroperly and you are not totally sure of what kind of undo/redo I'am asking for, just I'm asking for a undo/redo as it sounds, just test the Ctrl+Z(undo) and Ctrl+Y(redo) keys in the Notepad while performing changes in the text undone or redone, see how it acts, that is a real undo/redo implementation, what I'm trying to reproduce with the stacks.

This is the current code:
Public Enum UndoRedoCommand As Integer
    Undo
    Redo
End Enum

Public Enum UndoRedoTextBoxEvent As Integer
    TextChanged
End Enum

Public NotInheritable Class UndoRedoTextBox

    Private ReadOnly undoStack As Stack(Of KeyValuePair(Of UndoRedoTextBoxEvent, Object))
    Private ReadOnly redoStack As Stack(Of KeyValuePair(Of UndoRedoTextBoxEvent, Object))

    Private lastCommand As UndoRedoCommand
    Private lastText As String

    Public ReadOnly Property Control As TextBox
        Get
            Return Me.controlB
        End Get
    End Property
    Private WithEvents controlB As TextBox

    Public ReadOnly Property CanUndo As Boolean
        Get
            Return (Me.undoStack.Count <> 0)
        End Get
    End Property

    Public ReadOnly Property CanRedo As Boolean
        Get
            Return (Me.redoStack.Count <> 0)
        End Get
    End Property

    Public ReadOnly Property IsUndoing As Boolean
        Get
            Return Me.isUndoingB
        End Get
    End Property
    Private isUndoingB As Boolean

    Public ReadOnly Property IsRedoing As Boolean
        Get
            Return Me.isRedoingB
        End Get
    End Property
    Private isRedoingB As Boolean

    Public Sub New(ByVal tb As TextBox)

        Me.undoStack = New Stack(Of KeyValuePair(Of UndoRedoTextBoxEvent, Object))
        Me.redoStack = New Stack(Of KeyValuePair(Of UndoRedoTextBoxEvent, Object))

        Me.controlB = tb
        Me.lastText = tb.Text

    End Sub

    Public Sub Undo()

        If (Me.CanUndo) Then
            Me.InternalUndoRedo(UndoRedoCommand.Undo)
        End If

    End Sub

    Public Sub Redo()

        If (Me.CanRedo) Then
            Me.InternalUndoRedo(UndoRedoCommand.Redo)
        End If

    End Sub

    ' Undoes or redoues.
    Private Sub InternalUndoRedo(ByVal command As UndoRedoCommand)

        Dim undoRedoItem As KeyValuePair(Of UndoRedoTextBoxEvent, Object) = Nothing
        Dim undoRedoEvent As UndoRedoTextBoxEvent
        Dim undoRedoValue As Object = Nothing

        Select Case command

            Case UndoRedoCommand.Undo
                Me.isUndoingB = True
                undoRedoItem = Me.undoStack.Pop
                Me.AddUndoRedoItem(UndoRedoCommand.Redo, UndoRedoTextBoxEvent.TextChanged, Me.lastText, undoRedoItem.Value)

            Case UndoRedoCommand.Redo
                Me.isRedoingB = True
                undoRedoItem = Me.redoStack.Pop
                Me.AddUndoRedoItem(UndoRedoCommand.Undo, UndoRedoTextBoxEvent.TextChanged, undoRedoItem.Value, Me.lastText)

        End Select

        undoRedoEvent = undoRedoItem.Key
        undoRedoValue = undoRedoItem.Value

        Select Case undoRedoEvent

            Case UndoRedoTextBoxEvent.TextChanged
                Me.controlB.Text = CStr(undoRedoValue)

        End Select

        Me.isUndoingB = False
        Me.isRedoingB = False

    End Sub

    Private Sub AddUndoRedoItem(ByVal command As UndoRedoCommand, ByVal [event] As UndoRedoTextBoxEvent,
                                ByVal data As Object, ByVal lastData As Object)

        Console.WriteLine()
        Console.WriteLine("command     :" & command.ToString)
        Console.WriteLine("last command:" & lastCommand.ToString)
        Console.WriteLine("can undo    :" & Me.CanUndo)
        Console.WriteLine("can redo    :" & Me.CanRedo)
        Console.WriteLine("is undoing  :" & Me.isUndoingB)
        Console.WriteLine("is redoing  :" & Me.isRedoingB)
        Console.WriteLine("data        :" & data.ToString)
        Console.WriteLine("last data   :" & lastData.ToString)

        Dim undoRedoData As Object = Nothing
        Me.lastCommand = command

        Select Case command

            Case UndoRedoCommand.Undo

                If (Me.isUndoingB) Then
                    Exit Select
                End If

                undoRedoData = lastData
                Me.undoStack.Push(New KeyValuePair(Of UndoRedoTextBoxEvent, Object)([event], undoRedoData))

            Case UndoRedoCommand.Redo

                If (Me.isRedoingB) Then
                    Exit Select
                End If

                undoRedoData = lastData
                Me.redoStack.Push(New KeyValuePair(Of UndoRedoTextBoxEvent, Object)([event], undoRedoData))

        End Select

    End Sub

    Private Sub TextBox_TextChanged(ByVal sender As Object, ByVal e As EventArgs) _
    Handles controlB.TextChanged

        Dim currentText As String = Me.controlB.Text

        If Not String.Equals(Me.lastText, currentText, StringComparison.Ordinal) Then

            Select Case Me.lastCommand

                Case UndoRedoCommand.Undo

                    Me.AddUndoRedoItem(UndoRedoCommand.Undo, UndoRedoTextBoxEvent.TextChanged, currentText, Me.lastText)

                Case UndoRedoCommand.Redo
                    Me.AddUndoRedoItem(UndoRedoCommand.Redo, UndoRedoTextBoxEvent.TextChanged, Me.lastText, currentText)

            End Select

            Me.lastText = currentText

        End If

    End Sub

End Class

A:

Thanks to @Plutonix I solved it, I really didn't believe that a simple comment could help me to solve logic, but yes, I was making things more complicated than they really are.
I still need to think about how to manage disposable objects, but more or less the base of the idea is finished and the code below is working as expected (at least for what I expect).
These are the parts of the base undo/redo class for controls:
Public Enum UndoRedoCommand As Integer
    Undo
    Redo
End Enum

Public Class UndoRedoItem
    Public Property [Event] As Integer
    Public Property LastValue As Object
    Public Property CurrentValue As Object
End Class

Public MustInherit Class UndoRedo(Of T As Control)

#Region " Private Fields "

    Private ReadOnly undoStack As Stack(Of UndoRedoItem)
    Private ReadOnly redoStack As Stack(Of UndoRedoItem)

#End Region

#Region " Properties "

    Public ReadOnly Property Control As T
        Get
            Return Me.controlB
        End Get
    End Property
    Protected WithEvents controlB As T

    Public ReadOnly Property CanUndo As Boolean
        Get
            Return (Me.undoStack.Count <> 0)
        End Get
    End Property

    Public ReadOnly Property CanRedo As Boolean
        Get
            Return (Me.redoStack.Count <> 0)
        End Get
    End Property

    Public ReadOnly Property IsUndoing As Boolean
        Get
            Return Me.isUndoingB
        End Get
    End Property
    Private isUndoingB As Boolean

    Public ReadOnly Property IsRedoing As Boolean
        Get
            Return Me.isRedoingB
        End Get
    End Property
    Private isRedoingB As Boolean

#End Region

#Region " Constructors "

    Private Sub New()
    End Sub

    Public Sub New(ByVal ctrl As T)

        Me.undoStack = New Stack(Of UndoRedoItem)
        Me.redoStack = New Stack(Of UndoRedoItem)

        Me.controlB = ctrl

    End Sub

#End Region

#Region " Public Methods "

    Public Sub Undo()

        If (Me.CanUndo) Then
            Me.InternalUndoRedo(UndoRedoCommand.Undo)
        End If

    End Sub

    Public Sub Redo()

        If (Me.CanRedo) Then
            Me.InternalUndoRedo(UndoRedoCommand.Redo)
        End If

    End Sub

#End Region

#Region " Private Methods "

    Private Sub InternalUndoRedo(ByVal command As UndoRedoCommand)

        Dim undoRedoItem As UndoRedoItem = Nothing

        Select Case command

            Case UndoRedoCommand.Undo
                Me.isUndoingB = True
                undoRedoItem = Me.undoStack.Pop
                Me.AddUndoRedoItem(UndoRedoCommand.Redo, undoRedoItem.Event, undoRedoItem.LastValue, undoRedoItem.CurrentValue)

            Case UndoRedoCommand.Redo
                Me.isRedoingB = True
                undoRedoItem = Me.redoStack.Pop

        End Select

        Me.DoUndo(undoRedoItem.Event, undoRedoItem.CurrentValue)

        Me.isUndoingB = False
        Me.isRedoingB = False

    End Sub

    Protected MustOverride Sub DoUndo(ByVal [event] As Integer, ByVal data As Object)

    Protected Sub AddUndoRedoItem(ByVal command As UndoRedoCommand,
                                  ByVal [event] As Integer,
                                  ByVal currentData As Object,
                                  ByVal lastData As Object)

        Dim undoRedoItem As New UndoRedoItem
        undoRedoItem.Event = [event]

        Select Case command

            Case UndoRedoCommand.Undo

                If (Me.isUndoingB) Then
                    Exit Select
                End If

                If (Me.CanUndo) AndAlso (Me.CanRedo) AndAlso Not (Me.IsRedoing) Then
                    Me.redoStack.Clear()
                End If

                undoRedoItem.CurrentValue = lastData
                undoRedoItem.LastValue = currentData
                Me.undoStack.Push(undoRedoItem)

            Case UndoRedoCommand.Redo

                If (Me.isRedoingB) Then
                    Exit Select
                End If

                undoRedoItem.CurrentValue = currentData
                undoRedoItem.LastValue = lastData
                Me.redoStack.Push(undoRedoItem)

        End Select

    End Sub

#End Region

End Class

And this the implementation for a undo/redo on a textbox:
Public Enum UndoRedoTextBoxEvent As Integer

    TextChanged
    FontChanged
    BackColorChanged
    ForeColorChanged

End Enum

Public NotInheritable Class UndoRedoTextBox : Inherits UndoRedo(Of TextBox)

    Private lastText As String
    Private lastFont As Font
    Private lastBackColor As Color
    Private lastForeColor As Color

    Public Sub New(ByVal tb As TextBox)
        MyBase.New(tb)
    End Sub

    Protected Overrides Sub DoUndo([event] As Integer, data As Object)

        Select Case DirectCast([event], UndoRedoTextBoxEvent)

            Case UndoRedoTextBoxEvent.TextChanged
                MyBase.controlB.Text = CStr(data)

            Case UndoRedoTextBoxEvent.FontChanged
                MyBase.controlB.Font = DirectCast(data, Font)

            Case UndoRedoTextBoxEvent.BackColorChanged
                MyBase.controlB.BackColor = DirectCast(data, Color)

            Case UndoRedoTextBoxEvent.ForeColorChanged
                MyBase.controlB.ForeColor = DirectCast(data, Color)

        End Select

    End Sub

    Private Sub TextBox_TextChanged(ByVal sender As Object, ByVal e As EventArgs) _
    Handles controlB.TextChanged

        Dim currentText As String = MyBase.controlB.Text

        If Not String.Equals(Me.lastText, currentText, StringComparison.Ordinal) Then

            MyBase.AddUndoRedoItem(UndoRedoCommand.Undo, UndoRedoTextBoxEvent.TextChanged, currentText, Me.lastText)
            Me.lastText = currentText

        End If

    End Sub

    Private Sub TextBox_FontChanged(sender As Object, e As EventArgs) _
    Handles controlB.FontChanged

        Dim currentFont As Font = MyBase.controlB.Font

        If (Me.lastFont IsNot currentFont) Then
            MyBase.AddUndoRedoItem(UndoRedoCommand.Undo, UndoRedoTextBoxEvent.FontChanged, currentFont, Me.lastFont)
            Me.lastFont = currentFont
        End If

    End Sub

    Private Sub TextBox_BackColorChanged(sender As Object, e As EventArgs) _
    Handles controlB.BackColorChanged

        Dim currentBackColor As Color = MyBase.controlB.BackColor

        If (Me.lastBackColor <> currentBackColor) Then
            MyBase.AddUndoRedoItem(UndoRedoCommand.Undo, UndoRedoTextBoxEvent.BackColorChanged, currentBackColor, Me.lastBackColor)
            Me.lastBackColor = currentBackColor
        End If

    End Sub

    Private Sub TextBox_ForeColorChanged(sender As Object, e As EventArgs) _
    Handles controlB.ForeColorChanged

        Dim currentForeColor As Color = MyBase.controlB.ForeColor

        If (Me.lastForeColor <> currentForeColor) Then
            MyBase.AddUndoRedoItem(UndoRedoCommand.Undo, UndoRedoTextBoxEvent.ForeColorChanged, currentForeColor, Me.lastForeColor)
            Me.lastForeColor = currentForeColor
        End If

    End Sub

End Class


Q:

scala -> use .net (linq) and java code base in the same program?

Newbie here...can I write one program which incorporates .NET LINQ and also various Java frameworks in the same scala program? Or when I compile, at that time the decision is made either one or the other, .NET or Java
Thanks.

A:

When you compile scala you give it either -target:msil or -target:jvm-X.X (the default being java). This means that you could attempt to make something cross compilable (that would work  with both targets but must be compiled separately for each).
Attempting to host both frameworks at once with functions crossing the boundaries is, while technically possible, extremely hard and would require full support at both the compiler and runtime level.
Since scala operates on top one or the other runtime it is highly unlikely that this would ever work well or that anyone with the abilities to achieve it would bother. Also a variety of .Net types have no analogue in the jvm and vice versa.
Correctly and efficiently maintaining the GC roots across both runtimes in such a system would be a topic worthy of a PhD thesis in the abstract let alone implementing it.


Q:

How is the .data segment loaded into a seperate memory area than the .code segment in x86?

So I've been dabbling with assembly and have always wondered, how are the different segments loaded into different memory areas when loading the kernel. I am aware for user code in an OS the linker and the OS can simply put the code and data in whichever area they want, but this question is more specific to kernels, which don't have an OS to put the .code and .data into different areas.
Say I have a simple kernel:
.data
var dw 123

.code
mov eax ebx

How does the bootloader, or whatever handles this, actually load the Kernel code into a separate area to the data?
And say I have 5 different assembly files, all with .data segments, are the variables all loaded one after the other into the same area?

A:

It's up to the bootloader to handle this so it ultimately depends on what the bootloader does, but generally bootloaders are loading standard executable images in standard formats like PECOFF or ELF.  They load the kernel much like operating systems load program executables.
Sections exist so that the contents of sections with the same name will all be grouped together contiguously in the executable. The linker will take the contents of all the .text sections in all the input object files and combine them into one .text section in the output executable. Similarly it will do the same for .data and other named sections.
The linker takes all these combined sections and places them one after each other in the executable, creating one contiguous image that can be loaded into memory.  Under an operating system the executable would be loaded into memory in one single contiguous chunk.  If necessary, relocations would be applied to account for the executable being loaded at a different address than where it was intended to be loaded and uninitialized data segments (.bss) would be initialized with zeroes. Finally the permissions of each page of the executable in memory would be adjusted according to the segments they belong to.  For example, pages in .text sections would be marked read-only and executable, while in .data sections they would be marked read/write and not executable.
(Note that this simplifies and glosses over many details how linkers and operating systems create and load executables. It's possible for sections to be merged, renamed, discarded, etc. Padding space may be inserted between segments so that they're page aligned. Under ELF named sections in object files are actually converted unnamed program segments in executables and it's these program segments that determine page permissions.)
A bootloader loads a kernel executable much like an operating system, but may not support relocations, and won't change page permissions because those need an operating system to work. The kernel itself is responsible setting up its own page permissions.
So the kernel code and data gets loaded into one single contiguous area of memory, with that area of memory subdivided into separate areas for the code, data and any other sections the kernel uses.


Q:

How can I make product price dynamic on Magento page?

So I have a Magento Page with 3 products on it and the images/prices/product title are all hard coded. in HTML how can I make it so that the price is not hard coded and whenever the product price changes, the price will change on that page too for those 3 products? I say html because it's on a Magento page.

A:

I would ditch the hard-coding and use Magento's "Catalog Products List" widget. You can specify a bunch of criteria in the widget to show the products you want, e.g. from a certain category or - in your case - based on their IDs.
An overview to widgets is here, I'm not affiliated with this I just found it in Google:
https://www.humcommerce.com/tutorial/add-widgets-in-magento-2/
If your page needs a drastically different way of displaying the data, you could insert each product in its own widget and heavily customize the CSS as required.
If this is too generic then you'll be in the territory of writing your own block classes and rendering them with phtml templates within the page, which is a whole different ball game.


Q:

Using buttons in Listview row android

In my android application, I am using Listviewand each row of listview will have textview and play/pause button. Here I am displaying audio file in each list row.When user click play button, audio file will start and the icon of play button will be changed to pause .If i click same button again, it will stop that audio file and icon of pause button will be to play.
The problem is that if i am accessing the play button of 1st row and i click on play button of another row, then icon of 1st row should change.I don't know how to achieve this functionality. Please help me to solve this problem.
getView() method of customAdapter :
  public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        RowItem_ringtone rowItem = getItem(position);

        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.ringtone_row, null);
            holder = new ViewHolder();

            holder.txtTitle = (TextView) convertView
                    .findViewById(R.id.ringtoneTitle);
            holder.btnPlay = (ImageButton) convertView
                    .findViewById(R.id.btnPlay);
            holder.btnSet = (ImageButton) convertView.findViewById(R.id.btnSet);
            convertView.setTag(holder);
        } else
            holder = (ViewHolder) convertView.getTag();

        holder.txtTitle.setText(rowItem.getRingTitle());
        holder.btnPlay.setTag(rowItem.getRingId());
        holder.btnSet.setTag(rowItem.getRingId());

        holder.btnPlay.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Toast.makeText(getContext(), v.getTag().toString(),
                        Toast.LENGTH_LONG).show();
                if (CustomListViewAdapter_ringtone.mp != null) {
                    if (CustomListViewAdapter_ringtone.mp.isPlaying()) {
                        CustomListViewAdapter_ringtone.mp.stop();
                        CustomListViewAdapter_ringtone.mp.release();
                    }
                }
                mp = MediaPlayer.create(getContext(),
                        Integer.parseInt(v.getTag().toString()));
                mp.start();
                v.setBackgroundResource(R.drawable.set_icon);
                btnId = Integer.parseInt(v.getTag().toString());
            }
        });
return convertView;
    }

A:

On List view item click listener you are changing icon right? so there you get id for row also . So you can store that id in variable as currently playing row or file. And when you click on another row just check that id and change icon according to that.
Use like this
yourlistview.setOnItemClickListener(new OnItemClickListener()
{
    @Override public void onItemClick(AdapterView<?> arg0, View arg1,int position, long         arg3)
{
    Toast.makeText(SuggestionActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});

This sample code works for me:
View view = null;

 private OnItemClickListener onItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            if(view != null)
            {
                TextView count = (TextView) view.findViewById(R.id.downloadCount);
                count.setText("007");
            }
            view = arg1;

        }
    };


Q:

Fatal error: Call to undefined method PDO::select() in line 9

something strange has happened to my site. Everything was working perfect, and now i'm getting this error when i'm trying to log in:
Fatal error: Call to undefined method PDO::select() in line 9
Here is my code:
<?php
$db = new PDO('mysql:host=****;dbname=******;charset=utf8', '*****', '*****');

if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$myusername = $_POST['username'];
$mypassword = $_POST['password'];
$result = $db->select("SELECT userID FROM miembros WHERE user='$myusername' and  pass='$mypassword' AND confirm IS NULL");
$row = $result->fetch(PDO::FETCH_ASSOC);
$count = $result->rowCount();
// code continues
?>

What i am doing wrong at line 9 and $db?

A:

You want to use PDO::prepare to prepare a statement which you then execute
  $db = new PDO('mysql:host=****;dbname=******;charset=utf8', '*****', '*****');

  if($_SERVER["REQUEST_METHOD"] == "POST")
  {
    // username and password sent from Form
    $prepared = array(
      'username' => $_POST['username'],
      'password' => $_POST['password']);
    $stmt = $db->prepare("SELECT userID FROM miembros WHERE user=:username and  pass=:password AND confirm IS NULL");
    $result = $stmt->execute($prepared);
    $row = $result->fetch(PDO::FETCH_ASSOC);
    $count = $result->rowCount();
  }


Q:

Fattening of totally convex sets

Suppose $(M, g)$ is an open complete nonnegatively curved Riemannian manifold with $d$ its distance.
A totally convex set $C\subset M$ has the property that for any two point $x, y \in C$ any geodesic (not only the minimal ones) joining them must lie in $C$.
If $C$ is totally convex, the fattened set $C^a=\{x \in M \mid d(x,C)\leq a\}$ is still totally convex? Is it at least for small $a$?
This question is somehow related to question "Examples on small cut radius of totally convex set in non-negatively curved manifold", Examples on small cut radius of totally convex set in non-negatively curved manifold

A:

No. Consider a rotation-symmetric metric on $\mathbb R^2$ resembling a small spherical cap extented by a flat cone. A sufficiently short geodesic segment at the origin is totally convex in your sense. But a small neighborhood of such a  segment is not convex due to positive curvature.


Q:

How to center a ?

See my code at codepen
I'm trying to horizontally center the circle progress bar in the page, I tried setting margin: 0 auto; on the div, it didn't work. I, also, tried setting  text-align: center on the parent div and setting the div to display: inline-block, no success as well.
This is the element in the HTML I'm trying to center:

              50%

And this is the CSS I'm applying on the element:
.col-md-12{
  width: 100%;
}
.timer{
  width: 100%;
  margin: 0 auto;
}

A:

Edited Codepen
Remove float: left; or set it to none in .c100 css class.
.c100 {
    float:none;
}


Q:

How do I show a view of documents for the current user's department?

My first sharepoint task ever is to create a demo document management site, i need to define a way of departmentalising documents added to the store, then when a user logs in they only see documents by their department. How is best to do this, i don't know where to start.

A:

You could use different scenarios :

Apply security on a series of list depending on the AD Group they are in
Apply "By Item" security on a single list by adding an event handler by code, and with some logic, apply the good group to the item
Adding a column that would be the department, and filter the list by that column
Using this solution to edit the regular view http://social.technet.microsoft.com/Forums/en-US/sharepointadmin/thread/9dfce274-02d9-4232-80c0-8139a94e96ea/

There's a lot of options, it depends of your level of comfort with code and with the platform.


Q:

Error Must declare the scalar variable with Table Valued Parameter

I am not getting what I am doing wrong here. From the update segment, I am getting this error:

Must declare the scalar variable "@OrderTestTVP".

Here is my table-valued parameter type
CREATE TYPE [dbo].[TVP_OrderTest] AS TABLE(
    [OrderTestId] [int] NULL,
    [OrderId] [int] NOT NULL,
    [TestCode] [varchar](10) NOT NULL
    )
GO

ALTER PROCEDURE [dbo].[TVP_Save_OrderTest]
    @OrderTestTVP TVP_OrderTest READONLY
AS
BEGIN
    BEGIN TRY
        DECLARE @TableOfIdentities TABLE (IdentValue BIGINT, TestCode varchar(10) )
        INSERT INTO OrderTest
                (
                    OrderId
                    ,TestCode
                )
                OUTPUT Inserted.OrderTestId,inserted.TestCode
                INTO @TableOfIdentities(IdentValue,TestCode)
                   SELECT  OrderId
                    ,TestCode
            FROM @OrderTestTVP
            WHERE OrdertestID = 0

        UPDATE
                OrderTest
                SET
                    OrderId = @OrderTestTVP.OrderId,
                    TestCode = @OrderTestTVP.TestCode
                    FROM OrderTest INNER JOIN @OrderTestTVP
                  ON OrderTest.OrderTestId = @OrderTestTVP.OrderTestId

        SELECT * FROM @TableOfIdentities
    END TRY
    BEGIN CATCH
        exec error_catch
    END CATCH
END

A:

I'd say you have to use a table alias for the join operation:
UPDATE
 OrderTest
 SET
     OrderId = o.OrderId,
     TestCode = o.TestCode
 FROM OrderTest INNER JOIN @OrderTestTVP o
     ON OrderTest.OrderTestId = o.OrderTestId

I have no SQL at hand right now to try but if I recall correctly, table variables need aliases if used in expressions.


Q:

Can the marketing cloud login session be used for landing pages?

I'm looking to create a landing page that allows Marketing Cloud users to check various data sources (data views, data extensions, etc.) for a specific subscriber. I understand how to do all this, but my concern is privacy. Realistically no one on the internet will figure out how to access the page, but it's a concern nonetheless. Should it be?
If so, is there a Marketing Cloud session variable to use to check log in status on the landing page? Is it possible to force that log in before accessing the landing page?

A:

The option that Arvind referred to is called System Authenticated Redirection and more details about it can be found at:
http://help.exacttarget.com/en/documentation/exacttarget/content/microsites/landing_pages/
It sounds like it is exactly what you are looking for.  While the default URL generated for a landing page is a long GUID that someone is unlikely to accidentally discover, it is a good idea to implement this option to prevent access to a page if it exposed any information that you wouldn't want public.


Q:

m_pMainWnd is NULL in CWinApp, because InitInstance is not called

I'm trying to create a simple window using MFC, however the program terminates immediately and an output line from Debug seems strange:
d:\agent\_work\3\s\src\vctools\VC7Libs\Ship\ATLMFC\Src\MFC\appcore.cpp(783) : AppMsg - Warning: m_pMainWnd is NULL in CWinApp::Run - quitting application.

After further inspection, I realize that CMyFrame::InitInstance doesn't get called. I have had some experience related to MFC, because I have used Win32++ (aka Win32xx) in Code::Blocks. Now I'm trying out VS Community 2019 while using the official MFC framework, but I am not capable of creating a blank window. Here is the complete code:
//main.cpp
//Code taken from:
//www.tutorialspoint.com/mfc/mfc_windows_fundamentals.htm

#include <afxwin.h>
#include <iostream>

class CMyFrame : public CFrameWnd {
public:
    CMyFrame() {
        Create(NULL, _T("MFC Application Tutorial"));
    }
};

class CExample : public CWinApp {
public:
    CExample() { std::cout << "CExample Constructor\n"; }
    ~CExample() { std::cout << "CExample Destructor\n"; }

    virtual BOOL InitInstance() {
        std::cout << "CExample InitInstance\n";
        CMyFrame* Frame = new CMyFrame();
        m_pMainWnd = Frame; //<--

        Frame->ShowWindow(SW_NORMAL);
        Frame->UpdateWindow();

        return TRUE;
    }
};

CExample theApp;

int main() { return theApp.Run(); }

Console Output:
CExample Constructor
CExample Destructor

D:\Visual Studio Projects\Visual C++\MFC_Project\Debug\MFC_Project.exe (process 13012) exited with code 0.

Trying to manually call InitInstance in main triggers a runtime error. As long as I know, InitInstance should be called by MFC automatically.
Any help is appreciated, thanks :)

A:

Where did this source code come from? It does not appear to have been automatically generated by Visual Studio as it does not make sense.
MFC does not use main() nor does calling the run() method of CWinApp start up an MFC application.
See this documentation regarding the run() method which says that it starts the message pump. https://docs.microsoft.com/en-us/cpp/mfc/reference/cwinapp-class?view=vs-2019#run which means that your application is not doing any of the initialization needed to set up the environment so that the message pump can actually process messages correctly.

Run acquires and dispatches Windows messages until the application
  receives a WM_QUIT message. If the application's message queue
  currently contains no messages, Run calls OnIdle to perform idle-time
  processing. Incoming messages go to the PreTranslateMessage member
  function for special processing and then to the Windows function
  TranslateMessage for standard keyboard translation; finally, the
  DispatchMessage Windows function is called.
Run is rarely overridden, but you can override it to provide special
  behavior.

Allow Visual Studio to generate the proper skeleton for an MFC application which will create the necessary entry point for the application, link in all of the proper libraries, initialize the MFC runtime environment, and start the message pump to start handling the messages.


Q:

PHP - Include files without inhereting variables?

Is it possible to include (or, for my uses, run) another PHP file from within a PHP script without inheriting the variables set in the parent script? I know this is mostly possible to do by wrapping the include in a function, but that feels sloppy.
Is there a more elegant alternative?

A:

Unfortunately, at the time of this writing, it appears that wrapping what you want to include in a function or method is the only way to achieve this.


Q:

Tektronics 453 - Saving a single shot waveform for later analysis

I recently purchased a used analog Tektronix 453 and I want to capture some single shot transients. I also want to "save" the waveform so I can more easily measure things like peak to peak voltage of the transient. I know you can review saved one-shots in modern oscilloscopes but do analog scopes also support this useful feature?
In the manual, I see that single-shot trigger allows for "photographs" of the triggered waveform. However, after my trigger is activated, the waveform disappears. Changing the time/div or horizontal display doesn't show that any waveform is "saved". I am not sure how you would be able to photograph any transients since your window for taking the photograph would only be as long as your one-shot duration.
I would imagine analog memory to be much more expensive than digital memory but I don't  understand the usefulness of one-shot captures without the possibility for later analysis.

A:

Camera.  The word you are looking for is camera.
Tektronix made one for your scope, but good luck finding one these days.  You'll need even more luck (and maybe deep pockets) to get the needed instant film for the camera.
This is the camera Tektronix made for your scope:

Shameless plug
As an alternative, I can suggest the software I wrote to do similar tasks with my equally old Telequipment D43.
You'll need a web camera and an adapter for your scope.
Mine looks like this:

The software can capture one shot events, despite not having any electrical connection to the scope.
This image is a one shot capturing contact bounce on a switch:

You'll notice there are cursors on screen, and readouts below - you can make measurements like on a (somewhat) modern digital storage oscilloscope with the software.
You can also digitize the trace.  That only works for a single trace.  I use it to export data to other programs (like Baudline for spectrum analysis.)
I have a bunch of blog posts on it, and there's a Wiki for it on GitHub.
The software runs on Linux and Windows, and probably on Apple (if some one could try it out.)

As a final alternative, you could try the Fads to Obsessions webcam oscilloscope software.
It looks like this:

I tried to use it, but couldn't get it to run under Linux. (It is admittedly a Windows only program, but the Wine Windows emulator can some times work wonders - except this time.)
It's just as well that it didn't work.  My software runs real time - the Fads to Obsessions software seems to only take snapshots on demand.
It has a different set of features than my software.  Maybe it will suit you better.


Q:

How to design the database for a card game points counting app?

I would like to write an app for counting the points in a card game. Here's how the game works:

the game uses poker cards to play
There's no maximum number of players, but I will limit it to 8 so it's easier to design the database.
I'm not gonna go into how to play the game, but after each game, the winner is the player who has no cards left in his hand, every other player will have a point (number of cards left * a factor)
A match consists of a number of games. After a match, the player with the least points wins.

Here's my design of the app's database:
MATCH table:
- MatchID: primary key, integer
- Date:
- Player1: player name, varchar
- Player2: varchar
- Player3: varchar
- Player4: ..
- Player5: ..
- Player6: ..
- Player7: ..
- Player8: ..

POINTS table:
- MID: foreign key reference to MATCH.MatchID
- GameID: the ID of each game in a match, integer
- PID: should reference to Player 1-8
- Points: integer

An Example of the POINTS table (4 players):

| MID | GameID | PID | Points |
| 1   | 1      | 1   | 5      |
| 1   | 1      | 2   | 3      |
| 1   | 1      | 3   |  0      |
|  1   |  1      |  4   |  2      |
| 1   |   2     |  1   |   0     |
|  1   |    2    |   2  |    10    |
|   1  |   2     |  3   |   20     |
|   1  |   2     |  4   |   30     |
...

My questions are:

how can I reference the POINTS.PID to Player 1-8 in the MATCH table? I was thinking matching the number of PID with the column name Player#, but it doesn't sound like a proper solution.

is there a better way to design this database?

if there's no limit on the number of players, how should I design this database?

Thank you in advance!

A:

Unless the number of players is low (like 2) and you are certain that it is fixed for all time, you probably do not want to represent players as columns in your MATCH table.  Rather, you should have a separate MATCH_PLAYERS table to indicate the players in the match:
MATCH table:(MatchID,  MatchDate)

MATCH_PLAYERS table:(MatchID, PlayerID, PlayerName)

Where {MatchID, PlayerID} is the primary key of the MATCH_PLAYERS table.
This should answer most of your questions/problems.


Q:

What options besides using $_SESSION

I am working on a .net project that relies on pulling some information from a database upon login and persisting the information while the person is logged in.
The site is complex, but I feel that overuse of the Session variable may be occurring. I will right now say that I'm using session to store about 5 int values and 3 or 4 string values. I don't have any complex objects stored in it.  Every page of my site utilizes these values multiple times, and I feel that posting them each time would be ridiculous.  I don't think that viewstate is any better than session at this point either, but i'm open to suggestions.
Example current usage of Session variable
this.Session["vendorCategoryId"]
this.Session["ftp_directory_name"]
this.Session["VendorCodeOptionRefId"]

I thought about implementing a struct in a class and having a set method there that I use from Global.asax.cs in the Session_Start() event might be one solution...
(EDIT: This solution is designed to avoid having to hammer the db every time any piece of code wants to access the variables).
In VendorSessionData.cs class
    public struct VendorData
    {
        public int VendorCategoryId;

        public int NKIAccountingCode;

        public int OptionCodeRefId;

        public string FtpDirName;
    }

    /// <summary>
    ///   The set vendor session data.
    /// </summary>
    public class VendorSessionData
    {
        #region Public Methods

        public static VendorData GetVendorData(Guid vendorGuid)
        {
            VendorData retVal = new VendorData();

            using (NKIDBDataContext db = new NKIDBDataContext())
            {

                vendorInfo vendorRefs = (from vendorInfo in db.vendorInfos where vendorInfo.guid == vendorGuid.ToString() select vendorInfo).SingleOrDefault();
                if (vendorRefs != null)
                {
                    retVal.VendorCategoryId = vendorRefs.category_id;
                    retVal.NKIAccountingCode = vendorRefs.nki_vendor_id;
                    retVal.OptionCodeRefId = vendorRefs.option_ref_id;
                    retVal.FtpDirName = vendorRefs.ftp_directory_name;
                }

            }

            return retVal;
        } ......

And in global.asax.cs
 public class Global : HttpApplication
        {

            public static VendorData CurrentVendorData;

            public void Session_Start(object sender, EventArgs e)
            {
/////////////////FYI tmpVendorGuid is set in code above this point
                 Guid tmpVendorGuid;
                 if (Guid.TryParse(vendorGuid, out tmpVendorGuid))
                 {
                     CurrentVendorData = VendorSessionData.GetVendorData(tmpVendorGuid);
                 }

Would it be better to try to attack this using hidden fields on the master page? Every search I've done says "don't use session, don't use globals.." basically any idea I have, there is some page stating its the worst idea ever :)
Any suggestions would be appreciated.

A:

The amount of data isn't particularly surprising, but the choice is.
Normally a session would store user information (typically just their ID - you fetch the rest from the DB). "ftp_directory_name" sounds like a config variable or a per-user setting.
I'm surprised you don't store VendorData in the database with a unique ID and then just fetch the details (you'd need to store the Vendor ID in the session - if that's not the same as the User).

This solution is designed to avoid having to hammer the db every time any piece of code wants to access the variables

This seems like it might be a solution to a problem that doesn't exist - are you seeing problems with access time and are you sure this is the right solution? You're going to have to hit the DB for most pages anyway. One extra query per page load is unlikely to be a problem.


Q:

Rpi 3 B enable gpio pin using assembly

I'm trying to enable a GPIO pin on raspberry pi 3 B using assembly. I tried to do the same on raspberry pi 1 and it worked, also it worked when I used raspbian command to enable it and then I tried interpreting the Rpi 1 code to Rpi 3 B but it wouldn't work. here is my code
.section ".text.boot"

.global _start

_start:
    ldr X0,=0x3F200000
    mov X1,#1
    lsl X1,X1,#12
    str X1,[X0,#4]
    mov X1,#1
    lsl X1,X1,#14
    str X1,[X0,#40]
1:  wfe
    b       1b

Also should the kernel image be named 'kernel8.img'
N.B. I'm trying to enable pin 14 with this code

A:

What I was trying is basically debug an assembly code so I needed to know when does the code stop compilation which will be possible if I point it out with an external led using a gpio pin. I fixed my code and now its working correctly.
.section ".text.boot"

.global _start

_start:
    ldr X0,=0x3F200000
    mov W1,#1
    lsl W1,W1,#12
    str W1,[X0,#4]
    mov W1,#1
    lsl W1,W1,#14
    str W1,[X0,#28]
1:  wfe
    b       1b

I simply set the 3 bits that control pin 14 to 001 which are bit 12,13 and 14 and then enabled pin 14 by putting 1 in it and after that I just sent on which is 28 + the base address, (I looked up the manual for that). Hope that helps


Q:

Is it necessary to watch "The X-Files" Movie before Season 6?

I have watched seasons 1-5 of the X-Files.  In the first episode of season 6, the intro shows scenes from the end of season 5 and what I guess is "The X-Files" movie.
Do I need to watch the movie before season 6 for it to make sense?

A:

I don't want to give away the reasons why as it would include spoilers, but yes you should watch the movie before watching Season 6 as there is continuity from the movie into Season 6.
Hopefully this is not too much of a spoiler but I'll block it out just in case you want to avoid it all together.

 The movie shows a characteristic of the black oil that explains where greys come from, and the main "creature" from the movie shows up in the first episode of Season 6.


Q:

numpy.argsort is giving me strange unordered ints instead of sorted floats

I have two arrays of the same size and am multiplying one column by another to an output array using
array3=[]
for x in range(0,array1,shape[0]):
    array3.append(array1[x,5]/array2[x,5])
array_stack=np.hstack(array3).tolist()
array_sort=np.argsort(array_stack)

array_stack gives me a list of size 410 of float values between 1
and 2 which is what I want (1.2,1.5, etc.)  array_sort gives me a
list/array? of size (410,) of ints with values like 402, 75,
etc. (nothing like the floats it should be sorting and also not in any
sorted order)
I've tried replacing np.argsort with .sort() and get the same
output issues
Thoughts?

A:

np.argsort documentation states that the function

Returns the indices that would sort an array.

Hence what you see  means that the smallest element of array_stack is array_stack[402], the second smallest is array_stack[75] etc.


Q:

Getting selector name from json in Angular 2

I want a dynamic form. In which element details will come from json.
I have a json like this :
{
"FormElements": [
    {
        "selectorName": "text-input",
        "id": "",
        "class": "location",
        "name": "simpletext",
        "placeholder": "Enter your text here",
        "label": ""
    },
    {
        "selectorName": "radio-button",
        "id": "radio",
        "class": "",
        "name": "radio-name",
        "placeholder": "",
        "label": "Push this"
    }]
}

and My component template is something like:
<form>
    <div *ngFor="let fe of data.FormElements">
        <{{fe.selectorName}} idName="{{fe.id}}" className="{{fe.class}}" nameText="{{fe.name}}" placeholderText="{{fe.placeholder}}" labelName="{{fe.labell}}"></{{fe.selectorName}}>
    </div>
</form>

But this is giving an error :
Unexpected closing tag "{{fe.elementName}}" ("{{fe.class}}" nameText="{{fe.name}}" placeholderText="{{fe.placeholder}}" labelName="{{fe.labell}}">[ERROR ->]</{{fe.elementName}}>

Please Help. Thanks!

A:

You can't just use dynamic values for tag names like that, what I suggest you do is use ngSwitch like this
<form>
    <div *ngFor="let fe of data.FormElements">
        <div [ngSwitch]="fe.selectorName">
            <div *ngSwitchCase="'text-input'">
                <text-input idName="{{fe.id}}" className="{{fe.class}}" nameText="{{fe.name}}" placeholderText="{{fe.placeholder}}" labelName="{{fe.label}}"></text-input>
            </div>

            <div *ngSwitchCase="'radio-button'">
                <radio-button idName="{{fe.id}}" className="{{fe.class}}" nameText="{{fe.name}}" placeholderText="{{fe.placeholder}}" labelName="{{fe.label}}"></radio-button>
            </div>
        </div>
    </div>
</form>


Q:

Where to find I bit and how to edit it to enable interrupts in ARM Cortex-M4

In ARM Cortex-M4F MCU (TM4C1294NCPDT specifically), to deal with interrupts (GPIO interrupts), one of the steps to get the interrupts working is to clear the I BIT.
I searched a lot but I couldn't find any useful information about that, could anybody please tell me where to find that bit exactly and how to edit it if I need some special procedures?
And that will be great if I have been told where to find that information exactly after the explanation please (to learn how to answer myself on any other questions).

A:

The CMSIS provides a standard cross-vendor software interface to Cortex-M based devices.  The CMSIS defines a number of functions for interacting with the NVIC and PRIMASK including the intrinsics __disable_irq()/__enable_irq()

A:

OK, the easiest answer for my question is:
To use " CPSID I" or " CPSIE I" inline assembly code which will set or clear the PRIMASK (I) Bit respectively. (of course that will work just in privileged mode).
And both assembly instructions are equivalent to __disable_irq() and __enable_irq() functions in CMSIS respectively.


Q:

Simplify dictionary in python from a Firestore Trigger Event

I'm reading data from an Update Cloud Firestore Trigger. The event is a dictionary that contains the data whithin the key ['value']['fields']. However, each of the keys contains s nested dictionary containing a key like 'integerValue', 'booleanValue' or 'stringValue', where the value of integerValue is actually a string. Is there a method to remove the 'type pointers'?
How can I convert this:
{
    'fields': {
        'count': {
            'integerValue': '0'
        },
        'verified': {
            'booleanValue': False
        },
        'user': {
            'stringValue': 'Matt'
        }
    }
}

To this:
{
    'count': 0,
    'verified': False,
    'user': 'Matt',
}

A:

You can create a mapping of the known types and convert the values that way:
types = {
    'integerValue': int,
    'booleanValue': bool,
    'stringValue': str,
}

You can replace a nested dictionary like the one you have through the magic of dict.popitem:
replacement = {}
for key, meta in event['value']['fields'].items():
    typ, value = meta.popitem()
    replacement[key] = types[typ](value)
event['value'] = replacement

You can reduce it to a one liner with a dictionary comprehension:
event['value'] = {k: types[t](v) for k t, v in (k, *d.popitem()) for k, d in event['value']['fields'].items())}


Q:

I want to ask about session in jsp

index.jsp
<form action="a.jsp" method="post">
    <input type="text" name="a">
    <input type="radio" name="b" value="admin">admin <input type="radio" name="b" value="member">member
    <input type="submit" value="c">
</form>

a.jsp
<% String a=request.getParameter("a"); String b=request.getParameter("b");

session.setAttribute("a",a); session.setAttribute("b",b);

response.sendRedirect("b.jsp"); %>

b.jsp
<%
String b = (String)session.getAttribute("b");
if(b!="")
{
    if(b.equals("admin"))
    {
        out.print(session.getAttribute("a"));
        out.print("this is admin");
    }
    else if(b.equals("member"))
    {
        out.print(session.getAttribute("a"));
        out.print("this is member");
    }
}
else
{
    out.print(session.getAttribute("a"));
    out.print("this is guest");
}

%>
<form action="d.jsp" method="post">
    <input type="submit" value="d" />
</form>

d.jsp
<%
session.invalidate();
response.sendRedirect("index.jsp");
%>

The code is working fine, but if I don't choose the admin or member value, it should ideally go to guest condition in b.jsp page, but what I'm getting is an error at line 5.
error
An exception occurred processing JSP page /c/b.jsp at line 5
2: String b = (String)session.getAttribute("b");
3: if(b!="")
4: {
5:  if(b.equals("admin"))
6:  {
7:      out.print(session.getAttribute("a"));
8:      out.print("this is admin");

A:

In b.jsp it appears that you are attempting to check the session map for an entry whose key is b, and then to decide what type of user is viewing the page based on that value.
The problematical code is the second line of the scriptlet in b.jsp:
if (b!="")
{

When there is no entry for b in the session map, this comparison should be true, causing the code which checks for admin or member to be executed.  This in turn will result in b being dereferenced in comparisons like b.equals("admin"), which will result in a NullPointerException.  Your intention I believe is to check whether there is any entry for b in the session map.  If no entry be found, then you will treat the user as a guest.  If there is no entry in the session for the key b then null will be returned, not empty string.  So you should be checking for null:
if (b != null)
{

Or, if you wanted to also treat an empty string value as being a guest, then you could try:
if (b != null && !b.equals(""))
{


Q:

New to assembly, is there such thing as "generic assembly code"?

I'm new to assembly (much more used to working with C#), but I've decided to see if I can learn it and get more of an idea of what my computer does under the hood.
My question is, when programming on Windows, do I have to use the win32 libraries? For example, if I want to output, say, "A" in a console window, is there a "generic" way to do it, or do I have to call win32? Or am I completely off on how it works?

A:

You don't have to use Win32 unless you need something that Win32 does. I don't believe there is any level more primitive than Win32 for doing things like outputting to the console, for instance.


Q:

SQL Server 2012: Limit the maximum number of rows for count(*) query

Is there any way to limit the maximum value for count(*), so it stops counting rows after it found N rows?
I tried both SET ROWCOUNT N and TOP N, but they are ignored when I use SELECT count(*) FROM MyTable.

A:

SELECT Count(*)
FROM (
   SELECT TOP(@MaxRowCount) *
   FROM MyTable
) as q

I think your WITH solution might not be performant because it has to iterate each row to assign ROW_NUMBER(). I believe the solution here will perform better.