Programs & Examples On #Pega

Pega or PegaRULES Process Commander (PRPC) is a BPMS developed by PegaSystems

Java Multiple Inheritance

I think it depends very much on your needs, and how your animal classes are to be used in your code.

If you want to be able to make use of methods and features of your Horse and Bird implementations inside your Pegasus class, then you could implement Pegasus as a composition of a Bird and a Horse:

public class Animals {

    public interface Animal{
        public int getNumberOfLegs();
        public boolean canFly();
        public boolean canBeRidden();
    }

    public interface Bird extends Animal{
        public void doSomeBirdThing();
    }
    public interface Horse extends Animal{
        public void doSomeHorseThing();
    }
    public interface Pegasus extends Bird,Horse{

    }

    public abstract class AnimalImpl implements Animal{
        private final int numberOfLegs;

        public AnimalImpl(int numberOfLegs) {
            super();
            this.numberOfLegs = numberOfLegs;
        }

        @Override
        public int getNumberOfLegs() {
            return numberOfLegs;
        }
    }

    public class BirdImpl extends AnimalImpl implements Bird{

        public BirdImpl() {
            super(2);
        }

        @Override
        public boolean canFly() {
            return true;
        }

        @Override
        public boolean canBeRidden() {
            return false;
        }

        @Override
        public void doSomeBirdThing() {
            System.out.println("doing some bird thing...");
        }

    }

    public class HorseImpl extends AnimalImpl implements Horse{

        public HorseImpl() {
            super(4);
        }

        @Override
        public boolean canFly() {
            return false;
        }

        @Override
        public boolean canBeRidden() {
            return true;
        }

        @Override
        public void doSomeHorseThing() {
            System.out.println("doing some horse thing...");
        }

    }

    public class PegasusImpl implements Pegasus{

        private final Horse horse = new HorseImpl();
        private final Bird bird = new BirdImpl();


        @Override
        public void doSomeBirdThing() {
            bird.doSomeBirdThing();
        }

        @Override
        public int getNumberOfLegs() {
            return horse.getNumberOfLegs();
        }

        @Override
        public void doSomeHorseThing() {
            horse.doSomeHorseThing();
        }


        @Override
        public boolean canFly() {
            return true;
        }

        @Override
        public boolean canBeRidden() {
            return true;
        }
    }
}

Another possibility is to use an Entity-Component-System approach instead of inheritance for defining your animals. Of course this means, that you will not have individual Java classes of the animals, but instead they are only defined by their components.

Some pseudo code for an Entity-Component-System approach could look like this:

public void createHorse(Entity entity){
    entity.setComponent(NUMER_OF_LEGS, 4);
    entity.setComponent(CAN_FLY, false);
    entity.setComponent(CAN_BE_RIDDEN, true);
    entity.setComponent(SOME_HORSE_FUNCTIONALITY, new HorseFunction());
}

public void createBird(Entity entity){
    entity.setComponent(NUMER_OF_LEGS, 2);
    entity.setComponent(CAN_FLY, true);
    entity.setComponent(CAN_BE_RIDDEN, false);
    entity.setComponent(SOME_BIRD_FUNCTIONALITY, new BirdFunction());
}

public void createPegasus(Entity entity){
    createHorse(entity);
    createBird(entity);
    entity.setComponent(CAN_BE_RIDDEN, true);
}

Python base64 data decode

Python 3 (and 2)

import base64
a = 'eW91ciB0ZXh0'
base64.b64decode(a)

Python 2

A quick way to decode it without importing anything:

'eW91ciB0ZXh0'.decode('base64')

or more descriptive

>>> a = 'eW91ciB0ZXh0'
>>> a.decode('base64')
'your text'

Convert audio files to mp3 using ffmpeg

I had to purge my ffmpeg and then install another one from a ppa:

sudo apt-get purge ffmpeg
sudo apt-add-repository -y ppa:jon-severinsson/ffmpeg 
sudo apt-get update 
sudo apt-get install ffmpeg

Then convert:

 ffmpeg -i audio.ogg -f mp3 newfile.mp3

Search text in fields in every table of a MySQL database

I modified the PHP answer of Olivier a bit to:

  • print out the results in which the string was found
  • omit tables without results
  • also show output if column names match the search input
  • show total number of results

    function searchAllDB($search){
        global $mysqli;
    
        $out = "";
        $total = 0;
        $sql = "SHOW TABLES";
        $rs = $mysqli->query($sql);
        if($rs->num_rows > 0){
            while($r = $rs->fetch_array()){
                $table = $r[0];
                $sql_search = "select * from ".$table." where ";
                $sql_search_fields = Array();
                $sql2 = "SHOW COLUMNS FROM ".$table;
                $rs2 = $mysqli->query($sql2);
                if($rs2->num_rows > 0){
                    while($r2 = $rs2->fetch_array()){
                        $colum = $r2[0];
                        $sql_search_fields[] = $colum." like('%".$search."%')";
                        if(strpos($colum,$search))
                        {
                            echo "FIELD NAME: ".$colum."\n";
                        }
                    }
                    $rs2->close();
                }
                $sql_search .= implode(" OR ", $sql_search_fields);
                $rs3 = $mysqli->query($sql_search);
                if($rs3 && $rs3->num_rows > 0)
                {
                    $out .= $table.": ".$rs3->num_rows."\n";
                    if($rs3->num_rows > 0){
                        $total += $rs3->num_rows;
                        $out.= print_r($rs3->fetch_all(),1);
                        $rs3->close();
                    }
                }
            }
            $out .= "\n\nTotal results:".$total;
            $rs->close();
        }
        return $out;
    }
    

How to select unique records by SQL

If you only need to remove duplicates then use DISTINCT. GROUP BY should be used to apply aggregate operators to each group

GROUP BY v DISTINCT

What is the "realm" in basic authentication

From RFC 1945 (HTTP/1.0) and RFC 2617 (HTTP Authentication referenced by HTTP/1.1)

The realm attribute (case-insensitive) is required for all authentication schemes which issue a challenge. The realm value (case-sensitive), in combination with the canonical root URL of the server being accessed, defines the protection space. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme.

In short, pages in the same realm should share credentials. If your credentials work for a page with the realm "My Realm", it should be assumed that the same username and password combination should work for another page with the same realm.

Using isKindOfClass with Swift

Another approach using the new Swift 2 syntax is to use guard and nest it all in one conditional.

guard let touch = object.AnyObject() as? UITouch, let picker = touch.view as? UIPickerView else {
    return //Do Nothing
}
//Do something with picker

Is it possible to make a Tree View with Angular?

Yes it definitely possible. The question here probably assumes Angular 1.x, but for future reference I am including an Angular 2 example:

Conceptually all you have to do is create a recursive template:

<ul>
    <li *for="#dir of directories">

        <span><input type="checkbox" [checked]="dir.checked" (click)="dir.check()"    /></span> 
        <span (click)="dir.toggle()">{{ dir.name }}</span>

        <div *if="dir.expanded">
            <ul *for="#file of dir.files">
                {{file}}
            </ul>
            <tree-view [directories]="dir.directories"></tree-view>
        </div>
    </li>
</ul>

You then bind a tree object to the template and let Angular work its magic. This concept is obviously applicable to Angular 1.x as well.

Here is a complete example: http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0

What is fastest children() or find() in jQuery?

None of the other answers dealt with the case of using .children() or .find(">") to only search for immediate children of a parent element. So, I created a jsPerf test to find out, using three different ways to distinguish children.

As it happens, even when using the extra ">" selector, .find() is still a lot faster than .children(); on my system, 10x so.

So, from my perspective, there does not appear to be much reason to use the filtering mechanism of .children() at all.

How do you launch the JavaScript debugger in Google Chrome?

From the console in Chrome, you can do console.log(data_to_be_displayed).

There can be only one auto column

The full error message sounds:

ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key

So add primary key to the auto_increment field:

CREATE TABLE book (
   id INT AUTO_INCREMENT primary key NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

How to register ASP.NET 2.0 to web server(IIS7)?

Open Control Panel - Programs - Turn Windows Features on or off expand - Internet Information Services expand - World Wide Web Services expand - Application development Features check - ASP.Net

Its advisable you check other feature to avoid future problem that might not give direct error messages Please don't forget to mark this question as answered if it solves your problem for the purpose of others

Using gradle to find dependency tree

In Android Studio (at least since v2.3.3) you can run the command directly from the UI:

Click on the Gradle tab and then double click on :yourmodule -> Tasks -> android -> androidDependencies

The tree will be displayed in the Gradle Console tab

An image is worth a thousand words

Error "can't load package: package my_prog: found packages my_prog and main"

Yes, each package must be defined in its own directory.

The source structure is defined in How to Write Go Code.

A package is a component that you can use in more than one program, that you can publish, import, get from an URL, etc. So it makes sense for it to have its own directory as much as a program can have a directory.

JavaScript file upload size validation

You can try this fineuploader

It works fine under IE6(and above), Chrome or Firefox

Handling JSON Post Request in Go

There are two reasons why json.Decoder should be preferred over json.Unmarshal - that are not addressed in the most popular answer from 2013:

  1. February 2018, go 1.10 introduced a new method json.Decoder.DisallowUnknownFields() which addresses the concern of detecting unwanted JSON-input
  2. req.Body is already an io.Reader. Reading its entire contents and then performing json.Unmarshal wastes resources if the stream was, say a 10MB block of invalid JSON. Parsing the request body, with json.Decoder, as it streams in would trigger an early parse error if invalid JSON was encountered. Processing I/O streams in realtime is the preferred go-way.

Addressing some of the user comments about detecting bad user input:

To enforce mandatory fields, and other sanitation checks, try:

d := json.NewDecoder(req.Body)
d.DisallowUnknownFields() // catch unwanted fields

// anonymous struct type: handy for one-time use
t := struct {
    Test *string `json:"test"` // pointer so we can test for field absence
}{}

err := d.Decode(&t)
if err != nil {
    // bad JSON or unrecognized json field
    http.Error(rw, err.Error(), http.StatusBadRequest)
    return
}

if t.Test == nil {
    http.Error(rw, "missing field 'test' from JSON object", http.StatusBadRequest)
    return
}

// optional extra check
if d.More() {
    http.Error(rw, "extraneous data after JSON object", http.StatusBadRequest)
    return
}

// got the input we expected: no more, no less
log.Println(*t.Test)

Playground

Typical output:

$ curl -X POST -d "{}" http://localhost:8082/strict_test

expected json field 'test'

$ curl -X POST -d "{\"Test\":\"maybe?\",\"Unwanted\":\"1\"}" http://localhost:8082/strict_test

json: unknown field "Unwanted"

$ curl -X POST -d "{\"Test\":\"oops\"}g4rB4g3@#$%^&*" http://localhost:8082/strict_test

extraneous data after JSON

$ curl -X POST -d "{\"Test\":\"Works\"}" http://localhost:8082/strict_test 

log: 2019/03/07 16:03:13 Works

CSS selector based on element text?

It was probably discussed, but as of CSS3 there is nothing like what you need (see also "Is there a CSS selector for elements containing certain text?"). You will have to use additional markup, like this:

<li><span class="foo">some text</span></li>
<li>some other text</li>

Then refer to it the usual way:

li > span.foo {...}

How to search and replace text in a file?

Besides the answers already mentioned, here is an explanation of why you have some random characters at the end:
You are opening the file in r+ mode, not w mode. The key difference is that w mode clears the contents of the file as soon as you open it, whereas r+ doesn't.
This means that if your file content is "123456789" and you write "www" to it, you get "www456789". It overwrites the characters with the new input, but leaves any remaining input untouched.
You can clear a section of the file contents by using truncate(<startPosition>), but you are probably best off saving the updated file content to a string first, then doing truncate(0) and writing it all at once.
Or you can use my library :D

How to create localhost database using mysql?

removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.

How to download/upload files from/to SharePoint 2013 using CSOM?

A little late this comment but I will leave here my results working with the library of SharePoin Online and it is very easy to use and implement in your project, just go to the NuGet administrator of .Net and Add Microsoft.SharePoint.CSOM to your project .

https://developer.microsoft.com/en-us/office/blogs/new-sharepoint-csom-version-released-for-office-365-may-2017/

The following code snippet will help you connect your credentials to your SharePoint site, you can also read and download files from a specific site and folder.

using System;
using System.IO;
using System.Linq;
using System.Web;
using Microsoft.SharePoint.Client;
using System.Security;

using ClientOM = Microsoft.SharePoint.Client;

namespace MvcApplication.Models.Home
{
    public class SharepointModel
    {
        public ClientContext clientContext { get; set; }
        private string ServerSiteUrl = "https://somecompany.sharepoint.com/sites/ITVillahermosa";
        private string LibraryUrl = "Shared Documents/Invoices/";
        private string UserName = "[email protected]";
        private string Password = "********";
        private Web WebClient { get; set; }

        public SharepointModel()
        {
            this.Connect();
        }

        public void Connect()
        {
            try
            {
                using (clientContext = new ClientContext(ServerSiteUrl))
                {
                    var securePassword = new SecureString();
                    foreach (char c in Password)
                    {
                        securePassword.AppendChar(c);
                    }

                    clientContext.Credentials = new SharePointOnlineCredentials(UserName, securePassword);
                    WebClient = clientContext.Web;
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public string UploadMultiFiles(HttpRequestBase Request, HttpServerUtilityBase Server)
        {
            try
            {
                HttpPostedFileBase file = null;
                for (int f = 0; f < Request.Files.Count; f++)
                {
                    file = Request.Files[f] as HttpPostedFileBase;

                    string[] SubFolders = LibraryUrl.Split('/');
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/uploads"), filename);
                    file.SaveAs(path);

                    clientContext.Load(WebClient, website => website.Lists, website => website.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    //https://somecompany.sharepoint.com/sites/ITVillahermosa/Shared Documents/
                    List documentsList = clientContext.Web.Lists.GetByTitle("Documents"); //Shared Documents -> Documents
                    clientContext.Load(documentsList, i => i.RootFolder.Folders, i => i.RootFolder);
                    clientContext.ExecuteQuery();

                    string SubFolderName = SubFolders[1];//Get SubFolder 'Invoice'
                    var folderToBindTo = documentsList.RootFolder.Folders;
                    var folderToUpload = folderToBindTo.Where(i => i.Name == SubFolderName).First();

                    var fileCreationInformation = new FileCreationInformation();
                    //Assign to content byte[] i.e. documentStream
                    fileCreationInformation.Content = System.IO.File.ReadAllBytes(path);
                    //Allow owerwrite of document
                    fileCreationInformation.Overwrite = true;
                    //Upload URL
                    fileCreationInformation.Url = ServerSiteUrl + LibraryUrl + filename;

                    Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);

                    //Update the metadata for a field having name "DocType"
                    uploadFile.ListItemAllFields["Title"] = "UploadedCSOM";

                    uploadFile.ListItemAllFields.Update();
                    clientContext.ExecuteQuery();
                }

                return "";
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public string DownloadFiles()
        {
            try
            {
                string tempLocation = @"c:\Downloads\Sharepoint\";
                System.IO.DirectoryInfo di = new DirectoryInfo(tempLocation);
                foreach (FileInfo file in di.GetFiles())
                {
                    file.Delete();
                }

                FileCollection files = WebClient.GetFolderByServerRelativeUrl(this.LibraryUrl).Files;
                clientContext.Load(files);
                clientContext.ExecuteQuery();

                if (clientContext.HasPendingRequest)
                    clientContext.ExecuteQuery();

                foreach (ClientOM.File file in files)
                {
                    FileInformation fileInfo = ClientOM.File.OpenBinaryDirect(clientContext, file.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    var filePath = tempLocation + file.Name;
                    using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
                    {
                        fileInfo.Stream.CopyTo(fileStream);
                    }
                }

                return "";
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

    }
}

Then to invoke the functions from the controller in this case MVC ASP.NET is done in the following way.


using MvcApplication.Models.Home;
using System;
using System.Web.Mvc;

namespace MvcApplication.Controllers
{
    public class SharepointController : MvcBoostraBaseController
    {
        [HttpPost]
        public ActionResult Upload(FormCollection form)
        {
            try
            {
                SharepointModel sharepointModel = new SharepointModel();
                return Json(sharepointModel.UploadMultiFiles(Request, Server), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return ThrowJSONError(ex);
            }
        }

        public ActionResult Download(string ServerUrl, string RelativeUrl)
        {
            try
            {
                SharepointModel sharepointModel = new SharepointModel();
                return Json(sharepointModel.DownloadFiles(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return ThrowJSONError(ex);
            }
        }
    }
}

If you need the source code of this project you can request it to [email protected]

How can I find where Python is installed on Windows?

This worked for me: C:\Users\Your_user_name\AppData\Local\Programs\Python

My currently installed python version is 3.7.0

Hope this helps!

disable past dates on datepicker

you have just introduce parameter startDate as mentioned below.

var todaydate = new Date();
    $(".leave-day").datepicker({
        autoclose: true,
        todayBtn: "linked",
        todayHighlight: true,
        startDate: todaydate     
      }
    ).on('changeDate', function (e) {
        var dateCalendar = e.format();
        dateCalendar = moment(dateCalendar, 'MM/DD/YYYY').format('YYYY-MM-DD');
        $("#date-leave").val(dateCalendar);
    });

C error: Expected expression before int

This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570

I guess the counter-intuitive part of the question is: if this is correct C:

if (a == 1) {
  int b = 10;
}

then why is this not also correct C?

if (a == 1)
  int b = 10;

I mean, a one-line conditional if statement should be fine either with or without braces, right?

The answer lies in the grammar of the if statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10 line is a declaration, not a statement, and the grammar for the if statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.

And just for the sake of answering the question completely -- this has nothing to do with scope. The b variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror anyways ;-)

(6.7) declaration:
            declaration-speci?ers init-declarator-listopt ;
            static_assert-declaration

(6.7) init-declarator-list:
            init-declarator
            init-declarator-list , init-declarator

(6.7) init-declarator:
            declarator
            declarator = initializer

(6.8) statement:
            labeled-statement
            compound-statement
            expression-statement
            selection-statement
            iteration-statement
            jump-statement

(6.8.2) compound-statement:
            { block-item-listopt }

(6.8.4) selection-statement:
            if ( expression ) statement
            if ( expression ) statement else statement
            switch ( expression ) statement

How can I dynamically switch web service addresses in .NET without a recompile?

For me a Reference to a WebService is a

SERVICE REFERENCE

.

Anyway it's very easy. As someone said, you just have to change the URL in the web.config file.

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="YourServiceSoap" />
      </basicHttpBinding>
    </bindings>
    <client>
        **** CHANGE THE LINE BELOW TO CHANGE THE URL **** 
        <endpoint address="http://10.10.10.100:8080/services/YourService.asmx"
          binding="basicHttpBinding" bindingConfiguration="YourServiceSoap"
          contract="YourServiceRef.YourServiceSoap" name="YourServiceSoap" />
    </client>

How to create a zip file in Java

Look at this example:

StringBuilder sb = new StringBuilder();
sb.append("Test String");

File f = new File("d:\\test.zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f));
ZipEntry e = new ZipEntry("mytext.txt");
out.putNextEntry(e);

byte[] data = sb.toString().getBytes();
out.write(data, 0, data.length);
out.closeEntry();

out.close();

This will create a zip in the root of D: named test.zip which will contain one single file called mytext.txt. Of course you can add more zip entries and also specify a subdirectory like this:

ZipEntry e = new ZipEntry("folderName/mytext.txt");

You can find more information about compression with Java here.

Access elements of parent window from iframe

I think the problem may be that you are not finding your element because of the "#" in your call to get it:

window.parent.document.getElementById('#target'); 

You only need the # if you are using jquery. Here it should be:

window.parent.document.getElementById('target'); 

How can I calculate the time between 2 Dates in typescript

It doesn't work because Date - Date relies on exactly the kind of type coercion TypeScript is designed to prevent.

There is a workaround this using the + prefix:

var t = Date.now() - +(new Date("2013-02-20T12:01:04.753Z");

Or, if you prefer not to use Date.now():

var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));

See discussion here.

Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()

JSON formatter in C#?

Here's a compact version of a JSON beautifier.

private const string INDENT_STRING = "    ";

static string FormatJson(string json) {

    int indentation = 0;
    int quoteCount = 0;
    var result = 
        from ch in json
        let quotes = ch == '"' ? quoteCount++ : quoteCount
        let lineBreak = ch == ',' && quotes % 2 == 0 ? ch + Environment.NewLine +  String.Concat(Enumerable.Repeat(INDENT_STRING, indentation)) : null
        let openChar = ch == '{' || ch == '[' ? ch + Environment.NewLine + String.Concat(Enumerable.Repeat(INDENT_STRING, ++indentation)) : ch.ToString()
        let closeChar = ch == '}' || ch == ']' ? Environment.NewLine + String.Concat(Enumerable.Repeat(INDENT_STRING, --indentation)) + ch : ch.ToString()
        select lineBreak == null    
                    ? openChar.Length > 1 
                        ? openChar 
                        : closeChar
                    : lineBreak;

    return String.Concat(result);
}

Outputs:

 {
    "status":"OK",
     "results":[
         {
            "types":[
                 "locality",
                 "political"
            ],
             "formatted_address":"New York, NY, USA",
             "address_components":[
                 {
                    "long_name":"New York",
                     "short_name":"New York",
                     "types":[
                         "locality",
                         "political"
                    ]
                },
                 {
                    "long_name":"New York",
                     "short_name":"New York",
                     "types":[
                         "administrative_area_level_2",
                         "political"
                    ]
                },
                 {
                    "long_name":"New York",
                     "short_name":"NY",
                     "types":[
                         "administrative_area_level_1",
                         "political"
                    ]
                },
                 {
                    "long_name":"United States",
                     "short_name":"US",
                     "types":[
                         "country",
                         "political"
                    ]
                }
            ],
             "geometry":{
                "location":{
                    "lat":40.7143528,
                     "lng":-74.0059731
                },
                 "location_type":"APPROXIMATE",
                 "viewport":{
                    "southwest":{
                        "lat":40.5788964,
                         "lng":-74.2620919
                    },
                     "northeast":{
                        "lat":40.8495342,
                         "lng":-73.7498543
                    }
                },
                 "bounds":{
                    "southwest":{
                        "lat":40.4773990,
                         "lng":-74.2590900
                    },
                     "northeast":{
                        "lat":40.9175770,
                         "lng":-73.7002720
                    }
                }
            }
        }
    ]
}

How to check that an element is in a std::set?

Just to clarify, the reason why there is no member like contains() in these container types is because it would open you up to writing inefficient code. Such a method would probably just do a this->find(key) != this->end() internally, but consider what you do when the key is indeed present; in most cases you'll then want to get the element and do something with it. This means you'd have to do a second find(), which is inefficient. It's better to use find directly, so you can cache your result, like so:

auto it = myContainer.find(key);
if (it != myContainer.end())
{
    // Do something with it, no more lookup needed.
}
else
{
    // Key was not present.
}

Of course, if you don't care about efficiency, you can always roll your own, but in that case you probably shouldn't be using C++... ;)

Convert an NSURL to an NSString

Swift update:

var myUrlStr : String = myUrl.absoluteString

data.frame Group By column

require(reshape2)

T <- melt(df, id = c("A"))

T <- dcast(T, A ~ variable, sum)

I am not certain the exact advantages over aggregate.

Check if pull needed in Git

This one-liner works for me in zsh (from @Stephen Haberman's answer)

git fetch; [ $(git rev-parse HEAD) = $(git rev-parse @{u}) ] \
    && echo "Up to date" || echo "Not up to date"

Byte Array in Python

In Python 3, we use the bytes object, also known as str in Python 2.

# Python 3
key = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])

# Python 2
key = ''.join(chr(x) for x in [0x13, 0x00, 0x00, 0x00, 0x08, 0x00])

I find it more convenient to use the base64 module...

# Python 3
key = base64.b16decode(b'130000000800')

# Python 2
key = base64.b16decode('130000000800')

You can also use literals...

# Python 3
key = b'\x13\0\0\0\x08\0'

# Python 2
key = '\x13\0\0\0\x08\0'

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

You should use Asset Catalog:

I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.

Note: No need to make any entry in info.plist file :) And no any other configuration.

In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.

enter image description here

Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon. enter image description here

If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution. enter image description here

After uploading all required dimensions, you shouldn't get any warning. enter image description here

How to 'insert if not exists' in MySQL?

Solution:

INSERT INTO `table` (`value1`, `value2`) 
SELECT 'stuff for value1', 'stuff for value2' FROM DUAL 
WHERE NOT EXISTS (SELECT * FROM `table` 
      WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1) 

Explanation:

The innermost query

SELECT * FROM `table` 
      WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1

used as the WHERE NOT EXISTS-condition detects if there already exists a row with the data to be inserted. After one row of this kind is found, the query may stop, hence the LIMIT 1 (micro-optimization, may be omitted).

The intermediate query

SELECT 'stuff for value1', 'stuff for value2' FROM DUAL

represents the values to be inserted. DUAL refers to a special one row, one column table present by default in all Oracle databases (see https://en.wikipedia.org/wiki/DUAL_table). On a MySQL-Server version 5.7.26 I got a valid query when omitting FROM DUAL, but older versions (like 5.5.60) seem to require the FROM information. By using WHERE NOT EXISTS the intermediate query returns an empty result set if the innermost query found matching data.

The outer query

INSERT INTO `table` (`value1`, `value2`) 

inserts the data, if any is returned by the intermediate query.

Webdriver Screenshot

Have a look on the below python script to take snap of FB homepage by using selenium package of Chrome web driver.

Script:

import selenium

from selenium import webdriver

import time

from time import sleep

chrome_browser = webdriver.Chrome()

chrome_browser.get('https://www.facebook.com/') # Enter to FB login page

sleep(5)

chrome_browser.save_screenshot('C:/Users/user/Desktop/demo.png') # To take FB homepage snap

chrome_browser.close() # To Close the driver connection

chrome_browser.quit() # To Close the browser

URL encode sees “&” (ampersand) as “&amp;” HTML entity

Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

If that isn't the case, you can use the replace() method to replace the HTML entity:

encodeURIComponent(str.replace(/&amp;/g, "&"));

SaveFileDialog setting default path and file type?

Environment.GetSystemVariable("%SystemDrive%"); will provide the drive OS installed, and you can set filters to savedialog Obtain file path of C# save dialog box

Difference between arguments and parameters in Java

They are not. They're exactly the same.

However, some people say that parameters are placeholders in method signatures:

public void doMethod(String s, int i) {
  ..
}

String s and int i are sometimes said to be parameters. The arguments are the actual values/references:

myClassReference.doMethod("someString", 25);

"someString" and 25 are sometimes said to be the arguments.

Output array to CSV in Ruby

To a file:

require 'csv'
CSV.open("myfile.csv", "w") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

To a string:

require 'csv'
csv_string = CSV.generate do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

Here's the current documentation on CSV: http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

How to center the content inside a linear layout?

android:gravity handles the alignment of its children,

android:layout_gravity handles the alignment of itself.

So use one of these.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000"
    android:baselineAligned="false"
    android:gravity="center"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Main" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center" >

        <ImageView
            android:id="@+id/imageButton_speak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_speak" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center" >

        <ImageView
            android:id="@+id/imageButton_readtext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_readtext" />
    </LinearLayout>

    ...
</LinearLayout>

or

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000"
    android:baselineAligned="false"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Main" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1" >

        <ImageView
            android:id="@+id/imageButton_speak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_speak" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1" >

        <ImageView
            android:id="@+id/imageButton_readtext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_readtext" />
    </LinearLayout>

    ...
</LinearLayout>

How to populate options of h:selectOneMenu from database?

Roll-your-own generic converter for complex objects as selected item

The Balusc gives a very useful overview answer on this subject. But there is one alternative he does not present: The Roll-your-own generic converter that handles complex objects as the selected item. This is very complex to do if you want to handle all cases, but pretty simple for simple cases.

The code below contains an example of such a converter. It works in the same spirit as the OmniFaces SelectItemsConverter as it looks through the children of a component for UISelectItem(s) containing objects. The difference is that it only handles bindings to either simple collections of entity objects, or to strings. It does not handle item groups, collections of SelectItems, arrays and probably a lot of other things.

The entities that the component binds to must implement the IdObject interface. (This could be solved in other way, such as using toString.)

Note that the entities must implement equals in such a way that two entities with the same ID compares equal.

The only thing that you need to do to use it is to specify it as converter on the select component, bind to an entity property and a list of possible entities:

<h:selectOneMenu value="#{bean.user}" converter="selectListConverter">
  <f:selectItem itemValue="unselected" itemLabel="Select user..."/>
  <f:selectItem itemValue="empty" itemLabel="No user"/>
  <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

Converter:

/**
 * A converter for select components (those that have select items as children).
 * 
 * It convertes the selected value string into one of its element entities, thus allowing
 * binding to complex objects.
 * 
 * It only handles simple uses of select components, in which the value is a simple list of
 * entities. No ItemGroups, arrays or other kinds of values.
 * 
 * Items it binds to can be strings or implementations of the {@link IdObject} interface.
 */
@FacesConverter("selectListConverter")
public class SelectListConverter implements Converter {

  public static interface IdObject {
    public String getDisplayId();
  }

  @Override
  public Object getAsObject(FacesContext context, UIComponent component, String value) {
    if (value == null || value.isEmpty()) {
      return null;
    }

    return component.getChildren().stream()
      .flatMap(child -> getEntriesOfItem(child))
      .filter(o -> value.equals(o instanceof IdObject ? ((IdObject) o).getDisplayId() : o))
      .findAny().orElse(null);
  }

  /**
   * Gets the values stored in a {@link UISelectItem} or a {@link UISelectItems}.
   * For other components returns an empty stream.
   */
  private Stream<?> getEntriesOfItem(UIComponent child) {
    if (child instanceof UISelectItem) {
      UISelectItem item = (UISelectItem) child;
      if (!item.isNoSelectionOption()) {
        return Stream.of(item.getValue());
      }

    } else if (child instanceof UISelectItems) {
      Object value = ((UISelectItems) child).getValue();

      if (value instanceof Collection) {
        return ((Collection<?>) value).stream();
      } else {
        throw new IllegalStateException("Unsupported value of UISelectItems: " + value);
      }
    }

    return Stream.empty();
  }

  @Override
  public String getAsString(FacesContext context, UIComponent component, Object value) {
    if (value == null) return null;
    if (value instanceof String) return (String) value;
    if (value instanceof IdObject) return ((IdObject) value).getDisplayId();

    throw new IllegalArgumentException("Unexpected value type");
  }

}

Unicode character as bullet for list-item in CSS

You can construct it:

#modal-select-your-position li {
/* handle multiline */
    overflow: visible;
    padding-left: 17px;
    position: relative;
}

#modal-select-your-position li:before {
/* your own marker in content */
   content: "—";
   left: 0;
   position: absolute;
}

How to insert a new line in Linux shell script?

Use this echo statement

 echo -e "Hai\nHello\nTesting\n"

The output is

Hai
Hello
Testing

UITableview: How to Disable Selection for Some Rows but Not Others

SIMPLE

Just use cell.userInteractionEnabled = YES; to the cell if it can navigate and cell.userInteractionEnabled = NO; otherwise

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

For Python set - signature_version s3v4

s3 = boto3.client(
   's3',
   aws_access_key_id='AKIAIO5FODNN7EXAMPLE',
   aws_secret_access_key='ABCDEF+c2L7yXeGvUyrPgYsDnWRRC1AYEXAMPLE',
   config=Config(signature_version='s3v4')
)

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

In addition to installing the repository and the SDK packages one should be aware that the version number changes periodically. A simple solution at this point is to replace the specific version number with a plus (+) symbol.

compile 'com.google.android.gms:play-services:+'

Google instructions indicate that one should be sure to upgrade the version numbers, however adding the plus deals with the changes in versioning. Also note that when building in Android Studio a message will appear in the status line when a new version is available.

One can view the available versions of play services by drilling down on the correct repository path:

play-services repository path

References

This site also has instructions for Eclipse, and other IDE's.

ADS-Setup

Should I use the Reply-To header when sending emails as a service to others?

After reading all of this, I might just embed a hyperlink in the email body like this:

To reply to this email, click here <a href="mailto:...">[email protected]</a>

How to use the PI constant in C++

I just came across this article by Danny Kalev which has a great tip for C++14 and up.

template<typename T>
constexpr T pi = T(3.1415926535897932385);

I thought this was pretty cool (though I would use the highest precision PI in there I could), especially because templates can use it based on type.

template<typename T>
T circular_area(T r) {
  return pi<T> * r * r;
}
double darea= circular_area(5.5);//uses pi<double>
float farea= circular_area(5.5f);//uses pi<float>

How to count string occurrence in string?

No one will ever see this, but it's good to bring back recursion and arrow functions once in a while (pun gloriously intended)

String.prototype.occurrencesOf = function(s, i) {
 return (n => (n === -1) ? 0 : 1 + this.occurrencesOf(s, n + 1))(this.indexOf(s, (i || 0)));
};

What's the difference between Unicode and UTF-8?

Let's start from keeping in mind that data is stored as bytes; Unicode is a character set where characters are mapped to code points (unique integers), and we need something to translate these code points data into bytes. That's where UTF-8 comes in so called encoding – simple!

Difference between System.DateTime.Now and System.DateTime.Today

Time. .Now includes the 09:23:12 or whatever; .Today is the date-part only (at 00:00:00 on that day).

So use .Now if you want to include the time, and .Today if you just want the date!

.Today is essentially the same as .Now.Date

Does height and width not apply to span?

Span is an inline element. It has no width or height.

You could turn it into a block-level element, then it will accept your dimension directives.

span.product__specfield_8_arrow
{
    display: inline-block; /* or block */
}

Removing numbers from string

And, just to throw it in the mix, is the oft-forgotten str.translate which will work a lot faster than looping/regular expressions:

For Python 2:

from string import digits

s = 'abc123def456ghi789zero0'
res = s.translate(None, digits)
# 'abcdefghizero'

For Python 3:

from string import digits

s = 'abc123def456ghi789zero0'
remove_digits = str.maketrans('', '', digits)
res = s.translate(remove_digits)
# 'abcdefghizero'

How can I let a table's body scroll but keep its head fixed in place?

If its ok to use JavaScript here is my solution Create a table set fixed width on all columns (pixels!) add the class Scrollify to the table and add this javascript + jquery 1.4.x set height in css or style!

Tested in: Opera, Chrome, Safari, FF, IE5.5(Epic script fail), IE6, IE7, IE8, IE9

//Usage add Scrollify class to a table where all columns (header and body) have a fixed pixel width
$(document).ready(function () {
    $("table.Scrollify").each(function (index, element) {
        var header = $(element).children().children().first();
        var headerHtml = header.html();
        var width = $(element).outerWidth();
        var height = parseInt($(element).css("height")) - header.outerHeight();
        $(element).height("auto");
        header.remove();
        var html = "<table style=\"border-collapse: collapse;\" border=\"1\" rules=\"all\" cellspacing=\"0\"><tr>" + headerHtml +
                         "</tr></table><div style=\"overflow: auto;border:0;margin:0;padding:0;height:" + height + "px;width:" + (parseInt(width) + scrollbarWidth()) + "px;\">" +
                         $(element).parent().html() + "</div>";

        $(element).parent().html(html);
    });
});


//Function source: http://www.fleegix.org/articles/2006-05-30-getting-the-scrollbar-width-in-pixels
//License: Apache License, version 2
function scrollbarWidth() {
    var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;

    // Outer scrolling div
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-1000px';
    scr.style.left = '-1000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    // Start with no scrollbar
    scr.style.overflow = 'hidden';

    // Inner content div
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';

    // Put the inner div in the scrolling div
    scr.appendChild(inn);
    // Append the scrolling div to the doc
    document.body.appendChild(scr);

    // Width of the inner div sans scrollbar
    wNoScroll = inn.offsetWidth;
    // Add the scrollbar
    scr.style.overflow = 'auto';
    // Width of the inner div width scrollbar
    wScroll = inn.offsetWidth;

    // Remove the scrolling div from the doc
    document.body.removeChild(
        document.body.lastChild);

    // Pixel width of the scroller
    return (wNoScroll - wScroll);
}

Edit: Fixed height.

"int cannot be dereferenced" in Java

Change

id.equals(list[pos].getItemNumber())

to

id == list[pos].getItemNumber()

For more details, you should learn the difference between the primitive types like int, char, and double and reference types.

Playing a video in VideoView in Android

Add android.permission.READ_EXTERNAL_STORAGE in manifest, worked for me

Getting the base url of the website and globally passing it to twig in Symfony 2

 <base href="{{ app.request.getSchemeAndHttpHost() }}"/>

or from controller

$this->container->get('router')->getContext()->getSchemeAndHttpHost()

PHP CSV string to array

Slightly shorter version, without unnecessary second variable:

$csv = <<<'ENDLIST'
"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"
ENDLIST;

$arr = explode("\n", $csv);
foreach ($arr as &$line) {
  $line = str_getcsv($line);
}

Simulator or Emulator? What is the difference?

A simulation is a system that behaves similar to something else, but is implemented in an entirely different way. It provides the basic behavior of a system but may not necessarily abide by all of the rules of the system being simulated. It is there to give you an idea about how something works.

An emulation is a system that behaves exactly like something else, and abides by all of the rules of the system being emulated. It is effectively a complete replication of another system, right down to being binary compatible with the emulated system's inputs and outputs, but operating in a different environment to the environment of the original emulated system. The rules are fixed, and cannot be changed or the system fails.

Background color for Tk in Python

Its been updated so

root.configure(background="red")

is now:

root.configure(bg="red")

Difference between JSONObject and JSONArray

When a JSON start's with {} it is a ObjectJSON object and when it start's with [] it is an Array JOSN Array

An JSON array can consist of a/many objects and that is called an array of objects

How to append contents of multiple files into one file

You need the cat (short for concatenate) command, with shell redirection (>) into your output file

cat 1.txt 2.txt 3.txt > 0.txt

How can I declare and define multiple variables in one line using C++?

int column(0), row(0), index(0);

Note that this form will work with custom types too, especially when their constructors take more than one argument.

Is there an onSelect event or equivalent for HTML <select>?

I had the same problem when I was creating a design a few months back. The solution I found was to use .live("change", function()) in combination with .blur() on the element you are using.

If you wish to have it do something when the user simply clicks, instead of changing, just replace change with click.

I assigned my dropdown an ID, selected, and used the following:

$(function () {
    $("#selected").live("change", function () {

    // do whatever you need to do

    // you want the element to lose focus immediately
    // this is key to get this working.
    $('#selected').blur();
    });
});

I saw this one didn't have a selected answer, so I figured I'd give my input. This worked excellently for me, so hopefully someone else can use this code when they get stuck.

http://api.jquery.com/live/

Edit: Use the on selector as opposed to .live. See jQuery .on()

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

Number of days between past date and current date in Google spreadsheet

The following seemed to work well for me:

=DATEDIF(B2, Today(), "D")

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

Visual Studio 2015/2017's live debugger is injecting code that contains the deprecated call.

Android: Changing Background-Color of the Activity (Main View)

First Method

 View someView = findViewById(R.id.randomViewInMainLayout);// get Any child View

  // Find the root view
  View root = someView.getRootView()

  // Set the color
  root.setBackgroundColor(getResources().getColor(android.R.color.red));

Second Method

Add this single line after setContentView(...);

getWindow().getDecorView().setBackgroundColor(Color.WHITE);

Third Method

set background color to the rootView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
android:id="@+id/rootView"
</LinearLayout>

Important Thing

rootView.setBackgroundColor(0xFF00FF00); //after 0x the other four pairs are alpha,red,green,blue color. 

How do I pause my shell script for a second before continuing?

I realize that I'm a bit late with this, but you can also call sleep and pass the disired time in. For example, If I wanted to wait for 3 seconds I can do:

/bin/sleep 3

4 seconds would look like this:

/bin/sleep 4

How do I link to part of a page? (hash?)

You use an anchor and a hash. For example:

Target of the Link:

 <a name="name_of_target">Content</a>

Link to the Target:

 <a href="#name_of_target">Link Text</a>

Or, if linking from a different page:

 <a href="http://path/to/page/#name_of_target">Link Text</a>

NoClassDefFoundError for code in an Java library on Android

I encountered this NoClassDefFoundError when I used java.nio.charset.StandardCharsets.

The reason is that StandardCharsets has not existed until JRE 1.7. If I make the java compile version set to 1.7, Eclipse complained that "Android requires compiler compliance level 5.0 or 6.0". So, I fixed it by right-click the project name->Android Tools->Fix Project Properties. It is compiled with JRE1.6.

However, because StandardCharsets has not existed until 1.7. It reported NoClassDefFoundError when I ran it.

I has not come to realize this until after trying a lot of other methods including reinstalling JDK. The real reason is clearly told by the meaning of NoClassDefFoundError: The class cannot be found at run time although it passed compilation.

General conclusion is that as long as Android does not work with JRE 1.7, if you use any new feature provided since 1.7, you will encounter this error.

My solution is that I copied those source code into my code!

android.os.NetworkOnMainThreadException with android 4.2

android.os.NetworkOnMainThreadException occurs when you try to access network on your main thread (You main activity execution). To avoid this, you must create a separate thread or AsyncTask or Runnable implementation to execute your JSON data loading. Since HoneyComb you can not further execute the network task on main thread. Here is the implementation using AsyncTask for a network task execution

Are vectors passed to functions by value or by reference in C++

If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:

void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference

You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.

Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.

I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:

void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }

int main()
{
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    foo1(arr);
    foo2(arr);
    foo3(arr);
    foo4(arr);
}

How to sort a dataFrame in python pandas by two or more columns?

For large dataframes of numeric data, you may see a significant performance improvement via numpy.lexsort, which performs an indirect sort using a sequence of keys:

import pandas as pd
import numpy as np

np.random.seed(0)

df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])
df1 = pd.concat([df1]*100000)

def pdsort(df1):
    return df1.sort_values(['a', 'b'], ascending=[True, False])

def lex(df1):
    arr = df1.values
    return pd.DataFrame(arr[np.lexsort((-arr[:, 1], arr[:, 0]))])

assert (pdsort(df1).values == lex(df1).values).all()

%timeit pdsort(df1)  # 193 ms per loop
%timeit lex(df1)     # 143 ms per loop

One peculiarity is that the defined sorting order with numpy.lexsort is reversed: (-'b', 'a') sorts by series a first. We negate series b to reflect we want this series in descending order.

Be aware that np.lexsort only sorts with numeric values, while pd.DataFrame.sort_values works with either string or numeric values. Using np.lexsort with strings will give: TypeError: bad operand type for unary -: 'str'.

Throw away local commits in Git

Before answering let's add some background, explaining what is this HEAD. since some of the options below will result in detached head

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time. (excluding git worktree)

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history its called detached HEAD.

enter image description here

On the command line, it will look like this- SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch

enter image description here

enter image description here

A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit. 
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7)
    you can also use the git rebase --no-autostash as well.

git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.

# add new commit with the undo of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there reset && checkout modify the HEAD.

enter image description here

close fxml window by code, javafx

I'm not sure if this is the best way (or if it works), but you could try:

private void on_btnClose_clicked(ActionEvent actionEvent) {

        Window window = getScene().getWindow();   

        if (window instanceof Stage){
            ((Stage) window).close();
        }
}

(Assuming your controller is a Node. Otherwise you have to get the node first (getScene() is a method of Node)

Could not load file or assembly '' or one of its dependencies

if you are getting this error message by opening an application on you windows xp it mean first you have installed that app due to its not working without net framework 4 and service pack 3 . you installed both and again you are getting this error so you should reinstall that app again but first uninstall from add and remove

if this not work please dont abuse me . i am also a junior

How to fade changing background image

This is probably what you wanted:

$('#elem').fadeTo('slow', 0.3, function()
{
    $(this).css('background-image', 'url(' + $img + ')');
}).fadeTo('slow', 1);

With a 1 second delay:

$('#elem').fadeTo('slow', 0.3, function()
{
    $(this).css('background-image', 'url(' + $img + ')');
}).delay(1000).fadeTo('slow', 1);

AngularJS - Animate ng-view transitions

Angularjs 1.1.4 has now introduced the ng-animate directive to help animating different elements, in particular ng-view.

You can also watch the video about this new featue

UPDATE as of angularjs 1.2, the way animations work has changed drastically, most of it is now controlled with CSS, without having to setup javascript callbacks, etc.. You can check the updated tutorial on Year Of Moo. @dfsq pointed out in the comments a nice set of examples.

How to show all privileges from a user in oracle?

While Raviteja Vutukuri's answer works and is quick to put together, it's not particularly flexible for varying the filters and doesn't help too much if you're looking to do something programmatically. So I put together my own query:

SELECT
    PRIVILEGE,
    OBJ_OWNER,
    OBJ_NAME,
    USERNAME,
    LISTAGG(GRANT_TARGET, ',') WITHIN GROUP (ORDER BY GRANT_TARGET) AS GRANT_SOURCES, -- Lists the sources of the permission
    MAX(ADMIN_OR_GRANT_OPT) AS ADMIN_OR_GRANT_OPT, -- MAX acts as a Boolean OR by picking 'YES' over 'NO'
    MAX(HIERARCHY_OPT) AS HIERARCHY_OPT -- MAX acts as a Boolean OR by picking 'YES' over 'NO'
FROM (
    -- Gets all roles a user has, even inherited ones
    WITH ALL_ROLES_FOR_USER AS (
        SELECT DISTINCT CONNECT_BY_ROOT GRANTEE AS GRANTED_USER, GRANTED_ROLE
        FROM DBA_ROLE_PRIVS
        CONNECT BY GRANTEE = PRIOR GRANTED_ROLE
    )
    SELECT
        PRIVILEGE,
        OBJ_OWNER,
        OBJ_NAME,
        USERNAME,
        REPLACE(GRANT_TARGET, USERNAME, 'Direct to user') AS GRANT_TARGET,
        ADMIN_OR_GRANT_OPT,
        HIERARCHY_OPT
    FROM (
        -- System privileges granted directly to users
        SELECT PRIVILEGE, NULL AS OBJ_OWNER, NULL AS OBJ_NAME, GRANTEE AS USERNAME, GRANTEE AS GRANT_TARGET, ADMIN_OPTION AS ADMIN_OR_GRANT_OPT, NULL AS HIERARCHY_OPT
        FROM DBA_SYS_PRIVS
        WHERE GRANTEE IN (SELECT USERNAME FROM DBA_USERS)
        UNION ALL
        -- System privileges granted users through roles
        SELECT PRIVILEGE, NULL AS OBJ_OWNER, NULL AS OBJ_NAME, ALL_ROLES_FOR_USER.GRANTED_USER AS USERNAME, GRANTEE AS GRANT_TARGET, ADMIN_OPTION AS ADMIN_OR_GRANT_OPT, NULL AS HIERARCHY_OPT
        FROM DBA_SYS_PRIVS
        JOIN ALL_ROLES_FOR_USER ON ALL_ROLES_FOR_USER.GRANTED_ROLE = DBA_SYS_PRIVS.GRANTEE
        UNION ALL
        -- Object privileges granted directly to users
        SELECT PRIVILEGE, OWNER AS OBJ_OWNER, TABLE_NAME AS OBJ_NAME, GRANTEE AS USERNAME, GRANTEE AS GRANT_TARGET, GRANTABLE, HIERARCHY
        FROM DBA_TAB_PRIVS
        WHERE GRANTEE IN (SELECT USERNAME FROM DBA_USERS)
        UNION ALL
        -- Object privileges granted users through roles
        SELECT PRIVILEGE, OWNER AS OBJ_OWNER, TABLE_NAME AS OBJ_NAME, GRANTEE AS USERNAME, ALL_ROLES_FOR_USER.GRANTED_ROLE AS GRANT_TARGET, GRANTABLE, HIERARCHY
        FROM DBA_TAB_PRIVS
        JOIN ALL_ROLES_FOR_USER ON ALL_ROLES_FOR_USER.GRANTED_ROLE = DBA_TAB_PRIVS.GRANTEE
    ) ALL_USER_PRIVS
    -- Adjust your filter here
    WHERE USERNAME = 'USER_NAME'
) DISTINCT_USER_PRIVS
GROUP BY
    PRIVILEGE,
    OBJ_OWNER,
    OBJ_NAME,
    USERNAME
;

Advantages:

  • I easily can filter by a lot of different pieces of information, like the object, the privilege, whether it's through a particular role, etc. just by changing that one WHERE clause.
  • It's a single query, meaning I don't have to mentally compose the results together.
  • It resolves the issue of whether they can grant the privilege or not and whether it includes the privileges for subobjects (the "hierarchical" part) across differences sources of the privilege.
  • It's easy to see everything I need to do to revoke the privilege, since it lists all the sources of the privilege.
  • It combines table and system privileges into a single coherent view, allowing us to list all the privileges of a user in one fell swoop.
  • It's a query, not a function that spews all this out to DBMS_OUTPUT or something (compared to Pete Finnigan's linked script). This makes it useful for programmatic use and for exporting.
  • The filter is not repeated; it only appears once. This makes it easier to change.
  • The subquery can easily be pulled out if you need to examine it by each individual GRANT.

How do I separate an integer into separate digits in an array in JavaScript?

I realize this was asked several months ago, but I have an addition to samccone's answer which is more succinct but I don't have the rep to add as a comment!

Instead of:

(123456789).toString(10).split("").map(function(t){return parseInt(t)})

Consider:

(123456789).toString(10).split("").map(Number)

Absolute vs relative URLs

A URL that starts with the URL scheme and scheme specific part (http://, https://, ftp://, etc.) is an absolute URL.

Any other URL is a relative URL and needs a base URL the relative URL is resolved from (and thus depend on) that is the URL of the resource the reference is used in if not declared otherwise.

Take a look at RFC 2396 – Appendix C for examples of resolving relative URLs.

ios app maximum memory budget

By forking SPLITS repo, I built one to test iOS memory that can be allocated to the Today's Extension

iOSMemoryBudgetTestForExtension

Following is the result that i got in iPhone 5s

Memory Warning at 10 MB

App Crashed at 12 MB

By this means Apple is merely allowing any extensions to work with their full potential.

java.time.format.DateTimeParseException: Text could not be parsed at index 21

Your original problem was wrong pattern symbol "h" which stands for the clock hour (range 1-12). In this case, the am-pm-information is missing. Better, use the pattern symbol "H" instead (hour of day in range 0-23). So the pattern should rather have been like:

uuuu-MM-dd'T'HH:mm:ss.SSSX (best pattern also suitable for strict mode)

Create Log File in Powershell

Gist with log rotation: https://gist.github.com/barsv/85c93b599a763206f47aec150fb41ca0

Usage:

. .\logger.ps1
Write-Log "debug message"
Write-Log "info message" "INFO"

Adding a leading zero to some values in column in MySQL

I had similar problem when importing phone number data from excel to mysql database. So a simple trick without the need to identify the length of the phone number (because the length of the phone numbers varied in my data):

UPDATE table SET phone_num = concat('0', phone_num) 

I just concated 0 in front of the phone_num.

Comparing two columns, and returning a specific adjacent cell in Excel

In cell D2 and copied down:

=IF(COUNTIF($A$2:$A$5,C2)=0,"",VLOOKUP(C2,$A$2:$B$5,2,FALSE))

How to include a quote in a raw Python string

Use:

dqote='"'
sqote="'"

Use the '+' operator and dqote and squote variables to get what you need.

If I want sed -e s/",u'"/",'"/g -e s/^"u'"/"'"/, you can try the following:

dqote='"'
sqote="'"
cmd1="sed -e s/" + dqote + ",u'" + dqote + "/" + dqote + ",'" + dqote + '/g -e s/^"u' + sqote + dqote + '/' + dqote + sqote + dqote + '/'

Need to combine lots of files in a directory

I know this is an old post, but I found it and then found someone who suggested Total Mail Converter. I was able to convert my folder with 2k .msg files into .txt. It also allows you to convert into PDF and other popular formats.

It's a great tool that I am glad someone suggested as it will save me several days.

FYI - My project is combining the .msg files into one text file so that I can run a script to extract certain information from the files (ie: email and links). Instead of 2k files, I can work with one.

VarBinary vs Image SQL Server Data Type to Store Binary Data?

There is also the rather spiffy FileStream, introduced in SQL Server 2008.

Linux command to check if a shell script is running or not

I was quite inspired by the last answer by mklement0 - I have few scripts/small programs I run at every reboot via /etc/crontab. I built on his answer and built a login script, which shows if my programs are still running. I execute this scripts.sh via .profile -file on every login, to get instant notification on each login.

cat scripts.sh 
#!/bin/bash

getscript() {
  pgrep -lf ".[ /]$1( |\$)"
}

script1=keepalive.sh
script2=logger_v3.py

# test if script 1 is running
if getscript "$script1" >/dev/null; then
  echo "$script1" is RUNNING
  else
    echo "$script1" is NOT running
fi

# test if script 2 is running:
if getscript "$script2" >/dev/null; then
  echo "$script2" is RUNNING
  else
    echo "$script2" is NOT running
fi

How can I trim beginning and ending double quotes from a string?

If the double quotes only exist at the beginning and the end, a simple code as this would work perfectly:

string = string.replace("\"", "");

Import Excel spreadsheet columns into SQL Server database

If you would like a visual tool with Desktop interface including validation .. you may well like this Excel tool. You can also use the tool to create multi user data-edit tasks, or even paste data to SQL server from any source..

How to Validate and Import Excel spreadsheet to SQL Server database:

http://leansoftware.net/en-us/help/excel-database-tasks/worked-examples/how-to-import-excel-spreadsheet-to-sql-server-data.aspx

error: package javax.servlet does not exist

The answer provided by @Matthias Herlitzius is mostly correct. Just for further clarity.

The servlet-api jar is best left up to the server to manage see here for detail

With that said, the dependency to add may vary according to your server/container. For example in Wildfly the dependency would be

<dependency>
    <groupId>org.jboss.spec.javax.servlet</groupId>
    <artifactId>jboss-servlet-api_3.1_spec</artifactId>
    <scope>provided</scope>
</dependency>

So becareful to check how your container has provided the servlet implementation.

go to link on button click - jquery

Why not just change the second line to

document.location.href="www.example.com/index.php?id=" + $(this).attr('id');

Replace all whitespace characters

We can also use this if we want to change all multiple joined blank spaces with a single character:

str.replace(/\s+/g,'X');

See it in action here: https://regex101.com/r/d9d53G/1

Explanation

/ \s+ / g

  • \s+ matches any whitespace character (equal to [\r\n\t\f\v ])
  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

  • Global pattern flags
    • g modifier: global. All matches (don't return after first match)

Inserting Image Into BLOB Oracle 10g

You should do something like this:

1) create directory object what would point to server-side accessible folder

CREATE DIRECTORY image_files AS '/data/images'
/

2) Place your file into OS folder directory object points to

3) Give required access privileges to Oracle schema what will load data from file into table:

GRANT READ ON DIRECTORY image_files TO scott
/

4) Use BFILENAME, EMPTY_BLOB functions and DBMS_LOB package (example NOT tested - be care) like in below:

DECLARE
  l_blob BLOB; 
  v_src_loc  BFILE := BFILENAME('IMAGE_FILES', 'myimage.png');
  v_amount   INTEGER;
BEGIN
  INSERT INTO esignatures  
  VALUES (100, 'BOB', empty_blob()) RETURN iblob INTO l_blob; 
  DBMS_LOB.OPEN(v_src_loc, DBMS_LOB.LOB_READONLY);
  v_amount := DBMS_LOB.GETLENGTH(v_src_loc);
  DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount);
  DBMS_LOB.CLOSE(v_src_loc);
  COMMIT;
END;
/

After this you get the content of your file in BLOB column and can get it back using Java for example.

edit: One letter left missing: it should be LOADFROMFILE.

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

This worked for me right now.

  1. Visit this page then download that appropriated package for your computer (AccessDatabaseEngine.exe or AccessDatabaseEngine_X64.exe)
  2. Install that.
  3. Enjoye... Your codes is work now...

But for your application package you can use of any the following solutions:

  1. Go in "C:\Program Files (x86)\Common Files\microsoft shared" or "C:\Program Files\Common Files\Microsoft Shared" and put the "OFFICE14" directory in the same location of your package file.

Or

  1. Attach two projects (in item1) in your installation package.

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Copy all values from fields in one class to another through reflection

Mladen's basic idea worked (thanks), but needed a few changes to be robust, so I contributed them here.

The only place where this type of solution should be used is if you want to clone the object, but can't because it is a managed object. If you are lucky enough to have objects that all have 100% side-effect free setters for all fields, you should definitely use the BeanUtils option instead.

Here, I use lang3's utility methods to simplify the code, so if you paste it, you must first import Apache's lang3 library.

Copy code

static public <X extends Object> X copy(X object, String... skipFields) {
        Constructor constructorToUse = null;
        for (Constructor constructor : object.getClass().getConstructors()) {
            if (constructor.getParameterTypes().length == 0) {
                constructorToUse = constructor;
                constructorToUse.setAccessible(true);
                break;
            }
        }
        if (constructorToUse == null) {
            throw new IllegalStateException(object + " must have a zero arg constructor in order to be copied");
        }
        X copy;
        try {
            copy = (X) constructorToUse.newInstance();

            for (Field field : FieldUtils.getAllFields(object.getClass())) {
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }

                //Avoid the fields that you don't want to copy. Note, if you pass in "id", it will skip any field with "id" in it. So be careful.
                if (StringUtils.containsAny(field.getName(), skipFields)) {
                    continue;
                }

                field.setAccessible(true);

                Object valueToCopy = field.get(object);
                //TODO add here other special types of fields, like Maps, Lists, etc.
                field.set(copy, valueToCopy);

            }

        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            throw new IllegalStateException("Could not copy " + object, e);
        }
        return copy;
}

Adding image inside table cell in HTML

Sould look like:

<td colspan ='4'><img src="\Pics\H.gif" alt="" border='3' height='100' width='100' /></td>

.

<td> need to be closed with </td> <img /> is (in most case) an empty tag. The closing tag is replacede by /> instead... like for br's

<br/>

Your html structure is plain worng (sorry), but this will probably turn into a really bad cross-brwoser compatibility. Also, Encapsulate the value of your attributes with quotes and avoid using upercase in tags.

Any reason to prefer getClass() over instanceof when generating .equals()?

The reason to use getClass is to ensure the symmetric property of the equals contract. From equals' JavaDocs:

It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

By using instanceof, it's possible to not be symmetric. Consider the example: Dog extends Animal. Animal's equals does an instanceof check of Animal. Dog's equals does an instanceof check of Dog. Give Animal a and Dog d (with other fields the same):

a.equals(d) --> true
d.equals(a) --> false

This violates the symmetric property.

To strictly follow equal's contract, symmetry must be ensured, and thus the class needs to be the same.

deleted object would be re-saved by cascade (remove deleted object from associations)

This post contains a brilliant trick to detect where the cascade problem is:
Try to replace on Cascade at the time with Cascade.None() until you do not get the error and then you have detected the cascade causing the problem.

Then solve the problem either by changing the original cascade to something else or using Tom Anderson answer.

Test a string for a substring

if "ABCD" in "xxxxABCDyyyy":
    # whatever

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

The right answer is

Decoupled the build-specific components of the Android SDK from the platform-tools component, so that the build tools can be updated independently of the integrated development environment (IDE) components.

link (expand Revision 17)

How to auto-scroll to end of div when data is added?

var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;

Rename specific column(s) in pandas

A much faster implementation would be to use list-comprehension if you need to rename a single column.

df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]

If the need arises to rename multiple columns, either use conditional expressions like:

df.columns = ['log(gdp)' if x=='gdp' else 'cap_mod' if x=='cap' else x for x in df.columns]

Or, construct a mapping using a dictionary and perform the list-comprehension with it's get operation by setting default value as the old name:

col_dict = {'gdp': 'log(gdp)', 'cap': 'cap_mod'}   ## key?old name, value?new name

df.columns = [col_dict.get(x, x) for x in df.columns]

Timings:

%%timeit
df.rename(columns={'gdp':'log(gdp)'}, inplace=True)
10000 loops, best of 3: 168 µs per loop

%%timeit
df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]
10000 loops, best of 3: 58.5 µs per loop

Internal Error 500 Apache, but nothing in the logs?

In my case it was the ErrorLog directive in httpd.conf. Just accidently noticed it already after I gave up. Decided to share the discovery ) Now I know where to find the 500-errors.

Unable to run Java code with Intellij IDEA

Last resort option when nothing else seems to work: close and reopen IntelliJ.

My issue was with reverting a Git commit, which happened to change the Java SDK configured for the Project to a no longer installed version of the JDK. But fixing that back still didn't allow me to run the program. Restarting IntelliJ fixed this

Is it possible to style a mouseover on an image map using CSS?

Here's one that is pure css that uses the + next sibling selector, :hover, and pointer-events. It doesn't use an imagemap, technically, but the rect concept totally carries over:

_x000D_
_x000D_
.hotspot {_x000D_
    position: absolute;_x000D_
    border: 1px solid blue;_x000D_
}_x000D_
.hotspot + * {_x000D_
    pointer-events: none;_x000D_
    opacity: 0;_x000D_
}_x000D_
.hotspot:hover + * {_x000D_
    opacity: 1.0;_x000D_
}_x000D_
.wash {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    bottom: 0;_x000D_
    right: 0;_x000D_
    background-color: rgba(255, 255, 255, 0.6);_x000D_
}
_x000D_
<div style="position: relative; height: 188px; width: 300px;">_x000D_
    <img src="http://demo.cloudimg.io/s/width/300/sample.li/boat.jpg">_x000D_
        _x000D_
    <div class="hotspot" style="top: 50px; left: 50px; height: 30px; width: 30px;"></div>_x000D_
    <div>_x000D_
        <div class="wash"></div>_x000D_
        <div style="position: absolute; top: 0; left: 0;">A</div>_x000D_
    </div>_x000D_
        _x000D_
    <div class="hotspot" style="top: 100px; left: 120px; height: 30px; width: 30px;"></div>_x000D_
    <div>_x000D_
        <div class="wash"></div>_x000D_
        <div style="position: absolute; top: 0; left: 0;">B</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the best practice for creating a favicon on a web site?

There are several ways to create a favicon. The best way for you depends on various factors:

  • The time you can spend on this task. For many people, this is "as quick as possible".
  • The efforts you are willing to make. Like, drawing a 16x16 icon by hand for better results.
  • Specific constraints, like supporting a specific browser with odd specs.

First method: Use a favicon generator

If you want to get the job done well and quickly, you can use a favicon generator. This one creates the pictures and HTML code for all major desktop and mobiles browsers. Full disclosure: I'm the author of this site.

Advantages of such solution: it's quick and all compatibility considerations were already addressed for you.

Second method: Create a favicon.ico (desktop browsers only)

As you suggest, you can create a favicon.ico file which contains 16x16 and 32x32 pictures (note that Microsoft recommends 16x16, 32x32 and 48x48).

Then, declare it in your HTML code:

<link rel="shortcut icon" href="/path/to/icons/favicon.ico">

This method will work with all desktop browsers, old and new. But most mobile browsers will ignore the favicon.

About your suggestion of placing the favicon.ico file in the root and not declaring it: beware, although this technique works on most browsers, it is not 100% reliable. For example Windows Safari cannot find it (granted: this browser is somehow deprecated on Windows, but you get the point). This technique is useful when combined with PNG icons (for modern browsers).

Third method: Create a favicon.ico, a PNG icon and an Apple Touch icon (all browsers)

In your question, you do not mention the mobile browsers. Most of them will ignore the favicon.ico file. Although your site may be dedicated to desktop browsers, chances are that you don't want to ignore mobile browsers altogether.

You can achieve a good compatibility with:

  • favicon.ico, see above.
  • A 192x192 PNG icon for Android Chrome
  • A 180x180 Apple Touch icon (for iPhone 6 Plus; other device will scale it down as needed).

Declare them with

<link rel="shortcut icon" href="/path/to/icons/favicon.ico">
<link rel="icon" type="image/png" href="/path/to/icons/favicon-192x192.png" sizes="192x192">
<link rel="apple-touch-icon" sizes="180x180" href="/path/to/icons/apple-touch-icon-180x180.png">

This is not the full story, but it's good enough in most cases.

Setting state on componentDidMount()

The only reason that the linter complains about using setState({..}) in componentDidMount and componentDidUpdate is that when the component render the setState immediately causes the component to re-render. But the most important thing to note: using it inside these component's lifecycles is not an anti-pattern in React.

Please take a look at this issue. you will understand more about this topic. Thanks for reading my answer.

How we can bold only the name in table td tag not the value

I might be misunderstanding your question, so apologies if I am.

If you're looking for the words "Quid", "Application Number", etc. to be bold, just wrap them in <strong> tags:

<strong>Quid</strong>: ...

Hope that helps!

Change Name of Import in Java, or import two classes with the same name

There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.

Import one class and use the fully qualified name for the other one, i.e.

import com.text.Formatter;

private Formatter textFormatter;
private com.json.Formatter jsonFormatter;

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

It is today possible to configure Safari to access local files.

  • By default Safari doesn't allow access to local files.
  • To enable this option: First you need to enable the develop menu.
  • Click on the Develop menu Select Disable Local File Restrictions.

Source: http://ccm.net/faq/36342-safari-how-to-enable-local-file-access

Javascript onclick hide div

Simple & Best way:

onclick="parentNode.remove()"

Deletes the complete parent from html

Preferred way to create a Scala list

Note: This answer is written for an old version of Scala.

The Scala collection classes are going to be redesigned as of Scala 2.8, so be prepared to change the way you create lists very soon.

What is the forward compatible way of creating a List? I have no idea since I haven't read the 2.8 docs yet.

A PDF document describing the proposed changes of the collection classes

Passing a String by Reference in Java?

This works use StringBuffer

public class test {
 public static void main(String[] args) {
 StringBuffer zText = new StringBuffer("");
    fillString(zText);
    System.out.println(zText.toString());
 }
  static void fillString(StringBuffer zText) {
    zText .append("foo");
}
}

Even better use StringBuilder

public class test {
 public static void main(String[] args) {
 StringBuilder zText = new StringBuilder("");
    fillString(zText);
    System.out.println(zText.toString());
 }
  static void fillString(StringBuilder zText) {
    zText .append("foo");
}
}

How to POST JSON Data With PHP cURL?

You are POSTing the json incorrectly -- but even if it were correct, you would not be able to test using print_r($_POST) (read why here). Instead, on your second page, you can nab the incoming request using file_get_contents("php://input"), which will contain the POSTed json. To view the received data in a more readable format, try this:

echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';

In your code, you are indicating Content-Type:application/json, but you are not json-encoding all of the POST data -- only the value of the "customer" POST field. Instead, do something like this:

$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode( array( "customer"=> $data ) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.
echo "<pre>$result</pre>";

Sidenote: You might benefit from using a third-party library instead of interfacing with the Shopify API directly yourself.

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Tensorflow 2.1 works with Cuda 10.1.

If you want a quick hack:

  • Just download cudart64_101.dll from here. Extract the zip file and copy the cudart64_101.dll to your CUDA bin directory

Else:

  • Install Cuda 10.1

Controlling fps with requestAnimationFrame?

How to throttle requestAnimationFrame to a specific frame rate

Demo throttling at 5 FPS: http://jsfiddle.net/m1erickson/CtsY3/

This method works by testing the elapsed time since executing the last frame loop.

Your drawing code executes only when your specified FPS interval has elapsed.

The first part of the code sets some variables used to calculate elapsed time.

var stop = false;
var frameCount = 0;
var $results = $("#results");
var fps, fpsInterval, startTime, now, then, elapsed;


// initialize the timer variables and start the animation

function startAnimating(fps) {
    fpsInterval = 1000 / fps;
    then = Date.now();
    startTime = then;
    animate();
}

And this code is the actual requestAnimationFrame loop which draws at your specified FPS.

// the animation loop calculates time elapsed since the last loop
// and only draws if your specified fps interval is achieved

function animate() {

    // request another frame

    requestAnimationFrame(animate);

    // calc elapsed time since last loop

    now = Date.now();
    elapsed = now - then;

    // if enough time has elapsed, draw the next frame

    if (elapsed > fpsInterval) {

        // Get ready for next frame by setting then=now, but also adjust for your
        // specified fpsInterval not being a multiple of RAF's interval (16.7ms)
        then = now - (elapsed % fpsInterval);

        // Put your drawing code here

    }
}

Capture key press without placing an input element on the page?

For modern JS, use event.key!

document.addEventListener("keypress", function onPress(event) {
    if (event.key === "z" && event.ctrlKey) {
        // Do something awesome
    }
});

NOTE: The old properties (.keyCode and .which) are Deprecated.

Mozilla Docs

Supported Browsers

How to remove leading zeros using C#

Using the following will return a single 0 when input is all 0.

string s = "0000000"
s = int.Parse(s).ToString();

gridview data export to excel in asp.net

I think it will help you

string filename = String.Format("Results_{0}_{1}.xls", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());
        if (!string.IsNullOrEmpty(GRIDVIEWNAME.Page.Title))
            filename = GRIDVIEWNAME.Page.Title + ".xls";

        HttpContext.Current.Response.Clear();

        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);


        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.Charset = "";

        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);



        System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
        GRIDVIEWNAME.Parent.Controls.Add(form);
        form.Controls.Add(GRIDVIEWNAME);
        form.RenderControl(htmlWriter);

        HttpContext.Current.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
        HttpContext.Current.Response.Write(stringWriter.ToString());
        HttpContext.Current.Response.End();

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

Remove empty elements from an array in Javascript

This works, I tested it in AppJet (you can copy-paste the code on its IDE and press "reload" to see it work, don't need to create an account)

/* appjet:version 0.1 */
function Joes_remove(someArray) {
    var newArray = [];
    var element;
    for( element in someArray){
        if(someArray[element]!=undefined ) {
            newArray.push(someArray[element]);
        }
    }
    return newArray;
}

var myArray2 = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];

print("Original array:", myArray2);
print("Clenased array:", Joes_remove(myArray2) );
/*
Returns: [1,2,3,3,0,4,4,5,6]
*/

Java: Replace all ' in a string with \'

Use replace()

 s = s.replace("'", "\\'"); 

output:

You\'ll be totally awesome, I\'m really terrible

Laravel where on relationship object

@Cermbo's answer is not related to this question. In their answer, Laravel will give you all Events if each Event has 'participants' with IdUser of 1.

But if you want to get all Events with all 'participants' provided that all 'participants' have a IdUser of 1, then you should do something like this :

Event::with(["participants" => function($q){
    $q->where('participants.IdUser', '=', 1);
}])

N.B:

in where use your table name, not Model name.

ls command: how can I get a recursive full-path listing, one line per file?

Best command is: tree -fi

-f print the full path prefix for each file
-i don't print indentations

e.g.

$ tree -fi
.
./README.md
./node_modules
./package.json
./src
./src/datasources
./src/datasources/bookmarks.js
./src/example.json
./src/index.js
./src/resolvers.js
./src/schema.js

In order to use the files but not the links, you have to remove > from your output:

tree -fi |grep -v \>

If you want to know the nature of each file, (to read only ASCII files for example) with two whiles:

tree -fi | \
grep -v \> | \
while read first ; do 
    file ${first}
done | \
while read second; do 
    echo ${second} | grep ASCII
done

Download file from web in Python 3

If you are using Linux you can use the wget module of Linux through the python shell. Here is a sample code snippet

import os
url = 'http://www.example.com/foo.zip'
os.system('wget %s'%url)

Setting up a cron job in Windows

  1. Make sure you logged on as an administrator or you have the same access as an administrator.
  2. Start->Control Panel->System and Security->Administrative Tools->Task Scheduler
  3. Action->Create Basic Task->Type a name and Click Next
  4. Follow through the wizard.

Rails 4: how to use $(document).ready() with turbo-links

$(document).on 'ready turbolinks:load', ->
  console.log '(document).turbolinks:load'

Create an array with same element repeated multiple times

You can do it like this:

function fillArray(value, len) {
  if (len == 0) return [];
  var a = [value];
  while (a.length * 2 <= len) a = a.concat(a);
  if (a.length < len) a = a.concat(a.slice(0, len - a.length));
  return a;
}

It doubles the array in each iteration, so it can create a really large array with few iterations.


Note: You can also improve your function a lot by using push instead of concat, as concat will create a new array each iteration. Like this (shown just as an example of how you can work with arrays):

function fillArray(value, len) {
  var arr = [];
  for (var i = 0; i < len; i++) {
    arr.push(value);
  }
  return arr;
}

"Parser Error Message: Could not load type" in Global.asax

I also got the same error...check the IIS Configuration of your Virtual Directory and be sure that Properties - ASP.NET - ASP.NET Version is the same of Project Properties - Application - Target Framework. (That fixed this error for me.)

How should I unit test multithreaded code?

I spent most of last week at a university library studying debugging of concurrent code. The central problem is concurrent code is non-deterministic. Typically, academic debugging has fallen into one of three camps here:

  1. Event-trace/replay. This requires an event monitor and then reviewing the events that were sent. In a UT framework, this would involve manually sending the events as part of a test, and then doing post-mortem reviews.
  2. Scriptable. This is where you interact with the running code with a set of triggers. "On x > foo, baz()". This could be interpreted into a UT framework where you have a run-time system triggering a given test on a certain condition.
  3. Interactive. This obviously won't work in an automatic testing situation. ;)

Now, as above commentators have noticed, you can design your concurrent system into a more deterministic state. However, if you don't do that properly, you're just back to designing a sequential system again.

My suggestion would be to focus on having a very strict design protocol about what gets threaded and what doesn't get threaded. If you constrain your interface so that there is minimal dependancies between elements, it is much easier.

Good luck, and keep working on the problem.

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

A CORS POST request works from plain JavaScript, but why not with jQuery?

Modify your Jquery in following way:

$.ajax({
            url: someurl,
            contentType: 'application/json',
            data: JSONObject,
            headers: { 'Access-Control-Allow-Origin': '*' }, //add this line
            dataType: 'json',
            type: 'POST',                
            success: function (Data) {....}
});

CSS Selector "(A or B) and C"?

Not yet, but there is the experimental :matches() pseudo-class function that does just that:

:matches(.a .b) .c {
  /* stuff goes here */
}

You can find more info on it here and here. Currently, most browsers support its initial version :any(), which works the same way, but will be replaced by :matches(). We just have to wait a little more before using this everywhere (I surely will).

How to check java bit version on Linux?

Works for every binary, not only java:

file - < $(which java) # heavyly bashic

cat `which java` | file - # universal

What does [object Object] mean?

[object Object] is the default string representation of a JavaScript Object. It is what you'll get if you run this code:

alert({}); // [object Object]

You can change the default representation by overriding the toString method like so:

var o = {toString: function(){ return "foo" }};
alert(o); // foo

How to call jQuery function onclick?

Please have a look at http://jsfiddle.net/2dJAN/59/

$("#submit").click(function () {
var url = $(location).attr('href');
$('#spn_url').html('<strong>' + url + '</strong>');
});

How to convert dd/mm/yyyy string into JavaScript Date object?

Here is a way to transform a date string with a time of day to a date object. For example to convert "20/10/2020 18:11:25" ("DD/MM/YYYY HH:MI:SS" format) to a date object

    function newUYDate(pDate) {
      let dd = pDate.split("/")[0].padStart(2, "0");
      let mm = pDate.split("/")[1].padStart(2, "0");
      let yyyy = pDate.split("/")[2].split(" ")[0];
      let hh = pDate.split("/")[2].split(" ")[1].split(":")[0].padStart(2, "0");
      let mi = pDate.split("/")[2].split(" ")[1].split(":")[1].padStart(2, "0");
      let secs = pDate.split("/")[2].split(" ")[1].split(":")[2].padStart(2, "0");
    
      mm = (parseInt(mm) - 1).toString(); // January is 0
    
      return new Date(yyyy, mm, dd, hh, mi, secs);
    }

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

Phone validation regex

Try this

\+?\(?([0-9]{3})\)?[-.]?\(?([0-9]{3})\)?[-.]?\(?([0-9]{4})\)?

It matches the following cases

  • +123-(456)-(7890)
  • +123.(456).(7890)
  • +(123).(456).(7890)
  • +(123)-(456)-(7890)
  • +123(456)(7890)
  • +(123)(456)(7890)
  • 123-(456)-(7890)
  • 123.(456).(7890)
  • (123).(456).(7890)
  • (123)-(456)-(7890)
  • 123(456)(7890)
  • (123)(456)(7890)

For further explanation on the pattern CLICKME

In Spring MVC, how can I set the mime type header when using @ResponseBody

I would consider to refactor the service to return your domain object rather than JSON strings and let Spring handle the serialization (via the MappingJacksonHttpMessageConverter as you write). As of Spring 3.1, the implementation looks quite neat:

@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, 
    method = RequestMethod.GET
    value = "/foo/bar")
@ResponseBody
public Bar fooBar(){
    return myService.getBar();
}

Comments:

First, the <mvc:annotation-driven /> or the @EnableWebMvc must be added to your application config.

Next, the produces attribute of the @RequestMapping annotation is used to specify the content type of the response. Consequently, it should be set to MediaType.APPLICATION_JSON_VALUE (or "application/json").

Lastly, Jackson must be added so that any serialization and de-serialization between Java and JSON will be handled automatically by Spring (the Jackson dependency is detected by Spring and the MappingJacksonHttpMessageConverter will be under the hood).

Limit number of characters allowed in form input text field

The simplest way to do so:

maxlength="5"

So.. Adding this attribute to your control:

<input type="text" 
    id="sessionNo" 
    name="sessionNum" 
    onkeypress="return isNumberKey(event)" 
    maxlength="5" />

CSS ''background-color" attribute not working on checkbox inside <div>

The Best solution to change background checkbox color

_x000D_
_x000D_
input[type=checkbox] {_x000D_
    margin-right: 5px;_x000D_
    cursor: pointer;_x000D_
    font-size: 14px;_x000D_
    width: 15px;_x000D_
    height: 12px;_x000D_
    position: relative;_x000D_
  }_x000D_
  _x000D_
  input[type=checkbox]:after {_x000D_
    position: absolute;_x000D_
    width: 10px;_x000D_
    height: 15px;_x000D_
    top: 0;_x000D_
    content: " ";_x000D_
    background-color: #ff0000;_x000D_
    color: #fff;_x000D_
    display: inline-block;_x000D_
    visibility: visible;_x000D_
    padding: 0px 3px;_x000D_
    border-radius: 3px;_x000D_
  }_x000D_
  _x000D_
  input[type=checkbox]:checked:after {_x000D_
   content: "?";_x000D_
   font-size: 12px;_x000D_
  }
_x000D_
  <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>_x000D_
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>_x000D_
_x000D_
  <input type="checkbox" name="vehicle" value="Car" checked> I have a bus<br>
_x000D_
_x000D_
_x000D_

How to dynamically update labels captions in VBA form?

If you want to use this in VBA:

For i = 1 To X
    UserForm1.Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

Call a method of a controller from another controller using 'scope' in AngularJS

Here is good Demo in Fiddle how to use shared service in directive and other controllers through $scope.$on

HTML

<div ng-controller="ControllerZero">
    <input ng-model="message" >
    <button ng-click="handleClick(message);">BROADCAST</button>
</div>

<div ng-controller="ControllerOne">
    <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
    <input ng-model="message" >
</div>

<my-component ng-model="message"></my-component>

JS

var myModule = angular.module('myModule', []);

myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};

    sharedService.message = '';

    sharedService.prepForBroadcast = function(msg) {
        this.message = msg;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

By the same way we can use shared service in directive. We can implement controller section into directive and use $scope.$on

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
});

And here three our controllers where ControllerZero used as trigger to invoke prepForBroadcast

function ControllerZero($scope, sharedService) {
    $scope.handleClick = function(msg) {
        sharedService.prepForBroadcast(msg);
    };

    $scope.$on('handleBroadcast', function() {
        $scope.message = sharedService.message;
    });
}

function ControllerOne($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'ONE: ' + sharedService.message;
    });
}

function ControllerTwo($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'TWO: ' + sharedService.message;
    });
}

The ControllerOne and ControllerTwo listen message change by using $scope.$on handler.

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

I was thinking - maybe ID will be a useful tool. Every time a user creates a new account it should get a higher ID. I googled and found that there is a method to estimate the account creation date by ID and Massoud Seifi from metadatascience.com gathered some good data about it.

Enter image description here

Read this article:

http://metadatascience.com/2013/03/11/inferring-facebook-account-creation-date-from-facebook-user-id/

And here are some IDs to download:

http://metadatascience.com/2013/03/14/lookup-table-for-inferring-facebook-account-creation-date-from-facebook-user-id/

What does href expression <a href="javascript:;"></a> do?

    1. Use that java script to Clear an HTML row Or Delete a row using the id set to a span and use JQuery to set a function to that span's click event.
    2. Dynamically set the div html to a string variable and replace {id} with a 1 or 2 etc. cell of a larger div table and rows

<div class="table-cell">
    <span id="clearRow{id}">
        <a href="javascript:" style-"color:#c32029; align:right; font-size:8pt;">Clear</a>
    </span>
</div>

<div class="table-cell">
   <span id="deleteRow{id}">
       <a href="javascript:" style-"color:#c32029; align:right; font-size:8pt;">Delete</a>
   </span>
</div>

//JQuery - Clear row
$("#clearRow" + idNum).click(function(){
    $("someIDOrWildcardSelector" + idNum).val("");
    $("someIDOrWildcardSelector" + idNum).val("");
    $("someIDOrWildcardSelector" + idNum).val("");
});

//JQuery to remove / delete an html row
$("#deleteRow" + idNum).click(function(){
    //depending upon levels of parent / child use 1 to many .parent().parent().parent()
    $(this).parent().remove();
});

Checking for empty queryset in Django

The most efficient way (before django 1.2) is this:

if orgs.count() == 0:
    # no results
else:
    # alrigh! let's continue...

HTML5 <video> element on Android

According to : https://stackoverflow.com/a/24403519/365229

This should work, with plain Javascript:

var myVideo = document.getElementById('myVideoTag');

myVideo.play();
if (typeof(myVideo.webkitEnterFullscreen) != "undefined") {
    // This is for Android Stock.
    myVideo.webkitEnterFullscreen();
} else if (typeof(myVideo.webkitRequestFullscreen)  != "undefined") {
    // This is for Chrome.
    myVideo.webkitRequestFullscreen();
} else if (typeof(myVideo.mozRequestFullScreen)  != "undefined") {
    myVideo.mozRequestFullScreen();
}

You have to trigger play() before the fullscreen instruction, otherwise in Android Browser it will just go fullscreen but it will not start playing. Tested with the latest version of Android Browser, Chrome, Safari.

I've tested it on Android 2.3.3 & 4.4 browser.

What is the "continue" keyword and how does it work in Java?

I'm a bit late to the party, but...

It's worth mentioning that continue is useful for empty loops where all of the work is done in the conditional expression controlling the loop. For example:

while ((buffer[i++] = readChar()) >= 0)
    continue;

In this case, all of the work of reading a character and appending it to buffer is done in the expression controlling the while loop. The continue statement serves as a visual indicator that the loop does not need a body.

It's a little more obvious than the equivalent:

while (...)
{ }

and definitely better (and safer) coding style than using an empty statement like:

while (...)
    ;

Is header('Content-Type:text/plain'); necessary at all?

PHP uses Content-Type "text/html" as default - which is pretty similar to "text/plain" - and this explains why you don't see any differences. text/plain is necessary if you want to output text as is (including <>-symbols). Examples:

header("Content-Type: text/plain");
echo "<b>hello world</b>";
// Output: <b>hello world</b>

header("Content-Type: text/html");
echo "<b>hello world</b>";
// Output: hello world

How to get 30 days prior to current date?

Javascript can handle it without any external libraries.

_x000D_
_x000D_
var today = new Date();_x000D_
var dateLimit = new Date(new Date().setDate(today.getDate() - 30));_x000D_
_x000D_
document.write(today + "<br/>" + dateLimit)
_x000D_
_x000D_
_x000D_

How to get root access on Android emulator?

Here is the list of commands you have to run while the emulator is running, I test this solution for an avd on Android 2.2 :

adb shell mount -o rw,remount -t yaffs2 /dev/block/mtdblock03 /system  
adb push su /system/xbin/su  
adb shell chmod 06755 /system  
adb shell chmod 06755 /system/xbin/su

It assumes that the su binary is located in the working directory. You can find su and superuser here : http://forum.xda-developers.com/showthread.php?t=682828. You need to run these commands each time you launch the emulator. You can write a script that launch the emulator and root it.

Display Adobe pdf inside a div

You could create an image thumbnail, and link it to the actual pdf as an inline popup using something like http://orangoo.com/labs/GreyBox/

Good Java graph algorithm library?

JUNG is a good option for visualisation, and also has a fairly good set of available graph algorithms, including several different mechanisms for random graph creation, rewiring, etc. I've also found it to be generally fairly easy to extend and adapt where necessary.

PHP session handling errors

Go to your PHP.ini file or find PHP.ini EZConfig on your Cpanel and set your session.save_path to the full path leading to the tmp file, i.e: /home/cpanelusername/tmp

Best way to remove duplicate entries from a data table

Remove Duplicates

public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
{
   Hashtable hTable = new Hashtable();
   ArrayList duplicateList = new ArrayList();

   //Add list of all the unique item value to hashtable, which stores combination of key, value pair.
   //And add duplicate item value in arraylist.
   foreach (DataRow drow in dTable.Rows)
   {
      if (hTable.Contains(drow[colName]))
         duplicateList.Add(drow);
      else
         hTable.Add(drow[colName], string.Empty); 
   }

   //Removing a list of duplicate items from datatable.
   foreach (DataRow dRow in duplicateList)
      dTable.Rows.Remove(dRow);

   //Datatable which contains unique records will be return as output.
      return dTable;
}

Here Links below

http://www.dotnetspider.com/resources/4535-Remove-duplicate-records-from-table.aspx

http://www.dotnetspark.com/kb/94-remove-duplicate-rows-value-from-datatable.aspx

For remove duplicates in column

http://dotnetguts.blogspot.com/2007/02/removing-duplicate-records-from.html

Insert a row to pandas dataframe

The simplest way add a row in a pandas data frame is:

DataFrame.loc[ location of insertion ]= list( )

Example :

DF.loc[ 9 ] = [ ´Pepe’ , 33, ´Japan’ ]

NB: the length of your list should match that of the data frame.

Invalid character in identifier

If your keyboard is set to English US (International) rather than English US the double quotation marks don't work. This is why the single quotation marks worked in your case.

Xcode 5 and iOS 7: Architecture and Valid architectures

None of the answers worked and then I was forgetting to set minimum deployment target which can be found in Project -> General -> Deployment Info -> Deployment Target -> 8.0

Example

How can I measure the actual memory usage of an application or process?

If you want something quicker than profiling with Valgrind and your kernel is older and you can't use smaps, a ps with the options to show the resident set of the process (with ps -o rss,command) can give you a quick and reasonable _aproximation_ of the real amount of non-swapped memory being used.

A warning - comparison between signed and unsigned integer expressions

It is usually a good idea to declare variables as unsigned or size_t if they will be compared to sizes, to avoid this issue. Whenever possible, use the exact type you will be comparing against (for example, use std::string::size_type when comparing with a std::string's length).

Compilers give warnings about comparing signed and unsigned types because the ranges of signed and unsigned ints are different, and when they are compared to one another, the results can be surprising. If you have to make such a comparison, you should explicitly convert one of the values to a type compatible with the other, perhaps after checking to ensure that the conversion is valid. For example:

unsigned u = GetSomeUnsignedValue();
int i = GetSomeSignedValue();

if (i >= 0)
{
    // i is nonnegative, so it is safe to cast to unsigned value
    if ((unsigned)i >= u)
        iIsGreaterThanOrEqualToU();
    else
        iIsLessThanU();
}
else
{
    iIsNegative();
}

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

It works well - you must put unchecked in the checkbox "Enable Just My Code" as highlighted in below image:

enter image description here

Why would an Enum implement an Interface?

Enums are like Java Classes, they can have Constructors, Methods, etc. The only thing that you can't do with them is new EnumName(). The instances are predefined in your enum declaration.

Remove characters except digits from string using Python?

Ugly but works:

>>> s
'aaa12333bb445bb54b5b52'
>>> a = ''.join(filter(lambda x : x.isdigit(), s))
>>> a
'1233344554552'
>>>

Position a div container on the right side

  • Use float: right to.. float the second column to the.. right.
  • Use overflow: hidden to clear the floats so that the background color I just put in will be visible.

Live Demo

#wrapper{
    background:#000;
    overflow: hidden
}
#c1 {
   float:left;
   background:red;
}
#c2 {
    background:green;
    float: right
}

Git submodule head 'reference is not a tree' error

Your submodule history is safely preserved in the submodule git anyway.

So, why not just delete the submodule and add it again?

Otherwise, did you try manually editing the HEAD or the refs/master/head within the submodule .git

Could not load file or assembly '***.dll' or one of its dependencies

An easier way to determine what dependencies a native DLL has is to use Dependency Walker - http://www.dependencywalker.com/

I analysed the native DLL and discovered that it depended on MSVCR120.DLL and MSVCP120.DLL, both of which were not installed on my staging server in the System32 directory. I installed the C++ runtime on my staging server and the issue was resolved.

Maven: How to run a .java file from command line passing arguments

In addition to running it with mvn exec:java, you can also run it with mvn exec:exec

mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath your.package.MainClass"

Bootstrap change div order with pull-right, pull-left on 3 columns

Try this...

<div class="row">
    <div class="col-xs-3">
        Menu
    </div>
    <div class="col-xs-9">
        <div class="row">
          <div class="col-sm-4 col-sm-push-8">
          Right content
          </div>
          <div class="col-sm-8 col-sm-pull-4">
          Content
          </div>
       </div>
    </div>
</div>

Bootply

NSOperation vs Grand Central Dispatch

GCD is indeed lower-level than NSOperationQueue, its major advantage is that its implementation is very light-weight and focused on lock-free algorithms and performance.

NSOperationQueue does provide facilities that are not available in GCD, but they come at non-trivial cost, the implementation of NSOperationQueue is complex and heavy-weight, involves a lot of locking, and uses GCD internally only in a very minimal fashion.

If you need the facilities provided by NSOperationQueue by all means use it, but if GCD is sufficient for your needs, I would recommend using it directly for better performance, significantly lower CPU and power cost and more flexibility.

How many threads is too many?

ryeguy, I am currently developing a similar application and my threads number is set to 15. Unfortunately if I increase it at 20, it crashes. So, yes, I think the best way to handle this is to measure whether or not your current configuration allows more or less than a number X of threads.

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

What's the best way to limit text length of EditText in Android

EditText editText = new EditText(this);
int maxLength = 3;    
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});

Partial Dependency (Databases)

Partial Functional Dependency occurs only in relation with composite keys. Partial functional dependency occurs when one or more non key attribute are depending on a part of the primary key.

Example:

Table: Stud_id, Course_id, Stud_name, Course_Name

Where: Primary Key = Stud_id + Course_id

Then: To determine name of student we use only Stud_id, which is part of primary key.

{Stud_id} -> {Stud_Name}

Hence,Stud_name is partially dependent on Stud_id. This is called partial dependency.

What is the backslash character (\\)?

Imagine you are designing a programming language. You decide that Strings are enclosed in quotes ("Apple"). Then you hit your first snag: how to represent quotation marks since you've already used them ? Just out of convention you decide to use \" to represent quotation marks. Then you have a second problem: how to represent \ ? Again, out of convention you decide to use \\ instead. Thankfully, the process ends there and this is sufficient. You can also use what is called an escape sequence to represent other characters such as the carriage return (\n).

Docker remove <none> TAG images

To remove dangling images please use :

docker image rm $(docker images --format "{{.ID}}" --filter "dangling=true")

Please refer to my answer here for a more detailed description : https://unix.stackexchange.com/a/445664/292327

Getting 404 Not Found error while trying to use ErrorDocument

When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,

 ErrorDocument 404 /yourfoldernames/errors/404.html

How to install gem from GitHub source?

Try the specific_install gem it allows you you to install a gem from its github repository (like 'edge'), or from an arbitrary URL. Very usefull for forking gems and hacking on them on multiple machines and such.

gem install specific_install
gem specific_install -l <url to a github gem>

e.g.

gem specific_install https://github.com/githubsvnclone/rdoc.git 

MySQL Select all columns from one table and some from another table

Just use the table name:

SELECT myTable.*, otherTable.foo, otherTable.bar...

That would select all columns from myTable and columns foo and bar from otherTable.

Adding text to ImageView in Android

You can also use a TextView and set the background image to what you wanted in the ImageView. Furthermore if you were using the ImageView as a button you can set it to click-able

Here is some basic code for a TextView that shows an image with text on top of it.

<TextView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/your_image"
    android:text="your text here" />

int to hex string

Use ToString("X4").

The 4 means that the string will be 4 digits long.

Reference: The Hexadecimal ("X") Format Specifier on MSDN.

How to Deserialize XML document

The following snippet should do the trick (and you can ignore most of the serialization attributes):

public class Car
{
  public string StockNumber { get; set; }
  public string Make { get; set; }
  public string Model { get; set; }
}

[XmlRootAttribute("Cars")]
public class CarCollection
{
  [XmlElement("Car")]
  public Car[] Cars { get; set; }
}

...

using (TextReader reader = new StreamReader(path))
{
  XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
  return (CarCollection) serializer.Deserialize(reader);
}

git command to move a folder inside another

 git mv common include

should work.

From the git mv man page:

git mv [-f] [-n] [-k] <source> ... <destination directory>

In the second form, the last argument has to be an existing directory; the given sources will be moved into this directory.
The index is updated after successful completion, but the change must still be committed.

No "git add" should be done before the move.


Note: "git mv A B/", when B does not exist as a directory, should error out, but it didn't.

See commit c57f628 by Matthieu Moy (moy) for Git 1.9/2.0 (Q1 2014):

Git used to trim the trailing slash, and make the command equivalent to 'git mv file no-such-dir', which created the file no-such-dir (while the trailing slash explicitly stated that it could only be a directory).

This patch skips the trailing slash removal for the destination path.
The path with its trailing slash is passed to rename(2), which errors out with the appropriate message:

$ git mv file no-such-dir/
fatal: renaming 'file' failed: Not a directory

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

you should be using the .Value of the datetime parameter. All Nullable structs have a value property which returns the concrete type of the object. but you must check to see if it is null beforehand otherwise you will get a runtime error.

i.e:

datetime.Value

but check to see if it has a value first!

if (datetime.HasValue)
{
   // work with datetime.Value
}

Convert a character digit to the corresponding integer in C

Subtract char '0' or int 48 like this:

char c = '5';
int i = c - '0';

Explanation: Internally it works with ASCII value. From the ASCII table, decimal value of character 5 is 53 and 0 is 48. So 53 - 48 = 5

OR

char c = '5';
int i = c - 48; // Because decimal value of char '0' is 48

That means if you deduct 48 from any numeral character, it will convert integer automatically.

React Modifying Textarea Values

I think you want something along the line of:

Parent:

<Editor name={this.state.fileData} />

Editor:

var Editor = React.createClass({
  displayName: 'Editor',
  propTypes: {
    name: React.PropTypes.string.isRequired
  },
  getInitialState: function() { 
    return {
      value: this.props.name
    };
  },
  handleChange: function(event) {
    this.setState({value: event.target.value});
  },
  render: function() {
    return (
      <form id="noter-save-form" method="POST">
        <textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
        <input type="submit" value="Save" />
      </form>
    );
  }
});

This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html

Update for React 16.8:

import React, { useState } from 'react';

const Editor = (props) => {
    const [value, setValue] = useState(props.name);

    const handleChange = (event) => {
        setValue(event.target.value);
    };

    return (
        <form id="noter-save-form" method="POST">
            <textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
            <input type="submit" value="Save" />
        </form>
    );
}

Editor.propTypes = {
    name: PropTypes.string.isRequired
};

Get current application physical path within Application_Start

use below code

server.mappath() in asp.net

application.startuppath in c# windows application

Initialising mock objects - MockIto

For the mocks initialization, using the runner or the MockitoAnnotations.initMocks are strictly equivalent solutions. From the javadoc of the MockitoJUnitRunner :

JUnit 4.5 runner initializes mocks annotated with Mock, so that explicit usage of MockitoAnnotations.initMocks(Object) is not necessary. Mocks are initialized before each test method.


The first solution (with the MockitoAnnotations.initMocks) could be used when you have already configured a specific runner (SpringJUnit4ClassRunner for example) on your test case.

The second solution (with the MockitoJUnitRunner) is the more classic and my favorite. The code is simpler. Using a runner provides the great advantage of automatic validation of framework usage (described by @David Wallace in this answer).

Both solutions allows to share the mocks (and spies) between the test methods. Coupled with the @InjectMocks, they allow to write unit tests very quickly. The boilerplate mocking code is reduced, the tests are easier to read. For example:

@RunWith(MockitoJUnitRunner.class)
public class ArticleManagerTest {

    @Mock private ArticleCalculator calculator;
    @Mock(name = "database") private ArticleDatabase dbMock;
    @Spy private UserProvider userProvider = new ConsumerUserProvider();

    @InjectMocks private ArticleManager manager;

    @Test public void shouldDoSomething() {
        manager.initiateArticle();
        verify(database).addListener(any(ArticleListener.class));
    }

    @Test public void shouldDoSomethingElse() {
        manager.finishArticle();
        verify(database).removeListener(any(ArticleListener.class));
    }
}

Pros: The code is minimal

Cons: Black magic. IMO it is mainly due to the @InjectMocks annotation. With this annotation "you loose the pain of code" (see the great comments of @Brice)


The third solution is to create your mock on each test method. It allow as explained by @mlk in its answer to have "self contained test".

public class ArticleManagerTest {

    @Test public void shouldDoSomething() {
        // given
        ArticleCalculator calculator = mock(ArticleCalculator.class);
        ArticleDatabase database = mock(ArticleDatabase.class);
        UserProvider userProvider = spy(new ConsumerUserProvider());
        ArticleManager manager = new ArticleManager(calculator, 
                                                    userProvider, 
                                                    database);

        // when 
        manager.initiateArticle();

        // then 
        verify(database).addListener(any(ArticleListener.class));
    }

    @Test public void shouldDoSomethingElse() {
        // given
        ArticleCalculator calculator = mock(ArticleCalculator.class);
        ArticleDatabase database = mock(ArticleDatabase.class);
        UserProvider userProvider = spy(new ConsumerUserProvider());
        ArticleManager manager = new ArticleManager(calculator, 
                                                    userProvider, 
                                                    database);

        // when 
        manager.finishArticle();

        // then
        verify(database).removeListener(any(ArticleListener.class));
    }
}

Pros: You clearly demonstrate how your api works (BDD...)

Cons: there is more boilerplate code. (The mocks creation)


My recommandation is a compromise. Use the @Mock annotation with the @RunWith(MockitoJUnitRunner.class), but do not use the @InjectMocks :

@RunWith(MockitoJUnitRunner.class)
public class ArticleManagerTest {

    @Mock private ArticleCalculator calculator;
    @Mock private ArticleDatabase database;
    @Spy private UserProvider userProvider = new ConsumerUserProvider();

    @Test public void shouldDoSomething() {
        // given
        ArticleManager manager = new ArticleManager(calculator, 
                                                    userProvider, 
                                                    database);

        // when 
        manager.initiateArticle();

        // then 
        verify(database).addListener(any(ArticleListener.class));
    }

    @Test public void shouldDoSomethingElse() {
        // given
        ArticleManager manager = new ArticleManager(calculator, 
                                                    userProvider, 
                                                    database);

        // when 
        manager.finishArticle();

        // then 
        verify(database).removeListener(any(ArticleListener.class));
    }
}

Pros: You clearly demonstrate how your api works (How my ArticleManager is instantiated). No boilerplate code.

Cons: The test is not self contained, less pain of code

Images can't contain alpha channels or transparencies

You can simply create a new Photoshop document and set its default background to White instead of Transparent. Then, copy and paste your image to the newly created document and save it.

Using IS NULL or IS NOT NULL on join conditions - Theory question

Your execution plan should make this clear; the JOIN takes precedence, after which the results are filtered.

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

Android Camera : data intent returns null

I found an easy answer. it works!!

private void openCameraForResult(int requestCode){
    Intent photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    Uri uri  = Uri.parse("file:///sdcard/photo.jpg");
    photo.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);
    startActivityForResult(photo,requestCode);
}

if (requestCode == CAMERA_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {
            File file = new File(Environment.getExternalStorageDirectory().getPath(), "photo.jpg");
            Uri uri = Uri.fromFile(file);
            Bitmap bitmap;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                bitmap = cropAndScale(bitmap, 300); // if you mind scaling
                profileImageView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

if you would like to crop and scale this image

public static  Bitmap cropAndScale (Bitmap source, int scale){
    int factor = source.getHeight() <= source.getWidth() ? source.getHeight(): source.getWidth();
    int longer = source.getHeight() >= source.getWidth() ? source.getHeight(): source.getWidth();
    int x = source.getHeight() >= source.getWidth() ?0:(longer-factor)/2;
    int y = source.getHeight() <= source.getWidth() ?0:(longer-factor)/2;
    source = Bitmap.createBitmap(source, x, y, factor, factor);
    source = Bitmap.createScaledBitmap(source, scale, scale, false);
    return source;
}

How do I print the elements of a C++ vector in GDB?

put the following in ~/.gdbinit

define print_vector
    if $argc == 2
        set $elem = $arg0.size()
        if $arg1 >= $arg0.size()
            printf "Error, %s.size() = %d, printing last element:\n", "$arg0", $arg0.size()
            set $elem = $arg1 -1
        end
        print *($arg0._M_impl._M_start + $elem)@1
    else
        print *($arg0._M_impl._M_start)@$arg0.size()
    end
end

document print_vector
Display vector contents
Usage: print_vector VECTOR_NAME INDEX
VECTOR_NAME is the name of the vector
INDEX is an optional argument specifying the element to display
end

After restarting gdb (or sourcing ~/.gdbinit), show the associated help like this

gdb) help print_vector
Display vector contents
Usage: print_vector VECTOR_NAME INDEX
VECTOR_NAME is the name of the vector
INDEX is an optional argument specifying the element to display

Example usage:

(gdb) print_vector videoconfig_.entries 0
$32 = {{subChannelId = 177 '\261', sourceId = 0 '\000', hasH264PayloadInfo = false, bitrate = 0,     payloadType = 68 'D', maxFs = 0, maxMbps = 0, maxFps = 134, encoder = 0 '\000', temporalLayers = 0 '\000'}}

Convert Rtf to HTML

I would check out this tool on CodeProject RTFConverter. This guy gives a great breakdown of how the program works along with details of the conversion.

Writing Your Own RTF Converter