text:
Q: Using UITableView without a storyboard I'm trying to set a tableView as a subview in my viewController. But without using the storyboard! I'm trying this code, but it doesn't seem to work and I can't understand why..
So this is the code in which the tableview should be created:
func TableView(position: CGRect, allRecipes: [Recipe]) -> UITableView {
    let tableView: UITableView = UITableViewForAllRecipes(style: UITableViewStyle.Plain).tableView

    return tableView;
}

.
and this is my tableviewcontroller (UITableViewForAllRecipes)
class UITableViewForAllRecipes: UITableViewController {

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

    cell.textLabel.text = "ok"

    return cell
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    println("nosit")
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    println("tv")
    return 3
}

}
Does anyone see what I'm doing wrong? As it doesn't even seem to print those "nosit" and "tv", so It doesn't reach that code.. I didn't get anything out of debugging also..

A: How you implement your view controller which has a table view added to its view hierarchy  depends on whether you need a separate view controller to manage the table view.
If you do require a separate view controller, then
class UITableViewForAllRecipes: UITableViewController {

        override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
                var cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

                cell.textLabel.text = "ok"

                return cell
        }

        override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
                println("nosit")
                return 1
        }

        override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                println("tv")
                return 3
        }
}

class ViewController: UIViewController {
        let childTableViewController = UITableViewForAllRecipes(style: .Plain)
        let otherView = UIView()

        override func viewDidLoad() {
                super.viewDidLoad()

                // TODO: setup otherView's frame, autoresizingMask ...

                view.addSubview(otherView)

                addChildViewController(childTableViewController)

                let tableView = childTableViewController.tableView

                // TODO: setup tableView's frame, autoresizingMask ...

                view.addSubview(tableView)

                childTableViewController.didMoveToParentViewController(self)
        }
}

otherwise
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
        let tableView = UITableView()
        let otherView = UIView()

        override func viewDidLoad() {
                super.viewDidLoad()

                // TODO: setup otherView's frame, autoresizingMask ...

                view.addSubview(otherView)

                // TODO: setup tableView's frame, autoresizingMask ...

                tableView.dataSource = self
                tableView.delegate = self

                view.addSubview(tableView)
        }

        // MARK: - UITableViewControllerDataSource

        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
                var cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

                cell.textLabel.text = "ok"

                return cell
        }

        func numberOfSectionsInTableView(tableView: UITableView) -> Int {
                println("nosit")
                return 1
        }

        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                println("tv")
                return 3
        }
}

A: @Swipesight is right. The reason why you see an empty tableview:

*

*You create an instance of UITableViewForAllRecipes, the tableview controller holds a tableview and itself as that tableview's datasource and delegate.

*Then you grab the tableview, add it as a subview, but since tableview holds its delegate as weak reference, when you quit the TableView() func, the tableviewcontroller itself is released, since no more strong ref.

*When the tableview being rendered, it asks its datasource, which is nil and you get an empty table view.

Possible fix:

Hold a strong ref to your tableviewcontroller in your parent view controller

e.g
func TableViewController(position: CGRect, allRecipes: [Recipe]) -> UITableViewForAllRecipes {
    return UITableViewForAllRecipes(style: UITableViewStyle.Plain)
}

add a property in your parent view controller
var tableViewController: UITableViewForAllRecipes?

Then in your function where you call TableView
self.tableViewController = self.TableViewController(xxxx)
self.view.addSubview(self.tableViewController!.tableView)


text:
Q: Update to Xcode 12: Cannot convert value of type 'DataRequest' to closure result type 'Void' I am using AlamoFire and PromiseKit to do API calls.
The code was working fine for 2 years until I updated to Xcode 12.0.
Function now returning the error: "Cannot convert value of type 'DataRequest' to closure result type 'Void'"
My function is as follows:
   func fetchArticlesFromApi (API: String) -> Promise<[Article]> {
    return Promise<[Article]> { seal in
        return Alamofire.request(API).validate().responseString(completionHandler: { //Error happening here
            response in
            switch (response.result) {
            case .success(let responseString1):
                //Do something
            case .failure(let error):
                print (error)
                seal.reject(error)
            }
        })
    }
}

Error happening in third line of function
Any thoughts what might have changed in this update?
Note: The code works fine when i run the same code on xcode 11.6!

A: I found the answer for that on Github.
https://github.com/mxcl/PromiseKit/issues/1165
I shouldn't be trying to return anything from the closure passed to Promise.init.
Weird how that was working in previous versions of Xcode.
To fix that I have to replace the return in front of Alamofire.request... with _ =
The function now looks like this:
    func fetchArticlesFromApi (API: String) -> Promise<[Article]> {
    return Promise<[Article]> { seal in
        _ = AF.request(API).validate().responseString(completionHandler: {
            response in
            switch (response.result) {
            case .success(let responseString1):
            //Do something
            case .failure(let error):
                print (error)
                seal.reject(error)
            }
        })
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Zend Framework : Need All parameters for application.ini I want to know all the parameters/options which can be used in application.ini file. Is there any list available?
Please help

A: You can specify anything you want. For instance, I set my javascript files there:
js.jquery.filename = "/js/jquery.min.js"
js.jquery.offset = 0
js.jqueryui.filename = "/js/jquery-ui.min.js"
js.jqueryui.offset = 1
js.nestedsortable.filename = '/js/jquery.ui.nestedSortable.js'
js.nestedsortable.offset = 2
js.ckeditor.filename = "/js/ckeditor/ckeditor.js"
js.ckeditor.offset = 3

Now, whenever I need to add a javascript file, I do:
$config = Zend_Registry::get('config');
$js = $config['js'];
$this->view->headScript()->offsetSetFile($js['ckeditor']['offset'],$js['ckeditor']['filename']);
$this->view->headScript()->offsetSetFile($js['jquery']['offset'],$js['jquery']['filename']);

Like I said, you can specify any value. Anything you will be accessing often and need to be available globally can and perhaps should be there :).

A: During loading config in index.php you can store it in Zend_Registry and you can access them when you want.
You can also parse Zend_Config to an array and look, what is inside.

A: @Future King Do this:
$config = Zend_Registry::get('config');
Zend_Debug::dump($config);

That should do it. Let me know if it helps.


text:
Q: WP7 Binding to Local Variable I have a UI element whose color I'd like to set based on a local variable in the page (well actually in a module, but I can move it to the page).
I see in WPF one can bind a UI element to a local variable by making the variable a property and setting the binding RelativeSource to the parent class using FindAncestor:
WPF Binding to local variable
Unfortunately Silverlight doesn't seem to support FindAncestor mode.
Any possible solution, or do I have to create an instance of a custom class and such just for this one variable?

A: Ive been jumping from Silverlight to WPF a lot over the last few weeks, so the following idea may or may not fly.
Does your page have the name property set on it? If not, set it (x:Name="MyPage").
then you can do:
Fill="{Binding ElementName=MyPage, Path=MyProperty}"

Give that a try (just off the top of my head)


text:
Q: External Resource links used multiple times on a web page ,does it cause round trips? When a browser encounters a reference to a external javascript on a "single" html page multiple times then would it reload the .js file multiple time/cause a round trip to the server or does the browser automatically detect that the previous url was downloaded and not make a request again to the server?.
Would this be irrespective of the Cache header of the file?
What is the behaviour by default across all the spectrum of web browsers, and how does it apply for external css links?


text:
Q: Electron + Angular 6 blank screen on production application I have a problem with production build of Electron application with Angular 6. ng build --prod for Angular works fine. When I run the development version of my app by running an electron . command everything works fine and I able to use my application.
For build production application I'm using electron-builder, there is my command:
electron-builder build -w --x64
The application gets created without any problems by this command, but when I want to start the application .exe I'm getting the blank white screen, like on the image. DevTools are clean. What I'm doing wrong?
blank screen on application
There is a folder structure:
structure
There is package.json:
{
  "name": "simple-password-manager",
  "version": "1.0.0",
  "main": "main.js",
  "build": {
    "directories": {
      "buildResources": "dist",
      "output": "app"
    }
  },
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "electron": "electron .",
    "electron-build": "ng build --prod && electron ."
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^7.1.2",
    "@angular/cdk": "^7.1.1",
    "@angular/common": "~7.1.0",
    "@angular/compiler": "~7.1.0",
    "@angular/core": "~7.1.0",
    "@angular/forms": "~7.1.0",
    "@angular/material": "^7.1.1",
    "@angular/platform-browser": "~7.1.0",
    "@angular/platform-browser-dynamic": "~7.1.0",
    "@angular/router": "~7.1.0",
    "core-js": "^2.5.4",
    "generate-password": "^1.4.1",
    "reset-css": "^4.0.1",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.11.0",
    "@angular/cli": "~7.1.0",
    "@angular/compiler-cli": "~7.1.0",
    "@angular/language-service": "~7.1.0",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.5.0",
    "cross-env": "^5.2.0",
    "electron": "^3.0.10",
    "electron-builder": "^20.38.3",
    "electron-log": "^2.2.17",
    "electron-packager": "^13.0.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.1.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.1.6"
  }
}

This is main.js file:
const { app, BrowserWindow, Tray, Menu } = require('electron');
const url = require('url');
const path = require('path');

let window;
let trayContextMenu;
let appIcon;
const iconPath = path.join(__dirname, 'dist/assets/images/key.png');

function createContextMenu() {
  trayContextMenu = Menu.buildFromTemplate([
    { label: 'Show App',
      click: () => {
        window.show();
      }},
    { label: 'Quit',
      click: () => {
        app.isQuiting = true;
        app.quit();
      }
    }
  ]);
}

function createWindow() {
  window = new BrowserWindow({
    width: 1280,
    height: 768,
    icon: iconPath,
    autoHideMenuBar: true,
    webPreferences: {
      nodeIntegration: false,
      devTools: true,
      webSecurity: false,
    },
  });
  // window.webContents.openDevTools();
}

function contextMenuInit() {
  appIcon = new Tray(iconPath);
  appIcon.setContextMenu(trayContextMenu);
}

function windowLoad() {
  window.loadURL(url.format({
    pathname: path.join(__dirname, 'dist/index.html'),
    protocol: 'file',
    slashes: true,
  }));
}

function watchWindowEvents() {
  window.on('minimize', (event) => {
    event.preventDefault();
    window.hide();
  });

  window.on('close', (event) => {
    if(!app.isQuiting){
      event.preventDefault();
      window.hide();
    }
    return false;
  });

  window.on('closed', () => {
    window = null;
  });

  window.on('show', () => {
    appIcon.setHighlightMode('always');
  });
}

function init() {
  // createContextMenu();
  createWindow();
  // contextMenuInit();
  windowLoad();
  watchWindowEvents();
}

// Create window on electron intialization
app.on('ready', init);

// Quit when all windows are closed.
app.on('window-all-closed', () => {

  // On macOS specific close process
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // macOS specific close process
  if (window === null) {
    init();
  }
});

A: I had the same error with an Angular 7 application. The thing is, Angular is putting the application not directly under dist. Instead, it creates a subdirectory.
Changing the build variable in package.json to this, resolved the problem for me:
  "build": {
    "appId": "de.ubweb.okapi",
    "files": [
      "dist/okapi-electron/**/*",
      "node_modules/**/*",
      "package.json",
      "main.js"
    ]
  },

Make sure that the main.js is also adjusted accordingly.
win.loadURL(`file://${__dirname}/dist/okapi-electron/index.html`);


text:
Q: How to get started with drawing this flow chart in TikZ? I have some old drawings prepared in Word which I would like to translate into TikZ. Being a complete novice and having never worked with TikZ before, I am really struggling with getting started.
Here is the first flow chart that I want to convert:

One solution that appealed to me due to its simplicity was using a matrix and chains as explained in a tutorial in the manual. But then I already run into trouble with the two arrows that have to point to boxes 1, 2, and 3.
So my question boils down to: What is the easiest way to convert this chart into TikZ?
 Don't worry I'm not asking for code. I just want to know how to start, because finding your way in something as complex as TikZ, with an 800 page manual!, can be very frustrating for a beginner.

Update Oct 17, 2011
Getting the hang of it! Here is the output I can currently produce. Last question:
Any ideas how to align the arrows by their tips?
\documentclass[ngerman]{scrartcl}

\usepackage{ucs}
\usepackage[utf8x]{inputenc}
\usepackage{tikz}
\usetikzlibrary{shapes,arrows,positioning,calc}

\begin{document}

\tikzstyle{block} = [rectangle, fill=blue!20, minimum height=3em, minimum width=6em] \tikzstyle{arrow} = [single arrow, draw]

\begin{tikzpicture}[auto, node distance=0.5cm and 0.5cm, arr/.style={->,thick}, line/.style={thick}, font=\footnotesize]

\node (stoffVor) [block] {Box 1 text};
\node (haupt) [block, right=of stoffVor, align=center] {Box 2 text};
\node (stoffNach) [block, right=of haupt] {Box 3 text};
\node (pfeil1) [arrow, below left=of stoffVor] {Arrow 1};
\node (pfeil2) [arrow, below=of pfeil1] {Arrow 2 text};
\node (pfeil0) [arrow, left=of stoffVor] {Arrow 3 longer text};
\node (neben) [arrow, below right=of stoffNach, label=below:, yshift=0.5cm, xshift=1cm] {Text};
\node (hauptP) [arrow, above right=of stoffNach, label=above:,yshift=-0.5cm,xshift=1cm] {Text};
\node (pfeil3) [arrow, above=of hauptP] {Text};
\node (pfeil4) [arrow, above=of pfeil3] {Lorem, Ipsum, Dolor, Sit};

\draw[arr] (pfeil0.east) -- (stoffVor.west);
\draw[arr] (stoffVor.east) -- (haupt.west);
\draw[arr] (haupt.east) -- (stoffNach.west);
\draw[arr] (stoffNach.north) --  ++(0,0.5) node [auto, swap, yshift=6] {Text} -| ($ (stoffVor.east) + (0.25,0) $);
\draw[arr] (pfeil1.east) -| (stoffVor.240);
\draw[arr] (pfeil1.east) -| (haupt.240);
\draw[arr] (pfeil1.east) -| (stoffNach.240);
\draw[arr] (pfeil2.east) -| (stoffVor.300);
\draw[arr] (pfeil2.east) -| (haupt.300);
\draw[arr] (pfeil2.east) -| (stoffNach.300);
\draw[line] (haupt.150) |-  (pfeil4.west);
\draw[line] (haupt.30) |-  (pfeil3.west);
\draw[line] (stoffNach.350) -- ++ (0.25,0) -- ++ (0,-0.1) |- (neben.west);
\draw[line] (stoffNach.10) -- ++ (0.25,0) -- ++ (0, +0.1) |- (hauptP.west);

\end{tikzpicture}

\end{document}

A: One way to go - according to this answer - would be to save your diagram as a PDF file (this preserves the programmatic information on how to draw the figures), get Inkscape (free), import into Inkscape (don't worry if it takes awhile until it's done) and then using this plug-in, convert to TikZ. I have tried it, it should work well. Good luck! :)

A: The boxes could be nodes, something like
\node (box1) at (0,2) [rectangle,draw=black,fill=blue!20!white] {Box 1};

Notice the (box1), thats the name of that node, you can use it for easily drawing arrows:
\draw[->] (box1.east) -- (box2.west);

For the arrows with kinks, you can use the ++(x,y) coordinate notation, which means 'from the last position, go x right and y up, then make this the new position':
\draw[->] (box1.north) -- ++(0,1) -- ++(4,0) -- (box2.north);

Hope this helps getting started :)

Edit 1: You really learn TikZ by doing. I was wondering how to draw the double arrows entering the boxes on the south side. You could use the fact that you can specify any angle at which the arrows leave/enter:
\draw[->] (box1.300) -- ++(0,-0.5) -- ++(4,0) -- (box2.240);
\draw[->] (box1.240) -- ++(0,-1.0) -- ++(4,0) -- (box2.300);

However, the distance between entry and exit point is no longer 4. So it would be nice to specify 1cm below box2.240 which you can do with the calc library:
\coordinate (A) at ($ (box2.240) + (0,-0.5) $);
\coordinate (B) at ($ (box2.300) + (0,-1.0) $);
\draw[->] (box1.300) -- ++(0,-0.5) -- (A) -- (box2.240);
\draw[->] (box1.240) -- ++(0,-1.0) -- (B) -- (box2.300);

This should cover most things needed for your chart. Here a little example and a picture:
\documentclass[parskip]{scrartcl}
\usepackage[margin=15mm]{geometry}
\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}

\begin{tikzpicture}
\node (box1) at (0,0) [rectangle,draw=black,fill=blue!20!white] {Box 1};
\node (box2) at  (4,0) [rectangle,draw=black,fill=blue!20!white] {Box 2};
\draw[->] (box1.east) -- (box2.west);
\draw[->] (box1.north) -- ++(0,1) -- ++(4,0) -- (box2.north);
\coordinate (A) at ($ (box2.240) + (0,-0.5) $);
\coordinate (B) at ($ (box2.300) + (0,-1.0) $);
\draw[->] (box1.300) -- ++(0,-0.5) -- (A) -- (box2.240);
\draw[->] (box1.240) -- ++(0,-1.0) -- (B) -- (box2.300);
\end{tikzpicture}

\end{document}

Edit 2: A nice, calc free version by percusse:
\begin{tikzpicture}
 \node (box1) at (0,0) [draw,fill=blue!20!white] {Box 1};
 \node (box2) at (4,0) [draw,fill=blue!20!white] {Box 2};
 \draw[->] (box1) -- (box2);
 \draw[->] (box1.north) -- ++(0,1) -| (box2.north);
 \draw[->] (box1.300) -- ++(0,-0.5) -| (box2.240);
 \draw[->] (box1.240) -- ++(0,-1.0) -| (box2.300);
\end{tikzpicture}

Edit 3: Regarding the request for tip aligned arrows: I could not (right now) think of anything elegent, so I used absolute coordinates and the left option, e.g. draw the node left of the coordinates, e.g. ending at the specified coordinates:
\documentclass[ngerman]{scrartcl}

\usepackage{ucs}
\usepackage[utf8x]{inputenc}
\usepackage{tikz}
\usetikzlibrary{shapes,arrows,positioning,calc}

\begin{document}

\tikzstyle{block} = [rectangle, fill=blue!20, minimum height=3em, minimum width=6em] \tikzstyle{arrow} = [single arrow, draw]

\begin{tikzpicture}[auto, node distance=0.5cm and 0.5cm, arr/.style={->,thick}, line/.style={thick}, font=\footnotesize]

\node (stoffVor) [block] {Box 1 text};
\node (haupt) [block, right=of stoffVor, align=center] {Box 2 text};
\node (stoffNach) [block, right=of haupt] {Box 3 text};
\node (pfeil1) at (-2,-1.5) [arrow,left] {Arrow 1};
\node (pfeil2) at (-2,-2.5) [arrow,left] {Arrow 2 text};
\node (pfeil0) at (-2,0) [arrow,left] {Arrow 3 longer text};
\node (neben) at (9.5,-0.5) [arrow,left,label=below:] {Text};
\node (hauptP) at (9.5,0.5) [arrow,left,label=above:] {Text};
\node (pfeil3) at (9.5,1.5) [arrow,left] {Text};
\node (pfeil4) at (9.5,2.5) [arrow,left] {Lorem, Ipsum, Dolor, Sit};

\draw[arr] (pfeil0.east) -- (stoffVor.west);
\draw[arr] (stoffVor.east) -- (haupt.west);
\draw[arr] (haupt.east) -- (stoffNach.west);
\draw[arr] (stoffNach.north) --  ++(0,0.5) node [auto, swap, yshift=6] {Text} -| ($ (stoffVor.east) + (0.25,0) $);
\draw[arr] (pfeil1.east) -| (stoffVor.240);
\draw[arr] (pfeil1.east) -| (haupt.240);
\draw[arr] (pfeil1.east) -| (stoffNach.240);
\draw[arr] (pfeil2.east) -| (stoffVor.300);
\draw[arr] (pfeil2.east) -| (haupt.300);
\draw[arr] (pfeil2.east) -| (stoffNach.300);
\draw[line] (haupt.150) |-  (pfeil4.west);
\draw[line] (haupt.30) |-  (pfeil3.west);
\draw[line] (stoffNach.350) -- ++ (0.25,0) -- ++ (0,-0.1) |- (neben.west);
\draw[line] (stoffNach.10) -- ++ (0.25,0) -- ++ (0, +0.1) |- (hauptP.west);

\end{tikzpicture}

\end{document}


text:
Q: Subseting data frame based on multiple criteria for deletion of rows Consider the following data frame consisting of column names "id" and "x", where each id is repeated four times. Data is as follows:
df<-data.frame("id"=c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4),
                "x"=c(2,2,1,1,2,3,3,3,1,2,2,3,2,2,3,3))

The question is about how to subset the data frame by the following criteria:
(1) keep all entries of each id, if its corresponding values in column x does not contain 3 or it has 3 as the last number.
(2) for a given id with multiple 3s in column x, keep all the numbers up to the first 3 and delete the remaining 3s. The expected output would look like:
   id x
1   1 2
2   1 2
3   1 1
4   1 1
5   2 2
6   2 3
7   3 1
8   3 2
9   3 2
10  3 3
11  4 2
12  4 2
13  4 3

I am familiar with the use of the 'filter' function in dplyr package to subset data, but this particular situation confuses me because of the complexity of the above criteria. Any help on this would be greatly appraciated.

A: Here's one solution that uses / creates some new columns to help you filter on:
library(dplyr)

df<-data.frame("id"=c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4),
               "x"=c(2,2,1,1,2,3,3,3,1,2,2,3,2,2,3,3))

df %>%
  group_by(id) %>%                                    # for each id
  mutate(num_threes = sum(x == 3),                    # count number of 3s
         flag = ifelse(unique(num_threes) > 0,        # if there is a 3
                        min(row_number()[x == 3]),    # keep the row of the first 3
                        0)) %>%                       # otherwise put a 0
  filter(num_threes == 0 | row_number() <= flag) %>%  # keep ids with no 3s or up to first 3
  ungroup() %>%
  select(-num_threes, -flag)                          # remove helpful columns

# # A tibble: 13 x 2
#      id     x
#   <dbl> <dbl>
# 1     1     2
# 2     1     2
# 3     1     1
# 4     1     1
# 5     2     2
# 6     2     3
# 7     3     1
# 8     3     2
# 9     3     2
# 10    3     3
# 11    4     2
# 12    4     2
# 13    4     3

A: this works for me:
data
df<-data.frame("id"=c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4),
                "x"=c(2,2,1,1,2,3,3,3,1,2,2,3,2,2,3,3))

commands
library(dplyr)
df <- mutate(df, before = lag(x))

df$condition1 <- 1

df$condition1[df$x == 3 & df$before == 3] <- 0
final_df <- df[df$condition1 == 1, 1:2]

result
    x  id
    1   2
    1   2
    1   1
    1   1
    2   2
    2   3
    3   1
    3   2
    3   2
    3   3
    4   2
    4   2
    4   3`

A: One idea is to pick out the rows with x==3 and use unique() over them. Then append the unique rows with just single 3 to the rest part of the data frame, and finally order the rows.
Here is a solution with base R for the idea above:
res <- (r <- with(df,rbind(df[x!=3,],unique(df[x==3,]))))[order(as.numeric(rownames(r))),]
rownames(res) <- seq(nrow(res))

which give
> res
   id x
1   1 2
2   1 2
3   1 1
4   1 1
5   2 2
6   2 3
7   3 1
8   3 2
9   3 2
10  3 3
11  4 2
12  4 2
13  4 3

DATA
df<-data.frame("id"=c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4),
               "x"=c(2,2,1,1,2,3,3,3,1,2,2,3,2,2,3,3))


text:
Q: Anyone know why I'm getting this RSpec error? getting nil <-- def mock_category(stubs={})
  @mock_category ||= mock_model(Category, stubs).as_null_object
end

describe "GET show" do
  it "assigns the requested category as @category" do
    Category.stub(:find).with("37") { mock_category }
    get :show, :id => "37"
    assigns(:category).should be(mock_category)
  end
end

Which returns :
1) CategoriesController GET show assigns the requested category as @category
   Failure/Error: assigns(:category).should be(mock_category)
   expected Category_1002, got nil

I'm confused here, because this is a right out of the box controller that rspec set up. Why could this be failing?
My versions:
Rails 3.0.0.beta4
Ruby 1.8.7
RSpec 2.0.0.beta.10

Also tried this, same exact reproducible error with :
Rails 3.0.0
Ruby 1.8.7
RSpec 2.0.0.beta.20

The command I used to generate the specs were rails g scaffold Category
In my application.rb
config.generators do |g|
  g.template_engine :haml
  g.test_framework :rspec, :fixture => true, :views => false
end

UPDATE
This goes for any scaffolded controller by Rails 3, with RSpec2. Its guarenteed to fail. Anyone know how this is supposed to be written?

A: rspec-rails has a spec-suite it runs against itself that uses all the generators and runs all the generated specs and they all pass, so this should work. What versions of rspec, rails, and ruby are you using? What commands did you use to generate the Category model and CategoriesController?

A: The conflict comes from conflicts that occurred between Rspec Beta 10 and Rspec Beta 20, and Rails 3 Beta4, to Rails 3 release.
To solve this, I uninstalled haml, and installed haml-rails.
Then I deleted all the specs that were previously generated, and regenerated them.


text:
Q: asp.net Kendo, couldn't get selected row datas I have a kendo grid in my project and a custom button in that grid. I tried to get row data when I click the button. But javascript code gives me error which is:
"Javascript runtime error: Unable to get property "dataItem" of undefined or null referance"
My grid code :
@model IEnumerable<SalePortal.ServiceReference.Product>

    @{
        ViewBag.Title = "GetProduct";
    }

    @(Html.Kendo().Grid<SalePortal.ServiceReference.Product>()
    .Name("Grid")
    .DataSource(dataSource => dataSource
        .Ajax()
        .Read(read => read.Action("GetProduct", "Home"))
        )
    .Columns(columns =>
        {
            columns.Bound(product => product.pID);
            columns.Bound(product => product.productName);
            columns.Bound(product => product.productPrice);
            columns.Command(command => command.Custom("Buy").Click("Sale"));
        })

    )

My javascript code :
    <script type="text/javascript">

    function Sale() {

        var gridE = $("#kendoo").data("kendoGrid");
        var selectedItem = gridE.dataItem(gridE.select());  //Error here!!!

        alert(selectedItem);

</script>

A: You need to specify Grid Name/Id when fetching data through dataItem.
Try this:
 <script type="text/javascript">

function Sale() {

    var gridE = $("#Grid").data("kendoGrid");
    var selectedItem = gridE.select();  //Updated here!!!
    var dataItemSelectedData = gridE.dataItem(selectedItem); //Updated here!!!

    alert(dataItemSelectedData); //Updated here!!!

</script>


text:
Q: Using sun PDF Renderer to display PDFs with embedded fonts I'm having trouble using Sun's PDF Renderer package to view PDFs with embedded fonts.  I have the following code which creates a BufferedImage out of every page of a PDF for viewing in my application, and it works fine when there are no embedded fonts.  However, when the PDF has embedded fonts, it shows no text.  Any ideas?  Also, it opens fine in Adobe's PDF viewer.
File f = new File("C:\\test.pdf");
FileChannel fc = new RandomAccessFile(f, "r").getChannel();
PDFFile pdfFile = new PDFFile(fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()));
for(int x=0; x<pdfFile.getNumPages(); x++) {
    try {
        BufferedImage bi = (BufferedImage)pdfFile.getPage(x+1).getImage(
            (int)pdfFile.getPage(x+1).getWidth(),
            (int)pdfFile.getPage(x+1).getHeight(),
            new Rectangle((int)pdfFile.getPage(x+1).getWidth(),
            (int)pdfFile.getPage(x+1).getHeight()),
             null, true, true);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

A: I figured this out by changing PDF renders from PDFRenderer to PDFBox, which works much better.  More info is available here.

A: You could also look at Icesoft, IText, JPedal, and Multivalent who offer Open Source PDF tools.


text:
Q: JPA Criteria API and OrderBy on subclasses attributes I have an AbstractPerson wich as two subclasses : LegalPerson and PhysicalPerson.
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class AbstractPerson {
    private Long id;
    ...
}

@Entity
public class LegalPerson extends AbstractPerson {
    private String name;
    ...
}

@Entity
public class PhysicalPerson extends AbstractPerson {
    private String lastName;
    private String firstName;
    ...
}

When I retrieve all my entities (CriteriaQuery based on AbstractPerson) I would order them by LegalPerson.name ASC, PhysicalPerson.lastName ASC, PhysicalPerson.firstName ASC.
I need to produce an abstract entities list sorted and grouped by these criterias.
Original SQL query lets appear all subclass fields (SINGLE_TABLE strategy) but I don't know how to exploit them.
Is there any solution using Criteria API to order the query result on subclasses attributes ?
Thanks,
Best regards,
Seth.

A: The Criteira API defines an as() API that allows you to cast to another class.  This should work for subclasses I think, at least with EclipseLink it should.
If they all have a name, you should consider moving the name up into the superclass.  Ordering by a field that is only in a subclass will give an odd order, as you will first get all of the LegalPersons then all of the PhysicalPersons.

A: I spent several days struggling with polymorphism in JPA criteria. I came to the conclusion that jpa criteria is of no  help when it comes to polymorphic queries.
The best you can achieve is a restriction on a property of a subclass by a rather complicated exists-subquery-construction.
My tip is: Avoid criteria if you can.
If you have a static query maybe you are more lucky with JPQL.


text:
Q: Jquery how to change the oder of accordion I have a Jquery accordion with contents like this

  header 1

  contents 1

  header 2

  content 2

  header 3

content 3
When I view this HTML page, the accordion shows the heading as it is. Is there a way I can show header 3 first then header 1 , header 2 etc... Basically, I should be able to specify which header should  be shown first when the HTML is displayed.

A: This should work for you http://jsfiddle.net/Z5hZJ/1/
$('h3 a').click(function(){
    $(this).parents('h3').prependTo('.headers');
});


text: Q: Is there a way to automatically reorganize desktop icons? Gnome has "Keep Aligned", Windows "Rearrange Automatically"; can't find it in Unity. Is it perhaps because we're not intended to have icons in the desktop?


text:
Q: How to divide 24VAC to 24VDC for use with GPIO I'm working on a project to gather metrics from my HVAC. I need to detect the presence or absence of 24vAC on two different wires (Y/yellow/cooler, W/white/heater) relative to common - either of which will be periodically pulled to 24vAC by a relay in the thermostat. I have a Raspberry Pi with a 4-channel ADC ready to measure power but it is limited to +/- 1v.
I gave up trying to draw a voltage divider that could divide both Y and W without leaking voltage to the other input channel. That is to say, the ADC would see a range of voltages depending on none/one/both Y and W being pulled high, and it got too complicated.
Now I'm exploring the use of a couple of reed relays (datasheet) which run at 24vDC to isolate the channels. I need to come up with a way to carefully lower the 24vAC voltage to trigger the 24vDC reed relays. I'm thinking a single resistor in series with the AC power source should suffice, given an appropriate rating. I don't want to blow the relay coil and this needs to safely run unattended.
I need help calculating the rating of the resistor.
I hypothesize that I can simply lower the voltage with a resistor and not have to rectify the power before sending it to the relay but perhaps I am over simplifying?

A: Use a circuit like this with an optocoupler (which should isolate the 24VAC to prevent higher voltages from reaching the Rpi)
The circuit also has a RC filter to keep the circuit on in between phases, but in the diagram below its set to something like 1ms, you will probably want to adjust it to something higher like 20ms and a 20uF cap.
The LED in the TCLT1600 shouldn't need more than 10mA so a 2k resistor for R85 should work to limit the current.

Source: AC detection for microcontroller

A: Vending machines monitor their 24VAC input like so (resistors set for you 1V limit):

simulate this circuit – Schematic created using CircuitLab
So make two of these and wire up each one to a seperate A2D.
You can also wire them up to a GPIO and set an interrupt on falling edge, or something like that.  I've also seen that done too.


text:
Q: Make Lite-Server run as localhost:3000/parentdirectory and accessible as localhost/parentdirectory I have an Angular2 app with this file structure:

*

*ParentDirectory

*

*AppDirectory

*

*app

*

*app.component etc

*node-module

*

*@angular

*lite-server

*etc

*index.html

*styles.css

*etc

I am testing the app with the lite-server and it runs beautifully on localhost:3000. To make it work with an Apache proxy I am setting up, I need it to run as locahost:3000/parentdirectory.
Using angular routes, I can easily make my pages look like they are coming from localhost:3000/parentdirectory, but that is only a superficial fix. If I go to localhost/parentdirectory, it still needs to work.
I looked at this question, which I think is very similar: Can't change the base folder for lite-server in Angular 2 application
However, I'm new to all this and I'm afraid of breaking my currently working set-up.
My instinct is that I need to move my lite-server into the parentdirectory and change the root folder to look into my appdirectory, but I'm not sure if that will actually solve my problem.
I am hoping someone can give me concrete instructions or a link to documentation that outlines what I need to do to make this work before I start blindly changing things.
Thank you!

A: Please try following assuming your application now lives in app folder and server started on it. I.e https://localhost:3000/app
1. index.html set <base href='/app/' />
2. In bootstrap {provide: APP_BASE_HREF, useValue: '/app/'} // import it from router package
3. In system.config.ts add baseURL: /app/


text:
Q: How to add a foreign key constraint references to the IS-A-to-Two-Tables relationship? First in my ER-Model I have an account entity which has a IS-A relationship with two disjoint subentities saving-account and checking-account.
However I have a customer entity have a depositor relationship with the account entity, such the use case like the ER diagram below.

Therefore I translate the ER into the table like this:
customer(cid, cname)
depositor(cid, account-number)
saving-account(account-number, balance, interest-rate)
checking-account(account-number, balance, overdraft-amount)
So finally, I take only two tables saving-account and checking-account from the IS-A relationship.

Then the problem occurs, to create the depositor table, I take a T-SQL:
CREATE TABLE depositor(
    customer_id         int             not null,
    account_number      int             not null,
    access_date         Date            DEFAULT GETDATE(),
    PRIMARY KEY(customer_id, account_number),
    FOREIGN KEY(customer_id)    REFERENCES customer(customer_id),
    FOREIGN KEY(account_number) REFERENCES account(account_number)
)

At the final line, the foreign key account_number should reference to the account table, but what I have are saving-account and checking-account tables. In this situation, how do I add a constraint in T-SQL? Is it possible to add a constraint if I only take two tables from the IS-A relationship?

A: I suggest you have an extra table called account. Then saving-account and checking-account should be separate tables pointing to that.
Also, you should have an account_id field as a PK instead of account_number. As a best practice rule, PK should not have any business meaning, it should be an abstract concept.
In summary, I suggest following tables:
account(aid, account-number, balance, plus any other common field for account)
saving-account([optional pk], aid_ref, interest-rate, plus fields specific to saving-account)
checking-account([optional pk], aid_ref, overdraft-amount, plus fields specific to saving-account)
customer(cid, cname)
depositor(cid, aid)


text:
Q: In an array with null spaces, how can consolidate all of the non null values together? Hey so I have this homework assignment and I'm having issues with one of the methods. I would like hints and not actual answers/code.
So I have a class called HorseBarn that messes with an array of horses(horse being the type). My problem is I'm having troubles with the consolidate method.
What the array would look like before consolidate:
a,b,c,d are horses
|a|null|b|null|c|d|
What the array would look like after consolidate:
|a|b|c|d|null|null|
So my logic would be to make a nested for loop. The first loop would search for a null value, once the first loop finds the null value, the second loop would look for a horse and then swap with it. Then the second loop would end and go back to the first loop. So here is what I have right now and it doesn't work(it just terminates). Is my logic wrong or is it my syntax that's causing the problems?
public void consolidate()
{
    int j = 0;
    for(int i = 0; i < spaces.length;i++)
    {
        if( spaces[i] == null)
        {
            for(j = i; j < spaces.length && spaces[j] == null; j++)
            {

            }
            spaces[i] = spaces[j];
            spaces[j] = null;
        }

    }

A: Well for starters, this should give an index out of bounds exception if the last non-null is found and there still are elements remaining:
ex: horses = | a | null | null | null |
for i = 1, since horses[1] -> horses[3] are empty, j first gets set to 1 then ends with j = 4 (because of the termination condition j < horses.length())
You would then try to swap horses[1] with horses[4], which throws the array index out of bounds

A: In the inner for loop, just find the position of next non null value and break it there.
Then swap it with your null.
A better time efficient code.


text:
Q: Calculated measure in SSAS Cube either very slow or doesn't have all functionality I have a SSAS Cube with many calculated measures written in MDX.
One specific is causing me trouble - the Running Totals.
Purpose of the calculated measure
The calculated measure should sum all movements from B.O.T. until the end of time,
Meaning when there is no more movements because we have reached present day, then the value should be repeated until there is no more dates in my time dimension.
Example:
FY13  0.00
FY14  10.00
FY15  13.00
FY16  14.00
FY17  20.00
FY18  20.00
FY19  20.00
FY20  20.00
FY21  20.00

Also the measure should work along all my date hierarchies (there is four).
I actually got it to work as intended with the following code:
CREATE MEMBER CURRENTCUBE.[Measures].[Actual Balance LCY]
AS AGGREGATE(
  {NULL:[Posting Date].[Calendar Year Y-Q-M-D].CurrentMember}
   * {NULL:[Posting Date].[Calendar Year Y-M-D].CurrentMember}
   * {NULL:[Posting Date].[Fiscal Year Y-M-D].CurrentMember}
  * {NULL:[Posting Date].[Fiscal Year Y-Q-M-D].CurrentMember}
,[Measures].[Actual LCY]
),
FORMAT_STRING = "#,##0.00;-#,##0.00",
VISIBLE = 1 ,  ASSOCIATED_MEASURE_GROUP = 'Actual';

The problem:
When the measure is added to a PivotTable in Excel and e.g. two dimensions are added on the row and one date hierarchy on columns the query becomes very slow. 40-60 seconds ( I know this is slow, cause we have a legacy cube build in timeXtender that does the same Pivot table in 5-10 seconds on the same amount of data)
I added NON_EMPTY to the MDX. Then the query is fast, but there is no more values after FY17 which is not intended behavior.
In the legacy solution NON_EMPTY is also not typed, but it is still faster.
The question:
What to do, to get both the intended behavior of the measure and a reasonable query speed?

A: Your performance stopper here:
{NULL:[Posting Date].[Calendar Year Y-Q-M-D].CurrentMember}
* {NULL:[Posting Date].[Calendar Year Y-M-D].CurrentMember}
* {NULL:[Posting Date].[Fiscal Year Y-M-D].CurrentMember}
* {NULL:[Posting Date].[Fiscal Year Y-Q-M-D].CurrentMember}

This cross-joining operation is simply too heavy.
There are two ways I'd use. Pick which you like more:
1: Depend on which hierarchy you pick you get the result (no need to cross-join everything).
Aggregate(
   case
      when not [Posting Date].[Calendar Year Y-Q-M-D].CurrentMember is [Posting Date].[Calendar Year Y-Q-M-D].DefaultMember
      then {NULL:[Posting Date].[Calendar Year Y-Q-M-D].CurrentMember}
      when not [Posting Date].[Calendar Year Y-M-D].CurrentMember is [Posting Date].[Calendar Year Y-M-D].DefaultMember
      then {NULL:[Posting Date].[Calendar Year Y-M-D].CurrentMember}
      when not [Posting Date].[Fiscal Year Y-M-D].CurrentMember is [Posting Date].[Fiscal Year Y-M-D].DefaultMember
      then {NULL:[Posting Date].[Fiscal Year Y-M-D].CurrentMember}
      when not [Posting Date].[Fiscal Year Y-Q-M-D].CurrentMember is [Posting Date].[Fiscal Year Y-Q-M-D].DefaultMember
      then {NULL:[Posting Date].[Fiscal Year Y-Q-M-D].CurrentMember}
      else NULL
   end,
   [Measures].[Actual LCY]
)

2: Add a max day measure (so it knows last day of the current member (hierarchy-agnostic):
Aggregate(
   NULL:StrToMember('[Posting Date].[Day].[' + cint([Measures].[Max Day]) + ']')
   [Measures].[Actual LCY]
)


text:
Q: Blocking RBAC inheritance I'm creating subscriptions in Azure with a number of RBAC roles assigned: hosting team and project team. The hosting team should have full access to everything, and the project team should have full access to everything baring a few exception, e.g. no access to the 'Networking' resource group (although they are allowed to create their own resource group(s) containing networking). We have set the RBAC owner for the project team at the subscription level, but in doing so, this also allows them to fully manage the restricted areas.
In principal the 'deny' assignments in Azure Portal would fit our needs, however they are currently only available for Azure Blueprints. Any ideas?

A: Block inheritance doesnt exist yet, your only option is to carefully craft and assing custom rbac roles or carefully assing built-in roles (so, never at sub level, only at resource group level).
Or use Azure Blueprints, it appears they added support for that there.


text:
Q: How to update a single patch from withing a patchset? I would like to know how to update a patch that is part of patchset and have been already submitted to open-source project?
The tutorials online mention using --amend, but the patch to be fixed is not the last one, instead it's number 2 of 5.
Also, I would like to make sure... Should I submit the whole patchset again or just the fixed one?

*

*Additional info: the patchset is for U-Boot, created with cover letter & numbered as following:
git format-patch -o /home/sam/patchset --cover-letter -n --thread=shallow 0b9c250^..fd3c12d

Thank you.

A: The precise details might vary slightly depending on the recipients' preferences.  As a general rule, if you need to revise a patch-set, you submit a new patch-set, "[v2] ..." (version 2), "v3", and so on.  It's also nice to provide, in the "00/NN" entry, a (cumulative) description of the update.  You can also include explanatory text between the cut-line sections within individual patches:
Subject: [PATCH v5 07/11] foo/blah: frobulate the mizzenbeast
...

... descriptive text about the patch extracted from a commit message ...

Signed-off-by: A U Thor <thor@example.com>
---
We can sneak in a bit more information here.  This will not get
added to the commit.

  dir/sub/some.ext                 |  3 ++
  ...
diff --git ...

Since such patch-sets are actually just email messages, you could just stop using Git at all here.  However, that's doing things the hard way (at least in my opinion).
Since the new patch-set is a new set of email messages, and you might want to keep your existing work, the way to deal with this problem in Git itself is to make a new branch.
Suppose the above is a series of patches in your mizzenbeast branch.  The way I would handle this is to rename that branch mizzenbeast-v1 and create a new branch mizzenbeast-v2.  You can then git cherry-pick each individual commit, one at a time, until you reach the one(s) that need change(s).  At this point you can git cherry-pick -n the commit that needs some changes.
You now have, in your index and work-tree, everything staged and ready to commit, but not actually committed.  Now you can make whatever changes you like, git add them, and git commit the result.
You are now ready to resume cherry-picking any unchanged commits, resolving any conflicts that occur because of the one you did change.  When you are done, your mizzenbeast-v2 branch contains the new series of commits, ready to git format-patch as [PATCH v2 nn/howmany] and send to the mailing list for review.
(Note that you will still need to manually massage the text of the formatted patches, to insert the v2 and any extra information.)
Making this easier to do for yourself
There is a somewhat faster and easier way to cherry pick everything and modify it: make your new branch (mizzenbeast-v2) pointing to the tip commit of the renamed (mizzenbeast-v1) branch, so that both branches are identical.  Then run git rebase -i <hash or identifier of where to start>.  This brings up your editor on a series of pick commands, that tell Git to do the same cherry-picks you would have done manually.  Change one or more to edit, write out the file, and exit the editor.  Git will now being the cherry-picking process, much as above.  However, when it reaches the edit one, it will cherry-pick the commit—this time without -n—but then stop.
Now you can make changes and use git commit --amend to replace the current (anonymous) mizzenbeast-v2-in-progress branch tip commit.  This is similar to what you did when using git cherry-pick -n, except that you're shoving aside the current commit instead of just adding a new one.
Once that is done, you can run git rebase --continue to tell Git to continue with the saved cherry-picking instructions.  If all goes well, it will finish them all and move the mizzenbeast-v2 branch label to the tip of the new branch.  If something goes wrong (a conflict due to the amended commit in the middle of this process), you will have to fix that up, git add, and git rebase --continue yet again.
(I recommend waiting to use this "easier" process until after you have done it the "hard way", manually cherry-picking each commit, at least once or twice.  The reason is that while this automates that work, it's hard to tell what's happening.  If something goes wrong—and things will go wrong—it's very helpful to have a clear idea of what Git was doing, and what you need to do now to fix it.)


text:
Q: the wifi driver is not working in Ubuntu 16.04.1 My Broadcom chipset is BCM43142 802.11 b/g/n. I checked with the Software and Updates tab in the System Settings and it showed that I am using a driver sourced from bcmwl-kernel-source. But it is still not working.
I had used the bcmwl-kernel-source to fix the same issue in Ubuntu 15.10 but this is not working in the Ubuntu 16.04.
The output of lspci -knn |grep Net -A2 is:
08:00.0 network controller [0280]: broadcom corporation bcm43142 802.11b/g/n [14e4: 4365 ] rev 01
Device name: broadcom bcm43142 802.11bgn 1*1 WiFi adapter + bt 4.0 combo adapter
Subsystem: Hewlett Packard company bcm43142 802. 11b/g/n [103:2230 ]

A: I had a very similar problem on my HP Stream. For me, the solution was to go to the BIOS menu and disable secure boot manually (even though it may be prompting you to enter a password during installation of the OS or of packages, that does not mean it is disabling secure boot). This allowed my computer to use the bcmwl-kernel-source driver that it listed in the system settings, as you mentioned. I do not know if this is the fix you will need, but it is what worked for me - further info here.


text:
Q: Add resource automatically by task name in MS-project I want to automatically add resource name just for some task (sub-task) in MS-project for example if task is CMM i want  automatically add CMM to resource name
And this is my code
Sub Automatically()
Dim NR As MsProject.Resource
Dim Tsk As MsProject.Task
Dim Row As Integer
For each row in Ms.Project.Task
          If Tsk = "CMM" Or "EDM" Or "EL Milling" Or "CAM Wire cut" Or "Laser Welding" Or "Wire cut" Or "CNC Milling" Or "Grinding" Or "Lathe" Or "Manual Milling" Or "Polishing"
               Set NR = NR.Resource.Add.Tsk
          End If
          If Tsk = "Inspection" Or "Report" Then
               Set NR =  "CMM"
          End if
Next row
End Sub

A: This code assigns resources to tasks based on the names of the tasks. Given that task names are typically more descriptive than a single word, the code uses a contains search (e.g. Like). If the resource does not already exist, it is added.
Sub AddResourceAssignments()

    Dim resName As String

    Dim tsk As Task
    For Each tsk In ActiveProject.Tasks
        ' determine the resource to add to the task
        Select Case True
            Case (tsk.Name Like "*Gate*"): resName = "Gate"
            Case (tsk.Name Like "*CMM*"): resName = "CMM"
            Case (tsk.Name Like "*EDM*"): resName = "EDM"
            Case (tsk.Name Like "*EL Milling*"): resName = "EL Milling"
            Case (tsk.Name Like "*CAM Wire cut*"): resName = "CAM Wire cut"
            Case (tsk.Name Like "*Laser Welding*"): resName = "Laser Welding"
            Case (tsk.Name Like "*Wire cut*"): resName = "Wire cut"
            Case (tsk.Name Like "*CNC Milling*"): resName = "CNC Milling"
            Case (tsk.Name Like "*Grinding*"): resName = "Grinding"
            Case (tsk.Name Like "*Lathe*"): resName = "Lathe"
            Case (tsk.Name Like "*Manual Milling*"): resName = "Manual Milling"
            Case (tsk.Name Like "*Polishing*"): resName = "Polishing"
            Case (tsk.Name Like "*Inspection*"): resName = "CMM"
            Case (tsk.Name Like "*Report*"): resName = "CMM"
            Case Else: resName = vbNullString
        End Select

        If Len(resName) > 0 Then
            ' create the resource assignment
            On Error Resume Next
            Dim res As Resource
            Set res = ActiveProject.Resources(resName)
            If Err.Number <> 0 Then
                ' presume error due to missing resource
                Set res = ActiveProject.Resources.Add(Name:=resName)
            End If
            tsk.Assignments.Add ResourceID:=res.ID
        End If

    Next tsk

End Sub


text:
Q: Read IDataReader on a GROUP BY MySQL query I have a table "nesting_bar_detail", that I read like that in my C# code :
public List<RepereNest> SelectListRepereNestInMeb(string query)
{
    List<RepereNest> list = new List<RepereNest>();
    if (this.OpenConnection() == true)
    {
        IDataReader dataReader = ExecuteReader(query);
        while (dataReader.Read())
        {
            RepereNest det = new RepereNest();
            det.ID=(long)dataReader["ID"];
            det.IdDetail=(long)dataReader["ID_DETAIL"];
            det.IdNesting=(long)dataReader["ID_NESTING"];
            det.Name = (string)dataReader["NAME"];
            det.Quantity = (int)dataReader["QUANTITY"];
            list.Add(det);
        }
        this.CloseConnection();
    }
    return list;
}

If I make a simple query, as here, all is working fine
SELECT * FROM nesting_bar_detail WHERE NAME='TITI'
But when I want to group the results, I make the following request :
SELECT ID,ID_DETAIL,ID_NESTING, NAME, SUM(QUANTITY) AS QUANTITY GROUP BY ID_DETAIL,ID_NESTING ORDER BY ID_NESTING

But then I have an error on the lines where I "calculate" the field (in that case on the line det.Quantity = (int)dataReader["QUANTITY"];, that is a SUM)
Error "The specified cast is invalid"
I don't understand if this my SQL request that is not correct, or why the returned value type is not recognized ?
Edit :
Here is the data I have inside database :
+-------+-----------+------------+------+----------+
| ID    | ID_DETAIL | ID_NESTING | NAME | QUANTITY |
+-------+-----------+------------+------+----------+
| 10754 | 10        | 58         | TITI | 2        |
+-------+-----------+------------+------+----------+
| 10755 | 11        | 59         | TITI | 3        |
+-------+-----------+------------+------+----------+
| 10756 | 11        | 59         | TITI | 4        |
+-------+-----------+------------+------+----------+

And here is Expected result :
+-------+-----------+------------+------+----------+
| ID    | ID_DETAIL | ID_NESTING | NAME | QUANTITY |
+-------+-----------+------------+------+----------+
| 10754 | 10        | 58         | TITI | 2        |
+-------+-----------+------------+------+----------+
| 10755 | 11        | 59         | TITI | 7        |
+-------+-----------+------------+------+----------+

A: Aggregate (GROUP BY) Function Descriptions
"The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or DECIMAL), and a DOUBLE value for approximate-value arguments (FLOAT or DOUBLE)."
In your C# code you're trying to cast the resulting DECIMAL value of SUM(QUANTITY) as an int


text:
Q: Licence for DeepZoom and SeaDragaon AJAX? wats the licence for  microsoft silverlight DeepZoom and SeaDragaon AJAX.. can i use the libraries in commercial applications.. or do i need to purchase any commercial licnence...

A: DeepZoom is a feature of the Silverlight 3 product, and helped by the free Deep Zoom Composer application.
The Silverlight platform is open for anyone to build applications on top of, so go at it and build something great!
For the second part, I'm a little unsure. As far as I can tell, the SeaDragon AJAX is more of a "backup" plan, and being part of the Live Labs, might not be as well supported as a fully released product. However, there's nothing on the site to indicate that it cannot be used on a commercial site, other than the typical Live terms.


text:
Q: Retornar última entrada de cada produto me ajudem. Estou com uma situação onde quero trazer apenas a última entrada de nota de cada produto para criação de um relatório.
Criei um select, porém existem produtos se repetindo onde não deveria. Veja o select:
SELECT P.CodProd, MAX(E.Entrada) Entrada, P.PrecoCustoUNSC,IE.ValorCaixa
FROM Entradas E
        INNER JOIN ItensEntrada IE ON E.Cod_Entrada=IE.Cod_Entrada
        INNER JOIN Produtos P ON IE.CodProd=P.CodProd
        WHERE IE.ValorCaixa>0
GROUP BY P.CodProd, P.PrecoCustoUNSC, IE.ValorCaixa
ORDER BY 1

Resultado:
CodProd Entrada                 PrecoCustoUNSC                          ValorCaixa
------- ----------------------- --------------------------------------- ---------------------------------------
000001  2019-08-20 00:00:00.000 3.0000000000                            3.0000000000
000001  2019-08-19 00:00:00.000 3.0000000000                            10.0000000000
000001  2019-08-23 00:00:00.000 3.0000000000                            15.0000000000
000002  2019-08-20 00:00:00.000 15.0000000000                           15.0000000000
000002  2019-08-23 00:00:00.000 15.0000000000                           65.0000000000
000003  2019-08-23 00:00:00.000 30.0000000000                           30.0000000000
000003  2019-09-06 00:00:00.000 30.0000000000                           50.0000000000
000004  2019-08-23 00:00:00.000 50.0000000000                           50.0000000000
000005  2019-09-04 00:00:00.000 5.0000000000                            5.0000000000
000006  2019-09-04 00:00:00.000 5.0000000000                            5.0000000000
000007  2019-09-04 00:00:00.000 30.0000000000                           30.0000000000
000008  2019-09-04 00:00:00.000 50.0000000000                           50.0000000000
000009  2019-09-05 00:00:00.000 69.0000000000                           69.0000000000
000010  2019-09-05 00:00:00.000 35.0000000000                           35.0000000000
000011  2019-09-11 00:00:00.000 50.0000000000                           50.0000000000
000011  2019-09-06 00:00:00.000 50.0000000000                           60.0000000000
000012  2019-09-11 00:00:00.000 30.0000000000                           30.0000000000
000013  2019-09-11 00:00:00.000 15.0000000000                           15.0000000000
000014  2019-09-11 00:00:00.000 30.0000000000                           30.0000000000
000015  2019-09-11 00:00:00.000 13.0000000000                           13.0000000000
000015  2019-09-11 00:00:00.000 13.0000000000                           6.5000000000
000016  2019-09-11 00:00:00.000 30.0000000000                           30.0000000000

Então, o produto 1 por exemplo está se repetindo, sendo que eu queria apenas o último registro (Entrada = '2019-08-23') que foi a última entrada do produto dele. Precisei relacionar pois na Entradas está a data da entrada, a ItensEntrada contem ValorCaixa que é o preço de custo onde quero comparar com o cadastro do produto que é o PrecoCustoUNSC.

A: Considerando-se a informação adicional postada nos comentários pelo autor do tópico - podemos usar ao invés da entrada o campo COD_ENTRADA que é o número sequencial de cada nota -, eis sugestão:
-- código #1 v2
with Ultimo as (
SELECT P.CodProd, E.Entrada, P.PrecoCustoUNSC, IE.ValorCaixa,
       seq= row_number() over (partition by P.CodProd order by E.Cod_Entrada desc)
  from Entradas E
       inner join ItensEntrada as IE on E.Cod_Entrada = IE.Cod_Entrada
       inner join Produtos as P on IE.CodProd = P.CodProd
  where IE.ValorCaixa > 0
)
SELECT CodProd, Entrada, PrecoCustoUNSC, ValorCaixa
  from Ultimo
  where seq = 1
  order by CodProd;

Na CTE Ultimo para cada produto é gerado um numerador sequencial (seq), iniciando de 1 para o mais recente (isto é, com maior valor de Cod_Entrada) e incrementando à medida que é mais antigo. Para acompanhar este passo basta executar o seguinte código:
-- código #2
SELECT P.CodProd, E.Entrada, P.PrecoCustoUNSC, IE.ValorCaixa,
       seq= row_number() over (partition by P.CodProd order by E.Cod_Entrada desc)
  from Entradas E
      inner join ItensEntrada as IE on E.Cod_Entrada = IE.Cod_Entrada
      inner join Produtos as P on IE.CodProd = P.CodProd
  where IE.ValorCaixa > 0
  order by P.CodProd, E.Cod_Entrada desc;

Após, basta ler o resultado de Ultimo, filtrando por aqueles cujo valor de seq é 1.

A: Essa tarefa pode ser um pouco mais complexa que parece a primeira vista, então veja, eu vou colocar um código aqui só pra você fazer um teste, eu não sou um DBA experiente o bastante pra dizer se essa é a melhor técnica.
Também não sei qual o nome do campo que é chave primaria da sua tabela ItensEntrada então você mesmo corrige aí.
SELECT
    ie.CodProd,
    e.Entrada,
    p.PrecoCustoUNSC,
    ie.ValorCaixa
FROM (
    SELECT
        i1.CodProd,
        i1.Cod_Entrada,
        i1.ValorCaixa
    FROM ItensEntrada i1
    WHERE
        i1.CodItemEntrada = (SELECT MAX(i2.CodItemEntrada) FROM ItensEntrada i2 WHERE i2.CodProd = i1.CodProd)
) ie
INNER JOIN produtos p ON p.CodProd = ie.CodProd
INNER JOIN Entradas e ON e.Cod_Entrada = ie.Cod_Entrada
ORDER BY ie.CodProd


text:
Q: getpeername always gives bad file descriptor I have the following code, that i am trying to use to get the address of the other end of the socket, but getpeername() always fails with bad file descriptor error. What am i doing wrong?
#include <arpa/inet.h>
#include<syscall.h>
#include<errno.h>
#include <netinet/in.h>
#include<string.h>
#include<sys/socket.h>
#include<stdio.h>
#include<sys/ptrace.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<sys/user.h>
#include<sys/syscall.h>   /* For SYS_write etc */
#include<stdlib.h>

#define ORIG_RAX 15
#define SYSCALL_MAXARGS 6
#define RDI 14

int main()
{
    //**********declarations and memory allocations**********//
    ssize_t size;
    long sys_call_number, temp_long;
    int status, temp, i, j, k, flag;

    struct sockaddr_in ip_addr_struct;
    socklen_t ip_addr_structlen = sizeof(ip_addr_struct);
    struct user_regs_struct regs;

    struct sockaddr_in* connect_struct;

    char* filepath = malloc(1024);
    char* fdpath = malloc(1024);
    char* message = malloc(1024);
    char* connect_ip = malloc(1024);
    char* ip_addr = malloc(1024);

    char* temp_char1,* temp_char2;

    pid_t proc;

    //**********getting pid and attaching to process**********//
    scanf("%d",&proc);

    ptrace(PTRACE_ATTACH,proc, NULL, NULL);

    //**********starting the trace process**********//

    //The system call number used in switch() case to determine particular system   calls//
    while(1)
    {
            wait(&status);
            if(WIFEXITED(status))
            {
                printf("****Process exited****\n");
                break;
            }
                ptrace(PTRACE_GETREGS, proc, NULL, &regs);
                sys_call_number = regs.orig_rax;

        switch(sys_call_number)
        {
            case 44:
                printf("sendto\n");
                //***printing the register values containing system call parameters***//
                printf("%llu - %llu - %llu - %llu - %llu - %llu\n", regs.rdi, regs.rsi, regs.rdx, regs.r10, regs.r8, regs.r9);
                //***getting the peer address***//
                errno = 0;
                temp = getpeername(regs.rdi, (struct sockaddr *)&ip_addr_struct, &ip_addr_structlen);
                if(temp == -1)
                {
                    printf("error is getpeername-%d-%s\n",temp,strerror(errno));
                    return -1;
                }

                int port = ntohs(ip_addr_struct.sin_port);
                inet_ntop(AF_INET, &(ip_addr_struct.sin_addr), ip_addr, 1024);
                printf("%d-%s\n", port, ip_addr);
                port = 0;
                //***reading message being send***//
                temp_char2 = message;
                j = 0;
                while( j < (regs.rdx/8) )
                {
                    temp_long = ptrace(PTRACE_PEEKDATA, proc, regs.rsi + (j*8) , NULL);
                    memcpy(temp_char2, &temp_long, 8);
                    temp_char2 += 8;
                    ++j;
                }
                temp_long = ptrace(PTRACE_PEEKDATA, proc, regs.rsi + (j*8) , NULL);
                memcpy(temp_char2, &temp_long, regs.rdx - (j*8) );
                message[regs.rdx] = '\0';
                printf("Message-%s-\n\n", message);
            break;
        }
    }
}

Here is the output from one such system call
sendto
14 - 32064144 - 884 - 16384 - 0 - 0
--1-Bad file descriptor
0-0.0.0.0
Message-GET /?gfe_rd=cr&ei=2WYzVLCjFq7M8gfLlICoDg HTTP/1.1^M
User-Agent: NetSurf/2.9 (Linux; x86_64)^M
Host: www.google.co.in^M
Accept: */
Accept-Encoding: gzip^M
 Cookie:PREF=ID=yu3vtr7i452389b4o236v4t28o37v723tn8vt0783tnv0723p78 N823748923bt87t2387b473287b8273t48

A: socket descriptor is not shared between two processes. the captured socket descriptor is only effective in the traced process, and not effective in the tracer process. that's why getpeername complains bad descriptor. from the manual of ptrace:The ptrace() system call provides a means by which a parent process may observe and control the execution of another process, and  examine  and change its core image and registers.  It is primarily used to implement breakpoint debugging and system call tracing. there's no word says they share process space, thus, they can not share socket descriptors, memory address, etc..


text:
Q: AWS API Gateway Custom Domain with multi path I have some services registered at API Gateway with Lambda serverless deployment.
Both services are running well with long domain named from AWS API Gateway itself.
Then, I am trying to setup a custom domain to gathered all services into one domain and splitting services by path.
Here is the example I wanted to do (2 Services example):
1. User Service registered on user-api-service Gateway API

2. Order Service registered on order-api-service Gateway API

I want to add custom domain with these settings:
1. api.myapp.com/user path with destination user-api-service Gateway
    API
2. api.myapp.com/order path with destination order-api-service Gateway
    API

I have tried to set this up but it is not work. And this is the problem:
THE PATH ALWAYS USING ROOT !
Whatever I did, It is never use the defined path. And only the first registered mapping is working !
Based on my setting:
api.myapp.com/user/register should be called for register, but it's not work. It is said 404 or Not Found
But it is working with root path:
api.myapp.com/register
Any custom setup that the documentation of API Gateway is not telling ?
What should I do with this error ?

A: I am assuming you have created your custom domain and attached it to API gateway for base path mapping. Considering this, you can add Base path mapping with custom base path just as you wanted do.

*

*Go to API gateway in AWS console

*Scroll down to Custom Domain Names

*Here you will see your custom domain

*Click on EDIT option

*Now you can add mapping as "user" or "order" and select which service you need to attach this base path to "api.myapp.com/user/*"

After saving this settings you are able to run API on
Note: You can not use same base path for other service if you have already attached it before.
In case you haven't created a custom domain, first create custom domain in Route 53 and then add that custom domain to API gateway custom domain section to process further


text:
Q: How to operate on unsaved Excel file? I'd like to automate a loop:

*

*ABAQUS generates a Excel file;

*Matlab utilises data in Excel file;

*loop 1 and 2.
Now my question is: after step 1, the Excel file from ABAQUS is unsaved as Book1. I cannot use Matlab command to save it. Is there a way not to save this ''Book1'' file, but use the data in it? Or if I can find where it is so I can use the data inside? (I assume that Excel always saves the file even though user doesn't?)
Thank you!

A: As agentp mentioned, if you are running Abaqus via a Python script, you can just use Python to create a .txt file to save all the relevant information. If well structured, a .txt file can be as readable as an Excel spreadsheet. Because Matlab and Python have intrinsic functions to read and write files this communication can be easily done.
As for Matlab calling Abaqus, you can use something similar to:
system('abaqus cae nogui=YOUR_SCRIPT.py')

A: Your script that pipes to Excel should have some code similar to this:
 abq_ExcelUtilities.excelUtilities.XYtoExcel(
       xyDataNames='S:Mises PI: PART-1-1 E: 4309 IP: 1', trueName='')

writing the same data to a report (.rpt) file the code looks like this:
 x0 = session.xyDataObjects['S:Mises PI: PART-1-1 E: 4309 IP: 1']
 session.writeXYReport(fileName='abaqus.rpt', xyData=(x0, ))

now to "roll your own", use that x0 object: x0.data is a regular python tuple holding the actual data which you can write to a file however you like, eg:
 file=open('myfile.csv','w')
 for point in x0.data: file.write('%g,%g\n'%point)
 file.close()

(you can comment or delete the writeXYReport call )


text:
Q: Neo4j Cypher: Finding the largest disconnected subgraph fast I have a graph with one million nodes. There are many disconnected subgraphs within it. I would like to know what is the largest disconnected subgraph.

For instance this in this graph example we got three disconnected subgraph, so for this case the output will be 7.
I tried this but it is taking a long time,
match p = ()-[*]-() return MAX(length(p)) as l order by l desc limit 1

A: Your query will only ever return the longest path between two separate nodes, not the size of the largest connected subgraph.
Unfortunately Neo4j does not currently have any native support for subgraph operations, and I don't think APOC Procedures has anything here either.
There are ways in Cypher to find subgraphs, but the queries I can think of are not fast or performant, and are likely to time out with large graphs. Here's one, and again, this is not recommended, it is likely to time out for you, but if it works, awesome:
MATCH (n)-[*0..]-(subgraphNode)
WITH n, COUNT(DISTINCT subgraphNode) as subSize
RETURN MAX(subSize)

If this is to be a query run often, or every so often, instead of only once, then I'd recommend a means of tracking your subgraphs.
While I can give an approach to creating subgraph tracking, the approach for keeping this updated across graph operations (those that merge subgraphs, divide into smaller subgraphs, or create new subgraphs) is bound to be trickier, and you'll likely need some kind of Java extension to perform post-transaction processing to maintain this.
Also, this approach is best done during a maintenance window when no write operations are occurring.
The end-goal for this is to attach a single :Subgraph node to every disconnected subgraph, which will make future operations on subgraphs much easier, including your case of finding the largest disconnected subgraph.
The overall approach to fulfilling that goal is to first label all nodes in your graph (with a label like :Unprocessed), then, in batched queries for :Unprocessed nodes, find the entire disconnected subgraph they are a part of, attach a single :Subgraph node to it, and then remove the :Unprocessed label from the subgraph.
So, first, label all nodes in your db:
MATCH (n)
SET n:Unprocessed

Next, the batch operation. You'll want to use APOC Procedures to allow batch processing (which will also take advantage of entire subgraphs being removed from the :Unprocessed label as we process them...we don't want to redundantly perform operations on subgraphs).
CALL apoc.periodic.commit("
// only process a batch of :Unproccessed nodes at a time
MATCH (n:Unprocessed)
WITH n LIMIT {limit}
// subgraphNode will be all nodes in the subgraph including n
MATCH (n)-[*0..]-(subgraphNode)
WITH DISTINCT n, subgraphNode
REMOVE subgraphNode:Unprocessed
// find attach point node in each subgraph with smallest id
WITH n, min(id(subgraphNode)) as attachId
WITH DISTINCT attachId
MATCH (attachNode)
WHERE id(attachNode) = attachId
CREATE (attachNode)<-[:SUBGRAPH]-(:Subgraph)
RETURN count(*)
",{limit:100})

You can adjust your limit as necessary. A lower limit might actually work better, as this may reduce redundant operations on nodes of the same subgraph.
Now that all disconnected subgraphs have a :Subgraph node attached, you can make faster and easier queries for each subgraph. So, to find the largest disconnected subgraph, you might use:
MATCH (sub:Subgraph)-[*]-(subgraphNode)
WITH sub, COUNT(DISTINCT subgraphNode) as subSize
RETURN MAX(subSize)

EDIT
I found a faster means of gathering subgraph nodes compared to using a variable relationship match. APOC's Path Expander functionality, using NODE_GLOBAL uniqueness, should perform faster. Here are the relevant queries modified to use this approach.
CALL apoc.periodic.commit("
// only process a batch of :Unproccessed nodes at a time
MATCH (n:Unprocessed)
WITH n LIMIT {limit}
// subgraphNode will be all nodes in the subgraph including n
CALL apoc.path.expandConfig(n,{bfs:true, uniqueness:"NODE_GLOBAL"})
  YIELD path
WITH n, LAST(NODES(path)) as subgraphNode
REMOVE subgraphNode:Unprocessed
// find attach point node in each subgraph with smallest id
WITH n, min(id(subgraphNode)) as attachId
WITH DISTINCT attachId
MATCH (attachNode)
WHERE id(attachNode) = attachId
CREATE (attachNode)<-[:SUBGRAPH]-(:Subgraph)
RETURN count(*)
",{limit:100})

And the processing for each subgraph:
MATCH (sub:Subgraph)
CALL apoc.path.expandConfig(sub,{minLevel:1, bfs:true, uniqueness:"NODE_GLOBAL"})
  YIELD path
WITH sub, LAST(NODES(path)) as subgraphNode
WITH sub, COUNT(DISTINCT subgraphNode) as subSize
RETURN MAX(subSize)


text:
Q: List doesn't load in django templates So i'm trying to filter my model in this way in views.py:
news_list = list(models.Entry.objects.filter(category='news'))

and the problem is that the list cant be accessable from the django templates.
this is the way I'm trying to access it in home.html:
{% for news in news_list %}

{{ news.title }}

{% endfor %}

and this:
{{ news_list.0.title }}

I'm sure the way that I created the list is right beauce when I loop through the list in the views.py it show up in the terminal.
I'm using python3.3 and django 1.8.3
views.py :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views import generic
from . import models
from blog.models import Entry

class BlogIndex(generic.ListView):
    queryset = models.Entry.objects.published()
    template_name = "home.html"
    paginate_by = 3
    news_list = Entry.objects.filter(category='news')
    i = 0
    for x in news_list:
        i = i+1
        print(x.title,i)

A: You are trying to access news_list in the template when it is infact not present in the template.
You need to pass news_list in the context data. Override the get_context_data() and pass this variable.
class BlogIndex(generic.ListView):
    queryset = models.Entry.objects.published()
    template_name = "home.html"
    paginate_by = 3

    def get_context_data(self, **kwargs):
        context = super(BlogIndex, self).get_context_data(**kwargs)
        context['news_list'] = Entry.objects.filter(category='news') # pass 'news_list' in the context
        return context

Then in your template, you can use the normal for loop.
{% for news in news_list %}

    {{ news.title }}

{% endfor %}

Note: You don't need to convert the QuerySet to a list as it is already an iterable.

A: That's because in django you don't access lists, but querysets. Try:
context['news_list'] = Entry.objects.filter(category='news')

A: The queryset result can be used to iterate in django template. So there is no need to convert query set object into list. List is not iterable in django template though python does. You can use django-mptt is a premade solution, which should fit your problem quite good.


text:
Q: In pandas DataFrame, how can I store a specific value from a column into a variable, and then subsequently remove that value from the column? I'm sort of new to using pandas in Python for data visualization, and have this code so far:
import pandas as pd
data = pd.read_csv(r'/Users/ephemeralhappiness/Desktop/Packet/Fake Data.csv')
df = pd.DataFrame(data, columns=['A', 'B'])
print(df)

So I have created this DataFrame from reading Fake Data.csv with columns A and B. For example, how would I retrieve the 5th value of column A so I can store it into the variable. How would I remove the 5th value of column A?
I tried the following code for my first question:
print(df.iat(4,0))

In theory, this should return the fifth value of column A, but I get the following error:
TypeError: '_AtIndexer' object is not callable

Before/after picture but the 5th value removed from column A needs to be stored in a variable first

A: Please use square brackets [ for iat statement. For example print(df.iat[4,0]).

A: If I understood correctly, this might work:
a = df.iloc[4, 0]
df.iloc[4:,0] = df.iloc[4:,0].shift(-1)


text:
Q: Why is my ffmpeg stream failing? After 35-55 minutes, my ffmpeg stream fails with this error:

Here is the script I run to start my stream:
#! /bin/bash
python3 pre-run.py
VBR="500k"
FPS="30"
QUAL="superfast"

YOUTUBE_URL="rtmp://arn04.contribute.live-video.net/app"
YOUTUBE_KEY="stream_key"
VIDEO_SOURCE="${PWD}/bg.mp4"
AUDIO_ENCODER="aac"
  ffmpeg \
-stream_loop -1 \
-re \
-i "$VIDEO_SOURCE" \
-thread_queue_size 512 \
-stream_loop -1 \
-re \
-f concat -safe 0 -i <( for f in $PWD/input/*.wav; do echo "file '$f' "; done) \
-map 0:v:0 -map 1:a:0 \
-map_metadata:g 1:g \
-c:v libx264 -preset $QUAL -r $FPS -g $(($FPS *2)) -b:v $VBR -bufsize 3000k -maxrate $VBR \
-c:a $AUDIO_ENCODER -ar 44100 -b:a 128k -pix_fmt yuv420p \
-f flv $YOUTUBE_URL/$YOUTUBE_KEY


text:
Q: Unable to Insert data from DropDownListFor to Database I am using Dictionary to populate data into DropDownListFor. Now the problem is I am unable to fetch key on onchange event of DropDownListFor.
What I want is to select Schema on behalf of select client's KEY.
Controller:=
public ActionResult Index()
{
    DataComponents dcomponents = new Models.DataComponents();
    //Getting Data From Database to Dictionary
    dcomponents.clientName = getdata.Clients();
    dcomponents.schemaName = getdata.Schemas();
    return View(dcomponents);
}
public ActionResult Change(DataComponents dcomponents)
{
    //Select data on behalf of Client ID
    dcomponents.clientName = getdata.Clients();
    dcomponents.schemaName = getdata.Schemas(dcomponents.selectedClient);
    return View("Index",dcomponents);
}

Model =>
public class DataComponents
{
    public Dictionary<int,string> clientName { get; set; }
    public int selectedClient { get; set; }
    public Dictionary<int, string> schemaName { get; set; }
    public int selectedSchema { get; set; }
}

View =>

@Html.DropDownListFor(m => m.selectedClient,new SelectList(Model.clientName,"key","Value",Model.selectedClient), "Select Client", new { onchange = "document.location.href = '/Home/Change';" })

    @Html.DropDownListFor(m => m.selectedSchema, new SelectList(Model.schemaName, "key", "Value", Model.selectedClient), "Select Schema", new { onchange = "document.location.href = '/Home/Change';" }))

A: You need to get the data to the server. Either through a post, or through query strings. I've model things as a post.
You can see I wrapped the View information in a Form, and changed the event to submit the form on change.
public ActionResult Index()
{
    DataComponents dcomponents = new Models.DataComponents();
    //Getting Data From Database to Dictionary
    dcomponents.clientName = getdata.Clients();
    dcomponents.schemaName = getdata.Schemas();
    return View(dcomponents);
}
[HttpPost]
public ActionResult Change(DataComponents dcomponents)
{
    //Select data on behalf of Client ID
    dcomponents.clientName = getdata.Clients();
    dcomponents.schemaName = getdata.Schemas(dcomponents.selectedClient);
    return View("Index",dcomponents);
}

@using (Html.BeginForm("Change", "Home", FormMethod.Post))
{

        @Html.DropDownListFor(m => m.selectedClient,new SelectList(Model.clientName,"key","Value",Model.selectedClient), "Select Client", new { "this.form.submit();" })

        @Html.DropDownListFor(m => m.selectedSchema, new SelectList(Model.schemaName, "key", "Value", Model.selectedClient), "Select Schema", new { onchange = "this.form.submit();" }))

}


text:
Q: Eclipse RCP : How to show message dialog after editor loads? I am opening an editor from a view on click of a treenode. Now, when editor loads and controls are displayed to the user, I want to display a warning message dialog to the user based on certain values present on the editor.
I tried by putting the warning dialog at the end of createPartControl method of the editor. Dialog appears on double cliking the treenode as per the required functionality. But, the problem is that when the dialog appears, the controls on the editor are not yet visible. It's only when I close the dialog the editor controls are shown.
I want it to happen the other way around. i.e. The editor controls to show up first and then the warning dialog should appear. What changes should I do to achieve this effect?

A: You may want to call that MessageDialog in an asynchronous way, to leave the Editor the opportunity to complete itself, as suggested in this message.

show your warning dialog in an asyncExec() runnable would ensure that the editor's initialization all happens in the correct sequence.

So, something like (not tested) this code might do the trick:
getSite().getShell().getDisplay().asyncExec
    (new Runnable() {
        public void run() {
            MessageDialog.openWarning(getSite().getShell(),"wrong","no)
        }
    });
}

Some other examples in this MapEditor class, where a MessageDialog is displayed through an asyncExec which waits for the result:
PlatformGIS.syncInDisplayThread


text:
Q: Magento 2 static asset response code when static deployment is running When you are generating static content and you view a link to an asset for example
https://domain/static/version1234/frontend/Vendor/Theme/en_GB/mage/translate.js
If you view the file before it's been generated you see the following error

And a 404 response code is sent. Refresh after static content process is finished you see the asset and a 200 response code is sent. Does anyone know where the code that sends the  404 response code is set?

A: No sooner had I posted the question I finally figured this out.
The store is on default mode.
https://github.com/magento/magento2/blob/2.4.2/lib/internal/Magento/Framework/App/StaticResource.php#L163-L186
    /**
     * @inheritdoc
     */
    public function catchException(Bootstrap $bootstrap, \Exception $exception)
    {
        $this->getLogger()->critical($exception->getMessage());
        if ($bootstrap->isDeveloperMode()) {
            $this->response->setHttpResponseCode(404);
            $this->response->setHeader('Content-Type', 'text/plain');
            $this->response->setBody(
                $exception->getMessage() . "\n" .
                Debug::trace(
                    $exception->getTrace(),
                    true,
                    true,
                    (bool)getenv('MAGE_DEBUG_SHOW_ARGS')
                )
            );
            $this->response->sendResponse();
        } else {
            require $this->getFilesystem()->getDirectoryRead(DirectoryList::PUB)->getAbsolutePath('errors/404.php');
        }
        return true;
    }

So I'm hitting this part require $this->getFilesystem()->getDirectoryRead(DirectoryList::PUB)->getAbsolutePath('errors/404.php');
And checking errors/404.php
https://github.com/magento/magento2/blob/2.4.2/pub/errors/404.php#L11
$response = $processor->process404();
https://github.com/magento/magento2/blob/2.4-develop/pub/errors/processor.php#L209-L220
    /**
     * Process 404 error
     *
     * @return \Magento\Framework\App\Response\Http
     */
    public function process404()
    {
        $this->pageTitle = 'Error 404: Not Found';
        $this->_response->setHttpResponseCode(404);
        $this->_response->setBody($this->_renderPage('404.phtml'));
        return $this->_response;
    }

This part $this->_response->setHttpResponseCode(404);


text:
Q: How can I set my sidebar with a fixed width? I have a code: Codepen.io.

                     Brand

                                 Link

                                      Link

                                        Sub
                                        Sub longer

                                 Link

                                 Link

But I need to set fixed width left sidebar for all resolutions, except in mobile view I need to see like now (top menu with hamburger).
What I need to do?

A: Use a media query for Bootstrap's sm breakpoint and set min/max width in the "sidebar"...
@media (min-width: 768px) {
    aside.col-sm-3 {
        min-width: 200px;
        max-width: 200px;
    }
}

https://www.codeply.com/go/LsMGLozRq0

Also see: Bootstrap 4: responsive sidebar menu to top navbar


text:
Q: Stop for a couple of seconds a Progress Bar What I'm trying to accomplish:
I'd like to make a JFrame with multiple progress bars (JProgressBar) with different speeds.
The Problem
When the value of one progress bar is 25, 50 or 75, it's supposed to stop the current progress bar for 2 seconds.
As of now however, Thread.sleep() will stop the entire app.
Timer timer;

ActionListener listener;
listener = new ActionListener() {
    int counter = 0;
    int delta = 1;
    int min = 0;
    int max = 100;

    public void actionPerformed(ActionEvent ae) {
        counter += delta;
        if (jRadioButton1.isSelected()) {
            if (counter < min || counter > max) {
                delta *= -1;
            }
            counter = Math.min(max, Math.max(min, counter));
            jjProgressBar.setValue(counter);
            jjProgressBar2.setValue(counter);
            jjProgressBar3.setValue(counter);
            if (jProgressBar.getValue() == 25 || jProgressBar.getValue() == 0 || jProgressBar.getValue() == 50 || jProgressBar.getValue() == 75 || jProgressBar.getValue() == 100) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Sim1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
};
timer = new Timer(100, listener);
timer.start();

A: You can always multithread your progress bars and Thread.sleep() them individually.
Thread.sleep() does not really make sense in your particular context, since it's only one monolithic application controlling what should be an MVC/multithreading application.


text:
Q: PostgreSQL check if column A is null then B must be null I am new to PostgreSQL checks.
I need to add a check constraint that specifies if column A is null, then B must be null
But both can be NOT NULL
In probably more understandable words, if a row is inserted, both A and B columns has to be populated, there can't be a row with A populated if B is not populated, or the other way around.
But, both CAN be null in the same row
Surprisingly I am struggling to find the answer to this. I was easily able to add constraints like A must be greater than B, or below 0, or both columns must be null (if that even makes sense), and more.
However, I can't find the answer and the correct syntax for this.
Any help here?
Thanks a lot!

A: This can be achieved by using the handy function num_nulls(). You want that either both columns are not null (number of nulls = 0) or both are null (number of nulls = 2)
alter table the_table
   add constraint check_nulls_in_a_and_b
   check (num_nulls(a,b) in (0,2))


text:
Q: Kubuntu - Are there 'workspaces' in Kubuntu and how can I switch between them with shortcuts? I used Ubuntu before and now I migrated to Kubuntu. And I'd like to know if there are 'workspaces' in Kubuntu and how I can switch between them with shortcuts.

A: The only difference between Ubuntu and Kubuntu is that Ubuntu uses Unity as the Desktop Environment and Kubuntu uses KDE. Linux allows the user to choose which Desktop Environment to use, you can install Unity or Cinnamon or LXDE or whatever you want on your Kubuntu.
That said, yes indeed KDE (which is what you are using) offers workspaces. You should be able to control their behavior by going into the settings app (or running systemsettings from a terminal) and then
systemsettings -> workspace behavior -> virtual desktops


text:
Q: Change two-dimentional array's certain index value javascript I'm trying to put certain value in certain two dimensional array but it appends different.
Here is my code.

const arr = []
const tdArr = []

arr.length = 5
arr.fill('p', 0)

for(let i = 0; i < arr.length; i++){
  tdArr.push(arr)
}

const makeRnd = (min, max) => {
  min = Math.ceil(min)
  max = Math.floor(max)
  return Math.floor(Math.random() * (max - min)) + min
}

let firstRnd = makeRnd(0, 4)
let secRnd = makeRnd(0, 4)
let tdArr2 = [...tdArr]
tdArr2[firstRnd][secRnd] = 'q'

console.log(tdArr2)

I don't know why not (for example) tdArr2[0][1] is not changed but also change all second value of arrays.
It seems easy one but cannot google it :(
Thanks for help!

A: Use tdArr.push([...arr]) in the for loop instead of tdArr.push(arr).

const arr = []
const tdArr = []

arr.length = 5
arr.fill('p', 0)

for(let i = 0; i < arr.length; i++){
  tdArr.push([...arr])
}

const makeRnd = (min, max) => {
  min = Math.ceil(min)
  max = Math.floor(max)
  return Math.floor(Math.random() * (max - min)) + min
}

let firstRnd = makeRnd(0, 4)
let secRnd = makeRnd(0, 4)
let tdArr2 = [...tdArr]
tdArr2[firstRnd][secRnd] = 'q'

console.log(tdArr2)

A: As mentioned by @Dave Newton every element of tdArr array is the same one which is a reference to arr so when you change a value of arr all elements of tdArr are changes as they all reference the same array.
I would push an array literal instead of creating an array and then push it or create a copy like mentioned in the answer above and push the copy on each iteration.
tdArr.push(['p']);