text:
Q: PHP function returning thumbnail, not actual image This is kind of a follow-up to my previous PHP question. After ALFEaton helped me with the code, I had some additional changes to make to add extra functionality. However, I am having one small problem, and I can't seen to figure it out. The code is fairly well commented, so it should be easy to read:
<?php
class Functions {
/**
 * Allows you to save two copies of an image;
 * the resized copy, and the actual copy
 *
 * @param $file - URL to get images from */
public function resize_image($file) {
    // Gets the file name
    $path_parts = pathinfo($file);
    $filename_thumb = 'thumbs/' . $path_parts['filename'] . '.png';
    $filename = 'gallery/' . $path_parts['filename'] . '.png';

    if (!file_exists($filename_thumb)) {
        //Creates an image from the URL
        $image = imagecreatefrompng($file);

        //Defining the desired thumbnail size, and the current one
        $thumb_size = 150;
        $width = imagesx($image);
        $height = imagesy($image);

        //Defining image aspect ratio
        $original_aspect = $width / $height;
        $thumb_aspect = $thumb_size / $thumb_size;

        if ($original_aspect >= $thumb_aspect) {
            // If image is wider than thumbnail (in aspect ratio sense)
            $new_height = $thumb_size;
            $new_width = $width / ($height / $thumb_size);
        } else {
            // If the thumbnail is wider than the image
            $new_width = $thumb_size;
            $new_height = $height / ($width / $thumb_size);
        }

        $thumb = imagecreatetruecolor($thumb_size, $thumb_size);

        // Resize and crop
        imagecopyresampled($thumb, $image, 0 - ($new_width - $thumb_size) / 2, // Center the image horizontally
        0 - ($new_height - $thumb_size) / 2, // Center the image vertically
        0, 0, $new_width, $new_height, $width, $height);
        imagepng($thumb, $filename_thumb, 9);
    } else {
        if (!file_exists($filename)) {
            $image_large = imagecreatefrompng($file);
            imagepng($image_large, $filename, 9);
        } else {
            // Do Nothing
        }
    }
}

/**
 * Adds required HTML nodes to index.php
 *
 * @author AlfEaton from Stack Overflow */
public function getImages() {
    //Returns the index page
    $doc = new DOMDocument;
    libxml_use_internal_errors(true);
    $doc -> loadHTMLFile('http://hathorarts.deviantart.com/gallery/');
    libxml_use_internal_errors(false);

    //Selects the linked thumbnail images
    $xpath = new DOMXPath($doc);
    $nodes = $xpath -> query('//a[@class="thumb"]');

    // Get the URL for each actual image, and build the links
    $output = new DOMDocument;
    foreach ($nodes as $i => $node) {
        $source_pre = $node -> getAttribute('data-super-img');
        $source = str_replace("/PRE", "", $source_pre);
        $this -> resize_image($source);

        $path_parts = pathinfo($source);
        $path_parts_filename = $path_parts['filename'];
        $filename = 'thumbs/' . $path_parts_filename . '.png';
        $filename_original = 'gallery/' . $path_parts_filename . '.png';

        $image_thumb = $output -> createElement('img');
        $image_thumb -> setAttribute('class', 'image_thumb');
        $image_thumb -> setAttribute('src', $filename);

        $link = $output -> createElement('a');
        $link -> setAttribute('href', $filename_original);
        $link -> setAttribute('rel', 'lightbox-gallery');
        $link -> appendChild($image_thumb);

        $output -> appendChild($link);
    }
    print $output -> saveHTML();
}
}
?>

The thumbnail part works fine. But the $link href attribute returns the thumbnail. This is my file set-up for this project -

With my PHP functions in the functions.php file.
The code outputs the actual images and thumbnails, but it doesn't display the actual image, just the thumbnail.

A: OK, this may sound like a silly question, but are you certain you are creating the full size images with these functions? Your resize_image function only creates the full size image if the thumbnail file exists - it doesn't create it in your thumbnail routine:
Your code:
if (!file_exists($filename_thumb)) {
    //Creates an image from the URL
    $image = imagecreatefrompng($file);

    //Defining the desired thumbnail size, and the current one
    //*and carry on with your thumbnail creation*
} else {
    if (!file_exists($filename)) {
        $image_large = imagecreatefrompng($file);
        imagepng($image_large, $filename, 9);
}

Should you be putting the last line - imagepng($image_large, $filename, 9); in the thumbnail routine also?
Suggested:
if (!file_exists($filename_thumb)) {
    //Creates an image from the URL
    $image = imagecreatefrompng($file);
    imagepng($image, $filename, 9);

    //Defining the desired thumbnail size, and the current one
    //*and carry on with your thumbnail creation*
} else {
    if (!file_exists($filename)) {
        $image_large = imagecreatefrompng($file);
        imagepng($image_large, $filename, 9);
}


text:
Q: Crunchbang: Can't use simple-scan without administrator rights I'm running the latest version of Crunchbang 64-bit on a Dell E5510 notebook.

Installing my printer and scanner worked fine - I just used an existing Ubuntu tutorial. However, scanning without starting Simple-Scan as sudo produces an error message. My main account is listed as part of the group scanner, according to the output of less /etc/group. To my limited knowledge, this should suffice, shouldn't it? What more steps are necessary in order to run simple-scan without sudo?

Thanks in advance.

A: I found similar question asked on SU. Also this Ubuntu how-to could be useful. And there's a bug regarding permissions to access a scaner.
Summarizing this sources:

*

*Add saned to the group which owns your scanner device: sudo adduser saned scanner. Note that device may be owned by different group, so use sane-find-scanner to determine the device and ls -al /dev/bus/usb/XXX/XXX to identify the group. Then add saned to this group.

There's not very secure way to run saned as root.

*

*Add this line to /etc/rc.local (before exit 0): chmod -R a+w /dev/bus/usb

*Edit/create the following file: /etc/xinetd.d/saned:
service saned
{
socket_type = stream
server = /usr/sbin/saned
protocol = tcp
user = root
group = root
wait = no
disable = no
}

*

*Edit /etc/default/saned:
RUN_AS_USER=root
and
RUN=yes

*Reboot.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does this function fail if there is any formatting in the text? [in IE8] I am using the method below to search for a string in a web page.  It matches plain text; but, it fails in the following context:
 I am searching for text

If I search for "am searching" it will match.. But if I search for "I am searching" it does not match.  Below is the code I am using:
function search(text)
{
    if (document.body.createTextRange)
    {
        var textRange = document.body.createTextRange();
        while (textRange.findText(text))
        {
            textRange.execCommand("BackColor", false, "yellow");
            textRange.collapse(false);
        }
    }
}

here is the fiddle.  It is not working in IE8.
Thanks

A:

Should work: in short use jquery


text:
Q: How to extend tappable area to whole frame in SwiftUI (iOS14)? I am trying to make a VGrid with Swift 5.3, but the only tappable area is the upper part of the rectangle. Other answers suggest contentShape, but I am unable to make that work either. How to make the whole frame tappable? Code below:
import SwiftUI
import Combine
import Foundation

struct Item: Codable, Identifiable, Equatable {
    var id: Int
    var name: String
}

final class UserData: ObservableObject {
    @Published var items = Bundle.main.decode([Item].self, from: "data.json")
}

struct ContentView: View {
    @State var itemID = Item.ID()
    @StateObject var userData = UserData()
    let columns = [
        GridItem(.adaptive(minimum: 118))
    ]

    var body: some View {
        NavigationView {
            ScrollView {
                LazyVGrid(columns: columns) {
                    ForEach(userData.items) { item in
                        NavigationLink(destination: ContentDetail(itemID: item.id - 1)) {
                            ContentRow(item: item)
                        }
                    }
                }
            }
        }
    }
}

struct ContentRow: View {
    var item: Item

    var body: some View {
        VStack {
            GeometryReader { geo in
                ZStack{
                    VStack(alignment: .trailing) {
                        Text(item.name)
                            .font(.caption)
                    }
                }
                .padding()
                .foregroundColor(Color.primary)
                .frame(width: geo.size.width, height: 120)
                .border(Color.primary, width: 2)
                .cornerRadius(5)
                .contentShape(Rectangle())
            }
        }
    }
}

struct ContentDetail: View {
    @State var itemID = Item.ID()
    @StateObject var userData = UserData()

    var body: some View {
            Text(userData.items[itemID].name)
    }
}

extension Bundle {
    func decode<T: Decodable>(_ type: T.Type, from file: String, dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) -> T {
        guard let url = self.url(forResource: file, withExtension: nil) else {
            fatalError("Failed to locate \(file) in bundle.")
        }

        guard let data = try? Data(contentsOf: url) else {
            fatalError("Failed to load \(file) from bundle.")
        }

        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = dateDecodingStrategy
        decoder.keyDecodingStrategy = keyDecodingStrategy

        do {
            return try decoder.decode(T.self, from: data)
        } catch DecodingError.keyNotFound(let key, let context) {
            fatalError("Failed to decode \(file) from bundle due to missing key '\(key.stringValue)' not found – \(context.debugDescription)")
        } catch DecodingError.typeMismatch(_, let context) {
            fatalError("Failed to decode \(file) from bundle due to type mismatch – \(context.debugDescription)")
        } catch DecodingError.valueNotFound(let type, let context) {
            fatalError("Failed to decode \(file) from bundle due to missing \(type) value – \(context.debugDescription)")
        } catch DecodingError.dataCorrupted(_) {
            fatalError("Failed to decode \(file) from bundle because it appears to be invalid JSON")
        } catch {
            fatalError("Failed to decode \(file) from bundle: \(error.localizedDescription)")
        }
    }
}

And the JSON part:
[
    {
        "id": 1,
        "name": "Example data",
    },
    {
        "id": 2,
        "name": "Example data 2",
    }
]

Any help is appreciated. Could this be a bug in SwiftUI?

A: Try putting the contentShape on the outermost VStack of ContentRow. You need to put the contentShape on the view that is expanding to fill its parent (or on its parent), which in your case I think is the GeometryReader. The views inside the GeometryReader all shrink to fit their contents, so your contentShape rectangle doesn't help there.

A: You could simply remove the GeometryReader since you set the height anyway:
struct ContentRow: View {
    var item: Item

    var body: some View {
        VStack {
            ZStack{
                VStack(alignment: .trailing) {
                    Text(item.name)
                        .font(.caption)
                }
            }
            .padding()
            .foregroundColor(Color.primary)
            .frame(width: 120, height: 120)
            .border(Color.primary, width: 2)
            .cornerRadius(5)
            .background(Color.red)
        }
    }
}


text:
Q: Defining subclasses with common import methods I have been building a python image processing module for working with images related to laser beams.  The images differ in their content (laser beam image, scattered light image, etc.) and the file types differ based on the instrument used to capture the images.  But any one of the file types may contain any one of the content types.
The structure of the module currently is

*

*Parent Class: contains methods common to all types of content

*

*Child Class 1: contains methods useful for content type 1

*

*Grandchild Class 1: only an __init__() statement for importing file type a

*Grandchild Class 2: only an __init__() statement for importing file type b

*Child Class 2: contains methods useful for content type 2

*

*Grandchild Class 1: only an __init__() statement for importing file type a

*Grandchild Class 2: only an __init__() statement for importing file type b

The issue is that the grandchildren classes are essentially identical because they contain code for importing different types of files which may contain content from either child class.
Is there a more elegant/pythonic way to do this?

I should note that the different file types require different pre-processing, so the solution is not as simple as using e.g. PIL which can recognize the standard image file extensions.

A: Use 2 mixin classes:
class FileTypeAMixin:
    <logic>

class FileTypeBMixin:
    <logic>

class Parent:
    <logic>

class Child1(Parent):
    <logic>

class Child2(Parent):
    <logic>

class Child1GrandChild1(FileTypeAMixin, Child1):
    <logic>

class Child1GrandChild2(FileTypeBMixin, Child1):
    <logic>

class Child2GrandChild1(FileTypeAMixin, Child2):
    <logic>

class Child2GrandChild2(FileTypeBMixin, Child2):
    <logic>

EDIT
As pointed out by the OP, it is recommended to always put the mixins before the parent classes, in order to prevent strange MRO behavior when calling super() in case each of the parent classes/mixins have the same methods implemented.


text:
Q: SwiftUI - Custom Swipe Actions In List How can I use custom Swipe Actions in SwiftUI?
I tried to use the UIKit Framework to get these working in SwiftUI. But that doesn't work for me.
import SwiftUI
import UIKit

    init() {
        override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
            let important = importantAction(at: indexPath)
            return UISwipeActionsConfiguration(actions: [important])
        }
        func importantAction(at indexPath: IndexPath) -> UIContextualAction {
            let action = UIContextualAction(style: .normal, title: "Important") { (action, view, completion) in
                print("HI")
            }
            action.backgroundColor = UIColor(hue: 0.0861, saturation: 0.76, brightness: 0.94, alpha: 1.0) /* #f19938 */
            action.image = UIImage(named: "pencil")
            return action
        }
    }

struct TestView: View {

      NavigationView {
               List {
                    ForEach(appointmentsViewModel.appointments.identified(by: \.id)) { appointment in Row_Appointments(appointment: appointment)
                }.onDelete(perform: delete)
            }
        }
    }
}

A: iOS 15+
In iOS 15 we can finally use native Swipe Actions:
func swipeActions<T>(edge: HorizontalEdge = .trailing, allowsFullSwipe: Bool = true, content: () -> T) -> some View where T : View

They can be attached to the ForEach container just like onMove or onDelete:
List {
    ForEach(appointmentsViewModel.appointments.identified(by: \.id)) { appointment in
        Row_Appointments(appointment: appointment)
    }
    .swipeActions(edge: .trailing) {
        Button {
            print("Hi")
        } label: {
            Label("Important", systemImage: "pencil")
        }
    }
}

A: Based on Michał Ziobro answer using Introspect to simplify table view delegate setup.
Note that this will override the table view delegate and might BREAK some of the existing table view behaviours. While things such as header hight can be fixed by adding the method to custom delegate yourself, other might not be fixable.
struct ListSwipeActions: ViewModifier {

    @ObservedObject var coordinator = Coordinator()

    func body(content: Content) -> some View {

        return content
            .introspectTableView { tableView in
                tableView.delegate = self.coordinator
            }
    }

    class Coordinator: NSObject, ObservableObject, UITableViewDelegate {

        func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
            return .delete
        }

        func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

            let archiveAction = UIContextualAction(style: .normal, title: "Title") { action, view, completionHandler in
                // update data source
                completionHandler(true)
            }
            archiveAction.image = UIImage(systemName: "archivebox")!
            archiveAction.backgroundColor = .systemYellow

            let configuration = UISwipeActionsConfiguration(actions: [archiveAction])

            return configuration
        }
    }
}

extension List {
    func swipeActions() -> some View {
        return self.modifier(ListSwipeActions())
    }
}

A: It is able to be done in the way something like this:
           List {
                ForEach(items) { (item) in

                    Text("\(item.title)")
                }
                .onDelete(perform: self.delete)
            }.swipeActions()

Then you need to add this swipeActions() modifier
struct ListSwipeActions: ViewModifier {

    @ObservedObject var coordinator = Coordinator()

    func body(content: Content) -> some View {

        return content
            .background(TableViewConfigurator(configure: { tableView in
                delay {
                    tableView.delegate = self.coordinator
                }
            }))
    }

    class Coordinator: NSObject, ObservableObject, UITableViewDelegate {

        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            print("Scrolling ....!!!")
        }

        func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
            return .delete
        }

        func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

            let isArchived = false
            let title = isArchived ? NSLocalizedString("Unarchive", comment: "Unarchive") : NSLocalizedString("Archive", comment: "Archive")

            let archiveAction = UIContextualAction(style: .normal, title: title, handler: {
                (action, view, completionHandler) in

                // update data source
                completionHandler(true)
            })
            archiveAction.title = title
            archiveAction.image = UIImage(systemName: "archivebox")!
            archiveAction.backgroundColor = .systemYellow

            let configuration = UISwipeActionsConfiguration(actions: [archiveAction])

            return configuration
        }
    }
}

extension List {

    func swipeActions() -> some View {
        return self.modifier(ListSwipeActions())
    }
}

And have TableViewConfigurator that searches for table view behind the List
struct TableViewConfigurator: UIViewControllerRepresentable {

    var configure: (UITableView) -> Void = { _ in }

    func makeUIViewController(context: Context) -> UIViewController {

        UIViewController()
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {

        let tableViews = UIApplication.nonModalTopViewController()?.navigationController?.topViewController?.view.subviews(ofType: UITableView.self) ?? [UITableView]()

        for tableView in tableViews {
            self.configure(tableView)
        }
    }
}

A: If your deployment target is iOS 15 (or newer), then you can use the swipeActions modifier to customize the swipe actions of a list item.
This also applies to watchOS 8 and macOS 12.
These operating systems will be released in late 2021.
Prior to the late 2021 version of SwiftUI, there is no support for custom swipe actions for List items.
If you need to target an older version, you would probably be better off implementing a different user interface, like adding a toggle button as a subview of your list item, or adding a context menu to your list item.

A: Delighted to see that iOS 15 brings the long awaited .swipeActions view modifier to List in SwiftUI with an easy to use API.
List {
    ForEach(store.messages) { message in
        MessageCell(message: message)
            .swipeActions(edge: .leading) {
                Button { store.toggleUnread(message) } label: {
                    if message.isUnread {
                        Label("Read", systemImage: "envelope.open")
                    } else {
                        Label("Unread", systemImage: "envelope.badge")
                    }
                }
            }
            .swipeActions(edge: .trailing) {
                Button(role: .destructive) {
                    store.delete(message)
                } label: {
                    Label("Delete", systemImage: "trash")
                }
                Button { store.flag(message) } label: {
                    Label("Flag", systemImage: "flag")
                }
            }
        }
    }
}

Actions appear in the order listed, starting from the originating edge working inwards.
The example above produces:

Note that swipeActions override the onDelete handler if provided that is available on ForEach
Read more in Apple's developer docs

A: I wanted the same and have now the following implementation.
The SwipeController checks when to execute a swipe action and performs the SwipeAction, for now you can add your swipe actions under the print lines in the executeAction function. But it is better make an abstract class from this.
Then in the SwipeLeftRightContainer struct we have most of the logic in the DragGesture. What it does is while your dragging its gonna change the offset and then make calls to the SwipeController to see if the threshold for swipe left or right are reached. Then when you finish the dragging it will come into the onEnded callback of the DragGesture. Here we will reset the offset and let the SwipeController decide to execute an action.
Keep in mind lot of the variables in the view are static for an iPhone X so you should change them to what fits best.
Also what this does is creating an action for left and right swipe, but you can adjust it to your own use ofcourse.
import SwiftUI

/** executeRight: checks if it should execute the swipeRight action
    execute Left: checks if it should execute the swipeLeft action
    submitThreshold: the threshold of the x offset when it should start executing the action
*/
class SwipeController {
    var executeRight = false
    var executeLeft = false
    let submitThreshold: CGFloat = 200

    func checkExecutionRight(offsetX: CGFloat) {
        if offsetX > submitThreshold && self.executeRight == false {
            Utils.HapticSuccess()
            self.executeRight = true
        } else if offsetX < submitThreshold {
            self.executeRight = false
        }
    }

    func checkExecutionLeft(offsetX: CGFloat) {
        if offsetX < -submitThreshold && self.executeLeft == false {
            Utils.HapticSuccess()
            self.executeLeft = true
        } else if offsetX > -submitThreshold {
            self.executeLeft = false
        }
    }

    func excuteAction() {
        if executeRight {
            print("executed right")
        } else if executeLeft {
            print("executed left")
        }

        self.executeLeft = false
        self.executeRight = false
    }
}

struct SwipeLeftRightContainer: View {

    var swipeController: SwipeController = SwipeController()

    @State var offsetX: CGFloat = 0

    let maxWidth: CGFloat = 335
    let maxHeight: CGFloat = 125
    let swipeObjectsOffset: CGFloat = 350
    let swipeObjectsWidth: CGFloat = 400

    @State var rowAnimationOpacity: Double = 0
    var body: some View {
        ZStack {
            Group {
                HStack {
                    Text("Sample row")
                    Spacer()
                }
            }.padding(10)
            .zIndex(1.0)
            .frame(width: maxWidth, height: maxHeight)
            .cornerRadius(5)
            .background(RoundedRectangle(cornerRadius: 10).fill(Color.gray))
            .padding(10)
            .offset(x: offsetX)
            .gesture(DragGesture(minimumDistance: 5).onChanged { gesture in
                withAnimation(Animation.linear(duration: 0.1)) {
                    offsetX = gesture.translation.width
                }
                swipeController.checkExecutionLeft(offsetX: offsetX)
                swipeController.checkExecutionRight(offsetX: offsetX)
            }.onEnded { _ in
                withAnimation(Animation.linear(duration: 0.1)) {
                    offsetX = 0
                    swipeController.prevLocX = 0
                    swipeController.prevLocXDiff = 0
                    self.swipeController.excuteAction()
                }
            })
            Group {
                ZStack {
                    Rectangle().fill(Color.red).frame(width: swipeObjectsWidth, height: maxHeight).opacity(opacityDelete)
                    Image(systemName: "multiply").font(Font.system(size: 34)).foregroundColor(Color.white).padding(.trailing, 150)
                }
            }.zIndex(0.9).offset(x: swipeObjectsOffset + offsetX)
            Group {
                ZStack {
                    Rectangle().fill(Color.green).frame(width: swipeObjectsWidth, height: maxHeight).opacity(opacityLike)
                    Image(systemName: "heart").font(Font.system(size: 34)).foregroundColor(Color.white).padding(.leading, 150)
                }
            }.zIndex(0.9).offset(x: -swipeObjectsOffset + offsetX)
        }
    }

    var opacityDelete: Double {
        if offsetX < 0 {
            return Double(abs(offsetX) / 50)
        }
        return 0
    }

    var opacityLike: Double {
        if offsetX > 0 {
            return Double(offsetX / 50)
        }
        return 0
    }
}

struct SwipeListView: View {

    var body: some View {
        ScrollView {
            ForEach(0..<10) { index in
                SwipeLeftRightContainer().listRowInsets(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10))
            }
        }
    }

}

struct SwipeLeftRight_Previews: PreviewProvider {
    static var previews: some View {
        SwipeListView()
    }
}

A: Now with IOS 15 , Swift 5.5 we can add a Swipe action like this
struct ContentView: View {
    @State private var total = 0

    var body: some View {
        NavigationView {
            List {
                ForEach(1..<100) { i in
                    Text("\(i)")
                        .swipeActions(edge: .leading) {
                            Button {
                                total += i
                            } label: {
                                Label("Add \(i)", systemImage: "plus.circle")
                            }
                            .tint(.indigo)
                        }
                        .swipeActions(edge: .trailing) {
                            Button {
                                total -= i
                            } label: {
                                Label("Subtract \(i)", systemImage: "minus.circle")
                            }
                        }
                }
            }
            .navigationTitle("Total: \(total)")
        }
    }
}


text:
Q: Loop through variables in Dask using Machine Learning Good afternoon.
I am encountering a slight hiccup in Dask. I'm fairly new to Dask (in Python) and I'd like to run parallelized ML models using pure Dask (as opposed to dask-ml) based on the variable named 'class'. I wish to know what the predicted outcome of the model will be as I vary feature1 (as, in my data, I know this is the most significant one). I run my computing on a 4-node cluster and save all the predicted for all classes in predicted_all.
Here's an example of my pandas data df:
+-------+--------+-------------+-------------+---+-------------+
| class | target |  feature1   |  feature2   | … |  feature10  |
+-------+--------+-------------+-------------+---+-------------+
| A     |      5 | 97.19859896 | 816.6842211 | … | 0.54895439  |
| A     |      6 | 46.09606585 | 784.3270075 | … | 8.251889349 |
| A     |     43 | 17.65188263 | 549.5501609 | … | 13.50763389 |
| A     |      2 | 98.85817622 | 708.1968399 | … | 7.621150619 |
| A     |     56 | 88.01917025 | 613.0401243 | … | 6.000443628 |
| B     |      4 | 70.80513786 | 906.0185026 | … | 19.41657943 |
| B     |     78 | 93.80801173 | 891.289798  | … | 8.501099853 |
| B     |      7 | 46.63101139 | 483.0638367 | … | 3.875892614 |
| B     |      1 | 67.5788966  | 743.5923161 | … | 8.671806546 |
| B     |      0 | 90.90392867 | 109.8205978 | … | 17.70970394 |
| …     |        | …           | …           | … | …           |
| Z     |     89 | 58.424834   | 794.9165579 | … | 17.51302389 |
| Z     |    854 | 58.21094669 | 714.8873807 | … | 3.334251242 |
| Z     |     25 | 75.5155099  | 61.59911771 | … | 8.507249536 |
| Z     |     90 | 47.13722692 | 861.3884932 | … | 11.95500215 |
| Z     |     52 | 9.824626526 | 528.1958297 | … | 10.10468804 |
+-------+--------+-------------+-------------+---+-------------+

df is a pandas dataframe onto which I'd like to run a loop so that dask parallelizes the work on each node whilst using pandas dataframe.
As per the Dask tutorials, I do as follows:
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression

classes = ['ABC...Z']
predicted_all = pd.DataFrame()

def linearmodel(class): #application of linear regression on data

    global predicted_all
    df_oneClass = df[df['class'] == class].drop(['class'], axis=1)
    df_y = pd.DataFrame(df_oneClass['target'])
    df_X = df_oneClass.drop(['target'], axis=1)

    model = LinearRegression()
    model.fit(df_X, df_y)

    X_predict = [] ## range of feature1 values I'd like to know the forecast outcome for
    y_predict = model.predict(X_predict)
    predicted_all = pd.concat([predicted_all, y_predict], axis = 0

results = [delayed(linearmodel)(class) for class in classes]
resultsDask = compute(*results, get=dask.multiprocessing.get)

As per MRocklin's suggestion, I did a re-write and I focus on getting the Mean Absolute Errors of each class iteration and create a tuple. My function is now as follows:
def linearmodel(class): #application of linear regression on data

    df_oneClass = df[df['class'] == class].drop(['class'], axis=1)
    df_y = pd.DataFrame(df_oneClass['target'])
    df_X = df_oneClass.drop(['target'], axis=1)

    model = LinearRegression()
    model.fit(df_X, df_y)

    y_predict = model.predict(X_predict)
    mae = mean_absolute_error(df_y, y_predict)

    return (class, mae)

results = [delayed(linearmodel)(class) for class in classes]
resultsDask = compute(*results, get=dask.multiprocessing.get)

Unfortunately, the work is not parallelized and predicted_all is empty. Any clues as to why please?
Thanks for taking the time to read this and any help or pointers are more than welcome.
Regards,
Christian

A: I recommend not using global state and instead use functions that return values directly.


text:
Q: Possible to have a statement in stored procedure outside of current transaction? During a series of statements in my stored procedure I wish to log an entry by inserting a record. That record needs to survive even if the overall SP ends up rolling back.
Is this possible?

A: Declare the log table to be ENGINE=MyISAM.


text:
Q: PHP - Submitting Form I posted earlier about a problem that I had with sending an email to the designated address.
I found out that I had to setup an email server. I installed WAMP and then I had to setup a SMTP server, which I downloaded from softstack.com.
The previous error is gone, but now I have this error:

Warning: mail(): SMTP server response: 550 Invalid recipient:
  testing@testing.com in C:\wamp\www\process.php on line 56

Code on line 56:
    if (mail($to, $subject, $message)):
        $msg = "Thanks for filling out our form";
    else:
        $msg = "Problem sending the message";
    endif; // mail form data

I have seen other threads related to this which suggest to use phpEmailer, but I am following a tutorial and for don't have a clue why it isn't working.

A: This is an issue with your mail server, not with your PHP installation. Typically your ISP will block you from delivering mail outside of your local domain (in this case, your localhost). WAMP/your SMTP server is not configured nor likely available as a relay server (try using another known and configured SMTP server instead of your local server)

A: If you check here: http://www.serversmtp.com/en/smtp-error
At 550 error it says:

It usually defines a non-existent email address on the remote side.

Maybe you should try testing by using one of your own email addresses.


text:
Q: Post SQL data to Angular View with NodeJS I'm having a difficult time posting data retrieved from a server using mysql with node. I have connected to my db successfully, and I can return the data I want by console logging it to the CLI when running "node server.js". However, I'm not sure how to post this data to my Angular view. No problem console logging, but this doesn't help me get data to the application.
For the moment, I'm just trying to get the data to index.html, which is my primary view and holds my ng-view portion for Angular routing. I'm probably missing something obvious bc I'm new to NodeJS.
// MODULES

var express = require('express');

var app = express();

var port = process.env.PORT || 3000;

var mysql = require('mysql');

var serveStatic = require('serve-static');

var bodyParser = require('body-parser');

var source = __dirname + '/public/views/index.html';

app.use(serveStatic(__dirname, {'index': ['index.html']}));

app.route('/*')
  .get(function(req, res) {

    res.sendFile(source);
  });

var data;

var connection = mysql.createConnection({
    host     : 'thehostdb',
    user     : 'username', // credentials correct, connection works
    password : 'pw',
    database : 'db',
    port: '3306'
});

connection.query('SELECT * from poemTable', function(err, rows, fields) {
    if (!err) {

        data = JSON.stringify(rows);

        setDataValue(data);

}
    else {
        console.log('Error while performing Query:', err);
    }
});

function setDataValue(value) {

    data = value;

    console.log(data); //Where the data logs
}

app.listen(port, function () {
    console.log('Example app listening on port' + port + '!')
})

A: You have to understand what this code does, and how nodejs and angular are supposed to work together. Angular is served to the client and then rendered by the clients browser. So if you want to inject data you have to fetch it. So in your angular app when the controller starts make an api call, and in your server create a new route:
app.get('/data', function(req, res, next) {
    connection.query(..., function(err, rows, fields) {
        res.json(rows);
    });
});

Make sure you understand node and it's async nature, what is event loop and how it works and what is callback hell, also I would check out promises and other tutorials on nodeschool.io, it's a great place to start with node :)


text:
Q: when password and username match in DB, Error show up? when write anything in form and click Enter button, there is no error, but when i write the username and password correct the error show up
i tried echo "$_POST['username']"; // print username if username doesn't match ?
Error:
Notice: Undefined index: username in ..
Notice: Undefined index: password in ..
this is my form
<form action="2.php" method="post">

    Username
    <input type="text" name="username" />

    Password
    <input type="password" name="password" />

    <input type="submit" value="Enter"  />

</form>

and this my second page
<?php
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);

    $connection = mysql_connect('localhost', 'root', '');
    if (!$connection){
        die('Could not connect');
        exit;
    }
    mysql_select_db('dbName') or die( "Unable to select database");

    $query = "SELECT * FROM admin WHERE username = '$username'";

    $result = mysql_query($query) or die(mysql_error());

    $num = mysql_num_rows($result); // number of rows

    if ($num > 0){
    $i = 0;
    while ($i < $num){

        $row = mysql_fetch_array($result);

        if ( ($password) == $row['password'] && ($username) == $row['username'] ){

            header('location:2.php');

            $_SESSION['sessionname'] = $username;
            $_SESSION['sessionpass'] = $password;
        }

        elseif ( ($password) != $row['password'] && ($username) == $row['username'] ) {
            echo "Wrong Password Click Here";

        }

        $i++;
        }
    }else {
        echo "Username  $_POST[username] invalid ! Click Here ";

        }
    ?>

A: There is no reason to assign the username and password variables in the way you did. Simply assign the post data to the variables as you normally would with a session.


text:
Q: How can i prioritize pending jobs in Quartz that don't have same fire time? Quartz has a nice feature of trigger priority which allows to order triggers with identical fire time. (This is documented and covered by a question too).
How can I prioritize all pending jobs, not only those with identical fire time?
(I am fully aware this can lead to starvation of low priority jobs if higher-prioritized jobs keep coming in.)

A: There is no API for this, however it looks possible to 'hack' without changing Quartz code.
It seems sufficient to override RAMJobStore.acquireNextTriggers (if using RAMJobStore of course) properly (e.g. call super implementation with big maxCount, reorder results on priority, releaseAcquiredTrigger() on all except first originalMaxCount).


text:
Q: VBA click at element in IE I can't click on an element in the screen, it's not a button but works like one. I have successfully located it through the web inspector (I think) but I can't figure out the reason of why isn't working... Previously in my code I used the same code for clicking in a "Log in" button and it worked perfectly. Here it is the code:
    Set objCollection = IE.document.getelementsbytagname("div")
    For Each elem In objCollection
        If IsObject(IE.document.getElementsByClassName("btn-group")) Then 'Scratchpad button clicking
            If IsObject(IE.document.getElementsByClassName("pull-left fang-button fang-button-subtle no-margin ng-binding")) Then
                Debug.Print "found it"
                elem.Click
                Exit For
            End If
        End If
    Next elem

I'm trying to click in the element "Scratchpad" at the top of the page,  Thanks in advance!
HTML:

   Parameters    Scratchpad    Plot

A: It's an Angular JS directive. Try either of the following 2
ie.document.querySelector("[ng-click*=toggleScratchPad]").click

ie.document.parentWindow.execScript "document.querySelector('[ng-click*=toggleScratchPad]').click();"


text:
Q: Attempt to index global 'Grid' (a nil value) I have been trying to run the following codes from Euler Equations Solver. It is a Lua script that I have been toying with using ZeroBrane Studio. But the project gave the following error every time I try to execute it.

attempt to index global 'Grid' (a nil value)
stack traceback:
...mming Codes\Project 1\Lua Script\Problem 1\Problem 1.lua:7: in main chunk
      [C]: at 0x00401b00

I am completely new to Lua and I have been looking for the solutions everywhere. Appreciate any help that I can get.


text:
Q: Is there a easy way to change a directory in application iml to build folder for tests? I am playing with lucine through Spring-boot. I want to set the folder to the build folder because of test and permisions.
this is my code for now:

spring.jpa.hibernate.search.default.indexBase: ${LUCINE_FOLDER:/data/index/default}

Later on when deploy, I can easily control it by env variable LUCINE_FOLDER
I want it to be something like:

spring.jpa.hibernate.search.default.indexBase: ${LUCINE_FOLDER:build/index/default}

I am using gradle as well

A: I found the solution by local-heap:

spring.jpa.properties.hibernate.search.default.directory_provider: local-heap


text:
Q: assign integers as variables Generic topic I know. Its hard to be specific in a topic. Anyway I have problem with this sql logic:
"SELECT * FROM imagecomment WHERE filename = :filename ORDER BY comment_timestamp DESC LIMIT '$min', '$max'";

When I try the same logic but with integers directly in the sql logic it works. The variables min and max are integers:
int(10)
int(20) I get this when var_dump() them. I also tried to bindValue() the variables (as I usually do) to two parameters but it still didn't work.

A: You're using this in a PDOStatement, right? (since you're using :filename)

    $db = new PDO(); //assume you have this set
$stmt = $db->prepare(
         "SELECT *
          FROM imagecomment
          WHERE filename = :filename
          ORDER BY comment_timestamp
          DESC LIMIT :min, :max";

$stmt->bindValue(':filename', $filename);
$stmt->bindValue(':min', $min);
$stmt->bindValue(':max', $max);

$stmt->execute();

And you should be able to fetch your results, If that doesn't work, let me know what error you're getting back from the PDOStatement.

A:  "SELECT * FROM imagecomment
 WHERE filename = :filename ORDER BY comment_timestamp DESC LIMIT $min, $max";


text:
Q: IE6 domain cookie limit of 20? I've been trying to get to the bottom of this -- and was wondering if anyone can verify.
Does IE6 still only support 20 domain cookies at this time? I've found some MS articles online that indicate the domain cookie limit was increased in 2007 to 50 -- but, it's unclear if the article is discussing IE7.


text:
Q: eigenvalues and eigenvectors of functions I am quite confused about the following question below and how I should understand it.
Let $V=M_{3 \times 3}(\mathbb{R}) = \{$ all $ 3 \times 3 $ matricies with real entries}.
Let function $L: V \rightarrow V$ be defined by: L(X) = $A \cdot X $ - $X \cdot  A$
I intend to compute all eignevalues of L and chose a corresponding eigenvector for each eigenvalue.
Would it be possible to simplify $A \cdot X $ - $X \cdot  A$ into a simple matrix expression? In addition how would it be possible to calculate eigenvalues and eigenvectors of matrices containing variables? Thank you very much and any insights are well appreciated.

A: You can rewrite this as a single matrix-vector operation by "vectorizing" the $3\times 3$ matrices into vectors in $\mathbb{R}^9$. Stack the columns of $X$ like
$$
x = \begin{pmatrix}
x_{11} \\
x_{21} \\
\vdots \\
x_{23} \\
x_{33}
\end{pmatrix}.
$$
You can then write this out the operator $L$ as $L = A\otimes I_{3}-I_{3}\otimes A$. This can be written explicitly in block matrix notation as
$$
L = \begin{pmatrix}
a_{11}I_{3} & a_{12}I_{3} & a_{13}I_{3} \\
a_{21}I_{3} & a_{22}I_{3} & a_{23}I_{3} \\
a_{31}I_{3} & a_{32}I_{3} & a_{33}I_{3}
\end{pmatrix} -
\begin{pmatrix}
A & 0 &0 \\
0 & A & 0 \\
0 & 0 & A
\end{pmatrix}.
$$
Hopefully this makes the eigenvalue problem a little easier. I haven't worked it out myself, but one can notice that for a general matrix $A$, we have that $I$, $A$, and $A^2$ are all eigen-elements corresponding to the eigenvalue $0$. Higher order polynomials are also eigen-elements corresponding to $0$ but they are not linearly independent from these as a result of the characteristic polynomial of $A$ having degree $3$. This also implies that $A^{-1}$ is contained within this eigenspace.


text:
Q: How to get post value as array from form created using loop in codeigniter I need to get post value as array from form created using for loop ,
Here is my view
   <?php for ($i=0;$i<5;$i++) {?>

                    Name
                    <input name="<?php echo 'fname'.$i?>" class="form-control" type="text" />

                    Surname
                    <input  name="<?php echo 'sname'.$i?>" class="form-control" type="text" />

                    Date of Birth
                    <input name="<?php echo 'dob'.$i?>" class="date-pick-years form-control" type="text" />

        <?php }?>

        <input type="submit" />

How to get these post value in controller , i need as a array for example i value is 2 means i need my output as
    $array1=array('name'=>$this->input->post('name0')),'sname'=>$this->input->post('sname0')),'dob'=>$this->input->post('dob0'))

   $array2=array('name'=>$this->input->post('name1')),'sname'=>$this->input->post('sname1')),'dob'=>$this->input->post('dob1'))

Total array =array($array1,$array2);

How to get this in a loop in controller to get required output First array value as first loop second array value as 2nd loop ...etc

A: I just have changed the names of your inputs:
<form method="POST" action="">
 <?php for ($i=0;$i<5;$i++) {?>

                Name <input
                    name="<?php echo 'people['.$i.'][fname]'?>" class="form-control"
                    type="text" />

                Surname <input
                    name="<?php echo 'people['.$i.'][sname]'?>" class="form-control"
                    type="text" />

                Date of Birth <input
                    name="<?php echo 'people['.$i.'][dob]'?>"
                    class="date-pick-years form-control" type="text" />

        <?php }?>

        <input type="submit" />
</form>

The result $_POST array after submit form is:
array(1) {
  ["people"]=>
  array(5) {
    [0]=>
    array(3) {
      ["fname"]=>
      string(5) "James"
      ["sname"]=>
      string(4) "Bond"
      ["dob"]=>
      string(10) "22.01.1950"
    }
    [1]=>
    array(3) {
      ["fname"]=>
      string(4) "Jack"
      ["sname"]=>
      string(6) "Sparow"
      ["dob"]=>
      string(10) "08.05.1970"
    }
    [2]=>
    array(3) {
      ["fname"]=>
      string(0) ""
      ["sname"]=>
      string(0) ""
      ["dob"]=>
      string(0) ""
    }
    [3]=>
    array(3) {
      ["fname"]=>
      string(0) ""
      ["sname"]=>
      string(0) ""
      ["dob"]=>
      string(0) ""
    }
    [4]=>
    array(3) {
      ["fname"]=>
      string(0) ""
      ["sname"]=>
      string(0) ""
      ["dob"]=>
      string(0) ""
    }
  }
}

Now you can loop in your controller using:
$arr_res = $_POST['people']

or your wrapper(I'm not sure)
$arr_res = $this->input->post('people');
I hope this helps.
Good practice: don't use the same name vars as function names(particulary in php) - $array = array(...) etc. better use e.g. $arr_res (array with results) or $people, $people_arr.


text:
Q: Is there a simpler way to filter ng-model? I have a form with date inputs. In my model, the dates are formatted as such "/Date(123123123123)/". Apparently that's some sort of MVC3 date format, I dunno. I can run that string through Moment, it outputs local datetime just fine. The problem I'm running into is the binding. ng-model="currentNotification.startDate" obviously outputs the "/Date(123123123123)" string.
Ideally I want the prettified Moment string for the input value, but then upon submitting the form, the date would be converted back to the MVC3-style string.
I've seen some information on creating an attribute directive to deal with this, but that just seems overly complicated. I would think this would be a common use case. "I want to display the date as X, but I want to store it as Y."


text:
Q: WebApi Custom Filter with injected interface in constructor does not get called My problem statement is same as this question i.e., use an injected service in attribute/filter. I have tried the solution given by B Z and following is my code along the lines of solution given.
//marker attribute
public class AuthorizeViewAttribute : Attribute { }

//filter
public class AuthorizeViewFilter : IAuthorizationFilter
{
    private readonly IAccessRightsService _iAccessRightService;
    public AuthorizeViewFilter(IAccessRightsService iAccessRightService)
    {
        _iAccessRightService = iAccessRightService;
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        RoleFeature roleFeature = _iAccessRightService.GetRoleFeatures();

        if (roleFeature.IsView)
        {
            //redirect to controller
        }
    }
}

Following is the ninject binding I use:
this.BindFilter<AuthorizeViewFilter>(System.Web.Mvc.FilterScope.Controller, 0)
        .WhenControllerHas<AuthorizeViewAttribute>();

I do not need any parameter in attribute, so I figured I do not need to use WithConstructorArgument as mentioned in this answer
But my filter never gets called. I put a default constructor in AuthorizeViewAttribute , debugged and found that the control jumps to default constructor in AuthorizeViewAttribute and continues with the controller method.
I cannot find any solution to this. Any suggestions?

A: Short story : You seem to be trying to use MVC filter and MVC binding on a webapi controller. That's why it does not work.
Long story : first create a webapi filter provider ( note, you will need Ninject.Extensions.Factories package to have Func<AuthorizeViewFilter> resolved by Ninject)
public class AuthorizeViewFilterProvider : System.Web.Http.Filters.IFilterProvider
{
    private readonly Func<AuthorizeViewFilter> _authorizeViewFilterFactory;

    public AuthorizeViewFilterProvider(Func<AuthorizeViewFilter> authorizeViewFilterFactory)
    {
        this._authorizeViewFilterFactory = authorizeViewFilterFactory;
    }

    public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
    {
        if(!actionDescriptor.GetCustomAttributes<AuthorizeViewAttribute>().Any())
            return Enumerable.Empty<FilterInfo>();

        return new[]
        {
            new FilterInfo(this._authorizeViewFilterFactory(), FilterScope.Action)
        };
    }
}

then create a webapi filter
public class AuthorizeViewFilter : System.Web.Http.Filters.IAuthorizationFilter
{
    private readonly IAccessRightsService _iAccessRightService;
    public AuthorizeViewFilter(IAccessRightsService iAccessRightService)
    {
        _iAccessRightService = iAccessRightService;
    }

    public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(
        HttpActionContext actionContext,
        CancellationToken cancellationToken,
        Func<Task<HttpResponseMessage>> continuation)
    {
        RoleFeature roleFeature = _iAccessRightService.GetRoleFeatures();

        if (roleFeature.IsView)
        {
            return continuation();
        }
        else
          return Task.FromResult(actionContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Access denied"));
    }
}

then, bind the FilterProvider in your binding setup :
this.Bind<System.Web.Http.Filters.IFilterProvider>().To<AuthorizeViewFilterProvider>();


text:
Q: moment.js returns different timezones I'm using this code to create 2 dates that represent a filter date range (in this case the last 3 months):
$ctrl.startDate = moment().utc().startOf('month').add(-2, 'months').toDate();
$ctrl.endDate = moment().utc().endOf('month').add(0, 'months').toDate();

However the first returned date is timezone CET (GMT+1) (which is my zone) and the second is CEST (GMT+2). I have no idea why! I have tried using utc() to get "neutral" dates without success.
Returned dates:
01.01.2017 01:00:00 CET
01.04.2017 01:59:59 CEST
I want either GMT or CET but the same zone! Where does moment take these 2 zones from?
I've come so far that I think it is a bug.
I use version 2.17.1
Any ideas?
JSFIDDLE:
https://jsfiddle.net/FLhpq/8807/

A: I don't know if you can consider it a bug, in your fiddle you are showing in the result of toDate() that as docs says:

get the native Date object that Moment.js wraps

If you look at momentjs the code you will see that toDate() implementation:
function toDate () {
    return new Date(this.valueOf());
}

simply uses new Date() that returns a JavaScript date object in local time, see MDN Date:

Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments.

If you use format() in your code you will always see +00:00 offset.

var divUtc = $('#divUTC');
var divLocal = $('#divLocal');

var startDate = moment.utc().startOf('month').add(-2, 'months').format('YYYY-MM-DDTHH:mm:ssZ');
var endDate = moment.utc().endOf('month').add(0, 'months').format('YYYY-MM-DDTHH:mm:ssZ');
//put UTC time into divUTC
divUtc.text(startDate);
divLocal.text(endDate);

UTC

Your Local Time with respect to above UTC time


text:
Q: Adding more tables to search after a where clause in a Inner join clause Please help me with this query. I have included as much info as possible about this.
Here is my Query:

<?php
$sql4 = ('SELECT *,COUNT(*) FROM tt_new_make
inner join tt_new_size
ON tt_new_size.no=tt_new_make.no
inner join
tt_new_rub
on tt_new_rub.no=tt_new_make.no
WHERE tt_new_size.s_line_no1="12R" GROUP BY m_line_no1, line_no1');
?>

My results are not what I am looking for. I know that I am limiting my coding with being too specific with the s_line_no1="12R", but how do I include all columns?
tt_new_size
My results should be 4, not 2

A: I found that the problem was on the way I post it to the table.
I should have post everything under 1 row, not on multiple columns.
The results should look as follow:
Table layout


text:
Q: Updating custom DialogPreference's title in a SettingsFragment I have a PreferenceActivity that shows several custom classes based on DialogPreference.  They appear from the PreferenceActivity as a TextView that, when clicked, displays a dialog to allow the user to set a value.  I'd like the view shown in the PreferenceActivity to include the setting's title (i.e. "Volume"), plus its value ("Loud").  That's not hard to do with setTitle() and getTitle() from Preference.  That works fine for initially viewing the PreferenceActivity, but once I make a change and go back to the PreferenceActivity from my custom dialog, the title doesn't update.  I've tried updating it when the value changes, and when the dialog is dismissed, but it doesn't update until the setting gets clicked again (an instant before it shows that dialog again).  Any ideas?

A: You have to update your custom view manually from the PreferenceActivity. For example for a ListDialog you can do:
 ListPreference myList = (ListPreference) findPreference("listPref");
 myList.setSummary(your_string);

For editText:
EditTextPreference myEditTextPref = (EditTextPreference)findPreference("myEditText");

Use findPreference() method and update your view with its methods setSummary(), setTile() etc.


text:
Q: find rows where the variable "back" is greater than 100 The question is write the code to provide the rows where the variable "back" is greater than 100.I am a new for the R,now I only use x<-read.csv('data.csv',header = TRUE) to load the excel, just want to know how to find rows which value more than 100

A: Create a logical vector with the comparison operator (>), get the positions by wrapping with which and if we need to include the column names as index 1, then concatenate 1 and add 1 to the index we got with which
c(1, which(x$back > 100) + 1)


text:
Q: PHP foreach loop help I am working with a PHP foreach loop and I need it to output some specific HTML depending on which array value it is spitting out.
Everytime that the foreach loop hits a $content['contentTitle'] I need it to insert a new table and then from there carry on. Essentially I want the for the loop to spit out a new table everytime a new contentTitle is found, but then add the rest of the data in the array as tr and td's.

A: Well, add an if condition inside of your loop. If it hits a $content['contentTitle'], then close previous table and start a new one.

A: Assuming that $content is an element of some parent array, and that the first entry in that parent array does have a contentTitle entry, then you'd do something like this:
$first = true;
echo "
\n"; // start initial table
foreach ($stuff as $content) {
    if ($content['contentTitle']) {
        if (!$first) {
           // If this is NOT the $first run through, close the previous table
           $first = false; //... and set the sentinel to false
           echo "
\n";
        }
        // output the contentTitle
        echo <<<EOF

{$content['contentTitle']}

EOF;
    } else {
        // otherwise output the regular non-title content
        echo <<<EOF

    {$content['this']}
    {$content['that']}
    {$content['somethingelse']}

EOF;
   }
}

A: foreach($content as $key=>$value){
  if($key == "contentTitle"){
    echo "
";
  }
  else{
    echo "
";
  }
}


text:
Q: Color palette issue when overlaying layers in OpenLayers I'm trying to draw a temperature heatmap layer on top of the map. But here the problem arises that the heat map overlaps the names of cities, as in the first screen.

When adding opacity, the color palette changes and the names of cities are still not clearly visible
.
And finally, when adding the property
context.globalCompositeOperation = "multiply";

I achieve the desired result, but the heatmap itself changes the palette, probably due to mixing colors with the bottom layer.

If anyone has any ideas or suggestions in which direction to move, I will be very grateful.


text:
Q: Delete item of html table coming from input in JS DOM I have problem with deleting operation in html table in JS. I trying to delete item of table which coming from input.It is nothing happen.

const name = document.querySelector(".name");
const surname = document.querySelector(".surname");
const age = document.querySelector(".age");
const addBtn = document.querySelector(".addBtn");
const deleteBtn = document.querySelector(".delete");
const tbody = document.querySelector(".tbl");

addBtn.addEventListener("click",addItem);
deleteBtn.addEventListener("click",deleteItem);

function addItem(e){
    var html = `

                    ${name.value}
                    ${surname.value}
                    ${age.value}
                    DELETE

`;
    if(name.value === '' || surname.value === '' || age.value === ''){
        alert("Warning!!!");
    }else{
        tbody.innerHTML += html;
    }
    e.preventDefault();
}
function deleteItem(e) {
        if(e.target.className = 'delete'){
           e.target.parentElement.remove();
        }
}

A: I see two issues here:

*

*The event listener is assigned to the first element that matches
'.delete', not all elements

*Buttons that will be created via addItem won't have the listener attached to them

You can fix both by using event delegation: assign the listener on a common parent:
document.querySelector("table").addEventListener("click", deleteItem)

A: Your table rows are added dynamically, you bind the event listener before the content is loaded into the dom(your row is added only when you call the addItem method). One way you can fix is, add event listener after appending content to the table every time.
Something like this
if(name.value === '' || surname.value === '' || age.value === ''){
     alert("Warning!!!");
}else{
     tbody.innerHTML += html;
     document.querySelector(".delete").addEventListener("click",deleteItem);
}


text:
Q: There is a round cake. What is the chance of cutting a piece of cake with angle of $30°$/$30°$ or less? Problem statement:

There is a round cake. What is the chance of cutting a piece of cake (cutting two radiuses) with the angle of:

*

*$30°$ or less?

*$30°$?

In our class, our teacher and other students suggested two solutions and two different answers for  question number 1:
First Solution

As there are unlimited number of possible cutting angles, We indicate the probability with area. $30°$ is $\frac1{12}$ of the area of the cake, so probability is $\frac1{12}$.

Second Solution

Suppose that we have made the first cut. Then the angle of the wanted are is $60°$ because wanted cases can happen if you cut from $30°$ or less degrees from right or left. Take a look at this picture:

So the wanted area is $\frac1{6}$ of the whole cake, so probability is $\frac16$.

If you think one of these solutions is true, please explain why other one is wrong.
And about the question number 2, I've no idea about how to answer.

A: The first solution is incorrect. When calculating probabilities by finding area, you're finding the probability that one random outcome lands in a particular region. For example, the probability that a spinner lands in a certain segment of a board is the angle of that segment divided by $360$ degrees. So the area of a $30$ degree slice is the probability that a single random cut will be somewhere on that slice.
The second argument is correct, because it doesn't matter where the first cut is. You just need the second cut to be within the $60$ degree slice centered on the first cut.
As for the second question, you could think about it in a similar way: assume the first cut has been made. What is the probability that the second slice lands exactly $30$ degrees clockwise or counterclockwise from the first? Now you want the second slice to land on one of two particular lines. If we keep thinking about probability as area, we need the area of those lines. But the area of a line is...


text:
Q: How to update "physical path" of a site on IIS 10 using Powershell? When creating a site I manage to set the path with the following line of code
New-WebSite -Name "mysite" -port 8084 -PhysicalPath "c:\inetpub\wwwroot" -ApplicationPool "myappPool"

I have tried to figure out how to update the path, nothing found via Configuration Editor. I thought I had it with the following command
Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST'  -filter "system.applicationHost/sites/site[@name='mysite']/virtualDirectoryDefaults" -name "physicalPath" -value "c:\inetpub\wwwroot\mysite"

...but, it is not virtualdirectory I want to update, but the actual site...

A: You could use below PowerShell command to change the iis site physical path.
run PowerShell as administrator.
run below command:
PS C:\WINDOWS\system32> Import-Module WebAdministration
PS C:\WINDOWS\system32>  Set-ItemProperty IIS:\Sites\sitea -name physicalPath -value "D:\s1"

after changing the path open iis manager and refresh the site.


text:
Q: Updating a Json column that contains a JsonArray using Json_transform() function in Oracle Database 19c Enterprise Edition I have a table that keeps USER data.
Here is my table structure:
CREATE TABLE "USERS"
(
    "ID" NUMBER(16,0) PRIMARY KEY,
    "USER_NAME" VARCHAR2(85) UNIQUE NOT NULL,
    "IDENTIFICATION_TYPE" NUMBER(3,0) NOT NULL REFERENCES IDENTIFICATION_TYPES(ID),
    "IDENTIFICATION_CODE" VARCHAR2(24) NOT NULL,
    "TRADING_CODE" VARCHAR2(85) NULL,
    "PASSWORD" VARCHAR2(48) NOT NULL,
    "SALT" VARCHAR2(24) NOT NULL,
    "FLAGS" NUMBER(3) NOT NULL,
    "PROFILE" NCLOB NOT NULL CONSTRAINT profile_json CHECK ("PROFILE" IS JSON),
    "SETTINGS" NCLOB NOT NULL CONSTRAINT settings_json CHECK ("SETTINGS" IS JSON),
  UNIQUE(IDENTIFICATION_TYPE,IDENTIFICATION_CODE)
);

As you can see I have a Json column named SETTINGS.
And the data that will be kept in this column looks like :
{
  "lang" : "fa-IR",
  "cols" : [],
  "watch_lists" :
  {
    "list_1" : [5,6,7],
    "list_2" : [8,9],
    "list_3" :[1,2,3]
  }
}

Now my application receives an updated list of watch_lists that I want to replace with current one.
After some research at first I could write the following query using JSON_MERGEPATCH() function:
UPDATE USERS
SET SETTINGS = JSON_MERGEPATCH(SETTINGS, '{ "watch_lists": { "liist_1": [4,5],"liist_2": [1,3,5] }}' returning clob pretty)
WHERE USER_NAME = 'admin'

But I found that JSON_MERGEPATCH() will merge the updated list with current one, but I needed to replace it, then finally I understood that I need to use the JSON_TRANSFORM() function in order to replace the list, so I wrote the following query:
UPDATE USERS
SET SETTINGS = JSON_TRANSFORM(SETTINGS,
               SET '$.watch_lists' =
                   '{ "liist_1": [4,5],"liist_2": [1,3,5] }'
                   FORMAT JSON)
WHERE USER_NAME = 'admin'

But now it throws an exception :
SQL Error [1747] [42000]: ORA-01747: invalid user.table.column, table.column, or column specification

I could not find the reason of this error to resolve it.
Can anyone help me?
Any help will be appreciated!!

A: It somehow seems that JSON_TRANSFORM is available starting with 21c version (and was backported in higher release of 19c).
Anyway you can use JSON_MERGEPATH with a two step approach.
Reset the attribute first and than set it to the new value:
UPDATE USERS
SET SETTINGS = JSON_MERGEPATCH(SETTINGS,
                   '{ "watch_lists": null}'
                  )
WHERE USER_NAME = 'admin'
;
UPDATE USERS
SET SETTINGS = JSON_MERGEPATCH(SETTINGS,
                   '{ "watch_lists": { "liist_1": [4,5],"liist_2": [1,3,5] }}'
                  )
WHERE USER_NAME = 'admin'
;


text:
Q: Is my proof that $x^2+y^2+z^2 ≥ xy+yz+xz$ correct? The question:
Prove that $x^2+y^2+z^2 ≥ xy+yz+xz$ for all real numbers $x$, $y$ and $z$.
This problem has been posed before, but my question is whether my proof below is correct, since it seems the other answers to this problem are different.
If $x$, $y$ and $z$ are real numbers then $(x-y-z)^2 \geqslant 0$. That is $x^2 + y^2 +z^2 -2xy-2xz-2yz \geqslant 0$. But this implies that $\frac{x^2 + y^2 +z^2}{2} \geqslant xy + xz + yz$, so because $x^2 + y^2 +z^2 \geqslant \frac{x^2 + y^2 +z^2}{2} \geqslant xy + xz + yz$ we get the desired result.

A: Your concerns were already addressed in the comments, so there is no need to keep underlying your actual sign mistake. But on a meta-mathematical point of view, something should have struck you, since your method would have derived a symmetric inequality from a non-symmetric one, kind of strange.
A working and fast proof:
$$\color{red}{0\leq} (x-y)^2+(x-z)^2+(y-z)^2 = 2\color{red}{\left(x^2+y^2+z^2-xy-xz-yz\right)}. $$

A: another way $$xy+yz+zx\le \sqrt { \left( x^{ 2 }+{ y }^{ 2 }+{ z }^{ 2 } \right) \left( x^{ 2 }+{ y }^{ 2 }+{ z }^{ 2 } \right)  } =x^{ 2 }+{ y }^{ 2 }+{ z }^{ 2 }\\ \\ \\ $$

A: Based on hagnatural's comment: No, your proof is incorrect since one of your signs is wrong:
$$(x-y-z)^2 = x^2 + y^2 + z^2 - 2xy - 2xz \color{red}{+} 2yz.$$
And unfortunately there is no direct term $(\pm x \pm y \pm z)^2$ which gives you opposite signs on the cross terms, compared to the squares. (But as noted in the other answers, it is possible to use similar ideas by combining the three terms $(x - y)^2$, $(x - z)^2$, and $(y - z)^2$.)


text:
Q: Jenkins - How to get properties/fields of choice param defined in shared lib We have defined set of choice parameters in our shared Jenkins library, and I have a job in which I want to be able to create a set of permutations of some of them. e.g.:
in shared dynamic_params.groovy:
def dev_team() {
    def teams = ['backend', 'frontend']
    return choice(name: 'team', description: 'Choose the name of the team', choices: teams)
}

def environment() {
    def environments = ['prod', 'qa', 'staging']
    return choice(name: 'environment', description: 'Choose an environment', choices: environments)
}

Then, all I wanna do is, in a job, something like:
def envTeams = [:]

for (env in dynamic_params.environment().choices) {
    for (team in dynamic_params.dev_team().choices) {
        envTeams[env] = team
    }
}
......

(examples are mocked)
But I get org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: No such field found: field
I'm not even yet sure what do I get when I do dynamic_params.environment() because Jenkins prints
@choice(name=environment,description=Choose an environment,choices=[prod, qa, staging])
(Does that mean I have a class?)
Thanks

A: By your choice of choice (pardon the pun) I understand that you want to populate a parameter of the job before presenting it to the user in e.g. "Build with parameters" page.
That is a common trap: you want to run some code to prepare a parameter, but in order to execute your code Jenkins needs to run your pipeline, which happens after "Build with parameters" is pressed.
You have two options: either use ActiveChoice plugin, or run a scripted pipeline before your main pipeline. In your case this may look like this:
my_choice = ''

node('master') {
    stage('prepare choices') {
        println "before: my_choice is ${my_choice}"
        my_choice = get_choices() // def get_choices() { return ['prod', 'qa', 'staging'] }
        println "after: my_choice is ${my_choice}"
    }
}

pipeline {
    agent any

    parameters { choice(name: 'CHOICES', choices: my_choice, description: '') }

    // rest of pipeline


text:
Q: jQuery Validate not working (jqueryvalidation.org) I have a form, trying to validate using jquery.validate.js but its not working
Form
<form id="login_form" name="login_form" method="post" action="" enctype="multipart/form-data" >

        Email address
        <input class="form-control" id="user_email" name="user_email" type="email"  placeholder="Enter email">

        Password
        <input class="form-control" id="user_password" id="user_password" type="password" placeholder="Password">

    <input type="submit" name="submit" id="submit" value="Login" class="btn btn-primary btn-block" />
</form>

And below is the Javascript/JQuery

I don't know why the validation part is not working.
I have tried some stuff like adding novalidate in form, but i think the function is not getting initiated.
Please help.

A: You had an issue in your rule definition!
You can adress your field's with the name attribute.
Cleaned your input field user_password too.
See my snippet!

$(document).ready(function() {
  $("#login_form").validate({
    rules: {
      user_email: {
        required: true,
        email: true
      },
      user_password: {
        required: true
      }
    },
    messages: {
      email: "Please enter a valid email address",
      password: {
        required: "Please provide a password",
        minlength: "Your password must be at least 5 characters long"
      }
    }
  });
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<form id="login_form" name="login_form" method="post" action="" enctype="multipart/form-data">

    Email address
    <input class="form-control" name="user_email" id="user_email" type="email" placeholder="Enter email">

    Password
    <input class="form-control" name="user_password" id="user_password" type="password" placeholder="Password">

  <input type="submit" name="submit" id="submit" value="Login" class="btn btn-primary btn-block" />
</form>


text:
Q: Why Share Extension is not working on iOS 13? I was using a Share extension in my app in order to import audio files and it was working on iOS12. Now in iOS 13 is not working anymore, when I press the share button my app doesn't appear in the share sheet.
I think that maybe something has changed in the plist or similar but I coudn't find any information.
Does anyone have the same problem?
NB: I don't wanna use the copy - paste strategies, only the share extension.

A: Try this for iOS 13
    DispatchQueue.main.async {

      let activityItem = URL.init(fileURLWithPath: Bundle.main.path(forResource: "audio", ofType: "mp3")!)

      let activityVC = UIActivityViewController(activityItems: [activityItem],applicationActivities: nil)
      activityVC.popoverPresentationController?.sourceView = self.view

      self.present(activityVC, animated: true, completion: nil)
    }

A: For IOS 13 you Should add below code inside your open url method.
UISceneOpenExternalURLOptions * options = [[UISceneOpenExternalURLOptions alloc] init];
options.universalLinksOnly = false;


text:
Q: Difference between application cache and object cache I'm reading Martin L. Abbott, Michael T. Fisher's Scalability rules: 50 principles for scaling Web sites, and in rules 24 and 25 they talk about Application Caches and Object Caches respectively.
My previous understanding was that an Application Cache, let's say ehCache, it's a layer that you put between your services and your DB, where you put objects in order to avoid hitting the DB for objects previously queried (and still valid). But know I'm not sure.
Can somebody explain what is the difference between the two, if possible with an example?


text:
Q: class diagram without relationships after python reverse engineering I am trying to work on a Python project thant is not documented.
I did a reverse engineering to get the Class diagram 2 times in windows environment : with sparx EA and with visual paradigm.
But in both cases I got a class diagram with classes without relationships (even if i did configure the process to generate them). is it possible or is there a problem ?

A: Almost all tools (for myself I have expertise in EA and backdated in RSA) have difficulties showing relations between classes. Basically they RE the structure (files/packages) and the operations/properties of the single classes. In some cases you also will get relations but as said: this is limited.
Anyhow, if you are going to understand the code it's good practice to complete/correct the missing relations between the classes and thereby adding comments as well.

A: It's possible, certainly. There may not be anything in the code that the reverse-engineering process recognizes as a UML relationship. Precisely what that would be depends on the language and tool, since there are no standardized UML profiles for any implementation languages.
UML is fundamentally object-oriented, but in Python, object-orientation is optional. If the code doesn't use classes, there isn't much for UML to work with. Python's dynamic typing also makes it tricky to deduce the types of variables from the source code, which means it's hard for the UML tool to identify associations.
In EA, there are some options you can play with under Tools -- Options -- Source Code Engineering. On that page there's "Create dependencies for operation returns and parameter types," which I believe is off by default. But since EA treats all Python types as var I don't think this would have much of an effect.
There are further options per language, but I don't think there's anything in the Python section that affects relationships.


text:
Q: Composing/extending/"subclassing" Angular directives? Is there a standard way to create new Angular directives by extending existing directives?
Specifically I'd like to customize angular-contenteditable to allow more control over editing options, like preventing newlines:

Hello, world!

Where the implementation is something like:
app.directive("myCustomContentEditable", function() {
    return {
        link: function($scope, elem, attrs) {
            angular.element(elem).on("keydown", function($event) {
                if (attrs.preventNewlines && $event.keyCode == 13)
                    $event.preventDefault();
            });
        },

    };
})

What would be the best way to extend the contenteditable directive in my custom directive?
Note that I do know that I can combine the directives at the markup level —
…
 — but I'd like to know specifically how to create a single directive that extends another.

A: You don't subclass/extend directives, you can just combine them in line as in your example.
another example:
<input ng-init="myModel = 'stuff'" ng-change="somethingElse()" ng-model="myModel" />

Basically, directives do not allow inheritance. You can simply take the original code of whatever directive there is and modify it or combine directives to achieve the functionality you're looking for.
There are ways to hack at 'extending' a directive though... but this consists of using require, which I don't feel is quite the same. http://thaiat.github.io/blog/2014/03/10/extending-an-existing-directive-in-angularjs/


text:
Q: Proving $\forall x \in \Bbb R$ and $ \epsilon \gt 0$, $N(x;\epsilon) \backslash \{x\}$ is open.
Prove: $\forall x \in \Bbb R$ and $ \epsilon \gt 0$, $N(x;\epsilon) \backslash \{x\}$ is open.

Proof:
Let $S = N(x;\epsilon) \backslash \{x\}$.
We want to show that $S = intS$.

Let $y \in S$. If we take $\delta = \frac{\epsilon - |x-y|}{2}$, then $N(y;\delta) \subseteq S$.
So $y \in intS$.

Let $ y\in intS$. Then there exists an epsilon-neighborhood of $S$ such that $N(y;\epsilon) \subseteq S$.
So $y \in N(y;\epsilon) \subseteq S$ implies that $y \in S$.

I want to know if my proof is correct.

A: All open balls $N(x; r), r>0$ are open in the metric topology, by definition.
In any metric space $X$, $\{x\}$ is a closed set for any $x \in X$ and thus $\mathbb{R}\setminus \{x\}$ is open in $\mathbb{R}$.
So $N(x;r)\setminus \{x\} = N(x; r) \cap (\mathbb{R}\setminus \{x\})$ is open as the intersection of two open sets.
If you want a direct, more laborious, proof: for each $y \in N(x;r)\setminus\{x\}$, set $\delta=\min(d(x,y), r-d(x,y)) > 0$ and show that $y \in N(y; \delta) \subseteq N(x; r) \setminus \{x\}$.

A: The first part is actually sufficient as $\text{int}(S) \subseteq S$ always holds by definition. You made a small mistake when you defined $\delta$, but otherwise this is correct.

A: You can simplify your proof by noting that $\operatorname{int} X\subseteq X$ for any set $X$ in any topological space. By definition $\operatorname{int} X$ is the union of all open sets contained in $X$, so it too must be contained in $X$. Equivalently it is the set of all interior points of $X$, but all these elements are by definition in $X$, so once again the interior of $X$ must be contained in $X$.
For the other direction your $\delta$ has to depend on $y$ somehow. What if $y$ is in $N(x,\varepsilon/2)$? I'd suggest looking at $d(x,y)$.

A: I think that the $\delta$ might be wrong. There are some values for which $N(y, \delta)$ is not contained in $S$. Take $y = x + \frac{9}{10}\epsilon$ for example.


text:
Q: Canvas application not working in IE9 & working incorrectly in FF4b7 I'm working on an online roguelike game. It's current version is located here. It's working fine in Chrome 9 and Firefox 3.6, but it makes Firefox 4 beta 7 unresponsive for about a minute on every move and IE9 just says that it doesn't support <canvas> tag.
Could someone please explain these strange behaviours of IE9 and FF4b7?
Thank you very much.

A: In IE9 hit F12 and you'll see your site is loading in quirks mode which is why it doesn't have canvas.  From F12 you can switch it and see that you're site does work if it is in IE9 standards mode.
I think you want to put DOCTYPE html before everything else to avoid this.
http://en.wikipedia.org/wiki/Quirks_mode

A: I am posting this in case it helps someone else (I found this page when I was googling)
Pages worked fine in Firefox
In IE9 pages were working locally, but not from server. ("getContext not supported etc. etc.")
Had run out of ideas, but noticed that a trial of part of my page containing canvas did work.
Long story short:-
My pages were .htm  and so I thought "Is there an HTML5 standard ?" well I'm not sure if there is but when I changed all pages to .html the site behaved as intended in IE9 with all canvas elements working.
Bob


text:
Q: How to properly test a Python Flask system based on SQLAlchemy Declarative I have a project that I've been working on for a while, which is written in Flask, and uses SQLAlchemy with the Declarative extension http://flask.pocoo.org/docs/patterns/sqlalchemy/. I've recently decided to start unit testing my project, but for the life of me, I can't seem to figure out how to make it work.
I looked at http://flask.pocoo.org/docs/testing/, but I can't seem to make it work.
I tried a mix of things from different websites, but am unable to find something that works correctly.
class StopsTestCase(unittest.TestCase):

    def setUp(self):
        self.engine = create_engine('sqlite:///:memory:')
        self.session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=self.engine))
        models.Base = declarative_base()
        models.Base.query = self.session.query_property()

        models.Base.metadata.create_all(bind=self.engine)

    def test_empty_db(self):
        stops = session.query(models.Stop).all()
        assert len(stops) == 0

    def tearDown(self):
        session.remove()

if __name__ == '__main__':
    unittest.main()

Unfortunately, the best I can seem to get, causes the following error.
OperationalError: (OperationalError) no such table: stops u'SELECT stops.agency_id AS stops_agency_id, stops.id AS stops_id, stops.name AS stops_name, stops."desc" AS stops_desc, stops.lat AS stops_lat, stops.lon AS stops_lon, stops.zone_id AS stops_zone_id \nFROM stops' ()

----------------------------------------------------------------------
Ran 1 test in 0.025s

FAILED (errors=1)

Any help on this would be greatly appreciated. If someone has ever been through this before, and made it work, I would like some pointers! Thanks in advance.

A: Based on what I found and how I got it working, here is a template solution that works for testing the underlying SQLAlchemy systems using the Declarative extension.**
import unittest
from database import Base
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

import models

class StopsTestCase(unittest.TestCase):

    def setUp(self):
        self.engine = create_engine('sqlite:///:memory:')
        self.session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=self.engine))
        Base.query = self.session.query_property()

        Base.metadata.create_all(bind=self.engine)

        #Create objects here
        #These will likely involve something like the following for one of my stops

        # stop1 = models.Stop(id=1, name="Stop 1")
        # self.session.add(stop1)
        # self.session.commit()

        # But adding a stop to the database here will break the test below. Just saying.

    def test_empty_db(self):
        stops = self.session.query(models.Stop).all()
        assert len(stops) == 0

    def tearDown(self):
        self.session.remove()

A: You're instantiating declarative_base again, you should be using the same instance you used as a base class for your models. Also, you seem to be using two different session instances, self.session and some module-global session. Try cleaning that up, too.


text:
Q: asp.net mvc 4 app 'precompiliation' I have an asp.net mvc4 application that we deploy to about 1400 clients.  Our current deployment process goes like this:
:: Publish the project files to a local directory
%msbuild% RPortal.csproj "/p:Platform=AnyCPU;Configuration=Release;ConfigurationName=Release;SolutionDir=%solutionDir%;PublishDestination=.\Deploy\Release" /t:PublishToFileSystem

And then we have some powershell scripts that push the new build to each of our clients, using other tools to help with the sync.
We are noticing some sever slowness with application boot up times (sometimes upwards of 5 minutes), and one of the approaches we've investigated to solve this would be the idea of ASP.Net Precompiling (http://msdn.microsoft.com/en-us/library/vstudio/bb398860%28v=vs.100%29.aspx)
In some experiments with the idea, it appears that calling aspnet_compile.exe on our published system does, in fact, create some new files. (A couple of dlls, and a few *.compiled files).
My questions are as follows:

*

*How does this compilation differ from the primary compilation from the .cs source
files?

*Does this compilation happen regardless, at first run, or only when run manually?

*(related to 2), Does this compilation survive app pool restarts and server reboots?

With our current scenario, it seems that we are killing our servers trying to get 1400 applications to start up (yes, they all live on 1 webserver... that's not a situation I am in control of).  The server will be humming along, with no particular problems, resonable resource consumption, and then, all of a sudden, our CPU will peg to 100% and stay there.  The only factor we can tie it back to is that it happens when more than 5 (or so) of the 1400 apps are all booting up.
Our hope is that precompiling will front load most of the app start burden, but I clearly don't understand whats really going on here.
Any light you might shed would be most appreciated.


text:
Q: If $a^2|bc$, does $a|b$ or $a|c$ Basically, I am trying to prove that $a^2|bc$ implies $a|b$ or $a|c$.
I can visualize it in my head (based on the fundamental theorem of arithmetic and the factors of a,b,c), however, everything I try to write it down/express it in mathematical terms fail.  The closest I've gotten is showing $a|bc$, however, that is rather trivial.
Any help would be greatly appreciated - I am clearly missing something.

A: This will fail for the same reason that $a\mid bc$ does not directly imply that $a\mid b$ or $a\mid c$
Consider if $a=pq, b=p^2,c=q^2$ with $p,q$ both prime.


text:
Q: Django 1.8.8 Migrations first says nothing, then won't apply changes I believe these two are related.
I'm having two migration issues:

*

*I added a new file with two new classes (database tables).

*The tables are to be added to the local MySQL database (5.5).

*I have routers to other databases, but not the my local MySQL (developed under 1.5).

*I'm running Django 1.8.8 (recently updated from 1.6 via 1.7) and Python 2.7.6.

*The first problem I had was that Django did not recognize that I had added the new tables in the new file.

*I gave up on the new file (I have 6 other models_*.py files for this app that worked great under South) and just put the new classes in one of the existing files.

*Now makemigrations detected the changes and said it applied the changes. But the new tables did not appear in the database.

History
MY INITIAL MIGRATION (done during 1.7 upgrade):
$ ./manage.py makemigrations -v 3 sanity
Migrations for 'sanity':
  0001_initial.py:
- Create model Alert_User_Criteria
...
- Create model Test_Machine

$ ./manage.py migrate -v 3 --fake sanity
Operations to perform:
Apply all migrations: sanity0
Running pre-migrate handlers for application admin
...
Running migrations:
Rendering model states... DONE (0.296s)
  Applying sanity.0001_initial... FAKED (0.010s)
Running post-migrate handlers for application admin
...
Running post-migrate handlers for application staff_status

migrations/$ ls -al
-rw-rw-r-- 1  21731 Jan 25 16:06 0001_initial.py
-rw-rw-r-- 1   9953 Jan 25 16:06 0001_initial.pyc
-rw-rw-r-- 1         0 Jan 14 12:14 __init__.py
-rw-rw-r-- 1     142 Jan 25 16:06 __init__.pyc

mysql> select * from  django_migrations;
+----+---------------+---------------------------------------+---------------------+
| id | app           | name                                  | applied             |
+ ----+---------------+---------------------------------------+---------------------+
|  1 | contenttypes  | 0001_initial                          | 2016-01-12 11:56:34 |
|  2 | auth          | 0001_initial                          | 2016-01-12 11:56:34 |
|  3 | admin         | 0001_initial                          | 2016-01-12 11:56:34 |
. . .
| 30 | sanity        | 0001_initial                          | 2016-01-25 16:06:52 |
+----+---------------+---------------------------------------+---------------------+

NEW FILE: MODELS_SA.PY
from django.db   import models
from django.conf import settings

class Archive_Control(models.Model):
config_name  = models.CharField(max_length=128, null=False, unique=True, db_index=True)
is_active    = models.BooleanField(default=True)
oldest_build = models.DateTimeField(auto_now_add=True)
newest_build = models.DateTimeField(auto_now_add=True)
archive_url  = models.CharField(max_length=128, null=True)

def __unicode__(self):
    return self.config_name

class Meta:
    app_label = 'sanity'
    ordering = ['config_name']

class Build_Archives(models.Model):
config         = models.ForeignKey(Archive_Control, db_index=True)
gcid           = models.CharField(max_length=16, null=True)
build_nbr      = models.CharField(max_length=16, null=True)
build_url      = models.CharField(max_length=128, null=True)
build_datetime = models.DateTimeField(null=True)

def __unicode__(self):
    return self.config+" : "+str(self.build_datetime)

class Meta:
    app_label = 'sanity'
    ordering = ['build_datetime']
    get_latest_by = 'build_datetime'

def get_sortable_build_datetime(self):
    return self.build_datetime.strftime("%Y%m%d%H%M%S")
def get_formatted_build_datetime(self):
    return self.build_datetime.strftime("%Y-%m-%d %H:%M:%S")

build_datetime_sortable  = property(get_sortable_build_datetime)
build_datetime_formatted = property(get_formatted_build_datetime)

RUN MAKEMIGRATIONS WITH NEW FILE
$ ./manage.py makemigrations -v 3 sanity
No changes detected in app 'sanity'

ADDED CONTENTS OF MODELS_SA.PY TO MODELS.PY
$ ./manage.py makemigrations -v 3 sanity
Migrations for 'sanity':
  0002_archive_control_build_archives.py:
  - Create model Archive_Control
  - Create model Build_Archives

Why did it work now?
$ ./manage.py migrate -v 3 sanity
Operations to perform:
  Apply all migrations: sanity
Running pre-migrate handlers for application admin
. . .
Running migrations:
  Rendering model states... DONE (0.275s)
  Applying sanity.0002_archive_control_build_archives... OK (0.072s)
Running post-migrate handlers for application admin
...
Running post-migrate handlers for application staff_status

migrations$ ls -al
total 64
-rw-rw-r-- 1  21731 Jan 25 16:06 0001_initial.py
-rw-rw-r-- 1    9953 Jan 25 16:06 0001_initial.pyc
-rw-rw-r-- 1    1669 Jan 25 16:11 0002_archive_control_build_archives.py
-rw-rw-r-- 1    1673 Jan 25 16:12 0002_archive_control_build_archives.pyc
-rw-rw-r-- 1          0 Jan 14 12:14 __init__.py
-rw-rw-r-- 1      142 Jan 25 16:06 __init__.pyc

migrations$ cat 0002_archive_control_build_archives.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

dependencies = [
('sanity', '0001_initial'),
]

operations = [
migrations.CreateModel(
    name='Archive_Control',
    fields=[
        ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
        ('config_name', models.CharField(unique=True, max_length=128, db_index=True)),
        ('is_active', models.BooleanField(default=True)),
        ('oldest_build', models.DateTimeField(auto_now_add=True)),
        ('newest_build', models.DateTimeField(auto_now_add=True)),
        ('archive_url', models.CharField(max_length=128, null=True)),
    ],
    options={
        'ordering': ['config_name'],
    },
),
migrations.CreateModel(
    name='Build_Archives',
    fields=[
        ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
        ('gcid', models.CharField(max_length=16, null=True)),
        ('build_nbr', models.CharField(max_length=16, null=True)),
        ('build_url', models.CharField(max_length=128, null=True)),
        ('build_datetime', models.DateTimeField(null=True)),
        ('config', models.ForeignKey(to='sanity.Archive_Control')),
    ],
    options={
        'ordering': ['build_datetime'],
        'get_latest_by': 'build_datetime',
    },
),
]

mysql> select * from  django_migrations;
+----+---------------+---------------------------------------+---------------------+
| id | app           | name                                  | applied             |
+----+---------------+---------------------------------------+---------------------+
. . .
| 30 | sanity        | 0001_initial                          | 2016-01-25 16:06:52 |
| 31 | sanity        | 0002_archive_control_build_archives   | 2016-01-25 16:12:17 |
+----+---------------+---------------------------------------+---------------------+

TABLES ARE NOT IN THE DATABASE!
I have already read:

*

*Django Migration is not applying the migration changes

*Django 1.7 - "No migrations to apply" when run migrate after makemigrations

*Django 1.7 - makemigrations not detecting changes

*Django-migrations in Django 1.7 detects model changes but does not apply them on migrate

A: From the docs on migrations:

That in-memory structure is also used to work out what the differences are between your models and the current state of your migrations; Django runs through all the changes, in order, on an in-memory set of models to come up with the state of your models last time you ran makemigrations. It then uses these models to compare against the ones in your models.py files to work out what you have changed.

(Emphasis mine)
Since models_sa.py isn't a models.py file, it is ignored, hence when you move its contents to a models.py, its changes are applied.
I realise the docs link is for a newer version but the principles shown are the same


text:
Q: nginx: [emerg] invalid host in upstream "wordpress:/run/php/php7.3-fpm.sock" in /etc/nginx/sites-enabled/default:26 I am beginner and need some answers.
I always get invalid host in upstream, how can I fix it? Help pls.
docker-compose.yaml
version: '3.7'

services:
    db:
      image: mysql:8.0
      container_name: db
      restart: always
      networks:
        - app-network
    wordpress:
      build: ./requirements/wordpress/
      depends_on:
          - db
      container_name: wordpress
      restart: always
      networks:
        - app-network
    nginx:
      build: ./requirements/nginx/
      depends_on:
        - wordpress
      container_name: nginx
      restart: always
      ports:
          - 443:443
      networks:
          - app-network

networks:
  app-network:
    driver: bridge

Here I tried to build 3 services mysql, wordpress and nginx.
dockerfile for nginx
FROM debian:buster

RUN apt-get -y update

RUN apt-get -y upgrade

RUN apt-get install -y nginx vim procps openssl net-tools php-gd php-xml

COPY ./nginx.conf /etc/nginx/sites-available/default

RUN mkdir -p /etc/ssl/private

RUN chmod 700 /etc/ssl/private

RUN openssl req -x509 -nodes -days 365 -subj "/C=RF/ST=London/L=London/O=innoaca/OU=student/CN=rusya" -newkey rsa:2048 -keyout /etc/ssl/nginx-selfsigned.key -out /etc/ssl/nginx-selfsigned.crt;

CMD ["nginx", "-g", "daemon off;"]

In dockerfile for nginx I just installed it.
nginx.conf
   server {
        listen 443 ssl;
        listen [::]:443 ssl;
        server_name localhost;

        ssl on;

        ssl_certificate /etc/ssl/nginx-selfsigned.crt;
        ssl_certificate_key /etc/ssl/nginx-selfsigned.key;

        ssl_protocols TLSv1.3;

        root /var/www/html;
        index index.php index.html index.htm index.nginx-debian.html;

        location / {
                try_files $uri $uri/ =405;
        }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass wordpress:/run/php/php7.3-fpm.sock;
        }
}

Here I tried to use socket, I need that nginx and worpress communicate on 9000 port.
dockerfile for wordpress
FROM debian:buster

RUN apt-get -y update

RUN apt-get -y upgrade

RUN apt-get -y install vim wget nginx php-cli php-fpm php-mysql php-json php-opcache php-mbstring php-xml php-gd php-curl mariadb-server

WORKDIR /var/www/html/

RUN wget https://wordpress.org/latest.tar.gz

RUN tar -xvzf latest.tar.gz

RUN rm -rf latest.tar.gz

COPY ./wp-config.php ./wordpress/

RUN chown -R www-data:www-data /var/www/html/wordpress

RUN chmod -R 755 /var/www/html/wordpress

RUN sed -i '36 s/\/run\/php\/php7.3-fpm.sock/9000/' /etc/php/7.3/fpm/pool.d/www.conf

CMD ["/usr/sbin/php-fpm7.3", "daemon off"]

In dockerfile for wordpress I changed "listen = /var/run/fastcgi.sock" to "listen = 9000" in /etc/php/7.3/fpm/pool.d/www.conf.
I am not sure in last string "CMD ["/usr/sbin/php-fpm7.3", "daemon off"]", but hope that its wright, I wanted that the container would be always up, but I could make a mistake.


text:
Q: What's wrong with my Facebook app redirect URI? I'm developing an application and I'm configuring the Facebook application.
For the login I'm setting the Valid OAuth Redirect URIs to a working url.
However if I press Save, I get an error message, that says 'This url has bee identified as malicious and/or abusive.' There's nothing like that on the url. It only responds with a json:
    {"message": "The user declined the authorization"}
I've already tried the Facebook Debugger, but it only responds with:
    We can't review this website because the content doesn't meet our Community Standards. If you think this is a mistake, please let us know.
I thought it might be the 401 response status code, but it accepts a different url with the same status code.
I'm out of ideas.
Update: It seems like Facebook thinks my whole domain is malicious, no url with this particular domain can be added to Rewrite URI, nor can be shared by Facebook. I wrote them with the 'Let us know' option. but no naswers so far.

A: That error response should be pretty self explanatory and since you even confirmed that this URL is blocked you should use the available "let us know" function is the Sharing Debugger if you think it was blocked due to an error.