Q: How to make UITextView detect links for website, mail and phone number I have a UITextView object. The text in UIView has a phone number, mail link, a website link. I want to show them as links with following functionality.
When someone taps on URL - Safari should open the the website.
When someone taps on email link - Mail should open up with my address in to field
When someone taps on phone number - Phone application should call the number
Has anyone done this before or knows how to handle it?
Thanks,
AJ

A: Though the Question is super Old.
Still if anyone faces the same issue,
Also it can be used as a UILabel. Though
Below solution will do the job  : [There isn't a need for any library..]
So I've used MFMailcomposer() and UITexView [ Code is in Swift 3.0 - Xcode 8.3.2 ]
A 100% Crash Proof and Working Code Handles all the corner cases. =D
Step 1.
import MessageUI

Step 2. Add the delegate
class ViewController: UITextViewDelegate, MFMailComposeViewControllerDelegate{
Step 3. Add the textView IBOutlet From StoryBoard
@IBOutlet weak var infoTextView: UITextView!

Step 4. Call the below method in your viewDidload()
func addInfoToTextView()  {
    let attributedString = NSMutableAttributedString(string: "For further info call us on : \(phoneNumber)\nor mail us at : \(email)")
    attributedString.addAttribute(NSLinkAttributeName, value: "tel://", range: NSRange(location: 30, length: 10))
    attributedString.addAttribute(NSLinkAttributeName, value: "mailto:", range: NSRange(location: 57, length: 18))
    self.infoTextView.attributedText = attributedString
    self.infoTextView.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.blue, NSUnderlineStyleAttributeName:NSNumber(value: 0)]
    self.infoTextView.textColor = .white
    self.infoTextView.textAlignment = .center
    self.infoTextView.isEditable = false
    self.infoTextView.dataDetectorTypes = UIDataDetectorTypes.all
    self.infoTextView.delegate = self
}

Step 5. Implement delegate methods for TextView
@available(iOS, deprecated: 10.0)
func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange) -> Bool {
    if (url.scheme?.contains("mailto"))! && characterRange.location > 55{
        openMFMail()
    }
    if (url.scheme?.contains("tel"))! && (characterRange.location > 29 && characterRange.location < 39){
        callNumber()
    }
    return false
}

//For iOS 10
@available(iOS 10.0, *)
func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    if (url.scheme?.contains("mailto"))! && characterRange.location > 55{
        openMFMail()
    }
    if (url.scheme?.contains("tel"))! && (characterRange.location > 29 && characterRange.location < 39){
        callNumber()
    }
    return false
}

Step 6. Write the helper Methods to open MailComposer and Call App
func callNumber() {
    if let phoneCallURL = URL(string: "tel://\(phoneNumber)")
    {
        let application:UIApplication = UIApplication.shared
        if (application.canOpenURL(phoneCallURL))
        {
            let alert = UIAlertController(title: "Call", message: "\(phoneNumber)", preferredStyle: UIAlertControllerStyle.alert)
            if #available(iOS 10.0, *)
            {
                alert.addAction(UIAlertAction(title: "Call", style: .cancel, handler: { (UIAlertAction) in
                    application.open(phoneCallURL, options: [:], completionHandler: nil)
                }))
            }
            else
            {
                alert.addAction(UIAlertAction(title: "Call", style: .cancel, handler: { (UIAlertAction) in
                    application.openURL(phoneCallURL)
                }))
            }

            alert.addAction(UIAlertAction(title: "cancel", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
    else
    {
        self.showAlert("Couldn't", message: "Call, cannot open Phone Screen")
    }
}
func openMFMail(){
    let mailComposer = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self
    mailComposer.setToRecipients(["\(email)"])
    mailComposer.setSubject("Subject..")
    mailComposer.setMessageBody("Please share your problem.", isHTML: false)
    present(mailComposer, animated: true, completion: nil)

}

Step 7. Write MFMailComposer's Delegate Method
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    switch result {
    case .cancelled:
        print("Mail cancelled")
    case .saved:
        print("Mail saved")
    case .sent:
        print("Mail sent")
    case .failed:
        print("Mail sent failure: \(String(describing: error?.localizedDescription))")
    default:
        break
    }
    controller.dismiss(animated: true, completion: nil)
}

That's it you're Done... =D

Here is the swift file for the above code :
textViewWithEmailAndPhone.swift

Set the below properties to Use it as a UILabel

A: A note on detecting email addresses: The Mail app must be installed (it's not on the iOS Simulator) for email links to open a message compose screen.

A: Swift 3.0 +
As of swift 3.0, use the following code if you want to do it programmatically.
textview.isEditable = false
textview.dataDetectorTypes = .all

Or if you have a storyboard

A: If you are using OS3.0
you can do it like the following
textview.editable = NO;
textview.dataDetectorTypes = UIDataDetectorTypeAll;

A: Step 1. Create a subclass of UITextview and override the canBecomeFirstResponder function
KDTextView.h Code:
@interface KDTextView : UITextView

@end

KDTextView.m Code:
#import "KDTextView.h"

// Textview to disable the selection options

@implementation KDTextView

- (BOOL)canBecomeFirstResponder {
    return NO;
}

@end

Step 2. Create the Textview using subclass KDTextView
KDTextView*_textView = [[KDTextView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [_textView setScrollEnabled:false];
    [_textView setEditable:false];
    _textView.delegate = self;
    [_textView setDataDetectorTypes:UIDataDetectorTypeAll];
    _textView.selectable = YES;
    _textView.delaysContentTouches = NO;
    _textView.userInteractionEnabled = YES;
    [self.view addSubview:_textView];

Step 3: Implement the delegate method
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    return true;
}

A: I'm curious, do you have control over the text shown?  If so, you should probably just stick it in a UIWebView and throw some links in there to do it "the right way".

A: Swift 4.2 Xcode 10.1
func setupContactUsTextView() {
        let text = NSMutableAttributedString(string: "Love your App, but need more help? Text, Call (123) 456-1234 or email ")
        if let font = UIFont(name: "Calibri", size: 17) {
            text.addAttribute(NSAttributedStringKey.font,
                              value: font,
                              range: NSRange(location: 0, length: text.length))
        } else {
            text.addAttribute(NSAttributedStringKey.font,
                              value: UIFont.systemFont(ofSize: 17),
                              range: NSRange(location: 0, length: text.length))
        }
        text.addAttribute(NSAttributedStringKey.foregroundColor,
                          value: UIColor.init(red: 112/255, green: 112/255, blue: 112/255, alpha: 1.0),
                          range: NSRange(location: 0, length: text.length))
        text.addAttribute(NSAttributedStringKey.link, value: "tel://", range: NSRange(location: 49, length: 15))
        let interactableText = NSMutableAttributedString(string: "contact@abc.com")
        if let font = UIFont(name: "Calibri", size: 17) {
            interactableText.addAttribute(NSAttributedStringKey.font,
                                          value: font,
                                          range: NSRange(location: 0, length: interactableText.length))
        } else {
            interactableText.addAttribute(NSAttributedStringKey.font,
                                          value: UIFont.systemFont(ofSize: 17),
                                          range: NSRange(location: 0, length: interactableText.length))
        }
        interactableText.addAttribute(NSAttributedStringKey.link,
                                      value: "contact@abc.com",
                                      range: NSRange(location: 0, length: interactableText.length))
        interactableText.addAttribute(NSAttributedStringKey.underlineStyle,
                                      value: NSUnderlineStyle.styleSingle.rawValue,
                                      range: NSRange(location: 0, length: interactableText.length))
        text.append(interactableText)
        videoDescTextView.attributedText = text
        videoDescTextView.textAlignment = .center
        videoDescTextView.isEditable = false
        videoDescTextView.isSelectable = true
        videoDescTextView.delegate = self
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        if (characterRange.location > 48 && characterRange.location < 65){
            print("open phone")
        }else{
            print("open gmail")
        }
        return false
    }

Steps -
1. Set the delegate to your text field and don't forget to implement UITextViewDelegate
2. Take the textView outlet - @IBOutlet weak var videoDescTextView: UITextView!
3. Add these two functions given above.
This function shows how to detect phone numbers, email from textView, how to underline your email id, how to give custom color to your text, custom font, how to call a function when tapping on phone or email, etc.
Hope this will help someone to save their valuable time. Happy Coding :)

A: If you want to auto detect links, email etc Please make sure "isSelectable" is set to true.
textview.isSelectable = true
textview.editable = false
textview.dataDetectorTypes = .all


Q: Why does Debug mode not guarantee the completion of a Task (.net core, C#) every one.
I am a newbie to here and the programming world.
MS docs is saying A task is a single work that is guaranteed to complete.
I found it is true in release build but not in debug build.
My testing code is very simple.
        static void Main(string[] args)
        {
            Console.WriteLine("1st Code executed");
            Task task = new Task(() =>
            {
                Console.WriteLine("2nd Code executed");
                Console.WriteLine("3rd Code executed");
            });
            task.Start();
            Console.WriteLine("4th Code executed");

            Console.ReadLine();
           }

In debug mode, it results in one of three below:
         /*Mostly
         * 1st Code executed
         * 4th Code executed

         * rarely
         * 1st Code executed
         * 4th Code executed
         * 2nd Code executed

         * rarely
         * 1st Code executed
         * 4th Code executed
         * 2nd Code executed
         * 3rd Code executed */

In release build, there is no exception that all four lines are shown before the app finishes, although lines in the task and 4th line comes in arbitrary order.
My question is what makes the app finish without completion of a task in debug mode and, in addition, how I can fix it thru debug options, if any.

A: Quick answer
Your Main method and your task run in parallel, and the Main method does not wait the task to finish.
In release mode, the task is "lucky". It finishes before Main. Not in debug mode. In both case the execution is random.
The fact they run in parallel explain why your can't predict the order of the printed lines.
Explanations
A Task is a thread that comes from the thread pool, so they are background threads.
The process running your code (which consist of all your threads) does not wait for background threads to finish in order to terminate. The process only wait that foreground threads have finished.
Then you may want to use the Thread class because they are foreground by default. But using Task is easier. So @John Wu's comment is totally relevant:

A task is not guaranteed to finish unless you await it or call Wait or
  Result or do something else to wait for it

You simply want to add at the end of your code:
task.Wait();

However you'll never be able to predict the order of the printed lines, because the threads run in parallel.


Q: BackgroundWorker's ProgressChanged not updating UI until end of work loop I am coding a WPF application that will grab email's off of an IMAP account, and then export them into a user-selected folder.
I use a BackgroundWorker to download the emails. However, my UI isn't being updated until the loop is over.
Any tips would be appreciated.
Class MainWindow
    Public MailRepo As MailRepository
    Private bw_Connect As New BackgroundWorker
    Private bw_Save As New BackgroundWorker

    Public Sub New()
        InitializeComponent()

        bw_Connect.WorkerReportsProgress = True
        bw_Connect.WorkerSupportsCancellation = True
        AddHandler bw_Connect.DoWork, AddressOf bw_Connect_DoWork

        bw_Save.WorkerReportsProgress = True
        bw_Save.WorkerSupportsCancellation = True
        AddHandler bw_Save.DoWork, AddressOf bw_Save_DoWork
        AddHandler bw_Save.ProgressChanged, AddressOf bw_Save_ProgressChanged

    End Sub

    Private Sub bw_Save_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

        If bw_Connect.CancellationPending = True Then
            e.Cancel = True
        Else
            SaveEmails()
        End If
    End Sub

Private Sub SaveEmails()
    Dim allMails As IEnumerable(Of Message)
    'Get All Emails in Mailbox
    Try
        Dim mailBox As String
        Dispatcher.Invoke(DirectCast(Sub()
                                         mailBox = comboBoxEmailFolders.SelectedValue
                                     End Sub, Action))
        allMails = MailRepo.GetAllMails(mailBox)
    Catch i4e As Imap4Exception
        MsgBox("Error: Folder not found" & vbCrLf & i4e.Message)
        Return
    End Try
    Dim msg As Message
    Dim msgInt As Integer = 1
    'Save each message
    For Each msg In allMails
        bw_Save.ReportProgress(100 / allMails.Count * msgInt, Nothing)
        SaveMessage(msg)
        msgInt += 1
    Next
End Sub

Private Sub bw_Save_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
        Dim percentDone As String = e.ProgressPercentage.ToString() & "%"
        updateStatus("Saving Emails " & percentDone & " done.")
        progressBarStatus.Value = e.ProgressPercentage
    End Sub


Q: Run cmd reg delete commands from a txt I have a txt file like this:
HKLM\SOFTWARE\Classes\CLSID\{03ACC284-B757-4B8F-9951-86E600D2CD06}]
HKLM\SOFTWARE\Classes\CLSID\{03ACC284-B757-4B8F-9951-86E600D2CD06}\InprocServer32
HKLM\SOFTWARE\Classes\CLSID\{03ACC284-B757-4B8F-9951-86E600D2CD06}\ProgID
HKLM\SOFTWARE\Classes\CLSID\{03ACC284-B757-4B8F-9951-86E600D2CD06}\Programmable
HKLM\SOFTWARE\Classes\CLSID\{03ACC284-B757-4B8F-9951-86E600D2CD06}\TypeLib
HKLM\SOFTWARE\Classes\CLSID\{03ACC284-B757-4B8F-9951-86E600D2CD06}\VersionIndependentProgID
HKLM\SOFTWARE\Classes\CLSID\{17E3A1C3-EA8A-4970-AF29-7F54610B1D4C}
HKLM\SOFTWARE\Classes\CLSID\{17E3A1C3-EA8A-4970-AF29-7F54610B1D4C}\InprocServer32
HKLM\SOFTWARE\Classes\CLSID\{17E3A1C3-EA8A-4970-AF29-7F54610B1D4C}\ProgID
HKLM\SOFTWARE\Classes\CLSID\{17E3A1C3-EA8A-4970-AF29-7F54610B1D4C}\Programmable

I want to delete around 1000 registry keys. What is the easiest way?
I don't want to delete them one at a time.

A: From command-line:
for /f %A in (C:\your\text\file.txt) do (reg del "%A" /f)

In batch:
@echo off

set "src=C:\your\text\file.txt"

for /f %%A in (%src%) do (
    reg del "%%A" /f
)

As the comments say, be super careful when editing your registry - especially if you're not 100% positive that every line/key in your text file can and should be deleted. It may not save you from a catastrophic failure, but if you go with a batch solution you can also add some sort of backup feature to your loop:
@echo off

set "src=C:\your\text\file.txt"
set "bkp=%USERPROFILE%\Desktop\Backup"

if not exist "%bkp%" md "%bkp%"

for /f %%A in (%src%) do (
    if not exist "%bkp%\%%A" md "%bkp%\%%A"
    reg export "%%A" "%bkp%\%%A\key.reg"
    reg del "%%A" /f
)

This has a folder on your Desktop called "Backup", and will essentially recreate the registry structure of the keys you're deleting before exporting each key into its corresponding folder. Depending on what the keys are named it may have issues with special characters when making folders, but this is just an example in case you're interested in backing things up at all.


Q: Nginx and Unicorn - (Connection refused) while connecting to upstream Trying to deploy my first rails app on a vps. I have followed the instructions in the following setup.
https://www.digitalocean.com/community/articles/how-to-1-click-install-ruby-on-rails-on-ubuntu-12-10-with-digitalocean
But my site gets a 504 Gateway Time-out.
In the nginx log I get the following:
2013/10/16 03:10:45 [error] 19627#0: *82 connect() failed (111: Connection refused) while connecting to upstream, client: 121.218.167.90, server: _, request: "GET / HTTP/1.1", upstream: "http://162.243.39.196:8080/", host: "162.243.39.196"

And when I try to run unicorn I get the following
E, [2013-10-16T04:26:28.530019 #30087] ERROR -- : adding listener failed addr=0.0.0.0:8080 (in use)

My nginx default file has the following
server {
        listen   80;
        root /home/rails/public;
        server_name _;
        index index.htm index.html;

        location / {
                try_files $uri/index.html $uri.html $uri @app;
        }

        location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|mp3|flv|mpeg|avi)$ {
                        try_files $uri @app;
                }

         location @app {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_redirect off;
                proxy_pass http://app_server;
    }

}

My /home/unicorn/unicorn.conf has
listen "127.0.0.1:8080"
worker_processes 2
user "rails"
working_directory "/home/rails"
pid "/home/unicorn/pids/unicorn.pid"
stderr_path "/home/unicorn/log/unicorn.log"
stdout_path "/home/unicorn/log/unicorn.log"

Thanks for your help.

A: You are missing an upstream block where you refer to in proxy_pass http://app_server;. You can put it above the server block like this.
upstream app_server {
    server 127.0.0.1:8080 fail_timeout=0;
}

server {
    listen   80;
    root /home/rails/public;
    server_name _;
    index index.htm index.html;
    ...


Q: how do I order by the results of multiple union statements? I can't use a common table expression:
WITH    cte
          AS (SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB1].[dbo].[ProcessingStations]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB2].[dbo].[ProcessingStations]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB3].[dbo].[ProcessingStations]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB4].[dbo].[ProcessingStations]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB5].[dbo].[ProcessingStations]
              ORDER BY  [StationID]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB6].[dbo].[ProcessingStations]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB7].[dbo].[ProcessingStations]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB8].[dbo].[ProcessingStations])
    SELECT  *
    FROM    cte
    ORDER BY StationID

How would I go about doing this?

A: Just put the ORDER BY at the end of your chain of SELECT ... FROM ... UNION ALL statements:
SELECT    [StationID],
          [LastDistribution]
          FROM      [DB1].[dbo].[ProcessingStations]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB2].[dbo].[ProcessingStations]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB3].[dbo].[ProcessingStations]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB4].[dbo].[ProcessingStations]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB5].[dbo].[ProcessingStations]
          ORDER BY  [StationID]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB6].[dbo].[ProcessingStations]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB7].[dbo].[ProcessingStations]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB8].[dbo].[ProcessingStations]
ORDER BY StationID

Here's a quick example I did in SSMS:
DECLARE @a table (x int)
DECLARE @b table (x int)
DECLARE @c table (x int)

insert into @a values (5)
insert into @a values (4)
insert into @a values (3)

insert into @b values (0)
insert into @b values (1)
insert into @b values (2)

insert into @c values (0)
insert into @c values (1)
insert into @c values (2)

select * from @a
union all
select * from @b
union all
select * from @c
order by x

And here's the output:
  x
-----
  0
  0
  1
  1
  2
  2
  3
  4
  5

As you can see, even though the SELECT * FROM @a came first, it still placed those last in the result set

A: Why can't you use a CTE?. Anyway, you still can do the same using a derived table:
SELECT *
FROM (  SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB1].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB2].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB3].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB4].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB5].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB6].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB7].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB8].[dbo].[ProcessingStations]) A
ORDER BY StationID

A: See the fiddle, just put the ORDER BY on the last set to be "unioned". It achieves the same result without the overhead of the CTE.
The order will effect the entire unified set.
SELECT
        [StationID],
        [LastDistribution]
    FROM
        [dbo].[ProcessingStations]
UNION ALL
SELECT
        [StationID],
        [LastDistribution]
    FROM
        [dbo].[ProcessingStations]
UNION ALL
SELECT
        [StationID],
        [LastDistribution]
    FROM
        [dbo].[ProcessingStations]
    ORDER BY
        [StationID]


Q: Is there a way to get the resulting Makefile after includes? In a (GNU) Makefile, one can do:
include foo.mk

all:
    @echo "Hello, world!"

Is there a way to get make to spit out the Makefile after foo.mk has been included? Akin to after the C preprocessor has expanded macros etc.?
Update: a commenter below asked me to specify which problem I'm trying to solve. I wish to trigger a rebuild when/if there's changes to the Makefile and/or the underlying, included makefiles. I've found a recipe that goes something like:
.PHONY: bar

SHAFILE := foobar.sha256
$(SHAFILE): bar
    @sha256sum Makefile | cmp -s - $@ || sha256sum Makefile > $@

...

%.o: %.c $(SHAFILE)
$(CC) -c -o $@ $< $(CFLAGS)

(Obviously, the checksum should be of the Makefile including includes, but this is a start.)

A: Caveat: I haven't tried this, only read the manual.
After all your include lines (including the transitive set of nested includes, and even lines created by text substitution or built by functions), the Make variable MAKEFILE_LIST will reference all your makefiles.
So it should be sufficient to add a dependency to the end of your file such as
%.o: $(MAKEFILE_LIST)

You don't actually need the contents of the effective Makefile, just the list of files that comprise it.

A:
Is there a way to get make to spit out the Makefile after foo.mk has been included?

No.
There's gmake -d with a ton of debug output, some of which indicating which makefiles are being read:
$ gmake -d|grep Reading
Reading makefiles...
Reading makefile `GNUmakefile'...
Reading makefile `foo.mk' (search path) (no ~ expansion)...

This might be helpful if there are recursive include directives or those under conditionals.
Maybe you could tell us your actual problem you want to solve?


Q: Convert entire dom4j Element's namespace If I have an XML element as such:
<First id="" name="">
  <Second id="" name="">
  </Second>
</First>

How can I use dom4j to convert the namespace to something like below? Is there a simple way?
<test:First test:id="" test:name="">
  <test:Second test:id="" test:name="">
  </test:Second>
</test:First>

A: If you prefer a Java centric solution, DOM4J has support for traversing a document tree:
    Document doc = DocumentHelper.parseText(XML);
    final Namespace ns = Namespace.get("test", "urn:foo:bar");
    doc.accept(new VisitorSupport() {
        @Override
        public void visit(Element node) {
            node.setQName(QName.get(node.getName(), ns));
            // Attribute QNames are read-only, so need to create new
            List<Attribute> attributes = new ArrayList<Attribute>();
            while(node.attributes().size() > 0)
                attributes.add(node.attributes().remove(0));
            for(Attribute a: attributes) {
                node.addAttribute(QName.get(a.getName(), ns), a.getValue());
            }
        }
    });

A: You could run an XSLT transformation:
  <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
    <xsl:template match="*">
      <xsl:element name="test:{local-name()}" namespace="http://test-namepace/ns">
        <xsl:apply-templates select="@* | node()"/>
      </xsl:element>
    </xsl:template>
    <xsl:template match="@*">
      <xsl:attribute name="test:{local-name()}" namespace="http://test-namepace/ns">
        <xsl:value-of select="."/>
      </xsl:element>
    </xsl:template>
  </xsl:transform>

I think DOM4J has methods to apply an XSLT 1.0 transformation directly, but you also have the option to use Saxon, which handles DOM4J as input and/or output alongside many other tree models.
Incidentally, (a) in your requirements example, the result document is ill-formed because it doesn't declare the namespace, and (b) it's not generally considered good practice to put all the attributes in the same namespace as the containing elements; I've given you a solution on the assumption that you have good reasons for this rather strange design.


Q: Screen freezes, mouse still works on Windows 7 - requires reboot I started having super annoying problems on my machine all of a sudden (no hardware or software changes were made).
I can use the PC normally, and all of a sudden, the screen would just freeze, and stop responding to keyboard, and mouse clicks. Clock would freeze also. I can still move the mouse,  which changes from pointer, to hand, to stretch cursors when I move it over random stuff. Sometimes it would unfreeze after a minute or so, but usually it does not, and requires a power cycle.
Im running Windows 7 64x on i7 920, 12 GB ram, 2 x 80GB SSD raid0, dual 8800GTX, Gigabyte UDR5 mobo, 4 x 300GB drive in raid 5 on mobo, another 4 x 1.5TB in raid5 on a separate raid card and some 1000W power supply.
EDIT: Whats interesting is that once the screen freezes, computer still responds to mouse movements, and clicks, so if I move a mouse next a window, and resize it, it actually resizes it, but it doesn't visually change. The resize cursor position changes to where I last let it go. I can also minimize all windows, which doesn't allow me to resize anything anymore (since its all minimized), yet the screen still remains static. I figured this could be a GPU problem.... but why would the mouse still work?

A: That sounds like a display issue for sure.  Make sure your display drivers are up to date.  Try running the machine with the cover off to see if that changes when the freeze occurs; if it happens later or not at all, it's most likely heat related.  The temperatures you listed seem a trifle high by my standards.


Q: Interrrupt-able ScheduledExecutorService in Android Currently, I am designing a stock market app with the following requirement

*

*1) Scan stock price repeatedly, with a fixed sleep time.

*2) Able to interrupt the sleep any-time. This is because when user adds a new stock, we need to wake up from sleep, and scan immediately.

Previously, I'm using bare bone Thread, to full-fill the above 2 requirements.
private class StockMonitor extends Thread {
    @Override
    public void run() {
        final Thread thisThread = Thread.currentThread();

        while (thisThread == thread) {

            // Fetch stock prices...

            try {
                Thread.sleep(MIN_DELAY);
            } catch (java.lang.InterruptedException exp) {
                if (false == refreshed()) {
                    /* Exit the primary fail safe loop. */
                    thread = null;
                    break;
                }
            }
        }
    }

    public synchronized void refresh() {
        isRefresh = true;
        interrupt();
    }

    private synchronized boolean refreshed() {
        if (isRefresh) {
            isRefresh = false;
            // Interrupted status of the thread is cleared.
            interrupted();
            return true;
        }
        return false;
    }
}

When I want to perform requirement (2), I will call refresh. Thread will be waked up, and perform job immediately.
However, I feel it is difficult to maintain such bare bone Thread code, and can make mistake easily.
I prefer to use ScheduledExecutorService. However, it lack of ability for me to wake up the Thread from sleeping state, and perform job immediately.
I was wondering, is there any classes in Android, which enables me to perform periodically task as in ScheduledExecutorService? Yet has the ability to wake up the Thread from sleeping state, and perform job immediately.

A: Here is my solution with ScheduledThreadPoolExecutor. To cancel existing tasks, issue future.cancel() on Future object returned from scheduleAtFixedRate(). Then call scheduleAtFixedRate() again with initial delay set to 0.
class HiTask implements Runnable {
    @Override
    public void run() {
        System.out.println("Say Hi!");
    }
}

// periodically execute task in every 100 ms, without initial delay time

ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);

long initialDelay = 0;
long period = 100;

ScheduledFuture<?> future1 = exec.scheduleAtFixedRate(new HiTask(), initialDelay, period, TimeUnit.MILLISECONDS);

// to trigger task execution immediately

boolean success = future.cancel(true);    // mayInterruptIfRunning = true: interrupt thread even task has already started

ScheduledFuture<?> future2 = exec.scheduleAtFixedRate(new HiTask(), initialDelay, period, TimeUnit.MILLISECONDS);

A: Options you have with ScheduledExecutorService:

*

*submit() the same task again in the moment you need the data to be refreshed. If will be immediately executed (and only once). Possible drawback: If this happens very close to a scheduled execution, you have two scans with very little time in between.

*cancel() the Tasks in the moment you need the data to be refreshed, submit() it once for immediate execution and and schedule() for repeated execution.

Be aware that any exceptions that occur in the task that are unhandled cancel future executions. How to solve that is answered in How to reschedule a task using a ScheduledExecutorService?.
ExecutorService is not persistent (i.e. does not survive device reboot). I don't know if that's a problem for you. If it is there are libraries specialized on background task execution on Android:

*

*smart-scheduler-android

*android-priority-jobqueue

*android-job
You would have to apply the same workarounds mentioned above.


Q: get the child key for specific value when append table using Jquery i created a table and used Jquery to put all the user database from firebase info in it. The problem is: i have a button in the table that be should when you click the button console print the element key from database.
var userDataRef = firebase.database().ref("User/3N2f2rJSSAZmFOdZEeJdlsuEZam2").orderByKey();

userDataRef.on('child_added', function(childSnapshot) {
  var key = childSnapshot.key;
  var childData = childSnapshot.val();
  var title_val = childData.Title;
  var url_val = childData.Url;
    // Append data
    $("#data").append("
" + title_val + "	 <button class='box'>GO</button>	<button id='del' class='box'>Delete</button>	<
");

    $('#data').on('click', '#del', function(){
        console.log(key)
      });

                            Title
                            Link
                            Delete

when this function perform i gut all the keys not just the one from the exact raw
$('#data').on('click', '#del', function(){
        console.log(key)
      });

output :
-LkT_afLi9nfn65OS2QJ database.js:17:17
-LkTciKQVEa2bsbtSwkW database.js:17:17
-LkTclDO8dYSBfgiBjAZ

A: ID's should never be repeated, use the class of the buttons instead as a common attribute.

A: You are binding to all the elements and you are duplicating ids. Ids are singular.
You would be better off with either binding to the one button alone or event delegation with a data attribute.
userDataRef.on('child_added', function(childSnapshot) {
  /* cut out the vars */
  var myRow = $("
" + title_val + "	 <button class='box'>GO</button>	<button class='box'>Delete</button>
");
  myRow.find("button").on("click", function(){
    console.log(key)
  });
  $("#data").append(myRow);
});

or event delegation with a data attribute
$("#data").on("click", "button[data-key]", function(evt){
  var btn = $(this);
  console.log(btn.data("key"))
});

userDataRef.on('child_added', function(childSnapshot) {
  /* cut out the vars */
  var myRow = $("
" + title_val + "	 <button class='box'>GO</button>	<button class='box' data-key='" + key + "'>Delete</button>
");
  $("#data").append(myRow);
});


Q: How to query native html elements when testing a React application with Jest? When I render React elements, for example, a Button, then an equivalent HTML button element is created in the DOM.
But, when I query the DOM I'm still getting a wrapped element.
HTMLButtonElement {
      '__reactInternalInstance$gt1haeiqrhv': FiberNode {
        tag: 5,
        key: null,
        ...
}

Why don't I get the native element as if I rendered a normal div using JSDOM?
Is there a way to get it?

A: I suppose you have to query for getDOMNode:
const button = wrapper.find('button').getDOMNode();
// const button = wrapper.getDOMNode(); // <---if wrapper is button element

It will give you the lying dom element in the component.


Q: What is the best way to control a variable with radio buttons? I'm very new to Android programming, and I'm unable to find out what the accepted way to reach my goal is:
I have a variable in my main activity (sortOrder), which I want to set using radio buttons in a different activity. At the moment, I just change MainActivity.sortOrder from the other activity with a big switch case, so I'm wondering if there is a more elegant way.
Also, at the moment the radio buttons "forget" their choice when I return to MainActivity. Is is possible to save the selected radio button, and set the variable from that in MainActivity?
Here's some  code:
in MainActivity:
public static String sortOrder;
public static int checkedId;

These are given values in onCreate:
sortOrder = ShipContract.ShipEntry.COLUMN_NAME_NAME + " ASC";
checkedId = R.id.sort_name;

And here is OptionsSort, which is started from MainActivity:
public class OptionsSort extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_options_sort);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    RadioButton checkedButton = (RadioButton) findViewById(MainActivity.checkedId);
    checkedButton.setChecked(true);
}

public void onRadioButtonClicked(View view) {
    boolean checked = ((RadioButton) view).isChecked();

    switch(view.getId()) {
        case R.id.sort_name:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_NAME + " ASC";
            break;
        case R.id.sort_date:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_DATE + " ASC";
            break;
        case R.id.sort_capacity:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_CAPACITY + " ASC";
            break;
        case R.id.sort_line:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_LINE + " ASC";
            break;
        case R.id.sort_displacement:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_DISPLACEMENT + " ASC";
            break;
        case R.id.sort_speed:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_SPEED + " ASC";
            break;
        case R.id.sort_power:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_POWER + " ASC";
            break;
    }
    RadioGroup radiogroup = (RadioGroup) findViewById(R.id.sort_group);
    MainActivity.checkedId = radiogroup.getCheckedRadioButtonId();
    finish();
}

}

A: so far i understand your problem you want to take sortOder value from activity B and bring it to Activity A.This can be achieved if you startActivityForResult and there in activity B when you are done with everything just call setresult method and give it the resultant intent and finish this activity B.
In activity A you have to override onActivityResult and handle the result from activity B .
like
startActivityForResult(new Intent(this,ActivityB.class),123);
@Override
public void onActivityResult(int requestCode, int resultCode, Intentdata) {
        super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {

if (requestCode==123)
    {
      String sordData= data.getStringExtra("sortOrder","byName")
            sortYourDAta(sordData);
    }
}

}
and in activity b when sort order is selected
just store value in a variable sortOrder="byDate";
and onbackpressed or when ever you want to go back just call this
setResult(123,new Intent().putExtra("sortOrder",sortOrder));
finish();


Q: How to make flashlight Blink I am trying to make the camera flashlight blink. I already have written a code for switching the flashlight on and off. I am trying to create a method which could blink the flashlight on the click of a button.
How can i achieve this.
public void flash_effect() throws InterruptedException
{
    camera = Camera.open();
    params = camera.getParameters();
    params.setFlashMode(Parameters.FLASH_MODE_TORCH);

    Thread a = new Thread()
    {
        public void run()
        {
            for(int i =0; i < 10; i++)
            {
                camera.setParameters(params);
                camera.startPreview();
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                camera.stopPreview();
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    };
    a.start();
}

This code is not working.What am i doing wrong. Waiting for help.
EDITED
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testlight"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

        <uses-permission android:name="android.permission.CAMERA" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

LOGCAT
06-16 14:03:40.579: E/AndroidRuntime(20302): FATAL EXCEPTION: main
06-16 14:03:40.579: E/AndroidRuntime(20302): java.lang.IllegalStateException: Could not execute method of the activity
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.view.View$1.onClick(View.java:3626)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.view.View.performClick(View.java:4231)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.view.View$PerformClick.run(View.java:17537)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.os.Handler.handleCallback(Handler.java:725)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.os.Handler.dispatchMessage(Handler.java:92)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.os.Looper.loop(Looper.java:158)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.app.ActivityThread.main(ActivityThread.java:5751)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at java.lang.reflect.Method.invokeNative(Native Method)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at java.lang.reflect.Method.invoke(Method.java:511)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at dalvik.system.NativeStart.main(Native Method)
06-16 14:03:40.579: E/AndroidRuntime(20302): Caused by: java.lang.reflect.InvocationTargetException
06-16 14:03:40.579: E/AndroidRuntime(20302):    at java.lang.reflect.Method.invokeNative(Native Method)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at java.lang.reflect.Method.invoke(Method.java:511)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.view.View$1.onClick(View.java:3621)
06-16 14:03:40.579: E/AndroidRuntime(20302):    ... 11 more
06-16 14:03:40.579: E/AndroidRuntime(20302): Caused by: java.lang.RuntimeException: Fail to connect to camera service
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.hardware.Camera.native_setup(Native Method)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.hardware.Camera.(Camera.java:362)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.hardware.Camera.open(Camera.java:336)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at com.example.testlight.MainActivity.flash_effect(MainActivity.java:185)

A: I've been working on your problem, and my solution can blink the flashlight. I used your same logic, except I used Handler instead of Thread to delay the blink.
public void flash_effect(View view)
{
    long delay = 50;
    camera = Camera.open();
    params = camera.getParameters();
    params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);

    camera.setParameters(params);
    camera.startPreview();

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            camera.setParameters(params);
            camera.stopPreview();
            camera.release();

        }
    }, delay);

}

You have to initialise the handler before using it. Do it in the onCreate() method.
 Handler handler = new Handler();

This method is an onClick() of a button. I used a button to start a blink
 public void flash_effect(View view)


Q: How to rerender an outputpanel after remoting completes I have a repeat control that populates commandbuttons(view,edit,delete) for each record of an object. On click of a command button I want to delete the respective record and render the containing output panel. The code attached actually deletes the record but it looks like it postbacks the page and the panel doesn't show any record though it actually has records. I tried without the actionfunction, just by adding rerender="leftOPanel" in commandbutton, I could not see any change in the list, but if I refresh I could see the record deletion.  The rerender occurs before java script remote method for deletion completes?! I don't understand what is going wrong here. The record is getting deleted successfully in all the cases, but only this rerender is not working fine.
global with sharing class ProjectController {

public static List<Project__c> lstproj{get; set;}
public Project__c prj{get; set;}

public ProjectController(ApexPages.StandardController controller)
{
    prj = new Project__c();
    lstproj = [SELECT Name,Proj_Name__c,Status__c,Abstract__c
               FROM Project__c ];
}

@RemoteAction
global static List<Project__c> DeleteProj(String projId) {

    Project__c[] proj;
    proj = [SELECT id,Name,Proj_Name__c,Status__c,Abstract__c
               FROM Project__c  WHERE Name = :projId];
    if(proj.size() > 0 || proj[0].Id != ''){
        delete proj;}
   lstproj = [SELECT Name,Proj_Name__c,Status__c,Abstract__c
               FROM Project__c ];

    return lstproj;

}}

VF page
<apex:page  sidebar="false"  standardController="Project__c" extensions="ProjectController" >
<apex:form >
    <apex:pageBlock mode="edit" >
        <apex:outputPanel id="leftOPanel" >

                <apex:repeat value="{!lstproj}" var="p">

{!p.Proj_Name__c}

<apex:commandbutton value="View" />

<apex:commandbutton value="Edit" />

<apex:commandbutton value="Delete" onclick="DeleteProject('{!p.Name}');" />

                </apex:repeat>

        </apex:outputPanel>
        <apex:actionFunction name="rerenderleftOPanel" rerender="leftOPanel" />
    </apex:pageBlock>
</apex:form>
</apex:page>

A: java-script(VF) Remoting is an asynchronous call, you need to call your <apex:actionFunction> in the callback function of Remoting, means when remoting function finish with the execution. update your Remoting code to:
function DeleteProject(projId)
{
    Visualforce.remoting.Manager.invokeAction(
      '{!$RemoteAction.ProjectController.DeleteProj}',projId,
       function(result,event){
           if (event.status){// When call is succesfull with event.status = true
              console.log(result.length); // print the result length on console
              rerenderleftOPanel(); // call rerender function
           }
           else{
                console.log(event.message); // print error on console(if any)
           }
       },
       {escape:true}
    );
    //rerenderleftOPanel();
}

UPDATE
I just seen your controller code, and get to know you are using static variable lstproj for rendering on VF page. That where you are making mistake. Static variables are transient variable, which didn't communicate with Visualforce View state. In order to to interact with VF page, make your variable as instance with getter-setter property. Change your class code as below:
Apex Class Change:
global with sharing class ProjectController {

public List<Project__c> lstproj{get; set;}// #### CHANGE #### ***** variable Changed to instance variable*****
public Project__c prj{get; set;}

public ProjectController(ApexPages.StandardController controller)
{
    prj = new Project__c();
    initProjList(); // initialize your list with data
}

public void initProjList(){ // #### CHANGE #### ***** method to get data list into your page variable*****
   lstproj = [SELECT Name,Proj_Name__c,Status__c,Abstract__c
               FROM Project__c ];
}

@RemoteAction
global static List<Project__c> DeleteProj(String projId) {

    Project__c[] proj;
    proj = [SELECT id,Name,Proj_Name__c,Status__c,Abstract__c
               FROM Project__c  WHERE Name = :projId];
    if(proj.size() > 0 || proj[0].Id != ''){
        delete proj;}
   list<Project__c> lstproj = [SELECT Name,Proj_Name__c,Status__c,Abstract__c
               FROM Project__c ];   // #### CHANGE #### ***** initialize the list Object *****

    return lstproj;

}}

Page Change:
Also you need to change your page code and need to add following two changes:
First Change:
First change as @saroj suggested call an action method from <apex:actionfunction>, Well it is not required because of re-render will not work, re-render can work without Action also, but it is required to update your page list variable lstproj after deletion. so it can display the updated data list on page again. See change:
<apex:actionFunction action="{!initProjList}" name="rerenderleftOPanel" rerender="leftOPanel" />

Second Change:
Second change which I observed here, you have used <apex:commandButton> for initiate the action flow, <apex:commandButton> are act like submit button of html so they will refresh the page by deafult, for preventing them to reload the whole page, add one line of code return false after your VF Remoting Method call in onClick attribute, like: onclick="DeleteProject('{!p.Name}'); return false;"

A: In addition to updation of the Remoting code, you have to add an action to your <apex:actionFunction.
VF Page
.....
<apex:actionFunction action="{!fetchDetails}" name="rerenderleftOPanel" rerender="leftOPanel" />
......

Controller
......
......
public PageReference fetchDetails() {
    lstproj = [SELECT Name,Proj_Name__c,Status__c,Abstract__c FROM Project__c ];
    return null;
}
......


Q: Google Drive API IOS Permissions of GTLRDriveService I am playing around with the google drive API and trying to build a simple app that uploads a picture to my google drive. The app is supposed to upload a picture once the user is signed in, however it gives an error of

"2017-09-14 00:55:20.342237-0400 driveTest[6705:1647551] An error
  occurred: Error Domain=com.google.GTLRErrorObjectDomain Code=403
  "Insufficient Permission"
  UserInfo={GTLRStructuredError=GTLRErrorObject 0x1c4251d30:
  {message:"Insufficient Permission" errors:[1] code:403},
  NSLocalizedDescription=Insufficient Permission}"

I have tried to pass it the service which is of type GTLRDriveService to the initSetup() function of  the userSetUp class, but to no avail. Could someone please point me to the right track as to why my permissions are not working even though I have logged on correctly, and the part where I am passing in the GTLRDriveService is in the code that runs after a sucessful login.
I instantiate a userSetUp object and I
let setUpUser = userSetUp()
setUpUser.initSetup(service)
I have userSetUp written in objective c as such and it is bridged correctly as I am able to instantiate it in my viewcontroller file which is written in swift.
UserSetUp:::::::
#import "userSetUp.h"
#import <GoogleSignIn/GoogleSignIn.h>
@import GoogleAPIClientForREST;

@implementation userSetUp
- (void) initSetup:(GTLRDriveService *) driveService {

    printf("heloooooaiosuoiadoidauoalo");
    //GTLRDriveService *driveService = [GTLRDriveService new];
    //NSData *fileData = [[NSFileManager defaultManager] contentsAtPath:@"files/apple.jpg"];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"apple" ofType:@"jpg"];
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    GTLRDrive_File *metadata = [GTLRDrive_File object];
    metadata.name = @"apple.jpg";
    //metadata.mimeType = @"application/vnd.google-apps.document";

    GTLRUploadParameters *uploadParameters = [GTLRUploadParameters uploadParametersWithData:fileData
                                                                                MIMEType:@"image/jpeg"];
    uploadParameters.shouldUploadWithSingleRequest = TRUE;
    GTLRDriveQuery_FilesCreate *query = [GTLRDriveQuery_FilesCreate queryWithObject:metadata
                                                                   uploadParameters:uploadParameters];
    query.fields = @"id";
    [driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                         GTLRDrive_File *file,
                                                         NSError *error) {
        if (error == nil) {
            //NSLog(@"File ID %@", file.identifier);
            printf("it worked");
        } else {
            NSLog(@"An error occurred: %@", error);
        }
    }];

printf("upload complete!");

}
@end

And Viewcontroller. swift
     import GoogleAPIClientForREST
    import GoogleSignIn
    import UIKit
class ViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate     {

// If modifying these scopes, delete your previously saved credentials by
// resetting the iOS simulator or uninstall the app.
private let scopes = [kGTLRAuthScopeDriveReadonly]

let service = GTLRDriveService()
let signInButton = GIDSignInButton()
let output = UITextView()

override func viewDidLoad() {
    super.viewDidLoad()

    // Configure Google Sign-in.
    GIDSignIn.sharedInstance().delegate = self
    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().scopes = scopes

    GIDSignIn.sharedInstance().signInSilently()
    signInButton.frame = CGRect(x: view.frame.width/2 - signInButton.frame.width , y:  view.frame.height/2, width: signInButton.frame.width, height: signInButton.frame.height)
    // Add the sign-in button.
    view.addSubview(signInButton)

    // Add a UITextView to display output.
    output.frame = view.bounds
    output.isEditable = false
    output.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0)
    output.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    output.isHidden = true
    view.addSubview(output);
    //let itsASetup()
}

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
          withError error: Error!) {
    if let error = error {
        showAlert(title: "Authentication Error", message: error.localizedDescription)
        self.service.authorizer = nil
    } else {
        self.signInButton.isHidden = true
        self.output.isHidden = false
        self.service.authorizer = user.authentication.fetcherAuthorizer()

        listFiles()
    }
}

// List up to 10 files in Drive
func listFiles() {
    let query = GTLRDriveQuery_FilesList.query()
    query.pageSize = 10
    service.executeQuery(query,
                         delegate: self,
                         didFinish: #selector(displayResultWithTicket(ticket:finishedWithObject:error:))
    )

}

// Process the response and display output
@objc func displayResultWithTicket(ticket: GTLRServiceTicket,
                             finishedWithObject result : GTLRDrive_FileList,
                             error : NSError?) {

    if let error = error {
        showAlert(title: "Error", message: error.localizedDescription)
        return
    }

    var text = "";
    if let files = result.files, !files.isEmpty {
        text += "Files:\n"
        for file in files {
            text += "\(file.name!) (\(file.identifier!))\n"
        }
    } else {
        text += "No files found."
    }
    output.text = text
    let setUpUser = userSetUp()
    setUpUser.initSetup(service)
}

// Helper for showing an alert
func showAlert(title : String, message: String) {
    let alert = UIAlertController(
        title: title,
        message: message,
        preferredStyle: UIAlertControllerStyle.alert
    )
    let ok = UIAlertAction(
        title: "OK",
        style: UIAlertActionStyle.default,
        handler: nil
    )
    alert.addAction(ok)
    present(alert, animated: true, completion: nil)
}
}

A: try to Change your scope like:
class ViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate
{
    // If modifying these scopes, delete your previously saved credentials by

    private let scopes = ["https://www.googleapis.com/auth/drive"]

    ...
}


Q: Prevent triggering multiple triggers at same time on table update In the SQL server, I have a table X and a table Y.
The primary key of both is same say Z.
I created a trigger that if anything is created/deleted/updated in X then

*

*If the entry doesn't exist in Y for Z then create a new entry.

*If an entry exists in Y for Z then update that row.

I ran a query like this:
Delete FROM Table2 where TId = 1;

This query deleted 10 rows and 10 triggers ran simultaneously. As all ran parallel every trigger executed the else block because there was no entry in Y initially for Z and as all are running they won't find the row in Y. So because of this 10 rows gets created in the Y table.
I want that I should get only 1 entry created and the other triggers should update that entry.
As example I have tables:
Table1(TId PRIMARY KEY, C12, C13);
Table2(C21 PRIMARY KEY, TId FOREIGN KEY(Table1, C11), C23);
Table3(TId PRIMARY KEY, C32, C33);
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[trg1] ON  [dbo].[TABLE2] AFTER DELETE
        AS
        BEGIN
        SET NOCOUNT ON
            IF EXISTS (SELECT * FROM Deleted D )
                    BEGIN
                        IF EXISTS (Select * from [dbo].[Table3] where TId in (Select TId from Deleted D) )
                            BEGIN
                                Update [dbo].[Table3] SET C32 = 1 where TId in (Select TId from Deleted D);
                        END
                        ElSE
                            BEGIN
                            INSERT INTO [dbo].[Table3]
                                (
                                    TId,
                                    C32,
                                    C33
                                )
                            SELECT  TId,
                                    3,
                                    GETUTCDATE()
                            FROM Deleted D WHERE TId is not null
                            SET NOCOUNT OFF
                        END

            END
        SET NOCOUNT OFF
    END

PRINT '';
PRINT 'End of script';
PRINT ' --- // ---';

A: Your entire trigger's code should be something like this:
MERGE INTO Table3 t
USING (SELECT TId,CASE WHEN COUNT(*) > 1 THEN 1 ELSE 3 END as C32
       FROM deleted
       GROUP BY TId) u
ON t.TId = u.TId
WHEN MATCHED THEN UPDATE SET C32 = 1
WHEN NOT MATCHED AND u.TId is not null THEN
    INSERT (TId,C32,C33) VALUES (u.TId, u.C32, GETUTCDATE());

Which will insert a new row but decide whether to set C32 to 1 or 3, depending on how many rows in DELETED are for the same TId, and just update C32 to 1 if a row already existed.
This is all about thinking in sets. You weren't accounting for the fact that deleted could contain multiple rows, some or all of which may have the same TId value. You don't write IF/ELSE blocks that can only make a single decision for all rows in deleted1.

1E.g. if deleted had contained 4 rows total, 2 for TId 6 and 2 for TId 8, and Table3 had contained a row for TId 6 but no row for TId 8, your trigger would have found some matching rows in Table3 and just performed the UPDATE.


Q: android - how to find incompatible apis with older versions I have built an app with api 23/22/21 sdk with minTargetVersion = 16.
I use Android Studio
Sometimes during the development process, I saw android giving hints that a newer api is used when minTarget is 16.
I have fixed most of those but may not be all.
Now I have written lot of code and I am looking for a way to find out all usages of newer api which are not fully compatible with older versions.
I am looking for the same in layout files as well.
Is there an easy way I can find out?
Harder way is to look at every single line of code again or source files.

A: in Android Studio you can click on Analyze in the toolbar at the top > Inspect code > Whole Project
after AS is finished you will have a list of lint errors you can go through


Q: What are the limitations on a "single-line-of-text" column for sharepoint REST filters? So, I am messing with my REST queries again, and was having some of these random errors. After some testing, it was determined that it appears that whenever a filter was applied to the title field, the filter will then refuse to work. Is there something that I missed that I will need to treat the title field any differently than other columns? It also seems like some other single-line-of-text columns are generating errors. So what determines whether if a column can be filtered or not?
As an example, I have been testing on the filter only, and doing statements as below over and over again on different combinations. It seems to me that some columns just plain doesn't work, and some just do not. All the columns I have issues with are single line of texts, that return an error 403. The columns that do not work with filtering included the ones that is being displayed in the result set when other columns are filtered, which seems to indicate that this is related to the filter function, but I am not entirely sure.
$filter=FIELD1 eq 'XXX'
$filter=FIELD2 eq 'YYY'

A: Please add filter column on selected column on REST API
Like as show in below example
?$select=FIELD1,FIELD2&$filter=(FIELD1 eq 'XXX') and (FIELD2 eq 'YYY')


Q: Gulp clean task being called from other tasks gulp.task('watch', gulp.series('clean', gulp.parallel('css')),
    gulp.watch(['./app/scss/**/*.scss'], gulp.series('clean', gulp.parallel('css')))
);

When using any other task in my gulpfile for some reason gulp.watch is being called. Does anyone know what is going wrong with this task?

A: gulp.task('watch', gulp.series('clean', gulp.parallel('css')), () => {
      gulp.watch(['./app/scss/**/*.scss'], gulp.series('clean', gulp.parallel('css')))
    }
);

It appears the issue is calling the gulp.watch function directly rather than from inside of a function. The above code fixes the issue.


Q: Statistics: Binomials Suppose that 30% of all students who have to buy a textbook for a particular course want a new copy, whereas the other 70% want a used copy. Consider a random sample of 25 students.
(b) Suppose that new copies cost \$100 and used copies cost \$70. Assume the bookstore currently has 50 new copies and 50 used copies. What is the expected value of total revenue from the sale of the next 25 copies purchased?
I know that for expected value
$E(X)=\sum_x h(x)*p(x),$ and for problems with constants, it would be a $E(x)+b.$ I just don't know how to apply that here.


Q: How can I make window movement more precise while dragging? I'd like to know if I can make the dragging of windows/items on the screen more precise. As of, the dragging of windows is very vague. For instance, it's as if the window has some sort of virtual friction, and causes the window to be a bit sloppy, the mouse cursor often overtakes the window and window follows behind. It's not lagging or being choppy at all, it's just sloppy movement. Window movement on OS X 10.8 on the same computer is smooth and precise, the window stays with the cursor exactly. And the same happens on Windows too.
Now, if it's possible, could I improve this sloppiness or just make it more precise than it is now.
I am using Ubuntu GNOME, with Gnome 3.10, this happens on all versions of GNOME I’ve tried too.
Thanks in advance!
EDIT: I have researched, but I have not found any answers. And I have no idea where to start myself... thanks again.


Q: TwinCAT 3 user control Is it possible to create a library with Hmi usercontrols?
https://infosys.beckhoff.com/english.php?content=../content/1033/te2000_tc3_hmi_engineering/18014401986701963.html&id=
I have created a librarie for the plc with functionblocks and datastructs.
My usercontrols are mathed with my plcLib. And it would be nice if can use this set-up in every project

A: Your question is a bit unclear, however if you are asking about user access controls, whereby you can give certain users certain permissions, TwinCAT does have a built-in user management system. However, it relies on Beckhoff's HMI software products (Either HMI or HMI Web).
If you are using a different HMI solution, you would need to implement this functionality yourself.


Q: Optimizing pairwise subtruction I have to compute the pairwise difference of particle's velocities for around 1e6 objects each with approx. 1e4 particles. Right now I am using itertools.combinations to loop over the particles, but just for one object my code takes already more than 30 minutes. I was wondering what else can I do to speed it up to a feasible speed, since parallelising doesn't seem to add much in python. Is cython the way to go?
Here is my code just for one of the objects:
def pairwisevel(hist,velj,velk, xj, xk):
    vlos = (velj - velk)
    if( (xj - xk) < 0.):
        vlos = - vlos
    hist.add_from_value(vlos)

for i in itertools.combinations(np.arange(0,int(particles_per_group[0]),1),2):
    pairwisevel(hist, pvel[i[0]], pvel[i[1]],\
                pcoords[i[0]], pcoords[i[1]])

A: I hope I understood your qusition. In this example I calculated the histogramm of one particle object. But if you wan't to do this for all 1e6 groups (1e4*1e4*1e6=1e14) comparisons, this would still take a few days.
In this example I used Numba to accomplish the task.
Code
import numpy as np
import numba as nb
import time

#From Numba source
#Copyright (c) 2012, Anaconda, Inc.
#All rights reserved.

@nb.njit(fastmath=True)
def digitize(x, bins, right=False):
    # bins are monotonically-increasing
    n = len(bins)
    lo = 0
    hi = n

    if right:
        if np.isnan(x):
            # Find the first nan (i.e. the last from the end of bins,
            # since there shouldn't be many of them in practice)
            for i in range(n, 0, -1):
                if not np.isnan(bins[i - 1]):
                    return i
            return 0
        while hi > lo:
            mid = (lo + hi) >> 1
            if bins[mid] < x:
                # mid is too low => narrow to upper bins
                lo = mid + 1
            else:
                # mid is too high, or is a NaN => narrow to lower bins
                hi = mid
    else:
        if np.isnan(x):
            # NaNs end up in the last bin
            return n
        while hi > lo:
            mid = (lo + hi) >> 1
            if bins[mid] <= x:
                # mid is too low => narrow to upper bins
                lo = mid + 1
            else:
                # mid is too high, or is a NaN => narrow to lower bins
                hi = mid

    return lo

#Variant_1
@nb.njit(fastmath=True,parallel=True)
def bincount_comb_1(pvel,pcoords,bins):
  vlos_binned=np.zeros(bins.shape[0]+1,dtype=np.uint64)
  for i in nb.prange(pvel.shape[0]):
    for j in range(pvel.shape[0]):
      if( (pcoords[i] - pcoords[j]) < 0.):
        vlos = 0.
      else:
        vlos = (pvel[i] - pvel[j])

      dig_vlos=digitize(vlos, bins, right=False)
      vlos_binned[dig_vlos]+=1
  return vlos_binned

#Variant_2
#Is this also working?
@nb.njit(fastmath=True,parallel=True)
def bincount_comb_2(pvel,pcoords,bins):
  vlos_binned=np.zeros(bins.shape[0]+1,dtype=np.uint64)
  for i in nb.prange(pvel.shape[0]):
    for j in range(pvel.shape[0]):
      #only particles which fulfill this condition are counted?
      if( (pcoords[i] - pcoords[j]) < 0.):
        vlos = (pvel[i] - pvel[j])
        dig_vlos=digitize(vlos, bins, right=False)
        vlos_binned[dig_vlos]+=1
  return vlos_binned

#Variant_3
#Only counting once
@nb.njit(fastmath=True,parallel=True)
def bincount_comb_3(pvel,pcoords,bins):
  vlos_binned=np.zeros(bins.shape[0]+1,dtype=np.uint64)
  for i in nb.prange(pvel.shape[0]):
    for j in range(i,pvel.shape[0]):
      #only particles, where this condition is met are counted?
      if( (pcoords[i] - pcoords[j]) < 0.):
        vlos = (pvel[i] - pvel[j])
        dig_vlos=digitize(vlos, bins, right=False)
        vlos_binned[dig_vlos]+=1
  return vlos_binned

#Create some data to test
bins=np.arange(2,32)
pvel=np.random.rand(10_000)*35
pcoords=np.random.rand(10_000)*35

#first call has compilation overhead, we don't measure this
res_1=bincount_comb_1(pvel,pcoords,bins)
res_2=bincount_comb_2(pvel,pcoords,bins)

t1=time.time()
res=bincount_comb_1(pvel,pcoords,bins)
print(time.time()-t1)
t1=time.time()
res=bincount_comb_2(pvel,pcoords,bins)
print(time.time()-t1)
t1=time.time()
res=bincount_comb_3(pvel,pcoords,bins)
print(time.time()-t1)

Performance
#Variant_1: 0.5s 5.78d for 1e6 groups of points
#Variant_2: 0.3s 3.25d for 1e6 groups of points
#Variant_3: 0.22s 2.54d for 1e6 groups of points


Q: Matlab, finding common values in two array I want to find common values in two arrays(For example if A=[1 2 3 4 5 6] and B=[9 8 7 6 3 1 2] the result is ans=[1 2 3 6]).Is there any method without using loop?
Thanks

A: use intersect(A,B) to get the answer.
Another option is to use ismember, for example A(ismember(A,B)).


Q: Проверка комментариев в админке Django Возникла задача: реализовать проверку комментариев пользователя в админке.
У меня есть идея сделать следующим образом: добавить в таблицу поле булевского типа, а в админке отображать как две таблицы (с комментариями, которые уже проверены и добавлены на сайт (таблица 1), и с комментариями, которые еще не проверили и на сайте их еще нет (таблица 2)).
Но я не знаю, можно ли так делать. Если можно - подскажите как это реализовать. Или какой-либо другой способ, который знаете.

A: Вам нужен ModelAdmin.list_filter.


Q: Possible to save and list queries in MySQL? I have a database and have saved the code on a separate document for a number of queries - is there anyway of saving them as part of the database as some kind of list so that they can be clicked on to run them rather than keeping on having to paste the code in?
I realise that there are various Reports systems available to purchase on line, but this is a small database and a one-off, and they look complicated and not worth the trouble.
Is there anyway of streamlining this?

A: If I understand correctly you can write those sql queries to a script-or bunch of script files- file and directly run on mysql without copy/paste.
 mysql -u user -ppass < script.sql


Q: Generating repeated iterations of data across two data frames in R I'm trying to calculate distance between two sets of phonetic variables in R using an established matrix of phonetic measurements. For example, I want to take the measurements for /p/ and the measurements for /b/, and then compare the distance between these two phonetic units. I can do this using the following matrix of distinctive phonetic features:
 library(tibble)
 distinctive.feature.matrix <- tribble(~Symbol, ~Sonorant, ~Consonantal, ~Voice, ~Nasal,
 ~Degree, ~Labial, ~Palatal, ~Pharyngeal, ~Round, ~Tongue, ~Radical,
                                       "p", -1, 1, -1, -1, 1, 1, 0, -1, 1, 0, 0,
                                       "b", -1, 1, 0, -1, 1, 1, 0, -1, 1, 0, 0,
                                       "t", -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 0,
                                       "d", -1, 1, 0, -1, 1, -1, 1, -1, -1, 1, 0,
                                       "k", -1, 1, -1, -1, 1, -1, -1, -1, -1, -1, 0,
                                       "g", -1, 1, 0, -1, 1, -1, -1, -1, -1, -1, 0,
                                       "f", -0.5, 1, -1, -1, 0, -1, 1, -1, 1, 0, 0,
                                       "v", -0.5, 1, 0, -1, 0, -1, 1, -1, 1, 0, 0,
                                       "θ", -0.5, 1, -1, -1, 0, -1, 1, -1, -1, 0, 0,
                                       "ð", -0.5, 1, 0, -1, 0, -1, 1, -1, -1, 0, 0,
                                       "s", -0.5, 1, -1, -1, 0, -1, 1, -1, -1, 1, 0,
                                       "z", -0.5, 1, 0, -1, 0, -1, 1, -1, -1, 1, 0,
                                       "h", -0.5, 1, 0, -1, 0, -1, -1, 1, -1, -1, -1,
                                       "ʃ", -0.5, 1, -1, -1, 0, -1, 0, -1, -1, 0, 0,
                                       "ʒ", -0.5, 1, 0, -1, 0, -1, 0, -1, -1, 0, 0,
                                       "tʃ", -0.8, 1, -1, -1, 1, -1, 0, -1, -1, 0, 0,
                                       "dʒ", -0.8, 1, 0, -1, 1, -1, 0, -1, -1, 0, 0,
                                       "m", 0, 0, 1, 1, 1, 1, 0, -1, 1, 0, 0,
                                       "n", 0, 0, 1, 1, 1, -1, 1, -1, -1, 1, 0,
                                       "ŋ", 0, 0, 1, 1, 1, -1, -1, -1, -1, -1, 0,
                                       "r", 0.5, 0, 1, 0, -1, -1, -1, 1, 1, -1, -1,
                                       "l", 0.5, 0, 1, 0, -1, -1, 1, -1, -1, 1, 0,
                                       "w", 0.8, 0, 1, 0, 0, 1, -1, -1, 1, -1, 0,
                                       "j", 0.8, 0, 1, 0, 0, -1, 0, -1, -1, 0, 1)

I have another set of data showing child productions of different words, and I want to calculate the distance between the child's production and that of the target, for each consonant in the target word.
The production data looks a bit like this:
 library(tibble)
 production.data <- tribble(~Subject, ~Age, ~Target, ~C1_target, ~C1_actual,
      "subj1", "001126", "teddy", "t", "d",
      "subj1", "001126", "teddy", "t", "t",
      "subj1", "001126", "daddy", "d", "d",
      "subj1", "001126", "daddy", "d", "d",
      "subj1", "001126", "daddy", "d", "t",
      "subj1", "001126", "baby", "b", "p",
      "subj1", "001126", "Tigger", "t", "d",
      "subj1", "001126", "doggy", "d", "d",
      "subj1", "001126", "milk", "m", "m")

So, for each instance of production.data$C1_target I want to take the values of the corresponding consonant in distinctive.feature.matrix and compare them with the values of productiondata$C1_actual. Once I have these values, I will subtract the C1_actual value from the C1_target value, across each of the 11 distinctive features.
By way of example, for the first instance of 'teddy', I want to compare /t/ with /d/, which means subtracting -1 from -1 (distinctive.feature.matrix$Sonorant), 1 from 1 (distinctive.feature.matrix$Consonantal), 0 from -1 (distinctive.feature.matrix$Voice), etc. I'll then do some further calculations on these, but I'll leave it as this for now as it's already quite complicated.
I think I can use for loops to do this but I haven't used this function before and no amount of searching brings up a usable example.

A: The dplyr package provides join functions that can help.
For every row of the production.data, you can bring in the corresponding features for each C1_target, C1_actual to create a large tibble:
library(dplyr)
x <- production.data %>%
     inner_join(distinctive.feature.matrix, by = c("C1_target"="Symbol")) %>%
     inner_join(distinctive.feature.matrix, by = c("C1_actual"="Symbol"))

Note that there are two calls to inner_join: one to get features corresponding to C1_target, the second for features for C1_actual
The new tibble has column names such as Sonorant.x and Sonorant.y, the first corresponding to C1_target and the second corresponding to C1_actual.
You can create a list of feature names by taking the column names, excluding Symbol:
features <- colnames(distinctive.feature.matrix)[-1]

Now you can do your 'for-loop' to calculate the difference between the x and y values, and then combine the lot into a new data frame:
diffs <- do.call(cbind, sapply(features, function(f) x[paste0(f, '.x')] - x[paste0(f, '.y')]))
colnames(diffs) <- features

The paste0 function concatenates each feature name with .x or .y; the sapply is the equivalent of the for-loop; and the cbind bashes the result of each computation into a new table.
You will end up with a data frame whose column names are the features, and as many rows as your production.data had.
To be fair, the above code is an ugly confection of dplyr-like syntax and base R...


Q: System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code Index was out of range Getting:

"An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code
      Index was out of range. Must be non-negative and less than the size of the collection."

in
if (resD.Tables.Contains(ReDo.TableName))
{
    _result = resD.Tables[ReDo.TableName];
}

When I try to execute this code repeatedly, I am getting above exception, though, resD.Table contains the table name specified in condition. Any help much appreciated.


Q: Live Apache Log Viewer? Is there any type of program or installable web interface that can display apache access and error logs live. I know there are a few interfaces that use the modstatus module, but I guess I am asking which is the best. I am running a WAMP (Apache 2.2.17, PHP 5.3.5, MySQL) server on Windows 7 64bit

A: I setup a local instance of this script on a dev server for quick access to the log file.  I can't comment on how robust it is in general, but for me using it to quickly diagnose an error it hasn't given me any problems.


Q: Android SDK problem setting ringtone I am trying to add and set the default ringtone on the emulator/phone. The ringtone has been downloaded and is stored in the application folder /dada/dada/com.xxx/ringtones. the ringtones are ogg files.
I use the following code to add and set the ringtone:
public void setRingtone() {
    aajoAsset asset = null;
    asset = mXXXX.getAssetManager().getCurrentRingtoneAsset();

    if (asset != null && asset.isSaved()/* && !asset.getName().equals(mLastAssetName)*/) {
        String filepath = asset.getDirectoryPath() + asset.getFilename();
        File ringtoneFile = new File(filepath);

        if (LOG) {
            Log.i(TAG, "Sending Intent : " + Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        }

        mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + asset.getDirectoryPath() + asset.getFilename())));

        ContentValues content = new ContentValues();
        content.put(MediaStore.MediaColumns.DATA,ringtoneFile.getAbsolutePath());
        content.put(MediaStore.MediaColumns.TITLE, "1234");
        content.put(MediaStore.MediaColumns.SIZE, asset.getSize());
        content.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
        content.put(MediaStore.Audio.Media.ARTIST, "1234");
        content.put(MediaStore.Audio.Media.DURATION, 4800);
        content.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        content.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
        content.put(MediaStore.Audio.Media.IS_ALARM, false);
        content.put(MediaStore.Audio.Media.IS_MUSIC, false);

        if (LOG) {
            Log.i(TAG, "the absolute path of the file is : " + ringtoneFile.getAbsolutePath());
        }

        Uri uri = MediaStore.Audio.Media.getContentUriForPath(
        ringtoneFile.getAbsolutePath());
        Uri newUri = mContext.getContentResolver().insert(uri, content);

        if (LOG) {
            Log.i(TAG,"the ringtone uri is : " + newUri);
        }

        RingtoneManager.setActualDefaultRingtoneUri(mContext, RingtoneManager.TYPE_RINGTONE, newUri);

        mLastAssetName = asset.getName();
    }

The code executes fine and the ringtone shows in the ringtone list but when I click on it to test it or when I simulate a incoming call I get the following errors in LogCat:
DEBUG/MediaPlayer(1230): Couldn't open file on client side, trying server side
ERROR/MediaPlayerService(33): Couldn't open fd for content://media/internal/audio/media/1
ERROR/MediaPlayer(1230): Unable to to create media player
ERROR/RingtoneManager(1230): Failed to open ringtone content://media/internal/audio/media/1

I have searched for solutions in many forums and cannot find any.
any help is most welcome
Thanks


Q: How to turn column of number into a list of strings? I don't know why I cant figure this out. But I have a column of numbers that I would like to turn into a list of strings. I should of mention this when i initially posted this but this isn't a DataFrame or did it come from a file this is a result of a some code, sorry wasn't trying to waste anybody's time, I just didn't want to add a bunch of clutter. This is exactly how it prints out.
Here is my column of numbers.
3,1,3
3,1,3
3,1,3
3,3,3
3,1,1

And I would like them to look like this.
['3,1,3', '3,1,3', '3,1,3', '3,3,3', '3,1,1']

I'm trying to find a way that is not dependent on how many numbers are in each row or how many sets of numbers are in the column.
Thanks, really appreciate it.

A: Assume you start with a DataFrame
df = pd.DataFrame([[3, 1, 3], [3, 1, 3], [3, 1, 3], [3, 3, 3], [3, 1, 1]])

df.astype(str).apply(lambda x: ','.join(x.values), axis=1).values.tolist()

Looks like:
['3,1,3', '3,1,3', '3,1,3', '3,3,3', '3,1,1']

A: def foo():
    l = []
    with open("file.asd", "r") as f:
        for line in f:
            l.append(line)
    return l

A: To turn your dataframe in to strings, use the astype function:
df = pd.DataFrame([[3, 1, 3], [3, 1, 3], [3, 1, 3], [3, 3, 3], [3, 1, 1]])
df = df.astype('str')

Then manipulating your columns becomes easy, you can for instance create a new column:
In [29]:

df['temp'] = df[0] + ',' + df[1] + ',' + df[2]
df
Out[29]:
0   1   2   temp
0   3   1   3   3,1,3
1   3   1   3   3,1,3
2   3   1   3   3,1,3
3   3   3   3   3,3,3
4   3   1   1   3,1,1

And then compact it into a list:
In [30]:

list(df['temp'])
Out[30]:
['3,1,3', '3,1,3', '3,1,3', '3,3,3', '3,1,1']

A: # Done in Jupyter notebook
# add three quotes on each side of your column.
# The advantage to dataframe is the minimal number of operations for
# reformatting your column of numbers or column of text strings into
# a single string

a = """3,1,3
3,1,3
3,1,3
3,3,3
3,1,1"""

b = f'"{a}"'
print('String created with triple quotes:')
print(b)

c = a.split('\n')
print ("Use split() function on the string. Split on newline character:")
print(c)

print ("Use splitlines() function on the string:")
print(a.splitlines())


Q: How to compare text strings in a table colum matlab If I have an N-by-1 table colum how is it possible to detect if any of the rows is identical?

A: If you simply want to determine if there are duplicate rows, you can use unique to do this. You can check the number of unique values in the column and compare this to the total number of elements (numel) in the same column
tf = unique(t.Column) == numel(t.Column)

If you want to determine which rows are duplicates, you can again use unique but use the third output and then use accumarray to count the number of occurrences of each value and then select those values which appear more than once.
[vals, ~, inds] = unique(t.Column, 'stable');
repeats = vals(accumarray(inds, 1) > 1);

% And to print them out:
fprintf('Duplicate value: %s\n', repeats{:})

If you want a logical vector of true/false for where the duplicates exist you can do something similar to that above
[vals, ~, inds] = unique(t.Column, 'stable');
result = ismember(inds, find(accumarray(inds, 1) > 1));

Or
[vals, ~, inds] = unique(t.Column, 'stable');
result = sum(bsxfun(@eq, inds, inds.'), 2) > 1;

Update
You can combine the two approaches above to accomplish what you want.
[vals, ~, inds] = unique(t.Column, 'stable');
repeats = vals(accumarray(inds, 1) > 1);

hasDupes = numel(repeats) > 0;

if hasDupes
    for k = 1:numel(repeats)
        fprintf('Duplicate value: %s\n', repeats{k});
        fprintf('   Found at: ');
        fprintf('%d ', find(strcmp(repeats{k}, t.Column)));
        fprintf('\n');
    end
end


Q: Find newest message from each sender? I've got a Messages menu in my app, and I'm completely at a loss on how to show the newest message received/sent from EACH user, without loading ALL messages received/sent.
I'm using Parse as my backend, so I've gotta believe there's some clever subquery, or NSPredicate that I could user for this.
The current solution I have in mind is another Boolean attribute for my messages, where all but the most recent get augmented, so I can known what to load with a simple predicate. This seems slopy though, save me from myself!
EDIT:
Right now I'm getting the messages where the user is the sender or receiver (depending on a segmented control), and then displaying each user who was sent to/received from with a sample of their newest message.
Right now I'm using internal logic to do this, and still in the process of figuring it out (the logic is a little backwards right now...)
let query = PFQuery(className: "Messages")

            if recievedOrSent {
            query.whereKey("other", equalTo: userName)
            print("called OTHER query")
        } else {
            query.whereKey("sender", equalTo: userName)
            print("called SENDER query")
        }

        query.addDescendingOrder("createdAt")
        query.findObjectsInBackgroundWithBlock {
            (objects, error) -> Void in

            if error == nil {

                    if thisSender == userName || self.recievedUsers.contains(thisSender) &&  self.lesserDate(thisTime, rhs: self.recievedUsersTimes[self.recievedUsers.indexOf(thisSender)!])
                    {} else {
                        self.recievedUsers.append(thisSender)
                        self.recievedUsersMsg.append(thisMessage)
                        self.recievedUsersTimes.append(thisTime)
                        self.recievedUsersMsgRead.append(thisRead)
                    }

                    if thisOther == userName || self.sentUsers.contains(thisOther) && self.lesserDate(thisTime, rhs: self.sentUsersTimes[self.sentUsers.indexOf(thisOther)!])
                    {} else {
                        self.sentUsers.append(thisOther)
                        self.sentUsersMsg.append(thisMessage)
                        self.sentUsersTimes.append(thisTime)
                        self.sentUsersMsgRead.append(thisRead)
                }
    }

A: If you want to get only the most recent message from each user that you are having a conversation with, create a new class called RecentMessage and update it each time using an afterSave cloud function on the Message class.
In the afterSave hook, maintain a pointer in the RecentMessage class to the latest Message in the conversation for each user. Then all you have to do is query for all of the current user's RecentMessage objects and use includeKey on the Message pointer.
This let's you abstract away more logic from the client side and streamline your queries where performance really counts :)


Q: Get the alternate rows in SQL I have a table PERSON with a single column GENDER, and values in 6 rows is like:
GENDER

M
M
M
F
F
F

The output should be like
GENDER

M
F
M
F
M
F

What should be the SQL query to get such output? I believe ROWNUMBER() must be used.

A: SELECT GENDER, R = ROW_NUMBER() OVER (PARTITION BY GENDER ORDER BY GENDER)
FROM   PERSON
ORDER BY R, GENDER DESC


Q: Unity Photon PUN - unable to get IPunObservable call back to operate I am trying to understand the Photon Pun architecture. I cannot get the callback OnPhotonSerializeView() in 'IPunObservable' to be called.
What I have in my scene is

*

*a GameObject called DataHandler at the top of the hierachy

*DataHandler has a PhotonView and PhotonTransformView attached

*DataHandler also has a script attached called DataHandler

*The DataHandler script component has been dragged to the first observable in the PhotonView component (so it shows 'DataHandler (DataHandler)' as the observed component).

*The DataHandler script implements IPunObservable, and the one method in that is
 public class DataHandler : MonoBehaviourPunCallbacks, IPunObservable
 {
 ....

     public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
     {
         Debug.Log("OnPhotonSerializeView(): " + (stream.IsWriting ? "writing" : "reading"));
     }
 ....
 }

Nothing shows up in the log when it is run.
However when built and run as a Windows EXE, connected with a room in place, it comes up with NullReferenceExceptions. The log shows:
    NullReferenceException: Object reference not set to an instance of an object
      at Photon.Pun.PhotonView.SerializeComponent (UnityEngine.Component component, Photon.Pun.PhotonStream stream, Photon.Pun.PhotonMessageInfo info) [0x0001e] in C:\Users\nick\Documents\Unity3D\PhotonPunTest\Assets\Photon\PhotonUnityNetworking\Code\PhotonView.cs:368
      at Photon.Pun.PhotonView.SerializeView (Photon.Pun.PhotonStream stream, Photon.Pun.PhotonMessageInfo info) [0x00024] in C:\Users\nick\Documents\Unity3D\PhotonPunTest\Assets\Photon\PhotonUnityNetworking\Code\PhotonView.cs:330
      at Photon.Pun.PhotonNetwork.OnSerializeWrite (Photon.Pun.PhotonView view) [0x00089] in C:\Users\nick\Documents\Unity3D\PhotonPunTest\Assets\Photon\PhotonUnityNetworking\Code\PhotonNetworkPart.cs:1593
      at Photon.Pun.PhotonNetwork.RunViewUpdate () [0x000b3] in C:\Users\nick\Documents\Unity3D\PhotonPunTest\Assets\Photon\PhotonUnityNetworking\Code\PhotonNetworkPart.cs:1522
      at Photon.Pun.PhotonHandler.LateUpdate () [0x00042] in C:\Users\nick\Documents\Unity3D\PhotonPunTest\Assets\Photon\PhotonUnityNetworking\Code\PhotonHandler.cs:155

    (Filename: C:/Users/nick/Documents/Unity3D/PhotonPunTest/Assets/Photon/PhotonUnityNetworking/Code/PhotonView.cs Line: 368)

and the code around line 368 in PhotonView.cs is
    protected internal void SerializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info)
    {
        IPunObservable observable = component as IPunObservable;
        if (observable != null)
        {
            observable.OnPhotonSerializeView(stream, info);
        }
        else
        {
            Debug.LogError("Observed scripts have to implement IPunObservable. "+ component + " does not. It is Type: " + component.GetType(), component.gameObject);
        }
    }

(The Debug.LogError line is 368).
Don't see what is wrong, though I assume component is probably null. The script is implementing IPunObservable. Can anyone help?

A: The problem here is the photon logic about local player and master client. The rules about who can send are bound up in this.
In the end I found it much easier to go below the higher level 'helper' components (PhotonView etc) and send everything with the lowever level RaiseEvent() / OnEvent() mechanism.
See answer to previous question.