Programs & Examples On #Rss reader

RSS Reader is a client software or a web application which aggregates syndicated web content such as news headlines, blogs, podcasts, and video blogs in one location for easy viewing.

The import android.support cannot be resolved

I have resolved it by deleting android-support-v4.jar from my Project. Because appcompat_v7 already have a copy of it.

If you have already import appcompat_v7 but still the problem doesn't solve. then try it.

Best way to compare two complex objects

Use IEquatable<T> Interface which has a method Equals.

sql searching multiple words in a string

Here is what I uses to search for multiple words in multiple columns - SQL server

Hope my answer help someone :) Thanks

declare @searchTrm varchar(MAX)='one two three ddd 20   30 comment'; 
--select value from STRING_SPLIT(@searchTrm, ' ') where trim(value)<>''
select * from Bols 
WHERE EXISTS (SELECT value  
    FROM STRING_SPLIT(@searchTrm, ' ')  
    WHERE 
        trim(value)<>''
        and(    
        BolNumber like '%'+ value+'%'
        or UserComment like '%'+ value+'%'
        or RequesterId like '%'+ value+'%' )
        )

Set disable attribute based on a condition for Html.TextBoxFor

Another approach is to disable the text box on the client side.

In your case you have only one textbox that you need to disable but consider the case where you have multiple input, select, and textarea fields that yout need to disable.

It is much easier to do it via jquery + (since we can not rely on data coming from the client) add some logic to the controller to prevent these fields from being saved.

Here is an example:

<input id="document_Status" name="document.Status" type="hidden" value="2" />

$(document).ready(function () {

    disableAll();
}

function disableAll() {
  var status = $('#document_Status').val();

  if (status != 0) {
      $("input").attr('disabled', true);
      $("textarea").attr('disabled', true);
      $("select").attr('disabled', true);
  }
}

Easy way to convert Iterable to Collection

I use FluentIterable.from(myIterable).toList() a lot.

Why does git revert complain about a missing -m option?

Say the other guy created bar on top of foo, but you created baz in the meantime and then merged, giving a history of

$ git lola
*   2582152 (HEAD, master) Merge branch 'otherguy'
|\  
| * c7256de (otherguy) bar
* | b7e7176 baz
|/  
* 9968f79 foo

Note: git lola is a non-standard but useful alias.

No dice with git revert:

$ git revert HEAD
fatal: Commit 2582152... is a merge but no -m option was given.

Charles Bailey gave an excellent answer as usual. Using git revert as in

$ git revert --no-edit -m 1 HEAD
[master e900aad] Revert "Merge branch 'otherguy'"
 0 files changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 bar

effectively deletes bar and produces a history of

$ git lola
* e900aad (HEAD, master) Revert "Merge branch 'otherguy'"
*   2582152 Merge branch 'otherguy'
|\  
| * c7256de (otherguy) bar
* | b7e7176 baz
|/  
* 9968f79 foo

But I suspect you want to throw away the merge commit:

$ git reset --hard HEAD^
HEAD is now at b7e7176 baz

$ git lola
* b7e7176 (HEAD, master) baz
| * c7256de (otherguy) bar
|/  
* 9968f79 foo

As documented in the git rev-parse manual

<rev>^, e.g. HEAD^, v1.5.1^0
A suffix ^ to a revision parameter means the first parent of that commit object. ^<n> means the n-th parent (i.e. <rev>^ is equivalent to <rev>^1). As a special rule, <rev>^0 means the commit itself and is used when <rev> is the object name of a tag object that refers to a commit object.

so before invoking git reset, HEAD^ (or HEAD^1) was b7e7176 and HEAD^2 was c7256de, i.e., respectively the first and second parents of the merge commit.

Be careful with git reset --hard because it can destroy work.

Relational Database Design Patterns?

After many years of database development I can say there are some no goes and some question that you should answer before you begin:

questions:

  • Do you want use in the future another DBMS? If yes then does not use to special SQL stuff of the current DBMS. Remove logic in your application.

Does not use:

  • white spaces in table names and column names
  • Non Ascii characters in table and column names
  • binding to a specific lower case or upper case. And never use 2 tables or columns that differ only with lower case and upper case.
  • does not use SQL keywords for tables or columns names like "FROM", "BETWEEN", "DELETE", etc

recomendations:

  • Use NVARCHAR or equivalents for unicode support then you have no problems with codepages.
  • Give every column a unique name. This make it easer on join to select the column. It is very difficult if every table has a column "ID" or "Name" or "Description". Use XyzID and AbcID.
  • Use a resource bundle or equals for complex SQL expressions. It make it easer to switch to another DBMS.
  • Does not cast hard on any data type. Another DBMS can not have this data type. FOr example Oracle daes not have a SMALLINT only a number.

I hope this is a good starting point.

How to loop through a dataset in powershell?

Here's a practical example (build a dataset from your current location):

$ds = new-object System.Data.DataSet
$ds.Tables.Add("tblTest")
[void]$ds.Tables["tblTest"].Columns.Add("Name",[string])
[void]$ds.Tables["tblTest"].Columns.Add("Path",[string])

dir | foreach {
    $dr = $ds.Tables["tblTest"].NewRow()
    $dr["Name"] = $_.name
    $dr["Path"] = $_.fullname
    $ds.Tables["tblTest"].Rows.Add($dr)
}


$ds.Tables["tblTest"]

$ds.Tables["tblTest"] is an object that you can manipulate just like any other Powershell object:

$ds.Tables["tblTest"] | foreach {
    write-host 'Name value is : $_.name
    write-host 'Path value is : $_.path
}

What's the point of the X-Requested-With header?

Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.

Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.

Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html

Add to Array jQuery

For JavaScript arrays, you use Both push() and concat() function.

var array = [1, 2, 3];
array.push(4, 5);         //use push for appending a single array.




var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

var array3 = array1.concat(array2);   //It is better use concat for appending more then one array.

Are HTTPS URLs encrypted?

Linking to my answer on a duplicate question. Not only is the URL available in the browsers history, the server side logs but it's also sent as the HTTP Referer header which if you use third party content, exposes the URL to sources outside your control.

HTML not loading CSS file

You have to add type="text/css" you can also specify href="./style.css" which the . specifies the current directory

Using jQuery's ajax method to retrieve images as a blob

If you need to handle error messages using jQuery.AJAX you will need to modify the xhr function so the responseType is not being modified when an error happens.

So you will have to modify the responseType to "blob" only if it is a successful call:

$.ajax({
    ...
    xhr: function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 2) {
                if (xhr.status == 200) {
                    xhr.responseType = "blob";
                } else {
                    xhr.responseType = "text";
                }
            }
        };
        return xhr;
    },
    ...
    error: function(xhr, textStatus, errorThrown) {
        // Here you are able now to access to the property "responseText"
        // as you have the type set to "text" instead of "blob".
        console.error(xhr.responseText);
    },
    success: function(data) {
        console.log(data); // Here is "blob" type
    }
});

Note

If you debug and place a breakpoint at the point right after setting the xhr.responseType to "blob" you can note that if you try to get the value for responseText you will get the following message:

The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

New Intent() starts new instance with Android: launchMode="singleTop"

Quote from the documentation:

The "standard" and "singleTop" modes differ from each other in just one respect: Every time there's new intent for a "standard" activity, a new instance of the class is created to respond to that intent. Each instance handles a single intent. Similarly, a new instance of a "singleTop" activity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created.

I'm not 100% sure what "already has an existing instance of the activity at the top of its stack" means, but perhaps your activity isn't meeting this condition.

Would singleTask or singleInstance work for you? Or perhaps you could try setting FLAG_ACTIVITY_SINGLE_TOP on the intent you are creating to see if that makes a difference, although I don't think it will.

Group by multiple field names in java 8

This is how I did grouping by multiple fields branchCode and prdId, Just posting it for someone in need

    import java.math.BigDecimal;
    import java.math.BigInteger;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;

    /**
     *
     * @author charudatta.joshi
     */
    public class Product1 {

        public BigInteger branchCode;
        public BigInteger prdId;
        public String accountCode;
        public BigDecimal actualBalance;
        public BigDecimal sumActBal;
        public BigInteger countOfAccts;

        public Product1() {
        }

        public Product1(BigInteger branchCode, BigInteger prdId, String accountCode, BigDecimal actualBalance) {
            this.branchCode = branchCode;
            this.prdId = prdId;
            this.accountCode = accountCode;
            this.actualBalance = actualBalance;
        }

        public BigInteger getCountOfAccts() {
            return countOfAccts;
        }

        public void setCountOfAccts(BigInteger countOfAccts) {
            this.countOfAccts = countOfAccts;
        }

        public BigDecimal getSumActBal() {
            return sumActBal;
        }

        public void setSumActBal(BigDecimal sumActBal) {
            this.sumActBal = sumActBal;
        }

        public BigInteger getBranchCode() {
            return branchCode;
        }

        public void setBranchCode(BigInteger branchCode) {
            this.branchCode = branchCode;
        }

        public BigInteger getPrdId() {
            return prdId;
        }

        public void setPrdId(BigInteger prdId) {
            this.prdId = prdId;
        }

        public String getAccountCode() {
            return accountCode;
        }

        public void setAccountCode(String accountCode) {
            this.accountCode = accountCode;
        }

        public BigDecimal getActualBalance() {
            return actualBalance;
        }

        public void setActualBalance(BigDecimal actualBalance) {
            this.actualBalance = actualBalance;
        }

        @Override
        public String toString() {
            return "Product{" + "branchCode:" + branchCode + ", prdId:" + prdId + ", accountCode:" + accountCode + ", actualBalance:" + actualBalance + ", sumActBal:" + sumActBal + ", countOfAccts:" + countOfAccts + '}';
        }

        public static void main(String[] args) {
            List<Product1> al = new ArrayList<Product1>();
            System.out.println(al);
            al.add(new Product1(new BigInteger("01"), new BigInteger("11"), "001", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("01"), new BigInteger("11"), "002", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("01"), new BigInteger("12"), "003", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("01"), new BigInteger("12"), "004", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("01"), new BigInteger("12"), "005", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("01"), new BigInteger("13"), "006", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("02"), new BigInteger("11"), "007", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("02"), new BigInteger("11"), "008", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("02"), new BigInteger("12"), "009", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("02"), new BigInteger("12"), "010", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("02"), new BigInteger("12"), "011", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("02"), new BigInteger("13"), "012", new BigDecimal("10")));
            //Map<BigInteger, Long> counting = al.stream().collect(Collectors.groupingBy(Product1::getBranchCode, Collectors.counting()));
            // System.out.println(counting);

            //group by branch code
            Map<BigInteger, List<Product1>> groupByBrCd = al.stream().collect(Collectors.groupingBy(Product1::getBranchCode, Collectors.toList()));
            System.out.println("\n\n\n" + groupByBrCd);

             Map<BigInteger, List<Product1>> groupByPrId = null;
              // Create a final List to show for output containing one element of each group
            List<Product> finalOutputList = new LinkedList<Product>();
            Product newPrd = null;
            // Iterate over resultant  Map Of List
            Iterator<BigInteger> brItr = groupByBrCd.keySet().iterator();
            Iterator<BigInteger> prdidItr = null;    



            BigInteger brCode = null;
            BigInteger prdId = null;

            Map<BigInteger, List<Product>> tempMap = null;
            List<Product1> accListPerBr = null;
            List<Product1> accListPerBrPerPrd = null;

            Product1 tempPrd = null;
            Double sum = null;
            while (brItr.hasNext()) {
                brCode = brItr.next();
                //get  list per branch
                accListPerBr = groupByBrCd.get(brCode);

                // group by br wise product wise
                groupByPrId=accListPerBr.stream().collect(Collectors.groupingBy(Product1::getPrdId, Collectors.toList()));

                System.out.println("====================");
                System.out.println(groupByPrId);

                prdidItr = groupByPrId.keySet().iterator();
                while(prdidItr.hasNext()){
                    prdId=prdidItr.next();
                    // get list per brcode+product code
                    accListPerBrPerPrd=groupByPrId.get(prdId);
                    newPrd = new Product();
                     // Extract zeroth element to put in Output List to represent this group
                    tempPrd = accListPerBrPerPrd.get(0);
                    newPrd.setBranchCode(tempPrd.getBranchCode());
                    newPrd.setPrdId(tempPrd.getPrdId());

                    //Set accCOunt by using size of list of our group
                    newPrd.setCountOfAccts(BigInteger.valueOf(accListPerBrPerPrd.size()));
                    //Sum actual balance of our  of list of our group 
                    sum = accListPerBrPerPrd.stream().filter(o -> o.getActualBalance() != null).mapToDouble(o -> o.getActualBalance().doubleValue()).sum();
                    newPrd.setSumActBal(BigDecimal.valueOf(sum));
                    // Add product element in final output list

                    finalOutputList.add(newPrd);

                }

            }

            System.out.println("+++++++++++++++++++++++");
            System.out.println(finalOutputList);

        }
    }

Output is as below:

+++++++++++++++++++++++
[Product{branchCode:1, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2}, Product{branchCode:1, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3}, Product{branchCode:1, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}, Product{branchCode:2, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2}, Product{branchCode:2, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3}, Product{branchCode:2, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}]

After Formatting it :

[
Product{branchCode:1, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2}, 
Product{branchCode:1, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3}, 
Product{branchCode:1, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}, 
Product{branchCode:2, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2}, 
Product{branchCode:2, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3}, 
Product{branchCode:2, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}
]

Regex: Remove lines containing "help", etc

If you're on Windows, try findstr. Third-party tools are not needed:

findstr /V /L "searchstring" inputfile.txt > outputfile.txt

It supports regex's too! Just read the tool's help findstr /?.

P.S. If you want to work with big, huge files (like 400 MB log files) a text editor is not very memory-efficient, so, as someone already pointed out, command-line tools are the way to go. But there's no grep on Windows, so...

I just ran this on a 1 GB log file, and it literally took 3 seconds.

How to delete duplicate rows in SQL Server?

You need to group by the duplicate records according to the field(s), then hold one of the records and delete the rest. For example:

DELETE prg.Person WHERE Id IN (
SELECT dublicateRow.Id FROM
(
select MIN(Id) MinId, NationalCode
 from  prg.Person group by NationalCode  having count(NationalCode ) > 1
 ) GroupSelect
 JOIN  prg.Person dublicateRow ON dublicateRow.NationalCode = GroupSelect.NationalCode 
 WHERE dublicateRow.Id <> GroupSelect.MinId)

Iterating through a list in reverse order in java

Very simple Example:

List<String> list = new ArrayList<String>();

list.add("ravi");

list.add("kant");

list.add("soni");

// Iterate to disply : result will be as ---     ravi kant soni

for (String name : list) {
  ...
}

//Now call this method

Collections.reverse(list);

// iterate and print index wise : result will be as ---     soni kant ravi

for (String name : list) {
  ...
}

How to convert const char* to char* in C?

You can cast it by doing (char *)Identifier_Of_Const_char

But as there is probabbly a reason that the api doesn't accept const cahr *, you should do this only, if you are sure, the function doesn't try to assign any value in range of your const char* which you casted to a non const one.

Print all but the first three columns

Try this:

awk '{ $1=""; $2=""; $3=""; print $0 }'

How to put scroll bar only for modal-body?

If you're only supporting IE 9 or higher, you can use this CSS that will smoothly scale to the size of the window. You may need to tweak the "200px" though, depending on the height of your header or footer.

.modal-body{
    max-height: calc(100vh - 200px);
    overflow-y: auto;
}

How to resize JLabel ImageIcon?

Resizing the icon is not straightforward. You need to use Java's graphics 2D to scale the image. The first parameter is a Image class which you can easily get from ImageIcon class. You can use ImageIcon class to load your image file and then simply call getter method to get the image.

private Image getScaledImage(Image srcImg, int w, int h){
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = resizedImg.createGraphics();

    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();

    return resizedImg;
}

Failed to find 'ANDROID_HOME' environment variable

This solved my problem. Add below to your system path

PATH_TO_android\platforms

PATH_TO_android\platform-tools

Shell script to copy files from one location to another location and rename add the current date to every file

cp --archive home/webapps/project1/folder1/{aaa,bbb,ccc,ddd}.csv home/webapps/project1/folder2
rename 's/\.csv$/'$(date +%m%d%Y).csv'/' home/webapps/project1/folder2/{aaa,bbb,ccc,ddd}.csv

Explanation:

  • --archive ensures that the files are copied with the same ownership and permissions.
  • foo{bar,baz} is expanded into foobar foobaz.
  • rename is a commonly available program to do exactly this kind of substitution.

PS: don't use ls for this.

How to see the CREATE VIEW code for a view in PostgreSQL?

These is a little thing to point out.
Using the function pg_get_viewdef or pg_views or information_schema.views you will always get a rewrited version of your original DDL.
The rewited version may or not be the same as your originl DDL script.

If the Rule Manager rewrite your view definition your original DLL will be lost and you will able to read the only the rewrited version of your view definition.
Not all views are rewrited but if you use sub-select or joins probably your views will be rewrited.

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

The supplied host is not resolving for me (custom DNS or self configured host?) so I can only hazard to guess.

But as you are requesting the resources over SSL it is likely the certificate is invalid. Either it is self-signed and has not been added to your browser/OS exceptions or it is otherwise invalid.

Try the URI directly in the same browser and inspect the certificate.

Edit: this is in no way related to jQuery, JavaScript or CSS directly.

How to split csv whose columns may contain ,

With Cinchoo ETL - an open source library, it can automatically handles columns values containing separators.

string csv = @"2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,""Corvallis, OR"",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";

using (var p = ChoCSVReader.LoadText(csv)
    )
{
    Console.WriteLine(p.Dump());
}

Output:

Key: Column1 [Type: String]
Value: 2
Key: Column2 [Type: String]
Value: 1016
Key: Column3 [Type: String]
Value: 7/31/2008 14:22
Key: Column4 [Type: String]
Value: Geoff Dalgas
Key: Column5 [Type: String]
Value: 6/5/2011 22:21
Key: Column6 [Type: String]
Value: http://stackoverflow.com
Key: Column7 [Type: String]
Value: Corvallis, OR
Key: Column8 [Type: String]
Value: 7679
Key: Column9 [Type: String]
Value: 351
Key: Column10 [Type: String]
Value: 81
Key: Column11 [Type: String]
Value: b437f461b3fd27387c5d8ab47a293d35
Key: Column12 [Type: String]
Value: 34

For more information, please visit codeproject article.

Hope it helps.

How to set some xlim and ylim in Seaborn lmplot facetgrid

The lmplot function returns a FacetGrid instance. This object has a method called set, to which you can pass key=value pairs and they will be set on each Axes object in the grid.

Secondly, you can set only one side of an Axes limit in matplotlib by passing None for the value you want to remain as the default.

Putting these together, we have:

g = sns.lmplot('X', 'Y', df, col='Z', sharex=False, sharey=False)
g.set(ylim=(0, None))

enter image description here

Max or Default?

Just to let everyone out there know that is using Linq to Entities the methods above will not work...

If you try to do something like

var max = new[]{0}
      .Concat((From y In context.MyTable _
               Where y.MyField = value _
               Select y.MyCounter))
      .Max();

It will throw an exception:

System.NotSupportedException: The LINQ expression node type 'NewArrayInit' is not supported in LINQ to Entities..

I would suggest just doing

(From y In context.MyTable _
                   Where y.MyField = value _
                   Select y.MyCounter))
          .OrderByDescending(x=>x).FirstOrDefault());

And the FirstOrDefault will return 0 if your list is empty.

Function that creates a timestamp in c#

If you want timestamps that correspond to actual real times BUT also want them to be unique (for a given application instance), you can use the following code:

public class HiResDateTime
{
   private static long lastTimeStamp = DateTime.UtcNow.Ticks;
   public static long UtcNowTicks
   {
       get
       {
           long orig, newval;
           do
           {
               orig = lastTimeStamp;
               long now = DateTime.UtcNow.Ticks;
               newval = Math.Max(now, orig + 1);
           } while (Interlocked.CompareExchange
                        (ref lastTimeStamp, newval, orig) != orig);

           return newval;
       }
   }
}

"git pull" or "git merge" between master and development branches

This workflow works best for me:

git checkout -b develop

...make some changes...

...notice master has been updated...

...commit changes to develop...

git checkout master
git pull

...bring those changes back into develop...

git checkout develop
git rebase master

...make some more changes...

...commit them to develop...

...merge them into master...

git checkout master
git pull
git merge develop

Combine multiple JavaScript files into one JS file

This may be a bit of effort but you could download my open-source wiki project from codeplex:

http://shuttlewiki.codeplex.com

It contains a CompressJavascript project (and CompressCSS) that uses the http://yuicompressor.codeplex.com/ project.

The code should be self-explanatory but it makes combining and compressing the files a bit simnpler --- for me anyway :)

The ShuttleWiki project shows how to use it in the post-build event.

How to get the current loop index when using Iterator?

Here's a way to do it using your own variable and keeping it concise:

List<String> list = Arrays.asList("zero", "one", "two");

int i = 0;
for (Iterator<String> it = list.iterator(); it.hasNext(); i++) {
    String s = it.next();
    System.out.println(i + ": " + s);
}

Output (you guessed it):

0: zero
1: one
2: two

The advantage is that you don't increment your index within the loop (although you need to be careful to only call Iterator#next once per loop - just do it at the top).

how to delete a specific row in codeigniter?

It will come in the url so you can get it by two ways. Fist one

<td><?php echo anchor('textarea/delete_row', 'DELETE', 'id="$row->id"'); ?></td>
$id = $this->input->get('id');

2nd one.

$id = $this->uri->segment(3);

But in the second method you have to count the no. of segments in the url that on which no. your id come. 2,3,4 etc. then you have to pass. then in the ();

SQL: How To Select Earliest Row

Simply use min()

SELECT company, workflow, MIN(date) 
FROM workflowTable 
GROUP BY company, workflow

Make Vim show ALL white spaces as a character

highlight search

:set hlsearch 

in .vimrc that is

and search for space tabs and carriage returns

/ \|\t\|\r

or search for all whitespace characters

/\s

of search for all non white space characters (the whitespace characters are not shown, so you see the whitespace characters between words, but not the trailing whitespace characters)

/\S

to show all trailing white space characters - at the end of the line

/\s$

Add Favicon with React and Webpack

I will give simple steps to add favicon :-)

  • Create your logo and save as logo.png
  • Change logo.png to favicon.ico

    Note : when you save it is favicon.ico make sure it's not favicon.ico.png

  • It might take some time to update

    change icon size in manifest.json if you can't wait

How to capture multiple repeated groups?

Just to provide additional example of paragraph 2 in the answer. I'm not sure how critical it is for you to get three groups in one match rather than three matches using one group. E.g., in groovy:

def subject = "HELLO,THERE,WORLD"
def pat = "([A-Z]+)"
def m = (subject =~ pat)
m.eachWithIndex{ g,i ->
  println "Match #$i: ${g[1]}"
}

Match #0: HELLO
Match #1: THERE
Match #2: WORLD

Entity Framework Queryable async

There is a massive difference in the example you have posted, the first version:

var urls = await context.Urls.ToListAsync();

This is bad, it basically does select * from table, returns all results into memory and then applies the where against that in memory collection rather than doing select * from table where... against the database.

The second method will not actually hit the database until a query is applied to the IQueryable (probably via a linq .Where().Select() style operation which will only return the db values which match the query.

If your examples were comparable, the async version will usually be slightly slower per request as there is more overhead in the state machine which the compiler generates to allow the async functionality.

However the major difference (and benefit) is that the async version allows more concurrent requests as it doesn't block the processing thread whilst it is waiting for IO to complete (db query, file access, web request etc).

How to get changes from another branch

git fetch origin our-team

or

git pull origin our-team

but first you should make sure that you already on the branch you want to update to (featurex).

How can I use the python HTMLParser library to extract data from a specific div tag?

This works perfectly:

print (soup.find('the tag').text)

Get nth character of a string in Swift programming language

I just had the same issue. Simply do this:

var aString: String = "test"
var aChar:unichar = (aString as NSString).characterAtIndex(0)

filter out multiple criteria using excel vba

I don't have found any solution on Internet, so I have implemented one.

The Autofilter code with criteria is then

iColNumber = 1
Dim aFilterValueArray() As Variant
Call ConstructFilterValueArray(aFilterValueArray, iColNumber, Array("A", "B", "C"))

ActiveSheet.range(sRange).AutoFilter Field:=iColNumber _
    , Criteria1:=aFilterValueArray _
    , Operator:=xlFilterValues

In fact, the ConstructFilterValueArray() method (not function) get all distinct values that it found in a specific column and remove all values present in last argument.

The VBA code of this method is

'************************************************************
'* ConstructFilterValueArray()
'************************************************************

Sub ConstructFilterValueArray(a() As Variant, iCol As Integer, aRemoveArray As Variant)

    Dim aValue As New Collection
    Call GetDistinctColumnValue(aValue, iCol)
    Call RemoveValueList(aValue, aRemoveArray)
    Call CollectionToArray(a, aValue)

End Sub

'************************************************************
'* GetDistinctColumnValue()
'************************************************************

Sub GetDistinctColumnValue(ByRef aValue As Collection, iCol As Integer)

    Dim sValue As String

    iEmptyValueCount = 0
    iLastRow = ActiveSheet.UsedRange.Rows.Count

    Dim oSheet: Set oSheet = Sheets("X")

    Sheets("Data")
        .range(Cells(1, iCol), Cells(iLastRow, iCol)) _
            .AdvancedFilter Action:=xlFilterCopy _
                          , CopyToRange:=oSheet.range("A1") _
                          , Unique:=True

    iRow = 2
    Do While True
        sValue = Trim(oSheet.Cells(iRow, 1))
        If sValue = "" Then
            If iEmptyValueCount > 0 Then
                Exit Do
            End If
            iEmptyValueCount = iEmptyValueCount + 1
        End If

        aValue.Add sValue
        iRow = iRow + 1
    Loop

End Sub

'************************************************************
'* RemoveValueList()
'************************************************************

Sub RemoveValueList(ByRef aValue As Collection, aRemoveArray As Variant)

    For i = LBound(aRemoveArray) To UBound(aRemoveArray)
        sValue = aRemoveArray(i)
        iMax = aValue.Count
        For j = iMax To 0 Step -1
            If aValue(j) = sValue Then
                aValue.Remove (j)
                Exit For
            End If
        Next j
     Next i

End Sub

'************************************************************
'* CollectionToArray()
'************************************************************

Sub CollectionToArray(a() As Variant, c As Collection)

    iSize = c.Count - 1
    ReDim a(iSize)

    For i = 0 To iSize
        a(i) = c.Item(i + 1)
    Next

End Sub

This code can certainly be improved in returning an Array of String but working with Array in VBA is not easy.

CAUTION: this code work only if you define a sheet named X because CopyToRange parameter used in AdvancedFilter() need an Excel Range !

It's a shame that Microfsoft doesn't have implemented this solution in adding simply a new enum as xlNotFilterValues ! ... or xlRegexMatch !

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

Check space of your database.this error comes when space increased compare to space given to database.

How to use the 'main' parameter in package.json?

As far as I know, it's the main entry point to your node package (library) for npm. It's needed if your npm project becomes a node package (library) which can be installed via npm by others.


Let's say you have a library with a build/, dist/, or lib/ folder. In this folder, you got the following compiled file for your library:

-lib/
--bundle.js

Then in your package.json, you tell npm how to access the library (node package):

{
  "name": "my-library-name",
  "main": "lib/bundle.js",
  ...
}

After installing the node package with npm to your JS project, you can import functionalities from your bundled bundle.js file:

import { add, subtract } from 'my-library-name';

This holds also true when using Code Splitting (e.g. Webpack) for your library. For instance, this webpack.config.js makes use of code splitting the project into multiple bundles instead of one.

module.exports = {
  entry: {
    main: './src/index.js',
    add: './src/add.js',
    subtract: './src/subtract.js',
  },
  output: {
    path: `${__dirname}/lib`,
    filename: '[name].js',
    library: 'my-library-name',
    libraryTarget: 'umd',
  },
  ...
}

Still, you would define one main entry point to your library in your package.json:

{
  "name": "my-library-name",
  "main": "lib/main.js",
  ...
}

Then when using the library, you can import your files from your main entry point:

import { add, subtract } from 'my-library-name';

However, you can also bypass the main entry point from the package.json and import the code splitted bundles:

import add from 'my-library-name/lib/add';
import subtract from 'my-library-name/lib/subtract';

After all, the main property in your package.json only points to your main entry point file of your library.

How do I dynamically change the content in an iframe using jquery?

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script>
      $(document).ready(function(){
        var locations = ["http://webPage1.com", "http://webPage2.com"];
        var len = locations.length;
        var iframe = $('#frame');
        var i = 0;
        setInterval(function () {
            iframe.attr('src', locations[++i % len]);
        }, 30000);
      });
    </script>
  </head>
  <body>
    <iframe id="frame"></iframe>
  </body>
</html>

How to read/write a boolean when implementing the Parcelable interface?

This question has already been answered perfectly by other people, if you want to do it on your own.

If you prefer to encapsulate or hide away most of the low-level parceling code, you might consider using some of the code I wrote some time ago for simplifying handling of parcelables.

Writing to a parcel is as easy as:

parcelValues(dest, name, maxSpeed, weight, wheels, color, isDriving);

where color is an enum and isDriving is a boolean, for example.

Reading from a parcel is also not much harder:

color = (CarColor)unparcelValue(CarColor.class.getClassLoader());
isDriving = (Boolean)unparcelValue();

Just take a look at the "ParceldroidExample" I added to the project.

Finally, it also keeps the CREATOR initializer short:

public static final Parcelable.Creator<Car> CREATOR =
    Parceldroid.getCreatorForClass(Car.class);

C convert floating point to int

double a = 100.3;
printf("%f %d\n", a, (int)(a* 10.0));

Output Cygwin 100.3 1003
Output MinGW: 100.3 1002

Using (int) to convert double to int seems not to be fail-safe

You can find more about that here: Convert double to int?

What is mapDispatchToProps?

mapStateToProps() is a utility which helps your component get updated state(which is updated by some other components),
mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause change of application state)

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

Just Modified the previous example to print even collection containing user defined objects.

public class ToStringHelper {

    private  static String separator = "\n";

    public ToStringHelper(String seperator) {
        super();
        ToStringHelper.separator = seperator;

    }

    public  static String toString(List<?> l) {
        StringBuilder sb = new StringBuilder();
        String sep = "";
        for (Object object : l) {
            String v = ToStringBuilder.reflectionToString(object);
            int start = v.indexOf("[");
            int end = v.indexOf("]");
            String st =  v.substring(start,end+1);
            sb.append(sep).append(st);
            sep = separator;
        }
        return sb.toString();
    }

    public static String toString(Map<?,?> m) {
        StringBuilder sb = new StringBuilder();
        String sep = "";
        for (Object object : m.keySet()) {
            String v = ToStringBuilder.reflectionToString(m.get(object));
            int start = v.indexOf("[");
            int end = v.indexOf("]");
            String st =  v.substring(start,end+1);
            sb.append(sep).append(st);
            sep = separator;
        }
        return sb.toString();
    }

    public static String toString(Set<?> s) {
        StringBuilder sb = new StringBuilder();
        String sep = "";
        for (Object object : s) {
            String v = ToStringBuilder.reflectionToString(object);
            int start = v.indexOf("[");
            int end = v.indexOf("]");
            String st =  v.substring(start,end+1);
            sb.append(sep).append(st);
            sep = separator;
        }
        return sb.toString();
    }

    public static void print(List<?> l) {
        System.out.println(toString(l));    
    }
    public static void print(Map<?,?> m) {
        System.out.println(toString(m));    
    }
    public static void print(Set<?> s) {
        System.out.println(toString(s));    
    }

}

Mockito How to mock only the call of a method of the superclass

The reason is your base class is not public-ed, then Mockito cannot intercept it due to visibility, if you change base class as public, or @Override in sub class (as public), then Mockito can mock it correctly.

public class BaseService{
  public boolean foo(){
    return true;
  }
}

public ChildService extends BaseService{
}

@Test
@Mock ChildService childService;
public void testSave() {
  Mockito.when(childService.foo()).thenReturn(false);

  // When
  assertFalse(childService.foo());
}

Difference between git stash pop and git stash apply

git stash pop throws away the (topmost, by default) stash after applying it, whereas git stash apply leaves it in the stash list for possible later reuse (or you can then git stash drop it).

This happens unless there are conflicts after git stash pop, in which case it will not remove the stash, leaving it to behave exactly like git stash apply.

Another way to look at it: git stash pop is git stash apply && git stash drop.

JavaScript string newline character?

The \n is just fine for all cases I've encountered. I you are working with web, use \n and don't worry about it (unless you have had any newline-related issues).

How can I change the user on Git Bash?

If you want to change the user at git Bash .You just need to configure particular user and email(globally) at the git bash.

$ git config --global user.name "abhi"
$ git config --global user.email "[email protected]"

Note: No need to delete the user from Keychain .

Foreign key referring to primary keys across multiple tables?

Yes, it is possible. You will need to define 2 FKs for 3rd table. Each FK pointing to the required field(s) of one table (ie 1 FK per foreign table).

How to navigate through textfields (Next / Done Buttons)

Hi to everyone please see this one

- (void)nextPrevious:(id)sender
{

  UIView *responder = [self.view findFirstResponder];   

  if (nil == responder || ![responder isKindOfClass:[GroupTextField class]]) {
    return;
  }

  switch([(UISegmentedControl *)sender selectedSegmentIndex]) {
    case 0:
      // previous
      if (nil != ((GroupTextField *)responder).previousControl) {
        [((GroupTextField *)responder).previousControl becomeFirstResponder];
        DebugLog(@"currentControl: %i previousControl: %i",((GroupTextField *)responder).tag,((GroupTextField *)responder).previousControl.tag);
      }
      break;
    case 1:
      // next
      if (nil != ((GroupTextField *)responder).nextControl) {
        [((GroupTextField *)responder).nextControl becomeFirstResponder];
        DebugLog(@"currentControl: %i nextControl: %i",((GroupTextField *)responder).tag,((GroupTextField *)responder).nextControl.tag);
      }     
      break;    
  }
}

S3 Static Website Hosting Route All Paths to Index.html

I ran into the same problem today but the solution of @Mark-Nutter was incomplete to remove the hashbang from my angularjs application.

In fact you have to go to Edit Permissions, click on Add more permissions and then add the right List on your bucket to everyone. With this configuration, AWS S3 will now, be able to return 404 error and then the redirection rule will properly catch the case.

Just like this : enter image description here

And then you can go to Edit Redirection Rules and add this rule :

<RoutingRules>
    <RoutingRule>
        <Condition>
            <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
        </Condition>
        <Redirect>
            <HostName>subdomain.domain.fr</HostName>
            <ReplaceKeyPrefixWith>#!/</ReplaceKeyPrefixWith>
        </Redirect>
    </RoutingRule>
</RoutingRules>

Here you can replace the HostName subdomain.domain.fr with your domain and the KeyPrefix #!/ if you don't use the hashbang method for SEO purpose.

Of course, all of this will only work if you have already have setup html5mode in your angular application.

$locationProvider.html5Mode(true).hashPrefix('!');

Get first and last date of current month with JavaScript or jQuery

I fixed it with Datejs

This is alerting the first day:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);

OSError: [Errno 8] Exec format error

I will hijack this thread to point out that this error may also happen when target of Popen is not executable. Learnt it hard way when by accident I have had override a perfectly executable binary file with zip file.

Center/Set Zoom of Map to cover all visible Markers?

To extend the given answer with few useful tricks:

var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
   bounds.extend(markers[i].getPosition());
}

//center the map to a specific spot (city)
map.setCenter(center); 

//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());

map.fitBounds(bounds);

//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1); 

// set a minimum zoom 
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
  map.setZoom(15);
}

//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
    map.setMaxZoom(15);
    map.fitBounds(bounds);
    map.setMaxZoom(Null)
}

UPDATE:
Further research in the topic show that fitBounds() is a asynchronic and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds

google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
  this.setZoom(map.getZoom()-1);

  if (this.getZoom() > 15) {
    this.setZoom(15);
  }
});
map.fitBounds(bounds);

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub

How does HttpContext.Current.User.Identity.Name know which usernames exist?

Also check that

<modules>
      <remove name="FormsAuthentication"/>
</modules>

If you found anything like this just remove:

<remove name="FormsAuthentication"/>

Line from web.config and here you go it will work fine I have tested it.

How to get response status code from jQuery.ajax?

It is probably more idiomatic jQuery to use the statusCode property of the parameter object passed to the the $.ajax function:

$.ajax({
  statusCode: {
    500: function(xhr) {
      if(window.console) console.log(xhr.responseText);
    }
  }
});

However, as Livingston Samuel said, it is not possible to catch 301 status codes in javascript.

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

Suppose you are usin Jersey 2.25.1, this worked for me - I am using Apache Tomcat web container:

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.25.1</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>2.25.1</version>
    </dependency>

NB: Replace version with the version you are using

Difference between text and varchar (character varying)

A good explanation from http://www.sqlines.com/postgresql/datatypes/text:

The only difference between TEXT and VARCHAR(n) is that you can limit the maximum length of a VARCHAR column, for example, VARCHAR(255) does not allow inserting a string more than 255 characters long.

Both TEXT and VARCHAR have the upper limit at 1 Gb, and there is no performance difference among them (according to the PostgreSQL documentation).

Render a string in HTML and preserve spaces and linebreaks

You would want to replace all spaces with &nbsp; (non-breaking space) and all new lines \n with <br> (line break in html). This should achieve the result you're looking for.

body = body.replace(' ', '&nbsp;').replace('\n', '<br>');

Something of that nature.

Passing parameters to a Bash function

If you prefer named parameters, it's possible (with a few tricks) to actually pass named parameters to functions (also makes it possible to pass arrays and references).

The method I developed allows you to define named parameters passed to a function like this:

function example { args : string firstName , string lastName , integer age } {
  echo "My name is ${firstName} ${lastName} and I am ${age} years old."
}

You can also annotate arguments as @required or @readonly, create ...rest arguments, create arrays from sequential arguments (using e.g. string[4]) and optionally list the arguments in multiple lines:

function example {
  args
    : @required string firstName
    : string lastName
    : integer age
    : string[] ...favoriteHobbies

  echo "My name is ${firstName} ${lastName} and I am ${age} years old."
  echo "My favorite hobbies include: ${favoriteHobbies[*]}"
}

In other words, not only you can call your parameters by their names (which makes up for a more readable core), you can actually pass arrays (and references to variables - this feature works only in Bash 4.3 though)! Plus, the mapped variables are all in the local scope, just as $1 (and others).

The code that makes this work is pretty light and works both in Bash 3 and Bash 4 (these are the only versions I've tested it with). If you're interested in more tricks like this that make developing with bash much nicer and easier, you can take a look at my Bash Infinity Framework, the code below is available as one of its functionalities.

shopt -s expand_aliases

function assignTrap {
  local evalString
  local -i paramIndex=${__paramIndex-0}
  local initialCommand="${1-}"

  if [[ "$initialCommand" != ":" ]]
  then
    echo "trap - DEBUG; eval \"${__previousTrap}\"; unset __previousTrap; unset __paramIndex;"
    return
  fi

  while [[ "${1-}" == "," || "${1-}" == "${initialCommand}" ]] || [[ "${#@}" -gt 0 && "$paramIndex" -eq 0 ]]
  do
    shift # First colon ":" or next parameter's comma ","
    paramIndex+=1
    local -a decorators=()
    while [[ "${1-}" == "@"* ]]
    do
      decorators+=( "$1" )
      shift
    done

    local declaration=
    local wrapLeft='"'
    local wrapRight='"'
    local nextType="$1"
    local length=1

    case ${nextType} in
      string | boolean) declaration="local " ;;
      integer) declaration="local -i" ;;
      reference) declaration="local -n" ;;
      arrayDeclaration) declaration="local -a"; wrapLeft= ; wrapRight= ;;
      assocDeclaration) declaration="local -A"; wrapLeft= ; wrapRight= ;;
      "string["*"]") declaration="local -a"; length="${nextType//[a-z\[\]]}" ;;
      "integer["*"]") declaration="local -ai"; length="${nextType//[a-z\[\]]}" ;;
    esac

    if [[ "${declaration}" != "" ]]
    then
      shift
      local nextName="$1"

      for decorator in "${decorators[@]}"
      do
        case ${decorator} in
          @readonly) declaration+="r" ;;
          @required) evalString+="[[ ! -z \$${paramIndex} ]] || echo \"Parameter '$nextName' ($nextType) is marked as required by '${FUNCNAME[1]}' function.\"; " >&2 ;;
          @global) declaration+="g" ;;
        esac
      done

      local paramRange="$paramIndex"

      if [[ -z "$length" ]]
      then
        # ...rest
        paramRange="{@:$paramIndex}"
        # trim leading ...
        nextName="${nextName//\./}"
        if [[ "${#@}" -gt 1 ]]
        then
          echo "Unexpected arguments after a rest array ($nextName) in '${FUNCNAME[1]}' function." >&2
        fi
      elif [[ "$length" -gt 1 ]]
      then
        paramRange="{@:$paramIndex:$length}"
        paramIndex+=$((length - 1))
      fi

      evalString+="${declaration} ${nextName}=${wrapLeft}\$${paramRange}${wrapRight}; "

      # Continue to the next parameter:
      shift
    fi
  done
  echo "${evalString} local -i __paramIndex=${paramIndex};"
}

alias args='local __previousTrap=$(trap -p DEBUG); trap "eval \"\$(assignTrap \$BASH_COMMAND)\";" DEBUG;'

Reset auto increment counter in postgres

Use this query to check what is the Sequence Key with Schema and Table,

SELECT pg_get_serial_sequence('"SchemaName"."TableName"', 'KeyColumnName'); // output: "SequenceKey"

Use this query increase increment value one by one,

SELECT nextval('"SchemaName"."SequenceKey"'::regclass); // output 110

When inserting to table next incremented value will be used as the key (111).

Use this query to set specific value as the incremented value

SELECT setval('"SchemaName"."SequenceKey"', 120);

When inserting to table next incremented value will be used as the key (121).

Generate list of all possible permutations of a string

c# iterative:

public List<string> Permutations(char[] chars)
    {
        List<string> words = new List<string>();
        words.Add(chars[0].ToString());
        for (int i = 1; i < chars.Length; ++i)
        {
            int currLen = words.Count;
            for (int j = 0; j < currLen; ++j)
            {
                var w = words[j];
                for (int k = 0; k <= w.Length; ++k)
                {
                    var nstr = w.Insert(k, chars[i].ToString());
                    if (k == 0)
                        words[j] = nstr;
                    else
                        words.Add(nstr);
                }
            }
        }
        return words;
    }

Reading rather large json files in Python

The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.

The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.

The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.

Edit: Also worth a look - kashif's comment about json-streamer and Henrik Heino's comment about bigjson.

Sleep function in ORACLE

From Oracle 18c you could use DBMS_SESSION.SLEEP procedure:

This procedure suspends the session for a specified period of time.

DBMS_SESSION.SLEEP (seconds  IN NUMBER)

DBMS_SESSION.sleep is available to all sessions with no additional grants needed. Please note that DBMS_LOCK.sleep is deprecated.

If you need simple query sleep you could use WITH FUNCTION:

WITH FUNCTION my_sleep(i NUMBER)
RETURN NUMBER
BEGIN
    DBMS_SESSION.sleep(i);
    RETURN i;
END;
SELECT my_sleep(3) FROM dual;

How to link html pages in same or different folders?

If you'd like to link to the root directory you can use

/, or /index.html

If you'd like to link to a file in the same directory, simply put the file name

<a href="/employees.html">Employees Click Here</a>

To move back a folder, you can use

../

To link to the index page in the employees directory from the root directory, you'd do this

<a href="../employees/index.html">Employees Directory Index Page</a>

What is this weird colon-member (" : ") syntax in the constructor?

It's an initialization list for the constructor. Instead of default constructing x, y and z and then assigning them the values received in the parameters, those members will be initialized with those values right off the bat. This may not seem terribly useful for floats, but it can be quite a timesaver with custom classes that are expensive to construct.

How to change theme for AlertDialog

Anyone trying to do this within a Fragment (using the support library i.e. pre API 11) should go with this:

public class LoadingDialogFragment extends DialogFragment {
    public static final String ID = "loadingDialog";

    public static LoadingDialogFragment newInstance() {
        LoadingDialogFragment f = new LoadingDialogFragment();

        return f;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        StyleAlertDialog adb = new StyleAlertDialog(getActivity(), R.style.Your_Style);
        adb.setView(getActivity().getLayoutInflater().inflate(R.layout.fragment_dialog_layout, null));
        return adb;
    }

    private class StyleAlertDialog extends AlertDialog {
        protected StyleAlertDialog(Context context, int theme) {
            super(context, theme);
        }
    }
}

@Rflexor gave me the nudge to extend AlertDialog and expose the constructor thanks

Bootstrap 3 truncate long text inside rows of a table in a responsive way

This is what I achieved, but had to set width, and it cannot be percentual.

_x000D_
_x000D_
.trunc{_x000D_
  width:250px; _x000D_
  white-space: nowrap; _x000D_
  overflow: hidden; _x000D_
  text-overflow: ellipsis;_x000D_
}_x000D_
table tr td {_x000D_
padding: 5px_x000D_
}_x000D_
table tr td {_x000D_
background: salmon_x000D_
}_x000D_
table tr td:first-child {_x000D_
background: lightsalmon_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<table>_x000D_
      _x000D_
      <tr>_x000D_
        <td>Quisque dignissim ante in tincidunt gravida. Maecenas lectus turpis</td>_x000D_
      <td>_x000D_
         <div class="trunc">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
         </div>_x000D_
    </td>_x000D_
        </tr>_x000D_
      </table>
_x000D_
_x000D_
_x000D_

or this: http://collaboradev.com/2015/03/28/responsive-css-truncate-and-ellipsis/

How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

Note that You should free the memory only after you are done with your usage of the allocated pointers.

memory allocation for 1D arrays:

    buffer = malloc(num_items*sizeof(double));

memory deallocation for 1D arrays:

    free(buffer);

memory allocation for 2D arrays:

    double **cross_norm=(double**)malloc(150 * sizeof(double *));
    for(i=0; i<150;i++)
    {
        cross_norm[i]=(double*)malloc(num_items*sizeof(double));
    }

memory deallocation for 2D arrays:

    for(i=0; i<150;i++)
    {
        free(cross_norm[i]);
    }

    free(cross_norm);

Default values for Vue component props & how to check if a user did not set the prop?

Vue allows for you to specify a default prop value and type directly, by making props an object (see: https://vuejs.org/guide/components.html#Prop-Validation):

props: {
  year: {
    default: 2016,
    type: Number
  }
}

If the wrong type is passed then it throws an error and logs it in the console, here's the fiddle:

https://jsfiddle.net/cexbqe2q/

Send POST data using XMLHttpRequest

There's some duplicates that touch on this, and nobody really expounds on it. I'll borrow the accepted answer example to illustrate

http.open('POST', url, true);
http.send('lorem=ipsum&name=binny');

I oversimplified this (I use http.onload(function() {}) instead of that answer's older methodology) for the sake of illustration. If you use this as-is, you'll find your server is probably interpreting the POST body as a string and not actual key=value parameters (i.e. PHP won't show any $_POST variables). You must pass the form header in to get that, and do that before http.send()

http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

If you're using JSON and not URL-encoded data, pass application/json instead

How do I select last 5 rows in a table without sorting?

Suppose you have an index on id, this will be lightning fast:

SELECT * FROM [MyTable] WHERE [id] > (SELECT MAX([id]) - 5 FROM [MyTable])

How to import component into another root component in Angular 2

For Angular RC5 and RC6 you have to declare component in the module metadata decorator's declarations key, so add CoursesComponent in your main module declarations as below and remove directives from AppComponent metadata.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, CoursesComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

How to install VS2015 Community Edition offline

For the latest VS2015 sp3, the command line shoud be:

en_visual_studio_community_2015_with_update_3_x86_x64_web_installer_8922963.exe /Layout c:\VS2015sp3_offline

How to change the color of winform DataGridview header?

dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

How to redirect from one URL to another URL?

you can also use a meta tag to redirect to another url.

<meta http-equiv="refresh" content="2;url=http://webdesign.about.com/">

http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm

How do I get the XML SOAP request of an WCF Web service request?

I think you meant that you want to see the XML at the client, not trace it at the server. In that case, your answer is in the question I linked above, and also at How to Inspect or Modify Messages on the Client. But, since the .NET 4 version of that article is missing its C#, and the .NET 3.5 example has some confusion (if not a bug) in it, here it is expanded for your purpose.

You can intercept the message before it goes out using an IClientMessageInspector:

using System.ServiceModel.Dispatcher;
public class MyMessageInspector : IClientMessageInspector
{ }

The methods in that interface, BeforeSendRequest and AfterReceiveReply, give you access to the request and reply. To use the inspector, you need to add it to an IEndpointBehavior:

using System.ServiceModel.Description;
public class InspectorBehavior : IEndpointBehavior
{
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new MyMessageInspector());
    }
}

You can leave the other methods of that interface as empty implementations, unless you want to use their functionality, too. Read the how-to for more details.

After you instantiate the client, add the behavior to the endpoint. Using default names from the sample WCF project:

ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
client.Endpoint.Behaviors.Add(new InspectorBehavior());
client.GetData(123);

Set a breakpoint in MyMessageInspector.BeforeSendRequest(); request.ToString() is overloaded to show the XML.

If you are going to manipulate the messages at all, you have to work on a copy of the message. See Using the Message Class for details.

Thanks to Zach Bonham's answer at another question for finding these links.

moment.js, how to get day of week number

From the docs page, notice they have these helpful headers

http://momentjs.com/docs/#/get-set/weekday/
(I didn't see them at first)

With header sections for:

  • Date of Month
  • Day of Week
  • etc

.

  var now = moment();
  var day  = now.day();
  var date = now.date(); // Number

How to destroy Fragment?

If you are in the fragment itself, you need to call this. Your fragment needs to be the fragment that is being called. Enter code:

getFragmentManager().beginTransaction().remove(yourFragment).commitAllowingStateLoss();

or if you are using supportLib, then you need to call:

getSupportFragmentManager().beginTransaction().remove(yourFragment).commitAllowingStateLoss();

.htaccess 301 redirect of single page

redirect 301 /contact.php /contact-us.php

There is no point using the redirectmatch rule and then have to write your links so they are exact match. If you don't include you don't have to exclude! Just use redirect without match and then use links normally

Java String declaration

String s1 = "Welcome"; // Does not create a new instance  
String s2 = new String("Welcome"); // Creates two objects and one reference variable  

How can you debug a CORS request with cURL?

Here's how you can debug CORS requests using curl.

Sending a regular CORS request using cUrl:

curl -H "Origin: http://example.com" --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

The -H "Origin: http://example.com" flag is the third party domain making the request. Substitute in whatever your domain is.

The --verbose flag prints out the entire response so you can see the request and response headers.

The url I'm using above is a sample request to a Google API that supports CORS, but you can substitute in whatever url you are testing.

The response should include the Access-Control-Allow-Origin header.

Sending a preflight request using cUrl:

curl -H "Origin: http://example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: X-Requested-With" \
  -X OPTIONS --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

This looks similar to the regular CORS request with a few additions:

The -H flags send additional preflight request headers to the server

The -X OPTIONS flag indicates that this is an HTTP OPTIONS request.

If the preflight request is successful, the response should include the Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers response headers. If the preflight request was not successful, these headers shouldn't appear, or the HTTP response won't be 200.

You can also specify additional headers, such as User-Agent, by using the -H flag.

Installing PHP Zip Extension

I tried changing the repository list with:

http://security.ubuntu.com/ubuntu bionic-security main universe http://archive.ubuntu.com/ubuntu bionic main restricted universe

But none of them seem to work, but I finally found a repository that works running the following command

add-apt-repository ppa:ondrej/php

And then updating and installing normally the package using apt-get

As you can see it's installed at last.

Proper way to renew distribution certificate for iOS

As of January 2020 and Xcode 11.3.1 -

  • Open Xcode
  • Open Xcode Preferences (Xcode->Preferences or Cmd-,)
  • Click on Accounts
  • At the left, click on your developer ID
  • At the bottom right, click on Manage Certificates...
  • In the lower left corner, click the arrow to the right of the + (plus)
  • Select Apple Distribution from the menu

Xcode will automatically create an Apple Distribution certificate, install it in Keychain Access, and update Xcode's signing information

(Note: the single Apple Distribution certificate is now provided instead of the previous iOS Distribution certificate and equivalents.)

How to replace an entire line in a text file by line number

Excellent answer from Chepner. It is working for me in bash Shell.

 # To update/replace the new line string value with the exiting line of the file
 MyFile=/tmp/ps_checkdb.flag

 `sed -i "${index}s/.*/${newLine}/" $MyFile`

here
index - Line no
newLine - new line string which we want to replace.


Similarly below code is used to read a particular line in the file. This won't affect the actual file.

LineString=`sed "$index!d" $MyFile` 

here
!d - will delete the lines other than line no $index So we will get the output as line string of no $index in the file.

Writing unit tests in Python: How do I start?

unittest comes with the standard library, but I would recomend you nosetests.

"nose extends unittest to make testing easier."

I would also recomend you pylint

"analyzes Python source code looking for bugs and signs of poor quality."

Font size relative to the user's screen resolution?

I've developed a nice JS solution - which is suitable for entirely-responsive HTML (i.e. HTML built with percentages)

  1. I use only "em" to define font-sizes.

  2. html font size is set to 10 pixels:

    html {
      font-size: 100%;
      font-size: 62.5%;
    }
    
  3. I call a font-resizing function on document-ready:

// this requires JQuery

function doResize() {
    // FONT SIZE
    var ww = $('body').width();
    var maxW = [your design max-width here];
    ww = Math.min(ww, maxW);
    var fw = ww*(10/maxW);
    var fpc = fw*100/16;
    var fpc = Math.round(fpc*100)/100;
    $('html').css('font-size',fpc+'%');
}

Convert ArrayList to String array in Android

You could make an array the same size as the ArrayList and then make an iterated for loop to index the items and insert them into the array.

Can I change the height of an image in CSS :before/:after pseudo-elements?

content: "";
background-image: url("yourimage.jpg");
background-size: 30px, 30px;

css selector to match an element without attribute x

Just wanted to add to this, you can have the :not selector in oldIE using selectivizr: http://selectivizr.com/

How to sort dates from Oldest to Newest in Excel?

Here's how to sort unsorted dates:

Drag down the column to select the dates you want to sort.

Click Home tab > arrow under Sort & Filter, and then click Sort Oldest to Newest, or Sort Newest to Oldest.

NOTE: If the results aren't what you expected, the column might have dates that are stored as text instead of dates. Convert dates stored as text to dates.

JavaScript array to CSV

If your data contains any newlines or commas, you will need to escape those first:

const escape = text =>
    text.replace(/\\/g, "\\\\")
        .replace(/\n/g, "\\n")
        .replace(/,/g, "\\,")

escaped_array = test_array.map(fields => fields.map(escape))

Then simply do:

csv = escaped_array.map(fields => fields.join(","))
                .join("\n")

If you want to make it downloadable in-browser:

dl = "data:text/csv;charset=utf-8," + csv
window.open(encodeURI(dl))

How to serialize an Object into a list of URL query parameters?

Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&')

@UniqueConstraint annotation in Java

Way1 :

@Entity

@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames = "column1"),@UniqueConstraint(columnNames = "column2")})

-- Here both Column1 and Column2 acts as unique constraints separately. Ex : if any time either the value of column1 or column2 value matches then you will get UNIQUE_CONSTRAINT Error.

Way2 :

@Entity

@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames ={"column1","column2"})})

-- Here both column1 and column2 combined values acts as unique constraints

How can I split a string with a string delimiter?

Read C# Split String Examples - Dot Net Pearls and the solution can be something like:

var results = yourString.Split(new string[] { "is Marco and" }, StringSplitOptions.None);

How do I count unique visitors to my site?

I have edited the "Best answer" code, though I found a useful thing that was missing. This is will also track the ip of a user if they are using a Proxy or simply if the server has nginx installed as a proxy reverser.

I added this code to his script at the top of the function:

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$adresseip = getRealIpAddr();

Afther that I edited his code.

Find the line that says the following:

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

and replace it with this:

$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $adresseip. $vst_id;

This will work.

Here is the full code if anything happens:

<?php

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$adresseip = getRealIpAddr();

// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();        // start Session, if not already started

$filetxt = 'userson.txt';  // the file in which the online users /visitors are stored
$timeon = 120;             // number of secconds to keep a user online
$sep = '^^';               // characters used to separate the user name and date-time
$vst_id = '-vst-';        // an identifier to know that it is a visitor, not logged user

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the line with visitors
$nrvst = 0;                                       // to store the number of visitors

// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)

    $addrow[] = $uvon. $sep. time();

// check if the file from $filetxt exists and is writable

    if(is_writable($filetxt)) {
      // get into an array the lines added in $filetxt
      $ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $nrrows = count($ar_rows);

            // number of rows

  // if there is at least one line, parse the $ar_rows array

      if($nrrows>0) {
        for($i=0; $i<$nrrows; $i++) {
          // get each line and separate the user /visitor and the timestamp
          $ar_line = explode($sep, $ar_rows[$i]);
      // add in $addrow array the records in last $timeon seconds
          if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
            $addrow[] = $ar_rows[$i];
          }
        }
      }
    }

$nruvon = count($addrow);                   // total online
$usron = '';                                    // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
 if(preg_match($rgxvst, $addrow[$i])) $nrvst++;       // increment the visitors
 else {
   // gets and stores the user's name
   $ar_usron = explode($sep, $addrow[$i]);
   $usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
 }
}
$nrusr = $nruvon - $nrvst;              // gets the users (total - visitors)

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result

Haven't tested this on the Sql script yet.

Easiest way to open a download window without navigating away from the page

This javascript is nice that it doesn't open a new window or tab.

window.location.assign(url);

Gradle: Execution failed for task ':processDebugManifest'

In my context I removed the comment in manifest.xml and it worked.

Visual Studio replace tab with 4 spaces?

None of these answer were working for me on my macbook pro. So what i had to do was go to:

Preferences -> Source Code -> Code Formatting -> C# source code.

From here I could change my style and spacing tabs etc. This is the only project i have where the lead developer has different formatting than i do. It was a pain in the butt that my IDE would format my code different than theirs.

How to cast or convert an unsigned int to int in C?

It depends on what you want the behaviour to be. An int cannot hold many of the values that an unsigned int can.

You can cast as usual:

int signedInt = (int) myUnsigned;

but this will cause problems if the unsigned value is past the max int can hold. This means half of the possible unsigned values will result in erroneous behaviour unless you specifically watch out for it.

You should probably reexamine how you store values in the first place if you're having to convert for no good reason.

EDIT: As mentioned by ProdigySim in the comments, the maximum value is platform dependent. But you can access it with INT_MAX and UINT_MAX.

For the usual 4-byte types:

4 bytes = (4*8) bits = 32 bits

If all 32 bits are used, as in unsigned, the maximum value will be 2^32 - 1, or 4,294,967,295.

A signed int effectively sacrifices one bit for the sign, so the maximum value will be 2^31 - 1, or 2,147,483,647. Note that this is half of the other value.

Python iterating through object attributes

UPDATED

For python 3, you should use items() instead of iteritems()

PYTHON 2

for attr, value in k.__dict__.iteritems():
        print attr, value

PYTHON 3

for attr, value in k.__dict__.items():
        print(attr, value)

This will print

'names', [a list with names]
'tweet', [a list with tweet]

Disabling Log4J Output in Java

If you want to turn off logging programmatically then use

List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
loggers.add(LogManager.getRootLogger());
for ( Logger logger : loggers ) {
    logger.setLevel(Level.OFF);
}

Javascript Get Values from Multiple Select Option Box

Here i am posting the answer just for reference which may become useful.

<!DOCTYPE html>
<html>
<head>
<script>
function show()
{
     var InvForm = document.forms.form;
     var SelBranchVal = "";
     var x = 0;
     for (x=0;x<InvForm.kb.length;x++)
         {
            if(InvForm.kb[x].selected)
            {
             //alert(InvForm.kb[x].value);
             SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
            }
         }
         alert(SelBranchVal);
}
</script>
</head>
<body>
<form name="form">
<select name="kb" id="kb" onclick="show();" multiple>
<option value="India">India</option>
<option selected="selected" value="US">US</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
</select>
<!--input type="submit" name="cmdShow" value="Customize Fields"
 onclick="show();" id="cmdShow" /-->
</form>
</body>
</html>

Java - checking if parseInt throws exception

Check if it is integer parseable

public boolean isInteger(String string) {
    try {
        Integer.valueOf(string);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

or use Scanner

Scanner scanner = new Scanner("Test string: 12.3 dog 12345 cat 1.2E-3");

while (scanner.hasNext()) {
    if (scanner.hasNextDouble()) {
        Double doubleValue = scanner.nextDouble();
    } else {
        String stringValue = scanner.next();
    }
}

or use Regular Expression like

private static Pattern doublePattern = Pattern.compile("-?\\d+(\\.\\d*)?");

public boolean isDouble(String string) {
    return doublePattern.matcher(string).matches();
}

Declare Variable for a Query String

I will point out that in the article linked in the top rated answer The Curse and Blessings of Dynamic SQL the author states that the answer is not to use dynamic SQL. Scroll almost to the end to see this.

From the article: "The correct method is to unpack the list into a table with a user-defined function or a stored procedure."

Of course, once the list is in a table you can use a join. I could not comment directly on the top rated answer, so I just added this comment.

Getting the difference between two repositories

git diff master remotes/b

That's incorrect. remotes/b is a remote, but not a branch.

To get it to work, I had to do:

git diff master remotes/b/master

Convert data.frame column to a vector?

There's now an easy way to do this using dplyr.

dplyr::pull(aframe, a2)

How to use a SQL SELECT statement with Access VBA

If you wish to use the bound column value, you can simply refer to the combo:

sSQL = "SELECT * FROM MyTable WHERE ID = " & Me.MyCombo

You can also refer to the column property:

sSQL = "SELECT * FROM MyTable WHERE AText = '" & Me.MyCombo.Column(1) & "'"

Dim rs As DAO.Recordset     
Set rs = CurrentDB.OpenRecordset(sSQL)

strText = rs!AText
strText = rs.Fields(1)

In a textbox:

= DlookUp("AText","MyTable","ID=" & MyCombo)

*edited

Reset select2 value and show placeholder

So, to reset the form some of you will have a reset button. Add the following code inside the script tag

$('.your_btn_class').click(function(){
    $('#select_field_id').val([]);
    $("#select_field_id").select2({
    placeholder: "this is a placeholder",
    });
});

Or just to empty select field without keeping a placeholder:

$('.your_btn_class').click(function(){
    $('#select_field_id').val([]);
 });

MySQL error - #1062 - Duplicate entry ' ' for key 2

Seems like the second column is set as a unique index. If you dont need that remove it and your errors will go away. Possibly you added the index by mistake and thats why you are seeing the errors today and werent seeing them yesterday

Do we need to execute Commit statement after Update in SQL Server

The SQL Server Management Studio has implicit commit turned on, so all statements that are executed are implicitly commited.

This might be a scary thing if you come from an Oracle background where the default is to not have commands commited automatically, but it's not that much of a problem.

If you still want to use ad-hoc transactions, you can always execute

BEGIN TRANSACTION

within SSMS, and than the system waits for you to commit the data.

If you want to replicate the Oracle behaviour, and start an implicit transaction, whenever some DML/DDL is issued, you can set the SET IMPLICIT_TRANSACTIONS checkbox in

Tools -> Options -> Query Execution -> SQL Server -> ANSI

Parse strings to double with comma and point

You DO NOT NEED to replace the comma and dot..

I have had the very same problem. The reason is simple, the conversion culture plays a big role in which the comma or a dot is interpreted. I use a German culture where the comma distinguish the fractions, where as elsewhere the dot does the job.

Here I made a complete example to make the difference clear.

string[] doubleStrings = {"hello", "0.123", "0,123"};
double localCultreResult;
foreach (var doubleString in doubleStrings)
{
    double.TryParse(doubleString, NumberStyles.Any, CultureInfo.CurrentCulture, out localCultreResult);
    Console.WriteLine(string.Format("Local culture results for the parsing of {0} is {1}", doubleString, localCultreResult));
}

double invariantCultureResult;
foreach (var doubleString in doubleStrings)
{
    double.TryParse(doubleString, NumberStyles.Any, CultureInfo.InvariantCulture, out invariantCultureResult);
    Console.WriteLine(string.Format("Invariant culture results for the parsing of {0} is {1}", doubleString, invariantCultureResult));
}

The results is the following: enter image description here

Play around with the culture and you will get the result you need.

Setting Authorization Header of HttpClient

Use Basic Authorization And Json Parameters.

using (HttpClient client = new HttpClient())
{
    var request_json = "your json string";

    var content = new StringContent(request_json, Encoding.UTF8, "application/json");

    var authenticationBytes = Encoding.ASCII.GetBytes("YourUsername:YourPassword");

    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
            Convert.ToBase64String(authenticationBytes));
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var result = await client.PostAsync("YourURL", content);

    var result_string = await result.Content.ReadAsStringAsync();
}

How to convert C++ Code to C

http://llvm.org/docs/FAQ.html#translatecxx

It handles some code, but will fail for more complex implementations as it hasn't been fully updated for some of the modern C++ conventions. So try compiling your code frequently until you get a feel for what's allowed.

Usage sytax from the command line is as follows for version 9.0.1:

clang -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
clang -march=c  CPPtoC.bc -o CPPtoC.c

For older versions (unsure of transition version), use the following syntax:

llvm-g++ -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
llc -march=c  CPPtoC.bc -o CPPtoC.c

Note that it creates a GNU flavor of C and not true ANSI C. You will want to test that this is useful for you before you invest too heavily in your code. For example, some embedded systems only accept ANSI C.

Also note that it generates functional but fairly unreadable code. I recommend commenting and maintain your C++ code and not worrying about the final C code.

EDIT : although official support of this functionality was removed, but users can still use this unofficial support from Julia language devs, to achieve mentioned above functionality.

Transparent background on winforms?

What works for me is using a specific color instead of the real ability of .png to represent transparency.

So, what you can do is take your background image, and paint the transparent area with a specific color (Magenta always seemed appropriate to me...).

Set the image as the Form's BackgrounImage property, and set the color as the Form's TransparencyKey. No need for changes in the Control's style, and no need for BackColor.

I've tryed it right now and it worked for me...

Unexpected token ILLEGAL in webkit

This error can also be caused by a javascript line like this one:

navi_elements.style.bottom = 20px;

Notice that the value is not a string.

PyCharm import external library

I wanted to add an import path, for another project elsewhere in my workspace. MacOS Catalina 10.15.5 PyCharm Community 2020.1.1

PyCharm - Preferences - Project interpreter - Cog symbol - Show All

At the bottom of that dialog, it shows 5 buttons: Plus, Minus, Pencil, Funnel, and Directory tree.

Click Directory tree. You can now use the Plus button in the new dialog to add your 'external library' search path.

If successful, you should now see the directory name in the "External Libraries" pane in the Project panel.

Insert a row to pandas dataframe

Just assign row to a particular index, using loc:

 df.loc[-1] = [2, 3, 4]  # adding a row
 df.index = df.index + 1  # shifting index
 df = df.sort_index()  # sorting by index

And you get, as desired:

    A  B  C
 0  2  3  4
 1  5  6  7
 2  7  8  9

See in Pandas documentation Indexing: Setting with enlargement.

How to draw vertical lines on a given plot in matplotlib

matplotlib.pyplot.vlines vs. matplotlib.pyplot.axvline

  • The difference is that vlines accepts 1 or more locations for x, while axvline permits one location.
    • Single location: x=37
    • Multiple locations: x=[37, 38, 39]
  • vlines takes ymin and ymax as a position on the y-axis, while axvline takes ymin and ymax as a percentage of the y-axis range.
    • When passing multiple lines to vlines, pass a list to ymin and ymax.
  • If you're plotting a figure with something like fig, ax = plt.subplots(), then replace plt.vlines or plt.axvline with ax.vlines or ax.axvline, respectively.
import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)

plt.figure(figsize=(10, 7))

# only one line may be specified; full height
plt.axvline(x=36, color='b', label='axvline - full height')

# only one line may be specified; ymin & ymax spedified as a percentage of y-range
plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')

# multiple lines all full height
plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')

# multiple lines with varying ymin and ymax
plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')

# single vline with full ymin and ymax
plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')

# single vline with specific ymin and ymax
plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')

# place legend outside
plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')

plt.show()

enter image description here

How to give a pattern for new line in grep?

just found

grep $'\r'

It's using $'\r' for c-style escape in Bash.

in this article

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>

Best way to check if column returns a null value (from database to .net application)

Just check for

if(table.rows[0][0] == null)
{
     //Whatever I want to do
}

or you could

if(t.Rows[0].IsNull(0))
{
     //Whatever I want to do
}

Is there an equivalent of CSS max-width that works in HTML emails?

There is a trick you can do for Outlook 2007 using conditional html comments.
The code below will make sure that Outlook table is 800px wide, its not max-width but it works better than letting the table span across the entire window.

<!--[if gte mso 9]>
<style>
#tableForOutlook {
  width:800px;
}
</style>
<![endif]-->

<table style="width:98%;max-width:800px">
<!--[if gte mso 9]>
  <table id="tableForOutlook"><tr><td>
<![endif]-->
    <tr><td>
    [Your Content Goes Here]
    </td></tr>
<!--[if gte mso 9]>
  </td></tr></table>
<![endif]-->
<table>

Converting a JS object to an array using jQuery

I made a custom function:

    Object.prototype.toArray=function(){
    var arr=new Array();
    for( var i in this ) {
        if (this.hasOwnProperty(i)){
            arr.push(this[i]);
        }
    }
    return arr;
};

How to replace a set of tokens in a Java String?

My solution for replacing ${variable} style tokens (inspired by the answers here and by the Spring UriTemplate):

public static String substituteVariables(String template, Map<String, String> variables) {
    Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}");
    Matcher matcher = pattern.matcher(template);
    // StringBuilder cannot be used here because Matcher expects StringBuffer
    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
        if (variables.containsKey(matcher.group(1))) {
            String replacement = variables.get(matcher.group(1));
            // quote to work properly with $ and {,} signs
            matcher.appendReplacement(buffer, replacement != null ? Matcher.quoteReplacement(replacement) : "null");
        }
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}

Error: 'int' object is not subscriptable - Python

It would be a lot more simple just to do this;

name = input("What's your name? ")
age = int(input("How old are you? "))
print ("Hi,{0} you will be 21 in {1} years.".format(name, 21 - age))`

Creating/writing into a new file in Qt

Are you sure you're in the right directory?
Opening a file without a full path will open it in the current working directory. In most cases this is not what you want. Try changing the first line to

QString filename="c:\\Data.txt" or
QString filename="c:/Data.txt"

and see if the file is created in c:\

In Laravel, the best way to pass different types of flash messages in the session

Just send an array in the session rather than a string, like this:

Session::flash('message', ['text'=>'this is a danger message','type'=>'danger']);

@if(Session::has('message'))
    <div class="alert alert-{{session('message')['type']}}">
        {{session('message')['text']}}
    </div>
@endif

What does the error "arguments imply differing number of rows: x, y" mean?

Though this isn't a DIRECT answer to your question, I just encountered a similar problem, and thought I'd mentioned it:

I had an instance where it was instantiating a new (no doubt very inefficent) record for data.frame (a result of recursive searching) and it was giving me the same error.

I had this:

return(
  data.frame(
    user_id = gift$email,
    sourced_from_agent_id = gift$source,
    method_used = method,
    given_to = gift$account,
    recurring_subscription_id = NULL,
    notes = notes,
    stringsAsFactors = FALSE
  )
)

turns out... it was the = NULL. When I switched to = NA, it worked fine. Just in case anyone else with a similar problem hits THIS post as I did.

Can you animate a height change on a UITableViewCell when selected?

Add a property to keep track of the selected cell

@property (nonatomic) int currentSelection;

Set it to a sentinel value in (for example) viewDidLoad, to make sure that the UITableView starts in the 'normal' position

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //sentinel
    self.currentSelection = -1;
}

In heightForRowAtIndexPath you can set the height you want for the selected cell

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    int rowHeight;
    if ([indexPath row] == self.currentSelection) {
        rowHeight = self.newCellHeight;
    } else rowHeight = 57.0f;
    return rowHeight;
}

In didSelectRowAtIndexPath you save the current selection and save a dynamic height, if required

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        // do things with your cell here

        // set selection
        self.currentSelection = indexPath.row;
        // save height for full text label
        self.newCellHeight = cell.titleLbl.frame.size.height + cell.descriptionLbl.frame.size.height + 10;

        // animate
        [tableView beginUpdates];
        [tableView endUpdates];
    }
}

In didDeselectRowAtIndexPath set the selection index back to the sentinel value and animate the cell back to normal form

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {       
        // do things with your cell here

        // sentinel
        self.currentSelection = -1;

        // animate
        [tableView beginUpdates];
        [tableView endUpdates];
    }
}

Display tooltip on Label's hover?

You can use the "title attribute" for label tag.

<label title="Hello This Will Have Some Value">Hello...</label>

If you need more control over the looks,

1 . try http://getbootstrap.com/javascript/#tooltips as shown below. But you will need to include bootstrap.

<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="left" title="Hello This Will Have Some Value">Hello...</button>

2 . try https://jqueryui.com/tooltip/. But you will need to include jQueryUI.

<script type="text/javascript">
$(document).ready(function(){
$(this).tooltip();
});
</script>

Linux shell sort file according to the second column?

If this is UNIX:

sort -k 2 file.txt

You can use multiple -k flags to sort on more than one column. For example, to sort by family name then first name as a tie breaker:

sort -k 2,2 -k 1,1 file.txt

Relevant options from "man sort":

-k, --key=POS1[,POS2]

start a key at POS1, end it at POS2 (origin 1)

POS is F[.C][OPTS], where F is the field number and C the character position in the field. OPTS is one or more single-letter ordering options, which override global ordering options for that key. If no key is given, use the entire line as the key.

-t, --field-separator=SEP

use SEP instead of non-blank to blank transition

What exactly does a jar file contain?

A JAR file is actually just a ZIP file. It can contain anything - usually it contains compiled Java code (*.class), but sometimes also Java sourcecode (*.java).

However, Java can be decompiled - in case the developer obfuscated his code you won't get any useful class/function/variable names though.

Error importing Seaborn module in Python

I had the same problem and I am using iPython. pip or conda by itself did not work for me but when I use !conda it did work.

!conda install seaborn

How do I extract the contents of an rpm?

To debug / inspect your rpm I suggest to use redline which is a java program

Usage :

java -cp redline-1.2.1-jar-with-dependencies.jar org.redline_rpm.Scanner foo.rpm

Download : https://github.com/craigwblake/redline/releases

When & why to use delegates?

Delegates Overview

Delegates have the following properties:

  • Delegates are similar to C++ function pointers, but are type safe.
  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.
  • Methods don't need to match the delegate signature exactly. For more information, see Covariance and Contra variance.
  • C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.

Calling other function in the same controller?

Try:

return $this->sendRequest($uri);

Since PHP is not a pure Object-Orieneted language, it interprets sendRequest() as an attempt to invoke a globally defined function (just like nl2br() for example), but since your function is part of a class ('InstagramController'), you need to use $this to point the interpreter in the right direction.

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

Sometimes, it can be caused by wrong naming for xml or resource file.

At least, for me, that problem was solved by changing name .

Non-recursive depth first search algorithm

DFS iterative in Java:

//DFS: Iterative
private Boolean DFSIterative(Node root, int target) {
    if (root == null)
        return false;
    Stack<Node> _stack = new Stack<Node>();
    _stack.push(root);
    while (_stack.size() > 0) {
        Node temp = _stack.peek();
        if (temp.data == target)
            return true;
        if (temp.left != null)
            _stack.push(temp.left);
        else if (temp.right != null)
            _stack.push(temp.right);
        else
            _stack.pop();
    }
    return false;
}

Programmatically navigate using React router

React-Router V4

if you're using version 4 then you can use my library (Shameless plug) where you simply dispatch an action and everything just works!

dispatch(navigateTo("/aboutUs"));

trippler

Select all columns except one in MySQL?

I wanted this too so I created a function instead.

public function getColsExcept($table,$remove){
    $res =mysql_query("SHOW COLUMNS FROM $table");

    while($arr = mysql_fetch_assoc($res)){
        $cols[] = $arr['Field'];
    }
    if(is_array($remove)){
        $newCols = array_diff($cols,$remove);
        return "`".implode("`,`",$newCols)."`";
    }else{
        $length = count($cols);
        for($i=0;$i<$length;$i++){
            if($cols[$i] == $remove)
                unset($cols[$i]);
        }
        return "`".implode("`,`",$cols)."`";
    }
}

So how it works is that you enter the table, then a column you don't want or as in an array: array("id","name","whatevercolumn")

So in select you could use it like this:

mysql_query("SELECT ".$db->getColsExcept('table',array('id','bigtextcolumn'))." FROM table");

or

mysql_query("SELECT ".$db->getColsExcept('table','bigtextcolumn')." FROM table");

Is it possible to change the package name of an Android app on Google Play?

No, you cannot change package name unless you're okay with publishing it as a new app in Play Store:

Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application. Android manual confirms it as well here:

Caution: Once you publish your application, you cannot change the package name. The package name defines your application's identity, so if you change it, then it is considered to be a different application and users of the previous version cannot update to the new version. If you're okay with publishing new version of your app as a completely new entity, you can do it of course - just remove old app from Play Store (if you want) and publish new one, with different package name.

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can do it faster without any imports just by using magics:

%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0

Notice that all env variable are strings, so no need to use ". You can verify that env-variable is set up by running: %env <name_of_var>. Or check all of them with %env.

How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

Disabling the alert message is not a way to solve the problem. Despite the PHP core is continue to work it makes a dangerous assumptions and actions.

Never ignore the error where PHP should make an assumptions of something!!!!

If the class organized as a singleton you can always use function getInstance() and then use getData()

Likse:

$classObj = MyClass::getInstance();
$classObj->getData();

If the class is not a singleton, use

 $classObj = new MyClass();
 $classObj->getData();

How do I sort a VARCHAR column in SQL server that contains numbers?

This query is helpful for you. In this query, a column has data type varchar is arranged by good order.For example- In this column data are:- G1,G34,G10,G3. So, after running this query, you see the results: - G1,G10,G3,G34.

SELECT *,
       (CASE WHEN ISNUMERIC(column_name) = 1 THEN 0 ELSE 1 END) IsNum
FROM table_name 
ORDER BY IsNum, LEN(column_name), column_name;

Converting Go struct to JSON

You can define your own custom MarshalJSON and UnmarshalJSON methods and intentionally control what should be included, ex:

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    name string
}

func (u *User) MarshalJSON() ([]byte, error) {
    return json.Marshal(&struct {
        Name     string `json:"name"`
    }{
        Name:     "customized" + u.name,
    })
}

func main() {
    user := &User{name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

How to find the .NET framework version of a Visual Studio project?

The simplest way to find the framework version of the current .NET project is:

  1. Right-click on the project and go to "Properties."
  2. In the first tab, "Application," you can see the target framework this project is using.

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

Use this code. This works like a champ.

Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = outputPdfFile;
process.Start();

Global variables in c#.net

Just declare the variable at the starting of a class.

e.g. for string variable:

public partial class Login : System.Web.UI.Page
{
    public string sError;

    protected void Page_Load(object sender, EventArgs e)
    {
         //Page Load Code
    }

Filtering a spark dataframe based on date

The following solutions are applicable since spark 1.5 :

For lower than :

// filter data where the date is lesser than 2015-03-14
data.filter(data("date").lt(lit("2015-03-14")))      

For greater than :

// filter data where the date is greater than 2015-03-14
data.filter(data("date").gt(lit("2015-03-14"))) 

For equality, you can use either equalTo or === :

data.filter(data("date") === lit("2015-03-14"))

If your DataFrame date column is of type StringType, you can convert it using the to_date function :

// filter data where the date is greater than 2015-03-14
data.filter(to_date(data("date")).gt(lit("2015-03-14"))) 

You can also filter according to a year using the year function :

// filter data where year is greater or equal to 2016
data.filter(year($"date").geq(lit(2016))) 

Simple (non-secure) hash function for JavaScript?

// Simple but unreliable function to create string hash by Sergey.Shuchkin [t] gmail.com
// alert( strhash('http://www.w3schools.com/js/default.asp') ); // 6mn6tf7st333r2q4o134o58888888888
function strhash( str ) {
    if (str.length % 32 > 0) str += Array(33 - str.length % 32).join("z");
    var hash = '', bytes = [], i = j = k = a = 0, dict = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','1','2','3','4','5','6','7','8','9'];
    for (i = 0; i < str.length; i++ ) {
        ch = str.charCodeAt(i);
        bytes[j++] = (ch < 127) ? ch & 0xFF : 127;
    }
    var chunk_len = Math.ceil(bytes.length / 32);   
    for (i=0; i<bytes.length; i++) {
        j += bytes[i];
        k++;
        if ((k == chunk_len) || (i == bytes.length-1)) {
            a = Math.floor( j / k );
            if (a < 32)
                hash += '0';
            else if (a > 126)
                hash += 'z';
            else
                hash += dict[  Math.floor( (a-32) / 2.76) ];
            j = k = 0;
        }
    }
    return hash;
}

Returning Promises from Vuex actions

Just for an information on a closed topic: you don’t have to create a promise, axios returns one itself:

Ref: https://forum.vuejs.org/t/how-to-resolve-a-promise-object-in-a-vuex-action-and-redirect-to-another-route/18254/4

Example:

    export const loginForm = ({ commit }, data) => {
      return axios
        .post('http://localhost:8000/api/login', data)
        .then((response) => {
          commit('logUserIn', response.data);
        })
        .catch((error) => {
          commit('unAuthorisedUser', { error:error.response.data });
        })
    }

Another example:

    addEmployee({ commit, state }) {       
      return insertEmployee(state.employee)
        .then(result => {
          commit('setEmployee', result.data);
          return result.data; // resolve 
        })
        .catch(err => {           
          throw err.response.data; // reject
        })
    }

Another example with async-await

    async getUser({ commit }) {
        try {
            const currentUser = await axios.get('/user/current')
            commit('setUser', currentUser)
            return currentUser
        } catch (err) {
            commit('setUser', null)
            throw 'Unable to fetch current user'
        }
    },

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

Adding attributes to an XML node

You can use the Class XmlAttribute.

Eg:

XmlAttribute attr = xmlDoc.CreateAttribute("userName");
attr.Value = "Tushar";

node.Attributes.Append(attr);

JavaScript or jQuery browser back button click detector

Disable the url button by following function

window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle the back (or forward) buttons here
            // Will NOT handle refresh, use onbeforeunload for this.
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Detect and redirect change here
                // Works in older FF and IE9
                // * it does mess with your hash symbol (anchor?) pound sign
                // delimiter on the end of the URL
            }
            else {
                ignoreHashChange = false;
            }
        };
    }
};

Angular 4 - get input value

If you dont want to use two way data binding. You can do this.

In HTML

<form (ngSubmit)="onSubmit($event)">
   <input name="player" value="Name">
</form>

In component

onSubmit(event: any) {
   return event.target.player.value;
}

PHP if not statements

No matter what $action is, it will always either not be "add" OR not be "delete", which is why the if condition always passes. What you want is to use && instead of ||:

(!isset($action)) || ($action !="add" && $action !="delete"))

How to drop columns by name in a data frame

You can also try the dplyr package:

R> df <- data.frame(x=1:5, y=2:6, z=3:7, u=4:8)
R> df
  x y z u
1 1 2 3 4
2 2 3 4 5
3 3 4 5 6
4 4 5 6 7
5 5 6 7 8
R> library(dplyr)
R> dplyr::select(df2, -c(x, y))  # remove columns x and y
  z u
1 3 4
2 4 5
3 5 6
4 6 7
5 7 8

How do I tell Maven to use the latest version of a dependency?

If you want Maven should use the latest version of a dependency, then you can use Versions Maven Plugin and how to use this plugin, Tim has already given a good answer, follow his answer.

But as a developer, I will not recommend this type of practices. WHY?

answer to why is already given by Pascal Thivent in the comment of the question

I really don't recommend this practice (nor using version ranges) for the sake of build reproducibility. A build that starts to suddenly fail for an unknown reason is way more annoying than updating manually a version number.

I will recommend this type of practice:

<properties>
    <spring.version>3.1.2.RELEASE</spring.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

</dependencies>

it is easy to maintain and easy to debug. You can update your POM in no time.

how to declare global variable in SQL Server..?

I like the approach of using a table with a column for each global variable. This way you get autocomplete to aid in coding the retrieval of the variable. The table can be restricted to a single row as outlined here: SQL Server: how to constrain a table to contain a single row?

How to remove all leading zeroes in a string

Im Fixed with this way.

its very simple. only pass a string its remove zero start of string.

function removeZeroString($str='')
{
    while(trim(substr($str,0,1)) === '0')
    {
        $str = ltrim($str,'0');
    }
    return $str;
}

Wait until flag=true

I solved this issue by implementing the method below.

const waitUntil = (condition) => {
    return new Promise((resolve) => {
        let interval = setInterval(() => {
            if (!condition()) {
                return
            }

            clearInterval(interval)
            resolve()
        }, 100)
    })
}

Now, whenever you want to wait until a certain condition is met you can call it like this.

await waitUntil(() => /* your condition */)

Why powershell does not run Angular commands?

I solved my problem by running below command

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

How do you get the list of targets in a makefile?

This is far from clean, but did the job, for me.

make -p 2&>/dev/null | grep -A 100000 "# Files" | grep -v "^$" | grep -v "^\(\s\|#\|\.\)" | grep -v "Makefile:" | cut -d ":" -f 1

I use make -p that dumps the internal database, ditch stderr, use a quick and dirty grep -A 100000 to keep the bottom of the output. Then I clean the output with a couple of grep -v, and finally use cut to get what's before the colon, namely, the targets.

This is enough for my helper scripts on most of my Makefiles.

EDIT: added grep -v Makefile that is an internal rule

C++ deprecated conversion from string constant to 'char*'

As answer no. 2 by fnieto - Fernando Nieto clearly and correctly describes that this warning is given because somewhere in your code you are doing (not in the code you posted) something like:

void foo(char* str);
foo("hello");

However, if you want to keep your code warning-free as well then just make respective change in your code:

void foo(char* str);
foo((char *)"hello");

That is, simply cast the string constant to (char *).

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

You may get this error because you namespaced the file. If so you will need to specify that PHPUnit_Framework_TestCase is in the global namespace by preceding it with a backslash:

namespace AcmeInc\MyApplication\Tests
class StackTest extends \PHPUnit_Framework_TestCase {}

I submitted a crude PR to start conversation for correcting the documentation.

Table 'performance_schema.session_variables' doesn't exist

I was able to log on to the mysql server after running the command @robregonm suggested:

mysql_upgrade -u root -p --force

A MySQL server restart is required.

How can I count text lines inside an DOM element? Can I?

I found a way to calc the line number when I develop a html editor. The primary method is that:

  1. In IE you can call getBoundingClientRects, it returns each line as a rectangle

  2. In webkit or new standard html engine, it returns each element or node's client rectangles, in this case you can compare each rectangles, I mean each there must be a rectangle is the largest, so you can ignore those rectangles that height is smaller(if there is a rectangle's top smaller than it and bottom larger than it, the condition is true.)

so let's see the test result:

enter image description here

The green rectangle is the largest rectangle in each row

The red rectangle is the selection boundary

The blue rectangle is the boundary from start to selection after expanding, we see it may larger than red rectangle, so we have to check each rectangle's bottom to limit it must smaller than red rectangle's bottom.

        var lineCount = "?";
        var rects;
        if (window.getSelection) {
            //Get all client rectangles from body start to selection, count those rectangles that has the max bottom and min top
            var bounding = {};
            var range = window.getSelection().getRangeAt(0);//As this is the demo code, I dont check the range count
            bounding = range.getBoundingClientRect();//!!!GET BOUNDING BEFORE SET START!!!

            //Get bounding and fix it , when the cursor is in the last character of lineCount, it may expand to the next lineCount.
            var boundingTop = bounding.top;
            var boundingBottom = bounding.bottom;
            var node = range.startContainer;
            if (node.nodeType !== 1) {
                node = node.parentNode;
            }
            var style = window.getComputedStyle(node);
            var lineHeight = parseInt(style.lineHeight);
            if (!isNaN(lineHeight)) {
                boundingBottom = boundingTop + lineHeight;
            }
            else {
                var fontSize = parseInt(style.fontSize);
                if (!isNaN(fontSize)) {
                    boundingBottom = boundingTop + fontSize;
                }
            }
            range = range.cloneRange();

            //Now we have enougn datas to compare

            range.setStart(body, 0);
            rects = range.getClientRects();
            lineCount = 0;
            var flags = {};//Mark a flags to avoid of check some repeat lines again
            for (var i = 0; i < rects.length; i++) {
                var rect = rects[i];
                if (rect.width === 0 && rect.height === 0) {//Ignore zero rectangles
                    continue;
                }
                if (rect.bottom > boundingBottom) {//Check if current rectangle out of the real bounding of selection
                    break;
                }
                var top = rect.top;
                var bottom = rect.bottom;
                if (flags[top]) {
                    continue;
                }
                flags[top] = 1;

                //Check if there is no rectangle contains this rectangle in vertical direction.
                var succ = true;
                for (var j = 0; j < rects.length; j++) {
                    var rect2 = rects[j];
                    if (j !== i && rect2.top < top && rect2.bottom > bottom) {
                        succ = false;
                        break;
                    }
                }
                //If succ, add lineCount 1
                if (succ) {
                    lineCount++;
                }
            }
        }
        else if (editor.document.selection) {//IN IE8 getClientRects returns each single lineCount as a rectangle
            var range = body.createTextRange();
            range.setEndPoint("EndToEnd", range);
            rects = range.getClientRects();
            lineCount = rects.length;
        }
        //Now we get lineCount here

Google Text-To-Speech API

#! /usr/bin/python2
# -*- coding: utf-8 -*-

def run(cmd):
    import os
    import sys
    from subprocess import Popen, PIPE
    print(cmd)
    proc=Popen(cmd, stdin=None, stdout=PIPE, stderr=None, shell=True)
    while True:
        data = proc.stdout.readline()   # Alternatively proc.stdout.read(1024)
        if len(data) == 0:
            print("Finished process")
            break
        sys.stdout.write(data)

import urllib

msg='Hello preety world'
msg=urllib.quote_plus(msg)
# -v verbosity
cmd='curl '+ \
    '--output tts_responsivevoice.mp2 '+ \
    "\""+'https://code.responsivevoice.org/develop/getvoice.php?t='+msg+'&tl=en-US&sv=g2&vn=&pitch=0.5&rate=0.5&vol=1'+"\""+ \
    ' -H '+"\""+'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0'+"\""+ \
    ' -H '+"\""+'Accept: audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5'+"\""+ \
    ' -H '+"\""+'Accept-Language: pl,en-US;q=0.7,en;q=0.3'+"\""+ \
    ' -H '+"\""+'Range: bytes=0-'+"\""+ \
    ' -H '+"\""+'Referer: http://code.responsivevoice.org/develop/examples/example2.html'+"\""+ \
    ' -H '+"\""+'Cookie: __cfduid=ac862i73b6a61bf50b66713fdb4d9f62c1454856476; _ga=GA1.2.2126195996.1454856480; _gat=1'+"\""+ \
    ' -H '+"\""+'Connection: keep-alive'+"\""+ \
    ''
print('***************************')
print(cmd)
print('***************************')
run(cmd)

Line:

/getvoice.php?t='+msg+'&tl=en-US&sv=g2&vn=&pitch=0.5&rate=0.5&vol=1'+"\""+ \

is responsible for language.

tl=en-US

There is another preety interesting site with tts engines that can be used in this manner.

substitute o for null iv0na.c0m

have a nice day

Can I configure a subdomain to point to a specific port on my server

If you want to host multiple websites in a single server in different ports then, method mentioned by MRVDOG won't work. Because browser won't resolve SRV records and will always hit :80 port. For example if your requirement is:

site1.domain.com maps to domain.com:8080
site2.domain.com maps to domain.com:8081

Because often you want to fully utilize the server space you have bought. Then you can try the following:

Step 1: Install proxy server. I will use Nginx here.

apt-get install nginx

Step 2: Edit /etc/nginx/nginx.conf file to add the port mappings. To do so, add the following lines:

server {
    listen 80;
    server_name site1.domain.com;

    location / {
        proxy_pass http://localhost:8080;
    }   
}

server {
    listen 80;
    server_name site2.domain.com;

    location / {
        proxy_pass http://localhost:8081;
    }   
}

This does the magic. So the file will end up looking like following:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##
server {
    listen 80;
    server_name site1.domain.com;

    location / {
        proxy_pass http://localhost:8080;
    }   
}

server {
    listen 80;
    server_name site2.domain.com;

    location / {
        proxy_pass http://localhost:8081;
    }   
}

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}


#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
# 
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
# 
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
# 
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

Step 3: Start nginx:

/etc/init.d/nginx start.

Whenever you make any changes to configuration, you need to restart nginx:

/etc/init.d/nginx restart

Finally: Don't forget to add A records in your DNS configuration. All subdomains should point to domain. Like this: enter image description here

Put your static ip instead of 111.11.111.111

Further details:

How to escape single quotes within single quoted strings

Another way to fix the problem of too many layers of nested quotation:

You are trying to cram too much into too tiny a space, so use a bash function.

The problem is you are trying to have too many levels of nesting, and the basic alias technology is not powerful enough to accommodate. Use a bash function like this to make it so the single, double quotes back ticks and passed in parameters are all handled normally as we would expect:

lets_do_some_stuff() {
    tmp=$1                       #keep a passed in parameter.
    run_your_program $@          #use all your passed parameters.
    echo -e '\n-------------'    #use your single quotes.
    echo `date`                  #use your back ticks.
    echo -e "\n-------------"    #use your double quotes.
}
alias foobarbaz=lets_do_some_stuff

Then you can use your $1 and $2 variables and single, double quotes and back ticks without worrying about the alias function wrecking their integrity.

This program prints:

el@defiant ~/code $ foobarbaz alien Dyson ring detected @grid 10385
alien Dyson ring detected @grid 10385
-------------
Mon Oct 26 20:30:14 EDT 2015
-------------

gdb fails with "Unable to find Mach task port for process-id" error

You need to create a certificate and sign gdb:

  • Open application “Keychain Access” (/Applications/Utilities/Keychain Access.app)
  • Open menu /Keychain Access/Certificate Assistant/Create a Certificate...
  • Choose a name (gdb-cert in the example), set “Identity Type” to “Self Signed Root”, set “Certificate Type” to “Code Signing” and select the “Let me override defaults”. Click “Continue”. You might want to extend the predefined 365 days period to 3650 days.
  • Click several times on “Continue” until you get to the “Specify a Location For The Certificate” screen, then set “Keychain to System”.
  • If you can't store the certificate in the “System” keychain, create it in the “login” keychain, then export it. You can then import it into the “System” keychain.
  • In keychains select “System”, and you should find your new certificate. Use the context menu for the certificate, select “Get Info”, open the “Trust” item, and set “Code Signing” to “Always Trust”.
  • You must quit “Keychain Access” application in order to use the certificate and restart “taskgated” service by killing the current running “taskgated” process. Alternatively you can restart your computer.
  • Finally you can sign gdb:

    sudo codesign -s gdb-cert /usr/local/bin/ggdb

    sudo ggdb ./myprog

Convert Year/Month/Day to Day of Year in Python

Just subtract january 1 from the date:

import datetime
today = datetime.datetime.now()
day_of_year = (today - datetime.datetime(today.year, 1, 1)).days + 1

Laravel Update Query

This error would suggest that User::where('email', '=', $userEmail)->first() is returning null, rather than a problem with updating your model.

Check that you actually have a User before attempting to change properties on it, or use the firstOrFail() method.

$UpdateDetails = User::where('email', $userEmail)->first();

if (is_null($UpdateDetails)) {
    return false;
}

or using the firstOrFail() method, theres no need to check if the user is null because this throws an exception (ModelNotFoundException) when a model is not found, which you can catch using App::error() http://laravel.com/docs/4.2/errors#handling-errors

$UpdateDetails = User::where('email', $userEmail)->firstOrFail();

Redirect to external URL with return in laravel

Define the url you want to redirect in $url

Then just use

return Redirect::away($url);

If you want to redirect inside your views use

return Redirect::to($url);

Read more about Redirect here

Update 1 :

Here is the simple example

return Redirect::to('http://www.google.com');

Update 2 :

As the Questioner wants to return in the same page

$triggersms = file_get_contents('http://www.cloud.smsindiahub.in/vendorsms/pushsms.aspx?user=efg&password=abcd&msisdn=9197xxx2&sid=MYID&msg=Hello');
return $triggersms;

How do I lowercase a string in C?

Are you just dealing with ASCII strings, and have no locale issues? Then yes, that would be a good way to do it.

get all keys set in memcached

If you have PHP & PHP-memcached installed, you can run

$ php -r '$c = new Memcached(); $c->addServer("localhost", 11211); var_dump( $c->getAllKeys() );'

Angular cli generate a service and include the provider in one step

Angular 6+ Singleton Services

The recommended approach for a singleton service for Angular 6 and beyond is :

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class UserService {
}

In fact the CLI --module switch doesn't even exist any more for registering a service at the app level because it doesn't need to modify app.module.ts anymore.

This will create the above code, without needing to specify a module.

ng g s services/user

So if you don't want your service to be a singleton you must remove the providedIn code yourself - and then add it manually to providers for a component or lazy loaded module. Doesn't look like there is currently a switch to not generate the providedIn: 'root' part so you need to manually remove it.

How do I wait until Task is finished in C#?

When working with continuations I find it useful to think of the place where I write .ContinueWith as the place from which execution immediately continues to the statements following it, not the statements 'inside' it. In that case it becomes clear that you would get an empty string returned in Send. If your only processing of the response is writing it to the console, you don't need any Wait in Ito's solution - the console printout will happen without waits but both Send and Print should return void in that case. Run this in console app and you will get printout of the page.

IMO, waits and Task.Result calls (which block) are necessary sometimes, depending on your desired flow of control, but more often they are a sign that you don't really use asynchronous functionality correctly.

namespace TaskTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Send();
            Console.WriteLine("Press Enter to exit");
            Console.ReadLine();
        }

        private static void Send()
        {
            HttpClient client = new HttpClient();
            Task<HttpResponseMessage> responseTask = client.GetAsync("http://google.com");
            responseTask.ContinueWith(x => Print(x));
        }

        private static void Print(Task<HttpResponseMessage> httpTask)
        {
            Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
            Task continuation = task.ContinueWith(t =>
            {
                Console.WriteLine("Result: " + t.Result);
            });
        }
    }
}

move a virtual machine from one vCenter to another vCenter

For moving a virtual machine you need not clone the VM, just copy the VM files (after powering the VM off) to external HDD and register the same on destination host.

Could not load type from assembly error

Yet another solution: Old DLLs pointing to each other and cached by Visual Studio in

C:\Users\[yourname]\AppData\Local\Microsoft\VisualStudio\10.0\ProjectAssemblies

Exit VS, delete everything in this folder and Bob's your uncle.

Can not find the tag library descriptor of springframework

Removing the space between @ and taglib did the trick for me: <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

check for null date in CASE statement, where have I gone wrong?

Try:

select
     id,
     StartDate,
CASE WHEN StartDate IS NULL
    THEN 'Awaiting'
    ELSE 'Approved' END AS StartDateStatus
FROM myTable

You code would have been doing a When StartDate = NULL, I think.


NULL is never equal to NULL (as NULL is the absence of a value). NULL is also never not equal to NULL. The syntax noted above is ANSI SQL standard and the converse would be StartDate IS NOT NULL.

You can run the following:

SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison

And this returns:

EqualityCheck = 0
InEqualityCheck = 0
NullComparison = 1

For completeness, in SQL Server you can:

SET ANSI_NULLS OFF;

Which would result in your equals comparisons working differently:

SET ANSI_NULLS OFF

SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison

Which returns:

EqualityCheck = 1
InEqualityCheck = 0
NullComparison = 1

But I would highly recommend against doing this. People subsequently maintaining your code might be compelled to hunt you down and hurt you...

Also, it will no longer work in upcoming versions of SQL server:

https://msdn.microsoft.com/en-GB/library/ms188048.aspx

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

If the cell height is dynamic by the content, you should precisely count it out and then return the height value before the cell is rendered. An easy way is to define the counting method in the table view cell code for controller to call at the table cell height delegate method. Don't forget to count out the real cell frame width (default is 320) if the height is rely on the width of the table or screen. That is, in the table cell height delegate method, use cell.frame to correct the cell width first, then call the counting height method defined in the cell to get the suitable value and return it.

PS. The code for generating cell object could be defined in another method for different table view cell delegate method to call.

Unmount the directory which is mounted by sshfs in Mac

You can always do this from finder. Simply navigate to the directory above where the mount is and hit the eject icon over the mounted folder, which will have SSHFS in the name (in the finder). A shortcut to open a folder in the finder from the terminal is

open .

which will open up the current directory in a new finder window. Replace "." with your directory of choice.