Programs & Examples On #Activejdbc

ActiveJDBC is a Java ORM modeled on ActiveRecord from Ruby on Rails.

Convert List<T> to ObservableCollection<T> in WP7

If you are going to be adding lots of items, consider deriving your own class from ObservableCollection and adding items to the protected Items member - this won't raise events in observers. When you are done you can raise the appropriate events:

public class BulkUpdateObservableCollection<T> : ObservableCollection<T>
{
    public void AddRange(IEnumerable<T> collection)
    {
        foreach (var i in collection) Items.Add(i);
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        OnPropertyChanged(new PropertyChangedEventArgs("Count"));
    }
 }

When adding many items to an ObservableCollection that is already bound to a UI element (such as LongListSelector) this can make a massive performance difference.

Prior to adding the items, you could also ensure you have enough space, so that the list isn't continually being expanded by implementing this method in the BulkObservableCollection class and calling it prior to calling AddRange:

    public void IncreaseCapacity(int increment)
    {
        var itemsList = (List<T>)Items;
        var total = itemsList.Count + increment;
        if (itemsList.Capacity < total)
        {
            itemsList.Capacity = total;
        }
    }

How can I trigger the click event of another element in ng-click using angularjs?

One more directive

html

<btn-file-selector/>

code

.directive('btnFileSelector',[function(){
  return {
    restrict: 'AE', 
    template: '<div></div>', 
    link: function(s,e,a){

      var el = angular.element(e);
      var button = angular.element('<button type="button" class="btn btn-default btn-upload">Add File</button>'); 
      var fileForm = angular.element('<input type="file" style="display:none;"/>'); 

      fileForm.on('change', function(){
         // Actions after the file is selected
         console.log( fileForm[0].files[0].name );
      });

      button.bind('click',function(){
        fileForm.click();
      });     


     el.append(fileForm);
     el.append(button);
    }
  }  
}]); 

Is there a /dev/null on Windows?

NUL in Windows seems to be actually a virtual path in any folder. Just like .., . in any filesystem.

Use any folder followed with NUL will work.

Example,

echo 1 > nul
echo 1 > c:\nul
echo 1 > c:\users\nul
echo 1 > c:\windows\nul

have the same effect as /dev/null on Linux.

This was tested on Windows 7, 64 bit.

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

How does [HttpContext.Current.User] know which usernames exist or do not exist?

Let's look at an example of one way this works. Suppose you are using Forms Authentication and the "OnAuthenticate" event fires. This event occurs "when the application authenticates the current request" (Reference Source).

Up until this point, the application has no idea who you are.

Since you are using Forms Authentication, it first checks by parsing the authentication cookie (usually .ASPAUTH) via a call to ExtractTicketFromCookie. This calls FormsAuthentication.Decrypt (This method is public; you can call this yourself!). Next, it calls Context.SetPrincipalNoDemand, turning the cookie into a user and stuffing it into Context.User (Reference Source).

how to show calendar on text box click in html

yeah you will come across of various issues using HTML5 datepicker, it would work with some or might not be. I faced the same issue. Please check this DatePicker Demo, I solved my problem with this plugin. Its very good and flexible datepicker plugin with complete demo. It is completely compatible with mobile browsers too and can be integrated with jquery mobile too.

How to kill a thread instantly in C#?

You should first have some agreed method of ending the thread. For example a running_ valiable that the thread can check and comply with.

Your main thread code should be wrapped in an exception block that catches both ThreadInterruptException and ThreadAbortException that will cleanly tidy up the thread on exit.

In the case of ThreadInterruptException you can check the running_ variable to see if you should continue. In the case of the ThreadAbortException you should tidy up immediately and exit the thread procedure.

The code that tries to stop the thread should do the following:

running_ = false;
threadInstance_.Interrupt();
if(!threadInstance_.Join(2000)) { // or an agreed resonable time
   threadInstance_.Abort();
}

Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

System.Net.WebException: The remote name could not be resolved:

Open the hosts file located at : **C:\windows\system32\drivers\etc**.

Hosts file is for what?

Add the following at end of this file :

YourServerIP YourDNS

Example:

198.168.1.1 maps.google.com

How to drop column with constraint?

I got the same:

ALTER TABLE DROP COLUMN failed because one or more objects access this column message.

My column had an index which needed to be deleted first. Using sys.indexes did the trick:

DECLARE @sql VARCHAR(max)

SELECT @sql = 'DROP INDEX ' + idx.NAME + ' ON tblName'
FROM sys.indexes idx
INNER JOIN sys.tables tbl ON idx.object_id = tbl.object_id
INNER JOIN sys.index_columns idxCol ON idx.index_id = idxCol.index_id
INNER JOIN sys.columns col ON idxCol.column_id = col.column_id
WHERE idx.type <> 0
    AND tbl.NAME = 'tblName'
    AND col.NAME = 'colName'

EXEC sp_executeSql @sql
GO

ALTER TABLE tblName
DROP COLUMN colName

jquery $.each() for objects

Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.

You have programs: [ {...}, {...} ] so programs[0] is { "name":"zonealarm", "price":"500" } So your loop is just going over that.

You could do an outer loop over the array

$.each(data.programs, function(index) {

    // then loop over the object elements
    $.each(data.programs[index], function(key, value) {
        console.log(key + ": " + value);
    }

}

JAXB :Need Namespace Prefix to all the elements

Solved by adding

@XmlSchema(
    namespace = "http://www.example.com/a",
    elementFormDefault = XmlNsForm.QUALIFIED,
    xmlns = {
        @XmlNs(prefix="ns1", namespaceURI="http://www.example.com/a")
    }
)  

package authenticator.beans.login;
import javax.xml.bind.annotation.*;

in package-info.java

Took help of jaxb-namespaces-missing : Answer provided by Blaise Doughan

Why use @PostConstruct?

Also constructor based initialisation will not work as intended whenever some kind of proxying or remoting is involved.

The ct will get called whenever an EJB gets deserialized, and whenever a new proxy gets created for it...

When to use static methods

Static methods and variables are controlled version of 'Global' functions and variables in Java. In which methods can be accessed as classname.methodName() or classInstanceName.methodName(), i.e. static methods and variables can be accessed using class name as well as instances of the class.

Class can't be declared as static(because it makes no sense. if a class is declared public, it can be accessed from anywhere), inner classes can be declared static.

Should I use typescript? or I can just use ES6?

I've been using Typescript in my current angular project for about a year and a half and while there are a few issues with definitions every now and then the DefinitelyTyped project does an amazing job at keeping up with the latest versions of most popular libraries.

Having said that there is a definite learning curve when transitioning from vanilla JavaScript to TS and you should take into account the ability of you and your team to make that transition. Also if you are going to be using angular 1.x most of the examples you will find online will require you to translate them from JS to TS and overall there are not a lot of resources on using TS and angular 1.x together right now.

If you plan on using angular 2 there are a lot of examples using TS and I think the team will continue to provide most of the documentation in TS, but you certainly don't have to use TS to use angular 2.

ES6 does have some nice features and I personally plan on getting more familiar with it but I would not consider it a production-ready language at this point. Mainly due to a lack of support by current browsers. Of course, you can write your code in ES6 and use a transpiler to get it to ES5, which seems to be the popular thing to do right now.

Overall I think the answer would come down to what you and your team are comfortable learning. I personally think both TS and ES6 will have good support and long futures, I prefer TS though because you tend to get language features quicker and right now the tooling support (in my opinion) is a little better.

How to write the Fibonacci Sequence?

Canonical Python code to print Fibonacci sequence:

a,b=1,1
while True:
  print a,
  a,b=b,a+b       # Could also use b=a+b;a=b-a

For the problem "Print the first Fibonacci number greater than 1000 digits long":

a,b=1,1
i=1
while len(str(a))<=1000:
  i=i+1
  a,b=b,a+b

print i,len(str(a)),a

How to give credentials in a batch script that copies files to a network location?

You can also map the share to a local drive as follows:

net use X: "\\servername\share" /user:morgan password

Get host domain from URL?

try following statement

 Uri myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri);
 string pathQuery = myuri.PathAndQuery;
 string hostName = myuri.ToString().Replace(pathQuery , "");

Example1

 Input : http://localhost:4366/Default.aspx?id=notlogin
 Ouput : http://localhost:4366

Example2

 Input : http://support.domain.com/default.aspx?id=12345
 Output: support.domain.com

How do I find what Java version Tomcat6 is using?

After installing tomcat, you can choose "configure tomcat" by search in "search programs and files". After clicking on "configure Tomcat", you should give admin permissions and the window opens. Then click on "java" tab. There you can see the JVM and JAVA classpath.

How to delete a stash created with git stash create?

git stash           // create stash,
git stash push -m "message" // create stash with msg,
git stash apply         // to apply stash,
git stash apply indexno // to apply  specific stash, 
git stash list          //list stash,
git stash drop indexno      //to delete stash,
git stash pop indexno,
git stash pop = stash drop + stash apply
git stash clear         //clear all your local stashed code

How to set up a Web API controller for multipart/form-data

5 years later on and .NET Core 3.1 allows you to do specify the media type like this:

[HttpPost]
[Consumes("multipart/form-data")]
public IActionResult UploadLogo()
{
    return Ok();
}

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

i had this problem :

Installation did not succeed.
The application could not be installed: INSTALL_FAILED_CONFLICTING_PROVIDER

but it was not from provider of manifest the below library in my app has conflict with other app and the others can not be install:

implementation 'com.iceteck.silicompressorr:silicompressor:2.2.1'

og:type and valid values : constantly being parsed as og:type=website

As of May 2018, you can find the full list here: https://developers.facebook.com/docs/reference/opengraph#object-type

apps.saves An action representing someone saving an app to try later.

article This object represents an article on a website. It is the preferred type for blog posts and news stories.

book This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books. Do not use this type to represent magazines

books.author This object type represents a single author of a book.

books.book This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books

books.genre This object type represents the genre of a book or publication.

books.quotes
Returns no data as of April 4, 2018.

An action representing someone quoting from a book.

books.rates
Returns no data as of April 4, 2018.

An action representing someone rating a book.

books.reads
Returns no data as of April 4, 2018.

An action representing someone reading a book.

books.wants_to_read
Returns no data as of April 4, 2018.

An action representing someone wanting to read a book.

business.business This object type represents a place of business that has a location, operating hours and contact information.

fitness.bikes
Returns no data as of April 4, 2018.

An action representing someone cycling a course.

fitness.course This object type represents the user's activity contributing to a particular run, walk, or bike course.

fitness.runs
Returns no data as of April 4, 2018.

An action representing someone running a course.

fitness.walks
Returns no data as of April 4, 2018.

An action representing someone walking a course.

game.achievement This object type represents a specific achievement in a game. An app must be in the 'Games' category in App Dashboard to be able to use this object type. Every achievement has a game:points value associate with it. This is not related to the points the user has scored in the game, but is a way for the app to indicate the relative importance and scarcity of different achievements: * Each game gets a total of 1,000 points to distribute across its achievements * Each game gets a maximum of 1,000 achievements * Achievements which are scarcer and have higher point values will receive more distribution in Facebook's social channels. For example, achievements which have point values of less than 10 will get almost no distribution. Apps should aim for between 50-100 achievements consisting of a mix of 50 (difficult), 25 (medium), and 10 (easy) point value achievements Read more on how to use achievements in this guide.

games.achieves An action representing someone reaching a game achievement.

games.celebrate An action representing someone celebrating a victory in a game.

games.plays An action representing someone playing a game. Stories for this action will only appear in the activity log.

games.saves An action representing someone saving a game.

music.album This object type represents a music album; in other words, an ordered collection of songs from an artist or a collection of artists. An album can comprise multiple discs.

music.listens
Returns no data as of April 4, 2018.

An action representing someone listening to a song, album, radio station, playlist or musician

music.playlist This object type represents a music playlist, an ordered collection of songs from a collection of artists.

music.playlists
Returns no data as of April 4, 2018.

An action representing someone creating a playlist.

music.radio_station This object type represents a 'radio' station of a stream of audio. The audio properties should be used to identify the location of the stream itself.

music.song This object type represents a single song.

news.publishes An action representing someone publishing a news article.

news.reads
Returns no data as of April 4, 2018.

An action representing someone reading a news article.

og.follows An action representing someone following a Facebook user

og.likes An action representing someone liking any object.

pages.saves An action representing someone saving a place.

place This object type represents a place - such as a venue, a business, a landmark, or any other location which can be identified by longitude and latitude.

product This object type represents a product. This includes both virtual and physical products, but it typically represents items that are available in an online store.

product.group This object type represents a group of product items.

product.item This object type represents a product item.

profile This object type represents a person. While appropriate for celebrities, artists, or musicians, this object type can be used for the profile of any individual. The fb:profile_id field associates the object with a Facebook user.

restaurant.menu This object type represents a restaurant's menu. A restaurant can have multiple menus, and each menu has multiple sections.

restaurant.menu_item This object type represents a single item on a restaurant's menu. Every item belongs within a menu section.

restaurant.menu_section This object type represents a section in a restaurant's menu. A section contains multiple menu items.

restaurant.restaurant This object type represents a restaurant at a specific location.

restaurant.visited An action representing someone visiting a restaurant.

restaurant.wants_to_visit An action representing someone wanting to visit a restaurant

sellers.rates An action representing a commerce seller has been given a rating.

video.episode This object type represents an episode of a TV show and contains references to the actors and other professionals involved in its production. An episode is defined by us as a full-length episode that is part of a series. This type must reference the series this it is part of.

video.movie This object type represents a movie, and contains references to the actors and other professionals involved in its production. A movie is defined by us as a full-length feature or short film. Do not use this type to represent movie trailers, movie clips, user-generated video content, etc.

video.other This object type represents a generic video, and contains references to the actors and other professionals involved in its production. For specific types of video content, use the video.movie or video.tv_show object types. This type is for any other type of video content not represented elsewhere (eg. trailers, music videos, clips, news segments etc.)

video.rates
Returns no data as of April 4, 2018.

An action representing someone rating a movie, TV show, episode or another piece of video content.

video.tv_show This object type represents a TV show, and contains references to the actors and other professionals involved in its production. For individual episodes of a series, use the video.episode object type. A TV show is defined by us as a series or set of episodes that are produced under the same title (eg. a television or online series)

video.wants_to_watch
Returns no data as of April 4, 2018.

An action representing someone wanting to watch video content.

video.watches
Returns no data as of April 4, 2018.

An action representing someone watching video content.

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

My problem was that I tried to import a Django model before calling django.setup()

This worked for me:

import django
django.setup()

from myapp.models import MyModel

The above script is in the project root folder.

Interfaces vs. abstract classes

The advantages of an abstract class are:

  • Ability to specify default implementations of methods
  • Added invariant checking to functions
  • Have slightly more control in how the "interface" methods are called
  • Ability to provide behavior related or unrelated to the interface for "free"

Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.

HorizontalScrollView within ScrollView Touch Handling

This finally became a part of support v4 library, NestedScrollView. So, no longer local hacks is needed for most of cases I'd guess.

Random number c++ in some range

Since nobody posted the modern C++ approach yet,

#include <iostream>
#include <random>
int main()
{
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 gen(rd()); // seed the generator
    std::uniform_int_distribution<> distr(25, 63); // define the range

    for(int n=0; n<40; ++n)
        std::cout << distr(gen) << ' '; // generate numbers
}

how to select rows based on distinct values of A COLUMN only

if you dont wanna use DISTINCT use GROUP BY

 SELECT * FROM myTABLE GROUP BY EmailAddress

Rotate label text in seaborn factorplot

Any seaborn plots suported by facetgrid won't work with (e.g. catplot)

g.set_xticklabels(rotation=30) 

however barplot, countplot, etc. will work as they are not supported by facetgrid. Below will work for them.

g.set_xticklabels(g.get_xticklabels(), rotation=30)

Also, in case you have 2 graphs overlayed on top of each other, try set_xticklabels on graph which supports it.

Show hide div using codebehind

There are a few ways to handle rendering/showing controls on the page and you should take note to what happens with each method.

Rendering and Visibility

There are some instances where elements on your page don't need to be rendered for the user because of some type of logic or database value. In this case, you can prevent rendering (creating the control on the returned web page) altogether. You would want to do this if the control doesn't need to be shown later on the client side because no matter what, the user viewing the page never needs to see it.

Any controls or elements can have their visibility set from the server side. If it is a plain old html element, you just need to set the runat attribute value to server on the markup page.

<div id="myDiv" runat="server"></div>

The decision to render the div or not can now be done in the code behind class like so:

myDiv.Visible = someConditionalBool;

If set to true, it will be rendered on the page and if it's false it won't be rendered at all, not even hidden.

Client Side Hiding

Hiding an element is done on the client side only. Meaning, it's rendered but it has a display CSS style set on it which instructs your browser to not show it to the user. This is beneficial when you want to hide/show things based on user input. It's important to know that the element CAN be hidden on the server side too as long as the element/control has runat=server set just as I explained in the previous example.

Hiding in the Code Behind Class

To hide an element that you want rendered to the page but hidden is another simple single line of code:

myDiv.Style["display"] = "none";

If you have a need to remove the display style server side, it can be done by removing the display style, or setting it to a different value like inline or block (values described here).

myDiv.Style.Remove("display");
// -- or --
myDiv.Style["display"] = "inline";

Hiding on the Client Side with javascript

Using plain old javascript, you can easily hide the same element in this manner

var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";

// then to show again
myDivElem.style.display = "";

jQuery makes hiding elements a little simpler if you prefer to use jQuery:

var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();

// ... and to show 
myDiv.show();

jquery mobile background image

just simple replace your class with this.

.ui-page
{
   background: transparent url(images/EarthIcon.jpg) no-repeat center center;
}

I have same issue and i solved it.

How to get process ID of background process?

An even simpler way to kill all child process of a bash script:

pkill -P $$

The -P flag works the same way with pkill and pgrep - it gets child processes, only with pkill the child processes get killed and with pgrep child PIDs are printed to stdout.

No process is on the other end of the pipe (SQL Server 2012)

In my case the database was restored and it already had the user used for the connection. I had to drop the user in the database and recreate the user-mapping for the login.

  1. Drop the user

    DROP USER [MyUser]
    

It might fail if the user owns any schemas. Those has to assigned to dbo before dropping the user. Get the schemas owned by the user using first query below and then alter the owner of those schemas using second query (HangFire is the schema obtained from previous query).

select * from information_schema.schemata where schema_owner = 'MyUser'
ALTER AUTHORIZATION ON SCHEMA::[HangFire] TO [dbo]     
  1. Update user mapping for the user. In management studio go to Security-> Login -> Open the user -> Go to user mapping tab -> Enable the database and grant appropriate role.

shell script. how to extract string using regular expressions

One way would be with sed. For example:

echo $name | sed -e 's?http://www\.??'

Normally the sed regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:

echo ${name#http://www.}

(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)

PHP Echo text Color

This is an old question, but no one responded to the question regarding centering text in a terminal.

/**
 * Centers a string of text in a terminal window
 *
 * @param string $text The text to center
 * @param string $pad_string If set, the string to pad with (eg. '=' for a nice header)
 *
 * @return string The padded result, ready to echo
 */
function center($text, $pad_string = ' ') {
    $window_size = (int) `tput cols`;
    return str_pad($text, $window_size, $pad_string, STR_PAD_BOTH)."\n";
}

echo center('foo');
echo center('bar baz', '=');

Python Pandas - Find difference between two data frames

edit2, I figured out a new solution without the need of setting index

newdf=pd.concat([df1,df2]).drop_duplicates(keep=False)

Okay i found the answer of highest vote already contain what I have figured out. Yes, we can only use this code on condition that there are no duplicates in each two dfs.


I have a tricky method. First we set ’Name’ as the index of two dataframe given by the question. Since we have same ’Name’ in two dfs, we can just drop the ’smaller’ df’s index from the ‘bigger’ df. Here is the code.

df1.set_index('Name',inplace=True)
df2.set_index('Name',inplace=True)
newdf=df1.drop(df2.index)

Get current time in milliseconds using C++ and Boost

If you mean milliseconds since epoch you could do

ptime time_t_epoch(date(1970,1,1)); 
ptime now = microsec_clock::local_time();
time_duration diff = now - time_t_epoch;
x = diff.total_milliseconds();

However, it's not particularly clear what you're after.

Have a look at the example in the documentation for DateTime at Boost Date Time

Converting integer to digit list

Convert the integer to string first, and then use map to apply int on it:

>>> num = 132
>>> map(int, str(num))    #note, This will return a map object in python 3.
[1, 3, 2]

or using a list comprehension:

>>> [int(x) for x in str(num)]
[1, 3, 2]

Set height of chart in Chart.js

Just to add on to the answer given by @numediaweb

In case you're banging your head against the wall because after following the instructions to set maintainAspectRatio=false: I originally copied my code from an example I got on a website on using Chart.js with Angular 2+:

        <div style="display: block">
          <canvas baseChart
                  [datasets]="chartData"
                  [labels]="chartLabels"
                  [options]="chartOptions"
                  [legend]="chartLegend"
                  [colors]="chartColors"
                  [chartType]="chartType">
          </canvas>
        </div>

To make this work correctly you must remove the embedded (and unnecessary) style="display: block" Instead define a class for the enclosing div, and define its height in CSS.

Once you do that, the chart should have responsive width but fixed height.

Last non-empty cell in a column

Inspired by the great lead given by Doug Glancy's answer, I came up with a way to do the same thing without the need of an array-formula. Do not ask me why, but I am keen to avoid the use of array formulae if at all possible (not for any particular reason, it's just my style).

Here it is:

=SUMPRODUCT(MAX(($A:$A<>"")*(ROW(A:A))))

For finding the last non-empty row using Column A as the reference column

=SUMPRODUCT(MAX(($1:$1<>"")*(COLUMN(1:1))))

For finding the last non-empty column using row 1 as the reference row

This can be further utilized in conjunction with the index function to efficiently define dynamic named ranges, but this is something for another post as this is not related to the immediate question addressed herein.

I've tested the above methods with Excel 2010, both "natively" and in "Compatibility Mode" (for older versions of Excel) and they work. Again, with these you do not need to do any of the Ctrl+Shift+Enter. By leveraging the way sumproduct works in Excel we can get our arms around the need to carry array-operations but we do it without an array-formula. I hope someone out there may appreciate the beauty, simplicity and elegance of these proposed sumproduct solutions as much as I do. I do not attest to the memory-efficiency of the above solutions though. Just that they are simple, look beautiful, help the intended purpose and are flexible enough to extend their use to other purposes :)

Hope this helps!

All the best!

Remove Top Line of Text File with PowerShell

Inspired by AASoft's answer, I went out to improve it a bit more:

  1. Avoid the loop variable $i and the comparison with 0 in every loop
  2. Wrap the execution into a try..finally block to always close the files in use
  3. Make the solution work for an arbitrary number of lines to remove from the beginning of the file
  4. Use a variable $p to reference the current directory

These changes lead to the following code:

$p = (Get-Location).Path

(Measure-Command {
    # Number of lines to skip
    $skip = 1
    $ins = New-Object System.IO.StreamReader ($p + "\test.log")
    $outs = New-Object System.IO.StreamWriter ($p + "\test-1.log")
    try {
        # Skip the first N lines, but allow for fewer than N, as well
        for( $s = 1; $s -le $skip -and !$ins.EndOfStream; $s++ ) {
            $ins.ReadLine()
        }
        while( !$ins.EndOfStream ) {
            $outs.WriteLine( $ins.ReadLine() )
        }
    }
    finally {
        $outs.Close()
        $ins.Close()
    }
}).TotalSeconds

The first change brought the processing time for my 60 MB file down from 5.3s to 4s. The rest of the changes is more cosmetic.

Jquery : Refresh/Reload the page on clicking a button

You can also use window.location.href=window.location.href;

'pip' is not recognized as an internal or external command

Try going to Windows PowerShell or cmd prompt and typing:

python -m pip install openpyxl

How do I change JPanel inside a JFrame on the fly?

It all depends on how its going to be used. If you will want to switch back and forth between these two panels then use a CardLayout. If you are only switching from the first to the second once and (and not going back) then I would use telcontars suggestion and just replace it. Though if the JPanel isn't the only thing in your frame I would use remove(java.awt.Component) instead of removeAll.

If you are somewhere in between these two cases its basically a time-space tradeoff. The CardLayout will save you time but take up more memory by having to keep this whole other panel in memory at all times. But if you just replace the panel when needed and construct it on demand, you don't have to keep that meory around but it takes more time to switch.

Also you can try a JTabbedPane to use tabs instead (its even easier than CardLayout because it handles the showing/hiding automitically)

How can we print line numbers to the log in java

For anyone wondering, the index in the getStackTrace()[3] method signals the amount of threads the triggering line travels until the actual .getStackTrace() method excluding the executing line.

This means that if the Thread.currentThread().getStackTrace()[X].getLineNumber(); line is executed from 3 nested methods above, the index number must be 3.

Example:

First layer

private static String message(String TAG, String msg) {

    int lineNumber = Thread.currentThread().getStackTrace()[3].getLineNumber();

    return ".(" + TAG + ".java:"+ lineNumber +")" + " " + msg;
}

Second Layer

private static void print(String s) {
        System.out.println(s);
}

Third Layer

public static void normal(
        String TAG,
        String message
) {
    print(
            message(
                    TAG,
                    message
            )
    );
}

Executing Line:

    Print.normal(TAG, "StatelessDispatcher");

As someone that has not received any formal education on IT, this has been mind opening on how compilers work.

Different class for the last element in ng-repeat

To elaborate on Paul's answer, this is the controller logic that coincides with the template code.

// HTML
<div class="row" ng-repeat="thing in things">
  <div class="well" ng-class="isLast($last)">
      <p>Data-driven {{thing.name}}</p>
  </div>
</div>

// CSS
.last { /* Desired Styles */}

// Controller
$scope.isLast = function(check) {
    var cssClass = check ? 'last' : null;
    return cssClass;
};

Its also worth noting that you really should avoid this solution if possible. By nature CSS can handle this, making a JS-based solution is unnecessary and non-performant. Unfortunately if you need to support IE8> this solution won't work for you (see MDN support docs).

CSS-Only Solution

// Using the above example syntax
.row:last-of-type { /* Desired Style */ }

How to write to error log file in PHP

We all know that PHP save errors in php_errors.log file.

But, that file contains a lot of data.

If we want to log our application data, we need to save it to a custom location.

We can use two parameters in the error_log function to achieve this.

http://php.net/manual/en/function.error-log.php

We can do it using:

error_log(print_r($v, TRUE), 3, '/var/tmp/errors.log');

Where,

print_r($v, TRUE) : logs $v (array/string/object) to log file. 3: Put log message to custom log file specified in the third parameter.

'/var/tmp/errors.log': Custom log file (This path is for Linux, we can specify other depending upon OS).

OR, you can use file_put_contents()

file_put_contents('/var/tmp/e.log', print_r($v, true), FILE_APPEND);

Where:

'/var/tmp/errors.log': Custom log file (This path is for Linux, we can specify other depending upon OS). print_r($v, TRUE) : logs $v (array/string/object) to log file. FILE_APPEND: Constant parameter specifying whether to append to the file if it exists, if file does not exist, new file will be created.

Compare two Lists for differences

.... but how do we find the equivalent class in the second List to pass to the method below;

This is your actual problem; you must have at least one immutable property, a id or something like that, to identify corresponding objects in both lists. If you do not have such a property you, cannot solve the problem without errors. You can just try to guess corresponding objects by searching for minimal or logical changes.

If you have such an property, the solution becomes really simple.

Enumerable.Join(
   listA, listB,
   a => a.Id, b => b.Id,
   (a, b) => CompareTwoClass_ReturnDifferences(a, b))

thanks to you both danbruc and Noldorin for your feedback. both Lists will be the same length and in the same order. so the method above is close, but can you modify this method to pass the enum.Current to the method i posted above?

Now I am confused ... what is the problem with that? Why not just the following?

for (Int32 i = 0; i < Math.Min(listA.Count, listB.Count); i++)
{
    yield return CompareTwoClass_ReturnDifferences(listA[i], listB[i]);
}

The Math.Min() call may even be left out if equal length is guaranted.


Noldorin's implementation is of course smarter because of the delegate and the use of enumerators instead of using ICollection.

Sleep for milliseconds

To stay portable you could use Boost::Thread for sleeping:

#include <boost/thread/thread.hpp>

int main()
{
    //waits 2 seconds
    boost::this_thread::sleep( boost::posix_time::seconds(1) );
    boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );

    return 0;
}

This answer is a duplicate and has been posted in this question before. Perhaps you could find some usable answers there too.

java how to use classes in other package?

You have to provide the full path that you want to import.

import com.my.stuff.main.Main;
import com.my.stuff.second.*;

So, in your main class, you'd have:

package com.my.stuff.main

import com.my.stuff.second.Second;   // THIS IS THE IMPORTANT LINE FOR YOUR QUESTION

class Main {
   public static void main(String[] args) {
      Second second = new Second();
      second.x();  
   }
}

EDIT: adding example in response to Shawn D's comment

There is another alternative, as Shawn D points out, where you can specify the full package name of the object that you want to use. This is very useful in two locations. First, if you're using the class exactly once:

class Main {
    void function() {
        int x = my.package.heirarchy.Foo.aStaticMethod();

        another.package.heirarchy.Baz b = new another.package.heirarchy.Bax();
    }
}

Alternatively, this is useful when you want to differentiate between two classes with the same short name:

class Main {
    void function() {
        java.util.Date utilDate = ...;
        java.sql.Date sqlDate = ...;
    }
}

Should I use JSLint or JSHint JavaScript validation?

[EDIT]
This answer has been edited. I'm leaving the original answer below for context (otherwise the comments wouldn't make sense).

When this question was originally asked, JSLint was the main linting tool for JavaScript. JSHint was a new fork of JSLint, but had not yet diverged much from the original.

Since then, JSLint has remained pretty much static, while JSHint has changed a great deal - it has thrown away many of JSLint's more antagonistic rules, has added a whole load of new rules, and has generally become more flexible. Also, another tool ESLint is now available, which is even more flexible and has more rule options.

In my original answer, I said that you should not force yourself to stick to JSLint's rules; as long as you understood why it was throwing a warning, you could make a judgement for yourself about whether to change the code to resolve the warning or not.

With the ultra-strict ruleset of JSLint from 2011, this was reasonable advice -- I've seen very few JavaScript codesets that could pass a JSLint test. However with the more pragmatic rules available in today's JSHint and ESLint tools, it is a much more realistic proposition to try to get your code passing through them with zero warnings.

There may still occasionally be cases where a linter will complain about something that you've done intentionally -- for example, you know that you should always use === but just this one time you have a good reason to use ==. But even then, with ESLint you have the option to specify eslint-disable around the line in question so you can still have a passing lint test with zero warnings, with the rest of your code obeying the rule. (just don't do that kind of thing too often!)


[ORIGINAL ANSWER FOLLOWS]

By all means use JSLint. But don't get hung up on the results and on fixing everything that it warns about. It will help you improve your code, and it will help you find potential bugs, but not everything that JSLint complains about turns out to be a real problem, so don't feel like you have to complete the process with zero warnings.

Pretty much any Javascript code with any significant length or complexity will produce warnings in JSLint, no matter how well written it is. If you don't believe me, try running some popular libraries like JQuery through it.

Some JSLint warnings are more valuable than others: learn which ones to watch out for, and which ones are less important. Every warning should be considered, but don't feel obliged to fix your code to clear any given warning; it's perfectly okay to look at the code and decide you're happy with it; there are times when things that JSlint doesn't like are actually the right thing to do.

Difference between Activity and FragmentActivity

FragmentActivity is part of the support library, while Activity is the framework's default class. They are functionally equivalent.

You should always use FragmentActivity and android.support.v4.app.Fragment instead of the platform default Activity and android.app.Fragment classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.

How to import component into another root component in Angular 2

above answers In simple words, you have to register under @NgModule's

declarations: [
    AppComponent, YourNewComponentHere
  ] 

of app.module.ts

do not forget to import that component.

JavaScript: get code to run every minute

You could use setInterval for this.

<script type="text/javascript">
function myFunction () {
    console.log('Executed!');
}

var interval = setInterval(function () { myFunction(); }, 60000);
</script>

Disable the timer by setting clearInterval(interval).

See this Fiddle: http://jsfiddle.net/p6NJt/2/

Parse large JSON file in Nodejs

If you have control over the input file, and it's an array of objects, you can solve this more easily. Arrange to output the file with each record on one line, like this:

[
   {"key": value},
   {"key": value},
   ...

This is still valid JSON.

Then, use the node.js readline module to process them one line at a time.

var fs = require("fs");

var lineReader = require('readline').createInterface({
    input: fs.createReadStream("input.txt")
});

lineReader.on('line', function (line) {
    line = line.trim();

    if (line.charAt(line.length-1) === ',') {
        line = line.substr(0, line.length-1);
    }

    if (line.charAt(0) === '{') {
        processRecord(JSON.parse(line));
    }
});

function processRecord(record) {
    // Process the records one at a time here! 
}

Where is `%p` useful with printf?

You cannot depend on %p displaying a 0x prefix. On Visual C++, it does not. Use %#p to be portable.

"Unable to find remote helper for 'https'" during git clone

In my case git --exec-path was pointing to the correct path and git-remote-https existed but didn't have execution permission. So chmod +x git-remote-http fixed the issue.

How do I correctly detect orientation change using Phonegap on iOS?

I've found this code to detect if the device is in landscape orientation and in this case add a splash page saying "change orientation to see the site". It's working on iOS, android and windows phones. I think that this is very useful since it's quite elegant and avoid to set a landscape view for the mobile site. The code is working very well. The only thing not completely satisfying is that if someone load the page being in landscape view the splash page doesn't appears.

<script>
(function() {
    'use strict';

    var isMobile = {
        Android: function() {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function() {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };
    if (isMobile.any()) {
        doOnOrientationChange();
        window.addEventListener('resize', doOnOrientationChange, 'false');
    }

    function doOnOrientationChange() {
        var a = document.getElementById('alert');
        var b = document.body;
        var w = b.offsetWidth;
        var h = b.offsetHeight;
        (w / h > 1) ? (a.className = 'show', b.className = 'full-body') : (a.className = 'hide', b.className = '');
    }
})();
</script>

And the HTML: <div id="alert" class="hide"> <div id="content">This site is not thought to be viewed in landscape mode, please turn your device </div> </div>

How to add a margin to a table row <tr>

A hack to give the appearance of margins between table rows is to give them a border the same color as the background. This is useful when styling a 3rd party theme where you can't change the html markup. Eg:

tr{ 
    border: 5px solid white;
}

Drop all data in a pandas dataframe

My favorite:

df = df.iloc[0:0]

But be aware df.index.max() will be nan. To add items I use:

df.loc[0 if math.isnan(df.index.max()) else df.index.max() + 1] = data

How to move the cursor word by word in the OS X Terminal

Here's how you can do it

By default, the Terminal has these shortcuts to move (left and right) word-by-word:

  • esc+B (left)
  • esc+F (right)

You can configure alt+ and to generate those sequences for you:

  • Open Terminal preferences (cmd+,);
  • At Settings tab, select Keyboard and double-click ? ? if it's there, or add it if it's not.
  • Set the modifier as desired, and type the shortcut key in the box: esc+B, generating the text \033b (you can't type this text manually).
  • Repeat for word-right (esc+F becomes \033f)

Alternatively, you can refer to this blog post over at textmate:

http://blog.macromates.com/2006/word-movement-in-terminal/

OnClick vs OnClientClick for an asp:CheckBox?

Because they are two different kinds of controls...

You see, your web browser doesn't know about server side programming. it only knows about it's own DOM and the event models that it uses... And for click events of objects rendered to it. You should examine the final markup that is actually sent to the browser from ASP.Net to see the differences your self.

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

renders to

<input type="check" OnClick="alert(this.checked);" />

and

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

renders to

<input type="check" OnClientClick="alert(this.checked);" />

Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...

When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see.

Fit cell width to content

Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.

One option is to replace table with CSS4 flex divs:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

That works in new browsers i.e. IE11+ see table at the bottom of the article.

tsql returning a table from a function or store procedure

You can't access Temporary Tables from within a SQL Function. You will need to use table variables so essentially:

ALTER FUNCTION FnGetCompanyIdWithCategories()
RETURNS  @rtnTable TABLE 
(
    -- columns returned by the function
    ID UNIQUEIDENTIFIER NOT NULL,
    Name nvarchar(255) NOT NULL
)
AS
BEGIN
DECLARE @TempTable table (id uniqueidentifier, name nvarchar(255)....)

insert into @myTable 
select from your stuff

--This select returns data
insert into @rtnTable
SELECT ID, name FROM @mytable 
return
END

Edit

Based on comments to this question here is my recommendation. You want to join the results of either a procedure or table-valued function in another query. I will show you how you can do it then you pick the one you prefer. I am going to be using sample code from one of my schemas, but you should be able to adapt it. Both are viable solutions first with a stored procedure.

declare @table as table (id int, name nvarchar(50),templateid int,account nvarchar(50))

insert into @table
execute industry_getall

select * 
from @table 
inner join [user] 
    on account=[user].loginname

In this case, you have to declare a temporary table or table variable to store the results of the procedure. Now Let's look at how you would do this if you were using a UDF

select *
from fn_Industry_GetAll()
inner join [user] 
    on account=[user].loginname

As you can see the UDF is a lot more concise easier to read, and probably performs a little bit better since you're not using the secondary temporary table (performance is a complete guess on my part).

If you're going to be reusing your function/procedure in lots of other places, I think the UDF is your best choice. The only catch is you will have to stop using #Temp tables and use table variables. Unless you're indexing your temp table, there should be no issue, and you will be using the tempDb less since table variables are kept in memory.

Types in Objective-C on iOS

Update for the new 64bit arch

Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

How to split a string with any whitespace chars as delimiters

To get this working in Javascript, I had to do the following:

myString.split(/\s+/g)

submitting a GET form with query string params and hidden params disappear

If you need workaround, as this form can be placed in 3rd party systems, you can use Apache mod_rewrite like this:

RewriteRule ^dummy.link$ index.php?a=1&b=2 [QSA,L]

then your new form will look like this:

<form ... action="http:/www.blabla.com/dummy.link" method="GET">
<input type="hidden" name="c" value="3" /> 
</form>

and Apache will append 3rd parameter to query

Reading rows from a CSV file in Python

The csv module handles csv files by row. If you want to handle it by column, pandas is a good solution.

Besides, there are 2 ways to get all (or specific) columns with pure simple Python code.

1. csv.DictReader

with open('demo.csv') as file:
    data = {}
    for row in csv.DictReader(file):
        for key, value in row.items():
            if key not in data:
                data[key] = []
            data[key].append(value)

It is easy to understand.

2. csv.reader with zip

with open('demo.csv') as file:
    data = {values[0]: values[1:] for values in zip(*csv.reader(file))}

This is not very clear, but efficient.

zip(x, y, z) transpose (x, y, z), while x, y, z are lists. *csv.reader(file) make (x, y, z) for zip, with column names.

Demo Result

The content of demo.csv:

a,b,c
1,2,3
4,5,6
7,8,9

The result of 1:

>>> print(data)
{'c': ['3', '6', '9'], 'b': ['2', '5', '8'], 'a': ['1', '4', '7']}

The result of 2:

>>> print(data)
{'c': ('3', '6', '9'), 'b': ('2', '5', '8'), 'a': ('1', '4', '7')}

How to display a "busy" indicator with jQuery?

yes, it's really just a matter of showing/hiding an animated gif.

How to access SVG elements with Javascript

In case you use jQuery you need to wait for $(window).load, because the embedded SVG document might not be yet loaded at $(document).ready

$(window).load(function () {

    //alert("Document loaded, including graphics and embedded documents (like SVG)");
    var a = document.getElementById("alphasvg");

    //get the inner DOM of alpha.svg
    var svgDoc = a.contentDocument;

    //get the inner element by id
    var delta = svgDoc.getElementById("delta");
    delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);
});

Replace text inside td using jQuery having td containing other elements

$('#demoTable td').contents().each(function() {
    if (this.nodeType === 3) {
        this.textContent
        ? this.textContent = 'The text has been '
        : this.innerText  = 'The text has been '
    } else {
        this.innerHTML = 'changed';
        return false;
    }
})

http://jsfiddle.net/YSAjU/

How to stop app that node.js express 'npm start'

Check with netstat -nptl all processes

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      1736/mongod     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1594/sshd       
tcp6       0      0 :::3977                 :::*                    LISTEN      6231/nodejs     
tcp6       0      0 :::22                   :::*                    LISTEN      1594/sshd       
tcp6       0      0 :::3200                 :::*                    LISTEN      5535/nodejs 

And it simply kills the process by the PID reference.... In my case I want to stop the 6231/nodejs so I execute the following command:

kill -9 6231

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

How do we count rows using older versions of Hibernate (~2009)?

Long count = (Long) session.createQuery("select count(*) from  Book").uniqueResult();

Javascript | Set all values of an array

Use a for loop and set each one in turn.

Why does git status show branch is up-to-date when changes exist upstream?

While these are all viable answers, I decided to give my way of checking if local repo is in line with the remote, whithout fetching or pulling. In order to see where my branches are I use simply:

git remote show origin

What it does is return all the current tracked branches and most importantly - the info whether they are up to date, ahead or behind the remote origin ones. After the above command, this is an example of what is returned:

  * remote origin
  Fetch URL: https://github.com/xxxx/xxxx.git
  Push  URL: https://github.com/xxxx/xxxx.git
  HEAD branch: master
  Remote branches:
    master      tracked
    no-payments tracked
  Local branches configured for 'git pull':
    master      merges with remote master
    no-payments merges with remote no-payments
  Local refs configured for 'git push':
    master      pushes to master      (local out of date)
    no-payments pushes to no-payments (local out of date)

Hope this helps someone.

Setting Column width in Apache POI

With Scala there is a nice Wrapper spoiwo

You can do it like this:

Workbook(mySheet.withColumns(
      Column(autoSized = true),
      Column(width = new Width(100, WidthUnit.Character)),
      Column(width = new Width(100, WidthUnit.Character)))
    )

Perform curl request in javascript?

curl is a command in linux (and a library in php). Curl typically makes an HTTP request.

What you really want to do is make an HTTP (or XHR) request from javascript.

Using this vocab you'll find a bunch of examples, for starters: Sending authorization headers with jquery and ajax

Essentially you will want to call $.ajax with a few options for the header, etc.

$.ajax({
        url: 'https://api.wit.ai/message?v=20140826&q=',
        beforeSend: function(xhr) {
             xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
        }, success: function(data){
            alert(data);
            //process the JSON data etc
        }
})

How to update only one field using Entity Framework?

You have basically two options:

  • go the EF way all the way, in that case, you would
    • load the object based on the userId provided - the entire object gets loaded
    • update the password field
    • save the object back using the context's .SaveChanges() method

In this case, it's up to EF how to handle this in detail. I just tested this, and in the case I only change a single field of an object, what EF creates is pretty much what you'd create manually, too - something like:

`UPDATE dbo.Users SET Password = @Password WHERE UserId = @UserId`

So EF is smart enough to figure out what columns have indeed changed, and it will create a T-SQL statement to handle just those updates that are in fact necessary.

  • you define a stored procedure that does exactly what you need, in T-SQL code (just update the Password column for the given UserId and nothing else - basically executes UPDATE dbo.Users SET Password = @Password WHERE UserId = @UserId) and you create a function import for that stored procedure in your EF model and you call this function instead of doing the steps outlined above

How to pass command line arguments to a shell alias?

The easiest way, is to use function not alias. you can still call a function at any time from the cli. In bash, you can just add function name() { command } it loads the same as an alias.

function mkcd() { mkdir $1; cd $1 ;}

Not sure about other shells

Block direct access to a file over http but allow php script access

If you have access to you httpd.conf file (in ubuntu it is in the /etc/apache2 directory), you should add the same lines that you would to the .htaccess file in the specific directory. That is (for example):

ServerName YOURSERVERNAMEHERE
<Directory /var/www/>
AllowOverride None
order deny,allow
Options -Indexes FollowSymLinks
</Directory>

Do this for every directory that you want to control the information, and you will have one file in one spot to manage all access. It the example above, I did it for the root directory, /var/www.

This option may not be available with outsourced hosting, especially shared hosting. But it is a better option than adding many .htaccess files.

Parenthesis/Brackets Matching using Stack algorithm

import java.util.*;

public class Parenthesis

 {

    public static void main(String...okok)

    {
        Scanner sc= new Scanner(System.in);
        String str=sc.next();
        System.out.println(isValid(str));

    }
    public static int isValid(String a) {
        if(a.length()%2!=0)
        {

            return 0;
        }
        else if(a.length()==0)
        {

            return 1;
        }
        else
        {

            char c[]=a.toCharArray();
            Stack<Character> stk =  new Stack<Character>();
            for(int i=0;i<c.length;i++)
            {
                if(c[i]=='(' || c[i]=='[' || c[i]=='{')
                {
                    stk.push(c[i]);
                }
                else
                {
                    if(stk.isEmpty())
                    {
                        return 0;
                        //break;
                    }
                    else
                    {

                        char cc=c[i];
                        if(cc==')' && stk.peek()=='(' )
                        {
                            stk.pop();
                        }
                        else if(cc==']' && stk.peek()=='[' )
                        {

                            stk.pop();
                        }
                        else if(cc=='}' && stk.peek()=='{' )
                        {

                            stk.pop();
                        }
                    }
                }

            }
            if(stk.isEmpty())
            {
                return 1;
            }else
            {
                return 0;
            }
        }



    }

}

Preserve Line Breaks From TextArea When Writing To MySQL

Here is what I use

$textToStore = nl2br(htmlentities($inputText, ENT_QUOTES, 'UTF-8'));

$inputText is the text provided by either the form or textarea. $textToStore is the returned text from nl2br and htmlentities, to be stored in your database. ENT_QUOTES will convert both double and single quotes, so you'll have no trouble with those.

"cannot be used as a function error"

This line is the problem:

int estimatedPopulation (int currentPopulation,
                         float growthRate (birthRate, deathRate))

Make it:

int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)

instead and invoke the function with three arguments like

estimatePopulation( currentPopulation, birthRate, deathRate );

OR declare it with two arguments like:

int estimatedPopulation (int currentPopulation, float growthrt ) { ... }

and call it as

estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));

Edit:

Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate variable in the main() hides the function with the same name. So within main() you can only access grouthRate as float. On the other hand, outside of the main() you can only access that name as a function, since that automatic variable is only visible within the scope of main().

Just hope I didn't confuse you further :)

How to apply filters to *ngFor?

You could also use the following:

<template ngFor let-item [ngForOf]="itemsList">
    <div *ng-if="conditon(item)"></div>
</template>

This will only show the div if your items matches the condition

See the angular documentation for more information If you would also need the index, use the following:

<template ngFor let-item [ngForOf]="itemsList" let-i="index">
    <div *ng-if="conditon(item, i)"></div>
</template>

Styling mat-select in Angular Material

For Angular9+, according to this, you can use:

.mat-select-panel {
    background: red;
    ....
}

Demo


Angular Material uses mat-select-content as class name for the select list content. For its styling I would suggest four options.

1. Use ::ng-deep:

Use the /deep/ shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The /deep/ combinator works to any depth of nested components, and it applies to both the view children and content children of the component. Use /deep/, >>> and ::ng-deep only with emulated view encapsulation. Emulated is the default and most commonly used view encapsulation. For more information, see the Controlling view encapsulation section. The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.

CSS:

::ng-deep .mat-select-content{
    width:2000px;
    background-color: red;
    font-size: 10px;   
}

DEMO


2. Use ViewEncapsulation

... component CSS styles are encapsulated into the component's view and don't affect the rest of the application. To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes: .... None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.

None value is what you will need to break the encapsulation and set material style from your component. So can set on the component's selector:

Typscript:

  import {ViewEncapsulation } from '@angular/core';
  ....
  @Component({
        ....
        encapsulation: ViewEncapsulation.None
 })  

CSS

.mat-select-content{
    width:2000px;
    background-color: red;
    font-size: 10px;
}

DEMO


3. Set class style in style.css

This time you have to 'force' styles with !important too.

style.css

 .mat-select-content{
   width:2000px !important;
   background-color: red !important;
   font-size: 10px !important;
 } 

DEMO


4. Use inline style

<mat-option style="width:2000px; background-color: red; font-size: 10px;" ...>

DEMO

How do I make a LinearLayout scrollable?

you can make any layout scrollable. Just under <?xml version="1.0" encoding="utf-8"?> add these lines:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

and at the end add </ScrollView>

example of a non-scrollable activity:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:verticalScrollbarPosition="right"
    tools:context="p32929.demo.MainActivity">


    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="102dp"
        android:id="@+id/textView"
        android:textSize="30sp" />
</RelativeLayout>

After making it scrollable, it becomes like this:

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:verticalScrollbarPosition="right"
        tools:context="p32929.demo.MainActivity">


        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="102dp"
            android:text="TextView"
            android:textSize="30sp" />
    </RelativeLayout>
</ScrollView>

Read each line of txt file to new array element

Just use this:

$array = explode("\n", file_get_contents('file.txt'));

Good way of getting the user's location in Android

Recently refactored to obtain the location of the code, learn some good ideas, and finally achieved a relatively perfect library and Demo.

@Gryphius's answer is good

    //request all valid provider(network/gps)
private boolean requestAllProviderUpdates() {
    checkRuntimeEnvironment();
    checkPermission();

    if (isRequesting) {
        EasyLog.d("Request location update is busy");
        return false;
    }


    long minTime = getCheckTimeInterval();
    float minDistance = getCheckMinDistance();

    if (mMapLocationListeners == null) {
        mMapLocationListeners = new HashMap<>();
    }

    mValidProviders = getValidProviders();
    if (mValidProviders == null || mValidProviders.isEmpty()) {
        throw new IllegalArgumentException("Not available provider.");
    }

    for (String provider : mValidProviders) {
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                if (location == null) {
                    EasyLog.e("LocationListener callback location is null.");
                    return;
                }
                printf(location);
                mLastProviderTimestamp = location.getTime();

                if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                    finishResult(location);
                } else {
                    doLocationResult(location);
                }

                removeProvider(location.getProvider());
                if (isEmptyValidProviders()) {
                    requestTimeoutMsgInit();
                    removeUpdates();
                }
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        };
        getLocationManager().requestLocationUpdates(provider, minTime, minDistance, locationListener);
        mMapLocationListeners.put(provider, locationListener);
        EasyLog.d("Location request %s provider update.", provider);
    }
    isRequesting = true;
    return true;
}

//remove request update
public void removeUpdates() {
    checkRuntimeEnvironment();

    LocationManager locationManager = getLocationManager();
    if (mMapLocationListeners != null) {
        Set<String> keys = mMapLocationListeners.keySet();
        for (String key : keys) {
            LocationListener locationListener = mMapLocationListeners.get(key);
            if (locationListener != null) {
                locationManager.removeUpdates(locationListener);
                EasyLog.d("Remove location update, provider is " + key);
            }
        }
        mMapLocationListeners.clear();
        isRequesting = false;
    }
}

//Compared with the last successful position, to determine whether you need to filter
private boolean isNeedFilter(Location location) {
    checkLocation(location);

    if (mLastLocation != null) {
        float distance = location.distanceTo(mLastLocation);
        if (distance < getCheckMinDistance()) {
            return true;
        }
        if (location.getAccuracy() >= mLastLocation.getAccuracy()
                && distance < location.getAccuracy()) {
            return true;
        }
        if (location.getTime() <= mLastProviderTimestamp) {
            return true;
        }
    }
    return false;
}

private void doLocationResult(Location location) {
    checkLocation(location);

    if (isNeedFilter(location)) {
        EasyLog.d("location need to filtered out, timestamp is " + location.getTime());
        finishResult(mLastLocation);
    } else {
        finishResult(location);
    }
}

//Return to the finished position
private void finishResult(Location location) {
    checkLocation(location);

    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    float accuracy = location.getAccuracy();
    long time = location.getTime();
    String provider = location.getProvider();

    if (mLocationResultListeners != null && !mLocationResultListeners.isEmpty()) {
        String format = "Location result:<%f, %f> Accuracy:%f Time:%d Provider:%s";
        EasyLog.i(String.format(format, latitude, longitude, accuracy, time, provider));

        mLastLocation = location;
        synchronized (this) {
            Iterator<LocationResultListener> iterator =  mLocationResultListeners.iterator();
            while (iterator.hasNext()) {
                LocationResultListener listener = iterator.next();
                if (listener != null) {
                    listener.onResult(location);
                }
                iterator.remove();
            }
        }
    }
}

Complete implementation: https://github.com/bingerz/FastLocation/blob/master/fastlocationlib/src/main/java/cn/bingerz/fastlocation/FastLocation.java

1.Thanks @Gryphius solution ideas, I also share the complete code.

2.Each request to complete the location, it is best to removeUpdates, otherwise the phone status bar will always display the positioning icon

"git rebase origin" vs."git rebase origin/master"

Here's a better option:

git remote set-head -a origin

From the documentation:

With -a, the remote is queried to determine its HEAD, then $GIT_DIR/remotes//HEAD is set to the same branch. e.g., if the remote HEAD is pointed at next, "git remote set-head origin -a" will set $GIT_DIR/refs/remotes/origin/HEAD to refs/remotes/origin/next. This will only work if refs/remotes/origin/next already exists; if not it must be fetched first.

This has actually been around quite a while (since v1.6.3); not sure how I missed it!

NuGet Packages are missing

Tiberiu is correct. I had to edit my .csproj file as the files were moved and caused this issue

 <Import Project="..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.1\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.1\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />

I changed at top of the file and at the bottom

<Error Condition="!Exists('..\..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props'))" />
<Error Condition="!Exists('..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.1\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.1\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

Selecting a Record With MAX Value

What do you mean costs too much? Too much what?

SELECT MAX(Balance) AS MaxBalance, CustomerID FROM CUSTOMERS GROUP BY CustomerID

If your table is properly indexed (Balance) and there has got to be an index on the PK than I am not sure what you mean about costs too much or seems unreliable? There is nothing unreliable about an aggregate that you are using and telling it to do. In this case, MAX() does exactly what you tell it to do - there's nothing magical about it.

Take a look at MAX() and if you want to filter it use the HAVING clause.

Bootstrap 3 - Responsive mp4-video

Tip for MULTIPLE VIDEOS on a page: I recently solved an issue with no mp4 playback in Chrome or Firefox (played fine in IE) in a page with 16 videos in modals (bootstrap 3) after discovering the frame rates of all the videos must be identical. I had 6 videos at 25fps and 12 at 29.97fps... after rendering all to 25fps versions, everything runs smooth across all browsers.

HTTPS setup in Amazon EC2

First, you need to open HTTPS port (443). To do that, you go to https://console.aws.amazon.com/ec2/ and click on the Security Groups link on the left, then create a new security group with also HTTPS available. Then, just update the security group of a running instance or create a new instance using that group.

After these steps, your EC2 work is finished, and it's all an application problem.

Simulate a click on 'a' element using javascript/jquery

Here, try this one:

$('#gift-close').on('click', function () {
    _gaq.push(['_trackEvent','voucher_new','cart',$(this).attr('rel')+'-mask_x_button-inaction']);
});

How to remove MySQL completely with config and library files?

Just a little addition to the answer of @dAm2k :

In addition to sudo apt-get remove --purge mysql\*

I've done a sudo apt-get remove --purge mariadb\*.

I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.

Hope it helps.

Regular expression for first and last name

Don't forget about names like:

  • Mathias d'Arras
  • Martin Luther King, Jr.
  • Hector Sausage-Hausen

This should do the trick for most things:

/^[a-z ,.'-]+$/i

OR Support international names with super sweet unicode:

/^[a-zA-ZàáâäãåacceèéêëeiìíîïlnòóôöõøùúûüuuÿýzzñçcšžÀÁÂÄÃÅACCEEÈÉÊËÌÍÎÏILNÒÓÔÖÕØÙÚÛÜUUŸÝZZÑßÇŒÆCŠŽ?ð ,.'-]+$/u

Where is the itoa function in Linux?

The replacement with snprintf is NOT complete!

It covers only bases: 2, 8, 10, 16, whereas itoa works for bases between 2 and 36.

Since I was searching a replacement for base 32, I guess I'll have to code my own!

extract month from date in python

>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'

Python: How exactly can you take a string, split it, reverse it and join it back together again?

Not fitting 100% to this particular question but if you want to split from the back you can do it like this:

theStringInQuestion[::-1].split('/', 1)[1][::-1]

This code splits once at symbol '/' from behind.

A table name as a variable

Change your last statement to this:

EXEC('SELECT * FROM ' + @tablename)

This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.

--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE @table_name varchar(max)
SET @table_name =
    (SELECT 'TEST_'
            + DATENAME(YEAR,GETDATE())
            + UPPER(DATENAME(MONTH,GETDATE())) )

--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
          FROM sysobjects
          WHERE name = @table_name AND xtype = 'U')

BEGIN
    EXEC('drop table ' +  @table_name)
END

--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + @table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')

How do I view 'git diff' output with my preferred diff tool/ viewer?

You may want to try out xd http://github.com/jiqingtang/xd, which is GUI wrapper for GIT/SVN diff. It is NOT a diff tool itself. You run xd when you want to run git diff or svn diff and it will show you a list of files, a preview window and you can launch any diff tool you like, including tkdiff, xxdiff, gvimdiff, emacs(ediff), xemacs(ediff), meld, diffuse, kompare and kdiff3. You can also run any custom tool.

Unfortunately the tool doesn't support Windows.

Disclosure: I am the author of this tool.

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

In my case,I was getting error while refreshing gradle ('View'->Tool Windows->Gradle) tab and hit "refresh" and getting this error no such property gradleversion for class jetgradleplugin.

Had to install latest intellij compatible with gradle 5+

ValueError: could not convert string to float: id

Your data may not be what you expect -- it seems you're expecting, but not getting, floats.

A simple solution to figuring out where this occurs would be to add a try/except to the for-loop:

for i in range(0,N):
    w=f[i].split()
    l1=w[1:8]
    l2=w[8:15]
    try:
      list1=[float(x) for x in l1]
      list2=[float(x) for x in l2]
    except ValueError, e:
      # report the error in some way that is helpful -- maybe print out i
    result=stats.ttest_ind(list1,list2)
    print result[1]

Java multiline string

I sometimes use a parallel groovy class just to act as a bag of strings

The java class here

public class Test {
    public static void main(String[] args) {
        System.out.println(TestStrings.json1);
        // consume .. parse json
    }
}

And the coveted multiline strings here in TestStrings.groovy

class TestStrings {
    public static String json1 = """
    {
        "name": "Fakeer's Json",
        "age":100,
        "messages":["msg 1","msg 2","msg 3"]
    }""";
}

Of course this is for static strings only. If I have to insert variables in the text I will just change the entire file to groovy. Just maintain strong-typing practices and it can be pulled off.

Get a resource using getResource()

if you are calling from static method, use :

TestGameTable.class.getClassLoader().getResource("dice.jpg");

How to add a column in TSQL after a specific column?

You have to rebuild the table. Luckily, the order of the columns doesn't matter at all!

Watch as I magically reorder your columns:

SELECT ID, Newfield, FieldA, FieldB FROM MyTable

Also this has been asked about a bazillion times before.

how to use #ifdef with an OR condition?

OR condition in #ifdef

#if defined LINUX || defined ANDROID
// your code here
#endif /* LINUX || ANDROID */

or-

#if defined(LINUX) || defined(ANDROID)
// your code here
#endif /* LINUX || ANDROID */

Both above are the same, which one you use simply depends on your taste.


P.S.: #ifdef is simply the short form of #if defined, however, does not support complex condition.


Further-

  • AND: #if defined LINUX && defined ANDROID
  • XOR: #if defined LINUX ^ defined ANDROID

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

Separators for Navigation

You can add one li element where you want to add divider

<ul>
    <li> your content </li>
    <li class="divider-vertical-second-menu"></li>
    <li> NExt content </li>
    <li class="divider-vertical-second-menu"></li>
    <li> last item </li>
</ul>

In CSS you can Add following code.

.divider-vertical-second-menu{
   height: 40px;
   width: 1px;
   margin: 0 5px;
   overflow: hidden;
   background-color: #DDD;
   border-right: 2px solid #FFF;
}

This will increase you speed of execution as it will not load any image. just test it out.. :)

MAX function in where clause mysql

We can't reference the result of an aggregate function (for example MAX() ) in a WHERE clause of the same SELECT.

The normative pattern for solving this type of problem is to use an inline view, something like this:

SELECT t.firstName
     , t.Lastname
     , t.id
  FROM mytable t
  JOIN ( SELECT MAX(mx.id) AS max_id
           FROM mytable mx
       ) m
    ON m.max_id = t.id

This is just one way to get the specified result. There are several other approaches to get the same result, and some of those can be much less efficient than others. Other answers demonstrate this approach:

 WHERE t.id = (SELECT MAX(id) FROM ... )

Sometimes, the simplest approach is to use an ORDER BY with a LIMIT. (Note that this syntax is specific to MySQL)

SELECT t.firstName
     , t.Lastname
     , t.id
  FROM mytable t
 ORDER BY t.id DESC
 LIMIT 1

Note that this will return only one row; so if there is more than one row with the same id value, then this won't return all of them. (The first query will return ALL the rows that have the same id value.)

This approach can be extended to get more than one row, you could get the five rows that have the highest id values by changing it to LIMIT 5.

Note that performance of this approach is particularly dependent on a suitable index being available (i.e. with id as the PRIMARY KEY or as the leading column in another index.) A suitable index will improve performance of queries using all of these approaches.

How do I decode a string with escaped unicode?

Note that the use of unescape() is deprecated and doesn't work with the TypeScript compiler, for example.

Based on radicand's answer and the comments section below, here's an updated solution:

var string = "http\\u00253A\\u00252F\\u00252Fexample.com";
decodeURIComponent(JSON.parse('"' + string.replace(/\"/g, '\\"') + '"'));

http://example.com

Cancel a UIView animation?

On iOS 4 and greater, use the UIViewAnimationOptionBeginFromCurrentState option on the second animation to cut the first animation short.

As an example, assume you have a view with an activity indicator. You wish to fade in the activity indicator while some potentially time consuming activity begins, and fade it out when the activity is finished. In the code below, the view with the activity indicator on it is called activityView.

- (void)showActivityIndicator {
    activityView.alpha = 0.0;
    activityView.hidden = NO;
    [UIView animateWithDuration:0.5
                 animations:^(void) {
                     activityView.alpha = 1.0;
                 }];

- (void)hideActivityIndicator {
    [UIView animateWithDuration:0.5
                 delay:0 options:UIViewAnimationOptionBeginFromCurrentState
                 animations:^(void) {
                     activityView.alpha = 0.0;
                 }
                 completion:^(BOOL completed) {
                     if (completed) {
                         activityView.hidden = YES;
                     }
                 }];
}

Make the current commit the only (initial) commit in a Git repository?

Just delete the Github repo and create a new one. By far the fastest, easiest and safest approach. After all, what do you have to gain carrying out all those commands in the accepted solution when all you want is the master branch with a single commit?

How to use fetch in typescript

If you take a look at @types/node-fetch you will see the body definition

export class Body {
    bodyUsed: boolean;
    body: NodeJS.ReadableStream;
    json(): Promise<any>;
    json<T>(): Promise<T>;
    text(): Promise<string>;
    buffer(): Promise<Buffer>;
}

That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:

import { Actor } from './models/actor';

fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json<Actor>())
      .then(res => {
          let b:Actor = res;
      });

Bootstrap 3 Glyphicons CDN

If you only want to have glyphicons icons without any additional css you can create a css file and put the code below and include it into main css file.

I have to create this extra file as link below was messing with my site styles too.

//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css

Instead to using it directly I created a css file bootstrap-glyphicons.css

_x000D_
_x000D_
@font-face{font-family:'Glyphicons Halflings';src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot');src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff') format('woff'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;}_x000D_
.glyphicon-asterisk:before{content:"\2a";}_x000D_
.glyphicon-plus:before{content:"\2b";}_x000D_
.glyphicon-euro:before{content:"\20ac";}_x000D_
.glyphicon-minus:before{content:"\2212";}_x000D_
.glyphicon-cloud:before{content:"\2601";}_x000D_
.glyphicon-envelope:before{content:"\2709";}_x000D_
.glyphicon-pencil:before{content:"\270f";}_x000D_
.glyphicon-glass:before{content:"\e001";}_x000D_
.glyphicon-music:before{content:"\e002";}_x000D_
.glyphicon-search:before{content:"\e003";}_x000D_
.glyphicon-heart:before{content:"\e005";}_x000D_
.glyphicon-star:before{content:"\e006";}_x000D_
.glyphicon-star-empty:before{content:"\e007";}_x000D_
.glyphicon-user:before{content:"\e008";}_x000D_
.glyphicon-film:before{content:"\e009";}_x000D_
.glyphicon-th-large:before{content:"\e010";}_x000D_
.glyphicon-th:before{content:"\e011";}_x000D_
.glyphicon-th-list:before{content:"\e012";}_x000D_
.glyphicon-ok:before{content:"\e013";}_x000D_
.glyphicon-remove:before{content:"\e014";}_x000D_
.glyphicon-zoom-in:before{content:"\e015";}_x000D_
.glyphicon-zoom-out:before{content:"\e016";}_x000D_
.glyphicon-off:before{content:"\e017";}_x000D_
.glyphicon-signal:before{content:"\e018";}_x000D_
.glyphicon-cog:before{content:"\e019";}_x000D_
.glyphicon-trash:before{content:"\e020";}_x000D_
.glyphicon-home:before{content:"\e021";}_x000D_
.glyphicon-file:before{content:"\e022";}_x000D_
.glyphicon-time:before{content:"\e023";}_x000D_
.glyphicon-road:before{content:"\e024";}_x000D_
.glyphicon-download-alt:before{content:"\e025";}_x000D_
.glyphicon-download:before{content:"\e026";}_x000D_
.glyphicon-upload:before{content:"\e027";}_x000D_
.glyphicon-inbox:before{content:"\e028";}_x000D_
.glyphicon-play-circle:before{content:"\e029";}_x000D_
.glyphicon-repeat:before{content:"\e030";}_x000D_
.glyphicon-refresh:before{content:"\e031";}_x000D_
.glyphicon-list-alt:before{content:"\e032";}_x000D_
.glyphicon-flag:before{content:"\e034";}_x000D_
.glyphicon-headphones:before{content:"\e035";}_x000D_
.glyphicon-volume-off:before{content:"\e036";}_x000D_
.glyphicon-volume-down:before{content:"\e037";}_x000D_
.glyphicon-volume-up:before{content:"\e038";}_x000D_
.glyphicon-qrcode:before{content:"\e039";}_x000D_
.glyphicon-barcode:before{content:"\e040";}_x000D_
.glyphicon-tag:before{content:"\e041";}_x000D_
.glyphicon-tags:before{content:"\e042";}_x000D_
.glyphicon-book:before{content:"\e043";}_x000D_
.glyphicon-print:before{content:"\e045";}_x000D_
.glyphicon-font:before{content:"\e047";}_x000D_
.glyphicon-bold:before{content:"\e048";}_x000D_
.glyphicon-italic:before{content:"\e049";}_x000D_
.glyphicon-text-height:before{content:"\e050";}_x000D_
.glyphicon-text-width:before{content:"\e051";}_x000D_
.glyphicon-align-left:before{content:"\e052";}_x000D_
.glyphicon-align-center:before{content:"\e053";}_x000D_
.glyphicon-align-right:before{content:"\e054";}_x000D_
.glyphicon-align-justify:before{content:"\e055";}_x000D_
.glyphicon-list:before{content:"\e056";}_x000D_
.glyphicon-indent-left:before{content:"\e057";}_x000D_
.glyphicon-indent-right:before{content:"\e058";}_x000D_
.glyphicon-facetime-video:before{content:"\e059";}_x000D_
.glyphicon-picture:before{content:"\e060";}_x000D_
.glyphicon-map-marker:before{content:"\e062";}_x000D_
.glyphicon-adjust:before{content:"\e063";}_x000D_
.glyphicon-tint:before{content:"\e064";}_x000D_
.glyphicon-edit:before{content:"\e065";}_x000D_
.glyphicon-share:before{content:"\e066";}_x000D_
.glyphicon-check:before{content:"\e067";}_x000D_
.glyphicon-move:before{content:"\e068";}_x000D_
.glyphicon-step-backward:before{content:"\e069";}_x000D_
.glyphicon-fast-backward:before{content:"\e070";}_x000D_
.glyphicon-backward:before{content:"\e071";}_x000D_
.glyphicon-play:before{content:"\e072";}_x000D_
.glyphicon-pause:before{content:"\e073";}_x000D_
.glyphicon-stop:before{content:"\e074";}_x000D_
.glyphicon-forward:before{content:"\e075";}_x000D_
.glyphicon-fast-forward:before{content:"\e076";}_x000D_
.glyphicon-step-forward:before{content:"\e077";}_x000D_
.glyphicon-eject:before{content:"\e078";}_x000D_
.glyphicon-chevron-left:before{content:"\e079";}_x000D_
.glyphicon-chevron-right:before{content:"\e080";}_x000D_
.glyphicon-plus-sign:before{content:"\e081";}_x000D_
.glyphicon-minus-sign:before{content:"\e082";}_x000D_
.glyphicon-remove-sign:before{content:"\e083";}_x000D_
.glyphicon-ok-sign:before{content:"\e084";}_x000D_
.glyphicon-question-sign:before{content:"\e085";}_x000D_
.glyphicon-info-sign:before{content:"\e086";}_x000D_
.glyphicon-screenshot:before{content:"\e087";}_x000D_
.glyphicon-remove-circle:before{content:"\e088";}_x000D_
.glyphicon-ok-circle:before{content:"\e089";}_x000D_
.glyphicon-ban-circle:before{content:"\e090";}_x000D_
.glyphicon-arrow-left:before{content:"\e091";}_x000D_
.glyphicon-arrow-right:before{content:"\e092";}_x000D_
.glyphicon-arrow-up:before{content:"\e093";}_x000D_
.glyphicon-arrow-down:before{content:"\e094";}_x000D_
.glyphicon-share-alt:before{content:"\e095";}_x000D_
.glyphicon-resize-full:before{content:"\e096";}_x000D_
.glyphicon-resize-small:before{content:"\e097";}_x000D_
.glyphicon-exclamation-sign:before{content:"\e101";}_x000D_
.glyphicon-gift:before{content:"\e102";}_x000D_
.glyphicon-leaf:before{content:"\e103";}_x000D_
.glyphicon-eye-open:before{content:"\e105";}_x000D_
.glyphicon-eye-close:before{content:"\e106";}_x000D_
.glyphicon-warning-sign:before{content:"\e107";}_x000D_
.glyphicon-plane:before{content:"\e108";}_x000D_
.glyphicon-random:before{content:"\e110";}_x000D_
.glyphicon-comment:before{content:"\e111";}_x000D_
.glyphicon-magnet:before{content:"\e112";}_x000D_
.glyphicon-chevron-up:before{content:"\e113";}_x000D_
.glyphicon-chevron-down:before{content:"\e114";}_x000D_
.glyphicon-retweet:before{content:"\e115";}_x000D_
.glyphicon-shopping-cart:before{content:"\e116";}_x000D_
.glyphicon-folder-close:before{content:"\e117";}_x000D_
.glyphicon-folder-open:before{content:"\e118";}_x000D_
.glyphicon-resize-vertical:before{content:"\e119";}_x000D_
.glyphicon-resize-horizontal:before{content:"\e120";}_x000D_
.glyphicon-hdd:before{content:"\e121";}_x000D_
.glyphicon-bullhorn:before{content:"\e122";}_x000D_
.glyphicon-certificate:before{content:"\e124";}_x000D_
.glyphicon-thumbs-up:before{content:"\e125";}_x000D_
.glyphicon-thumbs-down:before{content:"\e126";}_x000D_
.glyphicon-hand-right:before{content:"\e127";}_x000D_
.glyphicon-hand-left:before{content:"\e128";}_x000D_
.glyphicon-hand-up:before{content:"\e129";}_x000D_
.glyphicon-hand-down:before{content:"\e130";}_x000D_
.glyphicon-circle-arrow-right:before{content:"\e131";}_x000D_
.glyphicon-circle-arrow-left:before{content:"\e132";}_x000D_
.glyphicon-circle-arrow-up:before{content:"\e133";}_x000D_
.glyphicon-circle-arrow-down:before{content:"\e134";}_x000D_
.glyphicon-globe:before{content:"\e135";}_x000D_
.glyphicon-tasks:before{content:"\e137";}_x000D_
.glyphicon-filter:before{content:"\e138";}_x000D_
.glyphicon-fullscreen:before{content:"\e140";}_x000D_
.glyphicon-dashboard:before{content:"\e141";}_x000D_
.glyphicon-heart-empty:before{content:"\e143";}_x000D_
.glyphicon-link:before{content:"\e144";}_x000D_
.glyphicon-phone:before{content:"\e145";}_x000D_
.glyphicon-usd:before{content:"\e148";}_x000D_
.glyphicon-gbp:before{content:"\e149";}_x000D_
.glyphicon-sort:before{content:"\e150";}_x000D_
.glyphicon-sort-by-alphabet:before{content:"\e151";}_x000D_
.glyphicon-sort-by-alphabet-alt:before{content:"\e152";}_x000D_
.glyphicon-sort-by-order:before{content:"\e153";}_x000D_
.glyphicon-sort-by-order-alt:before{content:"\e154";}_x000D_
.glyphicon-sort-by-attributes:before{content:"\e155";}_x000D_
.glyphicon-sort-by-attributes-alt:before{content:"\e156";}_x000D_
.glyphicon-unchecked:before{content:"\e157";}_x000D_
.glyphicon-expand:before{content:"\e158";}_x000D_
.glyphicon-collapse-down:before{content:"\e159";}_x000D_
.glyphicon-collapse-up:before{content:"\e160";}_x000D_
.glyphicon-log-in:before{content:"\e161";}_x000D_
.glyphicon-flash:before{content:"\e162";}_x000D_
.glyphicon-log-out:before{content:"\e163";}_x000D_
.glyphicon-new-window:before{content:"\e164";}_x000D_
.glyphicon-record:before{content:"\e165";}_x000D_
.glyphicon-save:before{content:"\e166";}_x000D_
.glyphicon-open:before{content:"\e167";}_x000D_
.glyphicon-saved:before{content:"\e168";}_x000D_
.glyphicon-import:before{content:"\e169";}_x000D_
.glyphicon-export:before{content:"\e170";}_x000D_
.glyphicon-send:before{content:"\e171";}_x000D_
.glyphicon-floppy-disk:before{content:"\e172";}_x000D_
.glyphicon-floppy-saved:before{content:"\e173";}_x000D_
.glyphicon-floppy-remove:before{content:"\e174";}_x000D_
.glyphicon-floppy-save:before{content:"\e175";}_x000D_
.glyphicon-floppy-open:before{content:"\e176";}_x000D_
.glyphicon-credit-card:before{content:"\e177";}_x000D_
.glyphicon-transfer:before{content:"\e178";}_x000D_
.glyphicon-cutlery:before{content:"\e179";}_x000D_
.glyphicon-header:before{content:"\e180";}_x000D_
.glyphicon-compressed:before{content:"\e181";}_x000D_
.glyphicon-earphone:before{content:"\e182";}_x000D_
.glyphicon-phone-alt:before{content:"\e183";}_x000D_
.glyphicon-tower:before{content:"\e184";}_x000D_
.glyphicon-stats:before{content:"\e185";}_x000D_
.glyphicon-sd-video:before{content:"\e186";}_x000D_
.glyphicon-hd-video:before{content:"\e187";}_x000D_
.glyphicon-subtitles:before{content:"\e188";}_x000D_
.glyphicon-sound-stereo:before{content:"\e189";}_x000D_
.glyphicon-sound-dolby:before{content:"\e190";}_x000D_
.glyphicon-sound-5-1:before{content:"\e191";}_x000D_
.glyphicon-sound-6-1:before{content:"\e192";}_x000D_
.glyphicon-sound-7-1:before{content:"\e193";}_x000D_
.glyphicon-copyright-mark:before{content:"\e194";}_x000D_
.glyphicon-registration-mark:before{content:"\e195";}_x000D_
.glyphicon-cloud-download:before{content:"\e197";}_x000D_
.glyphicon-cloud-upload:before{content:"\e198";}_x000D_
.glyphicon-tree-conifer:before{content:"\e199";}_x000D_
.glyphicon-tree-deciduous:before{content:"\e200";}_x000D_
.glyphicon-briefcase:before{content:"\1f4bc";}_x000D_
.glyphicon-calendar:before{content:"\1f4c5";}_x000D_
.glyphicon-pushpin:before{content:"\1f4cc";}_x000D_
.glyphicon-paperclip:before{content:"\1f4ce";}_x000D_
.glyphicon-camera:before{content:"\1f4f7";}_x000D_
.glyphicon-lock:before{content:"\1f512";}_x000D_
.glyphicon-bell:before{content:"\1f514";}_x000D_
.glyphicon-bookmark:before{content:"\1f516";}_x000D_
.glyphicon-fire:before{content:"\1f525";}_x000D_
.glyphicon-wrench:before{content:"\1f527";}
_x000D_
_x000D_
_x000D_

And imported the created css file into my main css file which enable me to just import the glyphicons only. Hope this help

@import url("bootstrap-glyphicons.css");

Android Fragment onClick button Method

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.writeqrcode_main, container, false);
    // Inflate the layout for this fragment

    txt_name = (TextView) view.findViewById(R.id.name);
    txt_usranme = (TextView) view.findViewById(R.id.surname);
    txt_number = (TextView) view.findViewById(R.id.number);
    txt_province = (TextView) view.findViewById(R.id.province);
    txt_write = (EditText) view.findViewById(R.id.editText_write);
    txt_show1 = (Button) view.findViewById(R.id.buttonShow1);

    txt_show1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.e("Onclick","Onclick");

            txt_show1.setVisibility(View.INVISIBLE);
            txt_name.setVisibility(View.VISIBLE);
            txt_usranme.setVisibility(View.VISIBLE);
            txt_number.setVisibility(View.VISIBLE);
            txt_province.setVisibility(View.VISIBLE);
        }
    });
    return view;
}

You OK !!!!

How to set environment via `ng serve` in Angular 6

You can use command ng serve -c dev for development environment ng serve -c prod for production environment

while building also same applies. You can use ng build -c dev for dev build

How to make a form close when pressing the escape key?

You can set a property on the form to do this for you if you have a button on the form that closes the form already.

Set the CancelButton property of the form to that button.

Gets or sets the button control that is clicked when the user presses the Esc key.

If you don't have a cancel button then you'll need to add a KeyDown handler and check for the Esc key in that:

private void Form_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
        this.Close();
    }
}

You will also have to set the KeyPreview property to true.

Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.

However, as Gargo points out in his answer this will mean that pressing Esc to abort an edit on a control in the dialog will also have the effect of closing the dialog. To avoid that override the ProcessDialogKey method as follows:

protected override bool ProcessDialogKey(Keys keyData)
{
    if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
    {
        this.Close();
        return true;
    }
    return base.ProcessDialogKey(keyData);
}

Query to get only numbers from a string

Just a little modification to @Epsicron 's answer

SELECT SUBSTRING(string, PATINDEX('%[0-9]%', string), PATINDEX('%[0-9][^0-9]%', string + 't') - PATINDEX('%[0-9]%', 
                    string) + 1) AS Number
FROM (values ('003Preliminary Examination Plan'),
    ('Coordination005'),
    ('Balance1000sheet')) as a(string)

no need for a temporary variable

Fatal error: "No Target Architecture" in Visual Studio

Another cause of this can be including a header that depends on windows.h, before including windows.h.

In my case I included xinput.h before windows.h and got this error. Swapping the order solved the problem.

Display Records From MySQL Database using JTable in Java

If you need to work a lot with database in your code and you know the structure of your table, I suggest you do it as follow:

First of all you can define a class which will help you to make objects capable of keeping your table rows data. For example in my project I created a class named Document.java to keep data of a single document from my database and I made an array list of these objects to keep data of my table which is gain by a query.

package financialdocuments;

import java.lang.*;
import java.util.HashMap;

/**
 *
 * @author Administrator
 */
public class Document {

 private int document_number; 
 private boolean document_type;
 private boolean document_status; 
 private StringBuilder document_date;
 private StringBuilder document_statement;
 private int document_code_number;
 private int document_employee_number;
 private int document_client_number;
 private String document_employee_name;
 private String document_client_name;
 private long document_amount;
 private long document_payment_amount;

 HashMap<Integer,Activity> document_activity_hashmap;


public Document(int dn,boolean dt,boolean ds,String dd,String dst,int dcon,int den,int dcln,long da,String dena,String dcna){

    document_date = new StringBuilder(dd);
    document_date.setLength(10);
    document_date.setCharAt(4, '.');
    document_date.setCharAt(7, '.');
    document_statement = new StringBuilder(dst);
    document_statement.setLength(50);
    document_number = dn; 
    document_type = dt;
    document_status = ds;
    document_code_number = dcon;
    document_employee_number = den;
    document_client_number = dcln;
    document_amount = da;
    document_employee_name = dena;
    document_client_name = dcna;

    document_payment_amount = 0;

    document_activity_hashmap = new HashMap<>();

}

public Document(int dn,boolean dt,boolean ds, long dpa){

    document_number = dn; 
    document_type = dt;
    document_status = ds;

    document_payment_amount = dpa;

    document_activity_hashmap = new HashMap<>();

}

// Print document information 
public void printDocumentInformation (){
    System.out.println("Document Number:" + document_number); 
    System.out.println("Document Date:" + document_date); 
    System.out.println("Document Type:" + document_type); 
    System.out.println("Document Status:" + document_status); 
    System.out.println("Document Statement:" + document_statement); 
    System.out.println("Document Code Number:" + document_code_number); 
    System.out.println("Document Client Number:" + document_client_number); 
    System.out.println("Document Employee Number:" + document_employee_number); 
    System.out.println("Document Amount:" + document_amount); 
    System.out.println("Document Payment Amount:" + document_payment_amount); 
    System.out.println("Document Employee Name:" + document_employee_name); 
    System.out.println("Document Client Name:" + document_client_name); 

} 
} 

Second of all, you can define a class to handle your database needs. For example I defined a class named DataBase.java which handles my connections to the database and my needed queries. And I instantiated an objected of it in my main class.

package financialdocuments;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class DataBase {

/** 
 * 
 * Defining parameters and strings that are going to be used
 * 
 */
//Connection connect;

// Tables which their datas are extracted at the beginning 
HashMap<Integer,String> code_table;
HashMap<Integer,String> activity_table;
HashMap<Integer,String> client_table;
HashMap<Integer,String> employee_table;

// Resultset Returned by queries 
private ResultSet result;

// Strings needed to set connection
String url = "jdbc:mysql://localhost:3306/financial_documents?useUnicode=yes&characterEncoding=UTF-8";
String dbName = "financial_documents";
String driver = "com.mysql.jdbc.Driver";
String userName = "root"; 
String password = "";

public DataBase(){

    code_table = new HashMap<>();
    activity_table = new HashMap<>();
    client_table = new HashMap<>();
    employee_table = new HashMap<>();
    Initialize();

}

/**
 * Set variables and objects for this class.
 */
private void Initialize(){

    System.out.println("Loading driver..."); 
    try {
        Class.forName(driver);
        System.out.println("Driver loaded!"); 
    } catch (ClassNotFoundException e) { 
        throw new IllegalStateException("Cannot find the driver in the classpath!", e); 
    }

    System.out.println("Connecting database...");

try (Connection connect = DriverManager.getConnection(url,userName,password)) {
            System.out.println("Database connected!");
            //Get tables' information 
            selectCodeTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printCodeTableQueryArray();

            selectActivityTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printActivityTableQueryArray(); 

            selectClientTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printClientTableQueryArray();

            selectEmployeeTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printEmployeeTableQueryArray();

            connect.close();
    }catch (SQLException e) { 
        throw new IllegalStateException("Cannot connect the database!", e);
    }

} 

/**
 * Write Queries 
 * @param s
 * @return 
 */
public boolean insertQuery(String s){

    boolean ret = false;
    System.out.println("Loading driver..."); 
    try {
        Class.forName(driver);
        System.out.println("Driver loaded!"); 
    } catch (ClassNotFoundException e) { 
        throw new IllegalStateException("Cannot find the driver in the classpath!", e); 
    }

    System.out.println("Connecting database...");

try (Connection connect = DriverManager.getConnection(url,userName,password)) {
            System.out.println("Database connected!");
            //Set tables' information 
            try {
                Statement st = connect.createStatement();
                int val = st.executeUpdate(s);
                if(val==1){ 
                    System.out.print("Successfully inserted value");
                    ret = true;
                }
                else{ 
                    System.out.print("Unsuccessful insertion");
                    ret = false;
                }
                st.close();
            } catch (SQLException ex) {
                Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
            }
            connect.close();
    }catch (SQLException e) { 
        throw new IllegalStateException("Cannot connect the database!", e);
    } 
    return ret;
}

/**
 * Query needed to get code table's data
 * @param c
 * @return 
 */
private void selectCodeTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  code;");
        while (res.next()) {
                int id = res.getInt("code_number");
                String msg = res.getString("code_statement");
                code_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printCodeTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : code_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
}

/**
 * Query needed to get activity table's data
 * @param c
 * @return 
 */
private void selectActivityTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  activity;");
        while (res.next()) {
                int id = res.getInt("activity_number");
                String msg = res.getString("activity_statement");
                activity_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printActivityTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : activity_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
}

/**
 * Query needed to get client table's data
 * @param c
 * @return 
 */
private void selectClientTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  client;");
        while (res.next()) {
                int id = res.getInt("client_number");
                String msg = res.getString("client_full_name");
                client_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printClientTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : client_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
}

/**
 * Query needed to get activity table's data
 * @param c
 * @return 
 */
private void selectEmployeeTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  employee;");
        while (res.next()) {
                int id = res.getInt("employee_number");
                String msg = res.getString("employee_full_name");
                employee_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printEmployeeTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : employee_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
} 
}

I hope this could be a little help.

WPF Add a Border to a TextBlock

No, you need to wrap your TextBlock in a Border. Example:

<Border BorderThickness="1" BorderBrush="Black">
    <TextBlock ... />
</Border>

Of course, you can set these properties (BorderThickness, BorderBrush) through styles as well:

<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="BorderBrush" Value="Black" />
</Style>

<Border Style="{StaticResource notCalledBorder}">
    <TextBlock ... />
</Border>

javascript node.js next()

It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send in your each REST block...

So you can do something like this as a simple next() example:

app.get("/", (req, res, next) => {
  console.log("req:", req, "res:", res);
  res.send(["data": "whatever"]);
  next();
},(req, res) =>
  console.log("it's all done!");
);

It's also very useful when you'd like to have a middleware in your app...

To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).

var express = require('express');
var app = express();

var myLogger = function (req, res, next) {
  console.log('LOGGED');
  next();
}

app.use(myLogger);

app.get('/', function (req, res) {
  res.send('Hello World!');
})

app.listen(3000);

MySQL SELECT statement for the "length" of the field is greater than 1

Just in case anybody want to find how in oracle and came here (like me), the syntax is

select length(FIELD) from TABLE

just in case ;)

Is there a way to SELECT and UPDATE rows at the same time?

Many years later...

The accepted answer of using the OUTPUT clause is good. I had to dig up the actual syntax, so here it is:

DECLARE @UpdatedIDs table (ID int)
UPDATE 
    Table1 
SET 
    AlertDate = getutcdate() 
OUTPUT
    inserted.Id
INTO
    @UpdatedIDs
WHERE 
    AlertDate IS NULL;

ADDED SEP 14, 2015:

"Can I use a scalar variable instead of a table variable?" one may ask... Sorry, but no you can't. You'll have to SELECT @SomeID = ID from @UpdatedIDs if you need a single ID.

How to read all rows from huge table?

I think your question is similar to this thread: JDBC Pagination which contains solutions for your need.

In particular, for PostgreSQL, you can use the LIMIT and OFFSET keywords in your request: http://www.petefreitag.com/item/451.cfm

PS: In Java code, I suggest you to use PreparedStatement instead of simple Statements: http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html

Linux Command History with date and time

HISTTIMEFORMAT="%d/%m/%y %H:%M "

For any commands typed prior to this, it will not help since they will just get a default time of when you turned history on, but it will log the time of any further commands after this.

If you want it to log history for permanent, you should put the following line in your ~/.bashrc

export HISTTIMEFORMAT="%d/%m/%y %H:%M "

Protect image download

this code will disable Right-Click on Win or Click and hold on mac to open "contextmenu"

$("img").on("contextmenu",function(e){return false;});

It's so simple and always works fine. and it's not depends on OS or Browser that you're using.

git: Your branch is ahead by X commits

I had this issue on my stage server where I do only pulls. And hard reset helped me to clean HEAD to the same as remote.

git reset --hard origin/master

So now I have again:

On branch master
Your branch is up-to-date with 'origin/master'.

Solve Cross Origin Resource Sharing with Flask

I might be a late on this question but below steps fixed the issue

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

Which exception should I raise on bad/illegal argument combinations in Python?

I would just raise ValueError, unless you need a more specific exception..

def import_to_orm(name, save=False, recurse=False):
    if recurse and not save:
        raise ValueError("save must be True if recurse is True")

There's really no point in doing class BadValueError(ValueError):pass - your custom class is identical in use to ValueError, so why not use that?

How to select distinct query using symfony2 doctrine query builder?

Just open your repository file and add this new function, then call it inside your controller:

 public function distinctCategories(){
        return $this->createQueryBuilder('cc')
        ->where('cc.contenttype = :type')
        ->setParameter('type', 'blogarticle')
        ->groupBy('cc.blogarticle')
        ->getQuery()
        ->getResult()
        ;
    }

Then within your controller:

public function index(YourRepository $repo)
{
    $distinctCategories = $repo->distinctCategories();


    return $this->render('your_twig_file.html.twig', [
        'distinctCategories' => $distinctCategories
    ]);
}

Good luck!

Extract time from moment js object

If you read the docs (http://momentjs.com/docs/#/displaying/) you can find this format:

moment("2015-01-16T12:00:00").format("hh:mm:ss a")

See JS Fiddle http://jsfiddle.net/Bjolja/6mn32xhu/

How to fix docker: Got permission denied issue

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/images/json: dial unix /var/run/docker.sock: connect: permission denied

sudo chmod 666 /var/run/docker.sock

This fix my problem.

Adding <script> to WordPress in <head> element

For anyone else who comes here looking, I'm afraid I'm with @usama sulaiman here.

Using the enqueue function provides a safe way to load style sheets and scripts according to the script dependencies and is WordPress' recommended method of achieving what the original poster was trying to achieve. Just think of all the plugins trying to load their own copy of jQuery for instance; you better hope they're using enqueue :D.

Also, wherever possible create a plugin; as adding custom code to your functions file can be pita if you don't have a back-up and you upgrade your theme and overwrite your functions file in the process.

Having a plugin handle this and other custom functions also means you can switch them off if you think their code is clashing with some other plugin or functionality.

Something along the following in a plugin file is what you are looking for:

<?php
/*
Plugin Name: Your plugin name
Description: Your description
Version: 1.0
Author: Your name
Author URI: 
Plugin URI: 
*/

function $yourJS() {
    wp_enqueue_script(
        'custom_script',
        plugins_url( '/js/your-script.js', __FILE__ ),
        array( 'jquery' )
    );
}
 add_action( 'wp_enqueue_scripts',  '$yourJS' );
 add_action( 'wp_enqueue_scripts', 'prefix_add_my_stylesheet' );

 function prefix_add_my_stylesheet() {
    wp_register_style( 'prefix-style', plugins_url( '/css/your-stylesheet.css', __FILE__ ) );
    wp_enqueue_style( 'prefix-style' );
  }

?>

Structure your folders as follows:

Plugin Folder
  |_ css folder
  |_ js folder
  |_ plugin.php ...contains the above code - modified of course ;D

Then zip it up and upload it to your WordPress installation using your add plugins interface, activate it and Bob's your uncle.

equivalent to push() or pop() for arrays?

You can use LinkedList. It has methods peek, poll and offer.

System.currentTimeMillis vs System.nanoTime

Yes, if such precision is required use System.nanoTime(), but be aware that you are then requiring a Java 5+ JVM.

On my XP systems, I see system time reported to at least 100 microseconds 278 nanoseconds using the following code:

private void test() {
    System.out.println("currentTimeMillis: "+System.currentTimeMillis());
    System.out.println("nanoTime         : "+System.nanoTime());
    System.out.println();

    testNano(false);                                                            // to sync with currentTimeMillis() timer tick
    for(int xa=0; xa<10; xa++) {
        testNano(true);
        }
    }

private void testNano(boolean shw) {
    long strMS=System.currentTimeMillis();
    long strNS=System.nanoTime();
    long curMS;
    while((curMS=System.currentTimeMillis()) == strMS) {
        if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)); }
        }
    if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)+", Milli: "+(curMS-strMS)); }
    }

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

Validate phone number using angular js

You can also use ng-pattern ,[7-9] = > mobile number must start with 7 or 8 or 9 ,[0-9] = mobile number accepts digits ,{9} mobile number should be 10 digits.

_x000D_
_x000D_
function form($scope){_x000D_
    $scope.onSubmit = function(){_x000D_
        alert("form submitted");_x000D_
    }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>_x000D_
<div ng-app ng-controller="form">_x000D_
<form name="myForm" ng-submit="onSubmit()">_x000D_
    <input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>_x000D_
    <span ng-show="myForm.mobile_number.$error.pattern">Please enter valid number!</span>_x000D_
    <input type="submit" value="submit"/>_x000D_
</form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Ruby: character to ascii from a string

You could also just call to_a after each_byte or even better String#bytes

=> 'hello world'.each_byte.to_a
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

=> 'hello world'.bytes
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

Copy rows from one Datatable to another DataTable?

 private void CopyDataTable(DataTable table){
     // Create an object variable for the copy.
     DataTable copyDataTable;
     copyDataTable = table.Copy();
     // Insert code to work with the copy.
 }

jQuery attr('onclick')

Do it the jQuery way (and fix the errors):

$('#stop').click(function() {
     $('#next').click(stopMoving);
     // ^-- missing #
});  // <-- missing );

If the element already has a click handler attached via the onclick attribute, you have to remove it:

$('#next').attr('onclick', '');

Update: As @Drackir pointed out, you might also have to call $('#next').unbind('click'); in order to remove other click handlers attached via jQuery.

But this is guessing here. As always: More information => better answers.

Custom Card Shape Flutter SDK

When Card I always use RoundedRectangleBorder.

Card(
  color: Colors.grey[900],
  shape: RoundedRectangleBorder(
    side: BorderSide(color: Colors.white70, width: 1),
    borderRadius: BorderRadius.circular(10),
  ),
  margin: EdgeInsets.all(20.0),
  child: Container(
    child: Column(
        children: <Widget>[
        ListTile(
            title: Text(
            'example',
            style: TextStyle(fontSize: 18, color: Colors.white),
            ),
        ),
        ],
    ),
  ),
),

How to make a flex item not fill the height of the flex container?

When you create a flex container various default flex rules come into play.

Two of these default rules are flex-direction: row and align-items: stretch. This means that flex items will automatically align in a single row, and each item will fill the height of the container.

If you don't want flex items to stretch – i.e., like you wrote:

make its height the minimum required for holding its content

... then simply override the default with align-items: flex-start.

_x000D_
_x000D_
#a {_x000D_
  display: flex;_x000D_
  align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
  background-color: red;_x000D_
  padding: 5px;_x000D_
  margin: 2px;_x000D_
}_x000D_
#b {_x000D_
  height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
  <div id="b">left</div>_x000D_
  <div>_x000D_
    right<br>right<br>right<br>right<br>right<br>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's an illustration from the flexbox spec that highlights the five values for align-items and how they position flex items within the container. As mentioned before, stretch is the default value.

enter image description here Source: W3C

How can I use Guzzle to send a POST request in JSON?

The simple and basic way (guzzle6):

$client = new Client([
    'headers' => [ 'Content-Type' => 'application/json' ]
]);

$response = $client->post('http://api.com/CheckItOutNow',
    ['body' => json_encode(
        [
            'hello' => 'World'
        ]
    )]
);

To get the response status code and the content of the body I did this:

echo '<pre>' . var_export($response->getStatusCode(), true) . '</pre>';
echo '<pre>' . var_export($response->getBody()->getContents(), true) . '</pre>';

Link to the issue number on GitHub within a commit message

If you want to link to a GitHub issue and close the issue, you can provide the following lines in your Git commit message:

Closes #1.
Closes GH-1.
Closes gh-1.

(Any of the three will work.) Note that this will link to the issue and also close it. You can find out more in this blog post (start watching the embedded video at about 1:40).

I'm not sure if a similar syntax will simply link to an issue without closing it.

Docker-compose: node_modules not present in a volume after npm install succeeds

In my opinion, we should not RUN npm install in the Dockerfile. Instead, we can start a container using bash to install the dependencies before runing the formal node service

docker run -it -v ./app:/usr/src/app  your_node_image_name  /bin/bash
root@247543a930d6:/usr/src/app# npm install

What does the return keyword do in a void method in Java?

It exits the function and returns nothing.

Something like return 1; would be incorrect since it returns integer 1.

How do you rename a MongoDB database?

There is no mechanism to re-name databases. The currently accepted answer at time of writing is factually correct and offers some interesting background detail as to the excuse upstream, but offers no suggestions for replicating the behavior. Other answers point at copyDatabase, which is no longer an option as the functionality has been removed in 4.0. I've updated SERVER-701 with my notes and incredulity.

Equivalent behavior involves mongodump and mongorestore in a bit of a dance:

  1. Export your data, making note of the "namespaces" in use. For example, on one of my datasets, I have a collection with the namespace byzmcbehoomrfjcs9vlj.Analytics — that prefix (actually the database name) will be needed in the next step.

  2. Import your data, supplying --nsFrom and --nsTo arguments. (Documentation.) Continuing with my above hypothetical (and extremely unreadable) example, to restore to a more sensical name, I invoke:

mongorestore --archive=backup.agz --gzip --drop \
    --nsFrom 'byzmcbehoomrfjcs9vlj.*' --nsTo 'rita.*'

Some may also point at the --db argument to mongorestore, however this, too, is deprecated and triggers a warning against use on non-BSON folder backups with a completely erroneous suggestion to "use --nsInclude instead". The above namespace translation is equivalent to use of the --db option, and is the correct namespace manipulation setup to use as we are not attempting to filter what is being restored.

How to check if there exists a process with a given pid in Python?

Look here for windows-specific way of getting full list of running processes with their IDs. It would be something like

from win32com.client import GetObject
def get_proclist():
    WMI = GetObject('winmgmts:')
    processes = WMI.InstancesOf('Win32_Process')
    return [process.Properties_('ProcessID').Value for process in processes]

You can then verify pid you get against this list. I have no idea about performance cost, so you'd better check this if you're going to do pid verification often.

For *NIx, just use mluebke's solution.

Arithmetic operation resulted in an overflow. (Adding integers)

The maximum value of an integer (which is signed) is 2147483647. If that value overflows, an exception is thrown to prevent unexpected behavior of your program.

If that exception wouldn't be thrown, you'd have a value of -2145629296 for your Volume, which is most probably not wanted.

Solution: Use an Int64 for your volume. With a max value of 9223372036854775807, you're probably more on the safe side.

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

Renaming Columns in an SQL SELECT Statement

select column1 as xyz,
      column2 as pqr,
.....

from TableName;

Which JDK version (Language Level) is required for Android Studio?

Android Studio now comes bundled with OpenJDK 8 . Legacy projects can still use JDK7 or JDK8

Reference: https://developer.android.com/studio/releases/index.html

Get the cell value of a GridView row

Windows Form Iteration Technique

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Selected)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            int index = cell.ColumnIndex;
            if (index == 0)
            {
                value = cell.Value.ToString();
                //do what you want with the value
            }
        }
    }
}

How can I delete derived data in Xcode 8?

In your terminal :

rm -rf ~/Library/Developer/Xcode/DerivedData

CSS scale down image to fit in containing div, without specifing original size

I believe this is the best way of doing it, I've tried it and it works very well.

#img {
  object-fit: cover;
}

This is where I found it. Good luck!

On Duplicate Key Update same as insert

I know it's late, but i hope someone will be helped of this answer

INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);

You can read the tutorial below here :

https://mariadb.com/kb/en/library/insert-on-duplicate-key-update/

http://www.mysqltutorial.org/mysql-insert-or-update-on-duplicate-key-update/

Get all column names of a DataTable into string array using (LINQ/Predicate)

Try this (LINQ method syntax):

string[] columnNames = dt.Columns.Cast<DataColumn>()
                                 .Select(x => x.ColumnName)
                                 .ToArray();  

or in LINQ Query syntax:

string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>()
                        select dc.ColumnName).ToArray();

Cast is required, because Columns is of type DataColumnCollection which is a IEnumerable, not IEnumerable<DataColumn>. The other parts should be obvious.

How to clone ArrayList and also clone its contents?

You will need to clone the ArrayList by hand (by iterating over it and copying each element to a new ArrayList), because clone() will not do it for you. Reason for this is that the objects contained in the ArrayList may not implement Clonable themselves.

Edit: ... and that is exactly what Varkhan's code does.

Adding default parameter value with type hint in Python

If you're using typing (introduced in Python 3.5) you can use typing.Optional, where Optional[X] is equivalent to Union[X, None]. It is used to signal that the explicit value of None is allowed . From typing.Optional:

def foo(arg: Optional[int] = None) -> None:
    ...

Java String to JSON conversion

Instead of JSONObject , you can use ObjectMapper to convert java object to json string

ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);

What does the 'b' character do in front of a string literal?

The answer to the question is that, it does:

data.encode()

and in order to decode it(remove the b, because sometimes you don't need it)

use:

data.decode()

Return list from async/await method

In addition to @takemyoxygen's answer the convention of having a function name that ends in Async is that this function is truly asynchronous. I.e. it does not start a new thread and it doesn't simply call Task.Run. If that is all the code that is in your function, it will be better to remove it completely and simply have:

List<Item> list = await Task.Run(() => manager.GetList());

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

Load content with ajax in bootstrap modal

Here is how I solved the issue, might be useful to some:

Ajax modal doesn't seem to be available with boostrap 2.1.1

So I ended up coding it myself:

$('[data-toggle="modal"]').click(function(e) {
  e.preventDefault();
  var url = $(this).attr('href');
  //var modal_id = $(this).attr('data-target');
  $.get(url, function(data) {
      $(data).modal();
  });
});

Example of a link that calls a modal:

<a href="{{ path('ajax_get_messages', { 'superCategoryID': 6, 'sex': sex }) }}" data-toggle="modal">
    <img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>

I now send the whole modal markup through ajax.

Credits to drewjoh

Android: show/hide status bar/power bar

I've tried so many things.

Finally, It is the most suitable code to hide and show full screen mode.

private fun hideSystemUi() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        window.setDecorFitsSystemWindows(true)
    } else {
        // hide status bar
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_IMMERSIVE or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
    }

}

private fun showSystemUi() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        window.setDecorFitsSystemWindows(false)
    } else {
        // Show status bar
        window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.decorView.systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_STABLE
    }

}

It Implemented it in this app : Android Breakdown.

Go to Videos(Bottom Bar) > Play Any Video > Toggle Fullscreen

LINQ Orderby Descending Query

I think this first failed because you are ordering value which is null. If Delivery is a foreign key associated table then you should include this table first, example below:

var itemList = from t in ctn.Items.Include(x=>x.Delivery)
                    where !t.Items && t.DeliverySelection
                    orderby t.Delivery.SubmissionDate descending
                    select t;

Center align a column in twitter bootstrap

With bootstrap 3 the best way to go about achieving what you want is ...with offsetting columns. Please see these examples for more detail:
http://getbootstrap.com/css/#grid-offsetting

In short, and without seeing your divs here's an example what might help, without using any custom classes. Just note how the "col-6" is used and how half of that is 3 ...so the "offset-3" is used. Splitting equally will allow the centered spacing you're going for:

<div class="container">
<div class="col-sm-6 col-sm-offset-3">
your centered, floating column
</div></div>

What does "make oldconfig" do exactly in the Linux kernel makefile?

It's torture. Instead of including a generic conf file, they make you hit return 9000 times to generate one.

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

Something throws an exception of type std::bad_alloc, indicating that you ran out of memory. This exception is propagated through until main, where it "falls off" your program and causes the error message you see.

Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h looks like a syntax error.

Set environment variables from file of key/value pairs

Simpler:

  1. grab the content of the file
  2. remove any blank lines (just incase you separated some stuff)
  3. remove any comments (just incase you added some...)
  4. add export to all the lines
  5. eval the whole thing

eval $(cat .env | sed -e /^$/d -e /^#/d -e 's/^/export /')

Another option (you don't have to run eval (thanks to @Jaydeep)):

export $(cat .env | sed -e /^$/d -e /^#/d | xargs)

Lastly, if you want to make your life REALLY easy, add this to your ~/.bash_profile:

function source_envfile() { export $(cat $1 | sed -e /^$/d -e /^#/d | xargs); }

(MAKE SURE YOU RELOAD YOUR BASH SETTINGS!!! source ~/.bash_profile or.. just make a new tab/window and problem solved) you call it like this: source_envfile .env

Install Qt on Ubuntu

In Ubuntu 18.04 the QtCreator examples and API docs missing, This is my way to solve this problem, should apply to almost every Ubuntu release.

For QtCreator and Examples and API Docs:

sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `

sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`

sudo apt-get install build-essential qtcreator qt5-default

If something is also missing, then:

sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `

Hope to be helpful.

Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing

html tables & inline styles

This should do the trick:

<table width="400" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="50" height="40" valign="top" rowspan="3">
      <img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
    </td>
  </tr>
  <tr>
    <td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

UPDATE: Adjusted code per the comments:

After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.

Here is an example that will NOT WORK:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="300" bgcolor="#252525">&nbsp;
    </td>
    <td width="300" bgcolor="#454545">&nbsp;
    </td>
  </tr>
</table>

Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="600" colspan="2" bgcolor="#353535">&nbsp;
    </td>
  </tr>
</table>

Not a full tutorial, but I hope that helps steer you in the right direction in the future.

Here is the code you are after:

<table width="900" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="57" height="43" valign="top" rowspan="2">
      <img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
    </td>
  </tr>
  <tr>
    <td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.

X close button only using css

Here's some variety for you with several sizes and hover animations.. demo(link)

enter image description here

<ul>
  <li>Large</li>
  <li>Medium</li>
  <li>Small</li>
  <li>Switch</li>
</ul>

<ul>
  <li class="ele">
    <div class="x large"><b></b><b></b><b></b><b></b></div>
    <div class="x spin large"><b></b><b></b><b></b><b></b></div>
    <div class="x spin large slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop large"><b></b><b></b><b></b><b></b></div>
    <div class="x t large"><b></b><b></b><b></b><b></b></div>
    <div class="x shift large"><b></b><b></b><b></b><b></b></div>
  </li>
  <li class="ele">
    <div class="x medium"><b></b><b></b><b></b><b></b></div>
    <div class="x spin medium"><b></b><b></b><b></b><b></b></div>
    <div class="x spin medium slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop medium"><b></b><b></b><b></b><b></b></div>
    <div class="x t medium"><b></b><b></b><b></b><b></b></div>
    <div class="x shift medium"><b></b><b></b><b></b><b></b></div>

  </li>
  <li class="ele">
    <div class="x small"><b></b><b></b><b></b><b></b></div>
    <div class="x spin small"><b></b><b></b><b></b><b></b></div>
    <div class="x spin small slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop small"><b></b><b></b><b></b><b></b></div>
    <div class="x t small"><b></b><b></b><b></b><b></b></div>
    <div class="x shift small"><b></b><b></b><b></b><b></b></div>
    <div class="x small grow"><b></b><b></b><b></b><b></b></div>

  </li>
  <li class="ele">
    <div class="x switch"><b></b><b></b><b></b><b></b></div>
  </li>
</ul>

css

.ele div.x {
-webkit-transition-duration:0.5s;
  transition-duration:0.5s;
}

.ele div.x.slow {
-webkit-transition-duration:1s;
  transition-duration:1s;
}

ul { list-style:none;float:left;display:block;width:100%; }
li { display:inline;width:25%;float:left; }
.ele { width:25%;display:inline; }
.x {
  float:left;
  position:relative;
  margin:0;
  padding:0;
  overflow:hidden;
  background:#CCC;
  border-radius:2px;
  border:solid 2px #FFF;
  transition: all .3s ease-out;
  cursor:pointer;
}
.x.large { 
  width:30px;
  height:30px;
}

.x.medium {
  width:20px;
  height:20px;
}

.x.small {
  width:10px;
  height:10px;
}

.x.switch {
  width:15px;
  height:15px;
}
.x.grow {

}

.x.spin:hover{
  background:#BB3333;
  transform: rotate(180deg);
}
.x.flop:hover{
  background:#BB3333;
  transform: rotate(90deg);
}
.x.t:hover{
  background:#BB3333;
  transform: rotate(45deg);
}
.x.shift:hover{
  background:#BB3333;
}

.x b{
  display:block;
  position:absolute;
  height:0;
  width:0;
  padding:0;
  margin:0;
}
.x.small b {
  border:solid 5px rgba(255,255,255,0);
}
.x.medium b {
  border:solid 10px rgba(255,255,255,0);
}
.x.large b {
  border:solid 15px rgba(255,255,255,0);
}
.x.switch b {
  border:solid 10px rgba(255,255,255,0);
}

.x b:nth-child(1){
  border-top-color:#FFF;
  top:-2px;
}
.x b:nth-child(2){
  border-left-color:#FFF;
  left:-2px;
}
.x b:nth-child(3){
  border-bottom-color:#FFF;
  bottom:-2px;
}
.x b:nth-child(4){
  border-right-color:#FFF;
  right:-2px;
}

How to get rid of punctuation using NLTK tokenizer?

As noticed in comments start with sent_tokenize(), because word_tokenize() works only on a single sentence. You can filter out punctuation with filter(). And if you have an unicode strings make sure that is a unicode object (not a 'str' encoded with some encoding like 'utf-8').

from nltk.tokenize import word_tokenize, sent_tokenize

text = '''It is a blue, small, and extraordinary ball. Like no other'''
tokens = [word for sent in sent_tokenize(text) for word in word_tokenize(sent)]
print filter(lambda word: word not in ',-', tokens)

How to enable C++11 in Qt Creator?

If you are using an earlier version of QT (<5) try this

QMAKE_CXXFLAGS += -std=c++0x

summing two columns in a pandas dataframe

Same think can be done using lambda function. Here I am reading the data from a xlsx file.

import pandas as pd
df = pd.read_excel("data.xlsx", sheet_name = 4)
print df

Output:

  cluster Unnamed: 1      date  budget  actual
0       a 2014-01-01  00:00:00   11000   10000
1       a 2014-02-01  00:00:00    1200    1000
2       a 2014-03-01  00:00:00     200     100
3       b 2014-04-01  00:00:00     200     300
4       b 2014-05-01  00:00:00     400     450
5       c 2014-06-01  00:00:00     700    1000
6       c 2014-07-01  00:00:00    1200    1000
7       c 2014-08-01  00:00:00     200     100
8       c 2014-09-01  00:00:00     200     300

Sum two columns into 3rd new one.

df['variance'] = df.apply(lambda x: x['budget'] + x['actual'], axis=1)
print df

Output:

  cluster Unnamed: 1      date  budget  actual  variance
0       a 2014-01-01  00:00:00   11000   10000     21000
1       a 2014-02-01  00:00:00    1200    1000      2200
2       a 2014-03-01  00:00:00     200     100       300
3       b 2014-04-01  00:00:00     200     300       500
4       b 2014-05-01  00:00:00     400     450       850
5       c 2014-06-01  00:00:00     700    1000      1700
6       c 2014-07-01  00:00:00    1200    1000      2200
7       c 2014-08-01  00:00:00     200     100       300
8       c 2014-09-01  00:00:00     200     300       500

Why Would I Ever Need to Use C# Nested Classes

A nested class can have private, protected and protected internal access modifiers along with public and internal.

For example, you are implementing the GetEnumerator() method that returns an IEnumerator<T> object. The consumers wouldn't care about the actual type of the object. All they know about it is that it implements that interface. The class you want to return doesn't have any direct use. You can declare that class as a private nested class and return an instance of it (this is actually how the C# compiler implements iterators):

class MyUselessList : IEnumerable<int> {
    // ...
    private List<int> internalList;
    private class UselessListEnumerator : IEnumerator<int> {
        private MyUselessList obj;
        public UselessListEnumerator(MyUselessList o) {
           obj = o;
        }
        private int currentIndex = -1;
        public int Current {
           get { return obj.internalList[currentIndex]; }
        }
        public bool MoveNext() { 
           return ++currentIndex < obj.internalList.Count;
        }
    }
    public IEnumerator<int> GetEnumerator() {
        return new UselessListEnumerator(this);
    }
}

JQuery Ajax Post results in 500 Internal Server Error

As mentioned I think your return string data is very long. so the JSON format has been corrupted.

There's other way for this problem. You should change the max size for JSON data in this way :

Open the Web.Config file and paste these lines into the configuration section

<system.web.extensions>
  <scripting>
    <webServices>
      <jsonSerialization maxJsonLength="50000000"/>
    </webServices>
  </scripting>
</system.web.extensions>

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Makefile part of the question

This is pretty easy, unless you don't need to generalize try something like the code below (but replace space indentation with tabs near g++)

SRC_DIR := .../src
OBJ_DIR := .../obj
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
LDFLAGS := ...
CPPFLAGS := ...
CXXFLAGS := ...

main.exe: $(OBJ_FILES)
   g++ $(LDFLAGS) -o $@ $^

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
   g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<

Automatic dependency graph generation

A "must" feature for most make systems. With GCC in can be done in a single pass as a side effect of the compilation by adding -MMD flag to CXXFLAGS and -include $(OBJ_FILES:.o=.d) to the end of the makefile body:

CXXFLAGS += -MMD
-include $(OBJ_FILES:.o=.d)

And as guys mentioned already, always have GNU Make Manual around, it is very helpful.

SELECT max(x) is returning null; how can I make it return 0?

Depends on what product you're using, but most support something like

SELECT IFNULL(MAX(X), 0, MAX(X)) AS MaxX FROM tbl WHERE XID = 1

or

SELECT CASE MAX(X) WHEN NULL THEN 0 ELSE MAX(X) FROM tbl WHERE XID = 1

How to get label of select option with jQuery?

Try this:

$('select option:selected').prop('label');

This will pull out the displayed text for both styles of <option> elements:

  • <option label="foo"><option> -> "foo"
  • <option>bar<option> -> "bar"

If it has both a label attribute and text inside the element, it'll use the label attribute, which is the same behavior as the browser.

For posterity, this was tested under jQuery 3.1.1

Proper way to set response status and JSON content in a REST API made with nodejs and express

try {
  var data = {foo: "bar"};
  res.json(JSON.stringify(data));
}
catch (e) {
  res.status(500).json(JSON.stringify(e));
}

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

As a general rule (i.e. in vanilla kernels), fork/clone failures with ENOMEM occur specifically because of either an honest to God out-of-memory condition (dup_mm, dup_task_struct, alloc_pid, mpol_dup, mm_init etc. croak), or because security_vm_enough_memory_mm failed you while enforcing the overcommit policy.

Start by checking the vmsize of the process that failed to fork, at the time of the fork attempt, and then compare to the amount of free memory (physical and swap) as it relates to the overcommit policy (plug the numbers in.)

In your particular case, note that Virtuozzo has additional checks in overcommit enforcement. Moreover, I'm not sure how much control you truly have, from within your container, over swap and overcommit configuration (in order to influence the outcome of the enforcement.)

Now, in order to actually move forward I'd say you're left with two options:

  • switch to a larger instance, or
  • put some coding effort into more effectively controlling your script's memory footprint

NOTE that the coding effort may be all for naught if it turns out that it's not you, but some other guy collocated in a different instance on the same server as you running amock.

Memory-wise, we already know that subprocess.Popen uses fork/clone under the hood, meaning that every time you call it you're requesting once more as much memory as Python is already eating up, i.e. in the hundreds of additional MB, all in order to then exec a puny 10kB executable such as free or ps. In the case of an unfavourable overcommit policy, you'll soon see ENOMEM.

Alternatives to fork that do not have this parent page tables etc. copy problem are vfork and posix_spawn. But if you do not feel like rewriting chunks of subprocess.Popen in terms of vfork/posix_spawn, consider using suprocess.Popen only once, at the beginning of your script (when Python's memory footprint is minimal), to spawn a shell script that then runs free/ps/sleep and whatever else in a loop parallel to your script; poll the script's output or read it synchronously, possibly from a separate thread if you have other stuff to take care of asynchronously -- do your data crunching in Python but leave the forking to the subordinate process.

HOWEVER, in your particular case you can skip invoking ps and free altogether; that information is readily available to you in Python directly from procfs, whether you choose to access it yourself or via existing libraries and/or packages. If ps and free were the only utilities you were running, then you can do away with subprocess.Popen completely.

Finally, whatever you do as far as subprocess.Popen is concerned, if your script leaks memory you will still hit the wall eventually. Keep an eye on it, and check for memory leaks.

How to get evaluated attributes inside a custom directive

For the same solution I was looking for Angularjs directive with ng-Model.
Here is the code that resolve the problem.

    myApp.directive('zipcodeformatter', function () {
    return {
        restrict: 'A', // only activate on element attribute
        require: '?ngModel', // get a hold of NgModelController
        link: function (scope, element, attrs, ngModel) {

            scope.$watch(attrs.ngModel, function (v) {
                if (v) {
                    console.log('value changed, new value is: ' + v + ' ' + v.length);
                    if (v.length > 5) {
                        var newzip = v.replace("-", '');
                        var str = newzip.substring(0, 5) + '-' + newzip.substring(5, newzip.length);
                        element.val(str);

                    } else {
                        element.val(v);
                    }

                }

            });

        }
    };
});


HTML DOM

<input maxlength="10" zipcodeformatter onkeypress="return isNumberKey(event)" placeholder="Zipcode" type="text" ng-readonly="!checked" name="zipcode" id="postal_code" class="form-control input-sm" ng-model="patient.shippingZipcode" required ng-required="true">


My Result is:

92108-2223

How to send a pdf file directly to the printer using JavaScript?

I think this Library of JavaScript might Help you:

It's called Print.js

First Include

<script src="print.js"></script>
<link rel="stylesheet" type="text/css" href="print.css">

It's basic usage is to call printJS() and just pass in a PDF document url: printJS('docs/PrintJS.pdf')

What I did was something like this, this will also show "Loading...." if PDF document is too large.

<button type="button" onclick="printJS({printable:'docs/xx_large_printjs.pdf', type:'pdf', showModal:true})">
    Print PDF with Message
</button>

However keep in mind that:

Firefox currently doesn't allow printing PDF documents using iframes. There is an open bug in Mozilla's website about this. When using Firefox, Print.js will open the PDF file into a new tab.

How to create a JavaScript callback for knowing when an image is loaded?

If the goal is to style the img after browser has rendered image, you should:

const img = new Image();
img.src = 'path/to/img.jpg';

img.decode().then(() => {
/* set styles */
/* add img to DOM */ 
});

because the browser first loads the compressed version of image, then decodes it, finally paints it. since there is no event for paint you should run your logic after browser has decoded the img tag.

How to remove text before | character in notepad++

Please use regex to remove anything before |

example

dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds

Use find and replace in notepad++

find: .+(\|) replace: \1

output

| fdfsfsf
|gfghhghg
|dfdsfsds

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

This can happen when you link to msvcrt.dll instead of msvcr10.dll (or similar), which is a good plan. Because it will free you up to redistribute your Visual Studio's runtime library inside your final software package.

That workaround helps me (at Visual Studio 2008):

#if _MSC_VER >= 1400
#undef stdin
#undef stdout
#undef stderr
extern "C" _CRTIMP extern FILE _iob[];
#define stdin   _iob
#define stdout  (_iob+1)
#define stderr  (_iob+2)
#endif

This snippet is not needed for Visual Studio 6 and its compiler. Therefore the #ifdef.

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

As pointed out by @Jayan in another post, the solution was to do the following

import jenkins.model.*
jenkins = Jenkins.instance

Then I was able to do the rest of my scripting the way it was.

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

For languages not specifying a memory model, you are writing code for the language and the memory model specified by the processor architecture. The processor may choose to re-order memory accesses for performance. So, if your program has data races (a data race is when it's possible for multiple cores / hyper-threads to access the same memory concurrently) then your program is not cross platform because of its dependence on the processor memory model. You may refer to the Intel or AMD software manuals to find out how the processors may re-order memory accesses.

Very importantly, locks (and concurrency semantics with locking) are typically implemented in a cross platform way... So if you are using standard locks in a multithreaded program with no data races then you don't have to worry about cross platform memory models.

Interestingly, Microsoft compilers for C++ have acquire / release semantics for volatile which is a C++ extension to deal with the lack of a memory model in C++ http://msdn.microsoft.com/en-us/library/12a04hfd(v=vs.80).aspx. However, given that Windows runs on x86 / x64 only, that's not saying much (Intel and AMD memory models make it easy and efficient to implement acquire / release semantics in a language).

exception.getMessage() output with class name

My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.

Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:

public class Test {
    public static void main(String[] args) {
        try {
            failingMethod();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }       

    private static void failingMethod() {
        throw new RuntimeException("Just the message");
    }
}

Output:

Error: Just the message

Output of git branch in tree like fashion

The answer below uses git log:

I mentioned a similar approach in 2009 with "Unable to show a Git tree in terminal":

git log --graph --pretty=oneline --abbrev-commit

But the full one I have been using is in "How to display the tag name and branch name using git log --graph" (2011):

git config --global alias.lgb "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset%n' --abbrev-commit --date=relative --branches"

git lgb

Original answer (2010)

git show-branch --list comes close of what you are looking for (with the topo order)

--topo-order

By default, the branches and their commits are shown in reverse chronological order.
This option makes them appear in topological order (i.e., descendant commits are shown before their parents).

But the tool git wtf can help too. Example:

$ git wtf
Local branch: master
[ ] NOT in sync with remote (needs push)
    - Add before-search hook, for shortcuts for custom search queries. [4430d1b] (edwardzyang@...; 7 days ago)
Remote branch: origin/master ([email protected]:sup/mainline.git)
[x] in sync with local

Feature branches:
{ } origin/release-0.8.1 is NOT merged in (1 commit ahead)
    - bump to 0.8.1 [dab43fb] (wmorgan-sup@...; 2 days ago)
[ ] labels-before-subj is NOT merged in (1 commit ahead)
    - put labels before subject in thread index view [790b64d] (marka@...; 4 weeks ago)
{x} origin/enclosed-message-display-tweaks merged in
(x) experiment merged in (only locally)

NOTE: working directory contains modified files

git-wtf shows you:

  • How your branch relates to the remote repo, if it's a tracking branch.
  • How your branch relates to non-feature ("version") branches, if it's a feature branch.
  • How your branch relates to the feature branches, if it's a version branch

git: fatal unable to auto-detect email address

if you face this problem to type in your git bash

git config --global user.name yourname

git config --global user.email youremail

if problem this cmds please try those cmds vica versa

Twitter bootstrap modal-backdrop doesn't disappear

Another point of view to this question. (I'm using the bootstrap.js version 3.3.6)

I mistaken initialize modal both by manually in javascript:

$('#myModal').modal({
   keyboard: false
})

and by using

data-toggle="modal"

in this button like example below (shown in document)

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>

so the result its create two instance of

<div class="modal-backdrop fade in"></div>

append to the body of my html when open the modal. This can be the cause when closing the modal by using function:

$('#myModal').modal('hide');

it remove only one backdrop instance (as show above) so the backdrop won't disappeared. But it did disappear if you use data-dismiss="modal" add on html as show in bootstrap doc.

So the solution to my problem is to only initialize modal manually in javascript and not using data attribute, In this way I can both close the modal manually and by using data-dismiss="modal" features.

Hope this will help if you encountered the same problem as me.