text:
Q: Trying to alter 'createdTime' in google docs with Google Apps Script. Getting Error 403 ..."field not writable". Any workaround? Full error message:

Request failed for https://www.googleapis.com returned code 403. Truncated server response: { "error": { "errors": [ { "domain": "global", "reason": "fieldNotWritable", "message": "The resource body includes fields which ... (use muteHttpExceptions option to examine full response). (line 13, file "Code")

The code below worked with 'viewedByMeTime' & 'modifiedTime'
function myFunction() {
  var newModifiedTime = "2019-01-01T00:00:00.000Z";
  var fileId = "1LaKH-wsjgGrCyG6zpbyzsBgsgTah2jQRIIDvDKaaRio";
  var url = "https://www.googleapis.com/drive/v3/files/" + fileId;

var params = {
    method: "patch",
    headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},//Last time opend by you
    payload: JSON.stringify({createdTime: newModifiedTime}),
    contentType: "application/json",
  };
  UrlFetchApp.fetch(url, params);

A: You appear to be trying to do a file.update

"fieldNotWritable"

means exactly that not all of the fields can be writen to.  which means you cant update every fields. and create time is one of the fields that you cant update.  if you check the documentation under request body you will see the fields you are allowed to update.


text:
Q: Items of LongListMultiSelector horizontally For several hours I have tried to change my LongListMultiSelector from WP toolkit to show its items horizontally like on the screenshot below (from Panorama Sample).

I even tried with changing its Template but with no possitive effects.
Thanks a lot for any help.

A: Ok. I finally did it. If somebody will have the same problem here is my solution.
I always try to avoid solving layout problems in WP by code behind way but exceptionally I did it this way.
My XAML:
<Grid Margin="10 -30 0 0" Name="GridWithLLMS">
    <toolkit:LongListMultiSelector LayoutMode="Grid"
        ItemsSource="{Binding Items}"
        GridCellSize="255,190"
        toolkit:TiltEffect.IsTiltEnabled="True"
        EnforceIsSelectionEnabled="True"
        Margin="0"
    />
</Grid>

My code:
public AddNewTrainingPage()
{
    InitializeComponent();

    SetWidthOfGridWithExercisesDependingOnQuantityOfItems();
    DataContext = App.Db;
}

private void SetWidthOfGridWithExercisesDependingOnQuantityOfItems()
{
    ExercisesListGrid.Width = ((App.Db.Items.Count / 3) + 1) * 270;
}

Where:

*

*3 is number of rows I want to have

*255 is width of 1 LongListMultiSelectorItem (+ potential margin width)

Of course I assume my LongListMultiSelector's items won't change. If you want to make it working with dynamic collection of elements you should bind the width of LongListMultiSelector to the property with quantity of your collection's items in your ViewModel

A: Check this out
http://www.geekchamp.com/articles/wp7-longlistselector-in-depth--part2-data-binding-scenarios
The code snippet in the last will help.
<toolkit:LongListSelector.GroupItemsPanel>
   <ItemsPanelTemplate>
      <toolkit:WrapPanel/>
    </ItemsPanelTemplate>
 </toolkit:LongListSelector.GroupItemsPanel>

redpajama_set_name: RedPajamaStackExchange


text:
Q: DrawerLayout with nested ViewPager - swiping in ViewPager I have a ViewPager in my DrawerLayout and I want it to handle the swipe gestures, but the parent DrawerLayout does handle them and so the ViewPager does not work if the swipe direction matches the DrawerLayout's close direction...
I tried arround with requestDisallowInterceptTouchEvent on the DrawerLayout but this seems to have no effect at all...
Does anyone know how to solve that?


text:
Q: How to remove " [ ] \ from string I have a string
"[\"1,1\",\"2,2\"]"

and I want to turn this string onto this
1,1,2,2

I am using Replace function for that like
obj.str.Replace("[","").Replace("]","").Replace("\\","");

But it does not return the expected result.
Please help.

A: You haven't removed the double quotes. Use the following:
obj.str = obj.str.Replace("[","").Replace("]","").Replace("\\","").Replace("\"", "");

A: Here is an optimized approach in case the string  or the list of exclude-characters is long:
public static class StringExtensions
{
    public static String RemoveAll(this string input, params Char[] charactersToRemove)
    {
        if(string.IsNullOrEmpty(input) || (charactersToRemove==null || charactersToRemove.Length==0))
            return input;

        var exclude = new HashSet<Char>(charactersToRemove); // removes duplicates and has constant lookup time
        var sb = new StringBuilder(input.Length);
        foreach (Char c in input)
        {
            if (!exclude.Contains(c))
                sb.Append(c);
        }
        return sb.ToString();
    }
}

Use it in this way:
str = str.RemoveAll('"', '[', ']', '\\');
// or use a string as "remove-array":
string removeChars = "\"{[]\\";
str = str.RemoveAll(removeChars.ToCharArray());

A: You should do following:
obj.str = obj.str.Replace("[","").Replace("]","").Replace("\"","");

string.Replace method does not replace string content in place. This means that if you have
string test = "12345" and do
test.Replace("2", "1");

test string will still be "12345". Replace doesn't change string itself, but creates new string with replaced content. So you need to assign this new string to a new or same variable
changedTest = test.Replace("2", "1");

Now, changedTest will containt "11345".
Another note on your code is that you don't actually have \ character in your string. It's only displayed in order to escape quote character. If you want to know more about this, please read MSDN article on string literals.

A: how about
var exclusions = new HashSet<char>(new[] { '"', '[', ']', '\\' });
return new string(obj.str.Where(c => !exclusions.Contains(c)).ToArray());

To do it all in one sweep.
As Tim Schmelter writes, if you wanted to do it often, especially with large exclusion sets over long strings, you could make an extension like this.
public static string Strip(
        this string  source,
        params char[] exclusions)
{
    if (!exclusions.Any())
    {
        return source;
    }

    var mask = new HashSet<char>(exclusions);
    var result = new StringBuilder(source.Length);
    foreach (var c in source.Where(c => !mask.Contains(c)))
    {
        result.Append(c);
    }

    return result.ToString();
}

so you could do,
var result = "[\"1,1\",\"2,2\"]".Strip('"', '[', ']', '\\');

A: Capture the numbers only with this regular expression [0-9]+ and then concatenate the matches:
var input = "[\"1,1\",\"2,2\"]";
var regex = new Regex("[0-9]+");
var matches = regex.Matches(input).Cast<Match>().Select(m => m.Value);
var result = string.Join(",", matches);


text:
Q: jQuery Ajax: pdf response I have a link and when user click on it, then he get a PDF. In jQuery, I create a POST ajax call to the server to get the PDF. The response is a PDF, with correct content headers etc that would normally cause the browser to open the Reader plugin, or allow the user to save the PDF. But in my case, this is not working. Is there any way to set data content type, or set content type to PDF?
My ajax call:
$('#sf_getpdf').click(function() {

 $.ajax({    //create an ajax request to load_page.php

        type: "POST",

        url: "index.php?route=sale/order/superfaktura_getpdf&token=<?php echo $token; ?>",

        data: 'invoice_id=<?php echo $invoice_id; ?>&sf_token=<?php echo $sf_token ?>',  //with the page number as a parameter

        dataType: "text",   //expect html to be returned

        success: function(msg){

            if(parseInt(msg)!=0)    //if no errors

            {

            document.write(msg)
            }

        }

    });

});

Firebug, response:

Response in browser...

I already tried to set content-type in server, without success:

Edit: The Ajax is not needed, to do this.
<a id="adr_stitok" target="_blank" href="index.php?route=sale/order/superfaktura_getpdf&token=<?php echo $token; ?>&invoice_id=<?php echo $invoice_id; ?>&sf_token=<?php echo $sf_token ?>" >Download

Will do the thing.

A: Be sure your server side returns a downloadeable content and make a submit to the file, something like:
            //$.download('path', 'data' [, 'post'])
            $.download = function(url, data, method) {
                //url and data options required
                if(url && data) {
                    var form = $('<form />', { action: url, method: (method || 'get') });
                    $.each(data, function(key, value) {
                        var input = $('<input />', {
                            type: 'hidden',
                            name: key,
                            value: value
                        }).appendTo(form);
                    });
                return form.appendTo('body').submit().remove();
                }
            throw new Error('$.download(url, data) - url or data invalid');
            };

$.download("index.php?route=sale/order/superfaktura_getpdf&token=<?php echo $token; ?>", {}, 'post')

A: It won't work because AJAX calls do NOT fetch PDF and load it inside the browser. That's why it's called XMLHttpRequest.. it only exchanges just text!


text:
Q: How to switch between themes in mezzanine? I am exploring Djanngo-cms and Mezzanine both for content management.
With Mezzannine you can add new themes into the INSTALLED_APPS like this -
INSTALLED_APPS = (
    "flat",     # current_active theme
    #"moderna",
    #"nova",
    #"solid",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.redirects",
    "django.contrib.sessions",
    "django.contrib.sites",
    "django.contrib.sitemaps",
    "django.contrib.staticfiles",
    "mezzanine.boot",
    "mezzanine.conf",
    "mezzanine.core",
    "mezzanine.generic",
    "mezzanine.blog",
    "mezzanine.forms",
    "mezzanine.pages",
    "mezzanine.galleries",
    "mezzanine.twitter",
    #"mezzanine.accounts",
    #"mezzanine.mobile",
)

If I need to give the customer an option to switch between themes flat and moderna, how would I achieve that, is there a plugin?


text:
Q: Calculate top-level of hierarchy path? I have a classstructure table:
create table classstructure (classstructureid number(8,0), classificationid varchar2(25), parent number(8,0));

insert into classstructure(classstructureid, classificationid, parent) values(1001, 'FLEET', null);
insert into classstructure(classstructureid, classificationid, parent) values(1002, 'LIGHTDUTYVEHICLE', 1001);
insert into classstructure(classstructureid, classificationid, parent) values(1004, 'MEDIUMDUTYVEHICLE', 1001);
insert into classstructure(classstructureid, classificationid, parent) values(1022, 'ACTIVETRANSPORTATION', null);
insert into classstructure(classstructureid, classificationid, parent) values(1023, 'FACILITYWALKWAY', 1022);
insert into classstructure(classstructureid, classificationid, parent) values(1024, 'TRAIL', 1022);
insert into classstructure(classstructureid, classificationid, parent) values(1085, 'SIDEWALK', 1022);
insert into classstructure(classstructureid, classificationid, parent) values(1091, 'SDWRAMP', 1085);
commit;

select * from classstructure;

CLASSSTRUCTUREID CLASSIFICATIONID              PARENT
---------------- ------------------------- ----------
            1001 FLEET
            1002 LIGHTDUTYVEHICLE                1001
            1004 MEDIUMDUTYVEHICLE               1001

            1022 ACTIVETRANSPORTATION
            1023 FACILITYWALKWAY                 1022
            1024 TRAIL                           1022
            1085 SIDEWALK                        1022
            1091 SDWRAMP                         1085

I would like to calculate the top level of each row's hierarchy path:
CLASSSTRUCTUREID TOP LEVEL
---------------- ---------
1001             FLEET
1002             FLEET
1004             FLEET

1022             ACTIVETRANSPORTATION
1023             ACTIVETRANSPORTATION
1024             ACTIVETRANSPORTATION
1085             ACTIVETRANSPORTATION
1091             ACTIVETRANSPORTATION

Is it possible to do this with Oracle 18c SQL?

A: You can use a hierarchical query, with connect_by_root:
select classstructureid, connect_by_root(classificationid)
from classstructure
connect by parent = prior classstructureid
start with parent is null;

db<>fiddle


text:
Q: Show that the linear map is surjective We have the linear map $f:\mathbb{R}^3\rightarrow \mathbb{R}^2, \ \begin{pmatrix}x_1 \\ x_2 \\ x_3\end{pmatrix}\mapsto \begin{pmatrix}x_3 \\ x_1\end{pmatrix}$.
I have shown that this map is not injective, since the kernel doesn't contain only the zero vector.
Now I want to show that this map is surjective.
For that we want that for each $z\in \mathbb{R}^2$  there is vector in $\mathbb{R}^3$ such that $f\begin{pmatrix}x_1 \\ x_2 \\ x_3\end{pmatrix}=z$.
So $z$ is in the form $\begin{pmatrix}x_3 \\ x_1\end{pmatrix}$. Therefore we already have the values $x_1$ and $x_3$ and we can arbitrarily choose $x_2$.
Is that corect toshow the surjectivity of $f$ ?


text:
Q: Lua project compiling with errors (luabind) I trying to make some HelloWorld with Lua + Luabind in Visual Studio 2010. I downloaded Lua src from here and added it's source files into project. Then I download and added source of luabind. Finaly added main.cpp. So after that tried to compile project and got errors in mostly all luabind files:
error C3861: 'lua_strlen': identifier not found
error C2065: 'LUA_GLOBALSINDEX' : undeclared identifier

Please help me what I did wrong? What files I must add to project? Maybe some additional library? What best practice to organize lua projects?

A: It seems that luabind is written for Lua 5.1 and you've downloaded Lua 5.2.


text:
Q: How to show HTML or Markdown in a SwiftUI Text? How can I set a SwiftUI Text to display rendered HTML or Markdown?
Something like this:
Text(HtmlRenderedString(fromString: "Hi!"))

or for MD:
Text(MarkdownRenderedString(fromString: "**Bold**"))

Perhaps I need a different View?

A: You can try to use the package https://github.com/iwasrobbed/Down, generate HTML or MD from you markdown string, then create a custom UILabel subclass and make it available to SwiftUI like in the following example:
struct TextWithAttributedString: UIViewRepresentable {

    var attributedString: NSAttributedString

    func makeUIView(context: Context) -> ViewWithLabel {
        let view = ViewWithLabel(frame: .zero)
        return view
    }

    func updateUIView(_ uiView: ViewWithLabel, context: Context) {
        uiView.setString(attributedString)
    }
}

class ViewWithLabel : UIView {
    private var label = UILabel()

    override init(frame: CGRect) {
        super.init(frame:frame)
        self.addSubview(label)
        label.numberOfLines = 0
        label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setString(_ attributedString:NSAttributedString) {
        self.label.attributedText = attributedString
    }

    override var intrinsicContentSize: CGSize {
        label.sizeThatFits(CGSize(width: UIScreen.main.bounds.width - 50, height: 9999))
    }
}

I have kind of success with that but cannot get the frame of the label subclass right. Maybe I need to use GeometryReader for that.

A: Some people advise to use WKWebView or UILabel, but these solutions are terribly slow or inconvenient. I couldn't find a native SwiftUI solution, so I implemented my own (AttributedText). It's quite simple and limited in its functionality, but it works quickly and satisfies my needs. You can see all features in the README.md file. Feel free to contribute if the existing functionality is not enough for you.
Code example
AttributedText("This is bold and italic text.")

Result

A: Text can just display Strings.
You can use a UIViewRepresentable with an UILabel and attributedText.
Probably attributedText text support will come later for SwiftUI.Text.

A: iOS 15 (beta)
Text now supports basic Markdown!
struct ContentView: View {
    var body: some View {
        VStack {
            Text("Regular")
            Text("*Italics*")
            Text("**Bold**")
            Text("~Strikethrough~")
            Text("`Code`")
            Text("[Link](https://apple.com)")
            Text("***[They](https://apple.com) ~are~ `combinable`***")
        }
    }
}

Result:

However, if you store a String that contains Markdown in a property, it doesn't render. I'm pretty sure this is a bug.
struct ContentView: View {
    @State var textWithMarkdown = "***[They](https://apple.com) ~are~ `combinable`***"
    var body: some View {
        Text(textWithMarkdown)
    }
}

Result:

You can work around this by converting textWithMarkdown to an AttributedString, using init(markdown:options:baseURL:).
struct ContentView: View {
    @State var textWithMarkdown = "***[They](https://apple.com) ~are~ `combinable`***"
    var body: some View {
        Text(textWithMarkdown.markdownToAttributed()) /// pass in AttributedString to Text
    }
}

extension String {
    func markdownToAttributed() -> AttributedString {
        do {
            return try AttributedString(markdown: self) /// convert to AttributedString
        } catch {
            return AttributedString("Error parsing markdown: \(error)")
        }
    }
}

Result:

A: Since iOS 15, Text can have an AttributedString parameter.
No UIViewRepresentable necessary
Since NSAttributedString can be created from HTML, the process is straight forward:
import SwiftUI

@available(iOS 15, *)
struct TestHTMLText: View {
    var body: some View {
        let html = "
Heading

paragraph.
"

        if let nsAttributedString = try? NSAttributedString(data: Data(html.utf8), options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil),
           let attributedString = try? AttributedString(nsAttributedString, including: \.uiKit) {
            Text(attributedString)
        } else {
            // fallback...
            Text(html)
        }
    }
}

@available(iOS 15, *)
struct TestHTMLText_Previews: PreviewProvider {
    static var previews: some View {
        TestHTMLText()
    }
}

The code renders this:

A: If you don't need to specifically use a Text view. You can create a UIViewRepresentable that shows a WKWebView and simple call loadHTMLString().
import WebKit
import SwiftUI

struct HTMLStringView: UIViewRepresentable {
    let htmlContent: String

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.loadHTMLString(htmlContent, baseURL: nil)
    }
}

In your body simple call this object like this:
import SwiftUI

struct Test: View {
    var body: some View {
        VStack {
            Text("Testing HTML Content")
            Spacer()
            HTMLStringView(htmlContent: "
This is HTML String
")
            Spacer()
        }
    }
}

struct Test_Previews: PreviewProvider {
    static var previews: some View {
        Test()
    }
}

A: I created a markdown library specifically for SwiftUI:
https://github.com/Lambdo-Labs/MDText
Feel free to contribute!

A: As far as rendering HTML in swiftUI there are a number of solutions, but for rendering it as a generic UILabel via AttributedText, this is what I went with after combining a few other solutions I found.
Here is the UIViewRepresentable which you'll use from your parent swiftUI views:
//Pass in your htmlstring, and the maximum width that you are allowing for the label
//this will, in turn, pass back the size of the newly created label via the binding 'size' variable
//you must use the new size variable frame on an encompassing view of wherever this htmlAttributedLabel now resides (like in an hstack, etc.)
struct htmlAttributedLabel: UIViewRepresentable {
    @Binding var htmlText: String
    var width: CGFloat
    @Binding var size:CGSize
    var lineLimit = 0
    //var textColor = Color(.label)

    func makeUIView(context: Context) -> UILabel {
        let label = UILabel()
        label.lineBreakMode = .byWordWrapping
        label.numberOfLines = lineLimit
        label.preferredMaxLayoutWidth = width
        //label.textColor = textColor.uiColor()
        return label
    }

    func updateUIView(_ uiView: UILabel, context: Context) {
    let htmlData = NSString(string: htmlText).data(using: String.Encoding.unicode.rawValue)
    let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]
    DispatchQueue.main.async {
        do {
            let attributedString = try NSMutableAttributedString(data: htmlData!, options: options, documentAttributes: nil)
            //add attributedstring attributes here if you want
            uiView.attributedText = attributedString
            size = uiView.sizeThatFits(CGSize(width: width, height: CGFloat.greatestFiniteMagnitude))
            print("htmlAttributedLabel size: \(size)")
        } catch {
            print("htmlAttributedLabel unexpected error: \(error).")
        }
    }
}

Now, to use this label effectively, you'll need to provide it a maximum width, which you can get from geometry reader.  You'll also need to pass in a CGSize binding so the label can tell the parent view how much space it needs to render.  You'll in turn use this size to set an encompassing view height, so that the rest of swiftUI can layout around your html label appropriately:
@State var htmlText = "Hello,
I am HTML!"
@State var size:CGSize = .zero
var body: some View {
    HStack {
        GeometryReader { geometry in
                                htmlAttributedLabel(htmlText: $htmlText, width: geometry.size.width, size: $size).frame(width:size.width, height: size.height). //the frame is important to set here, otherwise sometimes it won't render right on repeat loads, depending on how this view is presented
                       }
           }.frame(height: size.height) //most important, otherwise swiftui won't really know how to layout things around your attributed label
}

You can also set line limits, or text color, etc., and obviously you can extend this object to take in whatever UIlabel parameters you'd like to use.

A: Since I have found another solution I would like to share it with you.
Create a new View Representable
struct HTMLText: UIViewRepresentable {

   let html: String

   func makeUIView(context: UIViewRepresentableContext<Self>) -> UILabel {
        let label = UILabel()
        DispatchQueue.main.async {
            let data = Data(self.html.utf8)
            if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
                label.attributedText = attributedString
            }
        }

        return label
    }

    func updateUIView(_ uiView: UILabel, context: Context) {}
}

And use it later like this:
HTMLText(html: "
Your html string
")

A: For rendering HTML, I use extension of String for convert to Attributed HTML String and extension of UIColor for working with hex color
extension String {
    func htmlAttributedString(
        fontSize: CGFloat = 16,
        color: UIColor = UIColor(Color.theme.body),
        linkColor: UIColor = UIColor(Color.theme.primary),
        fontFamily: String = "Roboto"
    ) -> NSAttributedString? {
        let htmlTemplate = """
        <!doctype html>

            <link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet'>

            \(self)

        """

        guard let data = htmlTemplate.data(using: .unicode) else {
            return nil
        }

        guard let attributedString = try? NSAttributedString(
            data: data,
            options: [.documentType: NSAttributedString.DocumentType.html],
            documentAttributes: nil
            ) else {
            return nil
        }

        return attributedString
    }
}

extension UIColor {
    var hexString:String? {
        if let components = self.cgColor.components {
            let r = components[0]
            let g = components[1]
            let b = components[2]
            return  String(format: "#%02x%02x%02x", (Int)(r * 255), (Int)(g * 255), (Int)(b * 255))
        }
        return nil
    }
}

And use it later like this:
import SwiftUI

struct ContentView: View {

    @State var htmlText = """
        Example
    """

    var body: some View {
        if let nsAttrString = htmlText.htmlAttributedString() {
            Text(AttributedString(nsAttrString))
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

A: New since Swift 5.7 - convert from "basic" HTML
Swift 5.7 brought new functionalities related to regex. A new RegexBuilder was implemented in addition to the existing regex support, and that makes it easier to extrapolate the strings in HTML tags.
With little work, we can build a converter from "basic" HTML codes to markdown. By "basic" I mean:

*

*they contain line breaks, bold, italic (no attributes)

*they can contain hyperlinks, and that's the complicated part of the converter below

*they do not contain headers, scripts, id attributes...

Of course, with more effort, anything can be achieved, but I'm going to stick with the basic example.
The String extension:

extension String {
    func htmlToMarkDown() -> String {

        var text = self

        var loop = true

        // Replace HTML comments, in the format
        // Stop looking for comments when none is found
        while loop {

            // Retrieve hyperlink
            let searchComment = Regex {
                Capture {

                    // A comment in HTML starts with:
                    ""
                }
            }
            if let match = text.firstMatch(of: searchComment) {
                let (_, comment) = match.output
                text = text.replacing(comment, with: "")
            } else {
                loop = false
            }
        }

        // Replace line feeds with nothing, which is how HTML notation is read in the browsers
        var text = self.replacing("\n", with: "")

        // Line breaks
        text = text.replacing("
", with: "\n")
        text = text.replacing("
", with: "")
        text = text.replacing("
", with: "\n")
        text = text.replacing("
", with: "\n")

        // Text formatting
        text = text.replacing("", with: "**")
        text = text.replacing("", with: "**")
        text = text.replacing("", with: "**")
        text = text.replacing("", with: "**")
        text = text.replacing("", with: "*")
        text = text.replacing("", with: "*")
        text = text.replacing("", with: "*")
        text = text.replacing("", with: "*")

        // Replace hyperlinks block

        loop = true

        // Stop looking for hyperlinks when none is found
        while loop {

            // Retrieve hyperlink
            let searchHyperlink = Regex {

                // A hyperlink that is embedded in an HTML tag in this format: <a... href="<hyperlink>"....>
                "<a"

                // There could be other attributes between <a... and href=...
                // .reluctant parameter: to stop matching after the first occurrence
                ZeroOrMore(.any)

                // We could have href="..., href ="..., href= "..., href = "...
                "href"
                ZeroOrMore(.any)
                "="
                ZeroOrMore(.any)
                "\""

                // Here is where the hyperlink (href) is captured
                Capture {
                    ZeroOrMore(.any)
                }

                "\""

                // After href="<hyperlink>", there could be a ">" sign or other attributes
                ZeroOrMore(.any)
                ">"

                // Here is where the linked text is captured
                Capture {
                    ZeroOrMore(.any, .reluctant)
                }
                One("")
            }
                .repetitionBehavior(.reluctant)

            if let match = text.firstMatch(of: searchHyperlink) {
                let (hyperlinkTag, href, content) = match.output
                let markDownLink = "[" + content + "](" + href + ")"
                text = text.replacing(hyperlinkTag, with: markDownLink)
            } else {
                loop = false
            }
        }

        return text
    }
}

Usage:
HTML text:
let html = """

You need to follow this link here: sample site

"""

Markdown conversion:
let markdown = html.htmlToMarkDown()
print(markdown)

// Result:
// You need to **follow *this* link** here: [sample site](https://example.org/en)

In SwiftUI:
Text(.init(markdown))

What you see:


text:
Q: How to make a KeyListener draw an Image for a Java applet I am trying to make a java applet game for class that allow the user to enter up and down to move the "player" image and shoot the "zombies" using the space bar. I have a "bullet" image and am trying to use a KeyListener so that when the user presses the space bar, the "bullet" image is displayed on the screen at the players current location and travels across the screen. However when space is pressed, I get a run time error and the bullet image isn't displayed. If anyone could let me know how to fix this I would greatly appreciate it!
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class ZombieAttackMain extends Applet implements Runnable, KeyListener{

    private Image background, normalZombie, fastZombie, tankyZombie,player,bullet, bloodSplat, cow;

    private Graphics bufferGraphics;
    private Graphics g;
    private Image offScreen;

    private final int POSITION_1_Y = 100;
    private final int POSITION_2_Y = 255;
    private final int POSITION_3_Y = 400;
    private final int POSITION_4_Y = 550;

    private final int PLAYER_X_POSITION = 250;
    private int playerYPosition = POSITION_3_Y;

    private int zombieStartingXPosition = 1000; //change to 1100 later
    private final int NORMAL_ZOMBIE_DX = -2;    //not final
    private final int FAST_ZOMBIE_DX = -3;      //not final
    private final int TANKY_ZOMBIE_DX = -1;     //not final
    private int zombieYPosition; //depends on the zombieYPositionRandom

    private int bulletStartingXPosition = 405;
    private int bulletYPosition;    //depends on player position
    private final int BULLET_DX = 5;    //not final

    private int bloodSplatX, bloodSplatY; //depend on dead zombie position

    //Called when applet starts
    public void init(){
        setSize(1100, 700);
        normalZombie = getImage(getCodeBase(), "NormalZombie.png");
        tankyZombie = getImage(getCodeBase(), "TankyZombie.png");
        fastZombie = getImage(getCodeBase(), "FastZombie.png");
        player = getImage(getCodeBase(), "Player.png");
        bullet = getImage(getCodeBase(), "Bullet.png");
        bloodSplat = getImage(getCodeBase(), "BloodSplat.png");
        background = getImage(getCodeBase(), "Background.jpg");
        cow = getImage(getCodeBase(), "Cow.png");
        addKeyListener(this);
    }
    //Called after init, sets up thread and starts it
    public void start() {
        Thread thread = new Thread(this);
        thread.start();
    }

    public void run() {
        while(true){
            repaint();
            try {
                Thread.sleep(17);     //about 60 fps
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void update(Graphics g){
        if(offScreen == null){
            offScreen = createImage(this.getWidth(), this.getHeight());
            bufferGraphics = offScreen.getGraphics();
        }
        bufferGraphics.setColor(getBackground());
        bufferGraphics.fillRect(0,0,this.getWidth(),this.getHeight());

        bufferGraphics.setColor(getForeground());
        paint(bufferGraphics);

        g.drawImage(offScreen,0,0,this);
    }

    public void paint(Graphics g){
        g.drawImage(background,0,0,null);
        g.drawImage(cow,-15,115,null);
        g.drawImage(cow,-15,255,null);
        g.drawImage(cow,-15,400,null);
        g.drawImage(cow,-15,550,null);
        g.drawImage(normalZombie,zombieStartingXPosition,100,null);
        g.drawImage(tankyZombie,zombieStartingXPosition,400,null);
        g.drawImage(fastZombie,zombieStartingXPosition,255,null);
        g.drawImage(player,PLAYER_X_POSITION,playerYPosition, null);
        //g.drawImage(bullet,bulletStartingXPosition,336,this);
        g.drawImage(bloodSplat,bloodSplatX,bloodSplatY,null);
    }

    public void moveUp(Image player){
        if(playerYPosition == POSITION_2_Y){
            playerYPosition = POSITION_1_Y;
        }
        if(playerYPosition == POSITION_3_Y){
                playerYPosition = POSITION_2_Y;
        }
        if(playerYPosition == POSITION_4_Y){
            playerYPosition = POSITION_3_Y;
        }
    }

    public void moveDown(Image player){
        if(playerYPosition == POSITION_3_Y){
            playerYPosition = POSITION_4_Y;
        }
        if(playerYPosition == POSITION_2_Y){
            playerYPosition = POSITION_3_Y;
        }
        if(playerYPosition == POSITION_1_Y){
            playerYPosition = POSITION_2_Y;
        }

    }

    public void spawnBullet(){
        g.drawImage(bullet,bulletStartingXPosition, playerYPosition,null);
    }

    public void keyPressed(KeyEvent e) {
        switch(e.getKeyCode()){
        case KeyEvent.VK_UP:
            moveUp(player);
            break;
        case KeyEvent.VK_DOWN:
            moveDown(player);
            break;
        case KeyEvent.VK_SPACE:
            spawnBullet();
            break;
        }
    }

    public void keyReleased(KeyEvent e) {

    }

    public void keyTyped(KeyEvent e) {

    }

    public void stop() {

    }

    public void destroy() {

    }
}

Error Message:
Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
    at ZombieAttackMain.spawnBullet(ZombieAttackMain.java:118)
    at ZombieAttackMain.keyPressed(ZombieAttackMain.java:130)
    at java.awt.Component.processKeyEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

A: Your problem is that you never initialize your private Graphics g. This might not seem obvious at first, because your paint() and update() methods use g just fine, but in those methods, g is a completely different, local Graphics object which is overshadowing your global g. My suggestion would be to remove the private Graphics g; because there's really no need to have another Graphics object floating around, and change spawnBullet() to:
public void spawnBullet(){
    bufferGraphics.drawImage(bullet, bulletStartingXPosition, playerYPosition, null);
}

However, because you clear the entire screen every update, this will not show the bullet... It would be even better to only draw in the paint() method, but that is a different topic altogether.
EDIT: showing an example of how to get the bullet to actually show
private int bulletStartingXPosition = 405;
private int bulletYPosition;    //depends on player position
private final int BULLET_DX = 5;    //not final

// NEW STUFF
private int bulletXPosition;
private boolean showingBullet = false;

public void paint(Graphics g){
    g.drawImage(background,0,0,null);
    g.drawImage(cow,-15,115,null);
    g.drawImage(cow,-15,255,null);
    g.drawImage(cow,-15,400,null);
    g.drawImage(cow,-15,550,null);
    g.drawImage(normalZombie,zombieStartingXPosition,100,null);
    g.drawImage(tankyZombie,zombieStartingXPosition,400,null);
    g.drawImage(fastZombie,zombieStartingXPosition,255,null);
    g.drawImage(player,PLAYER_X_POSITION,playerYPosition, null);
    //g.drawImage(bullet,bulletStartingXPosition,336,this);
    g.drawImage(bloodSplat,bloodSplatX,bloodSplatY,null);

    // NEW STUFF
    if (showingBullet) {
       g.drawImage(bullet,bulletXPosition, playerYPosition, null);
       bulletXPosition += BULLET_DX;
       if (bulletXPosition > 1100) { // if it went off the screen
           showingBullet = false;
       }
    }
}

public void spawnBullet() {

    // NEW STUFF
    if (showingBullet) {
        return; // don't want to reset the bullet if it's already on the screen
    }
    showingBullet = true;
    bulletXPosition = bulletStartingXPosition;
}


text:
Q: RSA decryption according to the private key reports an error My code using RSA on the front end:
const rsa = new JSEncrypt();
rsa.setPublicKey(k);
const resultText = rsa.encrypt("violet");
console.log(resultText);

My code using RSA in the backend:
byte[] inputByte = org.apache.commons.codec.binary.Base64.decodeBase64(str.getBytes("UTF-8"));
byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(privateKey);
PrivateKey priKey = KeyFactory.getInstance("RSA").generatePrivate(new
PKCS8EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE,priKey);
String outStr=new String(cipher.doFinal(inputByte));
return outStr;

PublicKey like this:
    -----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA13gYdCmOjR9yqQD7ldzG
ZXabSon6SiLceCK6vRXf4NMbF+EQke0vRpqU3IZ/S1pFdvoQswQabsA4zf0WACVT
iaGIhWDlPu3mecri8rYtmOSfd8GCE0vEgFNvSD6IXRLPeLCB+i7WENBa4fCEtW8W
Hzdas96CLiESbjSAruRasQXP2OLqEA2GU83/069vh8uRKzui+yw0aAXZFyFyFRFa
lxYltFadVpz3+kBplvpzuj82t4fc3yCRbrpeRyTyX1sz0ULSxx/k3/p1OuJtIq9Y
9uN0G4gxhcDFJ4L41uXOln5CPapk7tlsYobhhvxYHw1rrweY+06hrQ7r0Hblv2nH
GQIDAQAB
-----END PUBLIC KEY-----

PrivateKey like this:
    -----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEA13gYdCmOjR9yqQD7ldzGZXabSon6SiLceCK6vRXf4NMbF+EQ
ke0vRpqU3IZ/S1pFdvoQswQabsA4zf0WACVTiaGIhWDlPu3mecri8rYtmOSfd8GC
E0vEgFNvSD6IXRLPeLCB+i7WENBa4fCEtW8WHzdas96CLiESbjSAruRasQXP2OLq
EA2GU83/069vh8uRKzui+yw0aAXZFyFyFRFalxYltFadVpz3+kBplvpzuj82t4fc
3yCRbrpeRyTyX1sz0ULSxx/k3/p1OuJtIq9Y9uN0G4gxhcDFJ4L41uXOln5CPapk
7tlsYobhhvxYHw1rrweY+06hrQ7r0Hblv2nHGQIDAQABAoIBAAyqFmXde294BblB
QYhRbafRDNeYvIlW+zZkdC1g98OzJMiGhf7NvhWcSFud3CWFrMeNcyXSe+s+iRgy
Y/SmPP6969RLGa5VNVK7RhOV+aAe7/COAyM3NNmGDehlJIaz8FXbqggWcKaUWIMn
K+WuHdK/4ijoTyZ+8yJfG6Er8tisryLQ9io9+op9g/ZWzaUKgu934/cDxUt70bfm
x+ZEPi6YfkJ1uOpXnnadDyw2RUDcvCM3fK3KF5fqM7SJAXY9b1pmLr+Ccn1qkT9G
I+QHidEsGfJciX5AoHnlIMLPMVIPKBbq4GwC/Ngb41LprNJWlPR38N2ySjky/Jyt
159XWHECgYEA9lx2KfFmyLyVjnkIF3JI50mSZAw4YPBBqB27UInacvxXbjfVURht
xK60GB9OkDbFdeNh89x86Gfwvm5bTq4W8YSH4Obd5Fg8XjTuaicTi03CSfF5SdJn
JLLOUmlqP75gkbEPNUoOfqhqq6IbyJVB3egyL90cd2/wCdJOVLEUly8CgYEA3+Y4
lNdl0xedkDNkWsCyyA4iPSUzVxsuch9hW/VGBwzga8rtiNllpKifVvctQOEu/KUe
vVQRF78ojZaMGT33l6TivnUL54z9Lo9uWghoG8TqMfnG34pFPe3R+zvGP87Hrozw
1EUhiMT198SlB/YHrgGGGlJbG+rlm5GIx3lEdDcCgYA4RSw0LlA0v2ZFkX14pYDj
WxmVwnjKI3ZLqObU4XfE1cA+i4AssrC3wNOfwt7V77ywTYxc/9qD1uHVDS3LzdWt
uoCyrOi3tDOtrNdb5asAIXWkIAR9CRLH/hNEHZHIF3rFLDT2DgE7iso6g59m9DiE
L/nulsleunGQPLnpfDzgvwKBgDRV5Q3tl3CTSZJGYQPRnTikDR7LzkdjJCUq7qAH
IhpNyTuJEKL3ZgnqHGzAlERhHpGRqzDIMMKjPUBzW0YfNPuuYA3y4Bh83UV/42SK
KIOtMK0D3JeuA2dparbWDw4lMIm9iiGkEyWcHH6Q6Z6FxN/InWcTrxZEfu0xRI6T
6wtbAoGAfl5dW9LNoaNfQbgIq+PJKZm9f1frza55mFTJgo3ravdb3GmzWVHN8xRf
nLKyKyNLqbkT35IGc39NkALJLxT5RibkAZLiUiwqdMF63sgODbA9AGTmhe+JHS+V
hBmFnCyp6UiN9E4ZAWcZQILa0rRMftMFngAJ3El0ZP+HziRnNzs=
-----END RSA PRIVATE KEY-----

Bu-t, when i do the java code decryption, it reported such an error:
java.security.InvalidKeyException: IOException : DerInputStream.getLength(): lengthTag=111, too big.

How can i solve this problem ?

A: 1. You are decoding wrong. PEM format has a dash-BEGIN line identifying the type of data, a block of base64 encoding the data, and a dash-END line. The BEGIN and END lines are part of the format, but they do not contain base64-encoded data; only the lines in between contain the base64-encoded data. You are apparently passing the whole thing, including the BEGIN and END lines, to commons.codec.Base64, which results in decoding a bunch of garbage before and after the actual data. That garbage isn't valid ASN.1 DER, so when Java tries to parse it as DER it fails.
2. Plus your data is not a PKCS8-clear privatekey. The PEM type 'RSA PRIVATE KEY' is an OpenSSL-defined format that contains a 'traditional' or 'legacy' format, namely the PKCS1 representation of the private key. This is not PKCS8, which is the only key format Java supports natively; that's why the spec class is named PKCS8EncodedKeySpec, because it is a key spec encoded as PKCS8 and more specifically PKCS8-clear. If you fix the above problem by removing the BEGIN and END lines before base64-decoding, Java can parse the result as DER, but not as a PKCS8-clear key; you get a different exception about 'algid parse error, not a sequence'. To fix this there are 5 approaches:

*

*change whatever process you use to initially generate the keypair so it generates PKCS8, not OpenSSL-legacy PKCS1. Especially since you need anyway to replace the keypair you compromised by publishing it, as 207421 said. You give no clue what that process is or was, so I can't give any details.

*convert your generated privatekey, or a copy, to PKCS8-clear. This is not programming or development and offtopic, but if you have or get OpenSSL (on the same or any accessible and secure system), you can do
openssl pkey -in oldfile -out newfile   # 1.0.0 up only, but older is now rare
# or
openssl pkcs8 -topk8 -nocrypt -in oldfile -out newfile   # even ancient versions

Once you have a PKCS8-clear file, just remove the BEGIN and END lines and base64-decode what is left, and pass that to KeyFactory as PKCS8EncodedKeySpec as you already do.

*

*use https://www.bouncycastle.org . The 'bcpkix' jar has (Java) code to read a large range of OpenSSL-supported PEM formats, including the RSA-PKCS1 private key format you have. There are lots of existing Qs about this; just search for PEMParser and JcaPEMKeyConverter.

*convert it yourself. Decode the body of the file you have, after removing the BEGIN and END lines, to get the PKCS1 key, then build the PKCS8 format for that key, and then pass it to KeyFactory as PKCS8EncodedKeySpec. See answers by Noa Resare and Jean-Alexis Aufauvre on Getting RSA private key from PEM BASE64 Encoded private key file or mine in Java: Convert DKIM private key from RSA to DER for JavaMail .

*do it entirely yourself. Decode the file you have without BEGIN/END to get PCKS1, parse that as DER following e.g. RFC8447, and build RSAPrivateCrtKeySpec. Some other As on the Q I linked just above do this. However, this requires either: using undocumented internal sun.* classes, which used to work in Java (hence the existing answers) but which 'modular' Java versions (9 up) since 2017 have steadily made more difficult or impossible; using BouncyCastle which has documented (and good) support for ASN.1 -- but then it's easier to use bcpkix for the whole job as above; or writing your own ASN.1 parsing, which is a good deal of work.
PS: encrypting text with RSA is usually a bad design; it's not suited for that. But that's not really a programming issue and doesn't belong here.


text:
Q: Windows 7 activate after renaming Do you need to re-activate Windows 7 after it has been renamed? The machine i'm talking about is a pc that is connected to a domain (at work).
Or is this not necessary?

A: Renaming your pc does not invalidate your activation status. Only big hardware changes or sometimes  BIOS updates.


text:
Q: How to add a Pmw tooltip to a rectangle object in a tkinter canvas? When the user hovers the mouse over the pink rectangle I want the program to display a tooltip in the same way that it would if you were to hover your mouse over a button. However, this doesn't work because I get the error >AttributeError: 'Bar' object has no attribute 'tk'. How do I bind a tooltip to a canvas rectangle in tkinter?
from tkinter import *
import Pmw

root = Tk()
Pmw.initialise(root)
canvas = Canvas()
canvas.config(width=800, height=700, bg='white')

class Bar:
   def __init__(self, x, y):
       self.x = x
       self.y = y
       self.bar = canvas.create_rectangle(x, y, x + 200, y + 200, fill='pink')

bar = Bar(200, 200)

# create balloon object and bind it to the widget
balloon = Pmw.Balloon(bar)
balloon.bind(bar, "Text for the tool tip")

lbl = balloon.component("label")
lbl.config(background="black", foreground="white")
# Pmw.Color.changecolor(lbl, background="black", foreground="white")

canvas.pack()
root.mainloop()

A: Use balloon.tagbind(Canvas/Text, tag, "tooltip text").
Minimal example:
import Pmw
from tkinter import *

root = Tk()
Pmw.initialise(root)
canvas = Canvas(root, width=800, height=700, bg="white")
canvas.pack()

bar1 = canvas.create_rectangle(50, 50, 100, 100, fill="pink")
bar2 = canvas.create_rectangle(300, 300, 500, 500, fill="red")

balloon = Pmw.Balloon()
balloon.tagbind(canvas, bar1, "first tooltip")
balloon.tagbind(canvas, bar2, "second tooltip")

root.mainloop()


text:
Q: Write a Text File (or PDF File) from Json in Xamarin.forms I am Trying to Write My listView (with multiple Binding Objects in it and user Entrys as input) to a Text file.
I came up with the Idea of Serialize it to Json and then write it to text with button clicked (I am new here :)). But I get stocked in Json Loops errors.
The name of my listView is LL:
private void Save_Clicked(object sender, EventArgs e)
{
    string Listi = JsonConvert.SerializeObject(LL);

    File.WriteAllText(DailyTex, Listi);

    editor.Text = File.ReadAllText(DailyTex);

    DisplayAlert("Save completed", "Please Try Egain", "Continue");
}

The error is:

Newtonsoft.Json.JsonSerializationException: 'Self referencing loop detected for property 'ParentView' with type 'Xamarin.Forms.Grid'. Path 'TemplatedItems[0].View.Children[0]'.'

My Xamlpage
<ListView x:Name="LL" Grid.Row="3"   ItemsSource="{Binding energy}" HeightRequest="300" >
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <ViewCell>

                                    <Grid  Padding="5" BackgroundColor="White" RowSpacing="40" >
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="50"></RowDefinition>
                                            <RowDefinition Height="50"></RowDefinition>
                                        </Grid.RowDefinitions>

                                        <Label x:Name="label" HorizontalOptions="Center" Text="{Binding EE}" FontSize="18"  TextColor="Black" Grid.Column="0" Grid.Row="0" />
                                        <Entry TextChanged="Entry_TextChanged" HorizontalOptions="Center" VerticalOptions="Center" Keyboard="Numeric" Placeholder=". . . . . . . ." Grid.Column="1" Grid.Row="0" BackgroundColor="Beige" WidthRequest="80" />
                                        <Entry TextChanged="Entry_TextChanged_1" HorizontalOptions="Center" VerticalOptions="Center" Keyboard="Numeric" Placeholder=". . . . . . . ." Grid.Column="2" Grid.Row="0" BackgroundColor="Beige" WidthRequest="80"/>
                                        <Entry TextChanged="Entry_TextChanged_2" HorizontalOptions="Center" VerticalOptions="Center" Keyboard="Numeric" Placeholder=". . . . . . . ." Grid.Column="3" Grid.Row="0" BackgroundColor="Beige" WidthRequest="80"/>
                                        <BoxView Grid.Column="0" Grid.Row="0" BackgroundColor="Black" WidthRequest="1" HorizontalOptions="EndAndExpand" VerticalOptions="FillAndExpand"/>
                                        <BoxView Grid.Column="1" Grid.Row="0" BackgroundColor="Black" WidthRequest="1" HorizontalOptions="EndAndExpand" VerticalOptions="FillAndExpand"/>
                                        <BoxView Grid.Column="2" Grid.Row="0" BackgroundColor="Black" WidthRequest="1" HorizontalOptions="EndAndExpand" VerticalOptions="FillAndExpand"/>

                                    </Grid>

                                </ViewCell>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

with a model I can now print this:

A: You can set the ItemsSource of listview as collection of objects like:
    ObservableCollection<MyText> txts = new ObservableCollection<MyText>();
    MyText txt1 = new MyText();
    MyText txt2 = new MyText();
    txt1.num = "1";
    txt2.num = "2";
    txts.Add(txt1);
    txts.Add(txt2);
   ll.ItemsSource = txts;

And when you save, you can serialize the ItemsSource like:
 private void saveload_clicked(object sender, EventArgs e)
{
    string jsontxt = JsonConvert.SerializeObject(ll.ItemsSource);
    File.WriteAllText(myfile, jsontxt);
    displaytext.Text = File.ReadAllText(myfile);
    Console.WriteLine("done");
}

Here are my xaml and running screenshot:
     <ContentPage.Content>
        <StackLayout>
            <Button Text="SaveandLoad" Clicked="saveload_clicked"/>
            <Label x:Name="displaytext"/>
       <ListView x:Name="ll" SeparatorColor="Blue" RowHeight="200">
           <ListView.ItemTemplate>
               <DataTemplate>
                   <ViewCell >
                       <StackLayout>
                       <Label Text="{Binding num}" BackgroundColor="Green" WidthRequest="20"/>
                       <Entry Text="{Binding line1}"/>
                       <Entry Text="{Binding line2}"/>
                       <Entry Text="{Binding line3}"/>
                           </StackLayout>
                       </ViewCell>
               </DataTemplate>
           </ListView.ItemTemplate>
       </ListView>
            </StackLayout>
    </ContentPage.Content>
</ContentPage>


text:
Q: What would be a nice (almost perfect) django settings and apache conf configuration? I know it is a bit a newbie question,
and that by reading a lot of docs about django and apache
I might find my perfect configuration..
But I am still a bit confused also because if you google you
find a lot about devel but little about running systems.
So I'd like to collect here a bit of additional info.
I decided that it is better to have a local server for
development then to use the:
python ./manage.py runserver

[it works fine for small projects and apps but as soon as you start
to get close to real it gets complicated]
What I know is:
 - Static files will be served by the apache.
What I guess is:
   I guess that django will address these files to the apache
   which will be "ignored"(?) by django.
   These are the settings: MEDIA_ROOT, MEDIA_URL
   I am not sure about: STATIC_ROOT, STATIC_URL
   [ok, assuming I do not mess up the url.py..]
Now the title question:
What would be a good apache (and unix permissions) configuraton?
How can I distinguish between MEDIA and STATIC?
Maybe I do miss something.
PS:
At present I have these aliases in apache:
Alias /admin-media /usr/lib/python2.7/site-packages/django/contrib/admin/media
Alias /things_media /home/udev/prj/DjangoSite/www/things_media


text:
Q: Validation rule for deletion of files or check via flow We have files with special categories, if a new file is uploaded the category is mandatory for each file.
Category A - can deleted
Category B - cant deleted
I though I can make a validation rule like "Text(category__c) == "B". But if I upload a new file with category B I get my error which I have added for the validation rule.
Second idea was to add a flow to validate the deletion, but I can't choose the file object for run the flow if record is deleted.

A: You will have to write an Apex trigger to prevent deletion of ContentDocument (file) records.  Validation rules cannot prevent record deletion, and you currently cannot use Flow on the ContentDocument object.


text:
Q: Prove that $\bigcup_{p\in P}C_p=(\bigcup_{i\in I}A_i)\times (\bigcup_{i\in I}B_i)$. Not a duplicate of
For each $(i, j) ∈ I × I$ let $C_{(i, j)} = A_i × B_j$, and let $P = I × I$ . Prove that $∪_{p∈P}C_p = (∪_{i∈I} A_i) × (∪_{i∈I} B_i)$.
This is exercise $4.1.11.b$ from the book How to Prove it by Velleman $($$2^{nd}$ edition$)$:
Suppose $\{A_i|i\in I\}$ and $\{B_i|i\in I\}$ are indexed families of sets.
$(b)$ For each $(i,j)\in I\times I$ let $C_{(i,j)}=A_i\times B_j$, and $P=I\times I$. Prove that $\bigcup_{p\in P}C_p=(\bigcup_{i\in I}A_i)\times (\bigcup_{i\in I}B_i)$.
Here is my proof:
$(\rightarrow)$ Let $(x,y)$ be an arbitrary element of $\bigcup_{p\in P}C_p$. So we can choose some $(i_0,j_0)\in P =I\times I$ such that $(x,y)\in C_p= A_{i_0}\times B_{j_0}$ and so $x\in A_{i_0}$ and $y\in B_{j_0}$. From $i_0\in I$ and $x\in A_{i_0}$, $x\in\bigcup_{i\in I}A_i$. Similarly, $y\in\bigcup_{i\in I}B_i$ and ergo $(x,y)\in(\bigcup_{i\in I}A_i)\times (\bigcup_{i\in I}B_i)$. Since $(x,y)$ is arbitrary, $\bigcup_{p\in P}C_p\subseteq(\bigcup_{i\in I}A_i)\times (\bigcup_{i\in I}B_i)$.
$(\leftarrow)$ Let $(x,y)$ be an arbitrary element of $(\bigcup_{i\in I}A_i)\times (\bigcup_{i\in I}B_i)$. So $x\in\bigcup_{i\in I}A_i$ from which we can choose some $i_0\in I$ such that $x\in A_{i_0}$ and $y\in\bigcup_{i\in I}B_i$ from which we can choose some $j_0\in I$ such that $y\in B_{j_0}$. Ergo $(i_0,j_0)\in I\times I=P$ and $(x,y)\in A_{i_0}\times B_{j_0}=C_{p=(i_0,j_0)}$ and so $(x,y)\in\bigcup_{p\in P}C_p$. Since $(x,y)$ is arbitrary, $(\bigcup_{i\in I}A_i)\times (\bigcup_{i\in I}B_i)\subseteq \bigcup_{p\in P}C_p$.
Ergo $\bigcup_{p\in P}C_p=(\bigcup_{i\in I}A_i)\times (\bigcup_{i\in I}B_i)$. $Q.E.D.$
Is my proof valid$?$
Thanks for your attention.


text:
Q: Spring/Hibernate: EntityManager multiplies instances I am trying to return a list of Hibernate entities from a list of ids. The following piece of code is responsible:
String sql = "select id from foo where some condition is met";
List<Long> ids = jdbcTemplate.queryForList(sql, Long.class); // 3 ids ..
List<FooEntity> list =  ((Session) this.entityManager.getDelegate())
        .createCriteria(FooEntity.class)
        .add(Restrictions.in("id", ids)).list(); // .. -> 60 entities

...

@Entity
public class FooEntity implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private long id;

  @OneToMany(
    targetEntity = BarEntity.class,
    cascade = { CascadeType.ALL },
    fetch = FetchType.EAGER)
  @JoinTable(
    name = "foo_bar",
    joinColumns = @JoinColumn(name = "foo_id"),
    inverseJoinColumns = @JoinColumn(name = "bar_id"))
  private List<BarEntity> bars;

  ...
}

When the code has executed I have a list of 3 ids and a list of 60 FooEntity instances!
Under normal circumstances I expect these lines of code to deliver just as many entities as ids. Any ideas what could cause this strange behaviour?
EDIT: Reacting to Thomas' comment below I found out that there are exactly 20 Bar instances for each Foo entity. And every FooEntity is also returned 20-fold.

A: AFAIK Hibernate by default doesn't remove duplicates from the result lists unless you place a distinct(foo) in the query. Thus you'll get 60 entries in the list for 3 FooEntity instances which are joined with 20 BarEntity instances each, just because the JDBC result set will have 60 rows.
So add a distinct predicate to the query (have a look here: How to get distinct results in hibernate with joins and row-based limiting (paging)?) or use new LinkedHashSet<FooEntity>( list ) if FooEntity has a meaningful implementation of equals() and hashCode() (I'd not rely on the default implementation since in some situations Hibernate might create multiple instances of the same entity, which results in a "this breaks == semantics" message).

A: I'm using
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
to remove duplicates from Result


text:
Q: Sending data to ajax posting data from the form to php using ajax.When we change the radio button data is not clearing.Please check the code.
Here is the code Please help me.
And this is my from
<form name="theform" action="" method="post" id="paymentHistory">

Type:

                    <input type="checkbox" name="Successfull" value='Successfull'>

                Successfull

                    <input type="checkbox" name="Failure" value='Failure' />

                Failure

Data Range:

                            <input type="radio" name="Today" id="Today" value='Today'>

                            Today

                            <input type="radio" name="Today" id="Lastweek" value='Lastweek'>

                            Lastweek

                            <input type="radio" name="Today" id="30days" value='30days'>

                            30days

</form>

And this is the script.

This is my php code data is not getting.Please help me.
<?php

  $select = 'SELECT *';
  $from = ' FROM payment_details';
  $where = ' WHERE TRUE';
  $nickname = $_SESSION['username'];

  $opts = $_POST['filterOpts'];
  $options = explode("&",$opts);

$Today = "";
$Lastweek = "";
$days = "";
$Successfull = "";
$Failure = "";

foreach($options as $key)
{
   $key = explode("=",$key);
   $type = $key[2];

   if ("Today" == $type)
   {
       $Today= "Today";
   }

   if ("Lastweek" == $type)
   {
      $Lastweek = "Lastweek";
   }

   if ("30days" == $type)
   {
      $days = "30days";
   }

   if ("Successfull" == $type)
   {
      $Successfull = "Successfull";
   }

   if ("Failure" == $type)
   {
     $Failure = "Failure";
   }
}

    if( $Today == "Today" )
    {
       date_default_timezone_set('Asia/Kolkata');
    $d = date('Y-m-d 00:00:00');
        $where .= " AND tran_ini_date >= '$d' ";
    }

    if('Lastweek' == $Lastweek)
    {
       $d =  date('Y-m-d 00:00:00', strtotime("-7 days") );
       $where .= " AND tran_ini_date >= '$d' ";
    }

   if('30days' == $days)
   {
     $d =  date('Y-m-d 00:00:00', strtotime("-30 days") );
     $where .= " AND tran_ini_date >= '$d' ";
   }
   if("30days" == $days)
   {
     $d =  date('Y-m-d 00:00:00', strtotime("30 days") );
     $where .= " AND tran_ini_date <= '$d' ";
   }

    $check = 0;
    if('Successfull' == $Successfull)
    {
         $check = 1;
         $where .= " AND (status='success' ";
    }

    if('Failure' == $Failure)
      {
         if($check == 0)
          $where .= " AND (status='pending') ";
         else
          $where .= " OR status='pending') ";
     }

$sql = $select . $from . $where . " and nickname="."'".$nickname."'";

$conn = mysql_connect("localhost","root","********");
if (!$conn)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("**********",$conn);
$result = mysql_query($sql,$conn);
$data   = array();
while ($row = mysql_fetch_assoc($result))
{
$data[] = $row;
}
$json = json_encode($data);
echo($json);

echo $sql;

?>

A: You have had errors in your code, and the approach to use :checkbox click inside of :radio click event is not proper way. See modified code which should work for you:
$(document).ready(function ()
{
    makeTable = function(data)
    {
        var tbl_body = "";
        $.each(data, function() {
            var tbl_row = "";
            $.each(this, function(k , v) {
                tbl_row += ""+v+"	";
            })
            tbl_body += "
"+tbl_row+"
";
        })

        return tbl_body;
    };

    var pushToServer = function(opts){
        alert(opts);
           $.ajax({
           type: "POST",
           url: "tabletest/submit.php",
           dataType : 'json',
           cache: false,
           data: {filterOpts: opts},
           success: function(records){
               $('#phones tbody').html(makeTable(records));
           }
       });
    };

    $('#paymentHistory input:radio, #paymentHistory input:checkbox').click(function() {
        pushToServer($('#paymentHistory').serialize());
    });
});

DEMO


text:
Q: Prove that an autonomous ODE f(x)=x' has no nonconstant periodic solutions Prove that an autonomous ODE $f(x)=x'$ has no nonconstant periodic solutions.
I guess I could prove it by contradiction by saying $x(t+T) = x(t)$ implies $x(t) =$ constant.

A: I think you are trying to prove that a first-order autonomous ODE $dx/dt = f(x)$ cannot have a periodic solution.  Of course it's pretty easy to think of a second-order autonomous ODE  that does have a periodic solution, so first-order autonomous systems of differential equations can likewise have periodic solutions.
For the single equation case, think about a periodic function (other than the trivial case of a constant function).  If the function is to be differentiable, it must be continuous.
Find two points on a continuous nonconstant periodic function where the function value is the same, but the function is decreasing at one argument and increasing at the other.
This would contradict the autonomous differential equation, right?
Once more, with rigor:
We show that if $x(t)$ is a real periodic solution of the autonomous first-order
differential equation:
$$x' = f(x)$$
then $x(t)$ is a constant function.
Suppose not for the sake of contradiction: $x$ has an interval of periodicity
$[0,T]$ and attains a bounded range $[X_{min},X_{max}]$.  WLOG we assume, by
translation in t if necessary, that $x(0) = X_{min} = x(T)$, and for the
sake of specificity that $x(t_*) = X_{max}$ for some $t_* \in (0,T)$.  Of course those
extremal values might also be attained elsewhere in $[0,T]$.
Since $X_{min}, X_{max}$ are extrema of $x(t)$, function $f$ must vanish there:
$$f(X_{min}) = 0 = f(X_{max})$$
Unless $f$ takes a nonzero value somewhere on $[X_{min},X_{max}]$, all solutions
$x(t)$ of the differential equation in this range would be constant.  So choose
$x_* \in (X_{min},X_{max})$ such that $f(x_*)$ is nonzero.
By the Intermediate Value Thm. continuity of $x$ implies $x(t) = x_*$ for some
points in $(0,t_*)$ and $(t_*,T)$.  In fact there is an open interval around
$t_*$ where $x(t) \gt x_*$, so we can pick a greatest $t_{left} \in (0,t_*)$
and a least $t_{right} \in (t_*,T)$ where $x$ takes the value $x_*$.
It follows that $x$ is increasing on the right side of $t_{left}$ and decreasing
on the left side of $t_{right}$.  But this forces the derivative $x'$ at both
points to be zero, contradicting our choice of $x_*$ s.t. $f(x_*)$ is nonzero.
QED
In a sense this is interesting because it assumes nothing about regularity of
$f$.  Under standard assumptions
solutions to initial value problems for the DE are (locally) unique.  But as
$x(t) = X_{min}$ would be a constant solution of the IVP for $x(0) = X_{min}$,
such uniqueness precludes nonconstant solutions.

A: I will give a slightly less rigorous, but perhaps more intuitively satisfying proof.
We have the differential equation $\frac{dx}{dt} = f(x)$. We want to find a periodic solution such that $f(x_t) = f(x_{t+T})$ for some $T>0$.
Since $f(x_t)$ is autonomous, $f$ does not explicitly depend on $t$.  Therefore, by chain rule, $\frac{df(x)}{dt} = 0\cdot \frac{dx}{dt} = 0$.
And since $f(x_t) = \frac{dx}{dt}$, we have $\frac{df(x_t)}{dt} = \frac{d^2x}{dt^2} = 0$.
Then, $x(t)$ is a linear function.  Now, the only linear function for which there exists a non-zero $T$ such that $x(t) = x(t+T)$ is a constant linear function.  Then, $x(t)$ must be a constant function, and we are done.


text:
Q: Modify just one file in library In node js, we import require('library') to use external library. let's say there's a external-file.js inside 'library' that we want to customise for our project. What is the technique that can be use?
In Java, this can be done irreverently through just copying the external file and make sure it adhere to same package path. How can this be done in node.js ?

A: Ideally if this external library is getting pulled from npm or github, you should create a fork, use that in your project's package.json and modify the file in your own fork. Then when you commit the changes to the file, it'll go into your own version of the third party library. (And if the change is good enough you can even ask the author to incorporate it in their code and get credit for contributing to open source :D)
Additional benefit of doing it like this is that you won't have to commit the dependencies in along with your source code.


text:
Q: JDBC Autocommit to false in application level When most of the best programming approaches recommend to set the JDBC auto commit to false, what is the rational behind JDBC API design that set the default value to true?

A: What is the rational behind JDBC API design that set the default value to true?
You will take transactions under your control by setting connection.setAutoCommit(false) only when you are dealing multiple INSERT/UPDATE sql queries (handling through JDBC) within/across database tables as an atomic operation, which is only needed for a medium/complex sized applications.
Now, if all transactions have to be handled explicitly (i.e., as you suggested if connection.setAutoCommit(false) is by default), then the developers should be very careful even for single INSERT/UPDATE sql query  (handling through JDBC) by ensuring that the commit() and rollback() have been handled properly, otherwise the connection will be hanging and it is quite hard to debug.

If auto-commit mode has been disabled, the method commit must be
  called explicitly in order to commit changes; otherwise, database
  changes will not be saved.

You can look here
Following your approach i.e., calling commit explicitly for each and every transaction is unnecessary and if we ignore do it even once, it will do more harm than good.

A: Similar to why we use logging frameworks instead of System.out.println.
The simplest setup is for the simplest cases.  Autocommitting is right for trivial usages and applications.  Simple cases don't need well defined transaction boundaries, so in the interest of Keeping It Simple, autocommit defaults to true.
Wikipedia has a pretty good article on DB transactions, worth a read: https://en.wikipedia.org/wiki/Database_transaction


text:
Q: Set 30px gutter with 4 Bootstrap-3 Cols @270 I've spent considerable time researching and trying various methods to achieve the desired outcome. The most helpful post Bootstrap - columns with spacing got me almost all the way there.
Given this 4-col comp at 1170px wide , with each of the four columns set to 270px wide with a 30px gutter, I can't seem to arrange Bootstrap 3 to force the 30px wide gutters so that the left and right outer columns left-align and right-align respectively, with equal gutters between them.
Here's what I ended up with:
CODE BLOCK

CSS
.services-outer {}
.services-wrap.row {
    margin: 0;
}
.services-wrap.container {
    padding:0;
}
.services-wrap .col-md-3 {
    padding:0;
}

Question: given that (4 x 270) + (3 x 30) = 1170, why doesn't Bootstrap equally space the columns and, how do I do so without impacting the responsive when it collapses?
BOOTPLY Thanks @T30!

A: The simplest way I can think to do this is pad each column by 15px and extend the row out like so:

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css');
 .service-row {
  margin: 0 -30px;
}
.service {
  padding: 0 15px;
}
.img-responsive {
  width: 100%;
  height: auto;
}


text:
Q: youtube inbox problem I'm trying to programmatically (using gdata api) retrieve incoming messages from youtube account.
My request:
NSURL *url = [NSURL URLWithString:@"http://gdata.youtube.com/feeds/api/users/my_nick/inbox"];

NSMutableURLRequest *inboxRequest = [NSMutableURLRequest requestWithURL:url];

NSString *authStr = [NSString stringWithFormat:@"GoogleLogin auth=%@", authMarker];

[inboxRequest setValue:authStr forHTTPHeaderField:@"Authorization"];
[inboxRequest addValue:@"Content-Type" forHTTPHeaderField:@"application/x-www-form-urlencoded"];
[inboxRequest setHTTPMethod:@"GET"];

NSHTTPURLResponse *response = NULL;

NSData *responseData = [NSURLConnection sendSynchronousRequest:inboxRequest returningResponse:&response error:nil];

NSString *responseDataString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];

NSLog(@"\n%@\n", responseDataString);
NSLog(@"\n%@\n", [inboxRequest ]);

return feed without entries... (although I can see incoming messages on the site)
here response from nslog:
<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'><id>http://gdata.youtube.com/feeds/api/users/thisistestnick/inbox</id><updated>2011-06-16T14:45:00.475Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#videoMessage'/><title type='text'>Inbox of thisistestnick</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='alternate' type='text/html' href='http://www.youtube.com/my_messages?folder=inbox&filter=videos'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/users/thisistestnick/inbox'/><link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/users/thisistestnick/inbox/batch'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/users/thisistestnick/inbox?start-index=1&max-results=25'/><author><name>thisistestnick</name><uri>http://gdata.youtube.com/feeds/api/users/thisistestnick</uri></author><generator version='2.0' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>0</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage></feed>
what is wrong? pls help.

A: Why cant you use,  gdata-objectivec lib api's rather doing your own parsing ? I havent tried retrieving 'inbox' but was fairly successful in getting the info i want. Advantages of using it are:
a) You get the info in native formats (Strings and Dictionaries), lib does the job of parsing feeds for you.
b) mainly, there wont be any parsing/api understanding errors (which i suppose is the reason for your problem).


text:
Q: How to call a method from another class ? Method has to modify the Image View(Variable) android I have a class in which i have defined XML file by set Content View(R.layout.A) and defined it components i.e. images imp = (Image view)find View by id(...) now I want to modify this image on click of button it should call the method from another class ...
my problem is about Image View variable I don't know how to deal with this variable (int,float,char are easy for me)  I have referred this links Error when call method from another class in android and Android Call an method from another class
 please help me in this matter.....
Thanks in advance....


text:
Q: Any better solution to ListenKey anywhere inside the frame? I've a frame with a text field, a table and two buttons!

I would like to add a KeyListener to listen when a modifier key is pressed and released, in order to change the text of the Ok button and let user select different methods. The listener should work regardless which component is in focus.
For example:

*

*No modifiers: "Ok" - Do Something;

*Shift key pressed: "Ok and close" - Do Something and close the frame;

*Alt key pressed... etc

Right now I've found this solution, but it seems a bit cluncky and not elegant at all.
public class MyFrame extends JFrame {
private boolean shiftPressed;
private MyDispatcher keyDispatcher;

public MyFrame () {
    super();
    initGUI();

    shiftPressed = false;

    KeyboardFocusManager currentManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    keyDispatcher = new MyDispatcher();
    currentManager.addKeyEventDispatcher(keyDispatcher);

    //...remain of code

}

@Override
public void dispose() {
    // I remove the dispatcher when the frame is closed;
    KeyboardFocusManager currentManager = KeyboardFocusManager
            .getCurrentKeyboardFocusManager();
    currentManager.removeKeyEventDispatcher(keyDispatcher);
    super.dispose();
}

private class MyDispatcher implements KeyEventDispatcher {
    @Override
    public boolean dispatchKeyEvent(KeyEvent e) {
        if (e.getModifiers() == KeyEvent.SHIFT_MASK) {
            if (e.getID() == KeyEvent.KEY_PRESSED) {
                System.out.println("Shift Pressed");
                shiftPressed = true;
                btnOk.setText("Ok and Close");
            }
        } else if (e.getID() == KeyEvent.KEY_RELEASED) {
            if(!e.isShiftDown() && shiftPressed) {
                System.out.println("Shift Released");
                btnOk.setText("Ok");
            }
        }
        return false;
    }
}

}
Any suggestion on how to improve the code?

A:
I would like to add a KeyListener to listen when a modifier key is pressed and released, in order to change the text of the Ok button and
  let user select different methods. The listener should work regardless
  which component is in focus.

IMHO using Key bindings is a more flexible and reliable approach that brings with these benefits:

*

*Separates the action itself from the key strokes.

*There are different conditions to trigger those actions: WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT

*We can take advantage of those conditions to attach different actions to different components relying a precedence-based policy (see the example presented here).

Having said that, we can create KeyStrokes using appropriate masks like follows:
KeyStroke shiftKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT, KeyEvent.SHIFT_DOWN_MASK);

And we can even specify that the key stroke will be triggered on a key release event:
KeyStroke shiftReleasedKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT, 0, true);

Note: 0 means no modifiers and true is a flag indicating the key stroke represents a key release event. See the API for more details.
Now, what I'd do is create a wrapper JPanel that contains all my components and attach actions using WHEN_IN_FOCUSED_WINDOW condition:
JPanel wrapperPanel = new JPanel();
...
InputMap wrapperPanelInputMap = wrapperPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
wrapperPanelInputMap.put(shiftKeyStroke, "pressedAction");
wrapperPanelInputMap.put(shiftReleasedKeyStroke, "releasedAction");
...
wrapperPanel.getActionMap().put("pressedAction", pressedAction);
wrapperPanel.getActionMap().put("releasedAction", releasedAction);

Where both pressedAction and releasedAction are different Actions that can do whatever you want (i.e.: change button's text).
The only minor disadvantage is the LOC needed to set key bindings. However you can avoid boilerplate code by creating a reusable panel that can accept Actions for the different modifiers (SHIFT, ALT, CTRL, etc.) and set key bindings internally in that class.

A: Your approach is ok but it uses a global focus manager. It's a little bit dangerous and can provoke some errors when you for example forget to dispose your frame. Much better is to add your listener to all focusable components in the frame.
private static void addToAll(Component aStart, KeyListener aListener) {
    if (aStart.isFocusable()) {
        aStart.addKeyListener(aListener);
    }
    if (aStart instanceof Container) {
        Container container = (Container) aStart;
        for (Component comp : container.getComponents()) {
            addToAll(comp, aListener);
        }
    }
}

To use it:
public MyFrame () {
    super();
    initGUI();

    shiftPressed = false;
    keyDispatcher = new MyDispatcher();
    addToAll(this.getContentPane(), keyDispatcher);
    //...remain of code

}

Disadvantage of this approach: when you modify your GUI dynamically (add/remove components after your GUI is created and listener is added to all components) you need to remove the listener from all components and add it again.


text:
Q: How to write and read from different lines in a text file? I have a very simple 'login' program that I've almost got finished. I'm trying to get my make_acc() function to write the username on line 1 and the password on line 2, as well as make my login() function read those separate lines per what needs to be checked. I'm pretty sure the answer has to do with marking the readline command for which line needs to be read, but I'm not sure how to implement it in my code properly. Here's the code.
# This function has the user input a username for their account
def make_acc():
    username = input('Make a username:')
    file = open('acc_data.txt','w')
    file.write(username)
    file.close()
    #password = input('Make a password:')
    #file = open('acc_data.txt','w')
    #file.write(password)

# This function has the user login to a preexisting account
def login():
    input_user = input('Enter your username:')
    file = open('acc_data.txt','r')
    username = file.readline()
    if input_user == username:
        print('You are now logged in')
    else:
        print('That user does not exist')
        login()

# This variable will be defined as a yes or no depending on whether or not the use has an account
acc_bool = input('Do you already have an account?:')

# This if statement runs the login() function if the user answered yes to the previous input
if acc_bool == 'yes':
    login()
# This elif statement runs the make_acc() function if the user answered no to the previous input
elif acc_bool == 'no':
    make_acc()
    login()

A: This should do it:
def make_acc():
    username = input('Make a username:')
    password = input('Make a password:')
    with open('acc_data.txt','a') as file:
        file.write(username+'\n')
        file.write(password)

def login():
    input_user = input('Enter your username:')
    with open('acc_data.txt','r') as file:
        if input_user in [u for i,u in enumerate(file.readlines()) if not u%2]:
            print('You are now logged in')
        else:
            print('That user does not exist')
            login()

Instead of having the usernames and passwords all in 2 lines, you can use indexes to determine whether a line is a username or password: even indexes are for usernames, and odd ones are for passwords.

UPDATE:
This part: [u for i,u in enumerate(file.readlines()) if not u%2] lists all the strings in file.readlines() (a list of all the lines in f.read()) if the index of the string, i, doesn't leave a remainder when divided by 2.
You see, enumerate() will basically let us iterate through an array and let use easily access the index of the current iteration.

A: First, uncomment the part of make_acc that asks for a password and add a file.close().
Then, notice that when you've run the program and inputted the two pieces of information, only one is left in the file, this is because, when calling open(), you use the
w mode, which truncates the file before allowing you to write. The consequence of this is that when you open the file again a couple of lines later, all information previously stored is lost. The solution is to use mode r+ or a or just not close the file until the end of the function, thereby avoiding having to reopening it when writing the password.
Next, when reading from the file, you can use file.readline() just as you already are doing. Choosing what line to read happens by default, because every call to readline advances what line is being read. This means that the second time you call it since you opened the file, the second line will be read.


text:
Q: asp.net mvc some models were added during the migration So I created several models in the project that I'm working on. But several models were not included on the migration class. So those models were not added to the database after running the Update-Database on the Package Manager Console. It is the initial migration/fresh database so I do not know where the conflict is.
I do not know where the error is or why it did not include all the models?
Kindly help me. Thank you!


text:
Q: Determining if a directory already exists using SVN ANT I'm looking to create a directory using SVN ANT, but only so if the directory does not already exist (using the mkdir nested task with SVN ANT appears to fail if you specify a directory that already exists).
Is there a isExists flag or something of that ilk that I can use here?  Or something else I can use to detect existing directories on an SVN repository before I continue with creating my directories via an ANT script?
Any thoughts on this would be much appreciated.
Cheers,
Stuart

A: You want to use the svnExists condition. This allows you to do something like (Using ant-contrib)
<if>
    <not><svnExists target="..."/></not>
    <then>
        <svn>
            <mkdir url="..." message="Creating a directory" />
        </svn>
    </then>
</if>

Note: all the intermediate directories must already exist when using mkdir.

A: The available task enables you to set a property dependent on the existence of a file or directory
<available property="desired-dir-exists" file="src/desired_dir"/>

<target name="mkdir" unless="desired-dir-exists">
    <svn>
        <mkdir path="src/desired_dir"/>
    </svn>
</target>

A: Two options:

*

*You can set the failonerror attribute to false. This way if the directory exists, an error message will be printed but the build will not be aborted.
<svn failonerror="false">
    <mkdir path="..." message="..."/>
</svn>

*If you want to avoid the error message you will probably need to do something more elaborate, such as performing a checkout / update first, then examine your working copy to see if the directory you want to create already exists.


text:
Q: SSAS - data in three places? New to DW concepts and SSAS.  I'm reading alot that normalized relational dbs are optimal for OLTP due to a typical workload of many one-transaction batches.  And denormalization is generally better for DW/BI applications because the nature of queries used for reporting are more batch-based...  there were other reasons that I don't recall right now.
It sounds like the advice says to create a denormalized model and populate it from the base relationship model and then build your cubes off the denormalized model.  Assuming you're using MOLAP storage type, your cube will store and incrementally update your data in a multidimensional model that it builds behind the scenes.
So now we have essentially the same data stored three times!
Am I reading that right?  Why do we even need that intermediate denormalized table? It can't be to optimize report queries because those are being run against the multidimensional SSAS data store.   Why not just build your cubes against a dsv whose definition is basically a view of the relational db?

A: The multidimensional model needs the relational model to be available in star schemas (that is what you call "denormalized model") for loading the data. And in many cases, there is some processing like combining data from different sources, keeping the data for reporting longer than it is needed in the OLTP world, keeping historical views like old regional or department structures available for analyzing which are not necessary and hence overwritten in the OLTP world. Hence, this intermediate step makes sense in many cases. You might also want to have clear cut of times, i. e. always report data for complete days (or, in some cases, months), and not have some data for the last day available and some not, which makes comparison of numbers for a day easier than comparing e. g. the sales of today containing only the data up to 10 o'clock with the sales of the whole day yesterday.
In some simple cases, the intermediate relational data structure need not be available physically. A few days ago I prepared a prototype cube where the star schema was just a set of views on the source data. In this case, of course, the data was only physically available in the original source form and in the cube. The structure of the source data did not make the views that inefficient, and thus data loading to the cube was fast enough for the prototype.


text:
Q: nextLink1.replace("""), Making " act differently nextLink1.replace(""",()), so basically I want to replace " with a blank. Any help would be greatly appreciated.
Thanks

A: You need to escape the " sign. Like this:
nextLink1.replace("\"","");

A: The compiler will recognize the first two quote marks, but the third one will produce a syntax error.
Using an escape sequence will place a double quote as such:
nextLink1.replace("\"","");

You can find more escape sequences here http://docs.oracle.com/javase/tutorial/java/data/characters.html

A: " is Java's metacharacter used to start or end Strings literals. If you want to use it inside String literal you need to escape it first with \ like \" (which is another Java's metacharacter used for example to create new lines mark "\n").
Also blank String is not () but "". So try this way
nextLink1.replace("\"","");

BTW Strings are immutable which means this method will not affect original String, but create new one with replaced character. If you want nextLink1 to contain String with replaced characters you will need to use
nextLink1 = nextLink1.replace("\"","");


text:
Q: linux shell script: how can I create a service that will run in background? I have a simple question, i searched and I couldn't find a solution.
I have a simple shell script that run a small php code every 2 seconds, I wrote it and save as a file:
$ cat every-2-seconds.sh
#!/bin/bash
while true
do
php /home/account/domains/domain.co.il/public_html/my-php-script.php
 sleep 2
done

Now, i need that this script will always run on background, but I also need that it will run on startup, Just like a service, it should always run in background, and I never want to start it manually (of course, if something happen and it will stop, i should be able to start it manually)
I heard about nohup, but its not a service right? and I can start it on startup.. :(
Can you help me on this??

A: You can make your script run with this line of code (assuming you are in the directory with your script)
nohup every-2-seconds.sh &

The & will run this as a background task and nohup will keep the process running even after you've disconnected from your session.
To handle starting it on reboot you need to add this command to your crontab
crontab -e
@reboot /path/to/every-2-seconds.sh > /dev/null

In the crontab you need to specify the full path. You can change /dev/null to the file you want output to go to (assuming you want the output)


text:
Q: paging of gridview i have a  gridview where i have allowed paging.
but when i click second page the gridview disappears
here is the c# code :
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        OdbcDataAdapter adpState = new OdbcDataAdapter("SELECT CALL_NO,TDATE,
        ID_NO,NAME,CONTACT,DEPARTMENT,ISSUE,STATUS FROM TBL_ITHELPDESK
        WHERE (STATUS IS NULL OR STATUS <> 'CLOSED') AND  TDATE= TO_DATE('" +
          txtDate.Text.ToString().Trim() + "','MM-DD-YYYY')", con1);
        DataSet ds = new DataSet();
        adpState.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }

can anyone help to find where i'm going wrong

A: You have to check multiple things.

*

*Check the query with the one that is working, Is it Same?

*Check the con1 variable is defined outside of any other method.

Define con1 in a class not in a method, something like that
 odbcConnection con = new odbcConnection(ConectionString);


text:
Q: Completeness of automorphism groups of free metabelian groups I am not very familiar with free metabelian groups, so I apologise in advance if this is trivial.
A group $G$ is said to be complete if every automorphism of $G$ is inner. In this case, $\operatorname{Aut}(G) \cong G$ (for centreless groups, this is an equivalent property to being complete). The following classes of groups are known to have complete automorphism groups: f.g. non-abelian free groups [1], f.g. free nilpotent groups of rank $\neq 1,3$ and class $2$ [2], f.g. non-abelian free solvable groups [3].
Hence we have e.g. $\operatorname{Aut}(\operatorname{Aut}(F_2)) \cong \operatorname{Aut}(F_2)$, where $F_2$ is the free group of rank $2$.
Is it known whether every f.g. non-abelian free metabelian group has complete automorphism group?
Note that Bachmuth [4] showed that the automorphism group of a free metabelian group of rank $>2$ is not metabelian (or solvable), and seemed to indicate that the structure for rank $2$ is somewhat tractable. I am curious if anything further has been shown later.
${}$
References
[1] Dyer, Joan L.; Formanek, Edward, Complete automorphism groups, Bull. Am. Math. Soc. 81, 435-437 (1975). ZBL0304.20030.
[2] Dyer, Joan L.; Formanek, Edward, Automorphism sequences of free nilpotent groups of class two, Math. Proc. Camb. Philos. Soc. 79, 271-279 (1976). ZBL0324.20043.
[3] Dyer, Joan L.; Formanek, Edward, Characteristic subgroups and complete automorphism groups, Am. J. Math. 99, 713-753 (1977). ZBL0367.20041.
[4] Bachmuth, S., Automorphisms of free metabelian groups, Trans. Am. Math. Soc. 118, 93-104 (1965). ZBL0131.02101.


text:
Q: jQuery: Is there a way to animate a div's width without any text movement? I'm using jQuery to shrink a div's width, like this:
$('div#foo').animate({width: 0},someSpeed);

While it's shrinking, the text reflows to fit the ever-thinner div. I don't want this to happen - I want the text to stay as it is, just disappearing from view as the width decreases, as happens if you do $('div#foo').slideUp().
Is there a CSS trick or some other way to make this work?

A: Live demo: http://jsfiddle.net/AvYyT/1/
The trick is to use an inner container and set its with to the width of the outer container.

A: One option is to use white-space: nowrap; on the div. The only problem there is that you will have to manually add line breaks if you have a long body of text.

A: You can use jQuery to set the width of the content to the with of the div, add overflow:hidden to the div and only then reduce the width.
Something like (untested, could have typos, but you get the idea...):
var el = $('div#foo');
el.children().each(function() {
  $(this).width(el.width());
});
el.css('overflow', 'hidden').animate({width: 0}, someSpeed);

But it depends on the contents of the div, this would not work if there are images inside it.

A: In your div CSS, use: overflow-x: hidden; overflow-y: hidden;

A: try giving it vertical-align:top


text:
Q: Assigning multiple keys to JSON I am retrieving data from a SQL server database that I would like to send to a web-service.  The server is expecting the JSON in a certain format as specified below.   My output now doesn't appear how I would like it to and cannot be consumed by the server.  How do I add the keys as specified below?  I am using Python 2.6.7.
   {
    "MetaData": {},
    "SRData": {
        "AddressVerified": "Y",
        "SRNumber": "1-16774241",
        "SRType": "Electronic Waste"
    }
}

Code:
    import pyodbc
    import json
    import collections
    import requests

        connstr = 'DRIVER={SQL Server};SERVER=url;DATABASE=ServiceRequest; UID=SA;PWD=pwd'
        conn = pyodbc.connect(connstr)
        cursor = conn.cursor()

        cursor.execute("""
                    SELECT SRNUMBER, FirstName, LastName, ParentNumber
         FROM MYLA311 """)

        rows = cursor.fetchall()

 metadata =  '{ "MetaData": {},"SRData":'

    objects_list = []
    for row in rows:
         d = collections.OrderedDict()
         d['SRNUMBER']= row.SRNUMBER
         d['FirstName']= row.FirstName
         d['LastName']= row.LastName
         d['ParentNumber']= row.ParentNumber

    objects_list.append(d)

    output = {
    metadata:  objects_list

        j = json.dumps(output)
        objects_file = 'C:\Users\Administrator\Desktop\JSONOutput.txt'
        f = open(objects_file,'w')

        url = "https://posttestserver.com/post.php"
        data = j
        headers = {'Content-type': 'text/plain', 'Accept': '/'}
        r = requests.post(url, data= json.dumps(output), headers=headers,  verify=False)
        conn.close()

Current Output:
{
    "{ \"MetaData\": {},\"SRData\":": [
        {
            "FirstName": "MyLAG",
            "LastName": "ThreeEleven",
            "ParentNumber": "021720151654176723",
            "SRNUMBER": "1-3580171"
        }
    ]
}

A: You're approaching the problem the wrong way. What you think you need to do is inject JSON syntax in between to get your end result, but what in stead you need to do is get the object you're serializing (formatting as JSON) to reflect the JSON structure you want to output.
In other words, if you have dict that has the exact same structure as your JSON, you're set:
import json
json.dumps(
   {"MetaData": {},
    "SRData": {"AddressVerified": "Y",
           "SRNumber": "1-16774241",
           "SRType": "Electronic Waste"}})

I'll leave making this dynamic to you :)

A: first you are passing text in this line:
metadata =  '{ "MetaData": {},"SRData":'

remember that json.dumps makes a python dictionary to json so forget about the single quotes
metadata =  { "MetaData": {},"SRData":

then objects_list is an array, so it will put the brackets[], if you need to get many rows, then its ok, but in your first JSON layout there are no arrays, just put the d = collections.OrderedDict() after the SRDATA: