Programs & Examples On #Nonblank

count (non-blank) lines-of-code in bash

It's kinda going to depend on the number of files you have in the project. In theory you could use

grep -c '.' <list of files>

Where you can fill the list of files by using the find utility.

grep -c '.' `find -type f`

Would give you a line count per file.

Powershell get ipv4 address into a variable

Another variant using $env environment variable to grab hostname:

Test-Connection -ComputerName $env:computername -count 1 | Select-Object IPV4Address

or if you just want the IP address returned without the property header

(Test-Connection -ComputerName $env:computername -count 1).IPV4Address.ipaddressTOstring

Last non-empty cell in a column

I think the response from W5ALIVE is closest to what I use to find the last row of data in a column. Assuming I am looking for the last row with data in Column A, though, I would use the following for the more generic lookup:

=MAX(IFERROR(MATCH("*",A:A,-1),0),IFERROR(MATCH(9.99999999999999E+307,A:A,1),0))

The first MATCH will find the last text cell and the second MATCH finds the last numeric cell. The IFERROR function returns zero if the first MATCH finds all numeric cells or if the second match finds all text cells.

Basically this is a slight variation of W5ALIVE's mixed text and number solution.

In testing the timing, this was significantly quicker than the equivalent LOOKUP variations.

To return the actual value of that last cell, I prefer to use indirect cell referencing like this:

=INDIRECT("A"&MAX(IFERROR(MATCH("*",A:A,-1),0),IFERROR(MATCH(9.99999999999999E+307,A:A,1),0)))

The method offered by sancho.s is perhaps a cleaner option, but I would modify the portion that finds the row number to this:

=INDEX(MAX((A:A<>"")*(ROW(A:A))),1)

the only difference being that the ",1" returns the first value while the ",0" returns the entire array of values (all but one of which are not needed). I still tend to prefer addressing the cell to the index function there, in other words, returning the cell value with:

=INDIRECT("A"&INDEX(MAX((A:A<>"")*(ROW(A:A))),1))

Great thread!

How do I fit an image (img) inside a div and keep the aspect ratio?

Using CSS only:

div > img {
  width: auto;
  height : auto;
  max-height: 100%;
  max-width: 100%;
}

Cannot read property 'map' of undefined

First of all, set more safe initial data:

getInitialState : function() {
    return {data: {comments:[]}};
},

And ensure your ajax data.

It should work if you follow above two instructions like Demo.

Updated: you can just wrap the .map block with conditional statement.

if (this.props.data) {
  var commentNodes = this.props.data.map(function (comment){
      return (
        <div>
          <h1>{comment.author}</h1>
        </div>
      );
  });
}

How to set session timeout in web.config

If you are using MVC, you put this in the web.config file in the Root directory of the web application, not the web.config in the Views directory. It also needs to be IN the system.web node, not under like George2 stated in his question: "I wrote under system.web section in the web.config"

The timeout parameter value represents minutes.

There are other attributes that can be set in the sessionState element. You can find information here: docs.microsoft.com sessionState

<configuration>
   <system.web>
      <sessionState timeout="20"></sessionState>
   </system.web>
</configuration>

You can then catch the begining of a new session in the Global.asax file by adding the following method:

void Session_Start(object sender, EventArgs e)
{
    if (Session.IsNewSession)
    {
        //do things that need to happen
        //when a new session starts.
    }
}

Configure active profile in SpringBoot via Maven

You can run using the following command. Here I want to run using spring profile local:

spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=local"

How to put space character into a string name in XML?

You want to it display like "-4, 5, -5, 6, -6," (two spaces),you can add the following code to string.xml

<string name="spelatonertext3"> "-4,&#160;&#160;5,&#160;-5,&#160;&#160;6,&#160;&#160;-6,"</string>

  is display one space.

CSS display:inline property with list-style-image: property on <li> tags

You want the list items to line up next to each other, but not really be inline elements. So float them instead:

ol.widgets li { 
    float: left;
    margin-left: 10px;
}

How do I make a self extract and running installer

Okay I have got it working, hope this information is useful.

  1. First of all I now realize that not only do self-extracting zip start extracting with doubleclick, but they require no extraction application to be installed on the users computer because the extractor code is in the archive itself. This means that you will get a different user experience depending on what you application you use to create the sfx

  2. I went with WinRar as follows, this does not require you to create an sfx file, everything can be created via the gui:

    • Select files, right click and select Add to Archive
    • Use Browse.. to create the archive in the folder above
    • Change Archive Format to Zip
    • Enable Create SFX archive
    • Select Advanced tab
    • Select SFX Options
    • Select Setup tab
    • Enter setup.exe into the Run after Extraction field
    • Select Modes tab
    • Enable Unpack to temporary folder
    • Select text and Icon tab
    • Enter a more appropriate title for your task
    • Select OK
    • Select OK

The resultant exe unzips to a temporary folder and then starts the installer

When should I use Memcache instead of Memcached?

Memcached client library was just recently released as stable. It is being used by digg ( was developed for digg by Andrei Zmievski, now no longer with digg) and implements much more of the memcached protocol than the older memcache client. The most important features that memcached has are:

  1. Cas tokens. This made my life much easier and is an easy preventive system for stale data. Whenever you pull something from the cache, you can receive with it a cas token (a double number). You can than use that token to save your updated object. If no one else updated the value while your thread was running, the swap will succeed. Otherwise a newer cas token was created and you are forced to reload the data and save it again with the new token.
  2. Read through callbacks are the best thing since sliced bread. It has simplified much of my code.
  3. getDelayed() is a nice feature that can reduce the time your script has to wait for the results to come back from the server.
  4. While the memcached server is supposed to be very stable, it is not the fastest. You can use binary protocol instead of ASCII with the newer client.
  5. Whenever you save complex data into memcached the client used to always do serialization of the value (which is slow), but now with memcached client you have the option of using igbinary. So far I haven't had the chance to test how much of a performance gain this can be.

All of this points were enough for me to switch to the newest client, and can tell you that it works like a charm. There is that external dependency on the libmemcached library, but have managed to install it nonetheless on Ubuntu and Mac OSX, so no problems there so far.

If you decide to update to the newer library, I suggest you update to the latest server version as well as it has some nice features as well. You will need to install libevent for it to compile, but on Ubuntu it wasn't much trouble.

I haven't seen any frameworks pick up the new memcached client thus far (although I don't keep track of them), but I presume Zend will get on board shortly.

UPDATE

Zend Framework 2 has an adapter for Memcached which can be found here

How to change the Title of the window in Qt?

void    QWidget::setWindowTitle ( const QString & )

EDIT: If you are using QtDesigner, on the property tab, there is an editable property called windowTitle which can be found under the QWidget section. The property tab can usually be found on the lower right part of the designer window.

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

First, you need to add HttpHeaders with HttpClient

import { HttpClient,HttpHeaders  } from '@angular/common/http';

your constructor should be like this.

constructor(private http: HttpClient) { }

then you can use like this

   let header = new HttpHeaders({ "Authorization": "Bearer "+token});

   const requestOptions = {  headers: header};                                                                                                                                                                            

    return this.http.get<any>(url, requestOptions)
        .toPromise()
        .then(data=> {
            //...
            return data;
    });

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

I've faced this error, That was because the value you want to filter in the _id field is not in an ID format, one "if" should solve your error.

const mongoose = require('mongoose');

console.log(mongoose.Types.ObjectId.isValid('53cb6b9b4f4ddef1ad47f943'));
// true
console.log(mongoose.Types.ObjectId.isValid('whatever'));
// false

To solve it, always validate if the criteria value for search is a valid ObjectId

const criteria = {};
criteria.$or = [];

if(params.q) {
  if(mongoose.Types.ObjectId.isValid(params.id)) {
    criteria.$or.push({ _id: params.q })
  }
  criteria.$or.push({ name: { $regex: params.q, $options: 'i' }})
  criteria.$or.push({ email: { $regex: params.q, $options: 'i' }})
  criteria.$or.push({ password: { $regex: params.q, $options: 'i' }})
}

return UserModule.find(criteria).exec(() => {
  // do stuff
})

When restoring a backup, how do I disconnect all active connections?

I prefer to do like this,

alter database set offline with rollback immediate

and then restore your database. after that,

alter database set online with rollback immediate

How do I get video durations with YouTube API version 3?

You will have to make a call to the YouTube data API's video resource after you make the search call. You can put up to 50 video IDs in a search, so you won't have to call it for each element.

https://developers.google.com/youtube/v3/docs/videos/list

You'll want to set part=contentDetails, because the duration is there.

For example, the following call:

https://www.googleapis.com/youtube/v3/videos?id=9bZkp7q19f0&part=contentDetails&key={YOUR_API_KEY}

Gives this result:

{
 "kind": "youtube#videoListResponse",
 "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/ny1S4th-ku477VARrY_U4tIqcTw\"",
 "items": [
  {

   "id": "9bZkp7q19f0",
   "kind": "youtube#video",
   "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/HN8ILnw-DBXyCcTsc7JG0z51BGg\"",
   "contentDetails": {
    "duration": "PT4M13S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "false",
    "licensedContent": true,
    "regionRestriction": {
     "blocked": [
      "DE"
     ]
    }
   }
  }
 ]
}

The time is formatted as an ISO 8601 string. PT stands for Time Duration, 4M is 4 minutes, and 13S is 13 seconds.

How to check if AlarmManager already has an alarm set?

    Intent intent = new Intent("com.my.package.MY_UNIQUE_ACTION");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                    sqlitewraper.context, 0, intent,
                    PendingIntent.FLAG_NO_CREATE);

FLAG_NO_CREATE is not create pending intent so that it gives boolean value false.

            boolean alarmUp = (PendingIntent.getBroadcast(sqlitewraper.context, 0,
                    new Intent("com.my.package.MY_UNIQUE_ACTION"),
                    PendingIntent.FLAG_NO_CREATE) != null);

            if (alarmUp) {
                System.out.print("k");

            }

            AlarmManager alarmManager = (AlarmManager) sqlitewraper.context
                    .getSystemService(Context.ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis(), 1000 * 60, pendingIntent);

After the AlarmManager check the value of Pending Intent it gives true because AlarmManager Update The Flag of Pending Intent.

            boolean alarmUp1 = (PendingIntent.getBroadcast(sqlitewraper.context, 0,
                    new Intent("com.my.package.MY_UNIQUE_ACTION"),
                    PendingIntent.FLAG_UPDATE_CURRENT) != null);
            if (alarmUp1) {
                System.out.print("k");

            }

Import data into Google Colaboratory

On the left bar of any colaboratory there is a section called "Files". Upload your files there and use this path

"/content/YourFileName.extension"

ex: pd.read_csv('/content/Forbes2015.csv');

How to determine tables size in Oracle

Here is a query, you can run it in SQL Developer (or SQL*Plus):

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
  FROM DBA_SEGMENTS DS
  WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
 GROUP BY DS.TABLESPACE_NAME,
       SEGMENT_NAME;

How do I delete files programmatically on Android?

File file=new File(getFilePath(imageUri.getValue()));
boolean b= file.delete();

not working in my case. The issue has been resolved by using below code-

ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );

"query function not defined for Select2 undefined error"

I also had this problem make sure that you don't initialize the select2 twice.

How to see my Eclipse version?

Go to Help -> About Eclipse Sdk

enter image description here

enter image description here

Oracle Error ORA-06512

I also had the same error. In my case reason was I have created a update trigger on a table and under that trigger I am again updating the same table. And when I have removed the update statement from the trigger my problem has been resolved.

How do I find a default constraint using INFORMATION_SCHEMA?

Is the COLUMN_DEFAULT column of INFORMATION_SCHEMA.COLUMNS what you are looking for?

Bash script plugin for Eclipse?

It works for me in Oxygen.

1) Go to Help > Eclipse Marketplace... and search for "DLTK". You'll find something like "Shell Script (DLTK) 5.8.0". Install it and reboot Eclipse.

(Or drag'n'drop "Install" button from this web page to your Eclipse: https://marketplace.eclipse.org/content/shell-script-dltk)

Shell Script (DLTK)

2) Right-click on the shell/batch file in Project Explorer > Open With > Other... and select Shell Script Editor. You can also associate the editor with all files of that extension.

Shell script editor

html button to send email

You can use an anchor to attempt to open the user's default mail client, prepopulated, with mailto:, but you cannot send the actual email. *Apparently it is possible to do this with a form action as well, but browser support is varied and unreliable, so I do not suggest it.

HTML cannot send mail, you need to use a server side language like php, which is another topic. There are plently of good resources on how to do this here on SO or elsewhere on the internet.

If you are using php, I see SwiftMailer suggested quite a bit.

what's the differences between r and rb in fopen

use "rb" to open a binary file. Then the bytes of the file won't be encoded when you read them

How to get rid of the "No bootable medium found!" error in Virtual Box?

The CD / DVD wanted to be on the IDE controller on my system, not the SATA controller

How to encode the plus (+) symbol in a URL

The + character has a special meaning in a URL => it means whitespace - . If you want to use the literal + sign, you need to URL encode it to %2b:

body=Hi+there%2bHello+there

Here's an example of how you could properly generate URLs in .NET:

var uriBuilder = new UriBuilder("https://mail.google.com/mail");

var values = HttpUtility.ParseQueryString(string.Empty);
values["view"] = "cm";
values["tf"] = "0";
values["to"] = "[email protected]";
values["su"] = "some subject";
values["body"] = "Hi there+Hello there";

uriBuilder.Query = values.ToString();

Console.WriteLine(uriBuilder.ToString());

The result

https://mail.google.com:443/mail?view=cm&tf=0&to=someemail%40somedomain.com&su=some+subject&body=Hi+there%2bHello+there

Cron job every three days

* * */3 * *  that says, every minute of every hour on every three days. 

0 0 */3 * *  says at 00:00 (midnight) every three days.

Installing Node.js (and npm) on Windows 10

Edit: It seems like new installers do not have this problem anymore, see this answer by Parag Meshram as my answer is likely obsolete now.

Original answer:

Follow these steps, closely:

  • http://nodejs.org/download/ download the 64 bits version, 32 is for hipsters
  • Install it anywhere you want, by default: C:\Program Files\nodejs
  • Control Panel -> System -> Advanced system settings -> Environment Variables
  • Select PATH and choose to edit it.

If the PATH variable is empty, change it to this: C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm;C:\Program Files\nodejs

If the PATH variable already contains C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm, append the following right after: ;C:\Program Files\nodejs

If the PATH variable contains information, but nothing regarding npm, append this to the end of the PATH: ;C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm;C:\Program Files\nodejs

Now that the PATH variable is set correctly, you will still encounter errors. Manually go into the AppData directory and you will find that there is no npm directory inside Roaming. Manually create this directory.

Re-start the command prompt and npm will now work.

Fastest method to replace all instances of a character in a string

Also you can try:

string.split('foo').join('bar');

Merge or combine by rownames

Using merge and renaming your t vector as tt (see the PS of Andrie) :

merge(tt,z,by="row.names",all.x=TRUE)[,-(5:8)]

Now if you would work with dataframes instead of matrices, this would even become a whole lot easier :

z <- as.data.frame(z)
tt <- as.data.frame(tt)
merge(tt,z["symbol"],by="row.names",all.x=TRUE)

SQLRecoverableException: I/O Exception: Connection reset

This simply means that something in the backend ( DBMS ) decided to stop working due to unavailability of resources etc. It has nothing to do with your code or the number of inserts. You can read more about similar problems here:

This may not answer your question, but you will get an idea of why it might be happening. You could further discuss with your DBA and see if there is something specific in your case.

How to give the background-image path in CSS?

You need to get 2 folders back from your css file.

Try:

background-image: url("../../images/image.png");

Difference between using Makefile and CMake to compile the code

Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.

CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.

If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.

I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.

Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?

Change GitHub Account username

Yes, it's possible. But first read, "What happens when I change my username?"

To change your username, click your profile picture in the top right corner, then click Settings. On the left side, click Account. Then click Change username.

Can HTML checkboxes be set to readonly?

@(Model.IsEnabled) Use this condition for dynamically check and uncheck and set readonly if check box is already checked.

 <input id="abc" name="abc"  type="checkbox" @(Model.IsEnabled ? "checked=checked onclick=this.checked=!this.checked;" : string.Empty) >

How to define constants in ReactJS

You can also do,

getDefaultProps: ->
  firstName: 'Rails'
  lastName: 'React'

now access, those constant (default value) using

@props.firstName

@props.lastName

Hope this help!!!.

Find the item with maximum occurrences in a list

I am surprised no-one has mentioned the simplest solution,max() with the key list.count:

max(lst,key=lst.count)

Example:

>>> lst = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
>>> max(lst,key=lst.count)
4

This works in Python 3 or 2, but note that it only returns the most frequent item and not also the frequency. Also, in the case of a draw (i.e. joint most frequent item) only a single item is returned.

Although the time complexity of using max() is worse than using Counter.most_common(1) as PM 2Ring comments, the approach benefits from a rapid C implementation and I find this approach is fastest for short lists but slower for larger ones (Python 3.6 timings shown in IPython 5.3):

In [1]: from collections import Counter
   ...: 
   ...: def f1(lst):
   ...:     return max(lst, key = lst.count)
   ...: 
   ...: def f2(lst):
   ...:     return Counter(lst).most_common(1)
   ...: 
   ...: lst0 = [1,2,3,4,3]
   ...: lst1 = lst0[:] * 100
   ...: 

In [2]: %timeit -n 10 f1(lst0)
10 loops, best of 3: 3.32 us per loop

In [3]: %timeit -n 10 f2(lst0)
10 loops, best of 3: 26 us per loop

In [4]: %timeit -n 10 f1(lst1)
10 loops, best of 3: 4.04 ms per loop

In [5]: %timeit -n 10 f2(lst1)
10 loops, best of 3: 75.6 us per loop

How to align two elements on the same line without changing HTML

In cases where I use floated elements like that, I usually need to be sure that the container element will always be big enough for the widths of both floated elements plus the desired margin to all fit inside of it. The easiest way to do that is obviously to give both inner elements fixed widths that will fit correctly inside of the outer element like this:

#container {width: 960px;}
#element1  {float:left; width:745px; margin-right:15px;}
#element2  {float:right; width:200px;}

If you can't do that because this is a scaling width layout, another option is to have every set of dimensions be percentages like:

#element1 {float:left; width:70%; margin-right:10%}
#element2 {float:right; width:20%;}

This gets tricky where you need something like this:

#element1 {float:left; width:70%; margin-right:10%}
#element2 {float:right; width:200px;}

In cases like that, I find that sometimes the best option is to not use floats, and use relative/absolute positioning to get the same effect like this:

#container {position:relative;} /* So IE won't bork the absolute positioning of #element2 */
#element1 {margin-right:215px;}
#element2 {display: block; position:absolute; top:0; right:0; height:100%; width:200px;}

While this isn't a floated solution, it does result in side by side columns where they are the same height, and one can remain fluid with while the other has a static width.

A simple jQuery form validation script

You can simply use the jQuery Validate plugin as follows.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        }
    });

});

HTML:

<form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="submit" />
</form>

DEMO: http://jsfiddle.net/xs5vrrso/

Options: http://jqueryvalidation.org/validate

Methods: http://jqueryvalidation.org/category/plugin/

Standard Rules: http://jqueryvalidation.org/category/methods/

Optional Rules available with the additional-methods.js file:

maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension

What is the difference between public, private, and protected?

It is typically considered good practice to default to the lowest visibility required as this promotes data encapsulation and good interface design. When considering member variable and method visibility think about the role the member plays in the interaction with other objects.

If you "code to an interface rather than implementation" then it's usually pretty straightforward to make visibility decisions. In general, variables should be private or protected unless you have a good reason to expose them. Use public accessors (getters/setters) instead to limit and regulate access to a class's internals.

To use a car as an analogy, things like speed, gear, and direction would be private instance variables. You don't want the driver to directly manipulate things like air/fuel ratio. Instead, you expose a limited number of actions as public methods. The interface to a car might include methods such as accelerate(), deccelerate()/brake(), setGear(), turnLeft(), turnRight(), etc.

The driver doesn't know nor should he care how these actions are implemented by the car's internals, and exposing that functionality could be dangerous to the driver and others on the road. Hence the good practice of designing a public interface and encapsulating the data behind that interface.

This approach also allows you to alter and improve the implementation of the public methods in your class without breaking the interface's contract with client code. For example, you could improve the accelerate() method to be more fuel efficient, yet the usage of that method would remain the same; client code would require no changes but still reap the benefits of your efficiency improvement.

Edit: Since it seems you are still in the midst of learning object oriented concepts (which are much more difficult to master than any language's syntax), I highly recommend picking up a copy of PHP Objects, Patterns, and Practice by Matt Zandstra. This is the book that first taught me how to use OOP effectively, rather than just teaching me the syntax. I had learned the syntax years beforehand, but that was useless without understanding the "why" of OOP.

How to create a hash or dictionary object in JavaScript

Use the in operator: e.g. "key1" in a.

Which characters make a URL invalid?

Not really an answer to your question but validating url's is really a serious p.i.t.a You're probably just better off validating the domainname and leave query part of the url be. That is my experience. You could also resort to pinging the url and seeing if it results in a valid response but that might be too much for such a simple task.

Regular expressions to detect url's are abundant, google it :)

413 Request Entity Too Large - File Upload Issue

Source: http://www.cyberciti.biz/faq/linux-unix-bsd-nginx-413-request-entity-too-large/

Edit the conf file of nginx:

nano /etc/nginx/nginx.conf

Add a line in the http section:

http {
    client_max_body_size 100M;
}

Doen't use MB it will not work, only the M!

Also do not forget to restart nginx

systemctl restart nginx

Regular Expressions- Match Anything

If you're using JavaScript, ES2018 added the /s (dotAll) flag. With the /s flag, the dot . will match any character, including a newline.

_x000D_
_x000D_
console.log("line_1\nline_2".match(/.+/s))
_x000D_
_x000D_
_x000D_

Note: It's not supported by all browsers yet.

How to crop an image using C#?

I was looking for a easy and FAST function with no additional libary to do the job. I tried Nicks solution, but i needed 29,4 sec to "extract" 1195 images of an atlas file. So later i managed this way and needed 2,43 sec to do the same job. Maybe this will be helpful.

// content of the Texture class
public class Texture
{
    //name of the texture
    public string name { get; set; }
    //x position of the texture in the atlas image
    public int x { get; set; }
    //y position of the texture in the atlas image
    public int y { get; set; }
    //width of the texture in the atlas image
    public int width { get; set; }
    //height of the texture in the atlas image
    public int height { get; set; }
}

Bitmap atlasImage = new Bitmap(@"C:\somepicture.png");
PixelFormat pixelFormat = atlasImage.PixelFormat;

foreach (Texture t in textureList)
{
     try
     {
           CroppedImage = new Bitmap(t.width, t.height, pixelFormat);
           // copy pixels over to avoid antialiasing or any other side effects of drawing
           // the subimages to the output image using Graphics
           for (int x = 0; x < t.width; x++)
               for (int y = 0; y < t.height; y++)
                   CroppedImage.SetPixel(x, y, atlasImage.GetPixel(t.x + x, t.y + y));
           CroppedImage.Save(Path.Combine(workingFolder, t.name + ".png"), ImageFormat.Png);
     }
     catch (Exception ex)
     {
          // handle the exception
     }
}

EditorFor() and html properties

This is the cleanest and most elegant/simple way to get a solution here.

Brilliant blog post and no messy overkill in writing custom extension/helper methods like a mad professor.

http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx

Why does sudo change the PATH?

Er, it's not really a test if you don't add something to your path:

bill@bill-desktop:~$ ls -l /opt/pkg/bin
total 12
-rwxr-xr-x 1 root root   28 2009-01-22 18:58 foo
bill@bill-desktop:~$ which foo
/opt/pkg/bin/foo
bill@bill-desktop:~$ sudo su
root@bill-desktop:/home/bill# which foo
root@bill-desktop:/home/bill# 

Working with $scope.$emit and $scope.$on

The Easiest way :

HTML

  <div ng-app="myApp" ng-controller="myCtrl"> 

        <button ng-click="sendData();"> Send Data </button>

    </div>

JavaScript

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope, $rootScope) {
            function sendData($scope) {
                var arrayData = ['sam','rumona','cubby'];
                $rootScope.$emit('someEvent', arrayData);
            }

        });
        app.controller('yourCtrl', function($scope, $rootScope) {
            $rootScope.$on('someEvent', function(event, data) {
                console.log(data); 
            }); 
        });
    </script>

Mock a constructor with parameter

To my knowledge, you can't mock constructors with mockito, only methods. But according to the wiki on the Mockito google code page there is a way to mock the constructor behavior by creating a method in your class which return a new instance of that class. then you can mock out that method. Below is an excerpt directly from the Mockito wiki:

Pattern 1 - using one-line methods for object creation

To use pattern 1 (testing a class called MyClass), you would replace a call like

   Foo foo = new Foo( a, b, c );

with

   Foo foo = makeFoo( a, b, c );

and write a one-line method

   Foo makeFoo( A a, B b, C c ) { 
        return new Foo( a, b, c );
   }

It's important that you don't include any logic in the method; just the one line that creates the object. The reason for this is that the method itself is never going to be unit tested.

When you come to test the class, the object that you test will actually be a Mockito spy, with this method overridden, to return a mock. What you're testing is therefore not the class itself, but a very slightly modified version of it.

Your test class might contain members like

  @Mock private Foo mockFoo;
  private MyClass toTest = spy(new MyClass());

Lastly, inside your test method you mock out the call to makeFoo with a line like

  doReturn( mockFoo )
      .when( toTest )
      .makeFoo( any( A.class ), any( B.class ), any( C.class ));

You can use matchers that are more specific than any() if you want to check the arguments that are passed to the constructor.

If you're just wanting to return a mocked object of your class I think this should work for you. In any case you can read more about mocking object creation here:

http://code.google.com/p/mockito/wiki/MockingObjectCreation

jQuery: Best practice to populate drop down?

Andreas Grech was pretty close... it's actually this (note the reference to this instead of the item in the loop):

var $dropdown = $("#dropdown");
$.each(result, function() {
    $dropdown.append($("<option />").val(this.ImageFolderID).text(this.Name));
});

How to get column values in one comma separated value

MYSQL: To get column values as one comma separated value use GROUP_CONCAT( ) function as

GROUP_CONCAT(  `column_name` )

for example

SELECT GROUP_CONCAT(  `column_name` ) 
FROM  `table_name` 
WHERE 1 
LIMIT 0 , 30

How to get current user in asp.net core

Taking IdentityUser would also work. This is a current user object and all values of user can be retrieved.

private readonly UserManager<IdentityUser> _userManager;
public yourController(UserManager<IdentityUser> userManager)
{
    _userManager = userManager;
}

var user = await _userManager.GetUserAsync(HttpContext.User);

IIS Express gives Access Denied error when debugging ASP.NET MVC

None of the above had worked for me. This had been working for me prior to today. I then realized I had been working with creating a hosted connection on my laptop and had Shared an internet connection with my Wireless Network Connection.

To fix my issue:

Go to Control Panel > Network and Internet > Network Connections

Right click on any secondary Wireless Network Connection you may have (mine was named Wireless Network Connection 2) and click 'Properties'.

Go to the 'Sharing' tab at the top.

Uncheck the box that states 'Allow other network users to connect through this computer's Internet connection'.

Hit OK > then Apply.

Hope this helps!

How to deal with bad_alloc in C++?

You can catch it like any other exception:

try {
  foo();
}
catch (const std::bad_alloc&) {
  return -1;
}

Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.



In general you cannot, and should not try, to respond to this error. bad_alloc indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.

Worse, modern operating systems often over-allocate: on such systems, malloc and new can return a valid pointer even if there is not enough free memory left – std::bad_alloc will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).

The only thing you could do when catching std::bad_alloc is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).

In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:

  1. The application must ensure that it runs on a system that does not overcommit memory, i.e. it signals failure upon allocation rather than later.
  2. The application must be able to free memory immediately, without any further accidental allocations in the meantime.

It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1

OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:

lru_cache<widget> widget_cache;

double perform_operation(int widget_id) {
    std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
    if (not maybe_widget) {
        maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
    }
    return maybe_widget->frobnicate();
}

…

for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
    try {
        return perform_operation(widget_id);
    } catch (std::bad_alloc const&) {
        if (widget_cache.empty()) throw; // memory error elsewhere.
        widget_cache.remove_oldest();
    }
}

// Handle too many failed attempts here.

But even here, using std::set_new_handler instead of handling std::bad_alloc provides the same benefit and would be much simpler.


1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.


What is the C++ Standard specified behavior of new in c++?

The usual notion is that if new operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc.
However, something more happens even before a bad_alloc exception is thrown:

C++03 Section 3.7.4.1.3: says

An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.

Consider the following code sample:

#include <iostream>
#include <cstdlib>

// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
    std::cerr << "Unable to satisfy request for memory\n";

    std::abort();
}

int main()
{
    //set the new_handler
    std::set_new_handler(outOfMemHandler);

    //Request huge memory size, that will cause ::operator new to fail
    int *pBigDataArray = new int[100000000L];

    return 0;
}

In the above example, operator new (most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler() will be called, and the program will abort after issuing an error message.

As seen here the default behavior of new operator when unable to fulfill a memory request, is to call the new-handler function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort(), outOfMemHandler() would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.

What is the new_handler and set_new_handler?

new_handler is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler is a function that takes and returns a new_handler.

Something like:

typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();

set_new_handler's parameter is a pointer to the function operator new should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.

How to handle out of memory conditions in C++?

Given the behavior of newa well designed user program should handle out of memory conditions by providing a proper new_handlerwhich does one of the following:

Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.

Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler). The next time operator new calls the new-handler function, it will get the one most recently installed.

(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)

Uninstall the new-handler: This is done by passing a null pointer to set_new_handler. With no new-handler installed, operator new will throw an exception ((convertible to) std::bad_alloc) when memory allocation is unsuccessful.

Throw an exception convertible to std::bad_alloc. Such exceptions are not be caught by operator new, but will propagate to the site originating the request for memory.

Not return: By calling abort or exit.

How to change MenuItem icon in ActionBar programmatically

This works for me. It should be in your onOptionsItemSelected(MenuItem item) method item.setIcon(R.drawable.your_icon);

PHP Curl UTF-8 Charset

You Can use this header

   header('Content-type: text/html; charset=UTF-8');

and after decoding the string

 $page = utf8_decode(curl_exec($ch));

It worked for me

Boolean operators && and ||

The shorter ones are vectorized, meaning they can return a vector, like this:

((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE  TRUE FALSE FALSE

The longer form evaluates left to right examining only the first element of each vector, so the above gives

((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE

As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."

So you want to use the long forms only when you are certain the vectors are length one.

You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.

The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.

One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.

a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found

Finally, see section 8.2.17 in The R Inferno, titled "and and andand".

500 Internal Server Error for php file not for html

I was having this problem because I was trying to connect to MySQL but I didn't have the required package. I figured it out because of @Amadan's comment to check the error log. In my case, I was having the error: Call to undefined function mysql_connect()

If your PHP file has any code to connect with a My-SQL db then you might need to install php5-mysql first. I was getting this error because I hadn't installed it. All my file permissions were good. In Ubuntu, you can install it by the following command:

sudo apt-get install php5-mysql

Identify if a string is a number

Pull in a reference to Visual Basic in your project and use its Information.IsNumeric method such as shown below and be able to capture floats as well as integers unlike the answer above which only catches ints.

    // Using Microsoft.VisualBasic;

    var txt = "ABCDEFG";

    if (Information.IsNumeric(txt))
        Console.WriteLine ("Numeric");

IsNumeric("12.3"); // true
IsNumeric("1"); // true
IsNumeric("abc"); // false

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

Adding values to specific DataTable cells

I think you can't do that but atleast you can update it. In order to edit an existing row in a DataTable, you need to locate the DataRow you want to edit, and then assign the updated values to the desired columns.

Example,

DataSet1.Tables(0).Rows(4).Item(0) = "Updated Company Name"
DataSet1.Tables(0).Rows(4).Item(1) = "Seattle"

SOURCE HERE

How can I inspect the file system of a failed `docker build`?

What I would do is comment out the Dockerfile below and including the offending line. Then you can run the container and run the docker commands by hand, and look at the logs in the usual way. E.g. if the Dockerfile is

RUN foo
RUN bar
RUN baz

and it's dying at bar I would do

RUN foo
# RUN bar
# RUN baz

Then

$ docker build -t foo .
$ docker run -it foo bash
container# bar
...grep logs...

Getting 400 bad request error in Jquery Ajax POST

You need to build query from "data" object using the following function

function buildQuery(obj) {
        var Result= '';
        if(typeof(obj)== 'object') {
            jQuery.each(obj, function(key, value) {
                Result+= (Result) ? '&' : '';
                if(typeof(value)== 'object' && value.length) {
                    for(var i=0; i<value.length; i++) {
                        Result+= [key+'[]', encodeURIComponent(value[i])].join('=');
                    }
                } else {
                    Result+= [key, encodeURIComponent(value)].join('=');
                }
            });
        }
        return Result;
    }

and then proceed with

var data= {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work, facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: buildQuery(data),
  error: function(e) {
    console.log(e);
  }
});

Concatenating Files And Insert New Line In Between Files

This works in Bash:

for f in *.txt; do cat $f; echo; done

In contrast to answers with >> (append), the output of this command can be piped into other programs.

Examples:

  • for f in File*.txt; do cat $f; echo; done > finalfile.txt
  • (for ... done) > finalfile.txt (parens are optional)
  • for ... done | less (piping into less)
  • for ... done | head -n -1 (this strips off the trailing blank line)

Java better way to delete file if exists

Use Apache Commons FileUtils.deleteDirectory() or FileUtils.forceDelete() to log exceptions in case of any failures,

or FileUtils.deleteQuietly() if you're not concerned about exceptions thrown.

How to get values from selected row in DataGrid for Windows Form Application?

Description

Assuming i understand your question.

You can get the selected row using the DataGridView.SelectedRows Collection. If your DataGridView allows only one selected, have a look at my sample.

DataGridView.SelectedRows Gets the collection of rows selected by the user.

Sample

if (dataGridView1.SelectedRows.Count != 0)
{
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];
    row.Cells["ColumnName"].Value
}

More Information

Regular expression to allow spaces between words

This one worked for me

([\w ]+)

How to get client IP address in Laravel 5+

You can get a few way ip address utilizing Request ip, Request getClientIp and solicitation partner work. In this model, I will tell you the best way to get current client ip address in laravel 5.8.

$clientIP = request()->ip();

dd($clientIP);

You can follow this from here

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

Solution 1

Run the app on a physical device instead of the emulator. I encountered this issue and my app didnt have a content provider defined.

Solution 2

In the other instance, i had an instrumented test app installed matching the same applicationId.

To fix the issue i had to run ./gradlew uA - uA short for uninstallAll task.

You can alternatively use the Gradle panel and choose navigate to app\install\uninstallAll task

If you using an emulator, you can wipe out the data

How do I make an HTTP request in Swift?

Swift 4 and above : Data Request using URLSession API

   //create the url with NSURL
   let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! //change the url

   //create the session object
   let session = URLSession.shared

   //now create the URLRequest object using the url object
   let request = URLRequest(url: url)

   //create dataTask using the session object to send data to the server
   let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

       guard error == nil else {
           return
       }

       guard let data = data else {
           return
       }

      do {
         //create json object from data
         if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
            print(json)
         }
      } catch let error {
        print(error.localizedDescription)
      }
   })

   task.resume()

Swift 4 and above, Decodable and Result enum

//APPError enum which shows all possible errors
enum APPError: Error {
    case networkError(Error)
    case dataNotFound
    case jsonParsingError(Error)
    case invalidStatusCode(Int)
}

//Result enum to show success or failure
enum Result<T> {
    case success(T)
    case failure(APPError)
}

//dataRequest which sends request to given URL and convert to Decodable Object
func dataRequest<T: Decodable>(with url: String, objectType: T.Type, completion: @escaping (Result<T>) -> Void) {

    //create the url with NSURL
    let dataURL = URL(string: url)! //change the url

    //create the session object
    let session = URLSession.shared

    //now create the URLRequest object using the url object
    let request = URLRequest(url: dataURL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request, completionHandler: { data, response, error in

        guard error == nil else {
            completion(Result.failure(AppError.networkError(error!)))
            return
        }

        guard let data = data else {
            completion(Result.failure(APPError.dataNotFound))
            return
        }

        do {
            //create decodable object from data
            let decodedObject = try JSONDecoder().decode(objectType.self, from: data)
            completion(Result.success(decodedObject))
        } catch let error {
            completion(Result.failure(APPError.jsonParsingError(error as! DecodingError)))
        }
    })

    task.resume()
}

example:

//if we want to fetch todo from placeholder API, then we define the ToDo struct and call dataRequest and pass "https://jsonplaceholder.typicode.com/todos/1" string url.

struct ToDo: Decodable {
    let id: Int
    let userId: Int
    let title: String
    let completed: Bool

}

dataRequest(with: "https://jsonplaceholder.typicode.com/todos/1", objectType: ToDo.self) { (result: Result) in
    switch result {
    case .success(let object):
        print(object)
    case .failure(let error):
        print(error)
    }
}

//this prints the result:

ToDo(id: 1, userId: 1, title: "delectus aut autem", completed: false)

Setting the character encoding in form submit for Internet Explorer

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

How to add style from code behind?

If no file available for download, I needed to disable the asp:linkButton, change it to grey and eliminate the underline on the hover. This worked:

.disabled {
    color: grey;
    text-decoration: none !important;
}

LinkButton button = item.FindControl("lnkFileDownload") as LinkButton;
button.Enabled = false;
button.CssClass = "disabled";

How to SELECT a dropdown list item by value programmatically

If you know that the dropdownlist contains the value you're looking to select, use:

ddl.SelectedValue = "2";

If you're not sure if the value exists, use (or you'll get a null reference exception):

ListItem selectedListItem = ddl.Items.FindByValue("2");

if (selectedListItem != null)
{
    selectedListItem.Selected = true;
}

Upload folder with subfolders using S3 and the AWS console

I ended up here when trying to figure this out. With the version that's up there right now you can drag and drop a folder into it and it works, even though it doesn't allow you to select a folder when you open the upload dialogue.

How to get JSON objects value if its name contains dots?

What you want is:

var smth = mydata.list[0]["points.bean.pointsBase"][0].time;

In JavaScript, any field you can access using the . operator, you can access using [] with a string version of the field name.

How to make a DIV not wrap?

Try to use width: 3000px; for the case of IE.

Matrix Transpose in Python

To complete J.F. Sebastian's answer, if you have a list of lists with different lengths, check out this great post from ActiveState. In short:

The built-in function zip does a similar job, but truncates the result to the length of the shortest list, so some elements from the original data may be lost afterwards.

To handle list of lists with different lengths, use:

def transposed(lists):
   if not lists: return []
   return map(lambda *row: list(row), *lists)

def transposed2(lists, defval=0):
   if not lists: return []
   return map(lambda *row: [elem or defval for elem in row], *lists)

vagrant login as root by default

vagrant destroy
vagrant up

Please add this to vagrant file:

config.ssh.username = 'vagrant'
config.ssh.password = 'vagrant'
config.ssh.insert_key = 'true'

Git push hangs when pushing to Github?

I had the same issue. Stop worrying and searching endless complicated solutions, just remove git and reinstall it.

sudo apt-get purge git
sudo apt-get autoremove
sudo apt-get install git

Thats it. It should work now

How do I pass multiple parameters in Objective-C?

Yes; the Objective-C method syntax is like this for a couple of reasons; one of these is so that it is clear what the parameters you are specifying are. For example, if you are adding an object to an NSMutableArray at a certain index, you would do it using the method:

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;

This method is called insertObject:atIndex: and it is clear that an object is being inserted at a specified index.

In practice, adding a string "Hello, World!" at index 5 of an NSMutableArray called array would be called as follows:

NSString *obj = @"Hello, World!";
int index = 5;

[array insertObject:obj atIndex:index];

This also reduces ambiguity between the order of the method parameters, ensuring that you pass the object parameter first, then the index parameter. This becomes more useful when using functions that take a large number of arguments, and reduces error in passing the arguments.

Furthermore, the method naming convention is such because Objective-C doesn't support overloading; however, if you want to write a method that does the same job, but takes different data-types, this can be accomplished; take, for instance, the NSNumber class; this has several object creation methods, including:

  • + (id)numberWithBool:(BOOL)value;
  • + (id)numberWithFloat:(float)value;
  • + (id)numberWithDouble:(double)value;

In a language such as C++, you would simply overload the number method to allow different data types to be passed as the argument; however, in Objective-C, this syntax allows several different variants of the same function to be implemented, by changing the name of the method for each variant of the function.

NoClassDefFoundError on Maven dependency

Choosing to Project -> Clean should resolve this

Putting -moz-available and -webkit-fill-available in one width (css property)

I needed my ASP.NET drop down list to take up all available space, and this is all I put in the CSS and it is working in Firefox and IE11:

width: 100%

I had to add the CSS class into the asp:DropDownList element

python object() takes no parameters error

I struggled for a while about this. Stupid rule for __init__. It is two "_" together to be "__"

Visual Studio can't 'see' my included header files

Try adding the header file to your project's files. (right click on project -> add existing file).

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

Are you concerned about the profile picture size? at the time of implementing login with Facebook using PHP. We’ll show you the simple way to get large size profile picture in Facebook PHP SDK. Also, you can get the custom size image of Facebook profile.

Set the profile picture dimension by using the following line of code.

$userProfile = $facebook->api('/me?fields=picture.width(400).height(400)');

check this post:http://www.codexworld.com/how-to-guides/get-large-size-profile-picture-in-facebook-php-sdk/

Removing empty rows of a data file in R

Alternative solution for rows of NAs using janitor package

myData %>% remove_empty("rows")

How do you setLayoutParams() for an ImageView?

An ImageView gets setLayoutParams from View which uses ViewGroup.LayoutParams. If you use that, it will crash in most cases so you should use getLayoutParams() which is in View.class. This will inherit the parent View of the ImageView and will work always. You can confirm this here: ImageView extends view

Assuming you have an ImageView defined as 'image_view' and the width/height int defined as 'thumb_size'

The best way to do this:

ViewGroup.LayoutParams iv_params_b = image_view.getLayoutParams();
iv_params_b.height = thumb_size;
iv_params_b.width = thumb_size;
image_view.setLayoutParams(iv_params_b);

How to perform an SQLite query within an Android application?

I came here for a reminder of how to set up the query but the existing examples were hard to follow. Here is an example with more explanation.

SQLiteDatabase db = helper.getReadableDatabase();

String table = "table2";
String[] columns = {"column1", "column3"};
String selection = "column3 =?";
String[] selectionArgs = {"apple"};
String groupBy = null;
String having = null;
String orderBy = "column3 DESC";
String limit = "10";

Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);

Parameters

  • table: the name of the table you want to query
  • columns: the column names that you want returned. Don't return data that you don't need.
  • selection: the row data that you want returned from the columns (This is the WHERE clause.)
  • selectionArgs: This is substituted for the ? in the selection String above.
  • groupBy and having: This groups duplicate data in a column with data having certain conditions. Any unneeded parameters can be set to null.
  • orderBy: sort the data
  • limit: limit the number of results to return

100% width table overflowing div container

Try adding

word-break: break-all 

to the CSS on your table element.

That will get the words in the table cells to break such that the table does not grow wider than its containing div, yet the table columns are still sized dynamically. jsfiddle demo.

C++ equivalent of StringBuffer/StringBuilder?

NOTE this answer has received some attention recently. I am not advocating this as a solution (it is a solution I have seen in the past, before the STL). It is an interesting approach and should only be applied over std::string or std::stringstream if after profiling your code you discover this makes an improvement.

I normally use either std::string or std::stringstream. I have never had any problems with these. I would normally reserve some room first if I know the rough size of the string in advance.

I have seen other people make their own optimized string builder in the distant past.

class StringBuilder {
private:
    std::string main;
    std::string scratch;

    const std::string::size_type ScratchSize = 1024;  // or some other arbitrary number

public:
    StringBuilder & append(const std::string & str) {
        scratch.append(str);
        if (scratch.size() > ScratchSize) {
            main.append(scratch);
            scratch.resize(0);
        }
        return *this;
    }

    const std::string & str() {
        if (scratch.size() > 0) {
            main.append(scratch);
            scratch.resize(0);
        }
        return main;
    }
};

It uses two strings one for the majority of the string and the other as a scratch area for concatenating short strings. It optimise's appends by batching the short append operations in one small string then appending this to the main string, thus reducing the number of reallocations required on the main string as it gets larger.

I have not required this trick with std::string or std::stringstream. I think it was used with a third party string library before std::string, it was that long ago. If you adopt a strategy like this profile your application first.

How to implement the Android ActionBar back button?

https://stackoverflow.com/a/46903870/4489222

To achieved this, there are simply two steps,

Step 1: Go to AndroidManifest.xml and in the add the parameter in tag - android:parentActivityName=".home.HomeActivity"

example :

 <activity
    android:name=".home.ActivityDetail"
    android:parentActivityName=".home.HomeActivity"
    android:screenOrientation="portrait" />

Step 2: in ActivityDetail add your action for previous page/activity

example :

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
      case android.R.id.home: 
          onBackPressed();
          return true;
   }
   return super.onOptionsItemSelected(item);}
}

Online SQL syntax checker conforming to multiple databases

You could try a formatter like this

They will always be limited because they don't (and can't) know what user defined functions you may have defined in your database (or which built-in functions you have or don't have access to).

You could also look at ANTLR (but that would be an offline solution)

unix - count of columns in file

Based on Cat Kerr response. This command is working on solaris

awk '{print NF; exit}' stores.dat

'Connect-MsolService' is not recognized as the name of a cmdlet

Following worked for me:

  1. Uninstall the previously installed ‘Microsoft Online Service Sign-in Assistant’ and ‘Windows Azure Active Directory Module for Windows PowerShell’.
  2. Install 64-bit versions of ‘Microsoft Online Service Sign-in Assistant’ and ‘Windows Azure Active Directory Module for Windows PowerShell’. https://littletalk.wordpress.com/2013/09/23/install-and-configure-the-office-365-powershell-cmdlets/

If you get the following error In order to install Windows Azure Active Directory Module for Windows PowerShell, you must have Microsoft Online Services Sign-In Assistant version 7.0 or greater installed on this computer, then install the Microsoft Online Services Sign-In Assistant for IT Professionals BETA: http://www.microsoft.com/en-us/download/details.aspx?id=39267

  1. Copy the folders called MSOnline and MSOnline Extended from the source

C:\Windows\System32\WindowsPowerShell\v1.0\Modules\

to the folder

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\

https://stackoverflow.com/a/16018733/5810078.

(But I have actually copied all the possible files from

C:\Windows\System32\WindowsPowerShell\v1.0\

to

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\

(For copying you need to alter the security permissions of that folder))

handle textview link click in my android app

Just to share an alternative solution using a library I created. With Textoo, this can be achieved like:

TextView locNotFound = Textoo
    .config((TextView) findViewById(R.id.view_location_disabled))
    .addLinksHandler(new LinksHandler() {
        @Override
        public boolean onClick(View view, String url) {
            if ("internal://settings/location".equals(url)) {
                Intent locSettings = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(locSettings);
                return true;
            } else {
                return false;
            }
        }
    })
    .apply();

Or with dynamic HTML source:

String htmlSource = "Links: <a href='http://www.google.com'>Google</a>";
Spanned linksLoggingText = Textoo
    .config(htmlSource)
    .parseHtml()
    .addLinksHandler(new LinksHandler() {
        @Override
        public boolean onClick(View view, String url) {
            Log.i("MyActivity", "Linking to google...");
            return false; // event not handled.  Continue default processing i.e. link to google
        }
    })
    .apply();
textView.setText(linksLoggingText);

Delete topic in Kafka 0.8.1.1

As mentioned in doc here

Topic deletion option is disabled by default. To enable it set the server config delete.topic.enable=true Kafka does not currently support reducing the number of partitions for a topic or changing the replication factor.

Make sure delete.topic.enable=true

sed: print only matching group

grep is the right tool for extracting.

using your example and your regex:

kent$  echo 'foo bar <foo> bla 1 2 3.4'|grep -o '[0-9][0-9]*[\ \t][0-9.]*[\ \t]*$'
2 3.4

alert a variable value

If I'm understanding your question and code correctly, then I want to first mention three things before sharing my code/version of a solution. First, for both name and value you probably shouldn't be using the getAttribute() method because they are, themselves, properties of (the variable named) inputs (at a given index of i). Secondly, the variable that you are trying to alert is one of a select handful of terms in JavaScript that are designated as 'reserved keywords' or simply "reserved words". As you can see in/on this list (on the link), new is clearly a reserved word in JS and should never be used as a variable name. For more information, simply google 'reserved words in JavaScript'. Third and finally, in your alert statement itself, you neglected to include a semicolon. That and that alone can sometimes be enough for your code not to run as expected. [Aside: I'm not saying this as advice but more as observation: JavaScript will almost always forgive and allow having too many and/or unnecessary semicolons, but generally JavaScript is also equally if not moreso merciless if/when missing (any of the) necessary, required semicolons. Therefore, best practice is, of course, to add the semicolons only at all of the required points and exclude them in all other circumstances. But practically speaking, if in doubt, it probably will not hurt things by adding/including an extra one but will hurt by ignoring a mandatory one. General rules are all declarations and assignments end with a semicolon (such as variable assignments, alerts, console.log statements, etc.) but most/all expressions do not (such as for loops, while loops, function expressions Just Saying.] But I digress..

    function whenWindowIsReady() {
        var inputs = document.getElementsByTagName('input');
        var lengthOfInputs = inputs.length; // this is for optimization
        for (var i = 0; i < lengthOfInputs; i++) {
            if (inputs[i].name === "ans") {   
                var ansIsName = inputs[i].value;
                alert(ansIsName);
            }
        }
    }

    window.onReady = whenWindowIsReady();

PS: You used a double assignment operator in your conditional statement, and in this case it doesn't matter since you are comparing Strings, but generally I believe the triple assignment operator is the way to go and is more accurate as that would check if the values are EQUIVALENT WITHOUT TYPE CONVERSION, which can be very important for other instances of comparisons, so it's important to point out. For example, 1=="1" and 0==false are both true (when usually you'd want those to return false since the value on the left was not the same as the value on the right, without type conversion) but 1==="1" and 0===false are both false as you'd expect because the triple operator doesn't rely on type conversion when making comparisons. Keep that in mind for the future.

Pandas: Subtracting two date columns and the result being an integer

You can use datetime module to help here. Also, as a side note, a simple date subtraction should work as below:

import datetime as dt
import numpy as np
import pandas as pd

#Assume we have df_test:
In [222]: df_test
Out[222]: 
   first_date second_date
0  2016-01-31  2015-11-19
1  2016-02-29  2015-11-20
2  2016-03-31  2015-11-21
3  2016-04-30  2015-11-22
4  2016-05-31  2015-11-23
5  2016-06-30  2015-11-24
6         NaT  2015-11-25
7         NaT  2015-11-26
8  2016-01-31  2015-11-27
9         NaT  2015-11-28
10        NaT  2015-11-29
11        NaT  2015-11-30
12 2016-04-30  2015-12-01
13        NaT  2015-12-02
14        NaT  2015-12-03
15 2016-04-30  2015-12-04
16        NaT  2015-12-05
17        NaT  2015-12-06

In [223]: df_test['Difference'] = df_test['first_date'] - df_test['second_date'] 

In [224]: df_test
Out[224]: 
   first_date second_date  Difference
0  2016-01-31  2015-11-19     73 days
1  2016-02-29  2015-11-20    101 days
2  2016-03-31  2015-11-21    131 days
3  2016-04-30  2015-11-22    160 days
4  2016-05-31  2015-11-23    190 days
5  2016-06-30  2015-11-24    219 days
6         NaT  2015-11-25         NaT
7         NaT  2015-11-26         NaT
8  2016-01-31  2015-11-27     65 days
9         NaT  2015-11-28         NaT
10        NaT  2015-11-29         NaT
11        NaT  2015-11-30         NaT
12 2016-04-30  2015-12-01    151 days
13        NaT  2015-12-02         NaT
14        NaT  2015-12-03         NaT
15 2016-04-30  2015-12-04    148 days
16        NaT  2015-12-05         NaT
17        NaT  2015-12-06         NaT

Now, change type to datetime.timedelta, and then use the .days method on valid timedelta objects.

In [226]: df_test['Diffference'] = df_test['Difference'].astype(dt.timedelta).map(lambda x: np.nan if pd.isnull(x) else x.days)

In [227]: df_test
Out[227]: 
   first_date second_date  Difference  Diffference
0  2016-01-31  2015-11-19     73 days           73
1  2016-02-29  2015-11-20    101 days          101
2  2016-03-31  2015-11-21    131 days          131
3  2016-04-30  2015-11-22    160 days          160
4  2016-05-31  2015-11-23    190 days          190
5  2016-06-30  2015-11-24    219 days          219
6         NaT  2015-11-25         NaT          NaN
7         NaT  2015-11-26         NaT          NaN
8  2016-01-31  2015-11-27     65 days           65
9         NaT  2015-11-28         NaT          NaN
10        NaT  2015-11-29         NaT          NaN
11        NaT  2015-11-30         NaT          NaN
12 2016-04-30  2015-12-01    151 days          151
13        NaT  2015-12-02         NaT          NaN
14        NaT  2015-12-03         NaT          NaN
15 2016-04-30  2015-12-04    148 days          148
16        NaT  2015-12-05         NaT          NaN
17        NaT  2015-12-06         NaT          NaN

Hope that helps.

How can I see the size of files and directories in linux?

To get the total size of directory or the total size of file use,

du -csh <directory or filename*> | grep total

AngularJS UI Router - change url without reloading state

This setup solved following issues for me:

  • The training controller is not called twice when updating the url from .../ to .../123
  • The training controller is not getting invoked again when navigating to another state

State configuration

state('training', {
    abstract: true,
    url: '/training',
    templateUrl: 'partials/training.html',
    controller: 'TrainingController'
}).
state('training.edit', {
    url: '/:trainingId'
}).
state('training.new', {
    url: '/{trainingId}',
    // Optional Parameter
    params: {
        trainingId: null
    }
})

Invoking the states (from any other controller)

$scope.editTraining = function (training) {
    $state.go('training.edit', { trainingId: training.id });
};

$scope.newTraining = function () {
    $state.go('training.new', { });
};

Training Controller

var newTraining;

if (!!!$state.params.trainingId) {

    // new      

    newTraining = // create new training ...

    // Update the URL without reloading the controller
    $state.go('training.edit',
        {
            trainingId : newTraining.id
        },
        {
            location: 'replace', //  update url and replace
            inherit: false,
            notify: false
        });     

} else {

    // edit

    // load existing training ...
}   

How can I permanently enable line numbers in IntelliJ?

Android Studio 1.3.2 and on, IntelliJ 15 and on

Global configuration

File -> Settings -> Editor -> General -> Appearance -> Show line numbers

enter image description here


Current editor configuration

First way: View -> Active Editor -> Show Line Numbers (this option will only be available if you previously have clicked into a file of the active editor)

Second way: Right click on the small area between the project's structure and the active editor (that is, the one that you can set breakpoints) -> Show Line Numbers. enter image description here

Laravel blade check empty foreach

Using following code, one can first check variable is set or not using @isset of laravel directive and then check that array is blank or not using @unless of laravel directive

@if(@isset($names))
    @unless($names)
        Array has no value
    @else
        Array has value

        @foreach($names as $name)
            {{$name}}
        @endforeach

    @endunless
@else
    Not defined
@endif

Combine two (or more) PDF's

Here is a single function that will merge X amount of PDFs using PDFSharp

using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;

public static void MergePDFs(string targetPath, params string[] pdfs) {
    using(PdfDocument targetDoc = new PdfDocument()){
        foreach (string pdf in pdfs) {
            using (PdfDocument pdfDoc = PdfReader.Open(pdf, PdfDocumentOpenMode.Import)) {
                for (int i = 0; i < pdfDoc.PageCount; i++) {
                    targetDoc.AddPage(pdfDoc.Pages[i]);
                }
            }
        }
        targetDoc.Save(targetPath);
    }
}

Check if option is selected with jQuery, if not select a default

You guys are doing way too much for selecting. Just select by value:

$("#mySelect").val( 3 );

JPA: unidirectional many-to-one and cascading delete

I have seen in unidirectional @ManytoOne, delete don't work as expected. When parent is deleted, ideally child should also be deleted, but only parent is deleted and child is NOT deleted and is left as orphan

Technology used are Spring Boot/Spring Data JPA/Hibernate

Sprint Boot : 2.1.2.RELEASE

Spring Data JPA/Hibernate is used to delete row .eg

parentRepository.delete(parent)

ParentRepository extends standard CRUD repository as shown below ParentRepository extends CrudRepository<T, ID>

Following are my entity class

@Entity(name = “child”)
public class Child  {

    @Id
    @GeneratedValue
    private long id;

    @ManyToOne( fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = “parent_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Parent parent;
}

@Entity(name = “parent”)
public class Parent {

    @Id
    @GeneratedValue
    private long id;

    @Column(nullable = false, length = 50)
    private String firstName;


}

Why use @Scripts.Render("~/bundles/jquery")

Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.

As example you could create your own bundle:

bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
            "~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
            "~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))

And render it like this:

@Scripts.Render("~/bundles/mybundle")

One more advantage of @Scripts.Render("~/bundles/mybundle") over the native <script src="~/bundles/mybundle" /> is that @Scripts.Render() will respect the web.config debug setting:

  <system.web>
    <compilation debug="true|false" />

If debug="true" then it will instead render individual script tags for each source script, without any minification.

For stylesheets you will have to use a StyleBundle and @Styles.Render().

Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.

SQL Server remove milliseconds from datetime

There's more than one way to do it:

select 1 where datediff(second, '2010-07-20 03:21:52', '2010-07-20 03:21:52.577') >= 0

or

select *
from table
where datediff(second, '2010-07-20 03:21:52', date) >= 0 

one less function call, but you have to be beware of overflowing the max integer if the dates are too far apart.

what are the .map files used for in Bootstrap 3.x?

From Working with CSS preprocessors in Chrome DevTools:

Many developers generate CSS style sheets using a CSS preprocessor, such as Sass, Less, or Stylus. Because the CSS files are generated, editing the CSS files directly is not as helpful.

For preprocessors that support CSS source maps, DevTools lets you live-edit your preprocessor source files in the Sources panel, and view the results without having to leave DevTools or refresh the page. When you inspect an element whose styles are provided by a generated CSS file, the Elements panel displays a link to the original source file, not the generated .css file.

Git push rejected "non-fast-forward"

Well I used the advice here and it screwed me as it merged my local code directly to master. .... so take it all with a grain of salt. My coworker said the following helped resolve the issue, needed to repoint my branch.

 git branch --set-upstream-to=origin/feature/my-current-branch feature/my-current-branch

System.Runtime.InteropServices.COMException (0x800A03EC)

Try this as it worked for me...

  1. Go to "Start" -> "Run" and enter "dcomcnfg"
  2. This will bring up the component services window, expand out "Console Root" -> "Computers" -> "DCOM Config"
  3. Find "Microsoft Excel Application" in the list of components.
  4. Right click on the entry and select "Properties"
  5. Go to the "Identity" tab on the properties dialog.
  6. Select "The interactive user."

courtesy of Last paragraph mentioned in here

How can prevent a PowerShell window from closing so I can see the error?

You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post.

  1. One-time Fix: Run your script from the PowerShell Console, or launch the PowerShell process using the -NoExit switch. e.g. PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
  2. Per-script Fix: Add a prompt for input to the end of your script file. e.g. Read-Host -Prompt "Press Enter to exit"
  3. Global Fix: Change your registry key to always leave the PowerShell Console window open after the script finishes running. Here's the 2 registry keys that would need to be changed:

    ? Open With ? Windows PowerShell
    When you right-click a .ps1 file and choose Open With

    Registry Key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command

    Default Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"
    

    Desired Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""
    

    ? Run with PowerShell
    When you right-click a .ps1 file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed).

    Registry Key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command

    Default Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
    

    Desired Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \"%1\""
    

You can download a .reg file from my blog to modify the registry keys for you if you don't want to do it manually.

It sounds like you likely want to use option #2. You could even wrap your whole script in a try block, and only prompt for input if an error occurred, like so:

try
{
    # Do your script's stuff
}
catch
{
    Write-Error $_.Exception.ToString()
    Read-Host -Prompt "The above error occurred. Press Enter to exit."
}

Export and Import all MySQL databases at one time

Based on these answers I've made script which backups all databases into separate files, but then compress them into one archive with date as name.

This will not ask for password, can be used in cron. To store password in .my.cnf check this answer https://serverfault.com/a/143587/62749

Made also with comments for those who are not very familiar with bash scripts.

#!/bin/bash

# This script will backup all mysql databases into 
# compressed file named after date, ie: /var/backup/mysql/2016-07-13.tar.bz2

# Setup variables used later

# Create date suffix with "F"ull date format
suffix=$(date +%F)
# Retrieve all database names except information schemas. Use sudo here to skip root password.
dbs=$(sudo mysql --defaults-extra-file=/root/.my.cnf --batch --skip-column-names -e "SHOW DATABASES;" | grep -E -v "(information|performance)_schema")
# Create temporary directory with "-d" option
tmp=$(mktemp -d)
# Set output dir here. /var/backups/ is used by system, 
# so intentionally used /var/backup/ for user backups.
outDir="/var/backup/mysql"
# Create output file name
out="$outDir/$suffix.tar.bz2"

# Actual script

# Check if output directory exists
if [ ! -d "$outDir" ];then
  # Create directory with parent ("-p" option) directories
  sudo mkdir -p "$outDir"
fi

# Loop through all databases
for db in $dbs; do
  # Dump database to temporary directory with file name same as database name + sql suffix
  sudo mysqldump --defaults-extra-file=/root/.my.cnf --databases "$db" > "$tmp/$db.sql"
done

# Go to tmp dir
cd $tmp

# Compress all dumps with bz2, discard any output to /dev/null
sudo tar -jcf "$out" * > "/dev/null"

# Cleanup
cd "/tmp/"
sudo rm -rf "$tmp"

Reading file input from a multipart/form-data POST

I open-sourced a C# Http form parser here.

This is slightly more flexible than the other one mentioned which is on CodePlex, since you can use it for both Multipart and non-Multipart form-data, and also it gives you other form parameters formatted in a Dictionary object.

This can be used as follows:

non-multipart

public void Login(Stream stream)
{
    string username = null;
    string password = null;

    HttpContentParser parser = new HttpContentParser(stream);
    if (parser.Success)
    {
        username = HttpUtility.UrlDecode(parser.Parameters["username"]);
        password = HttpUtility.UrlDecode(parser.Parameters["password"]);
    }
}

multipart

public void Upload(Stream stream)
{
    HttpMultipartParser parser = new HttpMultipartParser(stream, "image");

    if (parser.Success)
    {
        string user = HttpUtility.UrlDecode(parser.Parameters["user"]);
        string title = HttpUtility.UrlDecode(parser.Parameters["title"]);

        // Save the file somewhere
        File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
    }
}

Import cycle not allowed

You may have imported,

project/controllers/base

inside the

project/controllers/routes

You have already imported before. That's not supported.

How to crop an image using PIL?

An easier way to do this is using crop from ImageOps. You can feed the number of pixels you want to crop from each side.

from PIL import ImageOps

border = (0, 30, 0, 30) # left, up, right, bottom
ImageOps.crop(img, border)

ASP.NET email validator regex

Apart from the client side validation with a Validator, I also recommend doing server side validation as well.

bool isValidEmail(string input)
{
    try
    {
        var email = new System.Net.Mail.MailAddress(input);
        return true;
    }
    catch
    {
        return false;
    }
}

Powershell import-module doesn't find modules

My finding with PS 5.0 on Windows 7: $ENV:PsModulePath has to end with a . This normally means it will load all modules in that path.

I'm not able to add a single module to $env:PsModulePath and get it to load with Import-Module ExampleModule. I have to use the full path to the module. e.g. C:\MyModules\ExampleModule. I am sure it used to work.

For example: Say I have the modules:

C:\MyModules\ExampleModule
C:\MyModules\FishingModule

I need to add C:\MyModules\ to $env:PsModulePath, which will allow me to do

Import-Module ExampleModule
Import-Module FishingModule

If for some reason, I didn't want FishingModule, I thought I could add C:\MyModules\ExampleModule only (no trailing \), but this doesn't seem to work now. To load it, I have to Import-Module C:\MyModules\ExampleModule

Interestingly, in both cases, doing Get-Module -ListAvailable, shows the modules, but it won't import. Although, the module's cmdlets seem to work anyway.

AFAIK, to get the automatic import to work, one has to add the name of the function to FunctionsToExport in the manifest (.psd1) file. Adding FunctionsToExport = '*', breaks the auto load. You can still have Export-ModuleMember -Function * in the module file (.psm1).

These are my findings. Whether there's been a change or my computer is broken, remains to be seen. HTH

How Do I Take a Screen Shot of a UIView?

iOS 7 has a new method that allows you to draw a view hierarchy into the current graphics context. This can be used to get an UIImage very fast.

I implemented a category method on UIView to get the view as an UIImage:

- (UIImage *)pb_takeSnapshot {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);

    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];

    // old style [self.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

It is considerably faster then the existing renderInContext: method.

Reference: https://developer.apple.com/library/content/qa/qa1817/_index.html

UPDATE FOR SWIFT: An extension that does the same:

extension UIView {

    func pb_takeSnapshot() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)

        drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)

        // old style: layer.renderInContext(UIGraphicsGetCurrentContext())

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

UPDATE FOR SWIFT 3

    UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)

    drawHierarchy(in: self.bounds, afterScreenUpdates: true)

    let image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image

SQL GROUP BY CASE statement with aggregate function

While Shannon's answer is technically correct, it looks like overkill.

The simple solution is that you need to put your summation outside of the case statement. This should do the trick:

sum(CASE WHEN col1 > col2 THEN col3*col4 ELSE 0 END) AS some_product

Basically, your old code tells SQL to execute the sum(X*Y) for each line individually (leaving each line with its own answer that can't be grouped).

The code line I have written takes the sum product, which is what you want.

Unique random string generation

I am surprised why there is not a CrytpoGraphic solution in place. GUID is unique but not cryptographically safe. See this Dotnet Fiddle.

var bytes = new byte[40]; // byte size
using (var crypto = new RNGCryptoServiceProvider())
  crypto.GetBytes(bytes);

var base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

In case you want to Prepend with a Guid:

var result = Guid.NewGuid().ToString("N") + base64;
Console.WriteLine(result);

A cleaner alphanumeric string:

result = Regex.Replace(result,"[^A-Za-z0-9]","");
Console.WriteLine(result);

Add vertical scroll bar to panel

Add to your panel's style code something like this:

<asp:Panel ID="myPanel" runat="Server" CssClass="myPanelCSS" style="overflow-y:auto; overflow-x:hidden"></asp:Panel>

How to select the last record from MySQL table using SQL syntax

SELECT * FROM your_table ORDER BY id ASC LIMIT 0, 1

The ASC will return resultset in ascending order thereby leaving you with the latest or most recent record. The DESC counterpart will do the exact opposite. That is, return the oldest record.

assembly to compare two numbers

Compare two numbers. If it equals Yes "Y", it prints No "N" on the screen if it is not equal. I am using emu8086. You can use the SUB or CMP command.

MOV AX,5h
MOV BX,5h
SUB AX,BX 
JZ EQUALS
JNZ NOTEQUALS

EQUALS:
MOV CL,'Y'
JMP PRINT

NOTEQUALS:
MOV CL,'N'

PRINT:
MOV AH,2
MOV DL,CL
INT 21H

RET

enter image description here

Difference between mkdir() and mkdirs() in java for java.io.File

mkdir()

creates only one directory at a time, if it is parent that one only. other wise it can create the sub directory(if the specified path is existed only) and do not create any directories in between any two directories. so it can not create smultiple directories in one directory

mkdirs()

create the multiple directories(in between two directories also) at a time.

How are booleans formatted in Strings in Python?

If you want True False use:

"%s %s" % (True, False)

because str(True) is 'True' and str(False) is 'False'.

or if you want 1 0 use:

"%i %i" % (True, False)

because int(True) is 1 and int(False) is 0.

Copy and Paste a set range in the next empty row

You could also try this

Private Sub CommandButton1_Click()

Sheets("Sheet1").Range("A3:E3").Copy

Dim lastrow As Long
lastrow = Range("A65536").End(xlUp).Row

Sheets("Summary Info").Activate
Cells(lastrow + 1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

End Sub

Get request URL in JSP which is forwarded by Servlet

None of these attributes are reliable because per the servlet spec (2.4, 2.5 and 3.0), these attributes are overridden if you include/forward a second time (or if someone calls getNamedDispatcher). I think the only reliable way to get the original request URI/query string is to stick a filter at the beginning of your filter chain in web.xml that sets your own custom request attributes based on request.getRequestURI()/getQueryString() before any forwards/includes take place.

http://www.caucho.com/resin-3.0/webapp/faq.xtp contains an excellent summary of how this works (minus the technical note that a second forward/include messes up your ability to use these attributes).

What is "Linting"?

Apart from what others have mentioned, I would like to add that, Linting will run through your source code to find

 -  formatting discrepancy 
 -  non-adherence to coding standards and conventions 
 -  pinpointing possible logical errors in your program

Running a Lint program over your source code, helps to ensure that source code is legible, readable, less polluted and easier to maintain.

JQuery, select first row of table

Ok so if an image in a table is clicked you want the data of the first row of the table this image is in.

//image click stuff here {
$(this). // our image
closest('table'). // Go upwards through our parents untill we hit the table
children('tr:first'); // Select the first row we find

var $row = $(this).closest('table').children('tr:first');

parent() will only get the direct parent, closest should do what we want here. From jQuery docs: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

Android: Pass data(extras) to a fragment

There is a simple why that I prefered to the bundle due to the no duplicate data in memory. It consists of a init public method for the fragment

private ArrayList<Music> listMusics = new ArrayList<Music>();
private ListView listMusic;


public static ListMusicFragment createInstance(List<Music> music) {
    ListMusicFragment fragment = new ListMusicFragment();
    fragment.init(music);
    return fragment;
}

public void init(List<Music> music){
    this.listMusic = music;
}

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

    View view = inflater.inflate(R.layout.musiclistview, container, false);
    listMusic = (ListView) view.findViewById(R.id.musicListView);
    listMusic.setAdapter(new MusicBaseAdapter(getActivity(), listMusics));

    return view;
}
}

In two words, you create an instance of the fragment an by the init method (u can call it as u want) you pass the reference of your list without create a copy by serialization to the instance of the fragment. This is very usefull because if you change something in the list u will get it in the other parts of the app and ofcourse, you use less memory.

Setting cursor at the end of any text of a textbox

There are multiple options:

txtBox.Focus();
txtBox.SelectionStart = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.CaretIndex = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.Select(txtBox.Text.Length, 0);

Pass an array of integers to ASP.NET Web API?

My solution was to create an attribute to validate strings, it does a bunch of extra common features, including regex validation that you can use to check for numbers only and then later I convert to integers as needed...

This is how you use:

public class MustBeListAndContainAttribute : ValidationAttribute
{
    private Regex regex = null;
    public bool RemoveDuplicates { get; }
    public string Separator { get; }
    public int MinimumItems { get; }
    public int MaximumItems { get; }

    public MustBeListAndContainAttribute(string regexEachItem,
        int minimumItems = 1,
        int maximumItems = 0,
        string separator = ",",
        bool removeDuplicates = false) : base()
    {
        this.MinimumItems = minimumItems;
        this.MaximumItems = maximumItems;
        this.Separator = separator;
        this.RemoveDuplicates = removeDuplicates;

        if (!string.IsNullOrEmpty(regexEachItem))
            regex = new Regex(regexEachItem, RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var listOfdValues = (value as List<string>)?[0];

        if (string.IsNullOrWhiteSpace(listOfdValues))
        {
            if (MinimumItems > 0)
                return new ValidationResult(this.ErrorMessage);
            else
                return null;
        };

        var list = new List<string>();

        list.AddRange(listOfdValues.Split(new[] { Separator }, System.StringSplitOptions.RemoveEmptyEntries));

        if (RemoveDuplicates) list = list.Distinct().ToList();

        var prop = validationContext.ObjectType.GetProperty(validationContext.MemberName);
        prop.SetValue(validationContext.ObjectInstance, list);
        value = list;

        if (regex != null)
            if (list.Any(c => string.IsNullOrWhiteSpace(c) || !regex.IsMatch(c)))
                return new ValidationResult(this.ErrorMessage);

        return null;
    }
}

Fixed GridView Header with horizontal and vertical scrolling in asp.net

// create this Js and add reference

var GridViewScrollOptions = /** @class */ (function () {
    function GridViewScrollOptions() {
    }
    return GridViewScrollOptions;
}());

var GridViewScroll = /** @class */ (function ()
 {

    function GridViewScroll(options) {
        this._initialized = false;
        if (options.elementID == null)
            options.elementID = "";
        if (options.width == null)
            options.width = "700";
        if (options.height == null)
            options.height = "350";
        if (options.freezeColumnCssClass == null)
            options.freezeColumnCssClass = "";
        if (options.freezeFooterCssClass == null)
            options.freezeFooterCssClass = "";
        if (options.freezeHeaderRowCount == null)
            options.freezeHeaderRowCount = 1;
        if (options.freezeColumnCount == null)
            options.freezeColumnCount = 1;
        this.initializeOptions(options);
    }
    GridViewScroll.prototype.initializeOptions = function (options) {
        this.GridID = options.elementID;
        this.GridWidth = options.width;
        this.GridHeight = options.height;
        this.FreezeColumn = options.freezeColumn;
        this.FreezeFooter = options.freezeFooter;
        this.FreezeColumnCssClass = options.freezeColumnCssClass;
        this.FreezeFooterCssClass = options.freezeFooterCssClass;
        this.FreezeHeaderRowCount = options.freezeHeaderRowCount;
        this.FreezeColumnCount = options.freezeColumnCount;
    };

    GridViewScroll.prototype.enhance = function () 
{

        this.FreezeCellWidths = [];
        this.IsVerticalScrollbarEnabled = false;
        this.IsHorizontalScrollbarEnabled = false;
        if (this.GridID == null || this.GridID == "")
 {

            return;
        }

        this.ContentGrid = document.getElementById(this.GridID);
        if (this.ContentGrid == null) {

            return;
        }
        if (this.ContentGrid.rows.length < 2) {


            return;
        }
        if (this._initialized) {

            this.undo();
        }

        this._initialized = true;
        this.Parent = this.ContentGrid.parentNode;
        this.ContentGrid.style.display = "none";
        if (typeof this.GridWidth == 'string' && this.GridWidth.indexOf("%") > -1) {
            var percentage = parseInt(this.GridWidth);
            this.Width = this.Parent.offsetWidth * percentage / 100;
        }
        else {

            this.Width = parseInt(this.GridWidth);
        }
        if (typeof this.GridHeight == 'string' && this.GridHeight.indexOf("%") > -1) {


            var percentage = parseInt(this.GridHeight);
            this.Height = this.Parent.offsetHeight * percentage / 100;
        }
        else {

            this.Height = parseInt(this.GridHeight);
        }

        this.ContentGrid.style.display = "";
        this.ContentGridHeaderRows = this.getGridHeaderRows();
        this.ContentGridItemRow = this.ContentGrid.rows.item(this.FreezeHeaderRowCount);
        var footerIndex = this.ContentGrid.rows.length - 1;
        this.ContentGridFooterRow = this.ContentGrid.rows.item(footerIndex);
        this.Content = document.createElement('div');
        this.Content.id = this.GridID + "_Content";
        this.Content.style.position = "relative";
        this.Content = this.Parent.insertBefore(this.Content, this.ContentGrid);
        this.ContentFixed = document.createElement('div');
        this.ContentFixed.id = this.GridID + "_Content_Fixed";
        this.ContentFixed.style.overflow = "auto";
        this.ContentFixed = this.Content.appendChild(this.ContentFixed);
        this.ContentGrid = this.ContentFixed.appendChild(this.ContentGrid);
        this.ContentFixed.style.width = String(this.Width) + "px";
        if (this.ContentGrid.offsetWidth > this.Width) {

            this.IsHorizontalScrollbarEnabled = true;
        }

        if (this.ContentGrid.offsetHeight > this.Height) {

            this.IsVerticalScrollbarEnabled = true;
        }

        this.Header = document.createElement('div');
        this.Header.id = this.GridID + "_Header";
        this.Header.style.backgroundColor = "#F0F0F0";
        this.Header.style.position = "relative";
        this.HeaderFixed = document.createElement('div');
        this.HeaderFixed.id = this.GridID + "_Header_Fixed";
        this.HeaderFixed.style.overflow = "hidden";
        this.Header = this.Parent.insertBefore(this.Header, this.Content);
        this.HeaderFixed = this.Header.appendChild(this.HeaderFixed);
        this.ScrollbarWidth = this.getScrollbarWidth();
        this.prepareHeader();
        this.calculateHeader();
        this.Header.style.width = String(this.Width) + "px";
        if (this.IsVerticalScrollbarEnabled) {

            this.HeaderFixed.style.width = String(this.Width - this.ScrollbarWidth) + "px";
            if (this.IsHorizontalScrollbarEnabled) {

                this.ContentFixed.style.width = this.HeaderFixed.style.width;
                if (this.isRTL()) {

                    this.ContentFixed.style.paddingLeft = String(this.ScrollbarWidth) + "px";
                }

                else {

                    this.ContentFixed.style.paddingRight = String(this.ScrollbarWidth) + "px";
                }

            }

            this.ContentFixed.style.height = String(this.Height - this.Header.offsetHeight) + "px";
        }

        else {

            this.HeaderFixed.style.width = this.Header.style.width;
            this.ContentFixed.style.width = this.Header.style.width;
        }

        if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {

            this.appendFreezeHeader();
            this.appendFreezeContent();
        }
        if (this.FreezeFooter && this.IsVerticalScrollbarEnabled) {

            this.appendFreezeFooter();
            if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {


                this.appendFreezeFooterColumn();
            }
        }
        var self = this;
        this.ContentFixed.onscroll = function (event) {

            self.HeaderFixed.scrollLeft = self.ContentFixed.scrollLeft;
            if (self.ContentFreeze != null)
                self.ContentFreeze.scrollTop = self.ContentFixed.scrollTop;
            if (self.FooterFreeze != null)
                self.FooterFreeze.scrollLeft = self.ContentFixed.scrollLeft;
        };
    };
    GridViewScroll.prototype.getGridHeaderRows = function () {



        var gridHeaderRows = new Array();
        for (var i = 0; i < this.FreezeHeaderRowCount; i++) {

            gridHeaderRows.push(this.ContentGrid.rows.item(i));

        }
        return gridHeaderRows;
    };
    GridViewScroll.prototype.prepareHeader = function () {

        this.HeaderGrid = this.ContentGrid.cloneNode(false);
        this.HeaderGrid.id = this.GridID + "_Header_Fixed_Grid";
        this.HeaderGrid = this.HeaderFixed.appendChild(this.HeaderGrid);
        this.prepareHeaderGridRows();
        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            this.appendHelperElement(this.ContentGridItemRow.cells.item(i));
            this.appendHelperElement(this.HeaderGridHeaderCells[i]);
        }
    };
    GridViewScroll.prototype.prepareHeaderGridRows = function () {

        this.HeaderGridHeaderRows = new Array();
        for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
            var gridHeaderRow = this.ContentGridHeaderRows[i];
            var headerGridHeaderRow = gridHeaderRow.cloneNode(true);
            this.HeaderGridHeaderRows.push(headerGridHeaderRow);
            this.HeaderGrid.appendChild(headerGridHeaderRow);
        }

        this.prepareHeaderGridCells();
    };
    GridViewScroll.prototype.prepareHeaderGridCells = function () {

        this.HeaderGridHeaderCells = new Array();
        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            for (var rowIndex in this.HeaderGridHeaderRows) {


                var cgridHeaderRow = this.HeaderGridHeaderRows[rowIndex];
                var fixedCellIndex = 0;
                for (var cellIndex = 0; cellIndex < cgridHeaderRow.cells.length; cellIndex++) {
                    var cgridHeaderCell = cgridHeaderRow.cells.item(cellIndex);
                    if (cgridHeaderCell.colSpan == 1 && i == fixedCellIndex) {

                        this.HeaderGridHeaderCells.push(cgridHeaderCell);
                    }
                    else {
                        fixedCellIndex += cgridHeaderCell.colSpan - 1;
                    }
                    fixedCellIndex++;
                }
            }
        }
    };
    GridViewScroll.prototype.calculateHeader = function () {

        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            var gridItemCell = this.ContentGridItemRow.cells.item(i);
            var helperElement = gridItemCell.firstChild;
            var helperWidth = parseInt(String(helperElement.offsetWidth));
            this.FreezeCellWidths.push(helperWidth);
            helperElement.style.width = helperWidth + "px";
            helperElement = this.HeaderGridHeaderCells[i].firstChild;
            helperElement.style.width = helperWidth + "px";
        }
        for (var i = 0; i < this.FreezeHeaderRowCount; i++) {

            this.ContentGridHeaderRows[i].style.display = "none";
        }
    };
    GridViewScroll.prototype.appendFreezeHeader = function () {

        this.HeaderFreeze = document.createElement('div');
        this.HeaderFreeze.id = this.GridID + "_Header_Freeze";
        this.HeaderFreeze.style.position = "absolute";
        this.HeaderFreeze.style.overflow = "hidden";
        this.HeaderFreeze.style.top = "0px";
        this.HeaderFreeze.style.left = "0px";
        this.HeaderFreeze.style.width = "";
        this.HeaderFreezeGrid = this.HeaderGrid.cloneNode(false);
        this.HeaderFreezeGrid.id = this.GridID + "_Header_Freeze_Grid";
        this.HeaderFreezeGrid = this.HeaderFreeze.appendChild(this.HeaderFreezeGrid);
        this.HeaderFreezeGridHeaderRows = new Array();
        for (var i = 0; i < this.HeaderGridHeaderRows.length; i++) {

            var headerFreezeGridHeaderRow = this.HeaderGridHeaderRows[i].cloneNode(false);
            this.HeaderFreezeGridHeaderRows.push(headerFreezeGridHeaderRow);
            var columnIndex = 0;
            var columnCount = 0;
            while (columnCount < this.FreezeColumnCount) {

                var freezeColumn = this.HeaderGridHeaderRows[i].cells.item(columnIndex).cloneNode(true);
                headerFreezeGridHeaderRow.appendChild(freezeColumn);
                columnCount += freezeColumn.colSpan;
                columnIndex++;
            }
            this.HeaderFreezeGrid.appendChild(headerFreezeGridHeaderRow);
        }
        this.HeaderFreeze = this.Header.appendChild(this.HeaderFreeze);
    };
    GridViewScroll.prototype.appendFreezeContent = function () {

        this.ContentFreeze = document.createElement('div');
        this.ContentFreeze.id = this.GridID + "_Content_Freeze";
        this.ContentFreeze.style.position = "absolute";
        this.ContentFreeze.style.overflow = "hidden";
        this.ContentFreeze.style.top = "0px";
        this.ContentFreeze.style.left = "0px";
        this.ContentFreeze.style.width = "";
        this.ContentFreezeGrid = this.HeaderGrid.cloneNode(false);
        this.ContentFreezeGrid.id = this.GridID + "_Content_Freeze_Grid";
        this.ContentFreezeGrid = this.ContentFreeze.appendChild(this.ContentFreezeGrid);
        var freezeCellHeights = [];
        var paddingTop = this.getPaddingTop(this.ContentGridItemRow.cells.item(0));
        var paddingBottom = this.getPaddingBottom(this.ContentGridItemRow.cells.item(0));
        for (var i = 0; i < this.ContentGrid.rows.length; i++) {

            var gridItemRow = this.ContentGrid.rows.item(i);
            var gridItemCell = gridItemRow.cells.item(0);
            var helperElement = void 0;
            if (gridItemCell.firstChild.className == "gridViewScrollHelper") {

                helperElement = gridItemCell.firstChild;
            }
            else {
                helperElement = this.appendHelperElement(gridItemCell);
            }
            var helperHeight = parseInt(String(gridItemCell.offsetHeight - paddingTop - paddingBottom));
            freezeCellHeights.push(helperHeight);
            var cgridItemRow = gridItemRow.cloneNode(false);
            var cgridItemCell = gridItemCell.cloneNode(true);
            if (this.FreezeColumnCssClass != null || this.FreezeColumnCssClass != "")
                cgridItemRow.className = this.FreezeColumnCssClass;
            var columnIndex = 0;
            var columnCount = 0;
            while (columnCount < this.FreezeColumnCount) {

                var freezeColumn = gridItemRow.cells.item(columnIndex).cloneNode(true);
                cgridItemRow.appendChild(freezeColumn);
                columnCount += freezeColumn.colSpan;
                columnIndex++;
            }
            this.ContentFreezeGrid.appendChild(cgridItemRow);
        }
        for (var i = 0; i < this.ContentGrid.rows.length; i++) {

            var gridItemRow = this.ContentGrid.rows.item(i);
            var gridItemCell = gridItemRow.cells.item(0);
            var cgridItemRow = this.ContentFreezeGrid.rows.item(i);
            var cgridItemCell = cgridItemRow.cells.item(0);
            var helperElement = gridItemCell.firstChild;
            helperElement.style.height = String(freezeCellHeights[i]) + "px";
            helperElement = cgridItemCell.firstChild;
            helperElement.style.height = String(freezeCellHeights[i]) + "px";
        }
        if (this.IsVerticalScrollbarEnabled) {
            this.ContentFreeze.style.height = String(this.Height - this.Header.offsetHeight - this.ScrollbarWidth) + "px";
        }
        else {
            this.ContentFreeze.style.height = String(this.ContentFixed.offsetHeight - this.ScrollbarWidth) + "px";
        }
        this.ContentFreeze = this.Content.appendChild(this.ContentFreeze);
    };
    GridViewScroll.prototype.appendFreezeFooter = function () {

        this.FooterFreeze = document.createElement('div');
        this.FooterFreeze.id = this.GridID + "_Footer_Freeze";
        this.FooterFreeze.style.position = "absolute";
        this.FooterFreeze.style.overflow = "hidden";
        this.FooterFreeze.style.left = "0px";
        this.FooterFreeze.style.width = String(this.ContentFixed.offsetWidth - this.ScrollbarWidth) + "px";
        this.FooterFreezeGrid = this.HeaderGrid.cloneNode(false);
        this.FooterFreezeGrid.id = this.GridID + "_Footer_Freeze_Grid";
        this.FooterFreezeGrid = this.FooterFreeze.appendChild(this.FooterFreezeGrid);
        this.FooterFreezeGridHeaderRow = this.ContentGridFooterRow.cloneNode(true);
        if (this.FreezeFooterCssClass != null || this.FreezeFooterCssClass != "")
            this.FooterFreezeGridHeaderRow.className = this.FreezeFooterCssClass;
        for (var i = 0; i < this.FooterFreezeGridHeaderRow.cells.length; i++) {

            var cgridHeaderCell = this.FooterFreezeGridHeaderRow.cells.item(i);
            var helperElement = this.appendHelperElement(cgridHeaderCell);
            helperElement.style.width = String(this.FreezeCellWidths[i]) + "px";
        }
        this.FooterFreezeGridHeaderRow = this.FooterFreezeGrid.appendChild(this.FooterFreezeGridHeaderRow);
        this.FooterFreeze = this.Content.appendChild(this.FooterFreeze);
        var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
        if (this.IsHorizontalScrollbarEnabled) {

            footerFreezeTop -= this.ScrollbarWidth;
        }
        this.FooterFreeze.style.top = String(footerFreezeTop) + "px";
    };
    GridViewScroll.prototype.appendFreezeFooterColumn = function () {

        this.FooterFreezeColumn = document.createElement('div');
        this.FooterFreezeColumn.id = this.GridID + "_Footer_FreezeColumn";
        this.FooterFreezeColumn.style.position = "absolute";
        this.FooterFreezeColumn.style.overflow = "hidden";
        this.FooterFreezeColumn.style.left = "0px";
        this.FooterFreezeColumn.style.width = "";
        this.FooterFreezeColumnGrid = this.HeaderGrid.cloneNode(false);
        this.FooterFreezeColumnGrid.id = this.GridID + "_Footer_FreezeColumn_Grid";
        this.FooterFreezeColumnGrid = this.FooterFreezeColumn.appendChild(this.FooterFreezeColumnGrid);
        this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeGridHeaderRow.cloneNode(false);
        this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeColumnGrid.appendChild(this.FooterFreezeColumnGridHeaderRow);
        if (this.FreezeFooterCssClass != null)
            this.FooterFreezeColumnGridHeaderRow.className = this.FreezeFooterCssClass;
        var columnIndex = 0;
        var columnCount = 0;
        while (columnCount < this.FreezeColumnCount) {

            var freezeColumn = this.FooterFreezeGridHeaderRow.cells.item(columnIndex).cloneNode(true);
            this.FooterFreezeColumnGridHeaderRow.appendChild(freezeColumn);
            columnCount += freezeColumn.colSpan;
            columnIndex++;
        }
        var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
        if (this.IsHorizontalScrollbarEnabled) {

            footerFreezeTop -= this.ScrollbarWidth;
        }
        this.FooterFreezeColumn.style.top = String(footerFreezeTop) + "px";
        this.FooterFreezeColumn = this.Content.appendChild(this.FooterFreezeColumn);
    };
    GridViewScroll.prototype.appendHelperElement = function (gridItemCell) {

        var helperElement = document.createElement('div');
        helperElement.className = "gridViewScrollHelper";
        while (gridItemCell.hasChildNodes()) {

            helperElement.appendChild(gridItemCell.firstChild);
        }
        return gridItemCell.appendChild(helperElement);
    };
    GridViewScroll.prototype.getScrollbarWidth = function () {

        var innerElement = document.createElement('p');
        innerElement.style.width = "100%";
        innerElement.style.height = "200px";
        var outerElement = document.createElement('div');
        outerElement.style.position = "absolute";
        outerElement.style.top = "0px";
        outerElement.style.left = "0px";
        outerElement.style.visibility = "hidden";
        outerElement.style.width = "200px";
        outerElement.style.height = "150px";
        outerElement.style.overflow = "hidden";
        outerElement.appendChild(innerElement);
        document.body.appendChild(outerElement);
        var innerElementWidth = innerElement.offsetWidth;
        outerElement.style.overflow = 'scroll';
        var outerElementWidth = innerElement.offsetWidth;
        if (innerElementWidth === outerElementWidth)
            outerElementWidth = outerElement.clientWidth;
        document.body.removeChild(outerElement);
        return innerElementWidth - outerElementWidth;
    };
    GridViewScroll.prototype.isRTL = function () {

        var direction = "";
        if (window.getComputedStyle) {

            direction = window.getComputedStyle(this.ContentGrid, null).getPropertyValue('direction');
        }
        else {
            direction = this.ContentGrid.currentStyle.direction;
        }
        return direction === "rtl";
    };
    GridViewScroll.prototype.getPaddingTop = function (element) {

        var value = "";
        if (window.getComputedStyle) {

            value = window.getComputedStyle(element, null).getPropertyValue('padding-Top');
        }
        else {

            value = element.currentStyle.paddingTop;
        }
        return parseInt(value);
    };
    GridViewScroll.prototype.getPaddingBottom = function (element) {
        var value = "";

        if (window.getComputedStyle) {

            value = window.getComputedStyle(element, null).getPropertyValue('padding-Bottom');
        }
        else {

            value = element.currentStyle.paddingBottom;
        }
        return parseInt(value);
    };
    GridViewScroll.prototype.undo = function () {

        this.undoHelperElement();
        for (var _i = 0, _a = this.ContentGridHeaderRows; _i < _a.length; _i++) {
            var contentGridHeaderRow = _a[_i];
            contentGridHeaderRow.style.display = "";
        }
        this.Parent.insertBefore(this.ContentGrid, this.Header);
        this.Parent.removeChild(this.Header);
        this.Parent.removeChild(this.Content);
        this._initialized = false;
    };
    GridViewScroll.prototype.undoHelperElement = function () {

        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            var gridItemCell = this.ContentGridItemRow.cells.item(i);
            var helperElement = gridItemCell.firstChild;
            while (helperElement.hasChildNodes()) {

                gridItemCell.appendChild(helperElement.firstChild);
            }
            gridItemCell.removeChild(helperElement);
        }
        if (this.FreezeColumn) {

            for (var i = 2; i < this.ContentGrid.rows.length; i++) {

                var gridItemRow = this.ContentGrid.rows.item(i);
                var gridItemCell = gridItemRow.cells.item(0);
                var helperElement = gridItemCell.firstChild;
                while (helperElement.hasChildNodes()) {


                    gridItemCell.appendChild(helperElement.firstChild);
                }
                gridItemCell.removeChild(helperElement);
            }
        }
    };
    return GridViewScroll;
}());

//add On Head

<head runat="server">
    <title></title>

    <script src="client/js/jquery-3.1.1.min.js"></script>

    <script src="js/gridviewscroll.js"></script>

    <script type="text/javascript">
        window.onload = function () {

            var gridViewScroll = new GridViewScroll({
                elementID: "GridView1" // [Header is fix column will be Freeze ][1]Target Control
            });
            gridViewScroll.enhance();
        }
    </script>

</head>

//Add on Body

<body>
    <form id="form1" runat="server">

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">

       // <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

           <%-- <Columns>
                <asp:BoundField DataField="SHIPMENT_ID" HeaderText="SHIPMENT_ID"
                    ReadOnly="True" SortExpression="SHIPMENT_ID" />
                <asp:BoundField DataField="TypeValue" HeaderText="TypeValue"
                    SortExpression="TypeValue" />
                <asp:BoundField DataField="CHAId" HeaderText="CHAId"
                    SortExpression="CHAId" />
                <asp:BoundField DataField="Status" HeaderText="Status"
                    SortExpression="Status" />
            </Columns>--%>
        </asp:GridView>

Can’t delete docker image with dependent child images

Suppose we have a Dockerfile

FROM ubuntu:trusty
CMD ping localhost

We build image from that without TAG or naming

docker build .

Now we have a success report "Successfully built 57ca5ce94d04" If we see the docker images

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
<none>              <none>              57ca5ce94d04        18 seconds ago      188MB
ubuntu              trusty              8789038981bc        11 days ago         188MB

We need to first remove the docker rmi 57ca5ce94d04

Followed by

docker rmi 8789038981bc

By that image will be removed!

A forced removal of all as suggested by someone

docker rmi $(docker images -q) -f

Prime numbers between 1 to 100 in C Programming Language

#include<stdio.h>
int main()
{
    int a,b,i,c,j;
    printf("\n Enter the two no. in between you want to check:");
    scanf("%d%d",&a,&c);
    printf("%d-%d\n",a,c);
    for(j=a;j<=c;j++)
    {
        b=0;
        for(i=1;i<=c;i++)
        {
            if(j%i==0)
            {
                 b++;
            }
        }
        if(b==2)
        {
            printf("\nPrime number:%d\n",j);
        }
        else
        {
            printf("\n\tNot prime:%d\n",j);
        }
    }
}

Description Box using "onmouseover"

The CSS Tooltip allows you to format the popup as you like as any div section! And no Javascript needed.

"Fatal error: Cannot redeclare <function>"

or you can't create function in loop

  • such as

    for($i=1; $i<5; $i++) { function foo() { echo 'something'; } }

foo();
//It will show error regarding redeclaration

How to conditional format based on multiple specific text in Excel

You can use MATCH for instance.

  1. Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.

  2. In the entry box, put:

    =MATCH(A2, 'Sheet2'!A:A, 0)
    
  3. Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.

MATCH takes the value A2 from your data table, looks into 'Sheet2'!A:A and if there's an exact match (that's why there's a 0 at the end), then it'll return the row number.

Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.

EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:

=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))

In Linux, how to tell how much memory processes are using?

In case you don't have a current or long running process to track, you can use /usr/bin/time.

This is not the same as Bash time (as you will see).

Eg

# /usr/bin/time -f "%M" echo

2028

This is "Maximum resident set size of the process during its lifetime, in Kilobytes" (quoted from the man page). That is, the same as RES in top et al.

There are a lot more you can get from /usr/bin/time.

# /usr/bin/time -v echo

Command being timed: "echo"
User time (seconds): 0.00
System time (seconds): 0.00
Percent of CPU this job got: 0%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 1988
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 77
Voluntary context switches: 1
Involuntary context switches: 0
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0

web.xml is missing and <failOnMissingWebXml> is set to true

Select your project and select the "Deployment Descriptor" option and then choose "Generate Deployment Descriptor stub"

MVC 4 Data Annotations "Display" Attribute

Also internationalization.

I fooled around with this some a while back. Did this in my model:

[Display(Name = "XXX", ResourceType = typeof(Labels))]

I had a separate class library for all the resources, so I had Labels.resx, Labels.culture.resx, etc.

In there I had key = XXX, value = "meaningful string in that culture."

MySQL JOIN with LIMIT 1 on joined table

I would try something like this:

SELECT C.*,
      (SELECT P.id, P.title 
       FROM products as P
       WHERE P.category_id = C.id
       LIMIT 1)
FROM categories C

how to check if a file is a directory or regular file in python?

os.path.isfile("bob.txt") # Does bob.txt exist?  Is it a file, or a directory?
os.path.isdir("bob")

How to create number input field in Flutter?

Here is code for numeric keyboard : keyboardType: TextInputType.phone When you add this code in textfield it will open numeric keyboard.

  final _mobileFocus = new FocusNode();
  final _mobile = TextEditingController();


     TextFormField(
          controller: _mobile,
          focusNode: _mobileFocus,
          maxLength: 10,
          keyboardType: TextInputType.phone,
          decoration: new InputDecoration(
            counterText: "",
            counterStyle: TextStyle(fontSize: 0),
            hintText: "Mobile",
            border: InputBorder.none,
            hintStyle: TextStyle(
              color: Colors.black,
                fontSize: 15.0.
            ),
          ),
          style: new TextStyle(
              color: Colors.black,
              fontSize: 15.0,
           ),
          );

Using psql to connect to PostgreSQL in SSL mode

psql "sslmode=require host=localhost port=2345 dbname=postgres" --username=some_user

According to the postgres psql documentation, only the connection parameters should go in the conninfo string(that's why in our example, --username is not inside that string)

Angular 2 Dropdown Options Default Value

Add a binding to the selected property, like this:

<option *ngFor="#workout of workouts" 
    [selected]="workout.name == 'back'">{{workout.name}}</option>

How can I position my div at the bottom of its container?

CodePen link here.

_x000D_
_x000D_
html, body {_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.overlay {_x000D_
    min-height: 100%;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.container {_x000D_
    width: 900px;_x000D_
    position: relative;_x000D_
    padding-bottom: 50px;_x000D_
}_x000D_
_x000D_
.height {_x000D_
    width: 900px;_x000D_
    height: 50px;_x000D_
}_x000D_
_x000D_
.footer {_x000D_
    width: 900px;_x000D_
    height: 50px;_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
}
_x000D_
<div class="overlay">_x000D_
    <div class="container">_x000D_
        <div class="height">_x000D_
            content_x000D_
        </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="footer">_x000D_
        footer_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You must enable the openssl extension to download files via https

Make sure that you update your php.ini for CLI. For my case this was C:\wamp\bin\php\php5.4.3\php.ini and uncomment extension=php_openssl.dll line.

Mongoose (mongodb) batch insert?

Sharing working and relevant code from our project:

//documentsArray is the list of sampleCollection objects
sampleCollection.insertMany(documentsArray)  
    .then((res) => {
        console.log("insert sampleCollection result ", res);
    })
    .catch(err => {
        console.log("bulk insert sampleCollection error ", err);
    });

Image resizing in React Native

{ flex: 1, height: undefined, width: undefined, resizeMode: 'contain' }

If you are using these attributes in your style prop in the <Image /> and the image is disappeared.

Put your image into a <View> tag. Like this:

<View 
  style={{
      width: '100%',
     height: '30%'
     }}
>
          <Image
            source={require('../logo.png')}
            style={{
              flex: 1,
              height: undefined,
              width: undefined,
              resizeMode: 'contain'
            }}
            resizeMode={'cover'}
          />
</View>

Give your view the width and height you want.

document.getElementById('btnid').disabled is not working in firefox and chrome

use setAttribute() and removeAttribute()

function disbtn(e) { 
    if ( someCondition == true ) {
       document.getElementById('btn1').setAttribute("disabled","disabled");
    } else {
       document.getElementById('btn1').removeAttribute("disabled");
    }
}

SEE DEMO

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

You can use JavaScript as well, in case the textfield is dithered.

WebDriver driver=new FirefoxDriver();
driver.get("http://localhost/login.do");
driver.manage().window().maximize();
RemoteWebDriver r=(RemoteWebDriver) driver;
String s1="document.getElementById('username').value='admin'";
r.executeScript(s1);

Difference between \n and \r?

Since nobody else mentioned it specifically (are they too young to know/remember?) - I suspect the use of \r\n originated for typewriters and similar devices.

When you wanted a new line while using a multi-line-capable typewriter, there were two physical actions it had to perform: slide the carriage back to the beginning (left, in US) of the page, and feed the paper up one notch.

Back in the days of line printers the only way to do bold text, for example, was to do a carriage return WITHOUT a newline and print the same characters over the old ones, thus adding more ink, thus making it appear darker (bolded). When the mechanical "newline" function failed in a typewriter, this was the annoying result: you could type over the previous line of text if you weren't paying attention.

How can I format a decimal to always show 2 decimal places?

>>> print "{:.2f}".format(1.123456)
1.12

You can change 2 in 2f to any number of decimal points you want to show.

EDIT:

From Python3.6, this translates to:

>>> print(f"{1.1234:.2f}")
1.12

Regular expression [Any number]

UPDATE: for your updated question

variable.match(/\[[0-9]+\]/);

Try this:

variable.match(/[0-9]+/);    // for unsigned integers
variable.match(/[-0-9]+/);   // for signed integers
variable.match(/[-.0-9]+/);  // for signed float numbers

Hope this helps!

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

I come up with this query

SELECT CASE (SELECT count(*) FROM pragma_table_info(''product'') c WHERE c.name = ''purchaseCopy'') WHEN 0 THEN ALTER TABLE product ADD purchaseCopy BLOB END
  • Inner query will return 0 or 1 if column exists.
  • Based on the result, alter the column

How to add a button dynamically in Android?

You could create a base layout for your button and dynamically change only what is specific, like this project I made to run different exercises from a Material Design course I'm taking:

In this example, I use a preconfigured AppCompatButton:

layout_base_button.xml

<android.support.v7.widget.AppCompatButton
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/btn_base"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="8dp"
    style="@style/RaisedButton"
    >

</android.support.v7.widget.AppCompatButton>


<style name="RaisedButton" parent="Widget.AppCompat.Button.Colored">
    <item name="android:textSize">11sp</item>
    <item name="android:textStyle">bold</item>
</style>

And in the MainActivity I created some instances and changed what I need, like the button text and onClick event:

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="udemy.android.materialdesign.MainActivity">

    <LinearLayout
        android:id="@+id/base_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

    </LinearLayout>


</ScrollView>



public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout baseLayout = findViewById(R.id.base_layout);

        baseLayout.addView(createButton("TextFields", baseLayout,
                view -> startActivity(createIntent(TextFieldsActivity.class))
        ));

        baseLayout.addView(createButton("Buttons", baseLayout,
                view -> startActivity(createIntent(ButtonsActivity.class))
        ));

        baseLayout.addView(createButton("Toolbar", baseLayout,
                view -> startActivity(createIntent(ToolbarActivity.class))
        ));

    }

    private View createButton(String text, LinearLayout baseLayout, View.OnClickListener onClickEvent) {
        View inflated = LayoutInflater.from(this).inflate(R.layout.layout_base_button, baseLayout, false);
        AppCompatButton btnBase = inflated.findViewById(R.id.btn_base);

        btnBase.setText(text);
        btnBase.setOnClickListener(onClickEvent);
        return btnBase;
    }

    private Intent createIntent(Class<?> cls) {
        return new Intent(this, cls);
    }
}

Sorry for being late...

How to pause javascript code execution for 2 seconds

You can use setTimeout to do this

function myFunction() {
    // your code to run after the timeout
}

// stop for sometime if needed
setTimeout(myFunction, 5000);

insert data into database using servlet and jsp in eclipse

Same problem fetch main problem in PreparedStatement use simple statement then you successfully insert record same use below.

String  st2="insert into 
user(gender,name,address,telephone,fax,email,
     destination,sdate,edate,Participant,hcategory,
     Culture,Nature,People,Cities,Beaches,Festivals,username,password) 
values('"+gender+"','"+name+"','"+address+"','"+phone+"','"+fax+"',
       '"+email+"','"+desti+"','"+sdate+"','"+edate+"','"+parti+"',
       '"+hotel+"','"+chk1+"','"+chk2+"','"+chk3+"','"+chk4+"',
       '"+chk5+"','"+chk6+"','"+user+"','"+password+"')";


int i=stm.executeUpdate(st2);

java.io.IOException: Broken pipe

The most common reason I've had for a "broken pipe" is that one machine (of a pair communicating via socket) has shut down its end of the socket before communication was complete. About half of those were because the program communicating on that socket had terminated.

If the program sending bytes sends them out and immediately shuts down the socket or terminates itself, it is possible for the socket to cease functioning before the bytes have been transmitted and read.

Try putting pauses anywhere you are shutting down the socket and before you allow the program to terminate to see if that helps.

FYI: "pipe" and "socket" are terms that get used interchangeably sometimes.

Why use #define instead of a variable

#define can accomplish some jobs that normal C++ cannot, like guarding headers and other tasks. However, it definitely should not be used as a magic number- a static const should be used instead.

Configuring ObjectMapper in Spring

In Spring Boot 2.2.x you need to configure it like this:

@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    return builder.build()
}

Kotlin:

@Bean
fun objectMapper(builder: Jackson2ObjectMapperBuilder) = builder.build()

Java Loop every minute

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();

Change package name for Android in React Native

Go to file android/app/src/main/AndroidManifest.xml -

Update :

attr android:label of Element application as :

Old value - android:label="@string/app_name"

New Value - android:label="(string you want to put)"

and

attr android:label of Element activity as :

Old value - android:label="@string/app_name"

New Value - android:label="(string you want to put)"

Worked for me, hopefully it will help.

How to check if a specified key exists in a given S3 bucket using Java

I also faced this problem when I used

String BaseFolder = "3patti_Logs"; 
S3Object object = s3client.getObject(bucketName, BaseFolder);
 

I got error key not found

When I hit and try

String BaseFolder = "3patti_Logs"; 
S3Object object = s3client.getObject(bucketName, BaseFolder+"/");

it worked , this code is working with 1.9 jar otherwise update to 1.11 and use doesObjectExist as said above

aspx page to redirect to a new page

In a special case within ASP.NET If you want to know if the page is redirected by a specified .aspx page and not another one, just put the information in a session name and take necessary action in the receiving Page_Load Event.

How do I uniquely identify computers visiting my web site?

There is a popular method called canvas fingerprinting, described in this scientific article: The Web Never Forgets: Persistent Tracking Mechanisms in the Wild. Once you start looking for it, you'll be surprised how frequently it is used. The method creates a unique fingerprint, which is consistent for each browser/hardware combination.

The article also reviews other persistent tracking methods, like evercookies, respawning http and Flash cookies, and cookie syncing.

More info about canvas fingerprinting here:

Update TextView Every Second

You can also use TimerTask for that.

Here is an method

private void setTimerTask() {
    long delay = 3000;
    long periodToRepeat = 60 * 1000; /* 1 mint */
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                 //   do your stuff here.
                }
            });
        }
    }, 3000, 3000);
}

How to get a certain element in a list, given the position?

If you frequently need to access the Nth element of a sequence, std::list, which is implemented as a doubly linked list, is probably not the right choice. std::vector or std::deque would likely be better.

That said, you can get an iterator to the Nth element using std::advance:

std::list<Object> l;
// add elements to list 'l'...

unsigned N = /* index of the element you want to retrieve */;
if (l.size() > N)
{
    std::list<Object>::iterator it = l.begin();
    std::advance(it, N);
    // 'it' points to the element at index 'N'
}

For a container that doesn't provide random access, like std::list, std::advance calls operator++ on the iterator N times. Alternatively, if your Standard Library implementation provides it, you may call std::next:

if (l.size() > N)
{
    std::list<Object>::iterator it = std::next(l.begin(), N);
}

std::next is effectively wraps a call to std::advance, making it easier to advance an iterator N times with fewer lines of code and fewer mutable variables. std::next was added in C++11.

Git Server Like GitHub?

Gitorious is an open source web interface to git that you can run on your own server, much like github:

http://getgitorious.com/

Update:

http://gitlab.org/ is another alternative now as well.

Update 2:

Gitorious has now joined with GitLab

What is a web service endpoint?

An Endpoint is specified as a relative or absolute url that usually results in a response. That response is usually the result of a server-side process that, could, for instance, produce a JSON string. That string can then be consumed by the application that made the call to the endpoint. So, in general endpoints are predefined access points, used within TCP/IP networks to initiate a process and/or return a response. Endpoints could contain parameters passed within the URL, as key value pairs, multiple key value pairs are separated by an ampersand, allowing the endpoint to call, for example, an update/insert process; so endpoints don’t always need to return a response, but a response is always useful, even if it is just to indicate the success or failure of an operation.

Search for a string in Enum and return the Enum

You can use Enum.Parse to get an enum value from the name. You can iterate over all values with Enum.GetNames, and you can just cast an int to an enum to get the enum value from the int value.

Like this, for example:

public MyColours GetColours(string colour)
{
    foreach (MyColours mc in Enum.GetNames(typeof(MyColours))) {
        if (mc.ToString().Contains(colour)) {
            return mc;
        }
    }
    return MyColours.Red; // Default value
}

or:

public MyColours GetColours(string colour)
{
    return (MyColours)Enum.Parse(typeof(MyColours), colour, true); // true = ignoreCase
}

The latter will throw an ArgumentException if the value is not found, you may want to catch it inside the function and return the default value.

How to return a specific status code and no contents from Controller?

The best way to do it is:

return this.StatusCode(StatusCodes.Status418ImATeapot, "Error message");

'StatusCodes' has every kind of return status and you can see all of them in this link https://httpstatuses.com/

Once you choose your StatusCode, return it with a message.

How to determine an interface{} value's "real" type?

Your example does work. Here's a simplified version.

package main

import "fmt"

func weird(i int) interface{} {
    if i < 0 {
        return "negative"
    }
    return i
}

func main() {
    var i = 42
    if w, ok := weird(7).(int); ok {
        i += w
    }
    if w, ok := weird(-100).(int); ok {
        i += w
    }
    fmt.Println("i =", i)
}

Output:
i = 49

It uses Type assertions.

Making a POST call instead of GET using urllib2

The requests module may ease your pain.

url = 'http://myserver/post_service'
data = dict(name='joe', age='10')

r = requests.post(url, data=data, allow_redirects=True)
print r.content

How does ApplicationContextAware work in Spring?

ApplicationContextAware Interface ,the current application context, through which you can invoke the spring container services. We can get current applicationContext instance injected by below method in the class

public void setApplicationContext(ApplicationContext context) throws BeansException.

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

How to determine a Python variable's type?

It really depends on what level you mean. In Python 2.x, there are two integer types, int (constrained to sys.maxint) and long (unlimited precision), for historical reasons. In Python code, this shouldn't make a bit of difference because the interpreter automatically converts to long when a number is too large. If you want to know about the actual data types used in the underlying interpreter, that's implementation dependent. (CPython's are located in Objects/intobject.c and Objects/longobject.c.) To find out about the systems types look at cdleary answer for using the struct module.

Switch php versions on commandline ubuntu 16.04

To list all available versions and choose from them :

sudo update-alternatives --config php

Or do manually

sudo a2dismod php7.1 // disable
sudo a2enmod php5.6  // enable

Using fonts with Rails asset pipeline

If you don't want to keep track of moving your fonts around:

# Adding Webfonts to the Asset Pipeline
config.assets.precompile << Proc.new { |path|
  if path =~ /\.(eot|svg|ttf|woff)\z/
    true
  end
}

How to concatenate two MP4 files using FFmpeg?

From the documentation here: https://trac.ffmpeg.org/wiki/Concatenate

If you have MP4 files, these could be losslessly concatenated by first transcoding them to MPEG-2 transport streams. With H.264 video and AAC audio, the following can be used:

ffmpeg -i input1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate1.ts
ffmpeg -i input2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate2.ts
ffmpeg -i "concat:intermediate1.ts|intermediate2.ts" -c copy -bsf:a aac_adtstoasc output.mp4

This approach works on all platforms.

I needed the ability to encapsulate this in a cross platform script, so I used fluent-ffmpeg and came up with the following solution:

const unlink = path =>
  new Promise((resolve, reject) =>
    fs.unlink(path, err => (err ? reject(err) : resolve()))
  )

const createIntermediate = file =>
  new Promise((resolve, reject) => {
    const out = `${Math.random()
      .toString(13)
      .slice(2)}.ts`

    ffmpeg(file)
      .outputOptions('-c', 'copy', '-bsf:v', 'h264_mp4toannexb', '-f', 'mpegts')
      .output(out)
      .on('end', () => resolve(out))
      .on('error', reject)
      .run()
  })

const concat = async (files, output) => {
  const names = await Promise.all(files.map(createIntermediate))
  const namesString = names.join('|')

  await new Promise((resolve, reject) =>
    ffmpeg(`concat:${namesString}`)
      .outputOptions('-c', 'copy', '-bsf:a', 'aac_adtstoasc')
      .output(output)
      .on('end', resolve)
      .on('error', reject)
      .run()
  )

  names.map(unlink)
}

concat(['file1.mp4', 'file2.mp4', 'file3.mp4'], 'output.mp4').then(() =>
  console.log('done!')
)

What is a superfast way to read large files line-by-line in VBA?

Be careful when using Application.Transpose with a huge number of values. If you transpose values to a column, excel will assume you are assuming you transposed them from rows.


Max Column Limit < Max Row Limit, and it will only display the first (Max Column Limit) values, and anithing after that will be "N/A"

Difference between string and text in rails?

String translates to "Varchar" in your database, while text translates to "text". A varchar can contain far less items, a text can be of (almost) any length.

For an in-depth analysis with good references check http://www.pythian.com/news/7129/text-vs-varchar/

Edit: Some database engines can load varchar in one go, but store text (and blob) outside of the table. A SELECT name, amount FROM products could, be a lot slower when using text for name than when you use varchar. And since Rails, by default loads records with SELECT * FROM... your text-columns will be loaded. This will probably never be a real problem in your or my app, though (Premature optimization is ...). But knowing that text is not always "free" is good to know.

How can I find the dimensions of a matrix in Python?

You simply can find a matrix dimension by using Numpy:

import numpy as np

x = np.arange(24).reshape((6, 4))
x.ndim

output will be:

2

It means this matrix is a 2 dimensional matrix.

x.shape

Will show you the size of each dimension. The shape for x is equal to:

(6, 4)

How can I parse String to Int in an Angular expression?

Not really great but a funny hack: You can -- instead of +

{{num_str -- 1 }}

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>_x000D_
<div ng-app>_x000D_
  {{'1'--1}}_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to calculate time elapsed in bash script?

Seconds

To measure elapsed time (in seconds) we need:

  • an integer that represents the count of elapsed seconds and
  • a way to convert such integer to an usable format.

An integer value of elapsed seconds:

  • There are two bash internal ways to find an integer value for the number of elapsed seconds:

    1. Bash variable SECONDS (if SECONDS is unset it loses its special property).

      • Setting the value of SECONDS to 0:

        SECONDS=0
        sleep 1  # Process to execute
        elapsedseconds=$SECONDS
        
      • Storing the value of the variable SECONDS at the start:

        a=$SECONDS
        sleep 1  # Process to execute
        elapsedseconds=$(( SECONDS - a ))
        
    2. Bash printf option %(datefmt)T:

      a="$(TZ=UTC0 printf '%(%s)T\n' '-1')"    ### `-1`  is the current time
      sleep 1                                  ### Process to execute
      elapsedseconds=$(( $(TZ=UTC0 printf '%(%s)T\n' '-1') - a ))
      

Convert such integer to an usable format

The bash internal printf can do that directly:

$ TZ=UTC0 printf '%(%H:%M:%S)T\n' 12345
03:25:45

similarly

$ elapsedseconds=$((12*60+34))
$ TZ=UTC0 printf '%(%H:%M:%S)T\n' "$elapsedseconds"
00:12:34

but this will fail for durations of more than 24 hours, as we actually print a wallclock time, not really a duration:

$ hours=30;mins=12;secs=24
$ elapsedseconds=$(( ((($hours*60)+$mins)*60)+$secs ))
$ TZ=UTC0 printf '%(%H:%M:%S)T\n' "$elapsedseconds"
06:12:24

For the lovers of detail, from bash-hackers.org:

%(FORMAT)T outputs the date-time string resulting from using FORMAT as a format string for strftime(3). The associated argument is the number of seconds since Epoch, or -1 (current time) or -2 (shell startup time). If no corresponding argument is supplied, the current time is used as default.

So you may want to just call textifyDuration $elpasedseconds where textifyDuration is yet another implementation of duration printing:

textifyDuration() {
   local duration=$1
   local shiff=$duration
   local secs=$((shiff % 60));  shiff=$((shiff / 60));
   local mins=$((shiff % 60));  shiff=$((shiff / 60));
   local hours=$shiff
   local splur; if [ $secs  -eq 1 ]; then splur=''; else splur='s'; fi
   local mplur; if [ $mins  -eq 1 ]; then mplur=''; else mplur='s'; fi
   local hplur; if [ $hours -eq 1 ]; then hplur=''; else hplur='s'; fi
   if [[ $hours -gt 0 ]]; then
      txt="$hours hour$hplur, $mins minute$mplur, $secs second$splur"
   elif [[ $mins -gt 0 ]]; then
      txt="$mins minute$mplur, $secs second$splur"
   else
      txt="$secs second$splur"
   fi
   echo "$txt (from $duration seconds)"
}

GNU date.

To get formated time we should use an external tool (GNU date) in several ways to get up to almost a year length and including Nanoseconds.

Math inside date.

There is no need for external arithmetic, do it all in one step inside date:

date -u -d "0 $FinalDate seconds - $StartDate seconds" +"%H:%M:%S"

Yes, there is a 0 zero in the command string. It is needed.

That's assuming you could change the date +"%T" command to a date +"%s" command so the values will be stored (printed) in seconds.

Note that the command is limited to:

  • Positive values of $StartDate and $FinalDate seconds.
  • The value in $FinalDate is bigger (later in time) than $StartDate.
  • Time difference smaller than 24 hours.
  • You accept an output format with Hours, Minutes and Seconds. Very easy to change.
  • It is acceptable to use -u UTC times. To avoid "DST" and local time corrections.

If you must use the 10:33:56 string, well, just convert it to seconds,
also, the word seconds could be abbreviated as sec:

string1="10:33:56"
string2="10:36:10"
StartDate=$(date -u -d "$string1" +"%s")
FinalDate=$(date -u -d "$string2" +"%s")
date -u -d "0 $FinalDate sec - $StartDate sec" +"%H:%M:%S"

Note that the seconds time conversion (as presented above) is relative to the start of "this" day (Today).


The concept could be extended to nanoseconds, like this:

string1="10:33:56.5400022"
string2="10:36:10.8800056"
StartDate=$(date -u -d "$string1" +"%s.%N")
FinalDate=$(date -u -d "$string2" +"%s.%N")
date -u -d "0 $FinalDate sec - $StartDate sec" +"%H:%M:%S.%N"

If is required to calculate longer (up to 364 days) time differences, we must use the start of (some) year as reference and the format value %j (the day number in the year):

Similar to:

string1="+10 days 10:33:56.5400022"
string2="+35 days 10:36:10.8800056"
StartDate=$(date -u -d "2000/1/1 $string1" +"%s.%N")
FinalDate=$(date -u -d "2000/1/1 $string2" +"%s.%N")
date -u -d "2000/1/1 $FinalDate sec - $StartDate sec" +"%j days %H:%M:%S.%N"

Output:
026 days 00:02:14.340003400

Sadly, in this case, we need to manually subtract 1 ONE from the number of days. The date command view the first day of the year as 1. Not that difficult ...

a=( $(date -u -d "2000/1/1 $FinalDate sec - $StartDate sec" +"%j days %H:%M:%S.%N") )
a[0]=$((10#${a[0]}-1)); echo "${a[@]}"



The use of long number of seconds is valid and documented here:
https://www.gnu.org/software/coreutils/manual/html_node/Examples-of-date.html#Examples-of-date


Busybox date

A tool used in smaller devices (a very small executable to install): Busybox.

Either make a link to busybox called date:

$ ln -s /bin/busybox date

Use it then by calling this date (place it in a PATH included directory).

Or make an alias like:

$ alias date='busybox date'

Busybox date has a nice option: -D to receive the format of the input time. That opens up a lot of formats to be used as time. Using the -D option we can convert the time 10:33:56 directly:

date -D "%H:%M:%S" -d "10:33:56" +"%Y.%m.%d-%H:%M:%S"

And as you can see from the output of the Command above, the day is assumed to be "today". To get the time starting on epoch:

$ string1="10:33:56"
$ date -u -D "%Y.%m.%d-%H:%M:%S" -d "1970.01.01-$string1" +"%Y.%m.%d-%H:%M:%S"
1970.01.01-10:33:56

Busybox date can even receive the time (in the format above) without -D:

$ date -u -d "1970.01.01-$string1" +"%Y.%m.%d-%H:%M:%S"
1970.01.01-10:33:56

And the output format could even be seconds since epoch.

$ date -u -d "1970.01.01-$string1" +"%s"
52436

For both times, and a little bash math (busybox can not do the math, yet):

string1="10:33:56"
string2="10:36:10"
t1=$(date -u -d "1970.01.01-$string1" +"%s")
t2=$(date -u -d "1970.01.01-$string2" +"%s")
echo $(( t2 - t1 ))

Or formatted:

$ date -u -D "%s" -d "$(( t2 - t1 ))" +"%H:%M:%S"
00:02:14

How do you represent a JSON array of strings?

I'll elaborate a bit more on ChrisR awesome answer and bring images from his awesome reference.

A valid JSON always starts with either curly braces { or square brackets [, nothing else.

{ will start an object:

left brace followed by a key string (a name that can't be repeated, in quotes), colon and a value (valid types shown below), followed by an optional comma to add more pairs of string and value at will and finished with a right brace

{ "key": value, "another key": value }

Hint: although javascript accepts single quotes ', JSON only takes double ones ".

[ will start an array:

left bracket followed by value, optional comma to add more value at will and finished with a right bracket

[value, value]

Hint: spaces among elements are always ignored by any JSON parser.

And value is an object, array, string, number, bool or null:

Image showing the 6 types a JSON value can be: string, number, JSON object, Array/list, boolean, and null

So yeah, ["a", "b"] is a perfectly valid JSON, like you could try on the link Manish pointed.

Here are a few extra valid JSON examples, one per block:

{}

[0]

{"__comment": "json doesn't accept comments and you should not be commenting even in this way", "avoid!": "also, never add more than one key per line, like this"}

[{   "why":null} ]

{
  "not true": [0, false],
  "true": true,
  "not null": [0, 1, false, true, {
    "obj": null
  }, "a string"]
}

DNS caching in linux

Firefox contains a dns cache. To disable the DNS cache:

  1. Open your browser
  2. Type in about:config in the address bar
  3. Right click on the list of Properties and select New > Integer in the Context menu
  4. Enter 'network.dnsCacheExpiration' as the preference name and 0 as the integer value

When disabled, Firefox will use the DNS cache provided by the OS.

SQL Server equivalent to MySQL enum data type?

CREATE FUNCTION ActionState_Preassigned()
RETURNS tinyint
AS
BEGIN
    RETURN 0
END

GO

CREATE FUNCTION ActionState_Unassigned()
RETURNS tinyint
AS
BEGIN
    RETURN 1
END

-- etc...

Where performance matters, still use the hard values.

Foreach with JSONArray and JSONObject

Make sure you are using this org.json: https://mvnrepository.com/artifact/org.json/json

if you are using Java 8 then you can use

import org.json.JSONArray;
import org.json.JSONObject;

JSONArray array = ...;

array.forEach(item -> {
    JSONObject obj = (JSONObject) item;
    parse(obj);
});

Just added a simple test to prove that it works:

Add the following dependency into your pom.xml file (To prove that it works, I have used the old jar which was there when I have posted this answer)

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>

And the simple test code snippet will be:

import org.json.JSONArray;
import org.json.JSONObject;

public class Test {
    public static void main(String args[]) {
        JSONArray array = new JSONArray();

        JSONObject object = new JSONObject();
        object.put("key1", "value1");

        array.put(object);

        array.forEach(item -> {
            System.out.println(item.toString());
        });
    }
}

output:

{"key1":"value1"}

Getting the size of an array in an object

Arrays have a property .length that returns the number of elements.

var st =
    {
        "itema":{},
        "itemb":
        [
            {"id":"s01","cd":"c01","dd":"d01"},
            {"id":"s02","cd":"c02","dd":"d02"}
        ]
    };

st.itemb.length // 2

Remove everything after a certain character

var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);

Sample here

I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).

Updated code to account for no '?':

var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);

Sample here

How to count digits, letters, spaces for a string in Python?

Ignoring anything else that may or may not be correct with your "revised code", the issue causing the error currently quoted in your question is caused by calling the "count" function with an undefined variable because your didn't quote the string.

  • count(thisisastring222) looks for a variable called thisisastring222 to pass to the function called count. For this to work you would have to have defined the variable earlier (e.g. with thisisastring222 = "AStringWith1NumberInIt.") then your function will do what you want with the contents of the value stored in the variable, not the name of the variable.
  • count("thisisastring222") hardcodes the string "thisisastring222" into the call, meaning that the count function will work with the exact string passed to it.

To fix your call to your function, just add quotes around asdfkasdflasdfl222 changing count(asdfkasdflasdfl222) to count("asdfkasdflasdfl222").

As far as the actual question "How to count digits, letters, spaces for a string in Python", at a glance the rest of the "revised code" looks OK except that the return line is not returning the same variables you've used in the rest of the code. To fix it without changing anything else in the code, change number and word to digit and letters, making return number,word,space,other into return digit,letters,space,other, or better yet return (digit, letters, space, other) to match current behavior while also using better coding style and being explicit as to what type of value is returned (in this case, a tuple).