Programs & Examples On #Dcommit

dcommit is the command used by git-svn to commit changes to a subversion repository.

How to position one element relative to another with jQuery?

You can use the jQuery plugin PositionCalculator

That plugin has also included collision handling (flip), so the toolbar-like menu can be placed at a visible position.

$(".placeholder").on('mouseover', function() {
    var $menu = $("#menu").show();// result for hidden element would be incorrect
    var pos = $.PositionCalculator( {
        target: this,
        targetAt: "top right",
        item: $menu,
        itemAt: "top left",
        flip: "both"
    }).calculate();

    $menu.css({
        top: parseInt($menu.css('top')) + pos.moveBy.y + "px",
        left: parseInt($menu.css('left')) + pos.moveBy.x + "px"
    });
});

for that markup:

<ul class="popup" id="menu">
    <li>Menu item</li>
    <li>Menu item</li>
    <li>Menu item</li>
</ul>

<div class="placeholder">placeholder 1</div>
<div class="placeholder">placeholder 2</div>

Here is the fiddle: http://jsfiddle.net/QrrpB/1657/

How to initialize List<String> object in Java?

Can't instantiate an interface but there are few implementations:

JDK2

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

JDK7

//diamond operator
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");

JDK8

List<String> list = Stream.of("one", "two", "three").collect(Collectors.toList());

JDK9

// creates immutable lists, so you can't modify such list 
List<String> immutableList = List.of("one", "two", "three");

// if we want mutable list we can copy content of immutable list 
// to mutable one for instance via copy-constructor (which creates shallow copy)
List<String> mutableList = new ArrayList<>(List.of("one", "two", "three"));

Plus there are lots of other ways supplied by other libraries like Guava.

List<String> list = Lists.newArrayList("one", "two", "three");

What's better at freeing memory with PHP: unset() or $var = null

unset is not actually a function, but a language construct. It is no more a function call than a return or an include.

Aside from performance issues, using unset makes your code's intent much clearer.

SQL Server: Is it possible to insert into two tables at the same time?

You might create a View selecting the column names required by your insert statement, add an INSTEAD OF INSERT Trigger, and insert into this view.

Regex to validate date format dd/mm/yyyy

import re
expression = "Nov 05 20:10:09 2020"
reg_ex = r'((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-2][0-9]|(3)[0-1]) (([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])) (\d{4}))'
assert re.fullmatch(reg_ex, expression), True

Expaination with respect to given Example

  • Nov = A group of possible months i.e. (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)
  • 05 = A group of valid days i.e. ([0-2][0-9]|(3)[0-1])
  • 20:10:09 = A group for getting valid Hours : ([0-1][0-9]|2[0-3]), Minutes : ([0-5][0-9]) and Seconds : ([0-5][0-9])
  • 2020 = A group for getting year i.e (\d{4}))

How to select a schema in postgres when using psql?

This is old, but I put exports in my alias for connecting to the db:

alias schema_one.con="PGOPTIONS='--search_path=schema_one' psql -h host -U user -d database etc"

And for another schema:

alias schema_two.con="PGOPTIONS='--search_path=schema_two' psql -h host -U user -d database etc"

No mapping found for HTTP request with URI.... in DispatcherServlet with name

I had the same issue and after lots of reserach I found the classes were not getting published in my target folder. So I had run the below two commands from cmd

  1. mvn clean install
  2. mvn package

Surprisingly I was able to access the page and error was gone. Same can be verified from target folder where you will be able to find the complied classes which were missing earlier.

Displaying standard DataTables in MVC

Here is the answer in Razor syntax

 <table border="1" cellpadding="5">
    <thead>
       <tr>
          @foreach (System.Data.DataColumn col in Model.Columns)
          {
             <th>@col.Caption</th>
          }
       </tr>
    </thead>
    <tbody>
    @foreach(System.Data.DataRow row in Model.Rows)
    {
       <tr>
          @foreach (var cell in row.ItemArray)
          {
             <td>@cell.ToString()</td>
          }
       </tr>
    }      
    </tbody>
</table>

Interview Question: Merge two sorted singly linked lists without creating new nodes

A simple iterative solution.

Node* MergeLists(Node* A, Node* B)
{
    //handling the corner cases

    //if both lists are empty
    if(!A && !B)
    {
        cout << "List is empty" << endl;
        return 0;
    }
    //either of list is empty
    else if(!A) return B;
    else if(!B) return A;
    else
    {
        Node* head = NULL;//this will be the head of the newList
        Node* previous = NULL;//this will act as the

        /* In this algorithm we will keep the
         previous pointer that will point to the last node of the output list.
         And, as given we have A & B as pointer to the given lists.

         The algorithm will keep on going untill either one of the list become empty.
         Inside of the while loop, it will divide the algorithm in two parts:
            - First, if the head of the output list is not obtained yet
            - Second, if head is already there then we will just compare the values and keep appending to the 'previous' pointer.
         When one of the list become empty we will append the other 'left over' list to the output list.
         */
         while(A && B)
         {
             if(!head)
             {
                 if(A->data <= B->data)
                 {
                     head = A;//setting head of the output list to A
                     previous = A; //initializing previous
                     A = A->next;
                 }
                 else
                 {
                     head = B;//setting head of the output list to B
                     previous = B;//initializing previous
                     B = B->next;
                 }
             }
             else//when head is already set
             {
                 if(A->data <= B->data)
                 {
                     if(previous->next != A)
                         previous->next = A;
                     A = A->next;//Moved A forward but keeping B at the same position
                 }
                 else
                 {
                     if(previous->next != B)
                         previous->next = B;
                     B = B->next; //Moved B forward but keeping A at the same position
                 }
                 previous = previous->next;//Moving the Output list pointer forward
             }
         }
        //at the end either one of the list would finish
        //and we have to append the other list to the output list
        if(!A)
            previous->next = B;

        if(!B)
            previous->next = A;

        return head; //returning the head of the output list
    }
}

Importing CSV data using PHP/MySQL

set_time_limit(10000);

$con = mysql_connect('127.0.0.1','root','password');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("db", $con);

$fp = fopen("file.csv", "r");

while( !feof($fp) ) {
  if( !$line = fgetcsv($fp, 1000, ';', '"')) {
     continue;
  }

    $importSQL = "INSERT INTO table_name VALUES('".$line[0]."','".$line[1]."','".$line[2]."')";

    mysql_query($importSQL) or die(mysql_error());  

}

fclose($fp);
mysql_close($con);

How to zoom in/out an UIImage object when user pinches screen?

Here is a solution I've used before that does not require you to use the UIWebView.

- (UIImage *)scaleAndRotateImage(UIImage *)image
{
    int kMaxResolution = 320; // Or whatever

    CGImageRef imgRef = image.CGImage;

    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);


    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);
    if (width > kMaxResolution || height > kMaxResolution) {
        CGFloat ratio = width/height;
        if (ratio > 1) {
            bounds.size.width = kMaxResolution;
            bounds.size.height = bounds.size.width / ratio;
        }
        else {
            bounds.size.height = kMaxResolution;
            bounds.size.width = bounds.size.height * ratio;
        }
    }

    CGFloat scaleRatio = bounds.size.width / width;
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
    CGFloat boundHeight;
    UIImageOrientation orient = image.imageOrientation;
    switch(orient) {

        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;

        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;

        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;

        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];

    }

    UIGraphicsBeginImageContext(bounds.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    }
    else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
    }

    CGContextConcatCTM(context, transform);

    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return imageCopy;
}

The article can be found on Apple Support at: http://discussions.apple.com/message.jspa?messageID=7276709#7276709

How to get CSS to select ID that begins with a string (not in Javascript)?

I'd do it like this:

[id^="product"] {
  ...
}

Ideally, use a class. This is what classes are for:

<div id="product176" class="product"></div>
<div id="product177" class="product"></div>
<div id="product178" class="product"></div>

And now the selector becomes:

.product {
  ...
}

Display milliseconds in Excel

I've discovered in Excel 2007, if the results are a Table from an embedded query, the ss.000 does not work. I can paste the query results (from SQL Server Management Studio), and format the time just fine. But when I embed the query as a Data Connection in Excel, the format always gives .000 as the milliseconds.

Event on a disabled input

OR do this with jQuery and CSS!

$('input.disabled').attr('ignore','true').css({
    'pointer-events':'none',
     'color': 'gray'
});

This way you make the element look disabled and no pointer events will fire, yet it allows propagation and if submitted you can use the attribute 'ignore' to ignore it.

how do you filter pandas dataframes by multiple columns

For more general boolean functions that you would like to use as a filter and that depend on more than one column, you can use:

df = df[df[['col_1','col_2']].apply(lambda x: f(*x), axis=1)]

where f is a function that is applied to every pair of elements (x1, x2) from col_1 and col_2 and returns True or False depending on any condition you want on (x1, x2).

How to use color picker (eye dropper)?

Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.

However, I'm able to grab colors easily in Firefox.

  1. Open page in Firefox
  2. Hamburger Menu -> Web Developer -> Eyedropper
  3. Drag eyedropper tool over the image... Click.
    Color is copied to your clipboard, and eyedropper tool goes away.
  4. Paste color code

In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)

How to draw a line with matplotlib?

I was checking how ax.axvline does work, and I've written a small function that resembles part of its idea:

import matplotlib.pyplot as plt
import matplotlib.lines as mlines

def newline(p1, p2):
    ax = plt.gca()
    xmin, xmax = ax.get_xbound()

    if(p2[0] == p1[0]):
        xmin = xmax = p1[0]
        ymin, ymax = ax.get_ybound()
    else:
        ymax = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmax-p1[0])
        ymin = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmin-p1[0])

    l = mlines.Line2D([xmin,xmax], [ymin,ymax])
    ax.add_line(l)
    return l

So, if you run the following code you will realize how does it work. The line will span the full range of your plot (independently on how big it is), and the creation of the line doesn't rely on any data point within the axis, but only in two fixed points that you need to specify.

import numpy as np
x = np.linspace(0,10)
y = x**2

p1 = [1,20]
p2 = [6,70]

plt.plot(x, y)
newline(p1,p2)
plt.show()

enter image description here

How to set UITextField height?

A UITextField's height is not adjustable in Attributes Inspector only when it has the default rounded corners border style, but adding a height constraint (plus any other constraints which are required to satisfy the autolayout system - often by simply using Add Missing Constraints) to it and adjusting the constraint will adjust the textfield's height. If you don't want constraints, the constraints can be removed (Clear Constraints) and the textfield will remain at the adjusted height.

Works like a charm.

Log.INFO vs. Log.DEBUG

I usually try to use it like this:

  • DEBUG: Information interesting for Developers, when trying to debug a problem.
  • INFO: Information interesting for Support staff trying to figure out the context of a given error
  • WARN to FATAL: Problems and Errors depending on level of damage.

Using CSS how to change only the 2nd column of a table

You can use the :nth-child pseudo class like this:

.countTable table table td:nth-child(2)

Note though, this won't work in older browsers (or IE), you'll need to give the cells a class or use javascript in that case.

SSIS Excel Import Forcing Incorrect Column Type

I had the same issue, multiple data type values in single column, package load only numeric values. Remains all it updated as null.

Solution

To fix this changing the excel data type is one of the solution. In Excel Copy the column data and paste in different file. Delete that column and insert new column as Text datatype and paste that copied data in new column.

Now in ssis package delete and recreate the Excel source and destination table change the column data type as varchar.

This will work.

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

LINKS ARE TRICKY

Consider the tricks that <a href> knows by default but javascript linking won't do for you. On a decent website, anything that wants to behave as a link should implement these features one way or another. Namely:

  • Ctrl+Click: opens link in new tab
    You can simulate this by using a window.open() with no position/size argument
  • Shift+Click: opens link in new window
    You can simulate this by window.open() with size and/or position specified
  • Alt+Click: download target
    People rarely use this one, but if you insist to simulate it, you'll need to write a special script on server side that responds with the proper download headers.

EASY WAY OUT

Now if you don't want to simulate all that behaviour, I suggest to use <a href> and style it like a button, since the button itself is roughly a shape and a hover effect. I think if it's not semantically important to only have "the button and nothing else", <a href> is the way of the samurai. And if you worry about semantics and readability, you can also replace the button element when your document is ready(). It's clear and safe.

cannot connect to pc-name\SQLEXPRESS

I'm Running Windows 10 and this worked for me:

  1. Open services by searching in the toolbar for Services.
  2. Right click SQL Server (SQLEXPESS)
  3. Go To Properties - Log On
  4. Check Local System Account & Allow service to interact with desktop.
  5. Apply and restart service.
  6. I was then able to connect

Which icon sizes should my Windows application's icon include?

Not 96x96, use 64x64 instead. I usually use:

  • 16 - status/titlebar button
  • 32 - desktop icon
  • 48 - folder view
  • 64/128 - Additional sizes

256 works as well on XP, however, old resource compilers sometimes complained about "out of memory" errors.

PowerShell To Set Folder Permissions

Specifying inheritance in the FileSystemAccessRule() constructor fixes this, as demonstrated by the modified code below (notice the two new constuctor parameters inserted between "FullControl" and "Allow").

$Acl = Get-Acl "\\R9N2WRN\Share"

$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")

$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl

According to this topic

"when you create a FileSystemAccessRule the way you have, the InheritanceFlags property is set to None. In the GUI, this corresponds to an ACE with the Apply To box set to "This Folder Only", and that type of entry has to be viewed through the Advanced settings."

I have tested the modification and it works, but of course credit is due to the MVP posting the answer in that topic.

ASP.NET Core Web API exception handling

The well-accepted answer helped me a lot but I wanted to pass HttpStatusCode in my middleware to manage error status code at runtime.

According to this link I got some idea to do the same. So I merged the Andrei Answer with this. So my final code is below:


1. Base class

public class ErrorDetails
{
    public int StatusCode { get; set; }
    public string Message { get; set; }

    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }
}


2. Custom Exception Class Type

public class HttpStatusCodeException : Exception
{
    public HttpStatusCode StatusCode { get; set; }
    public string ContentType { get; set; } = @"text/plain";

    public HttpStatusCodeException(HttpStatusCode statusCode)
    {
        this.StatusCode = statusCode;
    }

    public HttpStatusCodeException(HttpStatusCode statusCode, string message) 
        : base(message)
    {
        this.StatusCode = statusCode;
    }

    public HttpStatusCodeException(HttpStatusCode statusCode, Exception inner) 
        : this(statusCode, inner.ToString()) { }

    public HttpStatusCodeException(HttpStatusCode statusCode, JObject errorObject) 
        : this(statusCode, errorObject.ToString())
    {
        this.ContentType = @"application/json";
    }

}


3. Custom Exception Middleware

public class CustomExceptionMiddleware
{
    private readonly RequestDelegate next;

    public CustomExceptionMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context /* other dependencies */)
    {
        try
        {
            await next(context);
        }
        catch (HttpStatusCodeException ex)
        {
            await HandleExceptionAsync(context, ex);
        }
        catch (Exception exceptionObj)
        {
            await HandleExceptionAsync(context, exceptionObj);
        }
    }

    private Task HandleExceptionAsync(HttpContext context, HttpStatusCodeException exception)
    {
        string result = null;
        context.Response.ContentType = "application/json";
        if (exception is HttpStatusCodeException)
        {
            result = new ErrorDetails() 
            {
                Message = exception.Message,
                StatusCode = (int)exception.StatusCode 
            }.ToString();
            context.Response.StatusCode = (int)exception.StatusCode;
        }
        else
        {
            result = new ErrorDetails() 
            { 
                Message = "Runtime Error",
                StatusCode = (int)HttpStatusCode.BadRequest
            }.ToString();
            context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        }
        return context.Response.WriteAsync(result);
    }

    private Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        string result = new ErrorDetails() 
        { 
            Message = exception.Message,
            StatusCode = (int)HttpStatusCode.InternalServerError 
        }.ToString();
        context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return context.Response.WriteAsync(result);
    }
}


4. Extension Method

public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app)
{
    app.UseMiddleware<CustomExceptionMiddleware>();
}

5. Configure Method in startup.cs

app.ConfigureCustomExceptionMiddleware();
app.UseMvc();

Now my login method in Account controller :

try
{
    IRepository<UserMaster> obj 
        = new Repository<UserMaster>(_objHeaderCapture, Constants.Tables.UserMaster);
    var result = obj.Get()
        .AsQueryable()
        .Where(sb => sb.EmailId.ToLower() == objData.UserName.ToLower() 
            && sb.Password == objData.Password.ToEncrypt() 
            && sb.Status == (int)StatusType.Active)
        .FirstOrDefault();
    if (result != null)//User Found
        return result;
    else // Not Found
        throw new HttpStatusCodeException(HttpStatusCode.NotFound,
            "Please check username or password");
}
catch (Exception ex)
{
    throw ex;
}

Above you can see if i have not found the user then raising the HttpStatusCodeException in which i have passed HttpStatusCode.NotFound status and a custom message
In middleware

catch (HttpStatusCodeException ex)

blocked will be called which will pass control to

private Task HandleExceptionAsync(HttpContext context, HttpStatusCodeException exception) method


But what if i got runtime error before? For that i have used try catch block which throw exception and will be catched in catch (Exception exceptionObj) block and will pass control to

Task HandleExceptionAsync(HttpContext context, Exception exception)

method.

I have used a single ErrorDetails class for uniformity.

What is the difference between an int and a long in C++?

For the most part, the number of bytes and range of values is determined by the CPU's architecture not by C++. However, C++ sets minimum requirements, which litb explained properly and Martin York only made a few mistakes with.

The reason why you can't use int and long interchangeably is because they aren't always the same length. C was invented on a PDP-11 where a byte had 8 bits, int was two bytes and could be handled directly by hardware instructions. Since C programmers often needed four-byte arithmetic, long was invented and it was four bytes, handled by library functions. Other machines had different specifications. The C standard imposed some minimum requirements.

URL Encode a string in jQuery for an AJAX request

I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded. I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)

Hardcoded URL i.e.>

 var encodedName = encodeURIComponent(name);
 var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;

Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method

 var url = "ControllerName/ActionName/";   
 $.post(url,
        { name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
 function (data) {.......});

Download file and automatically save it to folder

Take a look at http://www.csharp-examples.net/download-files/ and msdn docs on webclient http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx

My suggestion is try the synchronous download as its more straightforward. you might get ideas on whether webclient parameters are wrong or the file is in incorrect format while trying this.

Here is a code sample..

private void btnDownload_Click(object sender, EventArgs e)
{
  string filepath = textBox1.Text;
  WebClient webClient = new WebClient();
  webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
  webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
  webClient.DownloadFileAsync(new Uri("http://mysite.com/myfile.txt"), filepath);
}

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
  progressBar.Value = e.ProgressPercentage;
}

private void Completed(object sender, AsyncCompletedEventArgs e)
{
  MessageBox.Show("Download completed!");
}

Wheel file installation

You normally use a tool like pip to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI.

For this to work, you do need to install the wheel package:

pip install wheel

You can then tell pip to install the project (and it'll download the wheel if available), or the wheel file directly:

pip install project_name  # discover, download and install
pip install wheel_file.whl  # directly install the wheel

The wheel module, once installed, also is runnable from the command line, you can use this to install already-downloaded wheels:

python -m wheel install wheel_file.whl

Also see the wheel project documentation.

Create table variable in MySQL

MYSQL 8 does, in a way:

MYSQL 8 supports JSON tables, so you could load your results into a JSON variable and select from that variable using the JSON_TABLE() command.

How to pass command line argument to gnuplot?

Yet another way is this:

You have a gnuplot script named scriptname.gp:

#!/usr/bin/gnuplot -p
# This code is in the file 'scriptname.gp'
EPATH = $0
FILENAME = $1 

plot FILENAME

Now you can call the gnuplot script scriptname.gp by this convoluted peace of syntax:

echo "call \"scriptname.gp\" \"'.'\" \"'data.dat'\"" | gnuplot 

Difference between SurfaceView and View?

updated 05/09/2014

OK. We have official document now. It talked all I have mentioned, in a better way.


Read more detailed here.

Yes, the main difference is surfaceView can be updated on the background thread. However, there are more you might care.

  • surfaceView has dedicate surface buffer while all the view shares one surface buffer that is allocated by ViewRoot. In another word, surfaceView cost more resources.

  • surfaceView cannot be hardware accelerated (as of JB4.2) while 95% operations on normal View are HW accelerated using openGL ES.

  • More work should be done to create your customized surfaceView. You need to listener to the surfaceCreated/Destroy Event, create an render thread, more importantly, synchronized the render thread and main thread. However, to customize the View, all you need to do is override onDraw method.

  • The timing to update is different. Normal view update mechanism is constraint or controlled by the framework:You call view.invalidate in the UI thread or view.postInvalid in other thread to indicate to the framework that the view should be updated. However, the view won't be updated immediately but wait until next VSYNC event arrived. The easy approach to understand VSYNC is to consider it is as a timer that fire up every 16ms for a 60fps screen. In Android, all the normal view update (and display actually but I won't talk it today), is synchronized with VSYNC to achieve better smoothness. Now,back to the surfaceView, you can render it anytime as you wish. However, I can hardly tell if it is an advantage, since the display is also synchronized with VSYNC, as stated previously.

Excel VBA If cell.Value =... then

You can use the Like operator with a wildcard to determine whether a given substring exists in a string, for example:

If cell.Value Like "*Word1*" Then
'...
ElseIf cell.Value Like "*Word2*" Then
'...
End If

In this example the * character in "*Word1*" is a wildcard character which matches zero or more characters.

NOTE: The Like operator is case-sensitive, so "Word1" Like "word1" is false, more information can be found on this MSDN page.

The shortest possible output from git log containing author and date

enter image description here Note the -10 at the end, to show only the last 10 entries.

Use predefined git alias (hs - short for history):

git hs

Created once by command:

git config --global alias.hs "log --pretty='%C(yellow)%h %C(cyan)%ad %Cblue%aN%C(auto)%d %Creset%s' --date=relative --date-order --graph"

%h = abbreviated commit hash
%ad = author date (format respects --date= option, so you can adjust it later)
%aN = author name (respecting .mailmap)
%d = ref names
%s = subject

Reference: https://git-scm.com/docs/git-log#_pretty_formats

What function is to replace a substring from a string in C?

You can use strrep()

char* strrep ( const char * cadena, const char * strf, const char * strr )

strrep (String Replace). Replaces 'strf' with 'strr' in 'cadena' and returns the new string. You need to free the returned string in your code after using strrep.

Parameters cadena The string with the text. strf The text to find. strr The replacement text.

Returns The text updated wit the replacement.

Project can be found at https://github.com/ipserc/strrep

How can I test a PDF document if it is PDF/A compliant?

pdf validation with OPEN validator:

DROID (Digital Record Object Identification) http://sourceforge.net/projects/droid/

JHOVE - JSTOR/Harvard Object Validation Environment http://hul.harvard.edu/jhove/

Is there a way to force npm to generate package-lock.json?

If your npm version is lower than version 5 then install the higher version for getting the automatic generation of package-lock.json.

Example: Upgrade your current npm to version 6.14.0

npm i -g [email protected]

You could view the latest npm version list by

npm view npm versions

Set a button group's width to 100% and make buttons equal width?

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="btn-group btn-block">_x000D_
  <button type="button" data-toggle="dropdown" class="btn btn-default btn-xs  btn-block  dropdown-toggle">Actions <span class="caret"></span>_x000D_
<span class="sr-only">Toggle Dropdown</span></button><ul role="menu" class="dropdown-menu"><li><a href="#">Action one</a></li><li class="divider"></li><li><a href="#" >Action Two</a></li></ul></div>
_x000D_
_x000D_
_x000D_

How do I pass a unique_ptr argument to a constructor or a function?

Yes you have to if you take the unique_ptr by value in the constructor. Explicity is a nice thing. Since unique_ptr is uncopyable (private copy ctor), what you wrote should give you a compiler error.

Can we define min-margin and max-margin, max-padding and min-padding in css?

var w = window.innerWidth;
var h = window.innerHeight;
if(w < 1116)
    document.getElementById("profile").style.margin = "25px 0px 0px 975px";
else
    document.getElementById("profile").style.margin = "25px 0px 0px 89%";

Use code above as an example of how to set min-margin and padding

How do I finish the merge after resolving my merge conflicts?

Whenever You merge two branches using command git merge brancha branchb , There are two possibilities:

  1. One branch (lets say brancha) can be reached by the other branch (lets say branchb) by following its commits history.In this case git simply fast-forward the head to point to the recent branch (in this case branchb).

    2.But if the two branches have diverged at some older point then git creates a new snapshot and add a new commit that points to it. So in case there is no conflict between the branches you are merging, git smoothly creates a new commit.

Run git log to see the commit after you have merged two non-conflicting branches.

Now coming back to the interesting case when there are merge conflicts between the merging branches. I quote this from the page https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

Git hasn’t automatically created a new merge commit. It has paused the process while you resolve the conflict. If you want to see which files are unmerged at any point after a merge conflict, you can run git status


So in case there are merge conflicts, you need to resolve the conflict then add the changes you have made to the staging area using git add filename and then commit the changes by using the command git commit which was paused by git because of the conflict.I hope this explains your query. Also do visit the link above for a detailed understanding. In case of any query please comment below , I'll be happy to help.

Create Django model or update if exists

If one of the input when you create is a primary key, this will be enough:

Person.objects.get_or_create(id=1)

It will automatically update if exist since two data with the same primary key is not allowed.

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You are repeating the y,m,d.

Instead of

gmdate('yyyy-mm-dd hh:mm:ss \G\M\T', time());  

You should use it like

gmdate('Y-m-d h:m:s \G\M\T', time());

Convert hex to binary

bin(int("abc123efff", 16))[2:]

How can I read a whole file into a string variable

I'm not with computer,so I write a draft. You might be clear of what I say.

func main(){
    const dir = "/etc/"
    filesInfo, e := ioutil.ReadDir(dir)
    var fileNames = make([]string, 0, 10)
    for i,v:=range filesInfo{
        if !v.IsDir() {
            fileNames = append(fileNames, v.Name())
        }
    }

    var fileNumber = len(fileNames)
    var contents = make([]string, fileNumber, 10)
    wg := sync.WaitGroup{}
    wg.Add(fileNumber)

    for i,_:=range content {
        go func(i int){
            defer wg.Done()
            buf,e := ioutil.Readfile(fmt.Printf("%s/%s", dir, fileName[i]))
            defer file.Close()  
            content[i] = string(buf)
        }(i)   
    }
    wg.Wait()
}

installing apache: no VCRUNTIME140.dll

Check if your OS is Windows 7 Service Pack 1.. use "winver" to verify.

Make sure Service Pack 1 is there after "Build #### : Service Pack 1"

How to force a WPF binding to refresh?

I was fetching data from backend and updated the screen with just one line of code. It worked. Not sure, why we need to implement Interface. (windows 10, UWP)

    private void populateInCurrentScreen()
    {
        (this.FindName("Dets") as Grid).Visibility = Visibility.Visible;
        this.Bindings.Update();
    }

Can't clone a github repo on Linux via HTTPS

I met the same problem, the error message and OS info are as follows

OS info:

CentOS release 6.5 (Final)

Linux 192-168-30-213 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

error info:

Initialized empty Git repository in /home/techops/pyenv/.git/ Password: error: while accessing https://[email protected]/pyenv/pyenv.git/info/refs

fatal: HTTP request failed

git & curl version info

git info :git version 1.7.1

curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 Protocols: tftp ftp telnet dict ldap ldaps http file https ftps scp sftp Features: GSS-Negotiate IDN IPv6 Largefile NTLM SSL libz

debugging

$ curl --verbose https://github.com

  • About to connect() to github.com port 443 (#0)
  • Trying 13.229.188.59... connected
  • Connected to github.com (13.229.188.59) port 443 (#0)
  • Initializing NSS with certpath: sql:/etc/pki/nssdb
  • CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none
  • NSS error -12190
  • Error in TLS handshake, trying SSLv3... GET / HTTP/1.1 User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 Host: github.com Accept: /

  • Connection died, retrying a fresh connect

  • Closing connection #0
  • Issue another request to this URL: 'https://github.com'
  • About to connect() to github.com port 443 (#0)
  • Trying 13.229.188.59... connected
  • Connected to github.com (13.229.188.59) port 443 (#0)
  • TLS disabled due to previous handshake failure
  • CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none
  • NSS error -12286
  • Closing connection #0
  • SSL connect error curl: (35) SSL connect error

after upgrading curl , libcurl and nss , git clone works fine again, so here it is. the update command is as follows

sudo yum update -y nss curl libcurl

Remove Safari/Chrome textinput/textarea glow

This effect can occur on non-input elements, too. I've found the following works as a more general solution

:focus {
  outline-color: transparent;
  outline-style: none;
}

Update: You may not have to use the :focus selector. If you have an element, say <div id="mydiv">stuff</div>, and you were getting the outer glow on this div element, just apply like normal:

#mydiv {
  outline-color: transparent;
  outline-style: none;
}

Foreign key referencing a 2 columns primary key in SQL Server

The Content table likely to have multiple duplicate Application values that can't be mapped to Libraries. Is it possible to drop the Application column from the Libraries Primary Key Index and add it as a Unique Key Index instead?

"Unknown class <MyClass> in Interface Builder file" error at runtime

This problem happened to me when I added a picker view and then removed it. In case it will help someone, here's how I solved it finally:

  1. Open Document Outline at XCODE (don't know what is Document Outline? I didn't also - google it.. :) ).

  2. Find the Scene that makes the warning message appear, in the document outline window.

  3. On the problematic scene, stand (click) on View, and then in the Utility (google it) window select the Identity inspector tab and change back the custom class name to default UIView.

That't it. :)

Catch Ctrl-C in C

This just print before exit.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void sigint_handler(int);

int  main(void)
{
    signal(SIGINT, sigint_handler);

     while (1){
         pause();   
     }         
    return 0;
}

 void sigint_handler(int sig)
{
    /*do something*/
    printf("killing process %d\n",getpid());
    exit(0);
}

Failed Apache2 start, no error log

You have following ways to make it work:

  1. Delete /var/run/apache2/apache2.pid then check if its working

  2. You can disable SELinux and then check if it works. You can disable SELinux permanantly or temporarily by using https://linux4one.com/how-to-disable-selinux-on-centos-7/ tutorial

How can I tell gcc not to inline a function?

GCC has a switch called

-fno-inline-small-functions

So use that when invoking gcc. But the side effect is that all other small functions are also non-inlined.

How to connect android wifi to adhoc wifi?

I did notice something of interest here: In my 2.3.4 phone I can't see AP/AdHoc SSIDs in the Settings > Wireless & Networks menu. On an Acer A500 running 4.0.3 I do see them, prefixed by (*)

However in the following bit of code that I adapted from (can't remember source, sorry!) I do see the Ad Hoc show up in the Wifi Scan on my 2.3.4 phone. I am still looking to actually connect and create a socket + input/outputStream. But, here ya go:

    public class MainActivity extends Activity {

private static final String CHIPKIT_BSSID = "E2:14:9F:18:40:1C";
private static final int CHIPKIT_WIFI_PRIORITY = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final Button btnDoSomething = (Button) findViewById(R.id.btnDoSomething);
    final Button btnNewScan = (Button) findViewById(R.id.btnNewScan);
    final TextView textWifiManager = (TextView) findViewById(R.id.WifiManager);
    final TextView textWifiInfo = (TextView) findViewById(R.id.WifiInfo);
    final TextView textIp = (TextView) findViewById(R.id.Ip);

    final WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    final WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();

    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.BSSID = CHIPKIT_BSSID;
    wifiConfiguration.priority = CHIPKIT_WIFI_PRIORITY;
    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
    wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    wifiConfiguration.status = WifiConfiguration.Status.ENABLED;

    myWifiManager.setWifiEnabled(true);

    int netID = myWifiManager.addNetwork(wifiConfiguration);

    myWifiManager.enableNetwork(netID, true);

    textWifiInfo.setText("SSID: " + myWifiInfo.getSSID() + '\n' 
            + myWifiManager.getWifiState() + "\n\n");

    btnDoSomething.setOnClickListener(new View.OnClickListener() {          
        public void onClick(View v) {
            clearTextViews(textWifiManager, textIp);                
        }           
    });

    btnNewScan.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            getNewScan(myWifiManager, textWifiManager, textIp);
        }
    });     
}

private void clearTextViews(TextView...tv) {
    for(int i = 0; i<tv.length; i++){
        tv[i].setText("");
    }       
}

public void getNewScan(WifiManager wm, TextView...textViews) {
    wm.startScan();

    List<ScanResult> scanResult = wm.getScanResults();

    String scan = "";

    for (int i = 0; i < scanResult.size(); i++) {
        scan += (scanResult.get(i).toString() + "\n\n");
    }

    textViews[0].setText(scan);
    textViews[1].setText(wm.toString());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

Don't forget that in Eclipse you can use Ctrl+Shift+[letter O] to fill in the missing imports...

and my manifest:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.digilent.simpleclient"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Hope that helps!

Numbering rows within groups in a data frame

Another base R solution would be to split the data frame per cat, after that using lapply: add a column with number 1:nrow(x). The last step is to have your final data frame back with do.call, that is:

        df_split <- split(df, df$cat)
        df_lapply <- lapply(df_split, function(x) {
          x$num <- seq_len(nrow(x))
          return(x)
        })
        df <- do.call(rbind, df_lapply)

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

Failing custom jackson Serializers/Deserializers could also be the problem. Though it's not your case, it's worth mentioning.

I faced the same exception and that was the case.

How to search for an element in an stl list?

No, not directly in the std::list template itself. You can however use std::find algorithm like that:

std::list<int> my_list;
//...
int some_value = 12;
std::list<int>::iterator iter = std::find (my_list.begin(), my_list.end(), some_value);
// now variable iter either represents valid iterator pointing to the found element,
// or it will be equal to my_list.end()

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

Reading HTML content from a UIWebView

(Xcode 5 iOS 7) Universal App example for iOS 7 and Xcode 5. It is an open source project / example located here: Link to SimpleWebView (Project Zip and Source Code Example)

How to format background color using twitter bootstrap?

Just add a div around the container so it looks like:

<div style="background: red;">
  <div class="container marketing">
    <h2 style="padding-top: 60px;"></h2>
  </div>
</div>

DOS: find a string, if found then run another script

We have two commands, first is "condition_command", second is "result_command". If we need run "result_command" when "condition_command" is successful (errorlevel=0):

condition_command && result_command

If we need run "result_command" when "condition_command" is fail:

condition_command || result_command

Therefore for run "some_command" in case when we have "string" in the file "status.txt":

find "string" status.txt 1>nul && some_command

in case when we have not "string" in the file "status.txt":

find "string" status.txt 1>nul || some_command

Causes of getting a java.lang.VerifyError

I fixed this error on Android by making the project I was importing a library, as described here http://developer.android.com/tools/projects/projects-eclipse.html#SettingUpLibraryProject

Previously, I was just referencing the project (not making it a library) and I was getting this strange VerifyError.

Hope it helps someone.

How to convert an array to a string in PHP?

serialize() and unserialize() convert between php objects and a string representation.

Convert a secure string to plain text

You may also use PSCredential.GetNetworkCredential() :

$SecurePassword = Get-Content C:\Users\tmarsh\Documents\securePassword.txt | ConvertTo-SecureString
$UnsecurePassword = (New-Object PSCredential "user",$SecurePassword).GetNetworkCredential().Password

How to generate a Dockerfile from an image?

_x000D_
_x000D_
docker pull chenzj/dfimage


alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm chenzj/dfimage"

dfimage image_id
_x000D_
_x000D_
_x000D_

Below is ouput of dfimage command:

$ dfimage 0f1947a021ce

FROM node:8
WORKDIR /usr/src/app

COPY file:e76d2e84545dedbe901b7b7b0c8d2c9733baa07cc821054efec48f623e29218c in ./
RUN /bin/sh -c npm install
COPY dir:a89a4894689a38cbf3895fdc0870878272bb9e09268149a87a6974a274b2184a in .

EXPOSE 8080
CMD ["npm" "start"]

Convert String to Type in C#

Try:

Type type = Type.GetType(inputString); //target type
object o = Activator.CreateInstance(type); // an instance of target type
YourType your = (YourType)o;

Jon Skeet is right as usually :)

Update: You can specify assembly containing target type in various ways, as Jon mentioned, or:

YourType your = (YourType)Activator.CreateInstance("AssemblyName", "NameSpace.MyClass");

Elegant way to read file into byte[] array in Java

A long time ago:

Call any of these

byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input) 

From

http://commons.apache.org/io/

If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library

Today (Java 7+ or Android API Level 26+)

Luckily, we now have a couple of convenience methods in the nio packages. For instance:

byte[] java.nio.file.Files.readAllBytes(Path path)

Javadoc here

Can I pass column name as input parameter in SQL stored Procedure

Try using dynamic SQL:

create procedure sp_First @columnname varchar 
AS 
begin 
    declare @sql nvarchar(4000);
    set @sql='select ['+@columnname+'] from Table_1';
    exec sp_executesql @sql
end 
go

exec sp_First 'sname'
go

Run PHP Task Asynchronously

i think you should try this technique it will help to call as many as pages you like all pages will run at once independently without waiting for each page response as asynchronous.

cornjobpage.php //mainpage

    <?php

post_async("http://localhost/projectname/testpage.php", "Keywordname=testValue");
//post_async("http://localhost/projectname/testpage.php", "Keywordname=testValue2");
//post_async("http://localhost/projectname/otherpage.php", "Keywordname=anyValue");
//call as many as pages you like all pages will run at once independently without waiting for each page response as asynchronous.
            ?>
            <?php

            /*
             * Executes a PHP page asynchronously so the current page does not have to wait for it to     finish running.
             *  
             */
            function post_async($url,$params)
            {

                $post_string = $params;

                $parts=parse_url($url);

                $fp = fsockopen($parts['host'],
                    isset($parts['port'])?$parts['port']:80,
                    $errno, $errstr, 30);

                $out = "GET ".$parts['path']."?$post_string"." HTTP/1.1\r\n";//you can use POST instead of GET if you like
                $out.= "Host: ".$parts['host']."\r\n";
                $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
                $out.= "Content-Length: ".strlen($post_string)."\r\n";
                $out.= "Connection: Close\r\n\r\n";
                fwrite($fp, $out);
                fclose($fp);
            }
            ?>

testpage.php

    <?
    echo $_REQUEST["Keywordname"];//case1 Output > testValue
    ?>

PS:if you want to send url parameters as loop then follow this answer :https://stackoverflow.com/a/41225209/6295712

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

Easiest way is probably to convert from a VARCHAR to a DATE; then format it back to a VARCHAR again in the format you want;

SELECT TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') FROM EmpTable;

An SQLfiddle to test with.

How to start Fragment from an Activity

You can either add or replace fragment in your activity. Create a FrameLayout in activity layout xml file.

Then do this in your activity to add fragment:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

And to replace fragment do this:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

See Android documentation on adding a fragment to an activity or following related questions on SO:

Difference between add(), replace(), and addToBackStack()

Basic difference between add() and replace() method of Fragment

Difference between add() & replace() with Fragment's lifecycle

java.util.Date vs java.sql.Date

Congratulations, you've hit my favorite pet peeve with JDBC: Date class handling.

Basically databases usually support at least three forms of datetime fields which are date, time and timestamp. Each of these have a corresponding class in JDBC and each of them extend java.util.Date. Quick semantics of each of these three are the following:

  • java.sql.Date corresponds to SQL DATE which means it stores years, months and days while hour, minute, second and millisecond are ignored. Additionally sql.Date isn't tied to timezones.
  • java.sql.Time corresponds to SQL TIME and as should be obvious, only contains information about hour, minutes, seconds and milliseconds.
  • java.sql.Timestamp corresponds to SQL TIMESTAMP which is exact date to the nanosecond (note that util.Date only supports milliseconds!) with customizable precision.

One of the most common bugs when using JDBC drivers in relation to these three types is that the types are handled incorrectly. This means that sql.Date is timezone specific, sql.Time contains current year, month and day et cetera et cetera.

Finally: Which one to use?

Depends on the SQL type of the field, really. PreparedStatement has setters for all three values, #setDate() being the one for sql.Date, #setTime() for sql.Time and #setTimestamp() for sql.Timestamp.

Do note that if you use ps.setObject(fieldIndex, utilDateObject); you can actually give a normal util.Date to most JDBC drivers which will happily devour it as if it was of the correct type but when you request the data afterwards, you may notice that you're actually missing stuff.

I'm really saying that none of the Dates should be used at all.

What I am saying that save the milliseconds/nanoseconds as plain longs and convert them to whatever objects you are using (obligatory joda-time plug). One hacky way which can be done is to store the date component as one long and time component as another, for example right now would be 20100221 and 154536123. These magic numbers can be used in SQL queries and will be portable from database to another and will let you avoid this part of JDBC/Java Date API:s entirely.

Python: No acceptable C compiler found in $PATH when installing python

The gcc compiler is not in your $PATH. It means either you dont have gcc installed or it's not in your $PATH variable.

To install gcc use this: (run as root)

  • Redhat base:

    yum groupinstall "Development Tools"
    
  • Debian base:

    apt-get install build-essential
    

How to make a boolean variable switch between true and false every time a method is invoked?

Without looking at it, set it to not itself. I don't know how to code it in Java, but in Objective-C I would say

booleanVariable = !booleanVariable;

This flips the variable.

Converting newline formatting from Mac to Windows

In Xcode 9 in the left panel open/choose your file in project navigator. If file is not there, drug-and-drop it into the project navigator.

On right panel find Text Settings and change Line Endings to Windows (CRLF) .

XCode screendumpscreendump from XCode

CSS rounded corners in IE8

Internet Explorer (under version 9) does not natively support rounded corners.

There's an amazing script that will magically add it for you: CSS3 PIE.

I've used it a lot of times, with amazing results.

Regular Expression to match string starting with a specific word

If you wish to match only lines beginning with stop use

^stop

If you wish to match lines beginning with the word stop followed by a space

^stop\s

Or, if you wish to match lines beginning with the word stop but followed by either a space or any other non word character you can use (your regex flavor permitting)

^stop\W

On the other hand, what follows matches a word at the beginning of a string on most regex flavors (in these flavors \w matches the opposite of \W)

^\w

If your flavor does not have the \w shortcut, you can use

^[a-zA-Z0-9]+

Be wary that this second idiom will only match letters and numbers, no symbol whatsoever.

Check your regex flavor manual to know what shortcuts are allowed and what exactly do they match (and how do they deal with Unicode.)

How to send UTF-8 email?

You can add header "Content-Type: text/html; charset=UTF-8" to your message body.

$headers = "Content-Type: text/html; charset=UTF-8";

If you use native mail() function $headers array will be the 4th parameter mail($to, $subject, $message, $headers)

If you user PEAR Mail::factory() code will be:

$smtp = Mail::factory('smtp', $params);

$mail = $smtp->send($to, $headers, $body);

Add a new line to the end of a JtextArea

Instead of using JTextArea.setText(String text), use JTextArea.append(String text).

Appends the given text to the end of the document. Does nothing if the model is null or the string is null or empty.

This will add text on to the end of your JTextArea.

Another option would be to use getText() to get the text from the JTextArea, then manipulate the String (add or remove or change the String), then use setText(String text) to set the text of the JTextArea to be the new String.

xxxxxx.exe is not a valid Win32 application

I had the same issue on Windows XP when running an application built with a static version of Qt 5.7.0 (MSVC 2013).

Adding the following line to the project's .pro file solved it:

QMAKE_LFLAGS_WINDOWS = /SUBSYSTEM:WINDOWS,5.01

Fatal error: "No Target Architecture" in Visual Studio

_WIN32 identifier is not defined.

use #include <SDKDDKVer.h>

MSVS generated projects wrap this include by generating a local "targetver.h"which is included by "stdafx.h" that is comiled into a precompiled-header through "stdafx.cpp".

EDIT : do you have a /D "WIN32" on your commandline ?

Check date between two other dates spring data jpa

I did use following solution to this:

findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate);

Can you put two conditions in an xslt test attribute?

Maybe this is a no-brainer for the xslt-professional, but for me at beginner/intermediate level, this got me puzzled. I wanted to do exactly the same thing, but I had to test a responsetime value from an xml instead of a plain number. Following this thread, I tried this:

<xsl:when test="responsetime/@value &gt;= 5000 and responsetime/@value &lt;= 8999"> 

which generated an error. This works:

<xsl:when test="number(responsetime/@value) &gt;= 5000 and number(responsetime/@value) &lt;= 8999">

Don't really understand why it doesn't work without number(), though. Could it be that without number() the value is treated as a string and you can't compare numbers with a string?

Anyway, hope this saves someone a lot of searching...

How to convert a string to a date in sybase

Several ways to accomplish that but be aware that your DB date_format option & date_order option settings could affect the incoming format:

Select 
   cast('2008-09-16' as date)
   convert(date,'16/09/2008',103)
   date('2008-09-16')
from dummy;

How to get build time stamp from Jenkins build variables?

I know its late replying to this question, but I have recently found a better solution to this problem without installing any plugin. We can create a formatted version number and can then use the variable created to display the build date/time. Steps to create: Build Environment --> Create a formatted version number:

  • Environment Variable Name: BUILD_DATE

  • Version Number Format String: ${BUILD_DATE_FORMATTED}

thats it. Just use the variable created above in the email subject line as ${ENV, var="BUILD_DATE"} and you will get the date/time of the current build.

window.onload vs document.onload

Window.onload is the standard, however - the web browser in the PS3 (based on Netfront) doesn't support the window object, so you can't use it there.

How to parse date string to Date?

Here is a working example:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;

public class j4496359 {
    public static void main(String[] args) {
        try {
            String target = "Thu Sep 28 20:29:30 JST 2000";
            DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
            Date result =  df.parse(target);
            System.out.println(result); 
        } catch (ParseException pe) {
            pe.printStackTrace();
        }
    }
}

Will print:

Thu Sep 28 13:29:30 CEST 2000

Passing ArrayList from servlet to JSP

<html>
    <%

        ArrayList<Actor> list = new ArrayList<Actor>();
        list = (ArrayList<Actor>) request.getAttribute("actors");
    %>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Actor</title>
</head>

<body>

    <h2>This is Actor Class</h2>
    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
        </thead>
        <tbody>
            <% for(int i = 0; i < list.size(); i++) {
                Actor actor = new Actor();
                actor = list.get(i);
                //out.println(actor.getId());
                //out.println(actor.getFirstname());
                //out.println(actor.getLastname());
            %>


            <tr>
                <td><%=actor.getId()%></td>
                <td><%=actor.getFirstname()%></td>
                <td><%=actor.getLastname()%></td>
               </tr>
            <%
            };
            %>
        </tbody>
    </table>

</body>

Capturing mobile phone traffic on Wireshark

I had a similar problem that inspired me to develop an app that could help to capture traffic from an Android device. The app features SSH server that allows you to have traffic in Wireshark on the fly (sshdump wireshark component). As the app uses an OS feature called VPNService to capture traffic, it does not require the root access.

The app is in early Beta. If you have any issues/suggestions, do not hesitate to let me know.

Download From Play

Tutorial in which you could read additional details

Verify host key with pysftp

FWIR, if authentication is only username & pw, add remote server ip address to known_hosts like ssh-keyscan -H 192.168.1.162 >> ~/.ssh/known_hosts for ref https://www.techrepublic.com/article/how-to-easily-add-an-ssh-fingerprint-to-your-knownhosts-file-in-linux/

How to suspend/resume a process in Windows?

Without any external tool you can simply accomplish this on Windows 7 or 8, by opening up the Resource monitor and on the CPU or Overview tab right clicking on the process and selecting Suspend Process. The Resource monitor can be started from the Performance tab of the Task manager.

Download a file from HTTPS using download.file()

You can set global options and try-

options('download.file.method'='curl')
download.file(URL, destfile = "./data/data.csv", method="auto")

For issue refer to link- https://stat.ethz.ch/pipermail/bioconductor/2011-February/037723.html

Global environment variables in a shell script

source myscript.sh is also feasible.

Description for linux command source:

source is a Unix command that evaluates the file following the command, 
as a list of commands, executed in the current context

Today`s date in an excel macro

Try the Date function. It will give you today's date in a MM/DD/YYYY format. If you're looking for today's date in the MM-DD-YYYY format try Date$. Now() also includes the current time (which you might not need). It all depends on what you need. :)

How to extract request http headers from a request using NodeJS connect

To see a list of HTTP request headers, you can use :

console.log(JSON.stringify(req.headers));

to return a list in JSON format.

{
"host":"localhost:8081",
"connection":"keep-alive",
"cache-control":"max-age=0",
"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"upgrade-insecure-requests":"1",
"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"en-US,en;q=0.8,et;q=0.6"
}

alternative to "!is.null()" in R

The shiny package provides the convenient functions validate() and need() for checking that variables are both available and valid. need() evaluates an expression. If the expression is not valid, then an error message is returned. If the expression is valid, NULL is returned. One can use this to check if a variable is valid. See ?need for more information.

I suggest defining a function like this:

is.valid <- function(x) {
  require(shiny)
  is.null(need(x, message = FALSE))  
}

This function is.valid() will return FALSE if x is FALSE, NULL, NA, NaN, an empty string "", an empty atomic vector, a vector containing only missing values, a logical vector containing only FALSE, or an object of class try-error. In all other cases, it returns TRUE.

That means, need() (and is.valid()) covers a really broad range of failure cases. Instead of writing:

if (!is.null(x) && !is.na(x) && !is.nan(x)) {
  ...
}

one can write simply:

if (is.valid(x)) {
  ...
}

With the check for class try-error, it can even be used in conjunction with a try() block to silently catch errors: (see https://csgillespie.github.io/efficientR/programming.html#communicating-with-the-user)

bad = try(1 + "1", silent = TRUE)
if (is.valid(bad)) {
  ...
}

How can I export a GridView.DataSource to a datatable or dataset?

Personally I would go with:

DataTable tbl = Gridview1.DataSource as DataTable;

This would allow you to test for null as this results in either DataTable object or null. Casting it as a DataTable using (DataTable)Gridview1.DataSource would cause a crashing error in case the DataSource is actually a DataSet or even some kind of collection.

Supporting Documentation: MSDN Documentation on "as"

Convert decimal to hexadecimal in UNIX shell script

In zsh you can do this sort of thing:

% typeset -i 16 y
% print $(( [#8] x = 32, y = 32 ))
8#40
% print $x $y
8#40 16#20
% setopt c_bases
% print $y
0x20

Example taken from zsh docs page about Arithmetic Evaluation.

I believe Bash has similar capabilities.

Controlling execution order of unit tests in Visual Studio

I see that this topic is almost 6 years old, and we now have new version of Visual studio but I will reply anyway. I had that order problem in Visual Studio 19 and I figured it out by adding capital letter (you can also add small letter) in front of your method name and in alphabetical order like this:

[TestMethod]
        public void AName1()
        {}
[TestMethod]
        public void BName2()
        {}

And so on. I know that this doesn't look appealing, but it looks like Visual is sorting your tests in test explorer in alphabetical order, doesn't matter how you write it in your code. Playlist didn't work for me in this case.

Hope that this will help.

What is the use of "object sender" and "EventArgs e" parameters?

EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.

Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.

Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx

Example:

protected void btn_Click (object sender, EventArgs e){
   Button btn = sender as Button;
   btn.Text = "clicked!";
}

Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked

What properties does @Column columnDefinition make redundant?

columnDefinition will override the sql DDL generated by hibernate for this particular column, it is non portable and depends on what database you are using. You can use it to specify nullable, length, precision, scale... ect.

Is there any quick way to get the last two characters in a string?

The existing answers will fail if the string is empty or only has one character. Options:

String substring = str.length() > 2 ? str.substring(str.length() - 2) : str;

or

String substring = str.substring(Math.max(str.length() - 2, 0));

That's assuming that str is non-null, and that if there are fewer than 2 characters, you just want the original string.

How to force a line break on a Javascript concatenated string?

You can't have multiple lines in a text box, you need a textarea. Then it works with \n between the values.

Storing images in SQL Server?

I fell into this dilemma once, and researched quite a bit on google for opinions. What I found was that indeed many see saving images to disk better for larger images, while mySQL allows for easier access, specially from languages like PHP.

I found a similar question

MySQL BLOB vs File for Storing Small PNG Images?

My final verdict was that for things such as a profile picture, just a small square image that needs to be there per user, mySQL would be better than storing a bunch of thumbs in the hdd, while for photo albums and things like that, folders/image files are better.

Hope it helps

How do I set up access control in SVN?

The best way is to set up Apache and to set the access through it. Check the svn book for help. If you don't want to use Apache, you can also do minimalistic access control using svnserve.

How to permanently export a variable in Linux?

On Ubuntu systems, use the following locations:

  1. System-wide persistent variables in the format of JAVA_PATH=/usr/local/java store in

    /etc/environment
    
  2. System-wide persistent variables that reference variables such as
    export PATH="$JAVA_PATH:$PATH" store in

    /etc/.bashrc
    
  3. User specific persistent variables in the format of PATH DEFAULT=/usr/bin:usr/local/bin store in

    ~/.pam_environment
    

For more details on #2, check this Ask Ubuntu answer. NOTE: #3 is the Ubuntu recommendation but may have security concerns in the real world.

How do I loop through rows with a data reader in C#?

Actually the Read method iterating over records in a result set. In your case - over table rows. So you still can use it.

Python socket receive - incoming packets always have a different size

You could try always sending the first 4 bytes of your data as data size and then read complete data in one shot. Use the below functions on both client and server-side to send and receive data.

def send_data(conn, data):
    serialized_data = pickle.dumps(data)
    conn.sendall(struct.pack('>I', len(serialized_data)))
    conn.sendall(serialized_data)


def receive_data(conn):
    data_size = struct.unpack('>I', conn.recv(4))[0]
    received_payload = b""
    reamining_payload_size = data_size
    while reamining_payload_size != 0:
        received_payload += conn.recv(reamining_payload_size)
        reamining_payload_size = data_size - len(received_payload)
    data = pickle.loads(received_payload)

    return data

you could find sample program at https://github.com/vijendra1125/Python-Socket-Programming.git

PHP cURL HTTP CODE return 0

check the curl_error after the curl_getinfo to find out the hidden errors.

if(curl_errno($ch)){   
    echo 'Curl error: ' . curl_error($ch);
}

jQuery .each() index?

jQuery takes care of this for you. The first argument to your .each() callback function is the index of the current iteration of the loop. The second being the current matched DOM element So:

$('#list option').each(function(index, element){
  alert("Iteration: " + index)
});

Error "The input device is not a TTY"

If you are (like me) using git bash on windows, you just need to put

winpty

before your 'docker line' :

winpty docker exec -it some_cassandra bash

How do I calculate tables size in Oracle

First, gather optimiser stats on the table (if you haven't already):

begin
   dbms_stats.gather_table_stats('MYSCHEMA','MYTABLE');
end;
/

WARNING: As Justin says in his answer, gathering optimiser stats affects query optimisation and should not be done without due care and consideration!

Then find the number of blocks occupied by the table from the generated stats:

select blocks, empty_blocks, num_freelist_blocks
from   all_tables
where  owner = 'MYSCHEMA'
and    table_name = 'MYTABLE';
  • The total number of blocks allocated to the table is blocks + empty_blocks + num_freelist_blocks.

  • blocks is the number of blocks that actually contain data.

Multiply the number of blocks by the block size in use (usually 8KB) to get the space consumed - e.g. 17 blocks x 8KB = 136KB.

To do this for all tables in a schema at once:

begin
    dbms_stats.gather_schema_stats ('MYSCHEMA');
end;
/

select table_name, blocks, empty_blocks, num_freelist_blocks
from   user_tables;

Note: Changes made to the above after reading this AskTom thread

Environment variables in Jenkins

What ultimately worked for me was the following steps:

  1. Configure the Environment Injector Plugin: https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin
  2. Goto to the /job//configure screen
  3. In Build Environment section check "Inject environment variables to the build process"
  4. In "Properties Content" specified: TZ=America/New_York

Counting the number of elements in array

This expands on the answer by Denis Bubnov.

I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.

{% set count = 0 %}
{% for anchor in items %}
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}

{% if count > 0 %}
 ---  build the toc here --
{% endif %}

What is a lambda (function)?

Just because I cant see a C++11 example here, I'll go ahead and post this nice example from here. After searching, it is the clearest language specific example that I could find.

Hello, Lambdas, version 1

template<typename F>

void Eval( const F& f ) {
        f();
}
void foo() {
        Eval( []{ printf("Hello, Lambdas\n"); } );
}

Hello, Lambdas, version 2:

void bar() {
    auto f = []{ printf("Hello, Lambdas\n"); };
    f();
}

Sum a list of numbers in Python

Let us make it easy for Beginner:-

  1. The global keyword will allow the global variable message to be assigned within the main function without producing a new local variable
    message = "This is a global!"


def main():
    global message
    message = "This is a local"
    print(message)


main()
# outputs "This is a local" - From the Function call
print(message)
# outputs "This is a local" - From the Outer scope

This concept is called Shadowing

  1. Sum a list of numbers in Python
nums = [1, 2, 3, 4, 5]

var = 0


def sums():
    for num in nums:
        global var
        var = var + num
    print(var)


if __name__ == '__main__':
    sums()

Outputs = 15

How to make a page redirect using JavaScript?

Use:

document.location.href = "http://yoursite.com" + document.getElementById('somefield');

That would get the value of some text field or hidden field, and add it to your site URL to get a new URL (href). You can modify this to suit your needs.

Can I use a min-height for table, tr or td?

height for td works like min-height:

td {
  height: 100px;
}

instead of

td {
  min-height: 100px;
}

Table cells will grow when the content does not fit.

https://jsfiddle.net/qz70zps4/

npm install private github repositories by dependency in package.json

The accepted answer works, but I don't like much the idea to paste secure tokens into the package.json

I have found it elsewhere, just run this one-time command as documented in the git-config manpage.

git config --global url."https://${GITHUB_TOKEN}@github.com/".insteadOf [email protected]:

GITHUB_TOKEN may be setup as environmnet variable or pasted directly

and then I install private github repos like: npm install user/repo --save


works also in Heroku, just setup the above git config ... command as heroku-prebuild script in package.json and setup GITHUB_TOKEN as Heroku config variable.

Converting BitmapImage to Bitmap and vice versa

This converts from System.Drawing.Bitmap to BitmapImage:

MemoryStream ms = new MemoryStream();
YOURBITMAP.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
BitmapImage image = new BitmapImage();
image.BeginInit();
ms.Seek(0, SeekOrigin.Begin);
image.StreamSource = ms;
image.EndInit();

How to create major and minor gridlines with different linestyles in Python

A simple DIY way would be to make the grid yourself:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot([1,2,3], [2,3,4], 'ro')

for xmaj in ax.xaxis.get_majorticklocs():
  ax.axvline(x=xmaj, ls='-')
for xmin in ax.xaxis.get_minorticklocs():
  ax.axvline(x=xmin, ls='--')

for ymaj in ax.yaxis.get_majorticklocs():
  ax.axhline(y=ymaj, ls='-')
for ymin in ax.yaxis.get_minorticklocs():
  ax.axhline(y=ymin, ls='--')
plt.show()

What is syntax for selector in CSS for next element?

This is called the adjacent sibling selector, and it is represented by a plus sign...

h1.hc-reform + p {
  clear:both;
}

Note: this is not supported in IE6 or older.

Reading a registry key in C#

string InstallPath = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\MyApplication\AppPath", "Installed", null);    
if (InstallPath != null)
{
    // Do stuff
}

That code should get your value. You'll need to be

using Microsoft.Win32;

for that to work though.

Android canvas draw rectangle

Create a new class MyView, Which extends View. Override the onDraw(Canvas canvas) method to draw rectangle on Canvas.

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {

 Paint paint;
 Path path;

 public MyView(Context context) {
  super(context);
  init();
 }

 public MyView(Context context, AttributeSet attrs) {
  super(context, attrs);
  init();
 }

 public MyView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  init();
 }

 private void init(){
  paint = new Paint();
  paint.setColor(Color.BLUE);
  paint.setStrokeWidth(10);
  paint.setStyle(Paint.Style.STROKE);

 }

 @Override
 protected void onDraw(Canvas canvas) {
  // TODO Auto-generated method stub
  super.onDraw(canvas);

  canvas.drawRect(30, 50, 200, 350, paint);
  canvas.drawRect(100, 100, 300, 400, paint);
  //drawRect(left, top, right, bottom, paint)

 }

}

Then Move your Java activity to setContentView() using our custom View, MyView.Call this way.

    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(new MyView(this));
  }

For more details you can visit here

http://developer.android.com/reference/android/graphics/Canvas.html

Remote debugging a Java application

This is how you should setup Eclipse Debugger for remote debugging:

Eclipse Settings:

1.Click the Run Button
2.Select the Debug Configurations
3.Select the “Remote Java Application”
4.New Configuration

  • Name : GatewayPortalProject
  • Project : GatewayPortal-portlet
  • Connection Type: Socket Attach
  • Connection Properties: i) localhost ii) 8787

For JBoss:

1.Change the /path/toJboss/jboss-eap-6.1/bin/standalone.conf in your vm as follows: Uncomment the following line by removing the #:

JAVA_OPTS="$JAVA_OPTS -agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=n"

For Tomcat :

In catalina.bat file :

Step 1:

CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"

Step 2:

JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"

Step 3: Run Tomcat from command prompt like below:

catalina.sh jpda start

Then you need to set breakpoints in the Java classes you desire to debug.

How to make ng-repeat filter out duplicate results

You could use the unique filter from AngularUI (source code available here: AngularUI unique filter) and use it directly in the ng-options (or ng-repeat).

<select ng-model="orderProp" ng-options="place.category for place in places | unique:'category'">
    <option value="0">Default</option>
    // unique options from the categories
</select>

jQuery Mobile: document ready vs. page events

The simple difference between document ready and page event in jQuery-mobile is that:

  1. The document ready event is used for the whole HTML page,

    $(document).ready(function(e) {
        // Your code
    });
    
  2. When there is a page event, use for handling particular page event:

    <div data-role="page" id="second">
        <div data-role="header">
            <h3>
                Page header
            </h3>
        </div>
        <div data-role="content">
            Page content
        </div> <!--content-->
        <div data-role="footer">
            Page footer
        </div> <!--footer-->
    </div><!--page-->
    

You can also use document for handling the pageinit event:

$(document).on('pageinit', "#mypage", function() {

});

Optimistic vs. Pessimistic locking

Optimistic Locking is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) and check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic. (i.e. hasn't been updated between when you check the version and write the record to the disk) and update the version in one hit.

If the record is dirty (i.e. different version to yours) you abort the transaction and the user can re-start it.

This strategy is most applicable to high-volume systems and three-tier architectures where you do not necessarily maintain a connection to the database for your session. In this situation the client cannot actually maintain database locks as the connections are taken from a pool and you may not be using the same connection from one access to the next.

Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks. To use pessimistic locking you need either a direct connection to the database (as would typically be the case in a two tier client server application) or an externally available transaction ID that can be used independently of the connection.

In the latter case you open the transaction with the TxID and then reconnect using that ID. The DBMS maintains the locks and allows you to pick the session back up through the TxID. This is how distributed transactions using two-phase commit protocols (such as XA or COM+ Transactions) work.

Why is my JavaScript function sometimes "not defined"?

Verify your code with JSLint. It will usually find a ton of small errors, so the warning "JSLint may hurt your feelings" is pretty spot on. =)

align images side by side in html

Try using this format

<figure>
   <img src="img" alt="The Pulpit Rock" width="304" height="228">
   <figcaption>Fig1. - A view of the pulpit rock in Norway.</figcaption>
</figure>

This will give you a real caption (just add the 2nd and 3rd imgs using Float:left like others suggested)

Accessing nested JavaScript objects and arrays by string path

AngularJS has $scope.$eval

With AngularJS, one can use the $scope.$eval method to access nested objects:

$scope.someObject = someObject;
console.log( $scope.$eval("someObject.part3[0].name") ); //Part 3A

For more information, see

The DEMO

_x000D_
_x000D_
angular.module("app",[])
.run(function($rootScope) {
     $rootScope.someObject = {
         'part2' : {
              'name': 'Part 2',
              'size': '15',
              'qty' : '60'
         },
         'part3' : [{
              'name': 'Part 3A',
              'size': '10',
              'qty' : '20'
         },{
              name: 'Part 3B'           
         }]
     };
     console.log(
         "part3[0].name =",
         $rootScope.$eval("someObject.part3[0].name")
    );
})
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app"
</body>
_x000D_
_x000D_
_x000D_

how to use sqltransaction in c#

Update or Delete with sql transaction

 private void SQLTransaction() {
   try {
     string sConnectionString = "My Connection String";
     string query = "UPDATE [dbo].[MyTable] SET ColumnName = '{0}' WHERE ID = {1}";

     SqlConnection connection = new SqlConnection(sConnectionString);
     SqlCommand command = connection.CreateCommand();
     connection.Open();
     SqlTransaction transaction = connection.BeginTransaction("");
     command.Transaction = transaction;
     try {
       foreach(DataRow row in dt_MyData.Rows) {
         command.CommandText = string.Format(query, row["ColumnName"].ToString(), row["ID"].ToString());
         command.ExecuteNonQuery();
       }
       transaction.Commit();
     } catch (Exception ex) {
       transaction.Rollback();
       MessageBox.Show(ex.Message, "Error");
     }
   } catch (Exception ex) {
     MessageBox.Show("Problem connect to database.", "Error");
   }
 }

Correct way to initialize empty slice

The two alternative you gave are semantically identical, but using make([]int, 0) will result in an internal call to runtime.makeslice (Go 1.14).

You also have the option to leave it with a nil value:

var myslice []int

As written in the Golang.org blog:

a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.

A nil slice will however json.Marshal() into "null" whereas an empty slice will marshal into "[]", as pointed out by @farwayer.

None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.

Swift days between two NSDates

extension Date {
    func daysFromToday() -> Int {
        return Calendar.current.dateComponents([.day], from: self, to: Date()).day!
    }
}

Then use it like

    func dayCount(dateString: String) -> String{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMM dd,yyyy hh:mm a"
        let fetchedDate = dateFormatter.date(from: dateString)


        let day = fetchedDate?.daysFromToday()
        if day! > -1{
            return "\(day!) days passed."
        }else{
        return "\(day! * -1) days left."
        }
    }

"starting Tomcat server 7 at localhost has encountered a prob"

Hey i got the solution recently... Just copy the "ROOT" folder FROM C:\Program Files\ Apache Software Foundation\ Tomcat 7.0\ webapps \ TO your_Workspace\ .metadata\ .plugins\ org.eclipse.wst.server.core\ tmp0 \wtpwebapps\ and over write it when asked..

This is needed because eclipse forgets to copy that root folder to its workspace.. Just right click on Apache tomcat 7.0 in servers tab and observe that in location will be workspace metadata by default example:"location:[workspace metadata]". Therefore it will find the root folder which has the welcome page in it and the 404 page not found error will be displayed. Thankyou ..

how to run a winform from console application?

This worked for my needs...

Task mytask = Task.Run(() =>
{
    MyForm form = new MyForm();
    form.ShowDialog();
});

This starts the from in a new thread and does not release the thread until the form is closed. Task is in .Net 4 and later.

Python non-greedy regexes

Do you want it to match "(b)"? Do as Zitrax and Paolo have suggested. Do you want it to match "b"? Do

>>> x = "a (b) c (d) e"
>>> re.search(r"\((.*?)\)", x).group(1)
'b'

Stopping Excel Macro executution when pressing Esc won't work

You can stop a macro by pressing ctrl + break but if you don't have the break key you could use this autohotkey (open source) code:

+ESC:: SendInput {CtrlBreak} return

Pressing shift + Escape will be like pressing ctrl + break and thus will stop your macro.

All the glory to this page

Get folder up one level

To Whom, deailing with share hosting environment and still chance to have Current PHP less than 7.0 Who does not have dirname( __FILE__, 2 ); it is possible to use following.

function dirname_safe($path, $level = 0){
    $dir = explode(DIRECTORY_SEPARATOR, $path);
    $level = $level * -1;
    if($level == 0) $level = count($dir);
    array_splice($dir, $level);
    return implode($dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
}

print_r(dirname_safe(__DIR__, 2));

How to Set a Custom Font in the ActionBar Title?

To add to @Sam_D's answer, I had to do this to make it work:

this.setTitle("my title!");
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());
TextView title = ((TextView)v.findViewById(R.id.title));
title.setEllipsize(TextUtils.TruncateAt.MARQUEE);
title.setMarqueeRepeatLimit(1);
// in order to start strolling, it has to be focusable and focused
title.setFocusable(true);
title.setSingleLine(true);
title.setFocusableInTouchMode(true);
title.requestFocus();

It seems like overkill - referencing v.findViewById(R.id.title)) twice - but that's the only way it would let me do it.

ImportError: No module named psycopg2

Try installing

psycopg2-binary

with pip install psycopg2-binary --user

In bash, how to store a return value in a variable?

Something like this could be used, and still maintaining meanings of return (to return control signals) and echo (to return information) and logging statements (to print debug/info messages).

v_verbose=1
v_verbose_f=""         # verbose file name
FLAG_BGPID=""

e_verbose() {
        if [[ $v_verbose -ge 0 ]]; then
                v_verbose_f=$(tempfile)
                tail -f $v_verbose_f &
                FLAG_BGPID="$!"
        fi
}

d_verbose() {
        if [[ x"$FLAG_BGPID" != "x" ]]; then
                kill $FLAG_BGPID > /dev/null
                FLAG_BGPID=""
                rm -f $v_verbose_f > /dev/null
        fi
}

init() {
        e_verbose

        trap cleanup SIGINT SIGQUIT SIGKILL SIGSTOP SIGTERM SIGHUP SIGTSTP
}

cleanup() {
        d_verbose
}

init

fun1() {
    echo "got $1" >> $v_verbose_f
    echo "got $2" >> $v_verbose_f
    echo "$(( $1 + $2 ))"
    return 0
}

a=$(fun1 10 20)
if [[ $? -eq 0 ]]; then
    echo ">>sum: $a"
else
    echo "error: $?"
fi
cleanup

In here, I'm redirecting debug messages to separate file, that is watched by tail, and if there is any changes then printing the change, trap is used to make sure that background process always ends.

This behavior can also be achieved using redirection to /dev/stderr, But difference can be seen at the time of piping output of one command to input of other command.

Java double.MAX_VALUE?

Resurrecting the dead here, but just in case someone stumbles against this like myself. I know where to get the maximum value of a double, the (more) interesting part was to how did they get to that number.

double has 64 bits. The first one is reserved for the sign.

Next 11 represent the exponent (that is 1023 biased). It's just another way to represent the positive/negative values. If there are 11 bits then the max value is 1023.

Then there are 52 bits that hold the mantissa.

This is easily computed like this for example:

public static void main(String[] args) {

    String test = Strings.repeat("1", 52);

    double first = 0.5;
    double result = 0.0;
    for (char c : test.toCharArray()) {
        result += first;
        first = first / 2;
    }

    System.out.println(result); // close approximation of 1
    System.out.println(Math.pow(2, 1023) * (1 + result));
    System.out.println(Double.MAX_VALUE);

} 

You can also prove this in reverse order :

    String max = "0" + Long.toBinaryString(Double.doubleToLongBits(Double.MAX_VALUE));

    String sign = max.substring(0, 1);
    String exponent = max.substring(1, 12); // 11111111110
    String mantissa = max.substring(12, 64);

    System.out.println(sign); // 0 - positive
    System.out.println(exponent); // 2046 - 1023 = 1023
    System.out.println(mantissa); // 0.99999...8

Cannot read property 'map' of undefined

I think you forgot to change

data={this.props.data}

to

data={this.state.data}

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

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

instead of

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

Use python requests to download CSV

this worked nicely for me:

from csv import DictReader

f = requests.get('https://somedomain.com/file').content.decode('utf-8')
reader = DictReader(f.split('\n'))
csv_dict_list = list(reader)

Print second last column/field in awk

Small addition to Chris Kannon' accepted answer: only print if there actually is a second last column.

(
echo       | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1     | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2   | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2 3 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
)

How do I configure Notepad++ to use spaces instead of tabs?

In my Notepad++ 7.2.2, the Preferences section it's a bit different.

The option is located at: Settings / Preferences / Language / Replace by space as in the Screenshot.

Screenshot of the windows with preferences

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

Swift 4 • iOS 11.2.1 or later

extension ISO8601DateFormatter {
    convenience init(_ formatOptions: Options) {
        self.init()
        self.formatOptions = formatOptions
    }
}

extension Formatter {
    static let iso8601withFractionalSeconds = ISO8601DateFormatter([.withInternetDateTime, .withFractionalSeconds])
}

extension Date {
    var iso8601withFractionalSeconds: String { return Formatter.iso8601withFractionalSeconds.string(from: self) }
}

extension String {
    var iso8601withFractionalSeconds: Date? { return Formatter.iso8601withFractionalSeconds.date(from: self) }
}

Usage:

Date().description(with: .current)  //  Tuesday, February 5, 2019 at 10:35:01 PM Brasilia Summer Time"
let dateString = Date().iso8601withFractionalSeconds   //  "2019-02-06T00:35:01.746Z"

if let date = dateString.iso8601withFractionalSeconds {
    date.description(with: .current) // "Tuesday, February 5, 2019 at 10:35:01 PM Brasilia Summer Time"
    print(date.iso8601withFractionalSeconds)           //  "2019-02-06T00:35:01.746Z\n"
}

iOS 9 • Swift 3 or later

extension Formatter {
    static let iso8601withFractionalSeconds: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
        return formatter
    }()
}

Codable Protocol

If you need to encode and decode this format when working with Codable protocol you can create your own custom date encoding/decoding strategies:

extension JSONDecoder.DateDecodingStrategy {
    static let iso8601withFractionalSeconds = custom {
        let container = try $0.singleValueContainer()
        let string = try container.decode(String.self)
        guard let date = Formatter.iso8601withFractionalSeconds.date(from: string) else {
            throw DecodingError.dataCorruptedError(in: container,
                  debugDescription: "Invalid date: " + string)
        }
        return date
    }
}

and the encoding strategy

extension JSONEncoder.DateEncodingStrategy {
    static let iso8601withFractionalSeconds = custom {
        var container = $1.singleValueContainer()
        try container.encode(Formatter.iso8601withFractionalSeconds.string(from: $0))
    }
}

Playground Testing

let dates = [Date()]   // ["Feb 8, 2019 at 9:48 PM"]

encoding

let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601withFractionalSeconds
let data = try! encoder.encode(dates)
print(String(data: data, encoding: .utf8)!)

decoding

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601withFractionalSeconds
let decodedDates = try! decoder.decode([Date].self, from: data)  // ["Feb 8, 2019 at 9:48 PM"]

enter image description here

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

How to force keyboard with numbers in mobile website in Android

This should work. But I have same problems on an Android phone.

<input type="number" /> <input type="tel" />

I found out, that if I didn't include the jquerymobile-framework, the keypad showed correctly on the two types of fields.

But I havn't found a solution to solve that problem, if you really need to use jquerymobile.

UPDATE: I found out, that if the form-tag is stored out of the

<div data-role="page"> 

The number keypad isn't shown. This must be a bug...

How do ports work with IPv6?

They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.

An error occurred while signing: SignTool.exe not found

SignTool is moved to another location in the last SDK: C:\Program Files (x86)\Windows Kits\8.1\bin\x86

Need to install ClickOnce Publishing Tools during Visual Studio 2015 setup.

You can re-run the Installation from the Programs and Features section; find Visual Studio in the list and click Change.

Error ITMS-90717: "Invalid App Store Icon"

The below solution worked for me

  1. Click & open the App Store icon (1024*1024) in the preview app.
  2. Export it by unticking the Alpha channel.
  3. Replace the current App Store icon with the newly exported icon image.
  4. Validate and upload.

Note: This will not work on Mac OS High Sierra, please try a lower version to export without alpha or use any one of the image editing applications or try out the below alternatives.

Alternative 1: (Using Sierra or High Sierra and Ionic)

  1. Copy and Paste the App Store icon to the desktop.
  2. Open the image. Click File Menu->Duplicate.
  3. Save it by unticking the Alpha channel.
  4. Replace the current App Store icon with this one.
  5. Validate and upload.

Alternative 2: If duplicate does not work, try doing opening it in preview and then doing file export. I was able to unselect the alpha channel there. – by Alejandro Corredor.

Alternative 3 : Using High Sierra and Ionic, found the problem image in the following folder: [app name]/platforms/ios/[app name]/Images.xcassets/Appicon.appiconset/icon-1024.png. We have to copy it to the desktop and Save As while unchecking Alpha, then rename it to icon-1024.png, then delete the original and copy the new file back to the original folder. Export did not work though no error was displayed and all permissions were set/777. Hope this helps save someone the day I just lost. – by Ralph Hinkley

enter image description here

Convert python datetime to epoch with strftime

For an explicit timezone-independent solution, use the pytz library.

import datetime
import pytz

pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()

Output (float): 1333238400.0

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

I tried to change target sdk to 13 but does not works!! then when I changed compileSdkVersion 13 to compileSdkVersion 14 is compiled successfully :)

NOTE: I Work with Android Studio not Eclipse

PHP Redirect with POST data

I know this is an old question, but I have yet another alternative solution with jQuery:

var actionForm = $('<form>', {'action': 'nextpage.php', 'method': 'post'}).append($('<input>', {'name': 'action', 'value': 'delete', 'type': 'hidden'}), $('<input>', {'name': 'id', 'value': 'some_id', 'type': 'hidden'}));
actionForm.submit();

The above code uses jQuery to create a form tag, appending hidden fields as post fields, and submit it at last. The page will forward to the form target page with the POST data attached.

p.s. JavaScript & jQuery are required for this case. As suggested by the comments of the other answers, you can make use of <noscript> tag to create a standard HTML form in case JS is disabled.

How to Parse a JSON Object In Android

In the end I solved it by using JSONObject.get rather than JSONObject.getString and then cast test to a String.

private void saveData(String result) {
    try {
        JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
        JSONObject json2 = json.getJSONObject("results");
        test = (String) json2.get("name");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

How to copy a string of std::string type in C++?

strcpy is only for C strings. For std::string you copy it like any C++ object.

std::string a = "text";
std::string b = a; // copy a into b

If you want to concatenate strings you can use the + operator:

std::string a = "text";
std::string b = "image";
a = a + b; // or a += b;

You can even do many at once:

std::string c = a + " " + b + "hello";

Although "hello" + " world" doesn't work as you might expect. You need an explicit std::string to be in there: std::string("Hello") + "world"

How do I correct the character encoding of a file?

With vim from command line:

vim -c "set encoding=utf8" -c "set fileencoding=utf8" -c "wq" filename

Pushing value of Var into an Array

Off the top of my head I think it should be done like this:

var veggies = "carrot";
var fruitvegbasket = [];
fruitvegbasket.push(veggies);

How to create a POJO?

import java.io.Serializable;

public class Course implements Serializable {

    protected int courseId;
    protected String courseName;
    protected String courseType;

    public Course() {
        courseName = new String();
        courseType = new String();
    }

    public Course(String courseName, String courseType) {
        this.courseName = courseName;
        this.courseType = courseType;
    }

    public Course(int courseId, String courseName, String courseType) {
        this.courseId = courseId;
        this.courseName = courseName;
        this.courseType = courseType;
    }

    public int getCourseId() {
        return courseId;
    }

    public void setCourseId(int courseId) {
        this.courseId = courseId;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public String getCourseType() {
        return courseType;
    }

    public void setCourseType(String courseType) {
        this.courseType = courseType;
    }

    @Override
    public int hashCode() {
        return courseId;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj != null || obj instanceof Course) {
            Course c = (Course) obj;
            if (courseId == c.courseId && courseName.equals(c.courseName)
                    && courseType.equals(c.courseType))
                return true;
        }
        return false;
    }

    @Override
    public String toString() {
        return "Course[" + courseId + "," + courseName + "," + courseType + "]";
    }
}

HttpClient not supporting PostAsJsonAsync method C#

The missing reference is the System.Net.Http.Formatting.dll. But the better solution is to add the NuGet package Microsoft.AspNet.WebApi.Client to ensure the version of the formatting dll worked with the .NET framework version of System.Net.Http in my project.

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

Windows 10 x64 released August 2015 - same issue arising. MSVCR110.dll is also found in the sysWOW64 folder (which is where I found it, copying to system32 does not help). To resolve:

  1. uninstall the x86 versions of VC 11 vcredist_x64/86.exe for 2012 and 2013
  2. uninstall WAMP Server 2.5
  3. delete (maybe back up first) the WAMP folder
  4. restart windows
  5. reinstall WAMP 2.5

Hopefully like me you have a MySQL database backup handy!

T-SQL split string based on delimiter

These all helped me get to this. I am still on 2012 but now have something quick that will allow me to split a string, even if string has varying numbers of delimiters, and grab the nth substring from that string. It's quick too. I know this post is old, but it took me forever to find something so hopefully this will help someone else.

CREATE FUNCTION [dbo].[SplitsByIndex]
(@separator VARCHAR(20)  = ' ', 
 @string    VARCHAR(MAX), 
 @position  INT
)
RETURNS VARCHAR(MAX)
AS
     BEGIN
     DECLARE @results TABLE
     (id   INT IDENTITY(1, 1), 
      chrs VARCHAR(8000)
     );
     DECLARE @outResult VARCHAR(8000);
     WITH X(N)
          AS (SELECT 'Table1'
              FROM(VALUES(0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) T(C)),
          Y(N)
          AS (SELECT 'Table2'
              FROM X A1, 
                   X A2, 
                   X A3, 
                   X A4, 
                   X A5, 
                   X A6, 
                   X A7, 
                   X A8), -- Up to 16^8 = 4 billion
          T(N)
          AS (SELECT TOP (ISNULL(LEN(@string), 0)) ROW_NUMBER() OVER(
                                                   ORDER BY
              (
                  SELECT NULL
              )) - 1 N
              FROM Y),
          Delim(Pos)
          AS (SELECT t.N
              FROM T
              WHERE(SUBSTRING(@string, t.N, LEN(@separator + 'x') - 1) LIKE @separator
                    OR t.N = 0)),
          Separated(value)
          AS (SELECT SUBSTRING(@string, d.Pos + LEN(@separator + 'x') - 1, LEAD(d.Pos, 1, 2147483647) OVER(
                     ORDER BY
              (
                  SELECT NULL
              ))-d.Pos - LEN(@separator))
              FROM Delim d
              WHERE @string IS NOT NULL)
          INSERT INTO @results(chrs)
                 SELECT s.value
                 FROM Separated s
                 WHERE s.value <> @separator;
     SELECT @outResult =
     (
         SELECT chrs
         FROM @results
         WHERE id = @position
     );
     RETURN @outResult;
 END;

This can be used like this:

SELECT [dbo].[SplitsByIndex](' ',fieldname,2) 
from tablename

Smooth scroll without the use of jQuery

You can use a for loop with window.scrollTo and setTimeout to scroll smoothly with plain Javascript. To scroll to an element with my scrollToSmoothly function: scrollToSmoothly(elem.offsetTop) (assuming elem is a DOM element). You can use this to scroll smoothly to any y-position in the document.

function scrollToSmoothly(pos, time){
/*Time is only applicable for scrolling upwards*/
/*Code written by hev1*/
/*pos is the y-position to scroll to (in pixels)*/
     if(isNaN(pos)){
      throw "Position must be a number";
     }
     if(pos<0){
     throw "Position can not be negative";
     }
    var currentPos = window.scrollY||window.screenTop;
    if(currentPos<pos){
    var t = 10;
       for(let i = currentPos; i <= pos; i+=10){
       t+=10;
        setTimeout(function(){
        window.scrollTo(0, i);
        }, t/2);
      }
    } else {
    time = time || 2;
       var i = currentPos;
       var x;
      x = setInterval(function(){
         window.scrollTo(0, i);
         i -= 10;
         if(i<=pos){
          clearInterval(x);
         }
     }, time);
      }
}

Demo:

_x000D_
_x000D_
<button onClick="scrollToDiv()">Scroll To Element</button>_x000D_
<div style="margin: 1000px 0px; text-align: center;">Div element<p/>_x000D_
<button onClick="scrollToSmoothly(Number(0))">Scroll back to top</button>_x000D_
</div>_x000D_
<script>_x000D_
function scrollToSmoothly(pos, time){_x000D_
/*Time is only applicable for scrolling upwards*/_x000D_
/*Code written by hev1*/_x000D_
/*pos is the y-position to scroll to (in pixels)*/_x000D_
     if(isNaN(pos)){_x000D_
      throw "Position must be a number";_x000D_
     }_x000D_
     if(pos<0){_x000D_
     throw "Position can not be negative";_x000D_
     }_x000D_
    var currentPos = window.scrollY||window.screenTop;_x000D_
    if(currentPos<pos){_x000D_
    var t = 10;_x000D_
       for(let i = currentPos; i <= pos; i+=10){_x000D_
       t+=10;_x000D_
        setTimeout(function(){_x000D_
       window.scrollTo(0, i);_x000D_
        }, t/2);_x000D_
      }_x000D_
    } else {_x000D_
    time = time || 2;_x000D_
       var i = currentPos;_x000D_
       var x;_x000D_
      x = setInterval(function(){_x000D_
         window.scrollTo(0, i);_x000D_
         i -= 10;_x000D_
         if(i<=pos){_x000D_
          clearInterval(x);_x000D_
         }_x000D_
     }, time);_x000D_
      }_x000D_
}_x000D_
function scrollToDiv(){_x000D_
  var elem = document.querySelector("div");_x000D_
  scrollToSmoothly(elem.offsetTop);_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

Why is my Button text forced to ALL CAPS on Lollipop?

In Android Studio IDE, you have to click the Filter icon to show expert properties. Then you will see the textAllCaps property. Check it, then uncheck it.

Detect WebBrowser complete page loading

I did the following:

void BrowserDocumentCompleted(object sender,
        WebBrowserDocumentCompletedEventArgs e)
{
  if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath)
    return; 

  //The page is finished loading 
}

The last page loaded tends to be the one navigated to, so this should work.

From here.

How to correctly use the ASP.NET FileUpload control

Instead of instantiating the FileUpload in your code behind file, just declare it in your markup file (.aspx file):

<asp:FileUpload ID="fileUpload" runat="server" />

Then you will be able to access all of the properties of the control, such as HasFile.

scrollable div inside container

Is this what you are wanting?

_x000D_
_x000D_
<body>_x000D_
  <div id="div1" style="height: 500px;">_x000D_
    <div id="div2" style="height: inherit; overflow: auto; border:1px solid red;">_x000D_
      <div id="div3" style="height:1500px;border:5px solid yellow;">hello</div>_x000D_
    </div>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/fMs67/1/

jQuery, get ID of each element in a class using .each?

Try this, replacing .myClassName with the actual name of the class (but keep the period at the beginning).

$('.myClassName').each(function() {
    alert( this.id );
});

So if the class is "test", you'd do $('.test').each(func....

This is the specific form of .each() that iterates over a jQuery object.

The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t.

Using that form of $.each(), you would need to do it like this:

$.each($('.myClassName'), function() {
    alert( this.id );
});

...which will have the same result as the example above.

How can I check for Python version in a program that uses new language features?

Although the question is: How do I get control early enough to issue an error message and exit?

The question that I answer is: How do I get control early enough to issue an error message before starting the app?

I can answer it a lot differently then the other posts. Seems answers so far are trying to solve your question from within Python.

I say, do version checking before launching Python. I see your path is Linux or unix. However I can only offer you a Windows script. I image adapting it to linux scripting syntax wouldn't be too hard.

Here is the DOS script with version 2.7:

@ECHO OFF
REM see http://ss64.com/nt/for_f.html
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
IF NOT ErrorLevel 1 GOTO Python27
ECHO must use python2.7 or greater
GOTO EOF
:Python27
python.exe tern.py
GOTO EOF
:EOF

This does not run any part of your application and therefore will not raise a Python Exception. It does not create any temp file or add any OS environment variables. And it doesn't end your app to an exception due to different version syntax rules. That's three less possible security points of access.

The FOR /F line is the key.

FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul

For multiple python version check check out url: http://www.fpschultze.de/modules/smartfaq/faq.php?faqid=17

And my hack version:

[MS script; Python version check prelaunch of Python module] http://pastebin.com/aAuJ91FQ

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

I had this problem, setting copy local on and off etc did not work. The project was not using nuget so fixes around that were out of the question also.

The fix for me was to install MVC 3 (which I did through the web platform installer).

I suspect this will become more of a solution for people as the .net framework continues to advance and people don't have the older MVC stuff installed.

How to set custom header in Volley Request

In Kotlin,

You have to override getHeaders() method like :

val volleyEnrollRequest = object : JsonObjectRequest(GET_POST_PARAM, TARGET_URL, PAYLOAD_BODY_IF_YOU_WISH,
            Response.Listener {
                // Success Part  
            },

            Response.ErrorListener {
                // Failure Part
            }
        ) {
            // Providing Request Headers

            override fun getHeaders(): Map<String, String> {
               // Create HashMap of your Headers as the example provided below

                val headers = HashMap<String, String>()
                headers["Content-Type"] = "application/json"
                headers["app_id"] = APP_ID
                headers["app_key"] = API_KEY

                return headers
            }
        }

Ruby convert Object to Hash

To do this without Rails, a clean way is to store attributes on a constant.

class Gift
  ATTRIBUTES = [:name, :price]
  attr_accessor(*ATTRIBUTES)
end

And then, to convert an instance of Gift to a Hash, you can:

class Gift
  ...
  def to_h
    ATTRIBUTES.each_with_object({}) do |attribute_name, memo|
      memo[attribute_name] = send(attribute_name)
    end
  end
end

This is a good way to do this because it will only include what you define on attr_accessor, and not every instance variable.

class Gift
  ATTRIBUTES = [:name, :price]
  attr_accessor(*ATTRIBUTES)

  def create_random_instance_variable
    @xyz = 123
  end

  def to_h
    ATTRIBUTES.each_with_object({}) do |attribute_name, memo|
      memo[attribute_name] = send(attribute_name)
    end
  end
end

g = Gift.new
g.name = "Foo"
g.price = 5.25
g.to_h
#=> {:name=>"Foo", :price=>5.25}

g.create_random_instance_variable
g.to_h
#=> {:name=>"Foo", :price=>5.25}

Background color in input and text fields

The best solution is the attribute selector in CSS (input[type="text"]) as the others suggested.

But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.

In this case your only option seems to be to define classes on input elements.

<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...

and target them with a class selector:

input.input-box, textarea { background: cyan; }

Including an anchor tag in an ASP.NET MVC Html.ActionLink

Here is the real life example

@Html.Grid(Model).Columns(columns =>
    {
           columns.Add()
                   .Encoded(false)
                   .Sanitized(false)
                   .SetWidth(10)
                   .Titled(string.Empty)
                   .RenderValueAs(x => @Html.ActionLink("Edit", "UserDetails", "Membership", null, null, "discount", new { @id = @x.Id }, new { @target = "_blank" }));

  }).WithPaging(200).EmptyText("There Are No Items To Display")

And the target page has TABS

<ul id="myTab" class="nav nav-tabs" role="tablist">

        <li class="active"><a href="#discount" role="tab" data-toggle="tab">Discount</a></li>
    </ul>

Camera access through browser

You could try this:

<input type="file" capture="camera" accept="image/*" id="cameraInput" name="cameraInput">

but it has to be iOS 6+ to work. That will give you a nice dialogue for you to choose either to take a picture or to upload one from your album i.e.

Screenhot

An example can be found here: Capturing camera/picture data without PhoneGap

How to install an apk on the emulator in Android Studio?

Drag and drop apk if the emulator is launched from Android Studio. If the emulator is started from command line, drag and drop doesn't work, but @Tarek K. Ajaj instructions (above) work.

Note: Installed app won't automatically appear on the home screen, it is in the apps container - the dotted grid icon. It can be dragged from there to the home screen.

Dynamically Add Variable Name Value Pairs to JSON Object

when using javascript objects, you can also just use "dot notation" to add an item, (which JSLint prefers)

var myArray = { name : "john" };
//will initiate a key-value array with one item "name" and the value "john"
myArray.lastName = "smith";
//will add a key named lastName with the value "smith"
//Object {name: "john", lastName: "smith"}

Here is a screenshot from testing in the Chrome console

screenshot

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

Cannot find Dumpbin.exe

You probably need to open a command prompt with the PATH set up properly. Look for an icon in the start menu that says something like "Visual C++ 2005 Command Prompt". You should be able to run dumpbin (and all the other command line tools) from there.

2 "style" inline css img tags?

You should use :

<img src="http://img705.imageshack.us/img705/119/original120x75.png" style="height:100px;width:100px;" alt="25"/>

That should work!!

If you want to create class then :

.size {
width:100px;
height:100px;
}

and then apply it like :

<img src="http://img705.imageshack.us/img705/119/original120x75.png" class="size" alt="25"/>

by creating a class you can use it at multiple places.

If you want to use only at one place then use inline CSS. Also Inline CSS overrides other CSS.

Double quotes within php script echo

use a HEREDOC, which eliminates any need to swap quote types and/or escape them:

echo <<<EOL
<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>
EOL;

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

Simply changing HTTP to HTTPS solved this issue for me.

WRONG :

<script src="http://code.jquery.com/jquery-3.5.1.js"></script>

CORRECT :

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>

Changing the tmp folder of mysql

if you dont have apparmor or selinux issues, but still get errorcode 13's:

mysql must be able to access the full path. I.e. all folders must be mysql accessible, not just the one you intend in pointing to.

example, you try using this in your mysql configuration: tmp = /some/folder/on/disk

# will work, as user root:
mkdir -p /some/folder/on/disk
chown -R mysql:mysql /some

# will not work, also as user root:
mkdir -p /some/folder/on/disk
chown -R mysql:mysql /some/folder/on/disk

Regex for numbers only

Your regex will match anything that contains a number, you want to use anchors to match the whole string and then match one or more numbers:

regex = new Regex("^[0-9]+$");

The ^ will anchor the beginning of the string, the $ will anchor the end of the string, and the + will match one or more of what precedes it (a number in this case).

Set start value for column with autoincrement

You need to set the Identity seed to that value:

CREATE TABLE orders
(
 id int IDENTITY(9586,1)
)

To alter an existing table:

ALTER TABLE orders ALTER COLUMN Id INT IDENTITY (9586, 1);

More info on CREATE TABLE (Transact-SQL) IDENTITY (Property)

OnClick Send To Ajax

Tried and working. you are using,

<textarea name='Status'> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

I am using javascript , (don't know about php), use id ="status" in textarea like

<textarea name='Status' id="status"> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

then make a call to servlet sending the status to backend for updating using whatever strutucre(like MVC in java or anyother) you like, like this in your UI in script tag

<srcipt>
function UpdateStatus(){

//make an ajax call and get status value using the same 'id'
var var1= document.getElementById("status").value;
$.ajax({

        type:"GET",//or POST
        url:'http://localhost:7080/ajaxforjson/Testajax',
                           //  (or whatever your url is)
        data:{data1:var1},
        //can send multipledata like {data1:var1,data2:var2,data3:var3
        //can use dataType:'text/html' or 'json' if response type expected 
        success:function(responsedata){
               // process on data
               alert("got response as "+"'"+responsedata+"'");

        }
     })

}
</script>

and jsp is like

the servlet will look like:   //webservlet("/zcvdzv") is just for url annotation
@WebServlet("/Testajax")

public class Testajax extends HttpServlet {
private static final long serialVersionUID = 1L;
public Testajax() {
    super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String data1=request.getParameter("data1");
    //do processing on datas pass in other java class to add to DB
    // i am adding or concatenate
    String data="i Got : "+"'"+data1+"' ";
    System.out.println(" data1 : "+data1+"\n data "+data);
    response.getWriter().write(data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

DB2 Query to retrieve all table names for a given schema

db2 connect to MY_INSTACE_DB with myuser -- connect to db2    
db2 "select TABNAME from syscat.tables where tabschema = 'mySchema' with ur"
db2 terminate -- end connection

jQuery - Check if DOM element already exists

This question is about whether an element exists and all answers check if it doesn't exist :) Minor difference but worth mentioning.

Based on jQuery documentation the recommended way to check for existence is

if ($( "#myDiv" ).length) {
    // element exists
}

If you prefer to check for missing element you could use either:

if (!$( "#myDiv" ).length) {
    // element doesn't exist
}

or

if (0 === $( "#myDiv" ).length) {
    // element doesn't exist
}

Note please that in the second option I've used === which is slightly faster than == and put the 0 on the left as a Yoda condition.

node.js require all files in a folder?

I have a folder /fields full of files with a single class each, ex:

fields/Text.js -> Test class
fields/Checkbox.js -> Checkbox class

Drop this in fields/index.js to export each class:

var collectExports, fs, path,
  __hasProp = {}.hasOwnProperty;

fs = require('fs');    
path = require('path');

collectExports = function(file) {
  var func, include, _results;

  if (path.extname(file) === '.js' && file !== 'index.js') {
    include = require('./' + file);
    _results = [];
    for (func in include) {
      if (!__hasProp.call(include, func)) continue;
      _results.push(exports[func] = include[func]);
    }
    return _results;
  }
};

fs.readdirSync('./fields/').forEach(collectExports);

This makes the modules act more like they would in Python:

var text = new Fields.Text()
var checkbox = new Fields.Checkbox()

How to export a table dataframe in PySpark to csv?

You need to repartition the Dataframe in a single partition and then define the format, path and other parameter to the file in Unix file system format and here you go,

df.repartition(1).write.format('com.databricks.spark.csv').save("/path/to/file/myfile.csv",header = 'true')

Read more about the repartition function Read more about the save function

However, repartition is a costly function and toPandas() is worst. Try using .coalesce(1) instead of .repartition(1) in previous syntax for better performance.

Read more on repartition vs coalesce functions.

Download Excel file via AJAX MVC

First Create the controller action that will create the Excel File

[HttpPost]
public JsonResult ExportExcel()
{
    DataTable dt = DataService.GetData();
    var fileName = "Excel_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls";

    //save the file to server temp folder
    string fullPath = Path.Combine(Server.MapPath("~/temp"), fileName);

    using (var exportData = new MemoryStream())
    {
        //I don't show the detail how to create the Excel, this is not the point of this article,
        //I just use the NPOI for Excel handler
        Utility.WriteDataTableToExcel(dt, ".xls", exportData);

        FileStream file = new FileStream(fullPath, FileMode.Create, FileAccess.Write);
        exportData.WriteTo(file);
        file.Close();
    }

    var errorMessage = "you can return the errors in here!";

    //return the Excel file name
    return Json(new { fileName = fileName, errorMessage = "" });
}

then create the Download action

[HttpGet]
[DeleteFileAttribute] //Action Filter, it will auto delete the file after download, 
                      //I will explain it later
public ActionResult Download(string file)
{
    //get the temp folder and file path in server
    string fullPath = Path.Combine(Server.MapPath("~/temp"), file);

    //return the file for download, this is an Excel 
    //so I set the file content type to "application/vnd.ms-excel"
    return File(fullPath, "application/vnd.ms-excel", file);
}

if you want to delete the file after downloaded create this

public class DeleteFileAttribute : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.Flush();

        //convert the current filter context to file and get the file path
        string filePath = (filterContext.Result as FilePathResult).FileName;

        //delete the file after download
        System.IO.File.Delete(filePath);
    }
}

and finally ajax call from you MVC Razor view

//I use blockUI for loading...
$.blockUI({ message: '<h3>Please wait a moment...</h3>' });    
$.ajax({
    type: "POST",
    url: '@Url.Action("ExportExcel","YourController")', //call your controller and action
    contentType: "application/json; charset=utf-8",
    dataType: "json",
}).done(function (data) {
    //console.log(data.result);
    $.unblockUI();

    //get the file name for download
    if (data.fileName != "") {
        //use window.location.href for redirect to download action for download the file
        window.location.href = "@Url.RouteUrl(new 
            { Controller = "YourController", Action = "Download"})/?file=" + data.fileName;
    }
});

How to convert an entire MySQL database characterset and collation to UTF-8?

To change the character set encoding to UTF-8 follow simple steps in PHPMyAdmin

  1. Select your Database SS

  2. Go To Operations SS

  3. In operations tab, on the bottom collation drop down menu, select you desire encoding i.e(utf8_general_ci), and also check the checkbox (1)change all table collations, (2) Change all tables columns collations. and hit Go.

SS

Grep only the first match and stop

A single liner, using find:

find -type f -exec grep -lm1 "PATTERN" {} \; -a -quit

SQL - Create view from multiple tables

This works too and you dont have to use join or anything:

DROP VIEW IF EXISTS yourview;

CREATE VIEW yourview AS
    SELECT table1.column1, 
    table2.column2
FROM 
table1, table2 
WHERE table1.column1 = table2.column1;