Programs & Examples On #Aggregator

Mongoose limit/offset and count query

Instead of using 2 separate queries, you can use aggregate() in a single query:

Aggregate "$facet" can be fetch more quickly, the Total Count and the Data with skip & limit

    db.collection.aggregate([

      //{$sort: {...}}

      //{$match:{...}}

      {$facet:{

        "stage1" : [ {"$group": {_id:null, count:{$sum:1}}} ],

        "stage2" : [ { "$skip": 0}, {"$limit": 2} ]
  
      }},
     
     {$unwind: "$stage1"},
  
      //output projection
     {$project:{
        count: "$stage1.count",
        data: "$stage2"
     }}

 ]);

output as follows:-

[{
     count: 50,
     data: [
        {...},
        {...}
      ]
 }]

Also, have a look at https://docs.mongodb.com/manual/reference/operator/aggregation/facet/

How to get the location of the DLL currently executing?

In my case (dealing with my assemblies loaded [as file] into Outlook):

typeof(OneOfMyTypes).Assembly.CodeBase

Note the use of CodeBase (not Location) on the Assembly. Others have pointed out alternative methods of locating the assembly.

Mysql 1050 Error "Table already exists" when in fact, it does not

I am struggling with the same issue. I cannot create a table, even though it does not exist. I tried all the above solutions with no success.

My solution was to delete the files ib_logfil0, ib_logfile1, ibdata1, and auto.cnf from the data folder of MySQL; make sure to stop the MySQL service first before deleting these files.

Then after restarting the service, MySQL recreated these files and I was able to run a backup script were all my CREATEs were stored (a sqldump file).

What's causing my java.net.SocketException: Connection reset?

If you experience this trying to access Web services deployed on a Glassfish3 server, you might want to tune your http-thread-pool settings. That fixed SocketExceptions we had when many concurrent threads was calling the web service.

  1. Go to admin console
  2. Navigate to "Configurations"->"Server config"->"Thread pools"->"http-thread-pool".
  3. Change setting "Max Thread Pool Size" from 5 to 32
  4. Change setting "Min Thread Pool Size" from 2 to 16
  5. Restart Glassfish.

Best way to define private methods for a class in Objective-C

You could use blocks?

@implementation MyClass

id (^createTheObject)() = ^(){ return [[NSObject alloc] init];};

NSInteger (^addEm)(NSInteger, NSInteger) =
^(NSInteger a, NSInteger b)
{
    return a + b;
};

//public methods, etc.

- (NSObject) thePublicOne
{
    return createTheObject();
}

@end

I'm aware this is an old question, but it's one of the first I found when I was looking for an answer to this very question. I haven't seen this solution discussed anywhere else, so let me know if there's something foolish about doing this.

Ternary operator ?: vs if...else

Depends on your compiler, but on any modern compiler there is generally no difference. It's something you shouldn't worry about. Concentrate on the maintainability of your code.

Unity 2d jumping script

The answer above is now obsolete with Unity 5 or newer. Use this instead!

GetComponent<Rigidbody2D>().AddForce(new Vector2(0,10), ForceMode2D.Impulse);

I also want to add that this leaves the jump height super private and only editable in the script, so this is what I did...

    public float playerSpeed;  //allows us to be able to change speed in Unity
public Vector2 jumpHeight;

// Use this for initialization
void Start () {

}
// Update is called once per frame
void Update ()
{
    transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f);  //makes player run

    if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space))  //makes player jump
    {
        GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);

This makes it to where you can edit the jump height in Unity itself without having to go back to the script.

Side note - I wanted to comment on the answer above, but I can't because I'm new here. :)

jQuery Ajax calls and the Html.AntiForgeryToken()

Further to my comment against @JBall's answer that helped me along the way, this is the final answer that works for me. I'm using MVC and Razor and I'm submitting a form using jQuery AJAX so I can update a partial view with some new results and I didn't want to do a complete postback (and page flicker).

Add the @Html.AntiForgeryToken() inside the form as usual.

My AJAX submission button code (i.e. an onclick event) is:

//User clicks the SUBMIT button
$("#btnSubmit").click(function (event) {

//prevent this button submitting the form as we will do that via AJAX
event.preventDefault();

//Validate the form first
if (!$('#searchForm').validate().form()) {
    alert("Please correct the errors");
    return false;
}

//Get the entire form's data - including the antiforgerytoken
var allFormData = $("#searchForm").serialize();

// The actual POST can now take place with a validated form
$.ajax({
    type: "POST",
    async: false,
    url: "/Home/SearchAjax",
    data: allFormData,
    dataType: "html",
    success: function (data) {
        $('#gridView').html(data);
        $('#TestGrid').jqGrid('setGridParam', { url: '@Url.Action("GetDetails", "Home", Model)', datatype: "json", page: 1 }).trigger('reloadGrid');
    }
});

I've left the "success" action in as it shows how the partial view is being updated that contains an MvcJqGrid and how it's being refreshed (very powerful jqGrid grid and this is a brilliant MVC wrapper for it).

My controller method looks like this:

    //Ajax SUBMIT method
    [ValidateAntiForgeryToken]
    public ActionResult SearchAjax(EstateOutlet_D model) 
    {
        return View("_Grid", model);
    }

I have to admit to not being a fan of POSTing an entire form's data as a Model but if you need to do it then this is one way that works. MVC just makes the data binding too easy so rather than subitting 16 individual values (or a weakly-typed FormCollection) this is OK, I guess. If you know better please let me know as I want to produce robust MVC C# code.

How to post JSON to PHP with curl

Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use

$data = file_get_contents("php://input");

to just retrieve the http body and handle it yourself. See PHP input/output streams.

From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.

How to use orderby with 2 fields in linq?

Use ThenByDescending:

var hold = MyList.OrderBy(x => x.StartDate)
                 .ThenByDescending(x => x.EndDate)
                 .ToList();

You can also use query syntax and say:

var hold = (from x in MyList
           orderby x.StartDate, x.EndDate descending
           select x).ToList();

ThenByDescending is an extension method on IOrderedEnumerable which is what is returned by OrderBy. See also the related method ThenBy.

Replace Default Null Values Returned From Left Outer Join

In case of MySQL or SQLite the correct keyword is IFNULL (not ISNULL).

 SELECT iar.Description, 
      IFNULL(iai.Quantity,0) as Quantity, 
      IFNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
      iar.Compliance 
    FROM InventoryAdjustmentReason iar
    LEFT OUTER JOIN InventoryAdjustmentItem iai  on (iar.Id = iai.InventoryAdjustmentReasonId)
    LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
    LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'

How to select an option from drop down using Selenium WebDriver C#?

Adding a point to this- I came across a problem that OpenQA.Selenium.Support.UI namespace was not available after installing Selenium.NET binding into the C# project. Later found out that we can easily install latest version of Selenium WebDriver Support Classes by running the command:

Install-Package Selenium.Support

in NuGet Package Manager Console, or install Selenium.Support from NuGet Manager.

How to change shape color dynamically?

The simplest way to fill the shape with the Radius is:

XML:

<TextView
    android:id="@+id/textView"
    android:background="@drawable/test"
    android:layout_height="45dp"
    android:layout_width="100dp"
    android:text="Moderate"/>

Java:

(textView.getBackground()).setColorFilter(Color.parseColor("#FFDE03"), PorterDuff.Mode.SRC_IN);

Create a basic matrix in C (input by user !)

#include<stdio.h>
int main(void)
{  
int mat[10][10],i,j;

printf("Enter your matrix\n");  
for(i=0;i<2;i++)
  for(j=0;j<2;j++)
  {  
    scanf("%d",&mat[i][j]);  
  }  
printf("\nHere is your matrix:\n");   
for(i=0;i<2;i++)    
{  
    for(j=0;j<2;j++)  
    {  
      printf("%d ",mat[i][j]);  
    }  
    printf("\n");  
  }  

}

Getting time and date from timestamp with php

$mydatetime = "2012-04-02 02:57:54";
$datetimearray = explode(" ", $mydatetime);
$date = $datetimearray[0];
$time = $datetimearray[1];
$reformatted_date = date('d-m-Y',strtotime($date));
$reformatted_time = date('Gi.s',strtotime($time));

How to add header row to a pandas DataFrame

Alternatively you could read you csv with header=None and then add it with df.columns:

Cov = pd.read_csv("path/to/file.txt", sep='\t', header=None)
Cov.columns = ["Sequence", "Start", "End", "Coverage"]

Text in HTML Field to disappear when clicked?

Use the placeholder attribute. The text disappears when the user starts typing. This is an example of a project I am working on:

<div class="" id="search-form">
    <input type="text" name="" value="" class="form-control" placeholder="Search..." >
</div>

Why is Android Studio reporting "URI is not registered"?

Anyone getting this error right after project import might be hitting an unsuccessful initial gradle import/sync. Usually it is encountered with serious errors (blinking exclamation mark in the lower right corner). For me this was the very strange cause (project folder was symlinked): https://stackoverflow.com/a/52952148/44166

How do I watch a file for changes?

Well after a bit of hacking of Tim Golden's script, I have the following which seems to work quite well:

import os

import win32file
import win32con

path_to_watch = "." # look at the current directory
file_to_watch = "test.txt" # look for changes to a file called test.txt

def ProcessNewData( newData ):
    print "Text added: %s"%newData

# Set up the bits we'll need for output
ACTIONS = {
  1 : "Created",
  2 : "Deleted",
  3 : "Updated",
  4 : "Renamed from something",
  5 : "Renamed to something"
}
FILE_LIST_DIRECTORY = 0x0001
hDir = win32file.CreateFile (
  path_to_watch,
  FILE_LIST_DIRECTORY,
  win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
  None,
  win32con.OPEN_EXISTING,
  win32con.FILE_FLAG_BACKUP_SEMANTICS,
  None
)

# Open the file we're interested in
a = open(file_to_watch, "r")

# Throw away any exising log data
a.read()

# Wait for new data and call ProcessNewData for each new chunk that's written
while 1:
  # Wait for a change to occur
  results = win32file.ReadDirectoryChangesW (
    hDir,
    1024,
    False,
    win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
    None,
    None
  )

  # For each change, check to see if it's updating the file we're interested in
  for action, file in results:
    full_filename = os.path.join (path_to_watch, file)
    #print file, ACTIONS.get (action, "Unknown")
    if file == file_to_watch:
        newText = a.read()
        if newText != "":
            ProcessNewData( newText )

It could probably do with a load more error checking, but for simply watching a log file and doing some processing on it before spitting it out to the screen, this works well.

Thanks everyone for your input - great stuff!

Most efficient way to find mode in numpy array

Update

The scipy.stats.mode function has been significantly optimized since this post, and would be the recommended method

Old answer

This is a tricky problem, since there is not much out there to calculate mode along an axis. The solution is straight forward for 1-D arrays, where numpy.bincount is handy, along with numpy.unique with the return_counts arg as True. The most common n-dimensional function I see is scipy.stats.mode, although it is prohibitively slow- especially for large arrays with many unique values. As a solution, I've developed this function, and use it heavily:

import numpy

def mode(ndarray, axis=0):
    # Check inputs
    ndarray = numpy.asarray(ndarray)
    ndim = ndarray.ndim
    if ndarray.size == 1:
        return (ndarray[0], 1)
    elif ndarray.size == 0:
        raise Exception('Cannot compute mode on empty array')
    try:
        axis = range(ndarray.ndim)[axis]
    except:
        raise Exception('Axis "{}" incompatible with the {}-dimension array'.format(axis, ndim))

    # If array is 1-D and numpy version is > 1.9 numpy.unique will suffice
    if all([ndim == 1,
            int(numpy.__version__.split('.')[0]) >= 1,
            int(numpy.__version__.split('.')[1]) >= 9]):
        modals, counts = numpy.unique(ndarray, return_counts=True)
        index = numpy.argmax(counts)
        return modals[index], counts[index]

    # Sort array
    sort = numpy.sort(ndarray, axis=axis)
    # Create array to transpose along the axis and get padding shape
    transpose = numpy.roll(numpy.arange(ndim)[::-1], axis)
    shape = list(sort.shape)
    shape[axis] = 1
    # Create a boolean array along strides of unique values
    strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'),
                                 numpy.diff(sort, axis=axis) == 0,
                                 numpy.zeros(shape=shape, dtype='bool')],
                                axis=axis).transpose(transpose).ravel()
    # Count the stride lengths
    counts = numpy.cumsum(strides)
    counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])])
    counts[strides] = 0
    # Get shape of padded counts and slice to return to the original shape
    shape = numpy.array(sort.shape)
    shape[axis] += 1
    shape = shape[transpose]
    slices = [slice(None)] * ndim
    slices[axis] = slice(1, None)
    # Reshape and compute final counts
    counts = counts.reshape(shape).transpose(transpose)[slices] + 1

    # Find maximum counts and return modals/counts
    slices = [slice(None, i) for i in sort.shape]
    del slices[axis]
    index = numpy.ogrid[slices]
    index.insert(axis, numpy.argmax(counts, axis=axis))
    return sort[index], counts[index]

Result:

In [2]: a = numpy.array([[1, 3, 4, 2, 2, 7],
                         [5, 2, 2, 1, 4, 1],
                         [3, 3, 2, 2, 1, 1]])

In [3]: mode(a)
Out[3]: (array([1, 3, 2, 2, 1, 1]), array([1, 2, 2, 2, 1, 2]))

Some benchmarks:

In [4]: import scipy.stats

In [5]: a = numpy.random.randint(1,10,(1000,1000))

In [6]: %timeit scipy.stats.mode(a)
10 loops, best of 3: 41.6 ms per loop

In [7]: %timeit mode(a)
10 loops, best of 3: 46.7 ms per loop

In [8]: a = numpy.random.randint(1,500,(1000,1000))

In [9]: %timeit scipy.stats.mode(a)
1 loops, best of 3: 1.01 s per loop

In [10]: %timeit mode(a)
10 loops, best of 3: 80 ms per loop

In [11]: a = numpy.random.random((200,200))

In [12]: %timeit scipy.stats.mode(a)
1 loops, best of 3: 3.26 s per loop

In [13]: %timeit mode(a)
1000 loops, best of 3: 1.75 ms per loop

EDIT: Provided more of a background and modified the approach to be more memory-efficient

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

They can be considered as equivalent. The limits in size are the same:

  • Maximum length of CLOB (in bytes or OCTETS)) 2 147 483 647
  • Maximum length of BLOB (in bytes) 2 147 483 647

There is also the DBCLOBs, for double byte characters.

References:

How to parse JSON to receive a Date object in JavaScript?

if you use the JavaScript style ISO8601 date in JSON, you could use this, from MDN

var jsonDate = (new Date()).toJSON();
var backToDate = new Date(jsonDate);
console.log(jsonDate); //2015-10-26T07:46:36.611Z

Text Editor which shows \r\n?

SciTE does that very well with a single keystroke. It is also able to detect the most probably current line ending of the file (in case of mixed lines) and to convert them.
No need to install, lightweight, it can be used as a tool even if you don't want to give up your favorite editor.

Laravel Check If Related Model Exists

I had to completely refactor my code when I updated my PHP version to 7.2+ because of bad usage of the count($x) function. This is a real pain and its also extremely scary as there are hundreds usages, in different scenarios and there is no one rules fits all..

Rules I followed to refactor everything, examples:

$x = Auth::user()->posts->find(6); (check if user has a post id=6 using ->find())

[FAILS] if(count($x)) { return 'Found'; } 
[GOOD] if($x) { return 'Found'; }

$x = Auth::user()->profile->departments; (check if profile has some departments, there can have many departments)

[FAILS] if(count($x)) { return 'Found'; }
[GOOD] if($x->count()) { return 'Found'; }

$x = Auth::user()->profile->get(); (check if user has a profile after using a ->get())

[FAILS] if(count($x)) { return 'Found'; }
[GOOD] if($x->count()) { return 'Found'; }

Hopes this can help, even 5 years after the question has been asked, this stackoverflow post has helped me a lot!

Throughput and bandwidth difference?

Here is another example to help you imagine what the difference could be depending on the situation.

Imagine

  • You have a 1 MB file (say a photo) that you would like to share with 3 friends.
  • Each of them, however, uses different cloud storage application - Google Drive, Microsoft OneDrive and Dropbox. Therefore they all create a folder and give you access so you can upload the file to their folder.
  • You open the URLs to these three folders in your browser (say in 3 different tabs) and drag-n-drop the file (more or less at the same time) to each tab so to upload it.
  • You are connected to the Internet via a fiber-optic cable which gives you the ability to transfer at speed of 1 Gb per second (i.e. this is your bandwidth - the max capacity that you can utilise your connection).

Knowing that, theoretically (assuming no data lost, no big protocol overhead, connection to the cloud storage services offers at least the same bandwidth, etc.) you can transfer one 1 MB file over the 1 Gbps connection for roughly: 1MB / 1 Gbps = 1 x 10^3 x 8 / 1x10^9 which gives about 8x10^-6 seconds or say roughly 10 ms. Now, you have 1 file that you want to upload to 3 destinations, your connection bandwidth is big enough so you can transfer the same file to 3 destinations at the same time (we can also assume you have a modern laptop equipped with multi-core CPU so data transfer over the 3 connections to Google Drive, MS OneDrive and Dropbox can be done in parallel). Therefore, instead of waiting for 30ms to transfer the same file to 3 different destinations you only have to wait for 10ms as you have a very good bandwidth.

Now let's consider what protocol is being used and what implications that brings. As you use your browser to upload the file, the protocol that is being used is HTTP/S which is running on top of the TCP protocol. An important property of the TCP protocol is that it makes sure that a batch of data has reached any destination successfully before sending the next batch of data. That is being done by the TCP sender waiting for acknowledgement (for short an ACK) that the first batch of data has been received before it starts sending the second batch of data. What this means is that if it takes 0.5s to transfer 1 batch of data one direction and then 0.5s to received an ACK then you need to wait for 1 second until 1 batch of data is transferred and successfully confirmed to have been received (again, let's assume no data lost, therefore no need to re-transfer the same batch). Because of this round trip needed by the TCP protocol there appears to be a blocker. The blocker is the delay you experience for one round trip which includes transferring 1 batch of data and its successful acknowledgement. With that in mind we need to see how big is one batch of data. This can vary but it's usually 64KB. So your actual traffic to 1 destination (i.e, the throughput) is bound by this delay (i.e., latency) and the batch size by the following equation:

throughput = batch size / latency

In our example the throughput is 64KB/s and as we can split 1 MB in roughly 15.6 batches of 64KB size, you will need about 15.6 seconds to transfer 1 MB of file. That is a major slowdown compared to the bandwidth-only based calculations we made early.

import sun.misc.BASE64Encoder results in error compiled in Eclipse

I had this problem on jdk1.6.0_37. This is the only JDE/JRE on my system. I don't know why, but the following solved the problem:

Project -> Properties -> Java Build Path - > Libraries

Switch radio button from Execution environment to Alernate JRE. This selects the same jdk1.6.0_37, but after clean/build the compile error disappeared.

Maybe clarification in answer from ram (Mar 16 at 9:00) has to do something with that.

How to AUTO_INCREMENT in db2?

Added a few optional parameters for creating "future safe" sequences.

CREATE SEQUENCE <NAME>
  START WITH 1
  INCREMENT BY 1
  NO MAXVALUE
  NO CYCLE
  CACHE 10;

How can I disable HREF if onclick is executed?

You can use this simple code:

<a href="" onclick="return false;">add new action</a><br>

What is the best way to ensure only one instance of a Bash script is running?

Use the set -o noclobber option and attempt to overwrite a common file.

A short example

if ! (set -o noclobber ; echo > /tmp/global.lock) ; then
    exit 1  # the global.lock already exists
fi

# ... remainder of script ...

A longer example

This example will wait for the global.lock file but timeout after too long.

 function lockfile_waithold()
 {
    declare -ir time_beg=$(date '+%s')
    declare -ir time_max=7140  # 7140 s = 1 hour 59 min.
 
    # poll for lock file up to ${time_max}s
    # put debugging info in lock file in case of issues ...
    while ! \
       (set -o noclobber ; \
        echo -e "DATE:$(date)\nUSER:$(whoami)\nPID:$$" > /tmp/global.lock \ 
       ) 2>/dev/null
    do
        if [ $(($(date '+%s') - ${time_beg})) -gt ${time_max} ] ; then
            echo "Error: waited too long for lock file /tmp/global.lock" 1>&2
            return 1
        fi
        sleep 1
    done
 
    return 0
 }
 
 function lockfile_release()
 {
    rm -f /tmp/global.lock
 }
 
 if ! lockfile_waithold ; then
      exit 1
 fi
 trap lockfile_release EXIT
 
 # ... remainder of script ...

This has reliably worked for me on an Ubuntu 16 host with multiple instances of a bash script that used the same system-wide "lock" file.

(This is similar to this post by @Barry Kelly which was noticed afterward.)

How to reference Microsoft.Office.Interop.Excel dll?

You have to check which version of Excel you are targeting?

If you are targeting Excel 2010 use version 14 (as per Grant's screenshot answer), Excel 2007 use version 12 . You can not support Excel 2003 using vS2012 as they do not have the correct Interop dll installed.

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

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

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

Get data type of field in select statement in ORACLE

I came into the same situation. As a workaround, I just created a view (If you have privileges) and described it and dropped it later. :)

read complete file without using loop in java

Java 7 one line solution

List<String> lines = Files.readAllLines(Paths.get("file"), StandardCharsets.UTF_8);

or

 String text = new String(Files.readAllBytes(Paths.get("file")), StandardCharsets.UTF_8);

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

public FileContentResult GetImage(int productId) { 
     Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId); 
     if (prod != null) { 
         return File(prod.ImageData, prod.ImageMimeType); 
      } else { 
         return null; 
     } 
}

How to get a list of all files in Cloud Storage in a Firebase app?

You can list files in a directory of firebase storage by listAll() method. To use this method, have to implement this version of firebase storage. 'com.google.firebase:firebase-storage:18.1.1'

https://firebase.google.com/docs/storage/android/list-files

Keep in mind that upgrade the Security Rules to version 2.

How to override application.properties during production in Spring-Boot?

Update with Spring Boot 2.2.2.Release.

Full example here, https://www.surasint.com/spring-boot-override-property-example/

Assume that, in your jar file, you have the application.properties which have these two line:

server.servlet.context-path=/test
server.port=8081

Then, in production, you want to override the server.port=8888 but you don't want to override the other properties.

First you create another file, ex override.properties and have online this line:

server.port=8888

Then you can start the jar like this

java -jar spring-boot-1.0-SNAPSHOT.jar --spring.config.location=classpath:application.properties,/opt/somewhere/override.properties

How to restrict the selectable date ranges in Bootstrap Datepicker?

Most answers and explanations are not to explain what is a valid string of endDate or startDate. Danny gave us two useful example.

$('#datepicker').datepicker({
    startDate: '-2m',
    endDate: '+2d'
});

But why?let's take a look at the source code at bootstrap-datetimepicker.js. There are some code begin line 1343 tell us how does it work.

if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) {
            var part_re = /([-+]\d+)([dmwy])/,
                parts = date.match(/([-+]\d+)([dmwy])/g),
                part, dir;
            date = new Date();
            for (var i = 0; i < parts.length; i++) {
                part = part_re.exec(parts[i]);
                dir = parseInt(part[1]);
                switch (part[2]) {
                    case 'd':
                        date.setUTCDate(date.getUTCDate() + dir);
                        break;
                    case 'm':
                        date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);
                        break;
                    case 'w':
                        date.setUTCDate(date.getUTCDate() + dir * 7);
                        break;
                    case 'y':
                        date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir);
                        break;
                }
            }
            return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);
        }

There are four kinds of expressions.

  • w means week
  • m means month
  • y means year
  • d means day

Look at the regular expression ^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$. You can do more than these -0d or +1m.

Try harder like startDate:'+1y,-2m,+0d,-1w'.And the separator , could be one of [\f\n\r\t\v,]

What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

FragmentPagerAdapter stores the previous data which is fetched from the adapter while FragmentStatePagerAdapter takes the new value from the adapter everytime it is executed.

HTTP 415 unsupported media type error when calling Web API 2 endpoint

In my case it is Asp.Net Core 3.1 API. I changed the HTTP GET method from public ActionResult GetValidationRulesForField( GetValidationRulesForFieldDto getValidationRulesForFieldDto) to public ActionResult GetValidationRulesForField([FromQuery] GetValidationRulesForFieldDto getValidationRulesForFieldDto) and its working.

Ring Buffer in Java

Since Java 1.6, there is ArrayDeque, which implements Queue and seems to be faster and more memory efficient than a LinkedList and doesn't have the thread synchronization overhead of the ArrayBlockingQueue: from the API docs: "This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue."

final Queue<Object> q = new ArrayDeque<Object>();
q.add(new Object()); //insert element
q.poll(); //remove element

How to print time in format: 2009-08-10 18:17:54.811

The above answers do not fully answer the question (specifically the millisec part). My solution to this is to use gettimeofday before strftime. Note the care to avoid rounding millisec to "1000". This is based on Hamid Nazari's answer.

#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>

int main() {
  char buffer[26];
  int millisec;
  struct tm* tm_info;
  struct timeval tv;

  gettimeofday(&tv, NULL);

  millisec = lrint(tv.tv_usec/1000.0); // Round to nearest millisec
  if (millisec>=1000) { // Allow for rounding up to nearest second
    millisec -=1000;
    tv.tv_sec++;
  }

  tm_info = localtime(&tv.tv_sec);

  strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", tm_info);
  printf("%s.%03d\n", buffer, millisec);

  return 0;
}

How to choose between Hudson and Jenkins?

For those who have mentioned a reconciliation as a potential future for Hudson and Jenkins, with the fact that Jenkins will be joining SPI, it is unlikely at this point they will reconcile.

Which MySQL data type to use for storing boolean values

Until MySQL implements a bit datatype, if your processing is truly pressed for space and/or time, such as with high volume transactions, create a TINYINT field called bit_flags for all your boolean variables, and mask and shift the boolean bit you desire in your SQL query.

For instance, if your left-most bit represents your bool field, and the 7 rightmost bits represent nothing, then your bit_flags field will equal 128 (binary 10000000). Mask (hide) the seven rightmost bits (using the bitwise operator &), and shift the 8th bit seven spaces to the right, ending up with 00000001. Now the entire number (which, in this case, is 1) is your value.

SELECT (t.bit_flags & 128) >> 7 AS myBool FROM myTable t;

if bit_flags = 128 ==> 1 (true)
if bit_flags = 0 ==> 0 (false)

You can run statements like these as you test

SELECT (128 & 128) >> 7;

SELECT (0 & 128) >> 7;

etc.

Since you have 8 bits, you have potentially 8 boolean variables from one byte. Some future programmer will invariably use the next seven bits, so you must mask. Don’t just shift, or you will create hell for yourself and others in the future. Make sure you have MySQL do your masking and shifting — this will be significantly faster than having the web-scripting language (PHP, ASP, etc.) do it. Also, make sure that you place a comment in the MySQL comment field for your bit_flags field.

You’ll find these sites useful when implementing this method:

How do I add Git version control (Bitbucket) to an existing source code folder?

Final working solution using @Arrigo response and @Samitha Chathuranga comment, I'll put all together to build a full response for this question:

  1. Suppose you have your project folder on PC;
  2. Create a new repository on bitbucket: enter image description here

  3. Press on I have an existing project: enter image description here

  4. Open Git CMD console and type command 1 from second picture(go to your project folder on your PC)

  5. Type command git init

  6. Type command git add --all

  7. Type command 2 from second picture (git remote add origin YOUR_LINK_TO_REPO)

  8. Type command git commit -m "my first commit"

  9. Type command git push -u origin master

Note: if you get error unable to detect email or name, just type following commands after 5th step:

 git config --global user.email "yourEmail"  #your email at Bitbucket
 git config --global user.name "yourName"  #your name at Bitbucket

MySQL "Group By" and "Order By"

As pointed in a reply already, the current answer is wrong, because the GROUP BY arbitrarily selects the record from the window.

If one is using MySQL 5.6, or MySQL 5.7 with ONLY_FULL_GROUP_BY, the correct (deterministic) query is:

SELECT incomingEmails.*
  FROM (
    SELECT fromEmail, MAX(timestamp) `timestamp`
    FROM incomingEmails
    GROUP BY fromEmail
  ) filtered_incomingEmails
  JOIN incomingEmails USING (fromEmail, timestamp)
GROUP BY fromEmail, timestamp

In order for the query to run efficiently, proper indexing is required.

Note that for simplification purposes, I've removed the LOWER(), which in most cases, won't be used.

git add, commit and push commands in one?

Add in ~/.bash_profile for adding, committing and pushing with one command put:

function g() { git commit -a -m "$*"; git push; }

Usage:

g your commit message
g your commit message 'message'

No quotes are needed although you can't use semicolons or parenthesis in your commit messages (single quotes are allowed). If you want to any of these just simply put double quotes in you message, e.g.:

g "your commit message; (message)"

To create a comment in your message do:

g "your commit message:
> your note"

There's also a function for adding and committing in a similar way:

function c() { git add --all; git commit -m "$*"; }

Works exactly the same way that g function and has the same constraints. Just put c instead. E.g.

c your commit message

You can also add an alias for pushing to the remote:

alias p='git push'

Usage:

p

That amounts into 2 letters, c and p you use while working with your git repository. Or you can use g instead to do it all with only one letter.

Full list of aliases and functions: https://gist.github.com/matt360/0c5765d6f0579a5aa74641bc47ae50ac

Rails 3 execute custom sql query without a model

I'd recommend using ActiveRecord::Base.connection.exec_query instead of ActiveRecord::Base.connection.execute which returns a ActiveRecord::Result (available in rails 3.1+) which is a bit easier to work with.

Then you can access it in various the result in various ways like .rows, .each, or .to_hash

From the docs:

result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>


# Get the column names of the result:
result.columns
# => ["id", "title", "body"]

# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
      [2, "title_2", "body_2"],
      ...
     ]

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

# ActiveRecord::Result also includes Enumerable.
result.each do |row|
  puts row['title'] + " " + row['body']
end

note: copied my answer from here

Error: No module named psycopg2.extensions

For macOS Mojave just run pip install psycopg2-binary. Works fine for me, python version -> Python 3.7.2

How do I create an Android Spinner as a popup?

Try this:

Spinner popupSpinner = new Spinner(context, Spinner.MODE_DIALOG);

See this link for more details.

error: expected declaration or statement at end of input in c

Normally that error occurs when a } was missed somewhere in the code, for example:

void mi_start_curr_serv(void){
    #if 0
    //stmt
    #endif

would fail with this error due to the missing } at the end of the function. The code you posted doesn't have this error, so it is likely coming from some other part of your source.

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

The main difference is that with a = a + b, there is no typecasting going on, and so the compiler gets angry at you for not typecasting. But with a += b, what it's really doing is typecasting b to a type compatible with a. So if you do

int a=5;
long b=10;
a+=b;
System.out.println(a);

What you're really doing is:

int a=5;
long b=10;
a=a+(int)b;
System.out.println(a);

List append() in for loop

You don't need the assignment, list.append(x) will always append x to a and therefore there's no need te redefine a.

a = []
for i in range(5):    
    a.append(i)
print(a)

is all you need. This works because lists are mutable.

Also see the docs on data structures.

Check for file exists or not in sql server?

You can achieve this using a cursor but the performance is much slower than whileloop.. Here's the code:

set nocount on
declare cur cursor local fast_forward for
    (select filepath from Directory)
open cur;
declare @fullpath varchar(250);
declare @isExists int;

fetch from cur into @fullpath
while @@FETCH_STATUS = 0
    begin
        exec xp_fileexist @fullpath, @isExists out
        if @isExists = 1            
            print @fullpath + char(9) + char(9) + 'file exists'
        else            
            print @fullpath + char(9) + char(9) + 'file does not exists'
        fetch from cur into @fullpath
    end
close cur
deallocate cur

or you can put it in a tempTable if you want to integrate it in your frontend..

create proc GetFileStatus as
begin
    set nocount on
    create table #tempFileStatus(FilePath varchar(300),FileStatus varchar(30))
    declare cur cursor local fast_forward for
        (select filepath from Directory)
    open cur;
    declare @fullpath varchar(250);
    declare @isExists int;

    fetch from cur into @fullpath
    while @@FETCH_STATUS = 0
        begin
            exec xp_fileexist @fullpath, @isExists out
            if @isExists = 1                
                insert into #tempFileStatus values(@fullpath,'File exist')
            else
                insert into #tempFileStatus values(@fullpath,'File does not exists')
            fetch from cur into @fullpath
        end
    close cur
    deallocate cur
    select * from #tempFileStatus
    drop table #tempFileStatus
end

then call it using:

exec GetFileStatus

Date query with ISODate in mongodb doesn't seem to work

Old question, but still first google hit, so i post it here so i find it again more easily...

Using Mongo 4.2 and an aggregate():

db.collection.aggregate(
    [
     { $match: { "end_time": { "$gt": ISODate("2020-01-01T00:00:00.000Z")  } } },
     { $project: {
          "end_day": { $dateFromParts: { 'year' : {$year:"$end_time"}, 'month' : {$month:"$end_time"}, 'day': {$dayOfMonth:"$end_time"}, 'hour' : 0  } }
     }}, 
     {$group:{
        _id:   "$end_day",
        "count":{$sum:1},
    }}
   ]
)

This one give you the groupby variable as a date, sometimes better to hande as the components itself.

how to use LIKE with column name

declare @LkeVal as Varchar(100)
declare @LkeSelect Varchar(100)

Set @LkeSelect = (select top 1 <column> from <table> where <column> = 'value')
Set @LkeVal = '%' + @LkeSelect

select * from <table2> where <column2> like(''+@LkeVal+'');

Change header text of columns in a GridView

protected void grdDis_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            #region Dynamically Show gridView header From data base
            getAllheaderName();/*To get all Allowences master headerName*/

            TextBox txt_Days = (TextBox)grdDis.HeaderRow.FindControl("txtDays");
            txt_Days.Text = hidMonthsDays.Value;
            #endregion
        }
    }

remove url parameters with javascript or jquery

Well, I am using this:

stripUrl(urlToStrip){
        let stripped = urlToStrip.split('?')[0];
        stripped = stripped.split('&')[0];
        stripped = stripped.split('#')[0];
        return stripped;
    }

or:

    stripUrl(urlToStrip){
        return urlToStrip.split('?')[0].split('&')[0].split('#')[0];
    }

JavaScript set object key by variable

In ES6, you can do like this.

var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var key = "name";_x000D_
    var person = {[key]:"John"};_x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

Its called Computed Property Names, its implemented using bracket notation( square brackets) []

Example: { [variableName] : someValue }

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.

For ES5, try something like this

var yourObject = {};

yourObject[yourKey] = "yourValue";

console.log(yourObject );

example:

var person = {};
var key = "name";

person[key] /* this is same as person.name */ = "John";

console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var person = {};_x000D_
    var key = "name";_x000D_
    _x000D_
    person[key] /* this is same as person.name */ = "John";_x000D_
    _x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

how to calculate percentage in python

I know I am late, but if you want to know the easiest way, you could do a code like this:

number = 100
right_questions = 1
control = 100
c = control / number
cc = right_questions * c
print float(cc)

You can change up the number score, and right_questions. It will tell you the percent.

How do I free memory in C?

You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc(), the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap(). Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc(), it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free() the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.

If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc(). Thus, if you make a lot of calls to malloc() and free() with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc() fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.

CSS Positioning Elements Next to each other

If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:

float:left; display:inline; width: 49%;

on both of them.

#mainContent, #sideContent {float:left; display:inline; width: 49%;}

When to use Hadoop, HBase, Hive and Pig?

I believe this thread hasn't done in particular justice to HBase and Pig in particular. While I believe Hadoop is the choice of the distributed, resilient file-system for big-data lake implementations, the choice between HBase and Hive is in particular well-segregated.

As in, a lot of use-cases have a particular requirement of SQL like or No-SQL like interfaces. With Phoenix on top of HBase, though SQL like capabilities is certainly achievable, however, the performance, third-party integrations, dashboard update are a kind of painful experiences. However, it's an excellent choice for databases requiring horizontal scaling.

Pig is in particular excellent for non-recursive batch like computations or ETL pipelining (somewhere, where it outperforms Spark by a comfortable distance). Also, it's high-level dataflow implementations is an excellent choice for batch querying and scripting. The choice between Pig and Hive is also pivoted on the need of the client or server-side scripting, required file formats, etc. Pig supports Avro file format which is not true in the case of Hive. The choice for 'procedural dataflow language' vs 'declarative data flow language' is also a strong argument for the choice between pig and hive.

Enable remote connections for SQL Server Express 2012

On my installation of SQL Server 2012 Developer Edition, installed with default settings, I just had to load the SQL Server Configuration Manager -> SQL Server Network Configuration -> Protocols for MSSQLSERVER and change TCP/IP from Disabled to Enabled.

PowerShell Connect to FTP server and get files

Here is the full working code to download all files (with wildcard or file extension) from the FTP site to local directory. Set the variable values.

    #FTP Server Information - SET VARIABLES
    $ftp = "ftp://XXX.com/" 
    $user = 'UserName' 
    $pass = 'Password'
    $folder = 'FTP_Folder'
    $target = "C:\Folder\Folder1\"

    #SET CREDENTIALS
    $credentials = new-object System.Net.NetworkCredential($user, $pass)

    function Get-FtpDir ($url,$credentials) {
        $request = [Net.WebRequest]::Create($url)
        $request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
        if ($credentials) { $request.Credentials = $credentials }
        $response = $request.GetResponse()
        $reader = New-Object IO.StreamReader $response.GetResponseStream() 
        while(-not $reader.EndOfStream) {
            $reader.ReadLine()
        }
        #$reader.ReadToEnd()
        $reader.Close()
        $response.Close()
    }

    #SET FOLDER PATH
    $folderPath= $ftp + "/" + $folder + "/"

    $files = Get-FTPDir -url $folderPath -credentials $credentials

    $files 

    $webclient = New-Object System.Net.WebClient 
    $webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass) 
    $counter = 0
    foreach ($file in ($files | where {$_ -like "*.txt"})){
        $source=$folderPath + $file  
        $destination = $target + $file 
        $webclient.DownloadFile($source, $target+$file)

        #PRINT FILE NAME AND COUNTER
        $counter++
        $counter
        $source
    }

Clear the cache in JavaScript

Other than caching every hour, or every week, you may cache according to file data.

Example (in PHP):

<script src="js/my_script.js?v=<?=md5_file('js/my_script.js')?>"></script>

or even use file modification time:

<script src="js/my_script.js?v=<?=filemtime('js/my_script.js')?>"></script>

Getting Date or Time only from a DateTime Object

var day = value.Date; // a DateTime that will just be whole days
var time = value.TimeOfDay; // a TimeSpan that is the duration into the day

HTML: How to center align a form

@Lucius and @zyrolasting have it right.

However, you will probably need to give the form a specified width for it to work properly.

form { 
margin: 0 auto; 
width:250px;
}

Why does ASP.NET webforms need the Runat="Server" attribute?

HTML elements in ASP.NET files are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the HTML element. This attribute indicates that the element should be treated as a server control.

Rails 4 LIKE query - ActiveRecord adds quotes

While string interpolation will work, as your question specifies rails 4, you could be using Arel for this and keeping your app database agnostic.

def self.search(query, page=1)
  query = "%#{query}%"
  name_match = arel_table[:name].matches(query)
  postal_match = arel_table[:postal_code].matches(query)
  where(name_match.or(postal_match)).page(page).per_page(5)
end

Function that creates a timestamp in c#

when you need in a timestamp in seconds, you can use the following:

var timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds;

Simplest way to wait some asynchronous tasks complete, in Javascript?

Expanding upon @freakish answer, async also offers a each method, which seems especially suited for your case:

var async = require('async');

async.each(['aaa','bbb','ccc'], function(name, callback) {
    conn.collection(name).drop( callback );
}, function(err) {
    if( err ) { return console.log(err); }
    console.log('all dropped');
});

IMHO, this makes the code both more efficient and more legible. I've taken the liberty of removing the console.log('dropped') - if you want it, use this instead:

var async = require('async');

async.each(['aaa','bbb','ccc'], function(name, callback) {
    // if you really want the console.log( 'dropped' ),
    // replace the 'callback' here with an anonymous function
    conn.collection(name).drop( function(err) {
        if( err ) { return callback(err); }
        console.log('dropped');
        callback()
    });
}, function(err) {
    if( err ) { return console.log(err); }
    console.log('all dropped');
});

Capture Video of Android's Screen

Android 4.4 (KitKat) and higher devices have a shell utility for recording the Android device screen. Connect a device in developer/debug mode running KitKat with the adb utility over USB and then type the following:

adb shell screenrecord /sdcard/movie.mp4
(Press Ctrl-C to stop)
adb pull /sdcard/movie.mp4

Screen recording is limited to a maximum of 3 minutes.

Reference: https://developer.android.com/studio/command-line/adb.html#screenrecord

How do I convert from stringstream to string in C++?

std::stringstream::str() is the method you are looking for.

With std::stringstream:

template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
    std::stringstream ss;
    ss << NumericValue;
    return ss.str();
}

std::stringstream is a more generic tool. You can use the more specialized class std::ostringstream for this specific job.

template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
    std::ostringstream oss;
    oss << NumericValue;
    return oss.str();
}

If you are working with std::wstring type of strings, you must prefer std::wstringstream or std::wostringstream instead.

template <class T>
std::wstring YourClass::NumericToString(const T & NumericValue)
{
    std::wostringstream woss;
    woss << NumericValue;
    return woss.str();
}

if you want the character type of your string could be run-time selectable, you should also make it a template variable.

template <class CharType, class NumType>
std::basic_string<CharType> YourClass::NumericToString(const NumType & NumericValue)
{
    std::basic_ostringstream<CharType> oss;
    oss << NumericValue;
    return oss.str();
}

For all the methods above, you must include the following two header files.

#include <string>
#include <sstream>

Note that, the argument NumericValue in the examples above can also be passed as std::string or std::wstring to be used with the std::ostringstream and std::wostringstream instances respectively. It is not necessary for the NumericValue to be a numeric value.

"SMTP Error: Could not authenticate" in PHPMailer

SMTP Error: could not authenticate I had the same problem. The following troubleshooting steps helped me.

  • I turned off two-factor authentication in my gmail account.
  • I allowed less secure apps to access my gmail account. To get it working, I had to go to myaccount.google.com -> Sign-in & security -> Apps with account access, and turn Allow less secure apps to ON (near the bottom of the page).
  • At this step, when I tried to register a user, I would get the same error. Google would sent me a warning message that someone has my password and the login was blocked.
  • Gmail will then provide you with options. You either click whether the activity was yours or not yours. Click the option that the activity was yours.
  • Try registration again. It should now work.

Is it possible to use the instanceof operator in a switch statement?

I think there are reasons to use a switch statement. If you are using xText generated Code perhaps. Or another kind of EMF generated classes.

instance.getClass().getName();

returns a String of the Class Implementation Name. i.e: org.eclipse.emf.ecore.util.EcoreUtil

instance.getClass().getSimpleName();

returns the simple represenation i.e: EcoreUtil

Extract a subset of a dataframe based on a condition involving a field

Here are the two main approaches. I prefer this one for its readability:

bar <- subset(foo, location == "there")

Note that you can string together many conditionals with & and | to create complex subsets.

The second is the indexing approach. You can index rows in R with either numeric, or boolean slices. foo$location == "there" returns a vector of T and F values that is the same length as the rows of foo. You can do this to return only rows where the condition returns true.

foo[foo$location == "there", ]

How do I execute a PowerShell script automatically using Windows task scheduler?

  1. Open the created task scheduler

  2. switch to the “Action” tab and select your created “Action”

  3. In the Edit section, using the browser you could select powershell.exe in your system32\WindowsPowerShell\v1.0 folder.

       Example -C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    
  4. Next, in the ‘Add arguments’ -File parameter, paste your script file path in your system.

        Example – c:\GetMFAStatus.ps1
    

This blog might help you to automate your Powershell scripts with windows task scheduler

How can I use custom fonts on a website?

CSS lets you use custom fonts, downloadable fonts on your website. You can download the font of your preference, let’s say myfont.ttf, and upload it to your remote server where your blog or website is hosted.

@font-face {
    font-family: myfont;
    src: url('myfont.ttf');
}

Determining the path that a yum package installed to

I don't know about yum, but rpm -ql will list the files in a particular .rpm file. If you can find the package file on your system you should be good to go.

Download file using libcurl in C/C++

The example you are using is wrong. See the man page for easy_setopt. In the example write_data uses its own FILE, *outfile, and not the fp that was specified in CURLOPT_WRITEDATA. That's why closing fp causes problems - it's not even opened.

This is more or less what it should look like (no libcurl available here to test)

#include <stdio.h>
#include <curl/curl.h>
/* For older cURL versions you will also need 
#include <curl/types.h>
#include <curl/easy.h>
*/
#include <string>

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int main(void) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://localhost/aaa.txt";
    char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        /* always cleanup */
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    return 0;
}

Updated: as suggested by @rsethc types.h and easy.h aren't present in current cURL versions anymore.

Initialize a Map containing arrays

Per Mozilla's Map documentation, you can initialize as follows:

private _gridOptions:Map<string, Array<string>> = 
    new Map([
        ["1", ["test"]],
        ["2", ["test2"]]
    ]);

How to change Hash values?

This will do it:

my_hash.each_with_object({}) { |(key, value), hash| hash[key] = value.upcase }

As opposed to inject the advantage is that you are in no need to return the hash again inside the block.

SQL: how to select a single id ("row") that meets multiple criteria from a single column

Users who have one of the 3 countries

SELECT DISTINCT user_id
FROM table
WHERE ancestry IN('England','France','Germany')

Users who have all 3 countries

SELECT DISTINCT A.userID
FROM table A
   INNER JOIN table B on A.user_id = B.user_id
   INNER JOIN table C on A.user_id = C.user_id
WHERE A.ancestry = 'England'
   AND B.ancestry = 'Germany'
   AND C.ancestry = 'France'

JUnit 5: How to assert an exception is thrown?

In Java 8 and JUnit 5 (Jupiter) we can assert for exceptions as follows. Using org.junit.jupiter.api.Assertions.assertThrows

public static < T extends Throwable > T assertThrows(Class< T > expectedType, Executable executable)

Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.

If no exception is thrown, or if an exception of a different type is thrown, this method will fail.

If you do not want to perform additional checks on the exception instance, simply ignore the return value.

@Test
public void itShouldThrowNullPointerExceptionWhenBlahBlah() {
    assertThrows(NullPointerException.class,
            ()->{
            //do whatever you want to do here
            //ex : objectName.thisMethodShoulThrowNullPointerExceptionForNullParameter(null);
            });
}

That approach will use the Functional Interface Executable in org.junit.jupiter.api.

Refer :

How to remove specific substrings from a set of strings in Python?

if you delete something from list , u can use this way : (method sub is case sensitive)

new_list = []
old_list= ["ABCDEFG","HKLMNOP","QRSTUV"]

for data in old_list:
     new_list.append(re.sub("AB|M|TV", " ", data))

print(new_list) // output : [' CDEFG', 'HKL NOP', 'QRSTUV']

how to display variable value in alert box?

Try innerText property:

var content = document.getElementById("one").innerText;
alert(content);

See also this fiddle http://fiddle.jshell.net/4g8vb/

What does numpy.random.seed(0) do?

np.random.seed(0) makes the random numbers predictable

>>> numpy.random.seed(0) ; numpy.random.rand(4)
array([ 0.55,  0.72,  0.6 ,  0.54])
>>> numpy.random.seed(0) ; numpy.random.rand(4)
array([ 0.55,  0.72,  0.6 ,  0.54])

With the seed reset (every time), the same set of numbers will appear every time.

If the random seed is not reset, different numbers appear with every invocation:

>>> numpy.random.rand(4)
array([ 0.42,  0.65,  0.44,  0.89])
>>> numpy.random.rand(4)
array([ 0.96,  0.38,  0.79,  0.53])

(pseudo-)random numbers work by starting with a number (the seed), multiplying it by a large number, adding an offset, then taking modulo of that sum. The resulting number is then used as the seed to generate the next "random" number. When you set the seed (every time), it does the same thing every time, giving you the same numbers.

If you want seemingly random numbers, do not set the seed. If you have code that uses random numbers that you want to debug, however, it can be very helpful to set the seed before each run so that the code does the same thing every time you run it.

To get the most random numbers for each run, call numpy.random.seed(). This will cause numpy to set the seed to a random number obtained from /dev/urandom or its Windows analog or, if neither of those is available, it will use the clock.

For more information on using seeds to generate pseudo-random numbers, see wikipedia.

Cross-browser window resize event - JavaScript / jQuery

I think you should add further control to this:

    var disableRes = false;
    var refreshWindow = function() {
        disableRes = false;
        location.reload();
    }
    var resizeTimer;
    if (disableRes == false) {
        jQuery(window).resize(function() {
            disableRes = true;
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(refreshWindow, 1000);
        });
    }

Using array map to filter results with if conditional

Here's some info if someone comes upon this in 2019.

I think reduce vs map + filter might be somewhat dependent on what you need to loop through. Not sure on this but reduce does seem to be slower.

One thing is for sure - if you're looking for performance improvements the way you write the code is extremely important!

Here a JS perf test that shows the massive improvements when typing out the code fully rather than checking for "falsey" values (e.g. if (string) {...}) or returning "falsey" values where a boolean is expected.

Hope this helps someone

Unexpected 'else' in "else" error

You need to rearrange your curly brackets. Your first statement is complete, so R interprets it as such and produces syntax errors on the other lines. Your code should look like:

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else {
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)       
} 

To put it more simply, if you have:

if(condition == TRUE) x <- TRUE
else x <- FALSE

Then R reads the first line and because it is complete, runs that in its entirety. When it gets to the next line, it goes "Else? Else what?" because it is a completely new statement. To have R interpret the else as part of the preceding if statement, you must have curly brackets to tell R that you aren't yet finished:

if(condition == TRUE) {x <- TRUE
 } else {x <- FALSE}

How do I update a model value in JavaScript in a Razor view?

The model (@Model) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.

What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor will suffice.

However, you will want to change your foreach loop to a for loop. The final solution will look something like this:

for (int i = 0 ; i < Model.Post; i++)
{
    <br/>
    <b>Posted by :</b> @Model.Post[i].Username <br/>
    <span>@Model.Post[i].Content</span> <br/>
    if(Model.loginuser == Model.username)
    {
        @Html.HiddenFor(model => model.Post[i].PostID)
        @Html.TextAreaFor(model => model.addcomment.Content)
        <button type="submit">Add Comment</button>
    }
}

How do I use the JAVA_OPTS environment variable?

JAVA_OPTS is environment variable used by tomcat in its startup/shutdown script to configure params.

You can set it in linux by

export JAVA_OPTS="-Djava.awt.headless=true" 

Git - How to close commit editor?

In Mac 1.Press shift+Z shift+Z (capital Z twice).

SQL, How to convert VARCHAR to bigint?

This is the answer

(CASE
  WHEN
    (isnumeric(ts.TimeInSeconds) = 1) 
  THEN
    CAST(ts.TimeInSeconds AS bigint)
  ELSE
    0
  END) AS seconds

phantomjs not waiting for "full" page load

Maybe you can use the onResourceRequested and onResourceReceived callbacks to detect asynchronous loading. Here's an example of using those callbacks from their documentation:

var page = require('webpage').create();
page.onResourceRequested = function (request) {
    console.log('Request ' + JSON.stringify(request, undefined, 4));
};
page.onResourceReceived = function (response) {
    console.log('Receive ' + JSON.stringify(response, undefined, 4));
};
page.open(url);

Also, you can look at examples/netsniff.js for a working example.

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

add this to your stylesheet. line-height should match the height of your logo

.navbar-nav li a {
 line-height: 50px;
}

Check out the fiddle at: http://jsfiddle.net/nD4tW/

Horizontal scroll css?

I figured it this way:

* { padding: 0; margin: 0 }
body { height: 100%; white-space: nowrap }
html { height: 100% }

.red { background: red }
.blue { background: blue }
.yellow { background: yellow }

.header { width: 100%; height: 10%; position: fixed }
.wrapper { width: 1000%; height: 100%; background: green }
.page { width: 10%; height: 100%; float: left }

<div class="header red"></div>
<div class="wrapper">
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
</div>

I have the wrapper at 1000% and ten pages at 10% each. I set mine up to still have "pages" with each being 100% of the window (color coded). You can do eight pages with an 800% wrapper. I guess you can leave out the colors and have on continues page. I also set up a fixed header, but that's not necessary. Hope this helps.

how to convert integer to string?

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

Retrieving parameters from a URL

In pure Python:

def get_param_from_url(url, param_name):
    return [i.split("=")[-1] for i in url.split("?", 1)[-1].split("&") if i.startswith(param_name + "=")][0]

Best approach to real time http streaming to HTML5 video client

I wrote an HTML5 video player around broadway h264 codec (emscripten) that can play live (no delay) h264 video on all browsers (desktop, iOS, ...).

Video stream is sent through websocket to the client, decoded frame per frame and displayed in a canva (using webgl for acceleration)

Check out https://github.com/131/h264-live-player on github.

Getting attribute using XPath

How could I get the value of lang (where lang=eng in book title), for the first element?

Use:

/*/book[1]/title/@lang

This means:

Select the lang attribute of the title element that is a child of the first book child of the top element of the XML document.

To get just the string value of this attribute use the standard XPath function string():

string(/*/book[1]/title/@lang)

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

You can also run docker build with -f option

docker build -t ubuntu-test:latest -f Dockerfile.custom .

Regex doesn't work in String.matches()

String.matches returns whether the whole string matches the regex, not just any substring.

How can I combine hashes in Perl?

For hash references. You should use curly braces like the following:

$hash_ref1 = {%$hash_ref1, %$hash_ref2};

and not the suggested answer above using parenthesis:

$hash_ref1 = ($hash_ref1, $hash_ref2);

Carousel with Thumbnails in Bootstrap 3.0

Just found out a great plugin for this:

http://flexslider.woothemes.com/

Regards

Javascript date.getYear() returns 111 in 2011?

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getYear

getYear is no longer used and has been replaced by the getFullYear method.

The getYear method returns the year minus 1900; thus:

  • For years greater than or equal to 2000, the value returned by getYear is 100 or greater. For example, if the year is 2026, getYear returns 126.
  • For years between and including 1900 and 1999, the value returned by getYear is between 0 and 99. For example, if the year is 1976, getYear returns 76.
  • For years less than 1900, the value returned by getYear is less than 0. For example, if the year is 1800, getYear returns -100.
  • To take into account years before and after 2000, you should use getFullYear instead of getYear so that the year is specified in full.

Command to list all files in a folder as well as sub-folders in windows

The below post gives the solution for your scenario.

dir /s /b /o:gn

/S Displays files in specified directory and all subdirectories.

/B Uses bare format (no heading information or summary).

/O List by files in sorted order.

jQuery map vs. each

The each function iterates over an array, calling the supplied function once per element, and setting this to the active element. This:

function countdown() {
    alert(this + "..");
}

$([5, 4, 3, 2, 1]).each(countdown);

will alert 5.. then 4.. then 3.. then 2.. then 1..

Map on the other hand takes an array, and returns a new array with each element changed by the function. This:

function squared() {
    return this * this;
}

var s = $([5, 4, 3, 2, 1]).map(squared);

would result in s being [25, 16, 9, 4, 1].

How to vertically align text inside a flexbox?

The most voted answer is for solving this specific problem posted by OP, where the content (text) was being wrapped inside an inline-block element. Some cases may be about centering a normal element vertically inside a container, which also applied in my case, so for that all you need is:

align-self: center;

Get city name using geolocation

You would do something like that using Google API.

Please note you must include the google maps library for this to work. Google geocoder returns a lot of address components so you must make an educated guess as to which one will have the city.

"administrative_area_level_1" is usually what you are looking for but sometimes locality is the city you are after.

Anyhow - more details on google response types can be found here and here.

Below is the code that should do the trick:

<!DOCTYPE html> 
<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Reverse Geocoding</title> 

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
  var geocoder;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction(){
    alert("Geocoder failed");
}

  function initialize() {
    geocoder = new google.maps.Geocoder();



  }

  function codeLatLng(lat, lng) {

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      console.log(results)
        if (results[1]) {
         //formatted address
         alert(results[0].formatted_address)
        //find country name
             for (var i=0; i<results[0].address_components.length; i++) {
            for (var b=0;b<results[0].address_components[i].types.length;b++) {

            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                    //this is the object you are looking for
                    city= results[0].address_components[i];
                    break;
                }
            }
        }
        //city data
        alert(city.short_name + " " + city.long_name)


        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }
</script> 
</head> 
<body onload="initialize()"> 

</body> 
</html> 

How to get exact browser name and version?

Since some codes gave a wrong result for Edge and Opera, I suggest to try this code:

$popularBrowsers = ["Opera","OPR/", "Edg", "Chrome", "Safari", "Firefox", "MSIE", "Trident"];

$userAgent = $_SERVER['HTTP_USER_AGENT'];
$userBrowser = 'Other less popular browsers';
foreach ($popularBrowsers as $browser) {
    if (strpos($userAgent, $browser) !== false) {
        $userBrowser = $browser;
        break;
    }
}

switch ($userBrowser) {
    case 'OPR/':
        $userBrowser = 'Opera';
        break;
    case 'MSIE':
        $userBrowser = 'Internet Explorer';
        break;

    case 'Trident':
        $userBrowser = 'Internet Explorer';
        break;

    case 'Edg':
        $userBrowser = 'Microsoft Edge';
        break;
}

echo "Your browser: " . $userBrowser;

For information about agent strings for different browsers and some similarities in them, please refer to: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent

In Perl, how can I read an entire file into a string?

These are all good answers. BUT if you're feeling lazy, and the file isn't that big, and security is not an issue (you know you don't have a tainted filename), then you can shell out:

$x=`cat /tmp/foo`;    # note backticks, qw"cat ..." also works

How does Facebook disable the browser's integrated Developer Tools?

My simple way, but it can help for further variations on this subject. List all methods and alter them to useless.

  Object.getOwnPropertyNames(console).filter(function(property) {
     return typeof console[property] == 'function';
  }).forEach(function (verb) {
     console[verb] =function(){return 'Sorry, for security reasons...';};
  });

How can I prevent the backspace key from navigating back?

This code works on all browsers and swallows the backspace key when not on a form element, or if the form element is disabled|readOnly. It is also efficient, which is important when it is executing on every key typed in.

$(function(){
    /*
     * this swallows backspace keys on any non-input element.
     * stops backspace -> back
     */
    var rx = /INPUT|SELECT|TEXTAREA/i;

    $(document).bind("keydown keypress", function(e){
        if( e.which == 8 ){ // 8 == backspace
            if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
                e.preventDefault();
            }
        }
    });
});

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

Android - Package Name convention

But if your Android App is only for personal purpose or created by you alone, you can use:

me.app_name.app

How to create a new text file using Python

# Method 1
f = open("Path/To/Your/File.txt", "w")   # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name)    # Write inside file 
f.close()                                # Close file 

# Method 2
with open("Path/To/Your/File.txt", "w") as f:   # Opens file and casts as f 
    f.write("Hello World form " + f.name)       # Writing
    # File closed automatically

There are many more methods but these two are most common. Hope this helped!

Relative instead of Absolute paths in Excel VBA

You could use one of these for the relative path root:

ActiveWorkbook.Path
ThisWorkbook.Path
App.Path

How to create timer events using C++ 11?

Made a simple implementation of what I believe to be what you want to achieve. You can use the class later with the following arguments:

  • int (milliseconds to wait until to run the code)
  • bool (if true it returns instantly and runs the code after specified time on another thread)
  • variable arguments (exactly what you'd feed to std::bind)

You can change std::chrono::milliseconds to std::chrono::nanoseconds or microseconds for even higher precision and add a second int and a for loop to specify for how many times to run the code.

Here you go, enjoy:

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

class later
{
public:
    template <class callable, class... arguments>
    later(int after, bool async, callable&& f, arguments&&... args)
    {
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));

        if (async)
        {
            std::thread([after, task]() {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
            }).detach();
        }
        else
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
        }
    }

};

void test1(void)
{
    return;
}

void test2(int a)
{
    printf("%i\n", a);
    return;
}

int main()
{
    later later_test1(1000, false, &test1);
    later later_test2(1000, false, &test2, 101);

    return 0;
}

Outputs after two seconds:

101

Save PHP array to MySQL?

There is no good way to store an array into a single field.

You need to examine your relational data and make the appropriate changes to your schema. See example below for a reference to this approach.

If you must save the array into a single field then the serialize() and unserialize() functions will do the trick. But you cannot perform queries on the actual content.

As an alternative to the serialization function there is also json_encode() and json_decode().

Consider the following array

$a = array(
    1 => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    ),
    2 => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    ),
);

To save it in the database you need to create a table like this

$c = mysql_connect($server, $username, $password);
mysql_select_db('test');
$r = mysql_query(
    'DROP TABLE IF EXISTS test');
$r = mysql_query(
    'CREATE TABLE test (
      id INTEGER UNSIGNED NOT NULL,
      a INTEGER UNSIGNED NOT NULL,
      b INTEGER UNSIGNED NOT NULL,
      c INTEGER UNSIGNED NOT NULL,
      PRIMARY KEY (id)
    )');

To work with the records you can perform queries such as these (and yes this is an example, beware!)

function getTest() {
    $ret = array();
    $c = connect();
    $query = 'SELECT * FROM test';
    $r = mysql_query($query,$c);
    while ($o = mysql_fetch_array($r,MYSQL_ASSOC)) {
        $ret[array_shift($o)] = $o;
    }
    mysql_close($c);
    return $ret;
}
function putTest($t) {
    $c = connect();
    foreach ($t as $k => $v) {
        $query = "INSERT INTO test (id,".
                implode(',',array_keys($v)).
                ") VALUES ($k,".
                implode(',',$v).
            ")";
        $r = mysql_query($query,$c);
    }
    mysql_close($c);
}

putTest($a);
$b = getTest();

The connect() function returns a mysql connection resource

function connect() {
    $c = mysql_connect($server, $username, $password);
    mysql_select_db('test');
    return $c;
}

Call async/await functions in parallel

await Promise.all([someCall(), anotherCall()]); as already mention will act as a thread fence (very common in parallel code as CUDA), hence it will allow all the promises in it to run without blocking each other, but will prevent the execution to continue until ALL are resolved.

another approach that is worth to share is the Node.js async that will also allow you to easily control the amount of concurrency that is usually desirable if the task is directly linked to the use of limited resources as API call, I/O operations, etc.

// create a queue object with concurrency 2
var q = async.queue(function(task, callback) {
  console.log('Hello ' + task.name);
  callback();
}, 2);

// assign a callback
q.drain = function() {
  console.log('All items have been processed');
};

// add some items to the queue
q.push({name: 'foo'}, function(err) {
  console.log('Finished processing foo');
});

q.push({name: 'bar'}, function (err) {
  console.log('Finished processing bar');
});

// add some items to the queue (batch-wise)
q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
  console.log('Finished processing item');
});

// add some items to the front of the queue
q.unshift({name: 'bar'}, function (err) {
  console.log('Finished processing bar');
});

Credits to the Medium article autor (read more)

Rebase feature branch onto another feature branch

  1. Switch to Branch2

    git checkout Branch2
    
  2. Apply the current (Branch2) changes on top of the Branch1 changes, staying in Branch2:

    git rebase Branch1
    

Which would leave you with the desired result in Branch2:

a -- b -- c                      <-- Master
           \
            d -- e               <-- Branch1
           \
            d -- e -- f' -- g'   <-- Branch2

You can delete Branch1.

Aren't Python strings immutable? Then why does a + " " + b work?

The string objects themselves are immutable.

The variable, a, which points to the string, is mutable.

Consider:

a = "Foo"
# a now points to "Foo"
b = a
# b points to the same "Foo" that a points to
a = a + a
# a points to the new string "FooFoo", but b still points to the old "Foo"

print a
print b
# Outputs:

# FooFoo
# Foo

# Observe that b hasn't changed, even though a has.

jQuery when element becomes visible

(function() {
    var ev = new $.Event('display'),
        orig = $.fn.css;
    $.fn.css = function() {
        orig.apply(this, arguments);
        $(this).trigger(ev);
    }
})();

$('#element').bind('display', function(e) {
    alert("display has changed to :" + $(this).attr('style') );
});

$('#element').css("display", "none")// i change the style in this line !!
$('#element').css("display", "block")// i change the style in this line !!

http://fiddle.jshell.net/prollygeek/gM8J2/3/

changes will be alerted.

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

Please DISCARD the tablespace before IMPORT

I got same issue solution is below

  1. First you have to drop your database name. if your database is not deleting you have flow me. For Windows system your directory will be C:/xampp/mysql/data/yourdabasefolder remove "yourdabasefolder"

  2. Again you have to create new database and import your old sql file. It will be work

Thanks

True and False for && logic and || Logic table

I think You ask for Boolean algebra which describes the output of various operations performed on boolean variables. Just look at the article on Wikipedia.

How can I specify a local gem in my Gemfile?

In order to use local gem repository in a Rails project, follow the steps below:

  1. Check if your gem folder is a git repository (the command is executed in the gem folder)

    git rev-parse --is-inside-work-tree
    
  2. Getting repository path (the command is executed in the gem folder)

    git rev-parse --show-toplevel
    
  3. Setting up a local override for the rails application

    bundle config local.GEM_NAME /path/to/local/git/repository
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository is the output of the command in point 2

  4. In your application Gemfile add the following line:

    gem 'GEM_NAME', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    
  5. Running bundle install should give something like this:

    Using GEM_NAME (0.0.1) from git://github.com/GEM_NAME/GEM_NAME.git (at /path/to/local/git/repository) 
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository from point 2

  6. Finally, run bundle list, not gem list and you should see something like this:

    GEM_NAME (0.0.1 5a68b88)
    

    where GEM_NAME is the name of your gem


A few important cases I am observing using:

Rails 4.0.2  
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux] 
Ubuntu 13.10  
RubyMine 6.0.3
  • It seems RubyMine is not showing local gems as an external library. More information about the bug can be found here and here
  • When I am changing something in the local gem, in order to be loaded in the rails application I should stop/start the rails server
  • If I am changing the version of the gem, stopping/starting the Rails server gives me an error. In order to fix it, I am specifying the gem version in the rails application Gemfile like this:

    gem 'GEM_NAME', '0.0.2', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    

Accessing a Dictionary.Keys Key through a numeric index

I don't know if this would work because I'm pretty sure that the keys aren't stored in the order they are added, but you could cast the KeysCollection to a List and then get the last key in the list... but it would be worth having a look.

The only other thing I can think of is to store the keys in a lookup list and add the keys to the list before you add them to the dictionary... it's not pretty tho.

Invalid argument supplied for foreach()

I am not sure if this is the case but this problem seems to occur a number of times when migrating wordpress sites or migrating dynamic sites in general. If this is the case make sure the hosting you are migrating to uses the same PHP version your old site uses.

If you are not migrating your site and this is just a problem that has come up try updating to PHP 5. This takes care of some of these problems. Might seem like a silly solution but did the trick for me.

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try this:

import matplotlib as plt

after importing the file we can use matplotlib library but remember to use it as plt

df.plt(kind='line',figsize=(10,5))

after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.

Int division: Why is the result of 1/3 == 0?

1 and 3 are integer contants and so Java does an integer division which's result is 0. If you want to write double constants you have to write 1.0 and 3.0.

How to make in CSS an overlay over an image?

You can achieve this with this simple CSS/HTML:

.image-container {
    position: relative;
    width: 200px;
    height: 300px;
}
.image-container .after {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: none;
    color: #FFF;
}
.image-container:hover .after {
    display: block;
    background: rgba(0, 0, 0, .6);
}

HTML

<div class="image-container">
    <img src="http://lorempixel.com/300/200" />
    <div class="after">This is some content</div>
</div>

Demo: http://jsfiddle.net/6Mt3Q/


UPD: Here is one nice final demo with some extra stylings.

_x000D_
_x000D_
.image-container {_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
}_x000D_
.image-container img {display: block;}_x000D_
.image-container .after {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    display: none;_x000D_
    color: #FFF;_x000D_
}_x000D_
.image-container:hover .after {_x000D_
    display: block;_x000D_
    background: rgba(0, 0, 0, .6);_x000D_
}_x000D_
.image-container .after .content {_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
    font-family: Arial;_x000D_
    text-align: center;_x000D_
    width: 100%;_x000D_
    box-sizing: border-box;_x000D_
    padding: 5px;_x000D_
}_x000D_
.image-container .after .zoom {_x000D_
    color: #DDD;_x000D_
    font-size: 48px;_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    margin: -30px 0 0 -19px;_x000D_
    height: 50px;_x000D_
    width: 45px;_x000D_
    cursor: pointer;_x000D_
}_x000D_
.image-container .after .zoom:hover {_x000D_
    color: #FFF;_x000D_
}
_x000D_
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="image-container">_x000D_
    <img src="http://lorempixel.com/300/180" />_x000D_
    <div class="after">_x000D_
        <span class="content">This is some content. It can be long and span several lines.</span>_x000D_
        <span class="zoom">_x000D_
            <i class="fa fa-search"></i>_x000D_
        </span>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Use multiple @font-face rules in CSS

Note, you may also be interested in:

Custom web font not working in IE9

Which includes a more descriptive breakdown of the CSS you see below (and explains the tweaks that make it work better on IE6-9).


@font-face {
  font-family: 'Bumble Bee';
  src: url('bumblebee-webfont.eot');
  src: local('?'), 
       url('bumblebee-webfont.woff') format('woff'), 
       url('bumblebee-webfont.ttf') format('truetype'), 
       url('bumblebee-webfont.svg#webfontg8dbVmxj') format('svg');
}

@font-face {
  font-family: 'GestaReFogular';
  src: url('gestareg-webfont.eot');
  src: local('?'), 
       url('gestareg-webfont.woff') format('woff'), 
       url('gestareg-webfont.ttf') format('truetype'), 
       url('gestareg-webfont.svg#webfontg8dbVmxj') format('svg');
}

body {
  background: #fff url(../images/body-bg-corporate.gif) repeat-x;
  padding-bottom: 10px;
  font-family: 'GestaRegular', Arial, Helvetica, sans-serif;
}

h1 {
  font-family: "Bumble Bee", "Times New Roman", Georgia, Serif;
}

And your follow-up questions:

Q. I would like to use a font such as "Bumble bee," for example. How can I use @font-face to make that font available on the user's computer?

Note that I don't know what the name of your Bumble Bee font or file is, so adjust accordingly, and that the font-face declaration should precede (come before) your use of it, as I've shown above.

Q. Can I still use the other @font-face typeface "GestaRegular" as well? Can I use both in the same stylesheet?

Just list them together as I've shown in my example. There is no reason you can't declare both. All that @font-face does is instruct the browser to download and make a font-family available. See: http://iliadraznin.com/2009/07/css3-font-face-multiple-weights

PHPMailer character encoding issues

I work myself this way

  $mail->FromName = utf8_decode($_POST['name']);

http://php.net/manual/en/function.utf8-decode.php

@Autowired and static method

Use AppContext. Make sure you create a bean in your context file.

private final static Foo foo = AppContext.getApplicationContext().getBean(Foo.class);

public static void randomMethod() {
     foo.doStuff();
}

SQL permissions for roles

SQL-Server follows the principle of "Least Privilege" -- you must (explicitly) grant permissions.

'does it mean that they wont be able to update 4 and 5 ?'

If your users in the doctor role are only in the doctor role, then yes.

However, if those users are also in other roles (namely, other roles that do have access to 4 & 5), then no.

More Information: http://msdn.microsoft.com/en-us/library/bb669084%28v=vs.110%29.aspx

XAMPP - Apache could not start - Attempting to start Apache service

I had the same problem but was because I had already previously installed xampp , and I tried to install a newer version , then I installed the newer version in another file directory (I named the file directory xampp2). I solved the problem after uninstall the newer version, rename the old one (I renamed as xamppold), and installing xampp again.

I guess if you didn't installed xampp in another file directory or something like that , it should be enough to reinstall xampp. If you are worried about your files , you always can make a backup before reinstalling xampp.

I solved the problem after watching the xampp activity log (the list of the bottom) and realizing xampp was trying to open the custom file path but I had another route path. If the first option didn't worked, at least you can scroll up in the activity log and see whats the error you get while starting as admin and trying to re install the Apache module or trying to start the module.

You may wander why I didn't just simply uninstall the whole thing from the beginning , and the answer would be I have tweak a couple of things of xampp for some different projects (from changing the ports , to add .dll to run mongo.db in Apache), and I'm just too lazy to re-do everything again :b

I hope my answer can be helpful for anyone since is my first time writing in stackoverflow :)

Cheers

SQL JOIN vs IN performance?

Each database's implementation but you can probably guess that they all solve common problems in more or less the same way. If you are using MSSQL have a look at the execution plan that is generated. You can do this by turning on the profiler and executions plans. This will give you a text version when you run the command.

I am not sure what version of MSSQL you are using but you can get a graphical one in SQL Server 2000 in the query analyzer. I am sure that this functionality is lurking some where in SQL Server Studio Manager in later versions.

Have a look at the exeuction plan. As far as possible avoid table scans unless of course your table is small in which case a table scan is faster than using an index. Read up on the different join operations that each different scenario produces.

What is the difference between .py and .pyc files?

Python compiles the .py and saves files as .pyc so it can reference them in subsequent invocations.

There's no harm in deleting them, but they will save compilation time if you're doing lots of processing.

Matching an empty input box using CSS

Updating the value of a field does not update its value attribute in the DOM so that's why your selector is always matching a field, even when it's not actually empty.

Instead use the invalid pseudo-class to achieve what you want, like so:

_x000D_
_x000D_
input:required {_x000D_
  border: 1px solid green;_x000D_
}_x000D_
input:required:invalid {_x000D_
  border: 1px solid red;_x000D_
}
_x000D_
<input required type="text" value="">_x000D_
_x000D_
<input required type="text" value="Value">
_x000D_
_x000D_
_x000D_

Remove querystring from URL

var path = "path/to/myfile.png?foo=bar#hash";

console.log(
    path.replace(/(\?.*)|(#.*)/g, "")
);

How to convert DateTime to a number with a precision greater than days in T-SQL?

And here is a bigint version of the same

DECLARE @ts BIGINT 
SET @ts = CAST(CAST(getdate() AS TIMESTAMP) AS BIGINT)
SELECT @ts

Get the closest number out of an array

For a small range, the simplest thing is to have a map array, where, eg, the 80th entry would have the value 82 in it, to use your example. For a much larger, sparse range, probably the way to go is a binary search.

With a query language you could query for values some distance either side of your input number and then sort through the resulting reduced list. But SQL doesn't have a good concept of "next" or "previous", to give you a "clean" solution.

Difference between PCDATA and CDATA in DTD

The very main difference between PCDATA and CDATA is

PCDATA - Basically used for ELEMENTS while

CDATA - Used for Attributes of XML i.e ATTLIST

jQuery post() with serialize and extra data

I like to keep objects as objects and not do any crazy type-shifting. Here's my way

var post_vars = $('#my-form').serializeArray();
$.ajax({
  url: '//site.com/script.php',
  method: 'POST',
  data: post_vars,
  complete: function() {
    $.ajax({
      url: '//site.com/script2.php',
      method: 'POST',
      data: post_vars.concat({
        name: 'EXTRA_VAR',
        value: 'WOW THIS WORKS!'
      })
    });
  }
});

if you can't see from above I used the .concat function and passed in an object with the post variable as 'name' and the value as 'value'!

Hope this helps.

How can I make an entire HTML form "readonly"?

You can use this function to disable the form:

function disableForm(formID){
  $('#' + formID).children(':input').attr('disabled', 'disabled');
}

See the working demo here

Note that it uses jQuery.

React Native TextInput that only accepts numeric characters

First Solution

You can use keyboardType = 'numeric' for numeric keyboard.

  <View style={styles.container}>
        <Text style={styles.textStyle}>Enter Number</Text>
        <TextInput
          placeholder={'Enter number here'}
          style={styles.paragraph}
          keyboardType="numeric"
          onChangeText={value => this.onTextChanged(value)}
          value={this.state.number}
        />
      </View>

In first case punctuation marks are included ex:- . and -

Second Solution

Use regular expression to remove punctuation marks.

 onTextChanged(value) {
    // code to remove non-numeric characters from text
    this.setState({ number: value.replace(/[- #*;,.<>\{\}\[\]\\\/]/gi, '') });
  }

Please check snack link

https://snack.expo.io/@vishal7008/numeric-keyboard

How to get the first word in the string

You don't need regex to split a string on whitespace:

In [1]: text = '''WYATT    - Ranked # 855 with    0.006   %
   ...: XAVIER   - Ranked # 587 with    0.013   %
   ...: YONG     - Ranked # 921 with    0.006   %
   ...: YOUNG    - Ranked # 807 with    0.007   %'''

In [2]: print '\n'.join(line.split()[0] for line in text.split('\n'))
WYATT
XAVIER
YONG
YOUNG

Set Focus After Last Character in Text Box

Code for any Browser:

function focusCampo(id){
    var inputField = document.getElementById(id);
    if (inputField != null && inputField.value.length != 0){
        if (inputField.createTextRange){
            var FieldRange = inputField.createTextRange();
            FieldRange.moveStart('character',inputField.value.length);
            FieldRange.collapse();
            FieldRange.select();
        }else if (inputField.selectionStart || inputField.selectionStart == '0') {
            var elemLen = inputField.value.length;
            inputField.selectionStart = elemLen;
            inputField.selectionEnd = elemLen;
            inputField.focus();
        }
    }else{
        inputField.focus();
    }
}

Using jQuery to programmatically click an <a> link

<a href="#" id="myAnchor">Click me</a>

<script type="text/javascript">
$(document).ready(function(){
    $('#myAnchor').click(function(){
       window.location.href = 'index.php';
    });
})
</script>

Sort collection by multiple fields in Kotlin

Use sortedWith to sort a list with Comparator.

You can then construct a comparator using several ways:

  • compareBy, thenBy construct the comparator in a chain of calls:

    list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
    
  • compareBy has an overload which takes multiple functions:

    list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))
    

How to change node.js's console font color?

There are two ways to look at changing colors for a Node.js console today.

One is through general-purpose libraries that can decorate a text string with color tags, which you then output through the standard console.log.

The top libraries for that today:

And the other way - patching the existing console methods. One such library - manakin lets you automatically set standard colors for all your console methods (log, warn, error and info).

One significant difference from the generic color libraries - it can set colors either globally or locally, while keeping consistent syntax and output format for every Node.js console method, which you then use without having to specify the colors, as they are all set automatically.

I had to change the console background color to white because of eye problems, but the font is gray colored and it makes the messages unreadable. How can I change it?

Specifically for your problem, here's the simplest solution:

var con = require('manakin').global;
con.log.color = 30; // Use black color for console.log

It will set black color for every console.log call in your application. See more color codes.

Default colors as used by manakin:

enter image description here

Link entire table row?

Also it depends if you need to use a table element or not. You can imitate a table using CSS and make an A element the row

<div class="table" style="width:100%;">
  <a href="#" class="tr">
    <span class="td">
      cell 1
    </span>
    <span class="td">
      cell 2
    </span>
  </a>
</div>

css:

.table{display:table;}
.tr{display:table-row;}
.td{display:table-cell;}
.tr:hover{background-color:#ccc;}

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

add to your global file this action.

protected void Application_Start() {
   BundleConfig.RegisterBundles(BundleTable.Bundles);
}

How do I create a new user in a SQL Azure database?

I found this link very helpful:
https://azure.microsoft.com/en-gb/documentation/articles/sql-database-manage-logins/

It details things like:
- Azure SQL Database subscriber account
- Using Azure Active Directory users to access the database
- Server-level principal accounts (unrestricted access)
- Adding users to the dbmanager database role

I used this and Stuart's answer to do the following:
On the master database (see link as to who has permissions on this):

CREATE LOGIN [MyAdmin] with password='ReallySecurePassword'

And then on the database in question:

CREATE USER [MyAdmin] FROM LOGIN [MyAdmin]
ALTER ROLE db_owner ADD MEMBER [MyAdmin]

You can also create users like this, according to the link:

CREATE USER [[email protected]] FROM EXTERNAL PROVIDER;

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

If your dump file doesn't have DEFINER, make sure these lines below are also removed if they're there, or commented-out with --:

At the start:

-- SET @@SESSION.SQL_LOG_BIN= 0;
-- SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';

At the end:

-- SET @@SESSION.SQL_LOG_BIN = @MYSQLDUMP_TEMP_LOG_BIN;

How to install Java SDK on CentOS?

Here is a detailed information on setting up Java and its paths on CentOS6.

Below steps are for the installation of latest Java version 8:

  1. Download java rpm package from Oracle site. (jdk-8-linux-x64.rpm)
  2. Install from the rpm. (rpm -Uvh jdk-8-linux-x64.rpm)
  3. Open /etc/profile, and set the java paths, save it.
  4. Check the java installation path, and java version, with the commands: which java, java -version

Now you can test the installation with a sample java program

Android dex gives a BufferOverflowException when building

I solved this problem. Just make this change in the project properties file:

target=android-18
sdk.build.tools=18.1.1

And in the manifest file:

uses-sdk android:minSdkVersion="8"
android:targetSdkVersion="18"

Bootstrap: add margin/padding space between columns

I had the same issue and worked it out by nesting a div inside bootstrap col and adding padding to it. Something like:

<div class="container">
 <div class="row">
  <div class="col-md-4">
   <div class="custom-box">Your content with padding</div>
  </div>
  <div class="col-md-4">
   <div class="custom-box">Your content with padding</div>
  </div>
  <div class="col-md-4">
   <div class="custom-box">Your content with padding</div>
  </div>
 </div>
</div>

How to get $HOME directory of different user in bash script?

If the user doesn't exist, getent will return an error.

Here's a small shell function that doesn't ignore the exit code of getent:

get_home() {
  local result; result="$(getent passwd "$1")" || return
  echo $result | cut -d : -f 6
}

Here's a usage example:

da_home="$(get_home missing_user)" || {
  echo 'User does NOT exist!'; exit 1
}

# Now do something with $da_home
echo "Home directory is: '$da_home'"

Wi-Fi Direct and iOS Support

According to this thread:

The peer-to-peer Wi-Fi implemented by iOS (and recent versions of OS X) is not compatible with Wi-Fi Direct. Note Just as an aside, you can access peer-to-peer Wi-Fi without using Multipeer Connectivity. The underlying technology is Bonjour + TCP/IP, and you can access that directly from your app. The WiTap sample code shows how.

React: trigger onChange if input value is changing by state?

I think you should change that like so:

<input value={this.state.value} onChange={(e) => {this.handleChange(e)}}/>

That is in principle the same as onClick={this.handleClick.bind(this)} as you did on the button.

So if you want to call handleChange() when the button is clicked, than:

<button onClick={this.handleChange.bind(this)}>Change Input</button>

or

handleClick () {
  this.setState({value: 'another random text'});
  this.handleChange();
}

how to detect search engine bots with php?

I use this function ... part of the regex comes from prestashop but I added some more bot to it.

    public function isBot()
{
    $bot_regex = '/BotLink|bingbot|AhrefsBot|ahoy|AlkalineBOT|anthill|appie|arale|araneo|AraybOt|ariadne|arks|ATN_Worldwide|Atomz|bbot|Bjaaland|Ukonline|borg\-bot\/0\.9|boxseabot|bspider|calif|christcrawler|CMC\/0\.01|combine|confuzzledbot|CoolBot|cosmos|Internet Cruiser Robot|cusco|cyberspyder|cydralspider|desertrealm, desert realm|digger|DIIbot|grabber|downloadexpress|DragonBot|dwcp|ecollector|ebiness|elfinbot|esculapio|esther|fastcrawler|FDSE|FELIX IDE|ESI|fido|H?m?h?kki|KIT\-Fireball|fouineur|Freecrawl|gammaSpider|gazz|gcreep|golem|googlebot|griffon|Gromit|gulliver|gulper|hambot|havIndex|hotwired|htdig|iajabot|INGRID\/0\.1|Informant|InfoSpiders|inspectorwww|irobot|Iron33|JBot|jcrawler|Teoma|Jeeves|jobo|image\.kapsi\.net|KDD\-Explorer|ko_yappo_robot|label\-grabber|larbin|legs|Linkidator|linkwalker|Lockon|logo_gif_crawler|marvin|mattie|mediafox|MerzScope|NEC\-MeshExplorer|MindCrawler|udmsearch|moget|Motor|msnbot|muncher|muninn|MuscatFerret|MwdSearch|sharp\-info\-agent|WebMechanic|NetScoop|newscan\-online|ObjectsSearch|Occam|Orbsearch\/1\.0|packrat|pageboy|ParaSite|patric|pegasus|perlcrawler|phpdig|piltdownman|Pimptrain|pjspider|PlumtreeWebAccessor|PortalBSpider|psbot|Getterrobo\-Plus|Raven|RHCS|RixBot|roadrunner|Robbie|robi|RoboCrawl|robofox|Scooter|Search\-AU|searchprocess|Senrigan|Shagseeker|sift|SimBot|Site Valet|skymob|SLCrawler\/2\.0|slurp|ESI|snooper|solbot|speedy|spider_monkey|SpiderBot\/1\.0|spiderline|nil|suke|http:\/\/www\.sygol\.com|tach_bw|TechBOT|templeton|titin|topiclink|UdmSearch|urlck|Valkyrie libwww\-perl|verticrawl|Victoria|void\-bot|Voyager|VWbot_K|crawlpaper|wapspider|WebBandit\/1\.0|webcatcher|T\-H\-U\-N\-D\-E\-R\-S\-T\-O\-N\-E|WebMoose|webquest|webreaper|webs|webspider|WebWalker|wget|winona|whowhere|wlm|WOLP|WWWC|none|XGET|Nederland\.zoek|AISearchBot|woriobot|NetSeer|Nutch|YandexBot|YandexMobileBot|SemrushBot|FatBot|MJ12bot|DotBot|AddThis|baiduspider|SeznamBot|mod_pagespeed|CCBot|openstat.ru\/Bot|m2e/i';
    $userAgent = empty($_SERVER['HTTP_USER_AGENT']) ? FALSE : $_SERVER['HTTP_USER_AGENT'];
    $isBot = !$userAgent || preg_match($bot_regex, $userAgent);

    return $isBot;
}

Anyway take care that some bots uses browser like user agent to fake their identity
( I got many russian ip that has this behaviour on my site )

One distinctive feature of most of the bot is that they don't carry any cookie and so no session is attached to them.
( I am not sure how but this is for sure the best way to track them )

How does java do modulus calculations with negative numbers?

To overcome this, you could add 64 (or whatever your modulus base is) to the negative value until it is positive

int k = -13;
int modbase = 64;

while (k < 0) {
    k += modbase;
}

int result = k % modbase;

The result will still be in the same equivalence class.

How to find the lowest common ancestor of two nodes in any binary tree?

In scala, you can:

  abstract class Tree
  case class Node(a:Int, left:Tree, right:Tree) extends Tree
  case class Leaf(a:Int) extends Tree

  def lca(tree:Tree, a:Int, b:Int):Tree = {
    tree match {
      case Node(ab,l,r) => {
        if(ab==a || ab ==b) tree else {
          val temp = lca(l,a,b);
          val temp2 = lca(r,a,b);
          if(temp!=null && temp2 !=null)
            tree
          else if (temp==null && temp2==null)
            null
          else if (temp==null) r else l
        }

      }
      case Leaf(ab) => if(ab==a || ab ==b) tree else null
    }
  }

What is the difference between a static and const variable?

A static variable can get an initial value only one time. This means that if you have code such as "static int a=0" in a sample function, and this code is executed in a first call of this function, but not executed in a subsequent call of the function; variable (a) will still have its current value (for example, a current value of 5), because the static variable gets an initial value only one time.

A constant variable has its value constant in whole of the code. For example, if you set the constant variable like "const int a=5", then this value for "a" will be constant in whole of your program.

What charset does Microsoft Excel use when saving files?

I had a similar problem last week. I received a number of CSV files with varying encodings. Before importing into the database I then used the chardet libary to automatically sniff out the correct encoding.

Chardet is a port from Mozillas character detection engine and if the sample size is large enough (one accentuated character will not do) works really well.

Apache and IIS side by side (both listening to port 80) on windows2003

Either two different IP addresses (like recommended) or one web server is reverse-proxying the other (which is listening on a port <>80).

For instance: Apache listens on port 80, IIS on port 8080. Every http request goes to Apache first (of course). You can then decide to forward every request to a particular (named virtual) domain or every request that contains a particular directory (e.g. http://www.example.com/winapp/) to the IIS.

Advantage of this concept is that you have only one server listening to the public instead of two, you are more flexible as with two distinct servers.

Drawbacks: some webapps are crappily designed and a real pain in the ass to integrate into a reverse-proxy infrastructure. A working IIS webapp is dependent on a working Apache, so we have some inter-dependencies.

Can I embed a custom font in an iPhone application?

Better solution is to add a new property "Fonts provided by application" to your info.plist file.

Then, you can use your custom font like normal UIFont.

"Line contains NULL byte" in CSV reader (Python)

Turning my linux environment into a clean complete UTF-8 environment made the trick for me. Try the following in your command line:

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8

How to set an image as a background for Frame in Swing GUI of java?

There is no concept of a "background image" in a JPanel, so one would have to write their own way to implement such a feature.

One way to achieve this would be to override the paintComponent method to draw a background image on each time the JPanel is refreshed.

For example, one would subclass a JPanel, and add a field to hold the background image, and override the paintComponent method:

public class JPanelWithBackground extends JPanel {

  private Image backgroundImage;

  // Some code to initialize the background image.
  // Here, we use the constructor to load the image. This
  // can vary depending on the use case of the panel.
  public JPanelWithBackground(String fileName) throws IOException {
    backgroundImage = ImageIO.read(new File(fileName));
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw the background image.
    g.drawImage(backgroundImage, 0, 0, this);
  }
}

(Above code has not been tested.)

The following code could be used to add the JPanelWithBackground into a JFrame:

JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));

In this example, the ImageIO.read(File) method was used to read in the external JPEG file.

Peak-finding algorithm for Python/SciPy

There is a function in scipy named scipy.signal.find_peaks_cwt which sounds like is suitable for your needs, however I don't have experience with it so I cannot recommend..

http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks_cwt.html

How to export html table to excel or pdf in php

Easiest way to export Excel to Html table

$file_name ="file_name.xls";
$excel_file="Your Html Table Code";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file_name");
echo $excel_file;

How to convert minutes to Hours and minutes (hh:mm) in java

I use this function for my projects:

 public static String minuteToTime(int minute) {
    int hour = minute / 60;
    minute %= 60;
    String p = "AM";
    if (hour >= 12) {
        hour %= 12;
        p = "PM";
    }
    if (hour == 0) {
        hour = 12;
    }
    return (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute) + " " + p;
}

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

AssemblyInformationalVersion and AssemblyFileVersion are displayed when you view the "Version" information on a file through Windows Explorer by viewing the file properties. These attributes actually get compiled in to a VERSION_INFO resource that is created by the compiler.

AssemblyInformationalVersion is the "Product version" value. AssemblyFileVersion is the "File version" value.

The AssemblyVersion is specific to .NET assemblies and is used by the .NET assembly loader to know which version of an assembly to load/bind at runtime.

Out of these, the only one that is absolutely required by .NET is the AssemblyVersion attribute. Unfortunately it can also cause the most problems when it changes indiscriminately, especially if you are strong naming your assemblies.

app.config for a class library

If you want to configure your project logging using log4Net, while using a class library, There is no actual need of any config file. You can configure your log4net logger in a class and can use that class as library.

As log4net provides all the options to configure it.

Please find the code below.

public static void SetLogger(string pathName, string pattern)
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = pattern;
            patternLayout.ActivateOptions();

            RollingFileAppender roller = new RollingFileAppender();
            roller.AppendToFile = false;
            roller.File = pathName;
            roller.Layout = patternLayout;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize = "1GB";
            roller.RollingStyle = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName = true;
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            MemoryAppender memory = new MemoryAppender();
            memory.ActivateOptions();
            hierarchy.Root.AddAppender(memory);

            hierarchy.Root.Level = log4net.Core.Level.Info;
            hierarchy.Configured = true;
      }

Now instead of calling XmlConfigurator.Configure(new FileInfo("app.config")) you can directly call SetLogger with desired path and pattern to set the logger in Global.asax application start function.

And use the below code to log the error.

        public static void getLog(string className, string message)
        {
            log4net.ILog iLOG = LogManager.GetLogger(className);
            iLOG.Error(message);    // Info, Fatal, Warn, Debug
        }

By using following code you need not to write a single line neither in application web.config nor inside the app.config of library.

Disable/enable an input with jQuery?

Disable true for input type :

In case of a specific input type (Ex. Text type input)

$("input[type=text]").attr('disabled', true);

For all type of input type

$("input").attr('disabled', true);

Copy all the lines to clipboard

If your fingers default to CTRL-A CTRL-C, then try the mappings from $VIMRUNTIME/mswin.vim.

" CTRL-C and CTRL-Insert are Copy
vnoremap <C-C> "+y

" CTRL-A is Select all
noremap <C-A> gggH<C-O>G
inoremap <C-A> <C-O>gg<C-O>gH<C-O>G
cnoremap <C-A> <C-C>gggH<C-O>G
onoremap <C-A> <C-C>gggH<C-O>G
snoremap <C-A> <C-C>gggH<C-O>G
xnoremap <C-A> <C-C>ggVG

I have them mapped to <Leader><C-a> and <Leader><C-c>.

What is an opaque response, and what purpose does it serve?

javascript is a bit tricky getting the answer, I fixed it by getting the api from the backend and then calling it to the frontend.

public function get_typechange () {

    $ url = "https://........";
    $ json = file_get_contents ($url);
    $ data = json_decode ($ json, true);
    $ resp = json_encode ($data);
    $ error = json_last_error_msg ();
    return $ resp;

}

How can I create an object based on an interface file definition in TypeScript?

Many of the solutions so far posted use type assertions and therefor do not throw compilation errors if required interface properties are omitted in the implementation.

For those interested in some other robust, compact solutions:

Option 1: Instantiate an anonymous class which implements the interface:

new class implements MyInterface {
  nameFirst = 'John';
  nameFamily = 'Smith';
}();

Option 2: Create a utility function:

export function impl<I>(i: I) { return i; }

impl<MyInterface>({
  nameFirst: 'John';
  nameFamily: 'Smith';
})

composer laravel create project

I also had same problem then I found this on there documentation page

So if you want to create a project by name of test_laravel in directory /Applications/MAMP/htdocs/ then what you need to do is

go to your project parent directory

cd /Applications/MAMP/htdocs

and fire this command

composer create-project laravel/laravel test_laravel --prefer-dist

that's it, this is really easy and it also creates Application Key automatically for you

What is event bubbling and capturing?

I have found this tutorial at javascript.info to be very clear in explaining this topic. And its 3-points summary at the end is really talking to the crucial points. I quote it here:

  1. Events first are captured down to deepest target, then bubble up. In IE<9 they only bubble.
  2. All handlers work on bubbling stage excepts addEventListener with last argument true, which is the only way to catch the event on capturing stage.
  3. Bubbling/capturing can be stopped by event.cancelBubble=true (IE) or event.stopPropagation() for other browsers.

From a Sybase Database, how I can get table description ( field names and types)?

If Sybase is SQL-92 compliant then this information is stored within the INFORMATION_SCHEMA tables.

So the following will give you a list of tables and views in any SQL-92 compliant database

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES

What does '&' do in a C++ declaration?

In this context & is causing the function to take stringname by reference. The difference between references and pointers is:

  • When you take a reference to a variable, that reference is the variable you referenced. You don't need to dereference it or anything, working with the reference is sematically equal to working with the referenced variable itself.
  • NULL is not a valid value to a reference and will result in a compiler error. So generally, if you want to use an output parameter (or a pointer/reference in general) in a C++ function, and passing a null value to that parameter should be allowed, then use a pointer (or smart pointer, preferably). If passing a null value makes no sense for that function, use a reference.
  • You cannot 're-seat' a reference. While the value of a pointer can be changed to point at something else, a reference has no similar functionality. Once you take a variable by reference, you are effectively dealing with that variable directly. Just like you can't change the value of a by writing b = 4;. A reference's value is the value of whatever it referenced.

What is correct media query for IPad Pro?

This worked for me

/* Portrait */
@media only screen 
  and (min-device-width: 834px) 
  and (max-device-width: 834px) 
  and (orientation: portrait) 
  and (-webkit-min-device-pixel-ratio: 2) {

}

/* Landscape */
@media only screen 
  and (min-width: 1112px) 
  and (max-width: 1112px) 
  and (orientation: landscape) 
  and (-webkit-min-device-pixel-ratio: 2)
 {

}

Why have header files and .cpp files?

It's the preprocessor way of declaring interfaces. You put the interface (method declarations) into the header file, and the implementation into the cpp. Applications using your library only need to know the interface, which they can access through #include.

Call apply-like function on each row of dataframe with multiple arguments from each row

Others have correctly pointed out that mapply is made for this purpose, but (for the sake of completeness) a conceptually simpler method is just to use a for loop.

for (row in 1:nrow(df)) { 
    df$newvar[row] <- testFunc(df$x[row], df$z[row]) 
}

How do I detect a click outside an element?

jQuery().ready(function(){
    $('#nav').click(function (event) {
        $(this).addClass('activ');
        event.stopPropagation();
    });

    $('html').click(function () {
        if( $('#nav').hasClass('activ') ){
            $('#nav').removeClass('activ');
        }
    });
});

Android - drawable with rounded corners at the top only

Building upon busylee's answer, this is how you can make a drawable that only has one unrounded corner (top-left, in this example):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
            <!-- A numeric value is specified in "radius" for demonstrative purposes only,
                  it should be @dimen/val_name -->
            <corners android:radius="10dp" />
        </shape>
    </item>
    <!-- To keep the TOP-LEFT corner UNROUNDED set both OPPOSITE offsets (bottom+right): -->
    <item
        android:bottom="10dp"
        android:right="10dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
        </shape>
    </item>
</layer-list>

Please note that the above drawable is not shown correctly in the Android Studio preview (2.0.0p7). To preview it anyway, create another view and use this as android:background="@drawable/...".

Checking if an object is a given type in Swift

If you just want to check the class without getting a warning because of the unused defined value (let someVariable ...), you can simply replace the let stuff with a boolean:

if (yourObject as? ClassToCompareWith) != nil {
   // do what you have to do
}
else {
   // do something else
}

Xcode proposed this when I used the let way and didn't use the defined value.

How to create a new instance from a class object in Python

This is how you can dynamically create a class named Child in your code, assuming Parent already exists... even if you don't have an explicit Parent class, you could use object...

The code below defines __init__() and then associates it with the class.

>>> child_name = "Child"
>>> child_parents = (Parent,)
>>> child body = """
def __init__(self, arg1):
    # Initialization for the Child class
    self.foo = do_something(arg1)
"""
>>> child_dict = {}
>>> exec(child_body, globals(), child_dict)
>>> childobj = type(child_name, child_parents, child_dict)
>>> childobj.__name__
'Child'
>>> childobj.__bases__
(<type 'object'>,)
>>> # Instantiating the new Child object...
>>> childinst = childobj()
>>> childinst
<__main__.Child object at 0x1c91710>
>>>

Uninstalling an MSI file from the command line without using msiexec

I would try the following syntax - it works for me.

msiexec /x filename.msi /q 

IsNothing versus Is Nothing

You should absolutely avoid using IsNothing()

Here are 4 reasons from the article IsNothing() VS Is Nothing

  1. Most importantly, IsNothing(object) has everything passed to it as an object, even value types! Since value types cannot be Nothing, it’s a completely wasted check.
    Take the following example:

    Dim i As Integer
    If IsNothing(i) Then
       ' Do something 
    End If
    

    This will compile and run fine, whereas this:

    Dim i As Integer
    If i Is Nothing Then
        '   Do something 
    End If
    

    Will not compile, instead the compiler will raise the error:

    'Is' operator does not accept operands of type 'Integer'.
    Operands must be reference or nullable types.

  2. IsNothing(object) is actually part of part of the Microsoft.VisualBasic.dll.
    This is undesirable as you have an unneeded dependency on the VisualBasic library.

  3. Its slow - 33.76% slower in fact (over 1000000000 iterations)!

  4. Perhaps personal preference, but IsNothing() reads like a Yoda Condition. When you look at a variable you're checking it's state, with it as the subject of your investigation.

    i.e. does it do x? --- NOT Is xing a property of it?

    So I think If a IsNot Nothing reads better than If Not IsNothing(a)

How can I move HEAD back to a previous location? (Detached head) & Undo commits

Quickest possible solution (just 1 step)

Use git checkout -

You will see Switched to branch <branch_name>. Confirm it's the branch you want.


Brief explanation: this command will move HEAD back to its last position. See note on outcomes at the end of this answer.


Mnemonic: this approach is a lot like using cd - to return to your previously visited directory. Syntax and the applicable cases are a pretty good match (e.g. it's useful when you actually want HEAD to return to where it was).


More methodical solution (2-steps, but memorable)

The quick approach solves the OP's question. But what if your situation is slightly different: say you have restarted Bash then found yourself with HEAD detached. In that case, here are 2 simple, easily remembered steps.

1. Pick the branch you need

Use git branch -v

You see a list of existing local branches. Grab the branch name that suits your needs.

2. Move HEAD to it

Use git checkout <branch_name>

You will see Switched to branch <branch_name>. Success!


Outcomes

With either method, you can now continue adding and committing your work as before: your next changes will be tracked on <branch_name>.

Note that both git checkout - and git checkout <branch_name> will give additional instructions if you have committed changes while HEAD was detached.

JavaScript: client-side vs. server-side validation

You must always validate on the server.

Also having validation on the client is nice for users, but is utterly insecure.

How to remove an element from an array in Swift

Given

var animals = ["cats", "dogs", "chimps", "moose"]

Remove first element

animals.removeFirst() // "cats"
print(animals)        // ["dogs", "chimps", "moose"]

Remove last element

animals.removeLast() // "moose"
print(animals)       // ["cats", "dogs", "chimps"]

Remove element at index

animals.remove(at: 2) // "chimps"
print(animals)           // ["cats", "dogs", "moose"]

Remove element of unknown index

For only one element

if let index = animals.firstIndex(of: "chimps") {
    animals.remove(at: index)
}
print(animals) // ["cats", "dogs", "moose"]

For multiple elements

var animals = ["cats", "dogs", "chimps", "moose", "chimps"]

animals = animals.filter(){$0 != "chimps"}
print(animals) // ["cats", "dogs", "moose"]

Notes

  • The above methods modify the array in place (except for filter) and return the element that was removed.
  • Swift Guide to Map Filter Reduce
  • If you don't want to modify the original array, you can use dropFirst or dropLast to create a new array.

Updated to Swift 5.2

Is it possible to put a ConstraintLayout inside a ScrollView?

I had NestedScrollView inside ConstraintLayout, and this NestedScrollView has one ConstraintLayout.

If you're facing issue with NestedScrollView,

add android:fillViewport="true" to NestedScrollView, worked.

What data type to use for money in Java?

JSR 354: Money and Currency API

JSR 354 provides an API for representing, transporting, and performing comprehensive calculations with Money and Currency. You can download it from this link:

JSR 354: Money and Currency API Download

The specification consists of the following things:

  1. An API for handling e. g. monetary amounts and currencies
  2. APIs to support interchangeable implementations
  3. Factories for creating instances of the implementation classes
  4. Functionality for calculations, conversion and formatting of monetary amounts
  5. Java API for working with Money and Currencies, which is planned to be included in Java 9.
  6. All specification classes and interfaces are located in the javax.money.* package.

Sample Examples of JSR 354: Money and Currency API:

An example of creating a MonetaryAmount and printing it to the console looks like this::

MonetaryAmountFactory<?> amountFactory = Monetary.getDefaultAmountFactory();
MonetaryAmount monetaryAmount = amountFactory.setCurrency(Monetary.getCurrency("EUR")).setNumber(12345.67).create();
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.getDefault());
System.out.println(format.format(monetaryAmount));

When using the reference implementation API, the necessary code is much simpler:

MonetaryAmount monetaryAmount = Money.of(12345.67, "EUR");
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.getDefault());
System.out.println(format.format(monetaryAmount));

The API also supports calculations with MonetaryAmounts:

MonetaryAmount monetaryAmount = Money.of(12345.67, "EUR");
MonetaryAmount otherMonetaryAmount = monetaryAmount.divide(2).add(Money.of(5, "EUR"));

CurrencyUnit and MonetaryAmount

// getting CurrencyUnits by locale
CurrencyUnit yen = MonetaryCurrencies.getCurrency(Locale.JAPAN);
CurrencyUnit canadianDollar = MonetaryCurrencies.getCurrency(Locale.CANADA);

MonetaryAmount has various methods that allow accessing the assigned currency, the numeric amount, its precision and more:

MonetaryAmount monetaryAmount = Money.of(123.45, euro);
CurrencyUnit currency = monetaryAmount.getCurrency();
NumberValue numberValue = monetaryAmount.getNumber();

int intValue = numberValue.intValue(); // 123
double doubleValue = numberValue.doubleValue(); // 123.45
long fractionDenominator = numberValue.getAmountFractionDenominator(); // 100
long fractionNumerator = numberValue.getAmountFractionNumerator(); // 45
int precision = numberValue.getPrecision(); // 5

// NumberValue extends java.lang.Number. 
// So we assign numberValue to a variable of type Number
Number number = numberValue;

MonetaryAmounts can be rounded using a rounding operator:

CurrencyUnit usd = MonetaryCurrencies.getCurrency("USD");
MonetaryAmount dollars = Money.of(12.34567, usd);
MonetaryOperator roundingOperator = MonetaryRoundings.getRounding(usd);
MonetaryAmount roundedDollars = dollars.with(roundingOperator); // USD 12.35

When working with collections of MonetaryAmounts, some nice utility methods for filtering, sorting and grouping are available.

List<MonetaryAmount> amounts = new ArrayList<>();
amounts.add(Money.of(2, "EUR"));
amounts.add(Money.of(42, "USD"));
amounts.add(Money.of(7, "USD"));
amounts.add(Money.of(13.37, "JPY"));
amounts.add(Money.of(18, "USD"));

Custom MonetaryAmount operations

// A monetary operator that returns 10% of the input MonetaryAmount
// Implemented using Java 8 Lambdas
MonetaryOperator tenPercentOperator = (MonetaryAmount amount) -> {
  BigDecimal baseAmount = amount.getNumber().numberValue(BigDecimal.class);
  BigDecimal tenPercent = baseAmount.multiply(new BigDecimal("0.1"));
  return Money.of(tenPercent, amount.getCurrency());
};

MonetaryAmount dollars = Money.of(12.34567, "USD");

// apply tenPercentOperator to MonetaryAmount
MonetaryAmount tenPercentDollars = dollars.with(tenPercentOperator); // USD 1.234567

Resources:

Handling money and currencies in Java with JSR 354

Looking into the Java 9 Money and Currency API (JSR 354)

See Also: JSR 354 - Currency and Money

What, exactly, is needed for "margin: 0 auto;" to work?

Off the top of my head, it needs a width. You need to specify the width of the container you are centering (not the parent width).

Uploading Images to Server android

Try this method for uploading Image file from camera

package com.example.imageupload;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;

public class MultipartEntity implements HttpEntity {

private String boundary = null;

ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;

public MultipartEntity() {
    this.boundary = System.currentTimeMillis() + "";
}

public void writeFirstBoundaryIfNeeds() {
    if (!isSetFirst) {
        try {
            out.write(("--" + boundary + "\r\n").getBytes());
        } catch (final IOException e) {

        }
    }
    isSetFirst = true;
}

public void writeLastBoundaryIfNeeds() {
    if (isSetLast) {
        return;
    }
    try {
        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
    } catch (final IOException e) {

    }
    isSetLast = true;
}

public void addPart(final String key, final String value) {
    writeFirstBoundaryIfNeeds();
    try {
        out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
                .getBytes());
        out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
        out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
        out.write(value.getBytes());
        out.write(("\r\n--" + boundary + "\r\n").getBytes());
    } catch (final IOException e) {

    }
}

public void addPart(final String key, final String fileName,
        final InputStream fin) {
    addPart(key, fileName, fin, "application/octet-stream");
}

public void addPart(final String key, final String fileName,
        final InputStream fin, String type) {
    writeFirstBoundaryIfNeeds();
    try {
        type = "Content-Type: " + type + "\r\n";
        out.write(("Content-Disposition: form-data; name=\"" + key
                + "\"; filename=\"" + fileName + "\"\r\n").getBytes());
        out.write(type.getBytes());
        out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());

        final byte[] tmp = new byte[4096];
        int l = 0;
        while ((l = fin.read(tmp)) != -1) {
            out.write(tmp, 0, l);
        }
        out.flush();
    } catch (final IOException e) {

    } finally {
        try {
            fin.close();
        } catch (final IOException e) {

        }
    }
}

public void addPart(final String key, final File value) {
    try {
        addPart(key, value.getName(), new FileInputStream(value));
    } catch (final FileNotFoundException e) {

    }
}

public long getContentLength() {
    writeLastBoundaryIfNeeds();
    return out.toByteArray().length;
}

public Header getContentType() {
    return new BasicHeader("Content-Type", "multipart/form-data; boundary="
            + boundary);
}

public boolean isChunked() {
    return false;
}

public boolean isRepeatable() {
    return false;
}

public boolean isStreaming() {
    return false;
}

public void writeTo(final OutputStream outstream) throws IOException {
    outstream.write(out.toByteArray());
}

public Header getContentEncoding() {
    return null;
}

public void consumeContent() throws IOException,
        UnsupportedOperationException {
    if (isStreaming()) {
        throw new UnsupportedOperationException(
                "Streaming entity does not implement #consumeContent()");
    }
}

public InputStream getContent() throws IOException,
        UnsupportedOperationException {
    return new ByteArrayInputStream(out.toByteArray());
}

}

Use of class for uploading

private void doFileUpload(File file_path) {

    Log.d("Uri", "Do file path" + file_path);

    try {

        HttpClient client = new DefaultHttpClient();
        //use your server path of php file
        HttpPost post = new HttpPost(ServerUploadPath);

        Log.d("ServerPath", "Path" + ServerUploadPath);

        FileBody bin1 = new FileBody(file_path);
        Log.d("Enter", "Filebody complete " + bin1);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("uploaded_file", bin1);
        reqEntity.addPart("email", new StringBody(useremail));

        post.setEntity(reqEntity);
        Log.d("Enter", "Image send complete");

        HttpResponse response = client.execute(post);
        resEntity = response.getEntity();
        Log.d("Enter", "Get Response");
        try {

            final String response_str = EntityUtils.toString(resEntity);
            if (resEntity != null) {
                Log.i("RESPONSE", response_str);
                JSONObject jobj = new JSONObject(response_str);
                result = jobj.getString("ResponseCode");
                Log.e("Result", "...." + result);

            }
        } catch (Exception ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
    } catch (Exception e) {
        Log.e("Upload Exception", "");
        e.printStackTrace();
    }
}

Service for uploading

   <?php
$image_name = $_FILES["uploaded_file"]["name"]; 
$tmp_arr = explode(".",$image_name);
$img_extn = end($tmp_arr);
$new_image_name = 'image_'. uniqid() .'.'.$img_extn;    
$flag=0;                 

if (file_exists("Images/".$new_image_name))
{
           $msg=$new_image_name . " already exists."
           header('Content-type: application/json');        
           echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=>$msg));        
}else{  
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name);
                   $flag = 1;
}   

if($flag == 1){                    
            require 'db.php';   
            $static_url =$new_image_name;
            $conn=mysql_connect($db_host,$db_username,$db_password) or die("unable to connect localhost".mysql_error());
            $db=mysql_select_db($db_database,$conn) or die("unable to select message_app"); 
            $email = "";
            if((isset($_REQUEST['email'])))
            {
                     $email = $_REQUEST['email'];
            }

    $sql ="insert into alert(images) values('$static_url')";

     $result=mysql_query($sql);

     if($result){
    echo json_encode(array("ResponseCode"=>"1","ResponseMsg"=> "Insert data successfully.","Result"=>"True","ImageName"=>$static_url,"email"=>$email));
       } else
       {

         echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Could not insert data.","Result"=>"False","email"=>$email));
        }
}
    else{
    echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Erroe While Inserting Image.","Result"=>"False"));
    }
    ?>

How to find out the server IP address (using JavaScript) that the browser is connected to?

I am sure the following code will help you to get ip address.

<script type="application/javascript">
    function getip(json){
      alert(json.ip); // alerts the ip address
    }
</script>

<script type="application/javascript" src="http://www.telize.com/jsonip?callback=getip"></script>