Programs & Examples On #Context sensitive help

How to fix "set SameSite cookie to none" warning?

I ended up fixing our Ubuntu 18.04 / Apache 2.4.29 / PHP 7.2 install for Chrome 80 by installing mod_headers:

a2enmod headers

Adding the following directive to our Apache VirtualHost configurations:

Header edit Set-Cookie ^(.*)$ "$1; Secure; SameSite=None"

And restarting Apache:

service apache2 restart

In reviewing the docs (http://www.balkangreenfoundation.org/manual/en/mod/mod_headers.html) I noticed the "always" condition has certain situations where it does not work from the same pool of response headers. Thus not using "always" is what worked for me with PHP but the docs suggest that if you want to cover all your bases you could add the directive both with and without "always". I have not tested that.

Do not want scientific notation on plot axis

Try this. I purposely broke out various parts so you can move things around.

library(sfsmisc)

#Generate the data
x <- 1:100000
y <- 1:100000

#Setup the plot area
par(pty="m", plt=c(0.1, 1, 0.1, 1), omd=c(0.1,0.9,0.1,0.9))

#Plot a blank graph without completing the x or y axis
plot(x, y, type = "n", xaxt = "n", yaxt="n", xlab="", ylab="", log = "x", col="blue")
mtext(side=3, text="Test Plot", line=1.2, cex=1.5)

#Complete the x axis
eaxis(1, padj=-0.5, cex.axis=0.8)
mtext(side=1, text="x", line=2.5)

#Complete the y axis and add the grid
aty <- seq(par("yaxp")[1], par("yaxp")[2], (par("yaxp")[2] - par("yaxp")[1])/par("yaxp")[3])
axis(2, at=aty, labels=format(aty, scientific=FALSE), hadj=0.9, cex.axis=0.8, las=2)
mtext(side=2, text="y", line=4.5)
grid()

#Add the line last so it will be on top of the grid
lines(x, y, col="blue")

enter image description here

Space between two divs

If you don't require support for IE6:

h1 {margin-bottom:20px;}
div + div {margin-top:10px;}

The second line adds spacing between divs, but will not add any before the first div or after the last one.

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

I have written code that sniffs IE4 or greater and is currently functioning perfectly in sites for my company's clients, as well as my own personal sites.

Include the following enumerated constant and function variables into a javascript include file on your page...

//methods
var BrowserTypes = {
    Unknown: 0,
    FireFox: 1,
    Chrome: 2,
    Safari: 3,
    IE: 4,
    IE7: 5,
    IE8: 6,
    IE9: 7,
    IE10: 8,
    IE11: 8,
    IE12: 8
};

var Browser = function () {
    try {
        //declares
        var type;
        var version;
        var sVersion;

        //process
        switch (navigator.appName.toLowerCase()) {
            case "microsoft internet explorer":
                type = BrowserTypes.IE;
                sVersion = navigator.appVersion.substring(navigator.appVersion.indexOf('MSIE') + 5, navigator.appVersion.length);
                version = parseFloat(sVersion.split(";")[0]);
                switch (parseInt(version)) {
                    case 7:
                        type = BrowserTypes.IE7;
                        break;
                    case 8:
                        type = BrowserTypes.IE8;
                        break;
                    case 9:
                        type = BrowserTypes.IE9;
                        break;
                    case 10:
                        type = BrowserTypes.IE10;
                        break;
                    case 11:
                        type = BrowserTypes.IE11;
                        break;
                    case 12:
                        type = BrowserTypes.IE12;
                        break;
                }
                break;
            case "netscape":
                if (navigator.userAgent.toLowerCase().indexOf("chrome") > -1) { type = BrowserTypes.Chrome; }
                else { if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) { type = BrowserTypes.FireFox } };
                break;
            default:
                type = BrowserTypes.Unknown;
                break;
        }

        //returns
        return type;
    } catch (ex) {
    }
};

Then all you have to do is use any conditional functionality such as...

ie. value = (Browser() >= BrowserTypes.IE) ? node.text : node.textContent;

or WindowWidth = (((Browser() >= BrowserTypes.IE9) || (Browser() < BrowserTypes.IE)) ? window.innerWidth : document.documentElement.clientWidth);

or sJSON = (Browser() >= BrowserTypes.IE) ? xmlElement.text : xmlElement.textContent;

Get the idea? Hope this helps.

Oh, you might want to keep it in mind to QA the Browser() function after IE10 is released, just to verify they didn't change the rules.

How to toggle boolean state of react component?

Since nobody posted this, I am posting the correct answer. If your new state update depends on the previous state, always use the functional form of setState which accepts as argument a function that returns a new state.

In your case:

this.setState(prevState => ({
  check: !prevState.check
}));

See docs


Since this answer is becoming popular, adding the approach that should be used for React Hooks (v16.8+):

If you are using the useState hook, then use the following code (in case your new state depends on the previous state):

const [check, setCheck] = useState(false);
// ...
setCheck(prevCheck => !prevCheck);

mysql update query with sub query

Thanks, I didn't have the idea of an UPDATE with INNER JOIN.

In the original query, the mistake was to name the subquery, which must return a value and can't therefore be aliased.

UPDATE Competition
SET Competition.NumberOfTeams =
(SELECT count(*) -- no column alias
  FROM PicksPoints
  WHERE UserCompetitionID is not NULL
  -- put the join condition INSIDE the subquery :
  AND CompetitionID =  Competition.CompetitionID
  group by CompetitionID
) -- no table alias

should do the trick for every record of Competition.

To be noticed :

The effect is NOT EXACTLY the same as the query proposed by mellamokb, which won't update Competition records with no corresponding PickPoints.

Since SELECT id, COUNT(*) GROUP BY id will only count for existing values of ids,

whereas a SELECT COUNT(*) will always return a value, being 0 if no records are selected.

This may, or may not, be a problem for you.

0-aware version of mellamokb query would be :

Update Competition as C
LEFT join (
  select CompetitionId, count(*) as NumberOfTeams
  from PicksPoints as p
  where UserCompetitionID is not NULL
  group by CompetitionID
) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = IFNULL(A.NumberOfTeams, 0)

In other words, if no corresponding PickPoints are found, set Competition.NumberOfTeams to zero.

Allowed characters in filename

You should start with the Wikipedia Filename page. It has a decent-sized table (Comparison of filename limitations), listing the reserved characters for quite a lot of file systems.

It also has a plethora of other information about each file system, including reserved file names such as CON under MS-DOS. I mention that only because I was bitten by that once when I shortened an include file from const.h to con.h and spent half an hour figuring out why the compiler hung.

Turns out DOS ignored extensions for devices so that con.h was exactly the same as con, the input console (meaning, of course, the compiler was waiting for me to type in the header file before it would continue).

Python coding standards/best practices

Yes, I try to follow it as closely as possible.

I don't follow any other coding standards.

post ajax data to PHP and return data

 $.ajax({
            type: "POST",
            data: {data:the_id},
            url: "http://localhost/test/index.php/data/count_votes",
            success: function(data){
               //data will contain the vote count echoed by the controller i.e.  
                 "yourVoteCount"
              //then append the result where ever you want like
              $("span#votes_number").html(data); //data will be containing the vote count which you have echoed from the controller

                }
            });

in the controller

$data = $_POST['data'];  //$data will contain the_id
//do some processing
echo "yourVoteCount";

Clarification

i think you are confusing

{data:the_id}

with

success:function(data){

both the data are different for your own clarity sake you can modify it as

success:function(vote_count){
$(span#someId).html(vote_count);

Android: Clear the back stack

for me adding Intent.FLAG_ACTIVITY_CLEAR_TASK solved the problem

Intent i = new Intent(SettingsActivity.this, StartPage.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP  | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
finish();

Difference between Git and GitHub

Simply put, Git is a version control system that lets you manage and keep track of your source code history. GitHub is a cloud-based hosting service that lets you manage Git repositories. If you have open-source projects that use Git, then GitHub is designed to help you better manage them.

How to load GIF image in Swift?

Simple extension for local gifs. Gets all the images from the gif and adds it to the imageView animationImages.

extension UIImageView {
    static func fromGif(frame: CGRect, resourceName: String) -> UIImageView? {
        guard let path = Bundle.main.path(forResource: resourceName, ofType: "gif") else {
            print("Gif does not exist at that path")
            return nil
        }
        let url = URL(fileURLWithPath: path)
        guard let gifData = try? Data(contentsOf: url),
            let source =  CGImageSourceCreateWithData(gifData as CFData, nil) else { return nil }
        var images = [UIImage]()
        let imageCount = CGImageSourceGetCount(source)
        for i in 0 ..< imageCount {
            if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
                images.append(UIImage(cgImage: image))
            }
        }
        let gifImageView = UIImageView(frame: frame)
        gifImageView.animationImages = images
        return gifImageView
    }
}

To Use:

 guard let confettiImageView = UIImageView.fromGif(frame: view.frame, resourceName: "confetti") else { return }
 view.addSubview(confettiImageView)
 confettiImageView.startAnimating()

Repeat and duration customizations using UIImageView APIs.

confettiImageView.animationDuration = 3
confettiImageView.animationRepeatCount = 1

When you are done animating the gif and want to release the memory.

confettiImageView.animationImages = nil

Angularjs ng-model doesn't work inside ng-if

You can use $parent to refer to the model defined in the parent scope like this

<input type="checkbox" ng-model="$parent.testb" />

Does java.util.List.isEmpty() check if the list itself is null?

Invoking any method on any null reference will always result in an exception. Test if the object is null first:

List<Object> test = null;
if (test != null && !test.isEmpty()) {
    // ...
}

Alternatively, write a method to encapsulate this logic:

public static <T> boolean IsNullOrEmpty(Collection<T> list) {
    return list == null || list.isEmpty();
}

Then you can do:

List<Object> test = null;
if (!IsNullOrEmpty(test)) {
    // ...
}

Remove all items from RecyclerView

This is how I cleared my recyclerview and added new items to it with animation:

mList.clear();
mAdapter.notifyDataSetChanged();

mSwipeRefreshLayout.setRefreshing(false);

//reset adapter with empty array list (it did the trick animation)
mAdapter = new MyAdapter(context, mList);
recyclerView.setAdapter(mAdapter);

mList.addAll(newList);
mAdapter.notifyDataSetChanged();

Extracting just Month and Year separately from Pandas Datetime column

df['year_month']=df.datetime_column.apply(lambda x: str(x)[:7])

This worked fine for me, didn't think pandas would interpret the resultant string date as date, but when i did the plot, it knew very well my agenda and the string year_month where ordered properly... gotta love pandas!

Pointer-to-pointer dynamic two-dimensional array

The first method cannot be used to create dynamic 2D arrays because by doing:

int *board[4];

you essentially allocated an array of 4 pointers to int on stack. Therefore, if you now populate each of these 4 pointers with a dynamic array:

for (int i = 0; i < 4; ++i) {
  board[i] = new int[10];
}

what you end-up with is a 2D array with static number of rows (in this case 4) and dynamic number of columns (in this case 10). So it is not fully dynamic because when you allocate an array on stack you should specify a constant size, i.e. known at compile-time. Dynamic array is called dynamic because its size is not necessary to be known at compile-time, but can rather be determined by some variable in runtime.

Once again, when you do:

int *board[4];

or:

const int x = 4; // <--- `const` qualifier is absolutely needed in this case!
int *board[x];

you supply a constant known at compile-time (in this case 4 or x) so that compiler can now pre-allocate this memory for your array, and when your program is loaded into the memory it would already have this amount of memory for the board array, that's why it is called static, i.e. because the size is hard-coded and cannot be changed dynamically (in runtime).

On the other hand, when you do:

int **board;
board = new int*[10];

or:

int x = 10; // <--- Notice that it does not have to be `const` anymore!
int **board;
board = new int*[x];

the compiler does not know how much memory board array will require, and therefore it does not pre-allocate anything. But when you start your program, the size of array would be determined by the value of x variable (in runtime) and the corresponding space for board array would be allocated on so-called heap - the area of memory where all programs running on your computer can allocate unknown beforehand (at compile-time) amounts memory for personal usage.

As a result, to truly create dynamic 2D array you have to go with the second method:

int **board;
board = new int*[10]; // dynamic array (size 10) of pointers to int

for (int i = 0; i < 10; ++i) {
  board[i] = new int[10];
  // each i-th pointer is now pointing to dynamic array (size 10) of actual int values
}

We've just created an square 2D array with 10 by 10 dimensions. To traverse it and populate it with actual values, for example 1, we could use nested loops:

for (int i = 0; i < 10; ++i) {   // for each row
  for (int j = 0; j < 10; ++j) { // for each column
    board[i][j] = 1;
  }
}

How to take complete backup of mysql database using mysqldump command line utility

In addition to the --routines flag you will need to grant the backup user permissions to read the stored procedures:

GRANT SELECT ON `mysql`.`proc` TO <backup user>@<backup host>;

My minimal set of GRANT privileges for the backup user are:

GRANT USAGE ON *.* TO ...
GRANT SELECT, LOCK TABLES ON <target_db>.* TO ...
GRANT SELECT ON `mysql`.`proc` TO ...

RestSharp simple complete example

Pawel Sawicz .NET blog has a real good explanation and example code, explaining how to call the library;

GET:

var client = new RestClient("192.168.0.1");
var request = new RestRequest("api/item/", Method.GET);
var queryResult = client.Execute<List<Items>>(request).Data;

POST:

var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Item
{
   ItemName = someName,
   Price = 19.99
});
client.Execute(request);

DELETE:

var item = new Item(){//body};
var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/{id}", Method.DELETE);
request.AddParameter("id", idItem);
 
client.Execute(request)

The RestSharp GitHub page has quite an exhaustive sample halfway down the page. To get started install the RestSharp NuGet package in your project, then include the necessary namespace references in your code, then above code should work (possibly negating your need for a full example application).

NuGet RestSharp

Programmatically navigate using React router

This worked for me, no special imports needed:

<input 
  type="button" 
  name="back" 
  id="back" 
  class="btn btn-primary" 
  value="Back" 
  onClick={() => { this.props.history.goBack() }} 
/>

Get properties and values from unknown object

I haven't found this to work on, say Application objects. I have however had success with

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

string rval = serializer.Serialize(myAppObj);

How to add a "confirm delete" option in ASP.Net Gridview?

I didn't want any image so i modified the answer given by @statmaster to make it simple entry along with the other columns.

<asp:TemplateField ShowHeader="False">
        <ItemTemplate>
            <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this entry?');">Delete </asp:LinkButton>             
        </ItemTemplate>
</asp:TemplateField>

The colour of the text can be changed using the Forecolor Property.

python BeautifulSoup parsing table

Here you go:

data = []
table = soup.find('table', attrs={'class':'lineItemsTable'})
table_body = table.find('tbody')

rows = table_body.find_all('tr')
for row in rows:
    cols = row.find_all('td')
    cols = [ele.text.strip() for ele in cols]
    data.append([ele for ele in cols if ele]) # Get rid of empty values

This gives you:

[ [u'1359711259', u'SRF', u'08/05/2013', u'5310 4 AVE', u'K', u'19', u'125.00', u'$'], 
  [u'7086775850', u'PAS', u'12/14/2013', u'3908 6th Ave', u'K', u'40', u'125.00', u'$'], 
  [u'7355010165', u'OMT', u'12/14/2013', u'3908 6th Ave', u'K', u'40', u'145.00', u'$'], 
  [u'4002488755', u'OMT', u'02/12/2014', u'NB 1ST AVE @ E 23RD ST', u'5', u'115.00', u'$'], 
  [u'7913806837', u'OMT', u'03/03/2014', u'5015 4th Ave', u'K', u'46', u'115.00', u'$'], 
  [u'5080015366', u'OMT', u'03/10/2014', u'EB 65TH ST @ 16TH AV E', u'7', u'50.00', u'$'], 
  [u'7208770670', u'OMT', u'04/08/2014', u'333 15th St', u'K', u'70', u'65.00', u'$'], 
  [u'$0.00\n\n\nPayment Amount:']
]

Couple of things to note:

  • The last row in the output above, the Payment Amount is not a part of the table but that is how the table is laid out. You can filter it out by checking if the length of the list is less than 7.
  • The last column of every row will have to be handled separately since it is an input text box.

How do I implement basic "Long Polling"?

Below is a long polling solution I have developed for Inform8 Web. Basically you override the class and implement the loadData method. When the loadData returns a value or the operation times out it will print the result and return.

If the processing of your script may take longer than 30 seconds you may need to alter the set_time_limit() call to something longer.

Apache 2.0 license. Latest version on github https://github.com/ryanhend/Inform8/blob/master/Inform8-web/src/config/lib/Inform8/longpoll/LongPoller.php

Ryan

abstract class LongPoller {

  protected $sleepTime = 5;
  protected $timeoutTime = 30;

  function __construct() {
  }


  function setTimeout($timeout) {
    $this->timeoutTime = $timeout;
  }

  function setSleep($sleep) {
    $this->sleepTime = $sleepTime;
  }


  public function run() {
    $data = NULL;
    $timeout = 0;

    set_time_limit($this->timeoutTime + $this->sleepTime + 15);

    //Query database for data
    while($data == NULL && $timeout < $this->timeoutTime) {
      $data = $this->loadData();
      if($data == NULL){

        //No new orders, flush to notify php still alive
        flush();

        //Wait for new Messages
        sleep($this->sleepTime);
        $timeout += $this->sleepTime;
      }else{
        echo $data;
        flush();
      }
    }

  }


  protected abstract function loadData();

}

Android: how to hide ActionBar on certain activities

This works for me! Put this in your Activity in manifests

<activity
   // ...
   android:theme="@style/Theme.AppCompat.Light.NoActionBar"
   // ...
   </activity>

You can also make your custom theme in styles.xml like this:

<style name="Theme.MyCustomTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
        <item name = "android:windowActionBar">false</item>
        <item name = "android:windowNoTitle">true</item>
        // more custom...
    </style>

Hope this help.

Selecting a Record With MAX Value

Here's an option if you have multiple records for each Customer and are looking for the latest balance for each (say they are dated records):

SELECT ID, BALANCE FROM (
    SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DateModified DESC) as RowNum, ID, BALANCE
    FROM CUSTOMERS
) C
WHERE RowNum = 1

Simple way to understand Encapsulation and Abstraction

Encapsulation can be thought of as wrapping paper used to bind data and function together as a single unit which protects it from all kinds of external dirt (I mean external functions).

Abstraction involves absence of details and the use of a simple interface to control a complex system.

For example we can light a bulb by the pressing of a button without worrying about the underlying electrical engineering (Abstraction) .

However u cannot light the bulb in any other way. (Encapsulation)

sending email via php mail function goes to spam

The problem is simple that the PHP-Mail function is not using a well configured SMTP Server.

Nowadays Email-Clients and Servers perform massive checks on the emails sending server, like Reverse-DNS-Lookups, Graylisting and whatevs. All this tests will fail with the php mail() function. If you are using a dynamic ip, its even worse.

Use the PHPMailer-Class and configure it to use smtp-auth along with a well configured, dedicated SMTP Server (either a local one, or a remote one) and your problems are gone.

https://github.com/PHPMailer/PHPMailer

bootstrap 3 navbar collapse button not working

It happened with me, I used jquery.min.js file that downloaded from bootstrap site it is not working, I tried same page with other jquery.min.js file it worked fine so if you face this problem try to reference other jquery.min.js file in your page and try again

Cannot read property 'getContext' of null, using canvas

You should put javascript tag in your html file. because browser load your webpage according to html flow, you should put your javascript file<script src="javascript/game.js"> after the <canvas>element tag. otherwise,if you put your javascript in the header of html.Browser load script first but it doesn't find the canvas. So your canvas doesn't work.

Unable to start the mysql server in ubuntu

Yes, should try reinstall mysql, but use the --reinstall flag to force a package reconfiguration. So the operating system service configuration is not skipped:

sudo apt --reinstall install mysql-server

Cannot read property 'map' of undefined

I think you forgot to change

data={this.props.data}

to

data={this.state.data}

in the render function of CommentBox. I did the same mistake when I was following the tutorial. Thus the whole render function should look like

render: function() {
  return (
    <div className="commentBox">
      <h1>Comments</h1>
      <CommentList data={this.state.data} />
      <CommentForm />
    </div>
  );
}

instead of

render: function() {
  return (
    <div className="commentBox">
      <h1>Comments</h1>
      <CommentList data={this.props.data} />
      <CommentForm />
    </div>
  );

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

What does "hard coded" mean?

There are two types of coding.

(1) hard-coding (2) soft-coding

Hard-coding. Assign values to program during writing source code and make executable file of program.Now, it is very difficult process to change or modify the program source code values. like in block-chain technology, genesis block is hard-code that cannot changed or modified.

Soft-coding: it is process of inserting values from external source into computer program. like insert values through keyboard, command line interface. Soft-coding considered as good programming practice because developers can easily modify programs.

What's the best way to set a single pixel in an HTML5 canvas?

There are two best contenders:

  1. Create a 1×1 image data, set the color, and putImageData at the location:

    var id = myContext.createImageData(1,1); // only do this once per page
    var d  = id.data;                        // only do this once per page
    d[0]   = r;
    d[1]   = g;
    d[2]   = b;
    d[3]   = a;
    myContext.putImageData( id, x, y );     
    
  2. Use fillRect() to draw a pixel (there should be no aliasing issues):

    ctx.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";
    ctx.fillRect( x, y, 1, 1 );
    

You can test the speed of these here: http://jsperf.com/setting-canvas-pixel/9 or here https://www.measurethat.net/Benchmarks/Show/1664/1

I recommend testing against browsers you care about for maximum speed. As of July 2017, fillRect() is 5-6× faster on Firefox v54 and Chrome v59 (Win7x64).

Other, sillier alternatives are:

  • using getImageData()/putImageData() on the entire canvas; this is about 100× slower than other options.

  • creating a custom image using a data url and using drawImage() to show it:

    var img = new Image;
    img.src = "data:image/png;base64," + myPNGEncoder(r,g,b,a);
    // Writing the PNGEncoder is left as an exercise for the reader
    
  • creating another img or canvas filled with all the pixels you want and use drawImage() to blit just the pixel you want across. This would probably be very fast, but has the limitation that you need to pre-calculate the pixels you need.

Note that my tests do not attempt to save and restore the canvas context fillStyle; this would slow down the fillRect() performance. Also note that I am not starting with a clean slate or testing the exact same set of pixels for each test.

max(length(field)) in mysql

select * 
from my_table 
where length( Name ) = ( 
      select max( length( Name ) ) 
      from my_table
      limit 1 
);

It this involves two table scans, and so might not be very fast !

What's the difference between [ and [[ in Bash?

[[ is bash's improvement to the [ command. It has several enhancements that make it a better choice if you write scripts that target bash. My favorites are:

  1. It is a syntactical feature of the shell, so it has some special behavior that [ doesn't have. You no longer have to quote variables like mad because [[ handles empty strings and strings with whitespace more intuitively. For example, with [ you have to write

    if [ -f "$file" ]
    

    to correctly handle empty strings or file names with spaces in them. With [[ the quotes are unnecessary:

    if [[ -f $file ]]
    
  2. Because it is a syntactical feature, it lets you use && and || operators for boolean tests and < and > for string comparisons. [ cannot do this because it is a regular command and &&, ||, <, and > are not passed to regular commands as command-line arguments.

  3. It has a wonderful =~ operator for doing regular expression matches. With [ you might write

    if [ "$answer" = y -o "$answer" = yes ]
    

    With [[ you can write this as

    if [[ $answer =~ ^y(es)?$ ]]
    

    It even lets you access the captured groups which it stores in BASH_REMATCH. For instance, ${BASH_REMATCH[1]} would be "es" if you typed a full "yes" above.

  4. You get pattern matching aka globbing for free. Maybe you're less strict about how to type yes. Maybe you're okay if the user types y-anything. Got you covered:

    if [[ $ANSWER = y* ]]
    

Keep in mind that it is a bash extension, so if you are writing sh-compatible scripts then you need to stick with [. Make sure you have the #!/bin/bash shebang line for your script if you use double brackets.

See also

mysql command for showing current configuration variables

As an alternative you can also query the information_schema database and retrieve the data from the global_variables (and global_status of course too). This approach provides the same information, but gives you the opportunity to do more with the results, as it is a plain old query.

For example you can convert units to become more readable. The following query provides the current global setting for the innodb_log_buffer_size in bytes and megabytes:

SELECT
  variable_name,
  variable_value AS innodb_log_buffer_size_bytes,
  ROUND(variable_value / (1024*1024)) AS innodb_log_buffer_size_mb
FROM information_schema.global_variables
WHERE variable_name LIKE  'innodb_log_buffer_size';

As a result you get:

+------------------------+------------------------------+---------------------------+
| variable_name          | innodb_log_buffer_size_bytes | innodb_log_buffer_size_mb |
+------------------------+------------------------------+---------------------------+
| INNODB_LOG_BUFFER_SIZE | 268435456                    |                       256 |
+------------------------+------------------------------+---------------------------+
1 row in set (0,00 sec)

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

How to get a list of all files that changed between two Git commits?

With git show you can get a similar result. For look the commit (like it looks on git log view) with the list of files included in, use:

git show --name-only [commit-id_A]^..[commit-id_B]

Where [commit-id_A] is the initial commit and [commit-id_B] is the last commit than you want to show.

Special attention with ^ symbol. If you don't put that, the commit-id_A information will not deploy.

How can I group data with an Angular filter?

In addition to the accepted answers above I created a generic 'groupBy' filter using the underscore.js library.

JSFiddle (updated): http://jsfiddle.net/TD7t3/

The filter

app.filter('groupBy', function() {
    return _.memoize(function(items, field) {
            return _.groupBy(items, field);
        }
    );
});

Note the 'memoize' call. This underscore method caches the result of the function and stops angular from evaluating the filter expression every time, thus preventing angular from reaching the digest iterations limit.

The html

<ul>
    <li ng-repeat="(team, players) in teamPlayers | groupBy:'team'">
        {{team}}
        <ul>
            <li ng-repeat="player in players">
                {{player.name}}
            </li>
        </ul>
    </li>
</ul>

We apply our 'groupBy' filter on the teamPlayers scope variable, on the 'team' property. Our ng-repeat receives a combination of (key, values[]) that we can use in our following iterations.

Update June 11th 2014 I expanded the group by filter to account for the use of expressions as the key (eg nested variables). The angular parse service comes in quite handy for this:

The filter (with expression support)

app.filter('groupBy', function($parse) {
    return _.memoize(function(items, field) {
        var getter = $parse(field);
        return _.groupBy(items, function(item) {
            return getter(item);
        });
    });
});

The controller (with nested objects)

app.controller('homeCtrl', function($scope) {
    var teamAlpha = {name: 'team alpha'};
    var teamBeta = {name: 'team beta'};
    var teamGamma = {name: 'team gamma'};

    $scope.teamPlayers = [{name: 'Gene', team: teamAlpha},
                      {name: 'George', team: teamBeta},
                      {name: 'Steve', team: teamGamma},
                      {name: 'Paula', team: teamBeta},
                      {name: 'Scruath of the 5th sector', team: teamGamma}];
});

The html (with sortBy expression)

<li ng-repeat="(team, players) in teamPlayers | groupBy:'team.name'">
    {{team}}
    <ul>
        <li ng-repeat="player in players">
            {{player.name}}
        </li>
    </ul>
</li>

JSFiddle: http://jsfiddle.net/k7fgB/2/

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

This is still the top post when searching, but it's no longer valid. Best answer is here, but the TLDR is

<c-b>:resize-window -A

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

You should use

this.router.parent.navigate(['/About']);

As well as specifying the route path, you can also specify your route's name:

{ path:'/About', name: 'About',   ... }

this.router.parent.navigate(['About']);

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

ALTER TABLE `{$installer->getTable('sales/quote_payment')}`
ADD `custom_field_one` VARCHAR( 255 ) NOT NULL,
    ADD `custom_field_two` VARCHAR( 255 ) NOT NULL;

Add backtick i.e. " ` " properly. Write your getTable name and column name between backtick.

Check if object exists in JavaScript

zero and null are implicit pointers. If you arn't doing arithmetic, comparing, or printing '0' to screen there is no need to actually type it. Its implicit. As in implied. Typeof is also not required for the same reason. Watch.

if(obj) console.log("exists");

I didn't see request for a not or else there for it is not included as. As much as i love extra content which doesn't fit into the question. Lets keep it simple.

Apple Cover-flow effect using jQuery or other library?

the effect that happens when you hit the space bar in a folder of documents, allowing you to preview them in a lightbox fashion

Looks like a classic lightbox plugin is needed. This is my favorite jQuery lightbox plugin: http://colorpowered.com/colorbox/. It's easy to customize, etc.

Difference between jQuery’s .hide() and setting CSS to display: none

See there is no difference if you use basic hide method. But jquery provides various hide method which give effects to the element. Refer below link for detailed explanation: Effects for Hide in Jquery

Pattern matching using a wildcard

If you want to examine elements inside a dataframe you should not be using ls() which only looks at the names of objects in the current workspace (or if used inside a function in the current environment). Rownames or elements inside such objects are not visible to ls() (unless of course you add an environment argument to the ls(.)-call). Try using grep() which is the workhorse function for pattern matching of character vectors:

result <- a[ grep("blue", a$x) , ]  # Note need to use `a$` to get at the `x`

If you want to use subset then consider the closely related function grepl() which returns a vector of logicals can be used in the subset argument:

subset(a, grepl("blue", a$x))
      x
2 blue1
3 blue2

Edit: Adding one "proper" use of glob2rx within subset():

result <- subset(a,  grepl(glob2rx("blue*") , x) )
result
      x
2 blue1
3 blue2

I don't think I actually understood glob2rx until I came back to this question. (I did understand the scoping issues that were ar the root of the questioner's difficulties. Anybody reading this should now scroll down to Gavin's answer and upvote it.)

How should I do integer division in Perl?

Hope it works

int(9/4) = 2.

Thanks Manojkumar

android: stretch image in imageview to fit screen

Give in the xml file of your layout android:scaleType="fitXY"
P.S : this applies to when the image is set with android:src="..." rather than android:background="..." as backgrounds are set by default to stretch and fit to the View.

How do I start my app on startup?

Listen for the ACTION_BOOT_COMPLETE and do what you need to from there. There is a code snippet here.

Update:

Original link on answer is down, so based on the comments, here it is linked code, because no one would ever miss the code when the links are down.

In AndroidManifest.xml (application-part):

<receiver android:enabled="true" android:name=".BootUpReceiver"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

        <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</receiver>

...

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

...

public class BootUpReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
                Intent i = new Intent(context, MyActivity.class);  //MyActivity can be anything which you want to start on bootup...
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);  
        }

}

Source: https://web.archive.org/web/20150520124552/http://www.androidsnippets.com/autostart-an-application-at-bootup

How to add a new line of text to an existing file in Java?

Try: "\r\n"

Java 7 example:

// append = true
try(PrintWriter output = new PrintWriter(new FileWriter("log.txt",true))) 
{
    output.printf("%s\r\n", "NEWLINE");
} 
catch (Exception e) {}

how to loop through rows columns in excel VBA Macro

I'd recommend the Range object's AutoFill method for this:

rngSource.AutoFill Destination:=rngDest

Specify the Source range that contains the values or formulas you want to fill down, and the Destination range as the whole range that you want the cells filled to. The Destination range must include the Source range. You can fill across as well as down.

It works exactly the same way as it would if you manually "dragged" the cells at the corner with the mouse; absolute and relative formulas work as expected.

Here's an example:

'Set some example values'
Range("A1").Value = "1"
Range("B1").Formula = "=NOW()"
Range("C1").Formula = "=B1+A1"

'AutoFill the values / formulas to row 20'
Range("A1:C1").AutoFill Destination:=Range("A1:C20")

Hope this helps.

Increase max_execution_time in PHP?

Add this to an htaccess file (and see edit notes added below):

<IfModule mod_php5.c>
   php_value post_max_size 200M
   php_value upload_max_filesize 200M
   php_value memory_limit 300M
   php_value max_execution_time 259200
   php_value max_input_time 259200
   php_value session.gc_maxlifetime 1200
</IfModule>

Additional resources and information:


2021 EDIT:

As PHP and Apache evolve and grow, I think it is important for me to take a moment to mention a few things to consider and possible "gotchas" to consider:

  • PHP can be run as a module or as CGI. It is not recommended to run as CGI as it creates a lot of opportunities for attack vectors [Read More]. Running as a module (the safer option) will trigger the settings to be used if the specific module from <IfModule is loaded.
  • The answer indicates to write mod_php5.c in the first line. If you are using PHP 7, you would replace that with mod_php7.c.
  • Sometimes after you make changes to your .htaccess file, restarting Apache or NGINX will not work. The most common reason for this is you are running PHP-FPM, which runs as a separate process. You need to restart that as well.
  • Remember these are settings that are normally defined in your php.ini config file(s). This method is usually only useful in the event your hosting provider does not give you access to change those files. In circumstances where you can edit the PHP configuration, it is recommended that you apply these settings there.
  • Finally, it's important to note that not all php.ini settings can be configured via an .htaccess file. A file list of php.ini directives can be found here, and the only ones you can change are the ones in the changeable column with the modes PHP_INI_ALL or PHP_INI_PERDIR.

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

I resolved this by adding following code to the HTML page, since we are using the third party API which is not controlled by us.

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> 

Hope this would help, and for a record as well.

How do you add an in-app purchase to an iOS application?

Swift Answer

This is meant to supplement my Objective-C answer for Swift users, to keep the Objective-C answer from getting too big.

Setup

First, set up the in-app purchase on appstoreconnect.apple.com. Follow the beginning part of my Objective-C answer (steps 1-13, under the App Store Connect header) for instructions on doing that.

It could take a few hours for your product ID to register in App Store Connect, so be patient.

Now that you've set up your in-app purchase information on App Store Connect, we need to add Apple's framework for in-app-purchases, StoreKit, to the app.

Go into your Xcode project, and go to the application manager (blue page-like icon at the top of the left bar where your app's files are). Click on your app under targets on the left (it should be the first option), then go to "Capabilities" at the top. On the list, you should see an option "In-App Purchase". Turn this capability ON, and Xcode will add StoreKit to your project.

Coding

Now, we're going to start coding!

First, make a new swift file that will manage all of your in-app-purchases. I'm going to call it IAPManager.swift.

In this file, we're going to create a new class, called IAPManager that is a SKProductsRequestDelegate and SKPaymentTransactionObserver. At the top, make sure you import Foundation and StoreKit

import Foundation
import StoreKit

public class IAPManager: NSObject, SKProductsRequestDelegate,
                         SKPaymentTransactionObserver {
}

Next, we're going to add a variable to define the identifier for our in-app purchase (you could also use an enum, which would be easier to maintain if you have multiple IAPs).

// This should the ID of the in-app-purchase you made on AppStore Connect.
// if you have multiple IAPs, you'll need to store their identifiers in
// other variables, too (or, preferably in an enum).
let removeAdsID = "com.skiplit.removeAds"

Let's add an initializer for our class next:

// This is the initializer for your IAPManager class
//
// A better, and more scaleable way of doing this
// is to also accept a callback in the initializer, and call
// that callback in places like the paymentQueue function, and
// in all functions in this class, in place of calls to functions
// in RemoveAdsManager (you'll see those calls in the code below).

let productID: String
init(productID: String){
    self.productID = productID
}

Now, we're going to add the required functions for SKProductsRequestDelegate and SKPaymentTransactionObserver to work:

We'll add the RemoveAdsManager class later

// This is called when a SKProductsRequest receives a response
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse){
    // Let's try to get the first product from the response
    // to the request
    if let product = response.products.first{
        // We were able to get the product! Make a new payment
        // using this product
        let payment = SKPayment(product: product)

        // add the new payment to the queue
        SKPaymentQueue.default().add(self)
        SKPaymentQueue.default().add(payment)
    }
    else{
        // Something went wrong! It is likely that either
        // the user doesn't have internet connection, or
        // your product ID is wrong!
        //
        // Tell the user in requestFailed() by sending an alert,
        // or something of the sort

        RemoveAdsManager.removeAdsFailure()
    }
}

// This is called when the user restores their IAP sucessfully
private func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue){
    // For every transaction in the transaction queue...
    for transaction in queue.transactions{
        // If that transaction was restored
        if transaction.transactionState == .restored{
            // get the producted ID from the transaction
            let productID = transaction.payment.productIdentifier

            // In this case, we have only one IAP, so we don't need to check
            // what IAP it is. However, this is useful if you have multiple IAPs!
            // You'll need to figure out which one was restored
            if(productID.lowercased() == IAPManager.removeAdsID.lowercased()){
                // Restore the user's purchases
                RemoveAdsManager.restoreRemoveAdsSuccess()
            }

            // finish the payment
            SKPaymentQueue.default().finishTransaction(transaction)
        }
    }
}

// This is called when the state of the IAP changes -- from purchasing to purchased, for example.
// This is where the magic happens :)
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]){
    for transaction in transactions{
        // get the producted ID from the transaction
        let productID = transaction.payment.productIdentifier

        // In this case, we have only one IAP, so we don't need to check
        // what IAP it is.
        // However, if you have multiple IAPs, you'll need to use productID
        // to check what functions you should run here!

        switch transaction.transactionState{
        case .purchasing:
            // if the user is currently purchasing the IAP,
            // we don't need to do anything.
            //
            // You could use this to show the user
            // an activity indicator, or something like that
            break
        case .purchased:
            // the user successfully purchased the IAP!
            RemoveAdsManager.removeAdsSuccess()
            SKPaymentQueue.default().finishTransaction(transaction)
        case .restored:
                // the user restored their IAP!
                IAPTestingHandler.restoreRemoveAdsSuccess()
                SKPaymentQueue.default().finishTransaction(transaction)
        case .failed:
                // The transaction failed!
                RemoveAdsManager.removeAdsFailure()
                // finish the transaction
                SKPaymentQueue.default().finishTransaction(transaction)
        case .deferred:
                // This happens when the IAP needs an external action
                // in order to proceeded, like Ask to Buy
                RemoveAdsManager.removeAdsDeferred()
                break
        }
    }
}

Now let's add some functions that can be used to start a purchase or a restore purchases:

// Call this when you want to begin a purchase
// for the productID you gave to the initializer
public func beginPurchase(){
    // If the user can make payments
    if SKPaymentQueue.canMakePayments(){
        // Create a new request
        let request = SKProductsRequest(productIdentifiers: [productID])
        // Set the request delegate to self, so we receive a response
        request.delegate = self
        // start the request
        request.start()
    }
    else{
        // Otherwise, tell the user that
        // they are not authorized to make payments,
        // due to parental controls, etc
    }
}

// Call this when you want to restore all purchases
// regardless of the productID you gave to the initializer
public func beginRestorePurchases(){
    // restore purchases, and give responses to self
    SKPaymentQueue.default().add(self)
    SKPaymentQueue.default().restoreCompletedTransactions()
}

Next, let's add a new utilities class to manage our IAPs. All of this code could be in one class, but having it multiple makes it a little cleaner. I'm going to make a new class called RemoveAdsManager, and in it, put a few functions

public class RemoveAdsManager{

    class func removeAds()
    class func restoreRemoveAds()

    class func areAdsRemoved() -> Bool

    class func removeAdsSuccess()
    class func restoreRemoveAdsSuccess()
    class func removeAdsDeferred()
    class func removeAdsFailure()
}

The first three functions, removeAds, restoreRemoveAds, and areAdsRemoved, are functions that you'll call to do certain actions. The last four are one that will be called by IAPManager.

Let's add some code to the first two functions, removeAds and restoreRemoveAds:

// Call this when the user wants
// to remove ads, like when they
// press a "remove ads" button
class func removeAds(){
    // Before starting the purchase, you could tell the
    // user that their purchase is happening, maybe with
    // an activity indicator

    let iap = IAPManager(productID: IAPManager.removeAdsID)
    iap.beginPurchase()
}

// Call this when the user wants
// to restore their IAP purchases,
// like when they press a "restore
// purchases" button.
class func restoreRemoveAds(){
    // Before starting the purchase, you could tell the
    // user that the restore action is happening, maybe with
    // an activity indicator

    let iap = IAPManager(productID: IAPManager.removeAdsID)
    iap.beginRestorePurchases()
}

And lastly, let's add some code to the last five functions.

// Call this to check whether or not
// ads are removed. You can use the
// result of this to hide or show
// ads
class func areAdsRemoved() -> Bool{
    // This is the code that is run to check
    // if the user has the IAP.

    return UserDefaults.standard.bool(forKey: "RemoveAdsPurchased")
}

// This will be called by IAPManager
// when the user sucessfully purchases
// the IAP
class func removeAdsSuccess(){
    // This is the code that is run to actually
    // give the IAP to the user!
    //
    // I'm using UserDefaults in this example,
    // but you may want to use Keychain,
    // or some other method, as UserDefaults
    // can be modified by users using their
    // computer, if they know how to, more
    // easily than Keychain

    UserDefaults.standard.set(true, forKey: "RemoveAdsPurchased")
    UserDefaults.standard.synchronize()
}

// This will be called by IAPManager
// when the user sucessfully restores
//  their purchases
class func restoreRemoveAdsSuccess(){
    // Give the user their IAP back! Likely all you'll need to
    // do is call the same function you call when a user
    // sucessfully completes their purchase. In this case, removeAdsSuccess()

    removeAdsSuccess()
}

// This will be called by IAPManager
// when the IAP failed
class func removeAdsFailure(){
    // Send the user a message explaining that the IAP
    // failed for some reason, and to try again later
}

// This will be called by IAPManager
// when the IAP gets deferred.
class func removeAdsDeferred(){
    // Send the user a message explaining that the IAP
    // was deferred, and pending an external action, like
    // Ask to Buy.
}

Putting it all together, we get something like this:

import Foundation
import StoreKit

public class RemoveAdsManager{

    // Call this when the user wants
    // to remove ads, like when they
    // press a "remove ads" button
    class func removeAds(){
        // Before starting the purchase, you could tell the
        // user that their purchase is happening, maybe with
        // an activity indicator

        let iap = IAPManager(productID: IAPManager.removeAdsID)
        iap.beginPurchase()
    }

    // Call this when the user wants
    // to restore their IAP purchases,
    // like when they press a "restore
    // purchases" button.
    class func restoreRemoveAds(){
        // Before starting the purchase, you could tell the
        // user that the restore action is happening, maybe with
        // an activity indicator

        let iap = IAPManager(productID: IAPManager.removeAdsID)
        iap.beginRestorePurchases()
    }

    // Call this to check whether or not
    // ads are removed. You can use the
    // result of this to hide or show
    // ads
    class func areAdsRemoved() -> Bool{
        // This is the code that is run to check
        // if the user has the IAP.

        return UserDefaults.standard.bool(forKey: "RemoveAdsPurchased")
    }

    // This will be called by IAPManager
    // when the user sucessfully purchases
    // the IAP
    class func removeAdsSuccess(){
        // This is the code that is run to actually
        // give the IAP to the user!
        //
        // I'm using UserDefaults in this example,
        // but you may want to use Keychain,
        // or some other method, as UserDefaults
        // can be modified by users using their
        // computer, if they know how to, more
        // easily than Keychain

        UserDefaults.standard.set(true, forKey: "RemoveAdsPurchased")
        UserDefaults.standard.synchronize()
    }

    // This will be called by IAPManager
    // when the user sucessfully restores
    //  their purchases
    class func restoreRemoveAdsSuccess(){
        // Give the user their IAP back! Likely all you'll need to
        // do is call the same function you call when a user
        // sucessfully completes their purchase. In this case, removeAdsSuccess()
        removeAdsSuccess()
    }

    // This will be called by IAPManager
    // when the IAP failed
    class func removeAdsFailure(){
        // Send the user a message explaining that the IAP
        // failed for some reason, and to try again later
    }

    // This will be called by IAPManager
    // when the IAP gets deferred.
    class func removeAdsDeferred(){
        // Send the user a message explaining that the IAP
        // was deferred, and pending an external action, like
        // Ask to Buy.
    }

}

public class IAPManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver{

    // This should the ID of the in-app-purchase you made on AppStore Connect.
    // if you have multiple IAPs, you'll need to store their identifiers in
    // other variables, too (or, preferably in an enum).
    static let removeAdsID = "com.skiplit.removeAds"

    // This is the initializer for your IAPManager class
    //
    // An alternative, and more scaleable way of doing this
    // is to also accept a callback in the initializer, and call
    // that callback in places like the paymentQueue function, and
    // in all functions in this class, in place of calls to functions
    // in RemoveAdsManager.
    let productID: String
    init(productID: String){
        self.productID = productID
    }

    // Call this when you want to begin a purchase
    // for the productID you gave to the initializer
    public func beginPurchase(){
        // If the user can make payments
        if SKPaymentQueue.canMakePayments(){
            // Create a new request
            let request = SKProductsRequest(productIdentifiers: [productID])
            request.delegate = self
            request.start()
        }
        else{
            // Otherwise, tell the user that
            // they are not authorized to make payments,
            // due to parental controls, etc
        }
    }

    // Call this when you want to restore all purchases
    // regardless of the productID you gave to the initializer
    public func beginRestorePurchases(){
        SKPaymentQueue.default().add(self)
        SKPaymentQueue.default().restoreCompletedTransactions()
    }

    // This is called when a SKProductsRequest receives a response
    public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse){
        // Let's try to get the first product from the response
        // to the request
        if let product = response.products.first{
            // We were able to get the product! Make a new payment
            // using this product
            let payment = SKPayment(product: product)

            // add the new payment to the queue
            SKPaymentQueue.default().add(self)
            SKPaymentQueue.default().add(payment)
        }
        else{
            // Something went wrong! It is likely that either
            // the user doesn't have internet connection, or
            // your product ID is wrong!
            //
            // Tell the user in requestFailed() by sending an alert,
            // or something of the sort

            RemoveAdsManager.removeAdsFailure()
        }
    }

    // This is called when the user restores their IAP sucessfully
    private func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue){
        // For every transaction in the transaction queue...
        for transaction in queue.transactions{
            // If that transaction was restored
            if transaction.transactionState == .restored{
                // get the producted ID from the transaction
                let productID = transaction.payment.productIdentifier

                // In this case, we have only one IAP, so we don't need to check
                // what IAP it is. However, this is useful if you have multiple IAPs!
                // You'll need to figure out which one was restored
                if(productID.lowercased() == IAPManager.removeAdsID.lowercased()){
                    // Restore the user's purchases
                    RemoveAdsManager.restoreRemoveAdsSuccess()
                }

                // finish the payment
                SKPaymentQueue.default().finishTransaction(transaction)
            }
        }
    }

    // This is called when the state of the IAP changes -- from purchasing to purchased, for example.
    // This is where the magic happens :)
    public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]){
        for transaction in transactions{
            // get the producted ID from the transaction
            let productID = transaction.payment.productIdentifier

            // In this case, we have only one IAP, so we don't need to check
            // what IAP it is.
            // However, if you have multiple IAPs, you'll need to use productID
            // to check what functions you should run here!

            switch transaction.transactionState{
            case .purchasing:
                // if the user is currently purchasing the IAP,
                // we don't need to do anything.
                //
                // You could use this to show the user
                // an activity indicator, or something like that
                break
            case .purchased:
                // the user sucessfully purchased the IAP!
                RemoveAdsManager.removeAdsSuccess()
                SKPaymentQueue.default().finishTransaction(transaction)
            case .restored:
                // the user restored their IAP!
                RemoveAdsManager.restoreRemoveAdsSuccess()
                SKPaymentQueue.default().finishTransaction(transaction)
            case .failed:
                // The transaction failed!
                RemoveAdsManager.removeAdsFailure()
                // finish the transaction
                SKPaymentQueue.default().finishTransaction(transaction)
            case .deferred:
                // This happens when the IAP needs an external action
                // in order to proceeded, like Ask to Buy
                RemoveAdsManager.removeAdsDeferred()
                break
            }
        }
    }

}

Lastly, you need to add some way for the user to start the purchase and call RemoveAdsManager.removeAds() and start a restore and call RemoveAdsManager.restoreRemoveAds(), like a button somewhere! Keep in mind that, per the App Store guidelines, you do need to provide a button to restore purchases somewhere.

Submitting for review

The last thing to do is submit your IAP for review on App Store Connect! For detailed instructions on doing that, you can follow the last part of my Objective-C answer, under the Submitting for review header.

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

Adding a reference to System.Net.Http.Formatting.dll may cause DLL mismatch issues. Right now, System.Net.Http.Formatting.dll appears to reference version 4.5.0.0 of Newtonsoft.Json.DLL, whereas the latest version is 6.0.0.0. That means you'll need to also add a binding redirect to avoid a .NET Assembly exception if you reference the latest Newtonsoft NuGet package or DLL:

<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
 </dependentAssembly> 

So an alternative solution to adding a reference to System.Net.Http.Formatting.dll is to read the response as a string and then desearalize yourself with JsonConvert.DeserializeObject(responseAsString). The full method would be:

public async Task<T> GetHttpResponseContentAsType(string baseUrl, string subUrl)
{
     using (var client = new HttpClient())
     {
         client.BaseAddress = new Uri(baseUrl);
         client.DefaultRequestHeaders.Accept.Clear();
         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

         HttpResponseMessage response = await client.GetAsync(subUrl);
         response.EnsureSuccessStatusCode();
         var responseAsString = await response.Content.ReadAsStringAsync();
         var responseAsConcreteType = JsonConvert.DeserializeObject<T>(responseAsString);
         return responseAsConcreteType;
      }
}

substring index range

For substring(startIndex, endIndex), startIndex is inclusive and endIndex are exclusive. The startIndex and endIndex are very confusing. I would understand substring(startIndex, length) to remember that.

C# Java HashMap equivalent

Check out the documentation on MSDN for the Hashtable class.

Represents a collection of key-and-value pairs that are organized based on the hash code of the key.

Also, keep in mind that this is not thread-safe.

How to convert milliseconds to "hh:mm:ss" format?

I used this:

String.format("%1$tH:%1$tM:%1$tS.%1$tL", millis);

See description of class Formatter.

See runnable example using input of 2400 ms.

What's the difference between a word and byte?

What I don't understand is what's the point of having a byte? Why not say 8 bits?

Apart from the technical point that a byte isn't necessarily 8 bits, the reasons for having a term is simple human nature:

  • economy of effort (aka laziness) - it is easier to say "byte" rather than "eight bits"

  • tribalism - groups of people like to use jargon / a private language to set them apart from others.

Just go with the flow. You are not going to change 50+ years of accumulated IT terminology and cultural baggage by complaining about it.


FWIW - the correct term to use when you mean "8 bits independent of the hardware architecture" is "octet".

HTTP Error 500.30 - ANCM In-Process Start Failure

Download the .NET Core Hosting Bundle installer using the following link:

Current .NET Core Hosting Bundle installer (direct download)

  1. Run the installer on the IIS server.
  2. Restart the server or execute net stop was /y followed by net start w3svc in a command shell.

How to retrieve a user environment variable in CMake (Windows)

You can also invoke itself to do this in a cross-platform way:

cmake -E env EnvironmentVariableName="Hello World" cmake ..

env [--unset=NAME]... [NAME=VALUE]... COMMAND [ARG]...

Run command in a modified environment.


Just be aware that this may only work the first time. If CMake re-configures with one of the consecutive builds (you just call e.g. make, one CMakeLists.txt was changed and CMake runs through the generation process again), the user defined environment variable may not be there anymore (in comparison to system wide environment variables).

So I transfer those user defined environment variables in my projects into a CMake cached variable:

cmake_minimum_required(VERSION 2.6)

project(PrintEnv NONE)

if (NOT "$ENV{EnvironmentVariableName}" STREQUAL "")
    set(EnvironmentVariableName "$ENV{EnvironmentVariableName}" CACHE INTERNAL "Copied from environment variable")
endif()

message("EnvironmentVariableName = ${EnvironmentVariableName}")

Reference

Save a file in json format using Notepad++

Just show file name extension from Windows Explorer, after applying the below steps, create a new file, and type your extension as .json

Open Folder Options by clicking the Start button Picture of the Start button, clicking Control Panel, clicking Appearance and Personalization, and then clicking Folder Options.

Click the View tab, and then, under Advanced settings, clear the Hide extensions for known file types check box, and then click OK

Reference

What is the Simplest Way to Reverse an ArrayList?

The trick here is defining "reverse". One can modify the list in place, create a copy in reverse order, or create a view in reversed order.

The simplest way, intuitively speaking, is Collections.reverse:

Collections.reverse(myList);

This method modifies the list in place. That is, Collections.reverse takes the list and overwrites its elements, leaving no unreversed copy behind. This is suitable for some use cases, but not for others; furthermore, it assumes the list is modifiable. If this is acceptable, we're good.


If not, one could create a copy in reverse order:

static <T> List<T> reverse(final List<T> list) {
    final List<T> result = new ArrayList<>(list);
    Collections.reverse(result);
    return result;
}

This approach works, but requires iterating over the list twice. The copy constructor (new ArrayList<>(list)) iterates over the list, and so does Collections.reverse. We can rewrite this method to iterate only once, if we're so inclined:

static <T> List<T> reverse(final List<T> list) {
    final int size = list.size();
    final int last = size - 1;

    // create a new list, with exactly enough initial capacity to hold the (reversed) list
    final List<T> result = new ArrayList<>(size);

    // iterate through the list in reverse order and append to the result
    for (int i = last; i >= 0; --i) {
        final T element = list.get(i);
        result.add(element);
    }

    // result now holds a reversed copy of the original list
    return result;
}

This is more efficient, but also more verbose.

Alternatively, we can rewrite the above to use Java 8's stream API, which some people find more concise and legible than the above:

static <T> List<T> reverse(final List<T> list) {
    final int last = list.size() - 1;
    return IntStream.rangeClosed(0, last) // a stream of all valid indexes into the list
        .map(i -> (last - i))             // reverse order
        .mapToObj(list::get)              // map each index to a list element
        .collect(Collectors.toList());    // wrap them up in a list
}

nb. that Collectors.toList() makes very few guarantees about the result list. If you want to ensure the result comes back as an ArrayList, use Collectors.toCollection(ArrayList::new) instead.


The third option is to create a view in reversed order. This is a more complicated solution, and worthy of further reading/its own question. Guava's Lists#reverse method is a viable starting point.

Choosing a "simplest" implementation is left as an exercise for the reader.

What is IllegalStateException?

public class UserNotFoundException extends Exception {
    public UserNotFoundException(String message) {
        super(message)

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

You're comparing apples to oranges here:

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

  • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

  • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

SQL (MySQL) vs NoSQL (CouchDB)

Here's a quote from a recent blog post from Dare Obasanjo.

SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.

However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.

To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.

Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.

Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)

I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL

How can you float: right in React Native?

You can directly specify the item's alignment, for example:

textright: {    
  alignSelf: 'flex-end',  
},

how to use json file in html code

use jQuery's $.getJSON

$.getJSON('mydata.json', function(data) {
    //do stuff with your data here
});

How do you create a Swift Date object?

According to Apple documentation

Example :

var myObject = NSDate()
let futureDate = myObject.dateByAddingTimeInterval(10)
let timeSinceNow = myObject.timeIntervalSinceNow

What is your single most favorite command-line trick using Bash?

find -iregex '.*\.py$\|.*\.xml$' | xargs egrep -niH 'a.search.pattern'  | vi -R -

Searches a pattern in all Python files and all XML files and pipes the result in a readonly Vim session.

How can I hide or encrypt JavaScript code?

While everyone will generally agree that Javascript encryption is a bad idea, there are a few small use cases where slowing down the attack is better than nothing. You can start with YUI Compressor (as @Ben Alpert) said, or JSMin, Uglify, or many more.

However, the main case in which I want to really 'hide stuff' is when I'm publishing an email address. Note, there is the problem of Chrome when you click on 'inspect element'. It will show your original code: every time. This is why obfuscation is generally regarded as being a better way to go.

On that note, I take a two pronged attack, purely to slow down spam bots. I Obfuscate/minify the js and then run it again through an encoder (again, this second step is completely pointless in chrome).

While not exactly a pure Javascript encoder, the best html encoder I have found is http://hivelogic.com/enkoder/. It will turn this:

<script type="text/javascript">
//<![CDATA[
<!--
var c=function(e) { var m="mail" + "to:webmaster";var a="somedomain"; e.href = m+"@"+a+".com";  
};
//-->
//]]>
</script>
<a href="#" onclick="return c(this);"><img src="images/email.png" /></a>

into this:

<script type="text/javascript">
//<![CDATA[
<!--
var x="function f(x){var i,o=\"\",ol=x.length,l=ol;while(x.charCodeAt(l/13)!" +
"=50){try{x+=x;l+=l;}catch(e){}}for(i=l-1;i>=0;i--){o+=x.charAt(i);}return o" +
".substr(0,ol);}f(\")87,\\\"meozp?410\\\\=220\\\\s-dvwggd130\\\\#-2o,V_PY420" +
"\\\\I\\\\\\\\_V[\\\\\\\\620\\\\o710\\\\RB\\\\\\\\610\\\\JAB620\\\\720\\\\n\\"+
"\\{530\\\\410\\\\WJJU010\\\\|>snnn|j5J(771\\\\p{}saa-.W)+T:``vk\\\"\\\\`<02" +
"0\\\\!610\\\\'Dr\\\\010\\\\630\\\\400\\\\620\\\\700\\\\\\\\\\\\N730\\\\,530" +
"\\\\2S16EF600\\\\;420\\\\9ZNONO1200\\\\/000\\\\`'7400\\\\%n\\\\!010\\\\hpr\\"+
"\\= -cn720\\\\a(ce230\\\\500\\\\f730\\\\i,`200\\\\630\\\\[YIR720\\\\]720\\\\"+
"r\\\\720\\\\h][P]@JHADY310\\\\t230\\\\G500\\\\VBT230\\\\200\\\\Clxhh{tzra/{" +
"g0M0$./Pgche%Z8i#p`v^600\\\\\\\\\\\\R730\\\\Q620\\\\030\\\\730\\\\100\\\\72" +
"0\\\\530\\\\700\\\\720\\\\M410\\\\N730\\\\r\\\\530\\\\400\\\\4420\\\\8OM771" +
"\\\\`4400\\\\$010\\\\t\\\\120\\\\230\\\\r\\\\610\\\\310\\\\530\\\\e~o120\\\\"+
"RfJjn\\\\020\\\\lZ\\\\\\\\CZEWCV771\\\\v5lnqf2R1ox771\\\\p\\\"\\\\tr\\\\220" +
"\\\\310\\\\420\\\\600\\\\OSG300\\\\700\\\\410\\\\320\\\\410\\\\120\\\\620\\" +
"\\q)5<: 0>+\\\"(f};o nruter};))++y(^)i(tAedoCrahc.x(edoCrahCmorf.gnirtS=+o;" +
"721=%y;++y)87<i(fi{)++i;l<i;0=i(rof;htgnel.x=l,\\\"\\\"=o,i rav{)y,x(f noit" +
"cnuf\")"                                                                     ;
while(x=eval(x));
//-->
//]]>
</script>

Maybe it's enough to slow down a few spam bots. I haven't had any spam come through using this (!yet).

Connecting PostgreSQL 9.2.1 with Hibernate

This is a hibernate.cfg.xml for posgresql and it will help you with basic hibernate configurations for posgresql.

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>



        <property name="connection_pool_size">1</property>

        <property name="hbm2ddl.auto">create</property>

        <property name="show_sql">true</property>



       <mapping class="org.javabrains.sanjaya.dto.UserDetails"/>

    </session-factory>
</hibernate-configuration>

Which one is the best PDF-API for PHP?

This is just a quick review of how fPDF stands up against tcPDF in the area of performance at each libraries most basic functions.

SPEED TEST

17.0366 seconds to process 2000 PDF files using fPDF || 79.5982 seconds to process 2000 PDF files using tcPDF

FILE SIZE CHECK (in bytes)

788 fPDF || 1,860 tcPDF

The code used was as identical as possible and renders just a clean PDF file with no text. This is also using the latest version of each library as of June 22, 2011.

Converting std::__cxx11::string to std::string

For me -D_GLIBCXX_USE_CXX11_ABI=0 didn't help.

It works after I linked to C++ libs version instead of gnustl.

How do I check if file exists in jQuery or pure JavaScript?

I was getting a cross domain permissions issue when trying to run the answer to this question so I went with:

function UrlExists(url) {
$('<img src="'+ url +'">').load(function() {
    return true;
}).bind('error', function() {
    return false;
});
}

It seems to work great, hope this helps someone!

Java JRE 64-bit download for Windows?

I believe the link below will always give you the latest version of the 64-bit JRE http://javadl.sun.com/webapps/download/AutoDL?BundleId=43883

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

If you added (or have) a CSS class or id to the parent element, then you can do something like this:

<div id="parent">
  <div>
  </div>
</div>

JavaScript:
document.getElementById("parent").onmouseout = function(e) {
  e = e ? e : window.event //For IE
  if(e.target.id == "parent") {
    //Do your stuff
  }
}

So stuff only gets executed when the event is on the parent div.

Simulate delayed and dropped packets on Linux

netem leverages functionality already built into Linux and userspace utilities to simulate networks. This is actually what Mark's answer refers to, by a different name.

The examples on their homepage already show how you can achieve what you've asked for:

Examples

Emulating wide area network delays

This is the simplest example, it just adds a fixed amount of delay to all packets going out of the local Ethernet.

# tc qdisc add dev eth0 root netem delay 100ms

Now a simple ping test to host on the local network should show an increase of 100 milliseconds. The delay is limited by the clock resolution of the kernel (Hz). On most 2.4 systems, the system clock runs at 100 Hz which allows delays in increments of 10 ms. On 2.6, the value is a configuration parameter from 1000 to 100 Hz.

Later examples just change parameters without reloading the qdisc

Real wide area networks show variability so it is possible to add random variation.

# tc qdisc change dev eth0 root netem delay 100ms 10ms

This causes the added delay to be 100 ± 10 ms. Network delay variation isn't purely random, so to emulate that there is a correlation value as well.

# tc qdisc change dev eth0 root netem delay 100ms 10ms 25%

This causes the added delay to be 100 ± 10 ms with the next random element depending 25% on the last one. This isn't true statistical correlation, but an approximation.

Delay distribution

Typically, the delay in a network is not uniform. It is more common to use a something like a normal distribution to describe the variation in delay. The netem discipline can take a table to specify a non-uniform distribution.

# tc qdisc change dev eth0 root netem delay 100ms 20ms distribution normal

The actual tables (normal, pareto, paretonormal) are generated as part of the iproute2 compilation and placed in /usr/lib/tc; so it is possible with some effort to make your own distribution based on experimental data.

Packet loss

Random packet loss is specified in the 'tc' command in percent. The smallest possible non-zero value is:

2-32 = 0.0000000232%

# tc qdisc change dev eth0 root netem loss 0.1%

This causes 1/10th of a percent (i.e. 1 out of 1000) packets to be randomly dropped.

An optional correlation may also be added. This causes the random number generator to be less random and can be used to emulate packet burst losses.

# tc qdisc change dev eth0 root netem loss 0.3% 25%

This will cause 0.3% of packets to be lost, and each successive probability depends by a quarter on the last one.

Probn = 0.25 × Probn-1 + 0.75 × Random

Note that you should use tc qdisc add if you have no rules for that interface or tc qdisc change if you already have rules for that interface. Attempting to use tc qdisc change on an interface with no rules will give the error RTNETLINK answers: No such file or directory.

How to copy and paste worksheets between Excel workbooks?

You could do something with APIs.

Private Const SW_SHOW = 5
Private Const GW_HWNDNEXT = 2

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long

Private Declare Function ShowWindow Lib "user32" _
(ByVal hWnd As Long, ByVal nCmdShow As Long) As Long

Private Declare Function GetWindow Lib "user32" _
(ByVal hWnd As Long, ByVal wCmd As Long) As Long

Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _
(ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long

Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long

Function FindWindowPartialX(ByVal Title As String) As Long
    Dim hWndThis As Long
    hWndThis = FindWindow(vbNullString, vbNullString)
    While hWndThis
        Dim sTitle As String, sClass As String
        sTitle = Space$(255)
        sTitle = Left$(sTitle, GetWindowText(hWndThis, sTitle, Len(sTitle)))
        sClass = Space$(255)
        sClass = Left$(sClass, GetClassName(hWndThis, sClass, Len(sClass)))
        If InStr(sTitle, Title) > 0 Then
            FindWindowPartialX = hWndThis
            Exit Function
        End If
        hWndThis = GetWindow(hWndThis, GW_HWNDNEXT)
    Wend
End Function

Sub CopySheet()
Dim objXL As Excel.Application

' A suitable portion of the window title such as file name '
WinHandle = FindWindowPartialX("LTD.xls")

ShowWindow WinHandle, SW_SHOW

Set objXL = GetObject(, "Excel.Application")

objXL.Worksheets("Source").Activate
objXL.ActiveSheet.UsedRange.Copy

Application.ActiveSheet.Paste
End Sub

String split on new line, tab and some number of spaces

>>> for line in s.splitlines():
...     line = line.strip()
...     if not line:continue
...     ary.append(line.split(":"))
...
>>> ary
[['Name', ' John Smith'], ['Home', ' Anytown USA'], ['Misc', ' Data with spaces'
]]
>>> dict(ary)
{'Home': ' Anytown USA', 'Misc': ' Data with spaces', 'Name': ' John Smith'}
>>>

Changing Underline color

The easiest way I've tackled this is with CSS:

<style>
.redUnderline {
    color: #ff0000;
    border-bottom: 1px solid #000000;
}
</style>
<span class="redUnderline">$username</span>

Also, for an actual underline, if your item is a link, this works:

<style>
a.blackUnderline {
   color: #000000;
   text-decoration: underline;
}
.red {
    color: #ff0000;
}
</style>
<a href="" class="blackUnderline"><span class="red">$username</span></a>

Gradle DSL method not found: 'runProguard'

Using 'minifyEnabled' instead of 'runProguard' works properly.

Previous code:

buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

Current code:

buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

Hope this helps.

What is a callback function?

Developers are often confused by what a callback is because of the name of the damned thing.

A callback function is a function which is:

  • accessible by another function, and
  • is invoked after the first function if that first function completes

A nice way of imagining how a callback function works is that it is a function that is "called at the back" of the function it is passed into.

Maybe a better name would be a "call after" function.

This construct is very useful for asynchronous behaviour where we want an activity to take place whenever a previous event completes.

Pseudocode:

// A function which accepts another function as an argument
// (and will automatically invoke that function when it completes - note that there is no explicit call to callbackFunction)
funct printANumber(int number, funct callbackFunction) {
    printout("The number you provided is: " + number);
}

// a function which we will use in a driver function as a callback function
funct printFinishMessage() {
    printout("I have finished printing numbers.");
}

// Driver method
funct event() {
   printANumber(6, printFinishMessage);
}

Result if you called event():

The number you provided is: 6
I have finished printing numbers.

The order of the output here is important. Since callback functions are called afterwards, "I have finished printing numbers" is printed last, not first.

Callbacks are so-called due to their usage with pointer languages. If you don't use one of those, don't labour over the name 'callback'. Just understand that it is just a name to describe a method that's supplied as an argument to another method, such that when the parent method is called (whatever condition, such as a button click, a timer tick etc) and its method body completes, the callback function is then invoked.

Some languages support constructs where multiple callback function arguments are supported, and are called based on how the parent function completes (i.e. one callback is called in the event that the parent function completes successfully, another is called in the event that the parent function throws a specific error, etc).

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

For some reason, my terminal's option+arrow weren't working. To fix this on macOS 10.15.6, I opened the terminal app's preferences, and had to set the bindings.

Option-left = \033b
Option-right = \033e

Keyboard settings in Mac terminal app

For some reason, the option-right I had was set up to be \033f. Now that it's fixed, I can freely skip around words in the termianl again.

Load image from resources

ResourceManager will work if your image is in a resource file. If it is just a file in your project (let's say the root) you can get it using something like this:

System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file = assembly .GetManifestResourceStream("AssemblyName." + channel);
this.pictureBox1.Image = Image.FromStream(file);

Or if you're in WPF:

    private ImageSource GetImage(string channel)
    {
        StreamResourceInfo sri = Application.GetResourceStream(new Uri("/TestApp;component/" + channel, UriKind.Relative));
        BitmapImage bmp = new BitmapImage();
        bmp.BeginInit();
        bmp.StreamSource = sri.Stream;
        bmp.EndInit();

        return bmp;
    }

How to set the Android progressbar's height?

From this tutorial:

<style name="CustomProgressBarHorizontal" parent="android:Widget.ProgressBar.Horizontal">
      <item name="android:progressDrawable">@drawable/custom_progress_bar_horizontal</item>
      <item name="android:minHeight">10dip</item>
      <item name="android:maxHeight">20dip</item>
</style>

Then simply apply the style to your progress bars or better, override the default style in your theme to style all of your app's progress bars automatically.

The difference you are seeing in the screenshots is because the phones/emulators are using a difference Android version (latest is the theme from ICS (Holo), top is the original theme).

how to make a full screen div, and prevent size to be changed by content?

Notice how most of these can only be used WITHOUT a DOCTYPE. I'm looking for the same answer, but I have a DOCTYPE. There is one way to do it with a DOCTYPE however, although it doesn't apply to the style of my site, but it will work on the type of page you want to create:

div#full-size{
    position: absolute;
    top:0;
    bottom:0;
    right:0;
    left:0;
    overflow:hidden;

Now, this was mentioned earlier but I just wanted to clarify that this is normally used with a DOCTYPE, height:100%; only works without a DOCTYPE

How can I detect when an Android application is running in the emulator?

Well Android id does not work for me, I'm currently using:

"google_sdk".equals( Build.PRODUCT );

Cutting the videos based on start and end time using ffmpeg

ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 -c copy cut.mp4 

Use -c copy for make in instantly. In that case ffmpeg will not re-encode video, just will cut to according size.

Best way to concatenate List of String objects?

Depending on the need for performance and amount of elements to be added, this might be an ok solution. If the amount of elements are high, the Arraylists reallocation of memory might be a bit slower than StringBuilder.

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

All you need to do is make sure that the checkbox shown below is checked.

enter image description here

Lazy Method for Reading Big File in Python?

you can use following code.

file_obj = open('big_file') 

open() returns a file object

then use os.stat for getting size

file_size = os.stat('big_file').st_size

for i in range( file_size/1024):
    print file_obj.read(1024)

Add class to an element in Angular 4

If you need that each div will have its own toggle and don't want clicks to affect other divs, do this:

Here's what I did to solve this...

<div [ngClass]="{'teaser': !teaser_1 }" (click)="teaser_1=!teaser_1">
...content...
</div>

<div [ngClass]="{'teaser': !teaser_2 }" (click)="teaser_2=!teaser_2">
...content...
</div>

<div [ngClass]="{'teaser': !teaser_3 }" (click)="teaser_3=!teaser_3">
...content...
</div>

it requires custom numbering which sucks, but it works.

Get product id and product type in magento?

This worked for me-

if(Mage::registry('current_product')->getTypeId() == 'simple' ) {

Use getTypeId()

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

setContentView(R.layout.main); error

if you have multiple packages with different classes then it will be confusing: try this:

import package_name_from_AndroidManifest.R;

Get a list of URLs from a site

Write a spider which reads in every html from disk and outputs every "href" attribute of an "a" element (can be done with a parser). Keep in mind which links belong to a certain page (this is common task for a MultiMap datastructre). After this you can produce a mapping file which acts as the input for the 404 handler.

Username and password in command for git push

I used below format

git push https://username:[email protected]/file.git --all

and if your password or username contain @ replace it with %40

2D array values C++

Just want to point out you do not need to specify all dimensions of the array.

The leftmost dimension can be 'guessed' by the compiler.

#include <stdio.h>
int main(void) {
  int arr[][5] = {{1,2,3,4,5}, {5,6,7,8,9}, {6,5,4,3,2}};
  printf("sizeof arr is %d bytes\n", (int)sizeof arr);
  printf("number of elements: %d\n", (int)(sizeof arr/sizeof arr[0]));
  return 0;
}

How do I compile a .c file on my Mac?

Just for the record in modern times,

for 2017 !

1 - Just have updated Xcode on your machine as you normally do

2 - Open terminal and

$ xcode-select --install

it will perform a short install of a minute or two.

3 - Launch Xcode. "New" "Project" ... you have to choose "Command line tool"

Note - confusingly this is under the "macOS" tab.

choose this one

Select "C" language on the next screen...

enter image description here

4- You'll be asked to save the project somewhere on your desktop. The name you give the project here is just the name of the folder that will hold the project. It does not have any importance in the actual software.

5 - You're golden! You can now enjoy c with Mac and Xcode.

you're golden

Opening A Specific File With A Batch File?

If you are trying to open a file in the same directory it would be:

./PROGRAM TRYING TO OPEN
./FILE NAME/PROGRAM TRYING TO OPEN (or this)

Or, if trying to backtrack from the same directory it would be:

../PROGRAM TRYING TO OPEN
../FILE NAME/PROGRAM TRYING TO OPEN (or this)

Else, if you need a straight one from start, it would be:

(DIRECTORY TYPE)\Users\%username%\(FILE DIRECTORY)
(ex) C:\Users\ajste\Desktop\Henlo.cmd

How do I convert an enum to a list in C#?

Language[] result = (Language[])Enum.GetValues(typeof(Language))

ImportError: No module named 'google'

I figured out the solution:

  • I had to delete my anaconda and python installations
  • Re-install Anaconda only
  • Open Anaconda prompt and point it to Anaconda/Scripts
  • Run pip install google
  • Run the sample code now from Spyder.

No more errors.

How to make my layout able to scroll down?

For using scroll view along with Relative layout :

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"> <!--IMPORTANT otherwise backgrnd img. will not fill the whole screen -->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        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:background="@drawable/background_image"
    >

    <!-- Bla Bla Bla i.e. Your Textviews/Buttons etc. -->
    </RelativeLayout>
</ScrollView>

Add marker to Google Map on Click

  1. First declare the marker:
this.marker = new google.maps.Marker({
   position: new google.maps.LatLng(12.924640523603115,77.61965398949724),
   map: map
});
  1. Call the method to plot the marker on click:
this.placeMarker(coordinates, this.map);
  1. Define the function:
placeMarker(location, map) {
    var marker = new google.maps.Marker({
        position: location,
        map: map
    });
    this.markersArray.push(marker);
}

What is the optimal algorithm for the game 2048?

I wrote a 2048 solver in Haskell, mainly because I'm learning this language right now.

My implementation of the game slightly differs from the actual game, in that a new tile is always a '2' (rather than 90% 2 and 10% 4). And that the new tile is not random, but always the first available one from the top left. This variant is also known as Det 2048.

As a consequence, this solver is deterministic.

I used an exhaustive algorithm that favours empty tiles. It performs pretty quickly for depth 1-4, but on depth 5 it gets rather slow at a around 1 second per move.

Below is the code implementing the solving algorithm. The grid is represented as a 16-length array of Integers. And scoring is done simply by counting the number of empty squares.

bestMove :: Int -> [Int] -> Int
bestMove depth grid = maxTuple [ (gridValue depth (takeTurn x grid), x) | x <- [0..3], takeTurn x grid /= [] ]

gridValue :: Int -> [Int] -> Int
gridValue _ [] = -1
gridValue 0 grid = length $ filter (==0) grid  -- <= SCORING
gridValue depth grid = maxInList [ gridValue (depth-1) (takeTurn x grid) | x <- [0..3] ]

I thinks it's quite successful for its simplicity. The result it reaches when starting with an empty grid and solving at depth 5 is:

Move 4006
[2,64,16,4]
[16,4096,128,512]
[2048,64,1024,16]
[2,4,16,2]

Game Over

Source code can be found here: https://github.com/popovitsj/2048-haskell

Converting int to bytes in Python 3

int (including Python2's long) can be converted to bytes using following function:

import codecs

def int2bytes(i):
    hex_value = '{0:x}'.format(i)
    # make length of hex_value a multiple of two
    hex_value = '0' * (len(hex_value) % 2) + hex_value
    return codecs.decode(hex_value, 'hex_codec')

The reverse conversion can be done by another one:

import codecs
import six  # should be installed via 'pip install six'

long = six.integer_types[-1]

def bytes2int(b):
    return long(codecs.encode(b, 'hex_codec'), 16)

Both functions work on both Python2 and Python3.

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

Let's see an example:

int sum = 0;
for(int i = 1; i <= 100 ; i++){
    if(i % 2 == 0)
         continue;
    sum += i;
}

This would get the sum of only odd numbers from 1 to 100.

Handling InterruptedException in Java

I just wanted to add one last option to what most people and articles mention. As mR_fr0g has stated, it's important to handle the interrupt correctly either by:

  • Propagating the InterruptException

  • Restore Interrupt state on Thread

Or additionally:

  • Custom handling of Interrupt

There is nothing wrong with handling the interrupt in a custom way depending on your circumstances. As an interrupt is a request for termination, as opposed to a forceful command, it is perfectly valid to complete additional work to allow the application to handle the request gracefully. For example, if a Thread is Sleeping, waiting on IO or a hardware response, when it receives the Interrupt, then it is perfectly valid to gracefully close any connections before terminating the thread.

I highly recommend understanding the topic, but this article is a good source of information: http://www.ibm.com/developerworks/java/library/j-jtp05236/

Implementing autocomplete

I'd like to add something that no one has yet mentioned: ng2-input-autocomplete

NPM: https://www.npmjs.com/package/ng2-input-autocomplete

GitHub: https://github.com/liuy97/ng2-input-autocomplete#readme

"npm config set registry https://registry.npmjs.org/" is not working in windows bat file

We can also run npm install with registry options for multiple custom registry URLs.

npm install --registry=https://registry.npmjs.org/ 
npm install --registry=https://custom.npm.registry.com/ 

Run Python script at startup in Ubuntu

Put this in /etc/init (Use /etc/systemd in Ubuntu 15.x)

mystartupscript.conf

start on runlevel [2345]
stop on runlevel [!2345]

exec /path/to/script.py

By placing this conf file there you hook into ubuntu's upstart service that runs services on startup.

manual starting/stopping is done with sudo service mystartupscript start and sudo service mystartupscript stop

Call to undefined function curl_init().?

The CURL extension ext/curl is not installed or enabled in your PHP installation. Check the manual for information on how to install or enable CURL on your system.

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

try to reload daemon then restart docker service.

systemctl daemon-reload

foreach vs someList.ForEach(){}

You could name the anonymous delegate :-)

And you can write the second as:

someList.ForEach(s => s.ToUpper())

Which I prefer, and saves a lot of typing.

As Joachim says, parallelism is easier to apply to the second form.

Converting Epoch time into the datetime

To convert your time value (float or int) to a formatted string, use:

time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))

JavaScript seconds to time string with format hh:mm:ss

Here is a fairly simple solution that rounds to the nearest second!

_x000D_
_x000D_
var returnElapsedTime = function(epoch) {_x000D_
  //We are assuming that the epoch is in seconds_x000D_
  var hours = epoch / 3600,_x000D_
      minutes = (hours % 1) * 60,_x000D_
      seconds = (minutes % 1) * 60;_x000D_
  return Math.floor(hours) + ":" + Math.floor(minutes) + ":" + Math.round(seconds);_x000D_
}
_x000D_
_x000D_
_x000D_

How do I update a Linq to SQL dbml file?

To update a table in your .dbml-diagram with, for example, added columns, do this:

  1. Update your SQL Server Explorer window.
  2. Drag the "new" version of your table into the .dbml-diagram (report1 in the picture below).

report1 is the new version of the table

  1. Mark the added columns in the new version of the table, press Ctrl+C to copy the added columns.

copy the added columns

  1. Click the "old" version of your table and press Ctrl+V to paste the added columns into the already present version of the table.

paste the added columns to the old version of the table

How to trigger ngClick programmatically

Include following line in your method there you want to trigger click event

angular.element('#btn_you_want_to_click_progmaticallt').triggerHandler('click');
});

How do I get the path to the current script with Node.js?

I found it after looking through the documentation again. What I was looking for were the __filename and __dirname module-level variables.

  • __filename is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js)
  • __dirname is the directory name of the current module. (ex:/home/kyle/some/dir)

Getting the SQL from a Django QuerySet

Easy:

print my_queryset.query

For example:

from django.contrib.auth.models import User
print User.objects.filter(last_name__icontains = 'ax').query

It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:

from django.db import connections
connections['default'].queries

The django debug toolbar project uses this to present the queries on a page in a neat manner.

How do I send a POST request with PHP?

Based on the main answer, here is what I use:

function do_post($url, $params) {
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => $params
        )
    );
    $result = file_get_contents($url, false, stream_context_create($options));
}

Example usage:

do_post('https://www.google-analytics.com/collect', 'v=1&t=pageview&tid=UA-xxxxxxx-xx&cid=abcdef...');

AVD Manager - No system image installed for this target

you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image

if not installed ARM EABI v7a System Image, you should install all.

How to configure WAMP (localhost) to send email using Gmail?

As an alternative to PHPMailer, Pear's Mail and others you could use the Zend's library

  $config = array('auth' => 'login',
                   'ssl' => 'ssl',
                   'port'=> 465,
                   'username' => '[email protected]',
                   'password' => 'XXXXXXX');

 $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
 $mail = new Zend_Mail();
 $mail->setBodyText('This is the text of the mail.');
 $mail->setFrom('[email protected]', 'Some Sender');
 $mail->addTo('[email protected]', 'Some Recipient');
 $mail->setSubject('TestSubj');
 $mail->send($transport); 

That is my set up in localhost server and I can able to see incoming mail to my mail box.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

To answer your bonus question, the general answer is no, you don't need to set variables to "Nothing" in short .VBS scripts like yours, that get called by Wscript or Cscript.

The reason you might do this in the middle of a longer script is to release memory back to the operating system that VB would otherwise have been holding. These days when 8GB of RAM is typical and 16GB+ relatively common, this is unlikely to produce any measurable impact, even on a huge script that has several megabytes in a single variable. At this point it's kind of a hold-over from the days where you might have been working in 1MB or 2MB of RAM.

You're correct, the moment your .VBS script completes, all of your variables get destroyed and the memory is reclaimed anyway. Setting variables to "Nothing" simply speeds up that process, and allows you to do it in the middle of a script.

How to convert TimeStamp to Date in Java?

Just make a new Date object with the stamp's getTime() value as a parameter.

Here's an example (I use an example timestamp of the current time):

Timestamp stamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(stamp.getTime());
System.out.println(date);

What is MVC and what are the advantages of it?

MVC is the separation of model, view and controller — nothing more, nothing less. It's simply a paradigm; an ideal that you should have in the back of your mind when designing classes. Avoid mixing code from the three categories into one class.

For example, while a table grid view should obviously present data once shown, it should not have code on where to retrieve the data from, or what its native structure (the model) is like. Likewise, while it may have a function to sum up a column, the actual summing is supposed to happen in the controller.

A 'save file' dialog (view) ultimately passes the path, once picked by the user, on to the controller, which then asks the model for the data, and does the actual saving.

This separation of responsibilities allows flexibility down the road. For example, because the view doesn't care about the underlying model, supporting multiple file formats is easier: just add a model subclass for each.

How to show a dialog to confirm that the user wishes to exit an Android Activity?

I'd prefer to exit with double tap on the back button than with an exit Dialog.

In this solution, it show a toast when go back for the first time, warning that another back press will close the App. In this example less than 4 seconds.

private Toast toast;
private long lastBackPressTime = 0;

@Override
public void onBackPressed() {
  if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
    toast = Toast.makeText(this, "Press back again to close this app", 4000);
    toast.show();
    this.lastBackPressTime = System.currentTimeMillis();
  } else {
    if (toast != null) {
    toast.cancel();
  }
  super.onBackPressed();
 }
}

Token from: http://www.androiduipatterns.com/2011/03/back-button-behavior.html

Using "If cell contains" in VBA excel

This will loop through all cells in a given range that you define ("RANGE TO SEARCH") and add dashes at the cell below using the Offset() method. As a best practice in VBA, you should never use the Select method.

Sub AddDashes()

Dim SrchRng As Range, cel As Range

Set SrchRng = Range("RANGE TO SEARCH")

For Each cel In SrchRng
    If InStr(1, cel.Value, "TOTAL") > 0 Then
        cel.Offset(1, 0).Value = "-"
    End If
Next cel

End Sub

Good way to encapsulate Integer.parseInt()

The answer given by Jon Skeet is fine, but I don't like giving back a null Integer object. I find this confusing to use. Since Java 8 there is a better option (in my opinion), using the OptionalInt:

public static OptionalInt tryParse(String value) {
 try {
     return OptionalInt.of(Integer.parseInt(value));
  } catch (NumberFormatException e) {
     return OptionalInt.empty();
  }
}

This makes it explicit that you have to handle the case where no value is available. I would prefer if this kind of function would be added to the java library in the future, but I don't know if that will ever happen.

PostgreSQL delete with inner join

This worked for me:

DELETE from m_productprice
WHERE  m_pricelist_version_id='1000020'
       AND m_product_id IN (SELECT m_product_id
                            FROM   m_product
                            WHERE  upc = '7094'); 

What programming language does facebook use?

The language used by Facebook is PHP.

Also, do any other social networking sites use the same language?

The other one I know of is friendster.

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance(boolean) is useful when you want to have some component which is not tied to Activity lifecycle. This technique is used for example by rxloader to "handle Android's activity lifecyle for rxjava's Observable" (which I've found here).

Get string character by index - Java

The method you're looking for is charAt. Here's an example:

String text = "foo";
char charAtZero = text.charAt(0);
System.out.println(charAtZero); // Prints f

For more information, see the Java documentation on String.charAt. If you want another simple tutorial, this one or this one.

If you don't want the result as a char data type, but rather as a string, you would use the Character.toString method:

String text = "foo";
String letter = Character.toString(text.charAt(0));
System.out.println(letter); // Prints f

If you want more information on the Character class and the toString method, I pulled my info from the documentation on Character.toString.

Getting attributes of a class

I know this was three years ago, but for those who are to come by this question in the future, for me:

class_name.attribute 

works just fine.

What causing this "Invalid length for a Base-64 char array"

Take a look at your HttpHandlers. I've been noticing some weird and completely random errors over the past few months after I implemented a compression tool (RadCompression from Telerik). I was noticing errors like:

  • System.Web.HttpException: Unable to validate data.

  • System.Web.HttpException: The client disconnected.---> System.Web.UI.ViewStateException: Invalid viewstate.

and

  • System.FormatException: Invalid length for a Base-64 char array.

  • System.Web.HttpException: The client disconnected. ---> System.Web.UI.ViewStateException: Invalid viewstate.

I wrote about this on my blog.

How do I link to a library with Code::Blocks?

The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)

To link with gdi32:

enter image description here

This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a has no advantage over gdi32 other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib for MSVC).

For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).

Set value of textarea in jQuery

I think there is missing one important aspect:

$('#some-text-area').val('test');

works only when there is an ID selector (#)

for class selector there is an option to use native value like:

$('.some-text-area')[0].value = 'test';

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

My version of @sampopes answer

function exportToExcel(that, id, hasHeader, removeLinks, removeImages, removeInputParams) {
if (that == null || typeof that === 'undefined') {
    console.log('Sender is required');
    return false;
}

if (!(that instanceof HTMLAnchorElement)) {
    console.log('Sender must be an anchor element');
    return false;
}

if (id == null || typeof id === 'undefined') {
    console.log('Table id is required');
    return false;
}
if (hasHeader == null || typeof hasHeader === 'undefined') {
    hasHeader = true;
}
if (removeLinks == null || typeof removeLinks === 'undefined') {
    removeLinks = true;
}
if (removeImages == null || typeof removeImages === 'undefined') {
    removeImages = false;
}
if (removeInputParams == null || typeof removeInputParams === 'undefined') {
    removeInputParams = true;
}

var tab_text = "<table border='2px'>";
var textRange;

tab = $(id).get(0);

if (tab == null || typeof tab === 'undefined') {
    console.log('Table not found');
    return;
}

var j = 0;

if (hasHeader && tab.rows.length > 0) {
    var row = tab.rows[0];
    tab_text += "<tr bgcolor='#87AFC6'>";
    for (var l = 0; l < row.cells.length; l++) {
        if ($(tab.rows[0].cells[l]).is(':visible')) {//export visible cols only
            tab_text += "<td>" + row.cells[l].innerHTML + "</td>";
        }
    }
    tab_text += "</tr>";
    j++;
}

for (; j < tab.rows.length; j++) {
    var row = tab.rows[j];
    tab_text += "<tr>";
    for (var l = 0; l < row.cells.length; l++) {
        if ($(tab.rows[j].cells[l]).is(':visible')) {//export visible cols only
            tab_text += "<td>" + row.cells[l].innerHTML + "</td>";
        }
    }
    tab_text += "</tr>";
}

tab_text = tab_text + "</table>";
if (removeLinks)
    tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");
if (removeImages)
    tab_text = tab_text.replace(/<img[^>]*>/gi, ""); 
if (removeInputParams)
    tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, "");

var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");

if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
{
    myIframe.document.open("txt/html", "replace");
    myIframe.document.write(tab_text);
    myIframe.document.close();
    myIframe.focus();
    sa = myIframe.document.execCommand("SaveAs", true, document.title + ".xls");
    return true;
}
else {
    //other browser tested on IE 11
    var result = "data:application/vnd.ms-excel," + encodeURIComponent(tab_text);
    that.href = result;
    that.download = document.title + ".xls";
    return true;
}
}

Requires an iframe

<iframe id="myIframe" style="opacity: 0; width: 100%; height: 0px;" seamless="seamless"></iframe>

Usage

$("#btnExportToExcel").click(function () {
    exportToExcel(this, '#mytable');
});

Jquery insert new row into table at a certain index

$('#my_table tbody tr:nth-child(' + i + ')').after(html);

Programmatically set the initial view controller using Storyboards

For all the Swift lovers out there, here is the answer by @Travis translated into SWIFT:

Do what @Travis explained before the Objective C code. Then,

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    var exampleViewController: ExampleViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ExampleController") as! ExampleViewController

    self.window?.rootViewController = exampleViewController

    self.window?.makeKeyAndVisible()

    return true
}

The ExampleViewController would be the new initial view controller you would like to show.

The steps explained:

  1. Create a new window with the size of the current window and set it as our main window
  2. Instantiate a storyboard that we can use to create our new initial view controller
  3. Instantiate our new initial view controller based on it's Storyboard ID
  4. Set our new window's root view controller as our the new controller we just initiated
  5. Make our new window visible

Enjoy and happy programming!

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

The two commands have the same effect (thanks to Robert Siemer’s answer for pointing it out).

The practical difference comes when using a local branch named differently:

  • git checkout -b mybranch origin/abranch will create mybranch and track origin/abranch
  • git checkout --track origin/abranch will only create 'abranch', not a branch with a different name.

(That is, as commented by Sebastian Graf, if the local branch did not exist already.
If it did, you would need git checkout -B abranch origin/abranch)


Note: with Git 2.23 (Q3 2019), that would use the new command git switch:

git switch -c <branch> --track <remote>/<branch>

If the branch exists in multiple remotes and one of them is named by the checkout.defaultRemote configuration variable, we'll use that one for the purposes of disambiguation, even if the <branch> isn't unique across all remotes.
Set it to e.g. checkout.defaultRemote=origin to always checkout remote branches from there if <branch> is ambiguous but exists on the 'origin' remote.

Here, '-c' is the new '-b'.


First, some background: Tracking means that a local branch has its upstream set to a remote branch:

# git config branch.<branch-name>.remote origin
# git config branch.<branch-name>.merge refs/heads/branch

git checkout -b branch origin/branch will:

  • create/reset branch to the point referenced by origin/branch.
  • create the branch branch (with git branch) and track the remote tracking branch origin/branch.

When a local branch is started off a remote-tracking branch, Git sets up the branch (specifically the branch.<name>.remote and branch.<name>.merge configuration entries) so that git pull will appropriately merge from the remote-tracking branch.
This behavior may be changed via the global branch.autosetupmerge configuration flag. That setting can be overridden by using the --track and --no-track options, and changed later using git branch --set-upstream-to.


And git checkout --track origin/branch will do the same as git branch --set-upstream-to):

 # or, since 1.7.0
 git branch --set-upstream upstream/branch branch
 # or, since 1.8.0 (October 2012)
 git branch --set-upstream-to upstream/branch branch
 # the short version remains the same:
 git branch -u upstream/branch branch

It would also set the upstream for 'branch'.

(Note: git1.8.0 will deprecate git branch --set-upstream and replace it with git branch -u|--set-upstream-to: see git1.8.0-rc1 announce)


Having an upstream branch registered for a local branch will:

  • tell git to show the relationship between the two branches in git status and git branch -v.
  • directs git pull without arguments to pull from the upstream when the new branch is checked out.

See "How do you make an existing git branch track a remote branch?" for more.

HowTo Generate List of SQL Server Jobs and their owners

There is an easy way to get Jobs' Owners info from multiple instances by PowerShell:

Run the script in your PowerShell ISE:

Loads SQL Powerhell SMO and commands:

Import-Module SQLPS -disablenamechecking

BUild list of Servers manually (this builds an array list):

$SQLServers = "SERVERNAME\INSTANCE01","SERVERNAME\INSTANCE02","SERVERNAME\INSTANCE03";
$SysAdmins = $null;
foreach($SQLSvr in $SQLServers)
{
    ## - Add Code block:
    $MySQL = new-object Microsoft.SqlServer.Management.Smo.Server $SQLSvr;
    DIR SQLSERVER:\SQL\$SQLSvr\JobServer\Jobs| FT $SQLSvr, NAME, OWNERLOGINNAME -Auto 
    ## - End of Code block
}

Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress

If you have Wordfence plugin installed I found commenting out the suPHP_ConfigPath lines in the .htaccess file brought the website back to life:

# Wordfence WAF
#<IfModule mod_suphp.c>
#   suPHP_ConfigPath '/home/a1614947/public_html'
#</IfModule>

I've reported this to Wordfence too.

How to define partitioning of DataFrame?

Use the DataFrame returned by:

yourDF.orderBy(account)

There is no explicit way to use partitionBy on a DataFrame, only on a PairRDD, but when you sort a DataFrame, it will use that in it's LogicalPlan and that will help when you need to make calculations on each Account.

I just stumbled upon the same exact issue, with a dataframe that I want to partition by account. I assume that when you say "want to have the data partitioned so that all of the transactions for an account are in the same Spark partition", you want it for scale and performance, but your code doesn't depend on it (like using mapPartitions() etc), right?

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)

Or when you deal with text in Python if it is a Unicode text, make a note it is Unicode.

Set text=u'unicode text' instead just text='unicode text'.

This worked in my case.

is it possible to add colors to python output?

IDLE's console does not support ANSI escape sequences, or any other form of escapes for coloring your output.

You can learn how to talk to IDLE's console directly instead of just treating it like normal stdout and printing to it (which is how it does things like color-coding your syntax), but that's pretty complicated. The idle documentation just tells you the basics of using IDLE itself, and its idlelib library has no documentation (well, there is a single line of documentation—"(New in 2.3) Support library for the IDLE development environment."—if you know where to find it, but that isn't very helpful). So, you need to either read the source, or do a whole lot of trial and error, to even get started.


Alternatively, you can run your script from the command line instead of from IDLE, in which case you can use whatever escape sequences your terminal handles. Most modern terminals will handle at least basic 16/8-color ANSI. Many will handle 16/16, or the expanded xterm-256 color sequences, or even full 24-bit colors. (I believe gnome-terminal is the default for Ubuntu, and in its default configuration it will handle xterm-256, but that's really a question for SuperUser or AskUbuntu.)

Learning to read the termcap entries to know which codes to enter is complicated… but if you only care about a single console—or are willing to just assume "almost everything handles basic 16/8-color ANSI, and anything that doesn't, I don't care about", you can ignore that part and just hardcode them based on, e.g., this page.

Once you know what you want to emit, it's just a matter of putting the codes in the strings before printing them.

But there are libraries that can make this all easier for you. One really nice library, which comes built in with Python, is curses. This lets you take over the terminal and do a full-screen GUI, with colors and spinning cursors and anything else you want. It is a little heavy-weight for simple uses, of course. Other libraries can be found by searching PyPI, as usual.

Specifying trust store information in spring boot application.properties

I was also having the same issue with Spring Boot and embedded Tomcat.

From what I understand these properties only set the Tomcat configuration parameters. According to the Tomcat documentation this is only used for Client authentication (i.e. for two-way SSL) and not for verifying remote certificates:

truststoreFile - The trust store file to use to validate client certificates.

https://tomcat.apache.org/tomcat-8.0-doc/config/http.html

In order to configure the trust store for HttpClient it largely depends on the HttpClient implementation you use. For instance for RestTemplate by default Spring Boot uses a SimpleClientHttpRequestFactory based on standard J2SE classes like java.net.HttpURLConnection.

I've come up with a solution based on the Apache HttpClient docs and these posts: http://vincentdevillers.blogspot.pt/2013/02/configure-best-spring-resttemplate.html http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/

Basically this allows for a RestTemplate bean that only trusts certificates signed by the root CA in the configured truststore.

@Configuration
public class RestClientConfig {

    // e.g. Add http.client.ssl.trust-store=classpath:ssl/truststore.jks to application.properties
    @Value("${http.client.ssl.trust-store}")
    private Resource trustStore;

    @Value("${http.client.ssl.trust-store-password}")
    private char[] trustStorePassword;

    @Value("${http.client.maxPoolSize}")
    private Integer maxPoolSize;


    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    @Bean
    public HttpClient httpClient() {

        // Trust own CA and all child certs
        Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
        try {
            SSLContext sslContext = SSLContexts
                    .custom()
                    .loadTrustMaterial(trustStore.getFile(),
                            trustStorePassword)
                    .build();

            // Since only our own certs are trusted, hostname verification is probably safe to bypass
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    new HostnameVerifier() {

                        @Override
                        public boolean verify(final String hostname,
                                final SSLSession session) {
                            return true;
                        }
            });

            socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslSocketFactory)
                    .build();           

        } catch (Exception e) {
            //TODO: handle exceptions
            e.printStackTrace();
        }

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        connectionManager.setMaxTotal(maxPoolSize);
        // This client is for internal connections so only one route is expected
        connectionManager.setDefaultMaxPerRoute(maxPoolSize);
        return HttpClientBuilder.create()
                .setConnectionManager(connectionManager)
                .disableCookieManagement()
                .disableAuthCaching()
                .build();
    }

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(httpRequestFactory());
        return restTemplate;
    }    
}

And then you can use this custom Rest client whenever you need to, e.g.:

@Autowired
private RestTemplate restTemplate;

restTemplate.getForEntity(...)

This assumes your trying to connect to a Rest endpoint, but you can also use the above HttpClient bean for whatever you want.

sklearn plot confusion matrix with labels

You might be interested by https://github.com/pandas-ml/pandas-ml/

which implements a Python Pandas implementation of Confusion Matrix.

Some features:

  • plot confusion matrix
  • plot normalized confusion matrix
  • class statistics
  • overall statistics

Here is an example:

In [1]: from pandas_ml import ConfusionMatrix
In [2]: import matplotlib.pyplot as plt

In [3]: y_test = ['business', 'business', 'business', 'business', 'business',
        'business', 'business', 'business', 'business', 'business',
        'business', 'business', 'business', 'business', 'business',
        'business', 'business', 'business', 'business', 'business']

In [4]: y_pred = ['health', 'business', 'business', 'business', 'business',
       'business', 'health', 'health', 'business', 'business', 'business',
       'business', 'business', 'business', 'business', 'business',
       'health', 'health', 'business', 'health']

In [5]: cm = ConfusionMatrix(y_test, y_pred)

In [6]: cm
Out[6]:
Predicted  business  health  __all__
Actual
business         14       6       20
health            0       0        0
__all__          14       6       20

In [7]: cm.plot()
Out[7]: <matplotlib.axes._subplots.AxesSubplot at 0x1093cf9b0>

In [8]: plt.show()

Plot confusion matrix

In [9]: cm.print_stats()
Confusion Matrix:

Predicted  business  health  __all__
Actual
business         14       6       20
health            0       0        0
__all__          14       6       20


Overall Statistics:

Accuracy: 0.7
95% CI: (0.45721081772371086, 0.88106840959427235)
No Information Rate: ToDo
P-Value [Acc > NIR]: 0.608009812201
Kappa: 0.0
Mcnemar's Test P-Value: ToDo


Class Statistics:

Classes                                 business health
Population                                    20     20
P: Condition positive                         20      0
N: Condition negative                          0     20
Test outcome positive                         14      6
Test outcome negative                          6     14
TP: True Positive                             14      0
TN: True Negative                              0     14
FP: False Positive                             0      6
FN: False Negative                             6      0
TPR: (Sensitivity, hit rate, recall)         0.7    NaN
TNR=SPC: (Specificity)                       NaN    0.7
PPV: Pos Pred Value (Precision)                1      0
NPV: Neg Pred Value                            0      1
FPR: False-out                               NaN    0.3
FDR: False Discovery Rate                      0      1
FNR: Miss Rate                               0.3    NaN
ACC: Accuracy                                0.7    0.7
F1 score                               0.8235294      0
MCC: Matthews correlation coefficient        NaN    NaN
Informedness                                 NaN    NaN
Markedness                                     0      0
Prevalence                                     1      0
LR+: Positive likelihood ratio               NaN    NaN
LR-: Negative likelihood ratio               NaN    NaN
DOR: Diagnostic odds ratio                   NaN    NaN
FOR: False omission rate                       1      0

jQuery add text to span within a div

You can use:

$("#tagscloud span").text("Your text here");

The same code will also work for the second case. You could also use:

$("#tagscloud #WebPartCaptionWPQ2").text("Your text here");

Understanding the main method of python

In Python, execution does NOT have to begin at main. The first line of "executable code" is executed first.

def main():
    print("main code")

def meth1():
    print("meth1")

meth1()
if __name__ == "__main__":main() ## with if

Output -

meth1
main code

More on main() - http://ibiblio.org/g2swap/byteofpython/read/module-name.html

A module's __name__

Every module has a name and statements in a module can find out the name of its module. This is especially handy in one particular situation - As mentioned previously, when a module is imported for the first time, the main block in that module is run. What if we want to run the block only if the program was used by itself and not when it was imported from another module? This can be achieved using the name attribute of the module.

Using a module's __name__

#!/usr/bin/python
# Filename: using_name.py

if __name__ == '__main__':
    print 'This program is being run by itself'
else:
    print 'I am being imported from another module'

Output -

$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>

How It Works -

Every Python module has it's __name__ defined and if this is __main__, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

The last argument of CONVERT seems to determine the format used for parsing. Consult MSDN docs for CONVERT.

111 - the one you are using is Japan yy/mm/dd.

I guess the one you are looking for is 103, that is dd/mm/yyyy.

So you should try:

 SELECT convert(datetime, '23/07/2009', 103)

Progress Bar with HTML and CSS

_x000D_
_x000D_
.loading {_x000D_
  position: relative;_x000D_
  width: 50%;_x000D_
  height: 200px;_x000D_
  border: 1px solid rgba(160, 160, 164, 0.2);_x000D_
  background-color: rgba(160, 160, 164, 0.2);_x000D_
  border-radius: 3px;_x000D_
}_x000D_
_x000D_
span.loader {_x000D_
  position: absolute;_x000D_
  top: 40%;_x000D_
  left: 10%;_x000D_
  width: 250px;_x000D_
  height: 20px;_x000D_
  border-radius: 8px;_x000D_
  border: 2px solid rgba(160, 160, 164, 0.8);_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
span.loader span.innerLoad {_x000D_
  text-align: center;_x000D_
  width: 140px;_x000D_
  font-size: 15px;_x000D_
  font-stretch: extra-expanded;_x000D_
  color: #2A00FF;_x000D_
  padding: 1px 18px 3px 80px;_x000D_
  border-radius: 8px;_x000D_
  background: rgb(250, 198, 149);_x000D_
  background: -moz-linear-gradient(left, rgba(250, 198, 149, 1) 0%, rgba(245, 171, 102, 1) 47%, rgba(239, 141, 49, 1) 100%);_x000D_
  background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(250, 198, 149, 1)), color-stop(47%, rgba(245, 171, 102, 1)), color-stop(100%, rgba(239, 141, 49, 1)));_x000D_
  background: -webkit-linear-gradient(left, rgba(250, 198, 149, 1) 0%, rgba(245, 171, 102, 1) 47%, rgba(239, 141, 49, 1) 100%);_x000D_
  background: -o-linear-gradient(left, rgba(250, 198, 149, 1) 0%, rgba(245, 171, 102, 1) 47%, rgba(239, 141, 49, 1) 100%);_x000D_
  background: -ms-linear-gradient(left, rgba(250, 198, 149, 1) 0%, rgba(245, 171, 102, 1) 47%, rgba(239, 141, 49, 1) 100%);_x000D_
  background: linear-gradient(to right, rgba(250, 198, 149, 1) 0%, rgba(245, 171, 102, 1) 47%, rgba(239, 141, 49, 1) 100%);_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fac695', endColorstr='#ef8d31', GradientType=1);_x000D_
}
_x000D_
<div class="loading">_x000D_
  <span class="loader">_x000D_
      <span class="innerLoad">Loading...</span>_x000D_
  </span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to Right-align flex item?

A more flex approach would be to use an auto left margin (flex items treat auto margins a bit differently than when used in a block formatting context).

.c {
    margin-left: auto;
}

Updated fiddle:

_x000D_
_x000D_
.main { display: flex; }_x000D_
.a, .b, .c { background: #efefef; border: 1px solid #999; }_x000D_
.b { flex: 1; text-align: center; }_x000D_
.c {margin-left: auto;}
_x000D_
<h2>With title</h2>_x000D_
<div class="main">_x000D_
    <div class="a"><a href="#">Home</a></div>_x000D_
    <div class="b"><a href="#">Some title centered</a></div>_x000D_
    <div class="c"><a href="#">Contact</a></div>_x000D_
</div>_x000D_
<h2>Without title</h2>_x000D_
<div class="main">_x000D_
    <div class="a"><a href="#">Home</a></div>_x000D_
    <!--<div class="b"><a href="#">Some title centered</a></div>-->_x000D_
    <div class="c"><a href="#">Contact</a></div>_x000D_
</div>_x000D_
<h1>Problem</h1>_x000D_
<p>Is there a more flexbox-ish way to right align "Contact" than to use position absolute?</p>
_x000D_
_x000D_
_x000D_

How do I parse a string into a number with Dart?

Convert String to Int

var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
print(myInt.runtimeType);

Convert String to Double

var myDouble = double.parse('123.45');
assert(myInt is double);
print(myDouble); // 123.45
print(myDouble.runtimeType);

Example in DartPad

screenshot of dartpad

Return the characters after Nth character in a string

Another formula option is to use REPLACE function to replace the first n characters with nothing, e.g. if n = 4

=REPLACE(A1,1,4,"")

JSON order mixed up

For Java code, Create a POJO class for your object instead of a JSONObject. and use JSONEncapsulator for your POJO class. that way order of elements depends on the order of getter setters in your POJO class. for eg. POJO class will be like

Class myObj{
String userID;
String amount;
String success;
// getter setters in any order that you want

and where you need to send your json object in response

JSONContentEncapsulator<myObj> JSONObject = new JSONEncapsulator<myObj>("myObject");
JSONObject.setObject(myObj);
return Response.status(Status.OK).entity(JSONObject).build();

The response of this line will be

{myObject : {//attributes order same as getter setter order.}}

How can I pass a Bitmap object from one activity to another

Actually, passing a bitmap as a Parcelable will result in a "JAVA BINDER FAILURE" error. Try passing the bitmap as a byte array and building it for display in the next activity.

I shared my solution here:
how do you pass images (bitmaps) between android activities using bundles?

Go / golang time.Now().UnixNano() convert to milliseconds?

Keep it simple.

func NowAsUnixMilli() int64 {
    return time.Now().UnixNano() / 1e6
}

Rewrite all requests to index.php with nginx

Perfect solution I have tried it and succeed to get my index page when I have append this code in my site configuration file.

location / {
            try_files $uri $uri/ /index.php;
}

In configuration file itself explained that at "First attempt to serve request as file, then as directory, then fall back to index.html in my case it is index.php as I am providing page through php code.

How do you style a TextInput in react native for password input

I had to add:

secureTextEntry={true}

Along with

password={true}

As of 0.55

How do I get the total Json record count using JQuery?

If you have something like this:

var json = [ {a:b, c:d}, {e:f, g:h, ...}, {..}, ... ]

then, you can do:

alert(json.length)

Shorthand for if-else statement

Try this method;

Shorthand method:

_x000D_
_x000D_
let variable1 = '';_x000D_
_x000D_
let variable2 = variable1 || 'new'_x000D_
console.log(variable2); // new
_x000D_
_x000D_
_x000D_

Longhand method:

_x000D_
_x000D_
 let variable1 = 'ya';_x000D_
 let varibale2;_x000D_
_x000D_
 if (variable1 !== null || variable1 !== undefined || variable1 !== '')_x000D_
       variable2 = variable1;_x000D_
_x000D_
console.log(variable2); // ya
_x000D_
_x000D_
_x000D_

Get clicked element using jQuery on event?

You are missing the event parameter on your function.

$(document).on("click",".appDetails", function (event) {
    alert(event.target.id);
});

RuntimeError: module compiled against API version a but this version of numpy is 9

I had the same error when trying to launch spyder. "RuntimeError: module compiled against API version 0xb but this version of numpy is 0xa". This error appeared once I modified the numpy version of my machine by mistake (I thought I was in a venv). If your are using spyder installed with conda, my advice is to only use conda to manage package.

This works for me:

conda install anaconda

(I had conda but no anaconda on my machine) then:

conda update numpy

Send private messages to friends

Sending private message through api is now possible.

Fire this event for sending message(initialization of facebook object should be done before).

to:user id of facebook

function facebook_send_message(to) {
    FB.ui({
        app_id:'xxxxxxxx',
        method: 'send',
        name: "sdfds jj jjjsdj j j ",
        link: 'https://apps.facebook.com/xxxxxxxaxsa',
        to:to,
        description:'sdf sdf sfddsfdd s d  fsf s '

    });
}

Properties

  • app_id
    Your application's identifier. Required, but automatically specified by most SDKs.

  • redirect_uri
    The URL to redirect to after the user clicks the Send or Cancel buttons on the dialog. Required, but automatically specified by most SDKs.

  • display
    The display mode in which to render the dialog. This is automatically specified by most SDKs.

  • to
    A user ID or username to which to send the message. Once the dialog comes up, the user can specify additional users, Facebook groups, and email addresses to which to send the message. Sending content to a Facebook group will post it to the group's wall.

  • link
    (required) The link to send in the message.

  • picture
    By default a picture will be taken from the link specified. The URL of a picture to include in the message. The picture will be shown next to the link.

  • name By default a title will be taken from the link specified. The name of the link, i.e. the text to display that the user will click on.

  • description
    By default a description will be taken from the link specified. Descriptive text to show below the link.

See more here

@VishwaKumar:

For sending message with custom text, you have to add 'message' parameter to FB.ui, but I think this feature is deprecated. You can't pre-fill the message anymore. Though try once.

FB.ui({
  method: 'send',
  to: '1234',
  message: 'A request especially for one person.',
  data: 'tracking information for the user'
});

See this link: http://fbdevwiki.com/wiki/FB.ui

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

I am not sure if this is the best way to use GSON, but works for me. You can use some like this on the MainActivity:

 public void readJson() {
    dataArrayList = new ArrayList<>();
    String json = "[\n" + IOHelper.getData(this) + "\n]\n";
    Log.d(TAG, json);
    try{
        JSONArray channelSearchEnums = new JSONArray(json);

        for(int i=0; i< channelSearchEnums.length(); i++)
        {
            JSONObject enum = channelSearchEnums.getJSONObject(i);
            ChannelSearchEnum channel = new ChannelSearchEnum(
                   enum.getString("updated_at"), enum.getString("fetched_at"),
                   enum.getString("description"), enum.getString("language"),
                   enum.getString("title"), enum.getString("url"),
                   enum.getString("icon_url"), enum.getString("logo_url"),
                   enum.getString("id"), enum.getString("modified"))         

                   dataArrayList.add(channel);
        }

         //The code and place you want to show your data            

    }catch (Exception e)
    {
        Log.d(TAG, e.getLocalizedMessage());
    }
}

You only have strings, but if you would have doubles or int, you could put getDouble or getInt too.

The method of IOHelper class is the next (Here, the path is save on the internal Storage):

 public static String getData(Context context) {
    try {
        File f = new File(context.getFilesDir().getPath() + "/" + fileName);
        //check whether file exists
        FileInputStream is = new FileInputStream(f);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        return new String(buffer);
    } catch (IOException e) {
        Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage());
        return null;
    }
}

If you want more information about this, you can see this video, where I get the code of readJson(); and this thread where I get the code of getData().

How to access full source of old commit in BitBucket?

I was trying to figure out if it's possible to browse the code of an earlier commit like you can on GitHub and it brought me here. I used the information I found here, and after fiddling around with the urls, I actually found a way to browse code of old commits as well.

When you're browsing your code the URL is something like:

https://bitbucket.org/user/repo/src/

and by adding a commit hash at the end like this:

https://bitbucket.org/user/repo/src/a0328cb

You can browse the code at the point of that commit. I don't understand why there's no dropdown box for choosing a commit directly, the feature is already there. Strange.

How to suspend/resume a process in Windows?

I use (a very old) process explorer from SysInternals (procexp.exe). It is a replacement / addition to the standard Task manager, you can suspend a process from there.

Edit: Microsoft has bought over SysInternals, url: procExp.exe

Other than that you can set the process priority to low so that it does not get in the way of other processes, but this will not suspend the process.

Can not find module “@angular-devkit/build-angular”

From angular 6 you can run the command below to fix that issue

npm install --save-dev @angular-devkit/build-angular

OR

yarn add @angular-devkit/build-angular --dev 

If your you still can not resolve issues, you can see other option from an unhandled exception occurred: cannot find module '@angular-devkit/build-angular/package.json'

A simple algorithm for polygon intersection

If you do not care about predictable run time you could try by first splitting your polygons into unions of convex polygons and then pairwise computing the intersection between the sub-polygons.

This would give you a collection of convex polygons such that their union is exactly the intersection of your starting polygons.

Casting string to enum

As an extra, you can take the Enum.Parse answers already provided and put them in an easy-to-use static method in a helper class.

public static T ParseEnum<T>(string value)
{
    return (T)Enum.Parse(typeof(T), value, ignoreCase: true);
}

And use it like so:

{
   Content = ParseEnum<ContentEnum>(fileContentMessage);
};

Especially helpful if you have lots of (different) Enums to parse.

How to window.scrollTo() with a smooth effect

$('html, body').animate({scrollTop:1200},'50');

You can do this!

How to change button text or link text in JavaScript?

You can simply use:

document.getElementById(button_id).innerText = 'Your text here';

If you want to use HTML formatting, use the innerHTML property instead.

strdup() - what does it do in C?

Exactly what it sounds like, assuming you're used to the abbreviated way in which C and UNIX assigns words, it duplicates strings :-)

Keeping in mind it's actually not part of the ISO C standard itself(a) (it's a POSIX thing), it's effectively doing the same as the following code:

char *strdup(const char *src) {
    char *dst = malloc(strlen (src) + 1);  // Space for length plus nul
    if (dst == NULL) return NULL;          // No memory
    strcpy(dst, src);                      // Copy the characters
    return dst;                            // Return the new string
}

In other words:

  1. It tries to allocate enough memory to hold the old string (plus a '\0' character to mark the end of the string).

  2. If the allocation failed, it sets errno to ENOMEM and returns NULL immediately. Setting of errno to ENOMEM is something malloc does in POSIX so we don't need to explicitly do it in our strdup. If you're not POSIX compliant, ISO C doesn't actually mandate the existence of ENOMEM so I haven't included that here(b).

  3. Otherwise the allocation worked so we copy the old string to the new string(c) and return the new address (which the caller is responsible for freeing at some point).

Keep in mind that's the conceptual definition. Any library writer worth their salary may have provided heavily optimised code targeting the particular processor being used.


(a) However, functions starting with str and a lower case letter are reserved by the standard for future directions. From C11 7.1.3 Reserved identifiers:

Each header declares or defines all identifiers listed in its associated sub-clause, and *optionally declares or defines identifiers listed in its associated future library directions sub-clause.**

The future directions for string.h can be found in C11 7.31.13 String handling <string.h>:

Function names that begin with str, mem, or wcs and a lowercase letter may be added to the declarations in the <string.h> header.

So you should probably call it something else if you want to be safe.


(b) The change would basically be replacing if (d == NULL) return NULL; with:

if (d == NULL) {
    errno = ENOMEM;
    return NULL;
}

(c) Note that I use strcpy for that since that clearly shows the intent. In some implementations, it may be faster (since you already know the length) to use memcpy, as they may allow for transferring the data in larger chunks, or in parallel. Or it may not :-) Optimisation mantra #1: "measure, don't guess".

In any case, should you decide to go that route, you would do something like:

char *strdup(const char *src) {
    size_t len = strlen(src) + 1;       // String plus '\0'
    char *dst = malloc(len);            // Allocate space
    if (dst == NULL) return NULL;       // No memory
    memcpy (dst, src, len);             // Copy the block
    return dst;                         // Return the new string
}

How do I extract Month and Year in a MySQL date and compare them?

While it was discussed in the comments, there isn't an answer containing it yet, so it can be easy to miss. DATE_FORMAT works really well and is flexible to handle many different patterns.

DATE_FORMAT(date,'%Y%m')

To put it in a query:

SELECT DATE_FORMAT(test_date,'%Y%m') AS date FROM test_table;

How do I find out if the GPS of an Android device is enabled

Yes you can check below is the code:

public boolean isGPSEnabled (Context mContext){
    LocationManager locationManager = (LocationManager)
                mContext.getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

How can I create Min stl priority_queue?

We can do this using several ways.

Using template comparator parameter

    int main() 
    {
      priority_queue<int, vector<int>, greater<int> > pq;

      pq.push(40);
      pq.push(320);
      pq.push(42);
      pq.push(65);
      pq.push(12);

      cout<<pq.top()<<endl;
      return 0;
    }

Using used defined compartor class

     struct comp
     {
        bool operator () (int lhs, int rhs)
        {
           return lhs > rhs;
        }
     };

    int main()
    {
       priority_queue<int, vector<int>, comp> pq;

       pq.push(40);
       pq.push(320);
       pq.push(42);
       pq.push(65);
       pq.push(12);

       cout<<pq.top()<<endl;

       return 0;
    }

How to remove class from all elements jquery

try: $(".highlight").removeClass("highlight");. By selecting $(".edgetoedge") you are only running functions at that level.

How to Git stash pop specific stash in 1.8.3?

First check the list:-

git stash list

copy the index you wanted to pop from the stash list

git stash pop stash@{index_number}

eg.:

git stash pop stash@{1}

html form - make inputs appear on the same line

Try just putting a div around the first and last name inputs/labels like this:

<div class="name">
        <label for="First_Name">First Name:</label>
        <input name="first_name" id="First_Name" type="text" />

        <label for="Name">Last Name:</label>
        <input name="last_name" id="Last_Name" type="text" /> 
</div>

Look at the fiddle here: http://jsfiddle.net/XAkXg/

How to get Chrome to allow mixed content?

Steps as of Chrome v79 (2/24/2020):

  1. Click the (i) button next to the URL

enter image description here

  1. Click Site settings on the popup box

enter image description here

  1. At the bottom of the list is "Insecure content", change this to Allow

enter image description here

  1. Go back to the site and Refresh the page

Older Chrome Versions:

timmmy_42 answers this on: https://productforums.google.com/forum/#!topic/chrome/OrwppKWbKnc

In the address bar at the right end should be a 'shield' icon, you can click on that to run insecure content.

This worked for me in Chromium-dev Version 36.0.1933.0 (262849).

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Q:Can't bind to 'pSelectableRow' since it isn't a known property of 'tr'.

A:you need to configure the primeng tabulemodule in ngmodule

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

For Centos I was missing php-mysql library:

yum install php-mysql

service httpd restart

There is no need to enable any extension in php.ini, it is loaded by default.

Deep copy in ES6 using the spread syntax

const a = {
  foods: {
    dinner: 'Pasta'
  }
}
let b = JSON.parse(JSON.stringify(a))
b.foods.dinner = 'Soup'
console.log(b.foods.dinner) // Soup
console.log(a.foods.dinner) // Pasta

Using JSON.stringify and JSON.parse is the best way. Because by using the spread operator we will not get the efficient answer when the json object contains another object inside it. we need to manually specify that.

Read each line of txt file to new array element

$lines = array();
while (($line = fgets($file)) !== false)
    array_push($lines, $line);

Obviously, you'll need to create a file handle first and store it in $file.

How do I reflect over the members of dynamic object?

If the IDynamicMetaObjectProvider can provide the dynamic member names, you can get them. See GetMemberNames implementation in the apache licensed PCL library Dynamitey (which can be found in nuget), it works for ExpandoObjects and DynamicObjects that implement GetDynamicMemberNames and any other IDynamicMetaObjectProvider who provides a meta object with an implementation of GetDynamicMemberNames without custom testing beyond is IDynamicMetaObjectProvider.

After getting the member names it's a little more work to get the value the right way, but Impromptu does this but it's harder to point to just the interesting bits and have it make sense. Here's the documentation and it is equal or faster than reflection, however, unlikely to be faster than a dictionary lookup for expando, but it works for any object, expando, dynamic or original - you name it.

Call asynchronous method in constructor?

Brian Lagunas has shown a solution that I really like. More info his youtube video

Solution:

Add a TaskExtensions method

  public static class TaskExtensions
{
    public static async void Await(this Task task, Action completedCallback = null ,Action<Exception> errorCallBack = null )
    {
        try
        {
            await task;
            completedCallback?.Invoke();
        }
        catch (Exception e)
        {
            errorCallBack?.Invoke(e);
        }
    }
}

Usage:

  public class MyClass
{

    public MyClass()
    {
        DoSomething().Await();
       // DoSomething().Await(Completed, HandleError);
    }

    async Task DoSomething()
    {
        await Task.Delay(3000);
        //Some works here
        //throw new Exception("Thrown in task");
    }

    private void Completed()
    {
        //some thing;
    }

    private void HandleError(Exception ex)
    {
        //handle error
    }

}

How to add a Java Properties file to my Java Project in Eclipse

steps:

  1. Right click on any package where you want to create your .properties file or create a new package as required
  2. now select new then select file (if you dont find file then go to location of your package and create it there)
  3. now named it as yourfilename.properties

how to specify local modules as npm package dependencies

I couldn't find a neat way in the end so I went for create a directory called local_modules and then added this bashscript to the package.json in scripts->preinstall

#!/bin/sh
for i in $(find ./local_modules -type d -maxdepth 1) ; do
    packageJson="${i}/package.json"
    if [ -f "${packageJson}" ]; then
        echo "installing ${i}..."
        npm install "${i}"
    fi
done

Error 'tunneling socket' while executing npm install

I had this same error when trying to install Cypress via npm. I tried many of the above solutions as I am behind a proxy, but was still seeing the same error. In the end I found that my WIndows system configuration(can be checked by entering 'set' in command prompt) had HTTP and HTTPS proxys set that differed from the ones vonfigure in npm. I deleted these proxys and it downloaded staright away.

Regex to match 2 digits, optional decimal, two digits

A previous answer is mostly correct, but it will also match the empty string. The following would solve this.

^([0-9]?[0-9](\.[0-9][0-9]?)?)|([0-9]?[0-9]?(\.[0-9][0-9]?))$

Using request.setAttribute in a JSP page

The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.

Checking if a string is empty or null in Java

You can use Apache commons-lang

StringUtils.isEmpty(String str) - Checks if a String is empty ("") or null.

or

StringUtils.isBlank(String str) - Checks if a String is whitespace, empty ("") or null.

the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API

How to list only files and not directories of a directory Bash?

Listing content of some directory, without subdirectories

I like using ls options, for sample:

  • -l use a long listing format
  • -t sort by modification time, newest first
  • -r reverse order while sorting
  • -F, --classify append indicator (one of */=>@|) to entries
  • -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc...

Sometime --color and all others. (See ls --help)

Listing everything but folders

This will show files, symlinks, devices, pipe, sockets etc.

so

find /some/path -maxdepth 1 ! -type d

could be sorted by date easily:

find /some/path -maxdepth 1 ! -type d -exec ls -hltrF {} +

Listing files only:

or

find /some/path -maxdepth 1 -type f

sorted by size:

find /some/path -maxdepth 1 -type f -exec ls -lSF --color {} +

Prevent listing of hidden entries:

To not show hidden entries, where name begin by a dot, you could add ! -name '.*':

find /some/path -maxdepth 1 ! -type d ! -name '.*' -exec ls -hltrF {} +

Then

You could replace /some/path by . to list for current directory or .. for parent directory.

How to get the user input in Java?

You can make a simple program to ask for user's name and print what ever the reply use inputs.

Or ask user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like a behavior of a calculator.

So there you need Scanner class. You have to import java.util.Scanner; and in the code you need to use

Scanner input = new Scanner(System.in);

Input is a variable name.

Scanner input = new Scanner(System.in);

System.out.println("Please enter your name : ");
s = input.next(); // getting a String value

System.out.println("Please enter your age : ");
i = input.nextInt(); // getting an integer

System.out.println("Please enter your salary : ");
d = input.nextDouble(); // getting a double

See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();

According to a String, int and a double varies same way for the rest. Don't forget the import statement at the top of your code.

Also see the blog post "Scanner class and getting User Inputs".