Programs & Examples On #Icmp

Internet Control Message Protocol, designed for control and diagnostic messages. Used by common diagnostic tools like ping or traceroute.

ping response "Request timed out." vs "Destination Host unreachable"

Put very simply, request timeout means there was no response whereas destination unreachable may mean the address specified does not exist i.e. you typed in the wrong IP address.

Pinging servers in Python

  1 #!/usr/bin/python
  2
  3 import os
  4 import sys
  5 import time
  6
  7 os.system("clear")
  8 home_network = "172.16.23."
  9 mine = []
 10
 11 for i in range(1, 256):
 12         z =  home_network + str(i)
 13         result = os.system("ping -c 1 "+ str(z))
 14         os.system("clear")
 15         if result == 0:
 16                 mine.append(z)
 17
 18 for j in mine:
 19         print "host ", j ," is up"

A simple one i just cooked up in a minute..using icmplib needs root privs the below works pretty good! HTH

vba: get unique values from array

This post contains 2 examples. I like the 2nd one:

Sub unique() 
  Dim arr As New Collection, a 
  Dim aFirstArray() As Variant 
  Dim i As Long 
 
  aFirstArray() = Array("Banana", "Apple", "Orange", "Tomato", "Apple", _ 
  "Lemon", "Lime", "Lime", "Apple") 
 
  On Error Resume Next 
  For Each a In aFirstArray 
     arr.Add a, a 
  Next
  On Error Goto 0 ' added to original example by PEH
 
  For i = 1 To arr.Count 
     Cells(i, 1) = arr(i) 
  Next 
 
End Sub 

How to make all controls resize accordingly proportionally when window is maximized?

Just thought i'd share this with anyone who needs more clarity on how to achieve this:

myCanvas is a Canvas control and Parent to all other controllers. This code works to neatly resize to any resolution from 1366 x 768 upward. Tested up to 4k resolution 4096 x 2160

Take note of all the MainWindow property settings (WindowStartupLocation, SizeToContent and WindowState) - important for this to work correctly - WindowState for my user case requirement was Maximized

xaml

<Window x:Name="mainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyApp" 
    xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
    x:Class="MyApp.MainWindow" 
     Title="MainWindow"  SizeChanged="MainWindow_SizeChanged"
    Width="1366" Height="768" WindowState="Maximized" WindowStartupLocation="CenterOwner" SizeToContent="WidthAndHeight">
  
    <Canvas x:Name="myCanvas" HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1356">
        <Image x:Name="maxresdefault_1_1__jpg" Source="maxresdefault-1[1].jpg" Stretch="Fill" Opacity="0.6" Height="767" Canvas.Left="-6" Width="1366"/>

        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" Height="0" Canvas.Left="-811" Canvas.Top="148" Width="766"/>
        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" HorizontalAlignment="Right" Width="210" Height="0" Canvas.Left="1653" Canvas.Top="102"/>
        <Image x:Name="imgscroll" Source="BcaKKb47i[1].png" Stretch="Fill" RenderTransformOrigin="0.5,0.5" Height="523" Canvas.Left="-3" Canvas.Top="122" Width="580">
            <Image.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="89.093"/>
                    <TranslateTransform/>
                </TransformGroup>
            </Image.RenderTransform>
        </Image>

.cs

 private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        myCanvas.Width = e.NewSize.Width;
        myCanvas.Height = e.NewSize.Height;

        double xChange = 1, yChange = 1;

        if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width / e.PreviousSize.Width);

        if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

        ScaleTransform scale = new ScaleTransform(myCanvas.LayoutTransform.Value.M11 * xChange, myCanvas.LayoutTransform.Value.M22 * yChange);
        myCanvas.LayoutTransform = scale;
        myCanvas.UpdateLayout();
    }

Get class name of object as string in Swift

One can also use mirrors:

let vc = UIViewController()

String(Mirror(reflecting: vc).subjectType)

NB: This method can also be used for Structs and Enums. There is a displayStyle that gives an indication of what type of the structure:

Mirror(reflecting: vc).displayStyle

The return is an enum so you can:

Mirror(reflecting: vc).displayStyle == .Class

Laravel 5.2 not reading env file

I ran into this same problem on my local, and I have tried all the answers here but to no avail. Only this worked for me, php artisan config:clear and restart server. Works like a charm!

Styling multi-line conditions in 'if' statements?

I find that when I have long conditions, I often have a short code body. In that case, I just double-indent the body, thus:

if (cond1 == 'val1' and cond2 == 'val2' and
    cond3 == 'val3' and cond4 == 'val4'):
        do_something

How to initialize/instantiate a custom UIView class with a XIB file in Swift

And this is the answer of Frederik on Swift 3.0

/*
 Usage:
 - make your CustomeView class and inherit from this one
 - in your Xib file make the file owner is your CustomeView class
 - *Important* the root view in your Xib file must be of type UIView
 - link all outlets to the file owner
 */
@IBDesignable
class NibLoadingView: UIView {

    @IBOutlet weak var view: UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        nibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        nibSetup()
    }

    private func nibSetup() {
        backgroundColor = .clear

        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.translatesAutoresizingMaskIntoConstraints = true

        addSubview(view)
    }

    private func loadViewFromNib() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
        let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView

        return nibView
    }
}

UILabel - auto-size label to fit text?

I created some methods based Daniel's reply above.

-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text
{
    CGSize maximumLabelSize     = CGSizeMake(290, FLT_MAX);

    CGSize expectedLabelSize    = [text sizeWithFont:label.font
                                constrainedToSize:maximumLabelSize
                                    lineBreakMode:label.lineBreakMode];

    return expectedLabelSize.height;
}

-(void)resizeHeightToFitForLabel:(UILabel *)label
{
    CGRect newFrame         = label.frame;
    newFrame.size.height    = [self heightForLabel:label withText:label.text];
    label.frame             = newFrame;
}

-(void)resizeHeightToFitForLabel:(UILabel *)label withText:(NSString *)text
{
    label.text              = text;
    [self resizeHeightToFitForLabel:label];
}

How to overwrite the previous print to stdout in python?

Suppress the newline and print \r.

print 1,
print '\r2'

or write to stdout:

sys.stdout.write('1')
sys.stdout.write('\r2')

Alternative to the HTML Bold tag

A very old thread, I know. - but for completeness:

I use <span class="bold">my text</span>    

as I upload the four font styles: normal; bold; italic and bold italic into my web-site via css.

I feel the resulting output is better than simply modifying a font and is closer to the designers intention of how the boldened font should look.

The same applies for italic and bolditalic of course, which gives me additional flexibility.

Create tap-able "links" in the NSAttributedString of a UILabel?

based on Charles Gamble answer, this what I used (I removed some lines that confused me and gave me wrong indexed) :

- (BOOL)didTapAttributedTextInLabel:(UILabel *)label inRange:(NSRange)targetRange TapGesture:(UIGestureRecognizer*) gesture{
    NSParameterAssert(label != nil);

    // create instances of NSLayoutManager, NSTextContainer and NSTextStorage
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:label.attributedText];

    // configure layoutManager and textStorage
    [textStorage addLayoutManager:layoutManager];

    // configure textContainer for the label
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(label.frame.size.width, label.frame.size.height)];

    textContainer.lineFragmentPadding = 0.0;
    textContainer.lineBreakMode = label.lineBreakMode;
    textContainer.maximumNumberOfLines = label.numberOfLines;

    // find the tapped character location and compare it to the specified range
    CGPoint locationOfTouchInLabel = [gesture locationInView:label];
    [layoutManager addTextContainer:textContainer]; //(move here, not sure it that matter that calling this line after textContainer is set

    NSInteger indexOfCharacter = [layoutManager characterIndexForPoint:locationOfTouchInLabel
                                                           inTextContainer:textContainer
                                  fractionOfDistanceBetweenInsertionPoints:nil];
    if (NSLocationInRange(indexOfCharacter, targetRange)) {
        return YES;
    } else {
        return NO;
    }
}

What are the specific differences between .msi and setup.exe file?

MSI is an installer file which installs your program on the executing system.

Setup.exe is an application (executable file) which has msi file(s) as its one of the resources. Executing Setup.exe will in turn execute msi (the installer) which writes your application to the system.

Edit (as suggested in comment): Setup executable files don't necessarily have an MSI resource internally

@Cacheable key on multiple method arguments

You can use a Spring-EL expression, for eg on JDK 1.7:

@Cacheable(value="bookCache", key="T(java.util.Objects).hash(#p0,#p1, #p2)")

What is the cause for "angular is not defined"

You have to put your script tag after the one that references Angular. Move it out of the head:

<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>

The way you've set it up now, your script runs before Angular is loaded on the page.

jQuery vs. javascript?

"I actually tried to had a normal objective discusssion over pros and cons of 1., using framework over pure javascript and 2., jquery vs. others, since jQuery seems to be easiest to work with with quickest learning curve."

Using any framework because you don't want to actually learn the underlying language is absolutely wrong not only for JavaScript, but for any other programming language.

"Is there any reason (besides browser sniffing and personal "hate" against John Resig) why jQuery is wrong?"

Most of the hate agains it comes from the exaggerated fanboyism which pollutes forums with "use jQuery" as an answer for every single JavaScript question and the overuse which produces code in which simple statements such as declaring a variable are done through library calls.

Nevertheless, there are also some legit technical issues such as the shared guilt in producing illegible code and overhead. Of course those two are aggravated by the lack of developer proficiency rather than the library itself.

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

You should trigger the animation to revert once it's completed w/ javascript.

  $(".item").live("animationend webkitAnimationEnd", function(){
    $(this).removeClass('animate');
  });

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

.apply() takes in a function as the first parameter; pass in the label_race function as so:

df['race_label'] = df.apply(label_race, axis=1)

You don't need to make a lambda function to pass in a function.

How to set the height of table header in UITableView?

Just set the frame property of the tableHeaderView.

How to change status bar color to match app in Lollipop? [Android]

To set the status bar color, create a style.xml file under res/values-v21 folder with this content:

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

    <style name="AppBaseTheme" parent="AppTheme">
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@color/blue</item>
    </style>

</resources>

How do I create a comma-separated list from an array in PHP?

Follow this one

$teacher_id = '';

        for ($i = 0; $i < count($data['teacher_id']); $i++) {

            $teacher_id .= $data['teacher_id'][$i].',';

        }
        $teacher_id = rtrim($teacher_id, ',');
        echo $teacher_id; exit;

What is the function of the push / pop instructions used on registers in x86 assembly?

Pushing and popping registers are behind the scenes equivalent to this:

push reg   <= same as =>      sub  $8,%rsp        # subtract 8 from rsp
                              mov  reg,(%rsp)     # store, using rsp as the address

pop  reg    <= same as=>      mov  (%rsp),reg     # load, using rsp as the address
                              add  $8,%rsp        # add 8 to the rsp

Note this is x86-64 At&t syntax.

Used as a pair, this lets you save a register on the stack and restore it later. There are other uses, too.

Scroll to bottom of Div on page load (jQuery)

All the answers that I can see here, including the currently "accepted" one, is actually wrong in that they set:

scrollTop = scrollHeight

Whereas the correct approach is to set:

scrollTop = scrollHeight - clientHeight

In other words:

$('#div1').scrollTop($('#div1')[0].scrollHeight - $('#div1')[0].clientHeight);

Or animated:

$("#div1").animate({
  scrollTop: $('#div1')[0].scrollHeight - $('#div1')[0].clientHeight
}, 1000);

Number to String in a formula field

i wrote a simple function for this:

Function (stringVar param)
(
    Local stringVar oneChar := '0';
    Local numberVar strLen := Length(param);
    Local numberVar index := strLen;

    oneChar = param[strLen];

    while index > 0 and oneChar = '0' do
    (
        oneChar := param[index];
        index := index - 1;
    );

    Left(param , index + 1);
)

REST API error return good practices

The main choice is do you want to treat the HTTP status code as part of your REST API or not.

Both ways work fine. I agree that, strictly speaking, one of the ideas of REST is that you should use the HTTP Status code as a part of your API (return 200 or 201 for a successful operation and a 4xx or 5xx depending on various error cases.) However, there are no REST police. You can do what you want. I have seen far more egregious non-REST APIs being called "RESTful."

At this point (August, 2015) I do recommend that you use the HTTP Status code as part of your API. It is now much easier to see the return code when using frameworks than it was in the past. In particular, it is now easier to see the non-200 return case and the body of non-200 responses than it was in the past.

The HTTP Status code is part of your api

  1. You will need to carefully pick 4xx codes that fit your error conditions. You can include a rest, xml, or plaintext message as the payload that includes a sub-code and a descriptive comment.

  2. The clients will need to use a software framework that enables them to get at the HTTP-level status code. Usually do-able, not always straight-forward.

  3. The clients will have to distinguish between HTTP status codes that indicate a communications error and your own status codes that indicate an application-level issue.

The HTTP Status code is NOT part of your api

  1. The HTTP status code will always be 200 if your app received the request and then responded (both success and error cases)

  2. ALL of your responses should include "envelope" or "header" information. Typically something like:

    envelope_ver: 1.0
    status:  # use any codes you like. Reserve a code for success. 
    msg: "ok" # A human string that reflects the code. Useful for debugging.
    data: ...  # The data of the response, if any.
  3. This method can be easier for clients since the status for the response is always in the same place (no sub-codes needed), no limits on the codes, no need to fetch the HTTP-level status-code.

Here's a post with a similar idea: http://yuiblog.com/blog/2008/10/15/datatable-260-part-one/

Main issues:

  1. Be sure to include version numbers so you can later change the semantics of the api if needed.

  2. Document...

How get all values in a column using PHP?

Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.


This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php

$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $storeArray[] =  $row['names'];  
}
// now $storeArray will have all the names.

Calculate text width with JavaScript

Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size.

_x000D_
_x000D_
var fontSize = 12;_x000D_
var test = document.getElementById("Test");_x000D_
test.style.fontSize = fontSize;_x000D_
var height = (test.clientHeight + 1) + "px";_x000D_
var width = (test.clientWidth + 1) + "px"_x000D_
_x000D_
console.log(height, width);
_x000D_
#Test_x000D_
{_x000D_
    position: absolute;_x000D_
    visibility: hidden;_x000D_
    height: auto;_x000D_
    width: auto;_x000D_
    white-space: nowrap; /* Thanks to Herb Caudill comment */_x000D_
}
_x000D_
<div id="Test">_x000D_
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_x000D_
</div>
_x000D_
_x000D_
_x000D_

Best way to check if object exists in Entity Framework?

I just check if object is null , it works 100% for me

    try
    {
        var ID = Convert.ToInt32(Request.Params["ID"]);
        var Cert = (from cert in db.TblCompCertUploads where cert.CertID == ID select cert).FirstOrDefault();
        if (Cert != null)
        {
            db.TblCompCertUploads.DeleteObject(Cert);
            db.SaveChanges();
            ViewBag.Msg = "Deleted Successfully";
        }
        else
        {
            ViewBag.Msg = "Not Found !!";
        }                           
    }
    catch
    {
        ViewBag.Msg = "Something Went wrong";
    }

Firestore Getting documents id from collection

I've finally found the solution. Victor was close with the doc data.

const racesCollection: AngularFirestoreCollection<Race>;
return racesCollection.snapshotChanges().map(actions => {       
  return actions.map(a => {
    const data = a.payload.doc.data() as Race;
    data.id = a.payload.doc.id;
    return data;
  });
});

ValueChanges() doesn't include metadata, therefor we must use SnapshotChanges() when we require the document id and then map it properly as stated here https://github.com/angular/angularfire2/blob/master/docs/firestore/collections.md

How to start a stopped Docker container with a different command?

Edit this file (corresponding to your stopped container):

vi /var/lib/docker/containers/923...4f6/config.json

Change the "Path" parameter to point at your new command, e.g. /bin/bash. You may also set the "Args" parameter to pass arguments to the command.

Restart the docker service (note this will stop all running containers):

service docker restart

List your containers and make sure the command has changed:

docker ps -a

Start the container and attach to it, you should now be in your shell!

docker start -ai mad_brattain

Worked on Fedora 22 using Docker 1.7.1.

NOTE: If your shell is not interactive (e.g. you did not create the original container with -it option), you can instead change the command to "/bin/sleep 600" or "/bin/tail -f /dev/null" to give you enough time to do "docker exec -it CONTID /bin/bash" as another way of getting a shell.

NOTE2: Newer versions of docker have config.v2.json, where you will need to change either Entrypoint or Cmd (thanks user60561).

Detect element content changes with jQuery

Often a simple and effective way to achieve this is to keep track of when and where you are modifying the DOM.

You can do this by creating one central function that is always responsible for modifying the DOM. You then do whatever cleanup you need on the modified element from within this function.

In a recent application, I didn't need immediate action so I used a callback for the handly load() function, to add a class to any modified elements and then updated all modified elements every few seconds with a setInterval timer.

$($location).load("my URL", "", $location.addClass("dommodified"));

Then you can handle it however you want - e.g.

setInterval("handlemodifiedstuff();", 3000); 
function handlemodifiedstuff()
{
    $(".dommodified").each(function(){/* Do stuff with $(this) */});
}

UTC Date/Time String to Timezone

PHP's DateTime object is pretty flexible.

$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

So I'm not entirely sure why this works, but it saves an image with my plot:

dtf = pd.DataFrame.from_records(d,columns=h)
dtf2.plot()
fig = plt.gcf()
fig.savefig('output.png')

I'm guessing that the last snippet from my original post saved blank because the figure was never getting the axes generated by pandas. With the above code, the figure object is returned from some magic global state by the gcf() call (get current figure), which automagically bakes in axes plotted in the line above.

How to add content to html body using JS?

Working demo:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
onload = function(){
var divg = document.createElement("div");
divg.appendChild(document.createTextNode("New DIV"));
document.body.appendChild(divg);
};
</script>
</head>
<body>

</body>
</html>

What is the hamburger menu icon called and the three vertical dots icon called?

Not an official name per se, but I've heard vertical ellipsis referred to as "snowman" in SAS community.

jQuery bind/unbind 'scroll' event on $(window)

Note that the answers that suggest using unbind() are now out of date as that method has been deprecated and will be removed in future versions of jQuery.

As of jQuery 3.0, .unbind() has been deprecated. It was superseded by the .off() method since jQuery 1.7, so its use was already discouraged.

Instead, you should now use off():

$(window).off('scroll');

How to prevent tensorflow from allocating the totality of a GPU memory?

For TensorFlow 2.0 and 2.1 (docs):

import tensorflow as tf
tf.config.gpu.set_per_process_memory_growth(True)

For TensorFlow 2.2+ (docs):

import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
  tf.config.experimental.set_memory_growth(gpu, True)

The docs also list some more methods:

  • Set environment variable TF_FORCE_GPU_ALLOW_GROWTH to true.
  • Use tf.config.experimental.set_virtual_device_configuration to set a hard limit on a Virtual GPU device.

Html table with button on each row

Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.

<script type="text/javascript">

function handleClick(evt) {
  var node = evt.target || evt.srcElement;
  if (node.name == 'edit') {
    node.value = "Modify";
  }
}

</script>

<table id="table1" border="1" onclick="handleClick(event);">
    <thead>
      <tr>
          <th>Select
    </thead>
    <tbody>
       <tr> 
           <td>
               <form name="f1" action="#" >
                <input id="edit1" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f2" action="#" >
                <input id="edit2" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f3" action="#" >
                <input id="edit3" type="submit" name="edit" value="Edit">
               </form>

   </tbody>
</table>

Can we update primary key values of a table?

Primary key attributes are just as updateable as any other attributes of a table. Stability is often a desirable property of a key but definitely not an absolute requirement. If it makes sense from a business perpective to update a key then there's no fundamental reason why you shouldn't.

Read an Excel file directly from a R script

EDIT 2015-October: As others have commented here the openxlsx and readxl packages are by far faster than the xlsx package and actually manage to open larger Excel files (>1500 rows & > 120 columns). @MichaelChirico demonstrates that readxl is better when speed is preferred and openxlsx replaces the functionality provided by the xlsx package. If you are looking for a package to read, write, and modify Excel files in 2015, pick the openxlsx instead of xlsx.

Pre-2015: I have used xlsxpackage. It changed my workflow with Excel and R. No more annoying pop-ups asking, if I am sure that I want to save my Excel sheet in .txt format. The package also writes Excel files.

However, I find read.xlsx function slow, when opening large Excel files. read.xlsx2 function is considerably faster, but does not quess the vector class of data.frame columns. You have to use colClasses command to specify desired column classes, if you use read.xlsx2 function. Here is a practical example:

read.xlsx("filename.xlsx", 1) reads your file and makes the data.frame column classes nearly useful, but is very slow for large data sets. Works also for .xls files.

read.xlsx2("filename.xlsx", 1) is faster, but you will have to define column classes manually. A shortcut is to run the command twice (see the example below). character specification converts your columns to factors. Use Dateand POSIXct options for time.

coln <- function(x){y <- rbind(seq(1,ncol(x))); colnames(y) <- colnames(x)
rownames(y) <- "col.number"; return(y)} # A function to see column numbers

data <- read.xlsx2("filename.xlsx", 1) # Open the file 

coln(data)    # Check the column numbers you want to have as factors

x <- 3 # Say you want columns 1-3 as factors, the rest numeric

data <- read.xlsx2("filename.xlsx", 1, colClasses= c(rep("character", x),
rep("numeric", ncol(data)-x+1)))

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Another option would be using flexbox.

While it's not supported by IE8 and IE9, you could consider:

  • Not minding about those old IE versions
  • Providing a fallback
  • Using a polyfill

Despite some additional browser-specific style prefixing would be necessary for full cross-browser support, you can see the basic usage either on this fiddle and on the following snippet:

_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
html body {_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
  width: 100%;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
    background-color: #4C4;_x000D_
    min-height: 50px;_x000D_
    width: 100%;_x000D_
}_x000D_
footer {_x000D_
    background-color: #4C4;_x000D_
    min-height: 30px;_x000D_
    width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
_x000D_
_x000D_

java Compare two dates

You equals(Object o) comparison is correct.

Yet, you should use after(Date d) and before(Date d) for date comparison.

How to get ip address of a server on Centos 7 in bash

Run this command to show ip4 and ip6:

ifconfig eth0 | grep inet | awk '{print $2}' | cut -d/ -f1

Updating and committing only a file's permissions using git version control

By default, git will update execute file permissions if you change them. It will not change or track any other permissions.

If you don't see any changes when modifying execute permission, you probably have a configuration in git which ignore file mode.

Look into your project, in the .git folder for the config file and you should see something like this:

[core]
    filemode = false

You can either change it to true in your favorite text editor, or run:

git config core.filemode true

Then, you should be able to commit normally your files. It will only commit the permission changes.

Split string in JavaScript and detect line break

You should try detect the first line.

Then the:

if(n == 0){
  line = words[n]+"\n";
}

I'm not sure, but maybe it helps.

Fast query runs slow in SSRS

Aside from the parameter-sniffing issue, I've found that SSRS is generally slower at client side processing than (in my case) Crystal reports. The SSRS engine just doesn't seem as capable when it has a lot of rows to locally filter or aggregate. Granted, these are result set design problems which can frequently be addressed (though not always if the details are required for drilldown) but the more um...mature...reporting engine is more forgiving.

Why is it bad practice to call System.gc()?

The reason everyone always says to avoid System.gc() is that it is a pretty good indicator of fundamentally broken code. Any code that depends on it for correctness is certainly broken; any that rely on it for performance are most likely broken.

You don't know what sort of garbage collector you are running under. There are certainly some that do not "stop the world" as you assert, but some JVMs aren't that smart or for various reasons (perhaps they are on a phone?) don't do it. You don't know what it's going to do.

Also, it's not guaranteed to do anything. The JVM may just entirely ignore your request.

The combination of "you don't know what it will do," "you don't know if it will even help," and "you shouldn't need to call it anyway" are why people are so forceful in saying that generally you shouldn't call it. I think it's a case of "if you need to ask whether you should be using this, you shouldn't"


EDIT to address a few concerns from the other thread:

After reading the thread you linked, there's a few more things I'd like to point out. First, someone suggested that calling gc() may return memory to the system. That's certainly not necessarily true - the Java heap itself grows independently of Java allocations.

As in, the JVM will hold memory (many tens of megabytes) and grow the heap as necessary. It doesn't necessarily return that memory to the system even when you free Java objects; it is perfectly free to hold on to the allocated memory to use for future Java allocations.

To show that it's possible that System.gc() does nothing, view:

http://bugs.sun.com/view_bug.do?bug_id=6668279

and in particular that there's a -XX:DisableExplicitGC VM option.

How can I convert a PFX certificate file for use with Apache on a linux server?

With OpenSSL you can convert pfx to Apache compatible format with next commands:

openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes  -out domain.key   

First command extracts public key to domain.cer.
Second command extracts private key to domain.key.

Update your Apache configuration file with:

<VirtualHost 192.168.0.1:443>
 ...
 SSLEngine on
 SSLCertificateFile /path/to/domain.cer
 SSLCertificateKeyFile /path/to/domain.key
 ...
</VirtualHost>

convert string to number node.js

Using parseInt() is a bad idea mainly because it never fails. Also because some results can be unexpected, like in the case of INFINITY.
Below is the function for handling unexpected behaviour.

function cleanInt(x) {
    x = Number(x);
    return x >= 0 ? Math.floor(x) : Math.ceil(x);
}

See results of below test cases.

console.log("CleanInt: ", cleanInt('xyz'), " ParseInt: ", parseInt('xyz'));
console.log("CleanInt: ", cleanInt('123abc'), " ParseInt: ", parseInt('123abc'));
console.log("CleanInt: ", cleanInt('234'), " ParseInt: ", parseInt('234'));
console.log("CleanInt: ", cleanInt('-679'), " ParseInt: ", parseInt('-679'));
console.log("CleanInt: ", cleanInt('897.0998'), " ParseInt: ", parseInt('897.0998'));
console.log("CleanInt: ", cleanInt('Infinity'), " ParseInt: ", parseInt('Infinity'));

result:

CleanInt:  NaN  ParseInt:  NaN
CleanInt:  NaN  ParseInt:  123
CleanInt:  234  ParseInt:  234
CleanInt:  -679  ParseInt:  -679
CleanInt:  897  ParseInt:  897
CleanInt:  Infinity  ParseInt:  NaN

How to center an iframe horizontally?

Here I have put snippet for all of you who are suffering to make iframe or image in center of the screen horizontally. Give me THUMBS UP VOTE if you like.?.

style > img & iframe > this is your tag name so change that if you're want any other tag in center

_x000D_
_x000D_
<html >_x000D_
 <head> _x000D_
            <style type=text/css>_x000D_
            div{}_x000D_
            img{_x000D_
                 margin: 0 auto;_x000D_
          display:block;_x000D_
          }_x000D_
  iframe{ _x000D_
  margin: 0 auto;_x000D_
  display:block;_x000D_
  }_x000D_
    _x000D_
            </style>_x000D_
</head>_x000D_
 <body >_x000D_
           _x000D_
   <iframe src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4" width="320" height="180" frameborder="0" allowfullscreen="allowfullscreen"></iframe> _x000D_
   _x000D_
   <img src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg" width="320" height="180"  />_x000D_
            </body> _x000D_
            </html>
_x000D_
_x000D_
_x000D_

What is w3wp.exe?

An Internet Information Services (IIS) worker process is a windows process (w3wp.exe) which runs Web applications, and is responsible for handling requests sent to a Web Server for a specific application pool.

It is the worker process for IIS. Each application pool creates at least one instance of w3wp.exe and that is what actually processes requests in your application. It is not dangerous to attach to this, that is just a standard windows message.

Playing .mp3 and .wav in Java?

Using MP3 Decoder/player/converter Maven Dependency.

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class PlayAudio{

public static void main(String[] args) throws FileNotFoundException {

    try {
        FileInputStream fileInputStream = new FileInputStream("mp.mp3");
        Player player = new Player((fileInputStream));
        player.play();
        System.out.println("Song is playing");
        while(true){
            System.out.println(player.getPosition());
        }
    }catch (Exception e){
        System.out.println(e);
    }

  }

}

What is the proper use of an EventEmitter?

TL;DR:

No, don't subscribe manually to them, don't use them in services. Use them as is shown in the documentation only to emit events in components. Don't defeat angular's abstraction.

Answer:

No, you should not subscribe manually to it.

EventEmitter is an angular2 abstraction and its only purpose is to emit events in components. Quoting a comment from Rob Wormald

[...] EventEmitter is really an Angular abstraction, and should be used pretty much only for emitting custom Events in components. Otherwise, just use Rx as if it was any other library.

This is stated really clear in EventEmitter's documentation.

Use by directives and components to emit custom Events.

What's wrong about using it?

Angular2 will never guarantee us that EventEmitter will continue being an Observable. So that means refactoring our code if it changes. The only API we must access is its emit() method. We should never subscribe manually to an EventEmitter.

All the stated above is more clear in this Ward Bell's comment (recommended to read the article, and the answer to that comment). Quoting for reference

Do NOT count on EventEmitter continuing to be an Observable!

Do NOT count on those Observable operators being there in the future!

These will be deprecated soon and probably removed before release.

Use EventEmitter only for event binding between a child and parent component. Do not subscribe to it. Do not call any of those methods. Only call eve.emit()

His comment is in line with Rob's comment long time ago.

So, how to use it properly?

Simply use it to emit events from your component. Take a look a the following example.

@Component({
    selector : 'child',
    template : `
        <button (click)="sendNotification()">Notify my parent!</button>
    `
})
class Child {
    @Output() notifyParent: EventEmitter<any> = new EventEmitter();
    sendNotification() {
        this.notifyParent.emit('Some value to send to the parent');
    }
}

@Component({
    selector : 'parent',
    template : `
        <child (notifyParent)="getNotification($event)"></child>
    `
})
class Parent {
    getNotification(evt) {
        // Do something with the notification (evt) sent by the child!
    }
}

How not to use it?

class MyService {
    @Output() myServiceEvent : EventEmitter<any> = new EventEmitter();
}

Stop right there... you're already wrong...

Hopefully these two simple examples will clarify EventEmitter's proper usage.

Const in JavaScript: when to use it and is it necessary?

2017 Update

This answer still receives a lot of attention. It's worth noting that this answer was posted back at the beginning of 2014 and a lot has changed since then. support is now the norm. All modern browsers now support const so it should be pretty safe to use without any problems.


Original Answer from 2014

Despite having fairly decent browser support, I'd avoid using it for now. From MDN's article on const:

The current implementation of const is a Mozilla-specific extension and is not part of ECMAScript 5. It is supported in Firefox & Chrome (V8). As of Safari 5.1.7 and Opera 12.00, if you define a variable with const in these browsers, you can still change its value later. It is not supported in Internet Explorer 6-10, but is included in Internet Explorer 11. The const keyword currently declares the constant in the function scope (like variables declared with var).

It then goes on to say:

const is going to be defined by ECMAScript 6, but with different semantics. Similar to variables declared with the let statement, constants declared with const will be block-scoped.

If you do use const you're going to have to add in a workaround to support slightly older browsers.

Search in lists of lists by given index

What about:

list =[ ['a','b'], ['a','c'], ['b','d'] ]
search = 'b'

filter(lambda x:x[1]==search,list)

This will return each list in the list of lists with the second element being equal to search.

Is 'bool' a basic datatype in C++?

bool is a fundamental datatype in C++. Converting true to an integer type will yield 1, and converting false will yield 0 (4.5/4 and 4.7/4). In C, until C99, there was no bool datatype, and people did stuff like

enum bool {
    false, true
};

So did the Windows API. Starting with C99, we have _Bool as a basic data type. Including stdbool.h will typedef #define that to bool and provide the constants true and false. They didn't make bool a basic data-type (and thus a keyword) because of compatibility issues with existing code.

AppStore - App status is ready for sale, but not in app store

I published an update to my app yesterday noon(I have selected Manual release instead of Automatic) and Today early morning App store review was completed and after I release the build manually, the App shows Ready for sale in iTunesConect immediately. After 45mins I got the update on the App store.

What are all the possible values for HTTP "Content-Type" header?

I would aim at covering a subset of possible "Content-type" values, you question seems to focus on identifying known content types.

@Jeroen RFC 1341 reference is great, but for an fairly exhaustive list IANA keeps a web page of officially registered media types here.

Select unique or distinct values from a list in UNIX shell script

Pipe them through sort and uniq. This removes all duplicates.

uniq -d gives only the duplicates, uniq -u gives only the unique ones (strips duplicates).

How to automatically import data from uploaded CSV or XLS file into Google Sheets

You can programmatically import data from a csv file in your Drive into an existing Google Sheet using Google Apps Script, replacing/appending data as needed.

Below is some sample code. It assumes that: a) you have a designated folder in your Drive where the CSV file is saved/uploaded to; b) the CSV file is named "report.csv" and the data in it comma-delimited; and c) the CSV data is imported into a designated spreadsheet. See comments in code for further details.

function importData() {
  var fSource = DriveApp.getFolderById(reports_folder_id); // reports_folder_id = id of folder where csv reports are saved
  var fi = fSource.getFilesByName('report.csv'); // latest report file
  var ss = SpreadsheetApp.openById(data_sheet_id); // data_sheet_id = id of spreadsheet that holds the data to be updated with new report data

  if ( fi.hasNext() ) { // proceed if "report.csv" file exists in the reports folder
    var file = fi.next();
    var csv = file.getBlob().getDataAsString();
    var csvData = CSVToArray(csv); // see below for CSVToArray function
    var newsheet = ss.insertSheet('NEWDATA'); // create a 'NEWDATA' sheet to store imported data
    // loop through csv data array and insert (append) as rows into 'NEWDATA' sheet
    for ( var i=0, lenCsv=csvData.length; i<lenCsv; i++ ) {
      newsheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
    }
    /*
    ** report data is now in 'NEWDATA' sheet in the spreadsheet - process it as needed,
    ** then delete 'NEWDATA' sheet using ss.deleteSheet(newsheet)
    */
    // rename the report.csv file so it is not processed on next scheduled run
    file.setName("report-"+(new Date().toString())+".csv");
  }
};


// http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.

function CSVToArray( strData, strDelimiter ) {
  // Check to see if the delimiter is defined. If not,
  // then default to COMMA.
  strDelimiter = (strDelimiter || ",");

  // Create a regular expression to parse the CSV values.
  var objPattern = new RegExp(
    (
      // Delimiters.
      "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

      // Quoted fields.
      "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

      // Standard fields.
      "([^\"\\" + strDelimiter + "\\r\\n]*))"
    ),
    "gi"
  );

  // Create an array to hold our data. Give the array
  // a default empty first row.
  var arrData = [[]];

  // Create an array to hold our individual pattern
  // matching groups.
  var arrMatches = null;

  // Keep looping over the regular expression matches
  // until we can no longer find a match.
  while (arrMatches = objPattern.exec( strData )){

    // Get the delimiter that was found.
    var strMatchedDelimiter = arrMatches[ 1 ];

    // Check to see if the given delimiter has a length
    // (is not the start of string) and if it matches
    // field delimiter. If id does not, then we know
    // that this delimiter is a row delimiter.
    if (
      strMatchedDelimiter.length &&
      (strMatchedDelimiter != strDelimiter)
    ){

      // Since we have reached a new row of data,
      // add an empty row to our data array.
      arrData.push( [] );

    }

    // Now that we have our delimiter out of the way,
    // let's check to see which kind of value we
    // captured (quoted or unquoted).
    if (arrMatches[ 2 ]){

      // We found a quoted value. When we capture
      // this value, unescape any double quotes.
      var strMatchedValue = arrMatches[ 2 ].replace(
        new RegExp( "\"\"", "g" ),
        "\""
      );

    } else {

      // We found a non-quoted value.
      var strMatchedValue = arrMatches[ 3 ];

    }

    // Now that we have our value string, let's add
    // it to the data array.
    arrData[ arrData.length - 1 ].push( strMatchedValue );
  }

  // Return the parsed data.
  return( arrData );
};

You can then create time-driven trigger in your script project to run importData() function on a regular basis (e.g. every night at 1AM), so all you have to do is put new report.csv file into the designated Drive folder, and it will be automatically processed on next scheduled run.

If you absolutely MUST work with Excel files instead of CSV, then you can use this code below. For it to work you must enable Drive API in Advanced Google Services in your script and in Developers Console (see How to Enable Advanced Services for details).

/**
 * Convert Excel file to Sheets
 * @param {Blob} excelFile The Excel file blob data; Required
 * @param {String} filename File name on uploading drive; Required
 * @param {Array} arrParents Array of folder ids to put converted file in; Optional, will default to Drive root folder
 * @return {Spreadsheet} Converted Google Spreadsheet instance
 **/
function convertExcel2Sheets(excelFile, filename, arrParents) {

  var parents  = arrParents || []; // check if optional arrParents argument was provided, default to empty array if not
  if ( !parents.isArray ) parents = []; // make sure parents is an array, reset to empty array if not

  // Parameters for Drive API Simple Upload request (see https://developers.google.com/drive/web/manage-uploads#simple)
  var uploadParams = {
    method:'post',
    contentType: 'application/vnd.ms-excel', // works for both .xls and .xlsx files
    contentLength: excelFile.getBytes().length,
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    payload: excelFile.getBytes()
  };

  // Upload file to Drive root folder and convert to Sheets
  var uploadResponse = UrlFetchApp.fetch('https://www.googleapis.com/upload/drive/v2/files/?uploadType=media&convert=true', uploadParams);

  // Parse upload&convert response data (need this to be able to get id of converted sheet)
  var fileDataResponse = JSON.parse(uploadResponse.getContentText());

  // Create payload (body) data for updating converted file's name and parent folder(s)
  var payloadData = {
    title: filename, 
    parents: []
  };
  if ( parents.length ) { // Add provided parent folder(s) id(s) to payloadData, if any
    for ( var i=0; i<parents.length; i++ ) {
      try {
        var folder = DriveApp.getFolderById(parents[i]); // check that this folder id exists in drive and user can write to it
        payloadData.parents.push({id: parents[i]});
      }
      catch(e){} // fail silently if no such folder id exists in Drive
    }
  }
  // Parameters for Drive API File Update request (see https://developers.google.com/drive/v2/reference/files/update)
  var updateParams = {
    method:'put',
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    contentType: 'application/json',
    payload: JSON.stringify(payloadData)
  };

  // Update metadata (filename and parent folder(s)) of converted sheet
  UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files/'+fileDataResponse.id, updateParams);

  return SpreadsheetApp.openById(fileDataResponse.id);
}

/**
 * Sample use of convertExcel2Sheets() for testing
 **/
 function testConvertExcel2Sheets() {
  var xlsId = "0B9**************OFE"; // ID of Excel file to convert
  var xlsFile = DriveApp.getFileById(xlsId); // File instance of Excel file
  var xlsBlob = xlsFile.getBlob(); // Blob source of Excel file for conversion
  var xlsFilename = xlsFile.getName(); // File name to give to converted file; defaults to same as source file
  var destFolders = []; // array of IDs of Drive folders to put converted file in; empty array = root folder
  var ss = convertExcel2Sheets(xlsBlob, xlsFilename, destFolders);
  Logger.log(ss.getId());
}

The above code is also available as a gist here.

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

how to add picasso library in android studio

Add this to your dependencies in build.gradle:

enter image description here

dependencies {
 implementation 'com.squareup.picasso:picasso:2.71828'
  ...

The latest version can be found here

Make sure you are connected to the Internet. When you sync Gradle, all related files will be added to your project

Take a look at your libraries folder, the library you just added should be in there.

enter image description here

Oracle - What TNS Names file am I using?

Shouldn't it always be "$ORACLE_ HOME/network/admin/tnsnames.ora"? Then you can just do "echo $oracle_ home" or the *nix equivalent.

@Pete Holberton You are entirely correct. Which reminds me, there's another monkey wrench in the works called TWO_ TASK

According http://www.orafaq.com/wiki/TNS_ADMIN
TNS_ADMIN is an environment variable that points to the directory where the SQL*Net configuration files (like sqlnet.ora and tnsnames.ora) are located.

How to get text in QlineEdit when QpushButton is pressed in a string?

My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.

Here are some PyQt tutorials to help get you on the right track. The first one in the list is where you should start.

A good guide for figuring out what methods are available for specific classes is the PyQt4 Class Reference. In this case you would look up QLineEdit and see the there is a text method.

To answer your specific question:

To make your GUI elements available to the rest of the object, preface them with self.

import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect") 

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print shost


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

How to randomize (or permute) a dataframe rowwise and columnwise?

If the goal is to randomly shuffle each column, some of the above answers don't work since the columns are shuffled jointly (this preserves inter-column correlations). Others require installing a package. Yet a one-liner exist:

df2 = lapply(df1, function(x) { sample(x) })

How many threads is too many?

I think this is a bit of a dodge to your question, but why not fork them into processes? My understanding of networking (from the hazy days of yore, I don't really code networks at all) was that each incoming connection can be handled as a separate process, because then if someone does something nasty in your process, it doesn't nuke the entire program.

Find Number of CPUs and Cores per CPU using Command Prompt

You can use the environment variable NUMBER_OF_PROCESSORS for the total number of processors:

echo %NUMBER_OF_PROCESSORS%

Youtube iframe wmode issue

Try adding ?wmode=opaque to the URL or &wmode=opaque if there already is a parameter.

If it doesn't work try this instead, &amp;wmode=transparent which will work in IE browser as well.

How to convert JTextField to String and String to JTextField?

how to convert JTextField to string and string to JTextField in java

If you mean how to get and set String from jTextField then you can use following methods:

String str = jTextField.getText() // get string from jtextfield

and

jTextField.setText(str)  // set string to jtextfield
//or
new JTextField(str)     // set string to jtextfield

You should check JavaDoc for JTextField

How To fix white screen on app Start up?

enter image description here

Like you tube.. initially they show icon screen instead of white screen. And after 2 seconds shows home screen.

first create an XML drawable in res/drawable.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@color/gray"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher"/>
    </item>

</layer-list>

Next, you will set this as your splash activity’s background in the theme. Navigate to your styles.xml file and add a new theme for your splash activity

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

    <style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:windowBackground">@drawable/background_splash</item>
    </style>

</resources>

In your new SplashTheme, set the window background attribute to your XML drawable. Configure this as your splash activity’s theme in your AndroidManifest.xml:

<activity
    android:name=".SplashActivity"
    android:theme="@style/SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

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

This link gives what you want. step by step procedure. https://www.bignerdranch.com/blog/splash-screens-the-right-way/

UPDATE:

The layer-list can be even simpler like this (which also accepts vector drawables for the centered logo, unlike the <bitmap> tag):

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Background color -->
    <item android:drawable="@color/gray"/>

    <!-- Logo at the center of the screen -->
    <item
        android:drawable="@mipmap/ic_launcher"
        android:gravity="center"/>
</layer-list>

Write variable to file, including name

the repr function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.

>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'one': 1}"

writing to a file is pretty standard stuff, like any other file write:

f = open( 'file.py', 'w' )
f.write( 'dict = ' + repr(dict) + '\n' )
f.close()

How to do "If Clicked Else .."

This is all you need: http://api.jquery.com/click/

Having an "else" doesn't apply in this scenario, else would mean "did not click", in which case you just wouldn't do anything.

How to create a timer using tkinter?

Tkinter root windows have a method called after which can be used to schedule a function to be called after a given period of time. If that function itself calls after you've set up an automatically recurring event.

Here is a working example:

# for python 3.x use 'tkinter' rather than 'Tkinter'
import Tkinter as tk
import time

class App():
    def __init__(self):
        self.root = tk.Tk()
        self.label = tk.Label(text="")
        self.label.pack()
        self.update_clock()
        self.root.mainloop()

    def update_clock(self):
        now = time.strftime("%H:%M:%S")
        self.label.configure(text=now)
        self.root.after(1000, self.update_clock)

app=App()

Bear in mind that after doesn't guarantee the function will run exactly on time. It only schedules the job to be run after a given amount of time. It the app is busy there may be a delay before it is called since Tkinter is single-threaded. The delay is typically measured in microseconds.

What is the worst real-world macros/pre-processor abuse you've ever come across?

The driver code for an ASIC I used about 10 years ago had a lot of sections that looked like:

int foo(state_t *state) {
    int a, b, rval;

    $
    if (state->thing == whatever) {
        $
        do_whatever(state);
    }
    // more code

    $
    return rval;
}

After a lot of head scratching we finally found the definition:

#if DEBUG
#define $ dolog("%s %d", __FILE__, __LINE__);
#else
#define $
#endif

This was hard to find, because none of the source files that used it had any include files. There was a file called top.c source file that looked like:

#include <namechanged.h>
#include <foo.c>
#include <bar.c>
#include <baz.c>

Sure enough, this was the only file referenced in the Makefile. Whenever you changed anything, you had to recompile everything. This was "to make the code faster".

CSS: Position loading indicator in the center of the screen

change the position absolute of div busy to fixed

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.

Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).

How to use PHP's password_hash to hash and verify passwords

There is a distinct lack of discussion on backwards and forwards compatibility that is built in to PHP's password functions. Notably:

  1. Backwards Compatibility: The password functions are essentially a well-written wrapper around crypt(), and are inherently backwards-compatible with crypt()-format hashes, even if they use obsolete and/or insecure hash algorithms.
  2. Forwards Compatibilty: Inserting password_needs_rehash() and a bit of logic into your authentication workflow can keep you your hashes up to date with current and future algorithms with potentially zero future changes to the workflow. Note: Any string that does not match the specified algorithm will be flagged for needing a rehash, including non-crypt-compatible hashes.

Eg:

class FakeDB {
    public function __call($name, $args) {
        printf("%s::%s(%s)\n", __CLASS__, $name, json_encode($args));
        return $this;
    }
}

class MyAuth {
    protected $dbh;
    protected $fakeUsers = [
        // old crypt-md5 format
        1 => ['password' => '$1$AVbfJOzY$oIHHCHlD76Aw1xmjfTpm5.'],
        // old salted md5 format
        2 => ['password' => '3858f62230ac3c915f300c664312c63f', 'salt' => 'bar'],
        // current bcrypt format
        3 => ['password' => '$2y$10$3eUn9Rnf04DR.aj8R3WbHuBO9EdoceH9uKf6vMiD7tz766rMNOyTO']
    ];

    public function __construct($dbh) {
        $this->dbh = $dbh;
    }

    protected function getuser($id) {
        // just pretend these are coming from the DB
        return $this->fakeUsers[$id];
    }

    public function authUser($id, $password) {
        $userInfo = $this->getUser($id);

        // Do you have old, turbo-legacy, non-crypt hashes?
        if( strpos( $userInfo['password'], '$' ) !== 0 ) {
            printf("%s::legacy_hash\n", __METHOD__);
            $res = $userInfo['password'] === md5($password . $userInfo['salt']);
        } else {
            printf("%s::password_verify\n", __METHOD__);
            $res = password_verify($password, $userInfo['password']);
        }

        // once we've passed validation we can check if the hash needs updating.
        if( $res && password_needs_rehash($userInfo['password'], PASSWORD_DEFAULT) ) {
            printf("%s::rehash\n", __METHOD__);
            $stmt = $this->dbh->prepare('UPDATE users SET pass = ? WHERE user_id = ?');
            $stmt->execute([password_hash($password, PASSWORD_DEFAULT), $id]);
        }

        return $res;
    }
}

$auth = new MyAuth(new FakeDB());

for( $i=1; $i<=3; $i++) {
    var_dump($auth->authuser($i, 'foo'));
    echo PHP_EOL;
}

Output:

MyAuth::authUser::password_verify
MyAuth::authUser::rehash
FakeDB::prepare(["UPDATE users SET pass = ? WHERE user_id = ?"])
FakeDB::execute([["$2y$10$zNjPwqQX\/RxjHiwkeUEzwOpkucNw49yN4jjiRY70viZpAx5x69kv.",1]])
bool(true)

MyAuth::authUser::legacy_hash
MyAuth::authUser::rehash
FakeDB::prepare(["UPDATE users SET pass = ? WHERE user_id = ?"])
FakeDB::execute([["$2y$10$VRTu4pgIkGUvilTDRTXYeOQSEYqe2GjsPoWvDUeYdV2x\/\/StjZYHu",2]])
bool(true)

MyAuth::authUser::password_verify
bool(true)

As a final note, given that you can only re-hash a user's password on login you should consider "sunsetting" insecure legacy hashes to protect your users. By this I mean that after a certain grace period you remove all insecure [eg: bare MD5/SHA/otherwise weak] hashes and have your users rely on your application's password reset mechanisms.

How to call one shell script from another shell script?

Just add in a line whatever you would have typed in a terminal to execute the script!
e.g.:

#!bin/bash
./myscript.sh &

if the script to be executed is not in same directory, just use the complete path of the script.
e.g.:`/home/user/script-directory/./myscript.sh &

' << ' operator in verilog

<< is the left-shift operator, as it is in many other languages.

Here RAM_DEPTH will be 1 left-shifted by 8 bits, which is equivalent to 2^8, or 256.

How can I represent a range in Java?

import java.util.Arrays;

class Soft{
    public static void main(String[] args){
        int[] nums=range(9, 12);
        System.out.println(Arrays.toString(nums));
    }
    static int[] range(int low, int high){
        int[] a=new int[high-low];
        for(int i=0,j=low;i<high-low;i++,j++){
            a[i]=j;
        }
        return a;

    }
}

My code is similar to Python`s range :)

Query to display all tablespaces in a database and datafiles

SELECT a.file_name,
       substr(A.tablespace_name,1,14) tablespace_name,
       trunc(decode(A.autoextensible,'YES',A.MAXSIZE-A.bytes+b.free,'NO',b.free)/1024/1024) free_mb,
       trunc(a.bytes/1024/1024) allocated_mb,
       trunc(A.MAXSIZE/1024/1024) capacity,
       a.autoextensible ae
FROM (
     SELECT file_id, file_name,
            tablespace_name,
            autoextensible,
            bytes,
            decode(autoextensible,'YES',maxbytes,bytes) maxsize
     FROM   dba_data_files
     GROUP BY file_id, file_name,
              tablespace_name,
              autoextensible,
              bytes,
              decode(autoextensible,'YES',maxbytes,bytes)
     ) a,
     (SELECT file_id,
             tablespace_name,
             sum(bytes) free
      FROM   dba_free_space
      GROUP BY file_id,
               tablespace_name
      ) b
WHERE a.file_id=b.file_id(+)
AND A.tablespace_name=b.tablespace_name(+)
ORDER BY A.tablespace_name ASC; 

Calculating distance between two points, using latitude longitude?

Note: this solution only works for short distances.

I tried to use dommer's posted formula for an application and found it did well for long distances but in my data I was using all very short distances, and dommer's post did very poorly. I needed speed, and the more complex geo calcs worked well but were too slow. So, in the case that you need speed and all the calculations you're making are short (maybe < 100m or so). I found this little approximation to work great. it assumes the world is flat mind you, so don't use it for long distances, it works by approximating the distance of a single Latitude and Longitude at the given Latitude and returning the Pythagorean distance in meters.

public class FlatEarthDist {
    //returns distance in meters
    public static double distance(double lat1, double lng1, 
                                      double lat2, double lng2){
     double a = (lat1-lat2)*FlatEarthDist.distPerLat(lat1);
     double b = (lng1-lng2)*FlatEarthDist.distPerLng(lat1);
     return Math.sqrt(a*a+b*b);
    }

    private static double distPerLng(double lat){
      return 0.0003121092*Math.pow(lat, 4)
             +0.0101182384*Math.pow(lat, 3)
                 -17.2385140059*lat*lat
             +5.5485277537*lat+111301.967182595;
    }

    private static double distPerLat(double lat){
            return -0.000000487305676*Math.pow(lat, 4)
                -0.0033668574*Math.pow(lat, 3)
                +0.4601181791*lat*lat
                -1.4558127346*lat+110579.25662316;
    }
}

Trigger a keypress/keydown/keyup event in JS/jQuery?

Here's a vanilla js example to trigger any event:

function triggerEvent(el, type){
if ('createEvent' in document) {
        // modern browsers, IE9+
        var e = document.createEvent('HTMLEvents');
        e.initEvent(type, false, true);
        el.dispatchEvent(e);
    } else {
        // IE 8
        var e = document.createEventObject();
        e.eventType = type;
        el.fireEvent('on'+e.eventType, e);
    }
}

Is there a C# case insensitive equals operator?

Others answer are totally valid here, but somehow it takes some time to type StringComparison.OrdinalIgnoreCase and also using String.Compare.

I've coded simple String extension method, where you could specify if comparison is case sensitive or case senseless with boolean - see following answer:

https://stackoverflow.com/a/49208128/2338477

if block inside echo statement?

In sake of readability it should be something like

<?php 
  $countries = $myaddress->get_countries();
  foreach($countries as $value) {
    $selected ='';
    if($value=='United States') $selected ='selected="selected"'; 
    echo '<option value="'.$value.'"'.$selected.'>'.$value.'</option>';
  }
?>

desire to stuff EVERYTHING in a single line is a decease, man. Write distinctly.

But there is another way, a better one. There is no need to use echo at all. Learn to use templates. Prepare your data first, and display it only then ready.

Business logic part:

$countries = $myaddress->get_countries();
$selected_country = 1;    

Template part:

<? foreach($countries as $row): ?>
<option value="<?=$row['id']?>"<? if ($row['id']==$current_country):> "selected"><? endif ?>
  <?=$row['name']?>
</option>
<? endforeach ?>

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

1 : if you are interested only in the static block of the class , the loading the class only would do , and would execute static blocks then all you need is:

Class.forName("Somthing");

2 : if you are interested in loading the class , execute its static blocks and also want to access its its non static part , then you need an instance and then you need:

Class.forName("Somthing").newInstance();

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

My manifest does not reference any themes... it should not have to AFAIK

Sure it does. Nothing is going to magically apply Theme.Styled to an activity. You need to declare your activities -- or your whole application -- is using Theme.Styled, e.g., :

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.Styled">

How to Add Incremental Numbers to a New Column Using Pandas

df.insert(0, 'New_ID', range(880, 880 + len(df)))
df

enter image description here

reading text file with utf-8 encoding using java

I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));

while ((line = br.readLine()) != null) {

}

I hope this can help anyone who sees this post.

How to start new activity on button click

Create an intent to a ViewPerson activity and pass the PersonID (for a database lookup, for example).

Intent i = new Intent(getBaseContext(), ViewPerson.class);                      
i.putExtra("PersonID", personID);
startActivity(i);

Then in ViewPerson Activity, you can get the bundle of extra data, make sure it isn't null (in case if you sometimes don't pass data), then get the data.

Bundle extras = getIntent().getExtras();
if(extras !=null)
{
     personID = extras.getString("PersonID");
}

Now if you need to share data between two Activities, you can also have a Global Singleton.

public class YourApplication extends Application 
{     
     public SomeDataClass data = new SomeDataClass();
}

Then call it in any activity by:

YourApplication appState = ((YourApplication)this.getApplication());
appState.data.CallSomeFunctionHere(); // Do whatever you need to with data here.  Could be setter/getter or some other type of logic

How to parse unix timestamp to time.Time

You can directly use time.Unix function of time which converts the unix time stamp to UTC

package main

import (
  "fmt"
  "time"
)


func main() {
    unixTimeUTC:=time.Unix(1405544146, 0) //gives unix time stamp in utc 

    unitTimeInRFC3339 :=unixTimeUTC.Format(time.RFC3339) // converts utc time to RFC3339 format

    fmt.Println("unix time stamp in UTC :--->",unixTimeUTC)
    fmt.Println("unix time stamp in unitTimeInRFC3339 format :->",unitTimeInRFC3339)
}

Output

unix time stamp in UTC :---> 2014-07-16 20:55:46 +0000 UTC
unix time stamp in unitTimeInRFC3339 format :----> 2014-07-16T20:55:46Z

Check in Go Playground: https://play.golang.org/p/5FtRdnkxAd

Reverse order of foreach list items

If you don't mind destroying the array (or a temp copy of it) you can do:

$stack = array("orange", "banana", "apple", "raspberry");

while ($fruit = array_pop($stack)){
    echo $fruit . "\n<br>"; 
}

produces:

raspberry 
apple 
banana 
orange 

I think this solution reads cleaner than fiddling with an index and you are less likely to introduce index handling mistakes, but the problem with it is that your code will likely take slightly longer to run if you have to create a temporary copy of the array first. Fiddling with an index is likely to run faster, and it may also come in handy if you actually need to reference the index, as in:

$stack = array("orange", "banana", "apple", "raspberry");
$index = count($stack) - 1;
while($index > -1){
    echo $stack[$index] ." is in position ". $index . "\n<br>";
    $index--;
} 

But as you can see, you have to be very careful with the index...

Hidden TextArea

use

textarea{
  visibility:hidden;
}

Best way to store password in database

The best security practice is not to store the password at all (not even encrypted), but to store the salted hash (with a unique salt per password) of the encrypted password.

That way it is (practically) impossible to retrieve a plaintext password.

How to convert DataTable to class Object?

It is Vb.Net version:

Public Class Test
Public Property id As Integer
Public Property name As String
Public Property address As String
Public Property createdDate As Date

End Class

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim x As Date = Now

    Debug.WriteLine("Begin: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)

    Dim dt As New DataTable
    dt.Columns.Add("id")
    dt.Columns.Add("name")
    dt.Columns.Add("address")
    dt.Columns.Add("createdDate")

    For i As Integer = 0 To 100000
        dt.Rows.Add(i, "name - " & i, "address - " & i, DateAdd(DateInterval.Second, i, Now))
    Next

    Debug.WriteLine("Datatable created: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)


    Dim items As IList(Of Test) = dt.AsEnumerable().[Select](Function(row) New _
            Test With {
                        .id = row.Field(Of String)("id"),
                        .name = row.Field(Of String)("name"),
                        .address = row.Field(Of String)("address"),
                        .createdDate = row.Field(Of String)("createdDate")
                       }).ToList()

    Debug.WriteLine("List created: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)

    Debug.WriteLine("Complated")

End Sub

Change label text using JavaScript

Because the script will get executed first.. When the script will get executed, at that time controls are not getting loaded. So after loading controls you write a script.

It will work.

Spring Data JPA - "No Property Found for Type" Exception

In JPA a relationship has a single owner, and by using mappedByin your UserBoard class you tell that PinItem is the owner of that bidirectional relationship, and that the property in PinItem of the relationship is named board.

In your UserBoard class you do not have any fields/properties with the name board, but it has a property pinItemList, so you might try to use that property instead.

Linq order by, group by and order by each group?

Alternatively you can do like this :

     var _items = from a in StudentsGrades
                  group a by a.Name;

     foreach (var _itemGroup in _items)
     {
        foreach (var _item in _itemGroup.OrderBy(a=>a.grade))
        {
           ------------------------
           --------------------------
        }
     }

SQL Query to find the last day of the month

declare @date date=getdate()
declare @st_date date,@end_dt date
set @st_date=convert(varchar(5),year(@date))+'-'+convert(varchar(5),month(@date))+'-01'
set @end_dt=DATEADD(day,-1, DATEADD(month,1,@st_date))
---------**************--------------
select @st_date as [START DATE],@end_dt AS [END DATE]

String to Dictionary in Python

Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.

>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

I found it hard to decipher what is meant by "working directory of the VM". In my example, I was using the Java Service Wrapper program to execute a jar - the dump files were created in the directory where I had placed the wrapper program, e.g. c:\myapp\bin. The reason I discovered this is because the files can be quite large and they filled up the hard drive before I discovered their location.

Is there a git-merge --dry-run option?

If you want to fast forward from B to A, then you must make sure that git log B..A shows you nothing, i.e. A has nothing that B doesn't have. But even if B..A has something, you might still be able to merge without conflicts, so the above shows two things: that there will be a fast-forward, and thus you won't get a conflict.

How to enable mod_rewrite for Apache 2.2

New apache version has change in some way. If your apache version is 2.4 then you have to go to /etc/apache2/. There will be a file named apache2.conf. You have to edit that one(you should have root permission). Change directory text like this

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

Now restart apache.

service apache2 reload

Hope it works.

How can I extract audio from video with ffmpeg?

The command line is correct and works on a valid video file. I would make sure that you have installed the correct library to work with mp3, install lame o probe with another audio codec.

Usually

ffmpeg -formats

or

ffmpeg -codecs

would give sufficient information so that you know more.

Explaining the 'find -mtime' command

The POSIX specification for find says:

-mtimen The primary shall evaluate as true if the file modification time subtracted from the initialization time, divided by 86400 (with any remainder discarded), is n.

Interestingly, the description of find does not further specify 'initialization time'. It is probably, though, the time when find is initialized (run).

In the descriptions, wherever n is used as a primary argument, it shall be interpreted as a decimal integer optionally preceded by a plus ( '+' ) or minus-sign ( '-' ) sign, as follows:

+n More than n.
  n Exactly n.
-n Less than n.

At the given time (2014-09-01 00:53:44 -4:00, where I'm deducing that AST is Atlantic Standard Time, and therefore the time zone offset from UTC is -4:00 in ISO 8601 but +4:00 in ISO 9945 (POSIX), but it doesn't matter all that much):

1409547224 = 2014-09-01 00:53:44 -04:00
1409457540 = 2014-08-30 23:59:00 -04:00

so:

1409547224 - 1409457540 = 89684
89684 / 86400 = 1

Even if the 'seconds since the epoch' values are wrong, the relative values are correct (for some time zone somewhere in the world, they are correct).

The n value calculated for the 2014-08-30 log file therefore is exactly 1 (the calculation is done with integer arithmetic), and the +1 rejects it because it is strictly a > 1 comparison (and not >= 1).

Filter output in logcat by tagname

In case someone stumbles in on this like I did, you can filter on multiple tags by adding a comma in between, like so:

adb logcat -s "browser","webkit"

How to avoid .pyc files?

From "What’s New in Python 2.6 - Interpreter Changes":

Python can now be prevented from writing .pyc or .pyo files by supplying the -B switch to the Python interpreter, or by setting the PYTHONDONTWRITEBYTECODE environment variable before running the interpreter. This setting is available to Python programs as the sys.dont_write_bytecode variable, and Python code can change the value to modify the interpreter’s behaviour.

Update 2010-11-27: Python 3.2 addresses the issue of cluttering source folders with .pyc files by introducing a special __pycache__ subfolder, see What's New in Python 3.2 - PYC Repository Directories.

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

All (3) solotion is :

1- ctlr + C

2- in json file wreite a script that stop

"scripts": { "stop": "killall -SIGINT this-name-can-be-as-long-as-it-needs-to-be" },

*than in command write // npm stop //

3- Restart the pc

Apache: Restrict access to specific source IP inside virtual host

If you are using apache 2.2 inside your virtual host you should add following directive (mod_authz_host):

Order deny,allow
Deny from all
Allow from 10.0.0.1

You can even specify a subnet

Allow from 10.0.0

Apache 2.4 looks like a little different as configuration. Maybe better you specify which version of apache are you using.

Convert dictionary to list collection in C#

If you want to pass the Dictionary keys collection into one method argument.

List<string> lstKeys = Dict.Keys;
Methodname(lstKeys);
-------------------
void MethodName(List<String> lstkeys)
{
    `enter code here`
    //Do ur task
}

Jquery validation plugin - TypeError: $(...).validate is not a function

It looks like the JavaScript error your getting is probably being caused by

password: {
    required:true,
    rangelenght:[4.20]
},

As the [4.20] should be [4,20], which i'd guess is throwing off the validation code in additional-methods hence giving the type error's you posted.

Edit: As others have noted in the below comments rangelenght is also misspelled & jquery.validate.js library appears to be missing (assuming its not compiled in to one of your other assets)

Pandas: ValueError: cannot convert float NaN to integer

Also, even at the lastest versions of pandas if the column is object type you would have to convert into float first, something like:

df['column_name'].astype(np.float).astype("Int32")

NB: You have to go through numpy float first and then to nullable Int32, for some reason.

The size of the int if it's 32 or 64 depends on your variable, be aware you may loose some precision if your numbers are to big for the format.

How to sort in-place using the merge sort algorithm?

Including its "big result", this paper describes a couple of variants of in-place merge sort (PDF):

http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.22.5514&rep=rep1&type=pdf

In-place sorting with fewer moves

Jyrki Katajainen, Tomi A. Pasanen

It is shown that an array of n elements can be sorted using O(1) extra space, O(n log n / log log n) element moves, and n log2n + O(n log log n) comparisons. This is the first in-place sorting algorithm requiring o(n log n) moves in the worst case while guaranteeing O(n log n) comparisons, but due to the constant factors involved the algorithm is predominantly of theoretical interest.

I think this is relevant too. I have a printout of it lying around, passed on to me by a colleague, but I haven't read it. It seems to cover basic theory, but I'm not familiar enough with the topic to judge how comprehensively:

http://comjnl.oxfordjournals.org/cgi/content/abstract/38/8/681

Optimal Stable Merging

Antonios Symvonis

This paper shows how to stably merge two sequences A and B of sizes m and n, m = n, respectively, with O(m+n) assignments, O(mlog(n/m+1)) comparisons and using only a constant amount of additional space. This result matches all known lower bounds...

Django - after login, redirect user to his custom page --> mysite.com/username

Yes! In your settings.py define the following

LOGIN_REDIRECT_URL = '/your-path'

And have '/your-path' be a simple View that looks up self.request.user and does whatever logic it needs to return a HttpResponseRedirect object.

A better way might be to define a simple URL like '/simple' that does the lookup logic there. The URL looks more beautiful, saves you some work, etc.

Bootstrap - floating navbar button right

Create a separate ul.nav for just that list item and float that ul right.

jsFiddle

How can I force clients to refresh JavaScript files?

If you're generating the page that links to the JS files a simple solution is appending the file's last modification timestamp to the generated links.

This is very similar to Huppie's answer, but works in version control systems without keyword substitution. It's also better than append the current time, since that would prevent caching even when the file didn't change at all.

How to set NODE_ENV to production/development in OS X

heroku config:set NODE_ENV="production"

How do I print the content of httprequest request?

Rewrite @Juned Ahsan solution via stream in one line (headers are treated the same way):

public static String printRequest(HttpServletRequest req) {
    String params = StreamSupport.stream(
            ((Iterable<String>) () -> req.getParameterNames().asIterator()).spliterator(), false)
            .map(pName -> pName + '=' + req.getParameter(pName))
            .collect(Collectors.joining("&"));
    return req.getRequestURI() + '?' + params;
}

See also how to convert an iterator to a stream solution.

How to delete a workspace in Eclipse?

Click on the menu Window > Preferences and go to Workspaces like below :

| General
    | Startup and Shutdown
        | Workspaces

Select the workspace to delete and click on the Remove button.

Split data frame string column into multiple columns

To add to the options, you could also use my splitstackshape::cSplit function like this:

library(splitstackshape)
cSplit(before, "type", "_and_")
#    attr type_1 type_2
# 1:    1    foo    bar
# 2:   30    foo  bar_2
# 3:    4    foo    bar
# 4:    6    foo  bar_2

What is meaning of negative dbm in signal strength?

At ms end Rx lev ranges 0 to -120 dbm Mean antenna power which received at ms end alway less than 1mW.

Thats why it always -ve.

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

Make sure you import csv file using Pandas

import pandas as pd

condition = pd.isnull(data[i][j])

How to subtract X day from a Date object in Java?

Java 8 Time API:

Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);

What's the complete range for Chinese characters in Unicode?

The Unicode code blocks that the others answers gave certainly cover most of the Chinese Unicode characters, but check out some of these other code blocks, too.

CJK_UNIFIED_IDEOGRAPHS
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_E
CJK_COMPATIBILITY
CJK_COMPATIBILITY_FORMS
CJK_COMPATIBILITY_IDEOGRAPHS
CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT
CJK_RADICALS_SUPPLEMENT
CJK_STROKES
CJK_SYMBOLS_AND_PUNCTUATION
ENCLOSED_CJK_LETTERS_AND_MONTHS
ENCLOSED_IDEOGRAPHIC_SUPPLEMENT
KANGXI_RADICALS
IDEOGRAPHIC_DESCRIPTION_CHARACTERS

See my fuller discussion here. And this site is convenient for browsing Unicode.

What is an unsigned char?

unsigned char is the heart of all bit trickery. In almost ALL compiler for ALL platform an unsigned char is simply a byte and an unsigned integer of (usually) 8 bits that can be treated as a small integer or a pack of bits.

In addiction, as someone else has said, the standard doesn't define the sign of a char. so you have 3 distinct char types: char, signed char, unsigned char.

How do I get the list of keys in a Dictionary?

List<string> keyList = new List<string>(this.yourDictionary.Keys);

Accessing MVC's model property from Javascript

You could take your entire server-side model and turn it into a Javascript object by doing the following:

var model = @Html.Raw(Json.Encode(Model));

In your case if you just want the FloorPlanSettings object, simply pass the Encode method that property:

var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));

Flutter Circle Design

I would use a https://docs.flutter.io/flutter/widgets/Stack-class.html to be able to freely position widgets.

To create circles

  new BoxDecoration(
    color: effectiveBackgroundColor,
    image: backgroundImage != null
      ? new DecorationImage(image: backgroundImage, fit: BoxFit.cover)
      : null,
    shape: BoxShape.circle,
  ),

and https://docs.flutter.io/flutter/widgets/Transform/Transform.rotate.html to position the white dots.

CSS3 transitions inside jQuery .css()

Step 1) Remove the semi-colon, it's an object you're creating...

a(this).next().css({
    left       : c,
    transition : 'opacity 1s ease-in-out';
});

to

a(this).next().css({
    left       : c,
    transition : 'opacity 1s ease-in-out'
});

Step 2) Vendor-prefixes... no browsers use transition since it's the standard and this is an experimental feature even in the latest browsers:

a(this).next().css({
    left             : c,
    WebkitTransition : 'opacity 1s ease-in-out',
    MozTransition    : 'opacity 1s ease-in-out',
    MsTransition     : 'opacity 1s ease-in-out',
    OTransition      : 'opacity 1s ease-in-out',
    transition       : 'opacity 1s ease-in-out'
});

Here is a demo: http://jsfiddle.net/83FsJ/

Step 3) Better vendor-prefixes... Instead of adding tons of unnecessary CSS to elements (that will just be ignored by the browser) you can use jQuery to decide what vendor-prefix to use:

$('a').on('click', function () {
    var myTransition = ($.browser.webkit)  ? '-webkit-transition' :
                       ($.browser.mozilla) ? '-moz-transition' : 
                       ($.browser.msie)    ? '-ms-transition' :
                       ($.browser.opera)   ? '-o-transition' : 'transition',
        myCSSObj     = { opacity : 1 };

    myCSSObj[myTransition] = 'opacity 1s ease-in-out';
    $(this).next().css(myCSSObj);
});?

Here is a demo: http://jsfiddle.net/83FsJ/1/

Also note that if you specify in your transition declaration that the property to animate is opacity, setting a left property won't be animated.

How to add data into ManyToMany field?

There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

As that page states, you need to do:

my_obj.categories.add(fragmentCategory.objects.get(id=1))

or

my_obj.categories.create(name='val1')

Correlation between two vectors?

For correlations you can just use the corr function (statistics toolbox)

corr(A_1(:), A_2(:))

Note that you can also just use

corr(A_1, A_2)

But the linear indexing guarantees that your vectors don't need to be transposed.

get next and previous day with PHP

date('Y-m-d', strtotime('+1 day', strtotime($date)))

Should read

date('Y-m-d', strtotime(' +1 day'))

Update to answer question asked in comment about continuously changing the date.

<?php
$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$prev_date = date('Y-m-d', strtotime($date .' -1 day'));
$next_date = date('Y-m-d', strtotime($date .' +1 day'));
?>

<a href="?date=<?=$prev_date;?>">Previous</a>
<a href="?date=<?=$next_date;?>">Next</a>

This will increase and decrease the date by one from the date you are on at the time.

Clang vs GCC for my Linux Development project

EDIT:

The gcc guys really improved the diagnosis experience in gcc (ah competition). They created a wiki page to showcase it here. gcc 4.8 now has quite good diagnostics as well (gcc 4.9x added color support). Clang is still in the lead, but the gap is closing.


Original:

For students, I would unconditionally recommend Clang.

The performance in terms of generated code between gcc and Clang is now unclear (though I think that gcc 4.7 still has the lead, I haven't seen conclusive benchmarks yet), but for students to learn it does not really matter anyway.

On the other hand, Clang's extremely clear diagnostics are definitely easier for beginners to interpret.

Consider this simple snippet:

#include <string>
#include <iostream>

struct Student {
std::string surname;
std::string givenname;
}

std::ostream& operator<<(std::ostream& out, Student const& s) {
  return out << "{" << s.surname << ", " << s.givenname << "}";
}

int main() {
  Student me = { "Doe", "John" };
  std::cout << me << "\n";
}

You'll notice right away that the semi-colon is missing after the definition of the Student class, right :) ?

Well, gcc notices it too, after a fashion:

prog.cpp:9: error: expected initializer before ‘&’ token
prog.cpp: In function ‘int main()’:
prog.cpp:15: error: no match for ‘operator<<’ in ‘std::cout << me’
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:112: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (*)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:121: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ios<_CharT, _Traits>& (*)(std::basic_ios<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:131: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::ios_base& (*)(std::ios_base&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:169: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:173: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:177: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(bool) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:97: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:184: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:111: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:195: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:204: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long long int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:208: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:213: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(double) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:217: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(float) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:225: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long double) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:229: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(const void*) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:125: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_streambuf<_CharT, _Traits>*) [with _CharT = char, _Traits = std::char_traits<char>]

And Clang is not exactly starring here either, but still:

/tmp/webcompile/_25327_1.cc:9:6: error: redefinition of 'ostream' as different kind of symbol
std::ostream& operator<<(std::ostream& out, Student const& s) {
     ^
In file included from /tmp/webcompile/_25327_1.cc:1:
In file included from /usr/include/c++/4.3/string:49:
In file included from /usr/include/c++/4.3/bits/localefwd.h:47:
/usr/include/c++/4.3/iosfwd:134:33: note: previous definition is here
  typedef basic_ostream<char>           ostream;        ///< @isiosfwd
                                        ^
/tmp/webcompile/_25327_1.cc:9:13: error: expected ';' after top level declarator
std::ostream& operator<<(std::ostream& out, Student const& s) {
            ^
            ;
2 errors generated.

I purposefully choose an example which triggers an unclear error message (coming from an ambiguity in the grammar) rather than the typical "Oh my god Clang read my mind" examples. Still, we notice that Clang avoids the flood of errors. No need to scare students away.

How to easily get network path to the file you are working on?

Answer to my own question. The only way I have found that works consistently and instantaneously is to:

1) Create a link in my "Favorites" to the directory I use

2) Update the properties on that favorite to be an absolute path (\\ads\IT-DEPT-DFS\Data\MAILROOM)

3) When saving a new file, I navigate to that directory only via the Favorites directory created above (or you can use any Shortcut with an absolute path)

4) After saving, go to the File tab and the full path can be copied from the top of the Info (default) section

Explain the concept of a stack frame in a nutshell

A stack frame is a frame of data that gets pushed onto the stack. In the case of a call stack, a stack frame would represent a function call and its argument data.

If I remember correctly, the function return address is pushed onto the stack first, then the arguments and space for local variables. Together, they make the "frame," although this is likely architecture-dependent. The processor knows how many bytes are in each frame and moves the stack pointer accordingly as frames are pushed and popped off the stack.

EDIT:

There is a big difference between higher-level call stacks and the processor's call stack.

When we talk about a processor's call stack, we are talking about working with addresses and values at the byte/word level in assembly or machine code. There are "call stacks" when talking about higher-level languages, but they are a debugging/runtime tool managed by the runtime environment so that you can log what went wrong with your program (at a high level). At this level, things like line numbers and method and class names are often known. By the time the processor gets the code, it has absolutely no concept of these things.

How to cancel a Task in await?

One case which hasn't been covered is how to handle cancellation inside of an async method. Take for example a simple case where you need to upload some data to a service get it to calculate something and then return some results.

public async Task<Results> ProcessDataAsync(MyData data)
{
    var client = await GetClientAsync();
    await client.UploadDataAsync(data);
    await client.CalculateAsync();
    return await client.GetResultsAsync();
}

If you want to support cancellation then the easiest way would be to pass in a token and check if it has been cancelled between each async method call (or using ContinueWith). If they are very long running calls though you could be waiting a while to cancel. I created a little helper method to instead fail as soon as canceled.

public static class TaskExtensions
{
    public static async Task<T> WaitOrCancel<T>(this Task<T> task, CancellationToken token)
    {
        token.ThrowIfCancellationRequested();
        await Task.WhenAny(task, token.WhenCanceled());
        token.ThrowIfCancellationRequested();

        return await task;
    }

    public static Task WhenCanceled(this CancellationToken cancellationToken)
    {
        var tcs = new TaskCompletionSource<bool>();
        cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
        return tcs.Task;
    }
}

So to use it then just add .WaitOrCancel(token) to any async call:

public async Task<Results> ProcessDataAsync(MyData data, CancellationToken token)
{
    Client client;
    try
    {
        client = await GetClientAsync().WaitOrCancel(token);
        await client.UploadDataAsync(data).WaitOrCancel(token);
        await client.CalculateAsync().WaitOrCancel(token);
        return await client.GetResultsAsync().WaitOrCancel(token);
    }
    catch (OperationCanceledException)
    {
        if (client != null)
            await client.CancelAsync();
        throw;
    }
}

Note that this will not stop the Task you were waiting for and it will continue running. You'll need to use a different mechanism to stop it, such as the CancelAsync call in the example, or better yet pass in the same CancellationToken to the Task so that it can handle the cancellation eventually. Trying to abort the thread isn't recommended.

How do I use cx_freeze?

I'm really not sure what you're doing to get that error, it looks like you're trying to run cx_Freeze on its own, without arguments. So here is a short step-by-step guide on how to do it in windows (Your screenshot looks rather like the windows command line, so I'm assuming that's your platform)

  1. Write your setup.py file. Your script above looks correct so it should work, assuming that your script exists.

  2. Open the command line (Start -> Run -> "cmd")

  3. Go to the location of your setup.py file and run python setup.py build

Notes:

  1. There may be a problem with the name of your script. "Main.py" contains upper case letters, which might cause confusion since windows' file names are not case sensitive, but python is. My approach is to always use lower case for scripts to avoid any conflicts.

  2. Make sure that python is on your PATH (read http://docs.python.org/using/windows.html)1

  3. Make sure are are looking at the new cx_Freeze documentation. Google often seems to bring up the old docs.

How to display errors on laravel 4?

Maybe not on Laravel 4 this time, but on L5.2* I had similar issue:

I simply changed the ownership of the storage/logs directory to www-data with:

# chown -R www-data:www-data logs

PS: This is on Ubuntu 15 and with apache.

My logs directory now looks like:

drwxrwxr-x  2 www-data   www-data 4096 jaan  23 09:39 logs/

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

For those that are not overflowing but hiding by negative margin:

$('#element').height() + -parseInt($('#element').css("margin-top"));

(ugly but only one that works so far)

Dictionary of dictionaries in Python?

Using collections.defaultdict is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.

Here it's used twice: for the resulting dict, and for each of the values in the dict.

import collections

def aggregate_names(errors):
    result = collections.defaultdict(lambda: collections.defaultdict(list))
    for real_name, false_name, location in errors:
        result[real_name][false_name].append(location)
    return result

Combining this with your code:

dictionary = aggregate_names(previousFunction(string))

Or to test:

EXAMPLES = [
    ('Fred', 'Frad', 123),
    ('Jim', 'Jam', 100),
    ('Fred', 'Frod', 200),
    ('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)

How to use GNU Make on Windows?

I'm using GNU Make from the GnuWin32 project, see http://gnuwin32.sourceforge.net/ but there haven't been any updates for a while now, so I'm not sure on this project's status.

How to make HTML element resizable using pure Javascript?

See my cross browser compatible resizer.

_x000D_
_x000D_
    <!doctype html>_x000D_
    <html xmlns="http://www.w3.org/1999/xhtml">_x000D_
    <head>_x000D_
        <title>resizer</title>_x000D_
        <meta name="author" content="Andrej Hristoliubov [email protected]">_x000D_
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
        <script type="text/javascript" src="https://rawgit.com/anhr/resizer/master/Common.js"></script>_x000D_
        <script type="text/javascript" src="https://rawgit.com/anhr/resizer/master/resizer.js"></script>_x000D_
        <style>_x000D_
            .element {_x000D_
                border: 1px solid #999999;_x000D_
                border-radius: 4px;_x000D_
                margin: 5px;_x000D_
                padding: 5px;_x000D_
            }_x000D_
        </style>_x000D_
        <script type="text/javascript">_x000D_
            function onresize() {_x000D_
                var element1 = document.getElementById("element1");_x000D_
                var element2 = document.getElementById("element2");_x000D_
                var element3 = document.getElementById("element3");_x000D_
                var ResizerY = document.getElementById("resizerY");_x000D_
                ResizerY.style.top = element3.offsetTop - 15 + "px";_x000D_
                var topElements = document.getElementById("topElements");_x000D_
                topElements.style.height = ResizerY.offsetTop - 20 + "px";_x000D_
                var height = topElements.clientHeight - 32;_x000D_
                if (height < 0)_x000D_
                    height = 0;_x000D_
                height += 'px';_x000D_
                element1.style.height = height;_x000D_
                element2.style.height = height;_x000D_
            }_x000D_
            function resizeX(x) {_x000D_
                //consoleLog("mousemove(X = " + e.pageX + ")");_x000D_
                var element2 = document.getElementById("element2");_x000D_
                element2.style.width =_x000D_
                    element2.parentElement.clientWidth_x000D_
                    + document.getElementById('rezizeArea').offsetLeft_x000D_
                    - x_x000D_
                    + 'px';_x000D_
            }_x000D_
            function resizeY(y) {_x000D_
                //consoleLog("mousemove(Y = " + e.pageY + ")");_x000D_
                var element3 = document.getElementById("element3");_x000D_
                var height =_x000D_
                    element3.parentElement.clientHeight_x000D_
                    + document.getElementById('rezizeArea').offsetTop_x000D_
                    - y_x000D_
                ;_x000D_
                //consoleLog("mousemove(Y = " + e.pageY + ") height = " + height + " element3.parentElement.clientHeight = " + element3.parentElement.clientHeight);_x000D_
                if ((height + 100) > element3.parentElement.clientHeight)_x000D_
                    return;//Limit of the height of the elemtnt 3_x000D_
                element3.style.height = height + 'px';_x000D_
                onresize();_x000D_
            }_x000D_
            var emailSubject = "Resizer example error";_x000D_
        </script>_x000D_
    </head>_x000D_
    <body>_x000D_
        <div id='Message'></div>_x000D_
        <h1>Resizer</h1>_x000D_
        <p>Please see example of resizing of the HTML element by mouse dragging.</p>_x000D_
        <ul>_x000D_
            <li>Drag the red rectangle if you want to change the width of the Element 1 and Element 2</li>_x000D_
            <li>Drag the green rectangle if you want to change the height of the Element 1 Element 2 and Element 3</li>_x000D_
            <li>Drag the small blue square at the left bottom of the Element 2, if you want to resize of the Element 1 Element 2 and Element 3</li>_x000D_
        </ul>_x000D_
        <div id="rezizeArea" style="width:1000px; height:250px; overflow:auto; position: relative;" class="element">_x000D_
            <div id="topElements" class="element" style="overflow:auto; position:absolute; left: 0; top: 0; right:0;">_x000D_
                <div id="element2" class="element" style="width: 30%; height:10px; float: right; position: relative;">_x000D_
                    Element 2_x000D_
                    <div id="resizerXY" style="width: 10px; height: 10px; background: blue; position:absolute; left: 0; bottom: 0;"></div>_x000D_
                    <script type="text/javascript">_x000D_
                        resizerXY("resizerXY", function (e) {_x000D_
                                resizeX(e.pageX + 10);_x000D_
                                resizeY(e.pageY + 50);_x000D_
                            });_x000D_
                    </script>_x000D_
                </div>_x000D_
                <div id="resizerX" style="width: 10px; height:100%; background: red; float: right;"></div>_x000D_
                <script type="text/javascript">_x000D_
                    resizerX("resizerX", function (e) {_x000D_
                        resizeX(e.pageX + 25);_x000D_
                    });_x000D_
                </script>_x000D_
                <div id="element1" class="element" style="height:10px; overflow:auto;">Element 1</div>_x000D_
            </div>_x000D_
            <div id="resizerY" style="height:10px; position:absolute; left: 0; right:0; background: green;"></div>_x000D_
            <script type="text/javascript">_x000D_
                resizerY("resizerY", function (e) {_x000D_
                    resizeY(e.pageY + 25);_x000D_
                });_x000D_
            </script>_x000D_
            <div id="element3" class="element" style="height:100px; position:absolute; left: 0; bottom: 0; right:0;">Element 3</div>_x000D_
        </div>_x000D_
        <script type="text/javascript">_x000D_
            onresize();_x000D_
        </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Also see my example of resizer

How to get a unix script to run every 15 seconds?

If you insist of running your script from cron:

* * * * * /foo/bar/your_script
* * * * * sleep 15; /foo/bar/your_script
* * * * * sleep 30; /foo/bar/your_script
* * * * * sleep 45; /foo/bar/your_script

and replace your script name&path to /foo/bar/your_script

WSDL vs REST Pros and Cons

I know that this discussion is an old one, but after reading all the answers and commented, I believe that everyone missed the most important point about the difference between the 2 systems: SOAP uses complex types to not only give you the data, but validate it and keep it in the strict type designation it was defined for. A WSDL tells you what the data format is, what the data type is, allows you to add reg-ex pattern-style rules, and defines how many times a piece of data must be, and may be, allowed in a request/response. Rest on the other-hand has none of these mechanisms.

SOAP is complex and heavy because it allows you to send complex heavy hierarchical data. REST is plain text, with the origin and endpoint sorting out the rules.

SOAP is business independent, because it has all the data rules embedded in the document.

The difference between SOAP and REST is that SOAP is a self-contained business oriented schema. REST is a text document.

How to populate a dropdownlist with json data in jquery?

var listItems= "";
var jsonData = jsonObj.d;
    for (var i = 0; i < jsonData.Table.length; i++){
      listItems+= "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
    }
    $("#<%=DLState.ClientID%>").html(listItems);

Example

   <html>
    <head></head>
    <body>
      <select id="DLState">
      </select>
    </body>
    </html>

    /*javascript*/
    var jsonList = {"Table" : [{"stateid" : "2","statename" : "Tamilnadu"},
                {"stateid" : "3","statename" : "Karnataka"},
                {"stateid" : "4","statename" : "Andaman and Nicobar"},
                 {"stateid" : "5","statename" : "Andhra Pradesh"},
                 {"stateid" : "6","statename" : "Arunachal Pradesh"}]}

    $(document).ready(function(){
      var listItems= "";
      for (var i = 0; i < jsonList.Table.length; i++){
        listItems+= "<option value='" + jsonList.Table[i].stateid + "'>" + jsonList.Table[i].statename + "</option>";
      }
      $("#DLState").html(listItems);
    });    

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

You just need to include the standard.jar file in your project build path.

Oracle timestamp data type

Quite simply the number is the precision of the timestamp, the fraction of a second held in the column:

SQL> create table t23
  2  (ts0 timestamp(0)
  3   , ts3 timestamp(3)
  4  , ts6 timestamp(6)
  5  )
  6  /

Table created.

SQL> insert into t23 values (systimestamp, systimestamp, systimestamp)
  2  /

1 row created.

SQL> select * from t23
  2  /

TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM


SQL> 

If we don't specify a precision then the timestamp defaults to six places.

SQL> alter table t23 add ts_def timestamp;

Table altered.

SQL> update t23      
  2  set ts_def = systimestamp
  3  /

1 row updated.

SQL> select * from t23
  2  /

TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM


SQL> 

Note that I'm running on Linux so my TIMESTAMP column actually gives me precision to six places i.e. microseconds. This would also be the case on most (all?) flavours of Unix. On Windows the limit is three places i.e. milliseconds. (Is this still true of the most modern flavours of Windows - citation needed).

As might be expected, the documentation covers this. Find out more.


"when you create timestamp(9) this gives you nanos right"

Only if the OS supports it. As you can see, my OEL appliance does not:

SQL> alter table t23 add ts_nano timestamp(9)
  2  /

Table altered.

SQL> update t23 set ts_nano = systimestamp(9)
  2  /

1 row updated.

SQL> select * from t23
  2  /

TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
TS_NANO
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
24-JAN-12 08.28.03.990557000 AM


SQL> 

(Those trailing zeroes could be a coincidence but they aren't.)

Retrieve specific commit from a remote Git repository

I think 'git ls-remote' ( http://git-scm.com/docs/git-ls-remote ) should do what you want. Without force fetch or pull.

jquery UI dialog: how to initialize without a title bar?

I think that the best solution is to use the option dialogClass.

An extract from jquery UI docs:

during init : $('.selector').dialog({ dialogClass: 'noTitleStuff' });

or if you want after init. :

$('.selector').dialog('option', 'dialogClass', 'noTitleStuff');

So i created some dialog with option dialogClass='noTitleStuff' and the css like that:

.noTitleStuff .ui-dialog-titlebar {display:none}

too simple !! but i took 1 day to think why my previous id->class drilling method was not working. In fact when you call .dialog() method the div you transform become a child of another div (the real dialog div) and possibly a 'brother' of the titlebar div, so it's very difficult to try finding the latter starting from former.

How to find difference between two columns data?

IF the table is alias t

SELECT t.Present , t.previous, t.previous- t.Present AS Difference
FROM   temp1 as t

Get connection string from App.config

Can't you just do the following:

var connection = 
    System.Configuration.ConfigurationManager.
    ConnectionStrings["Test"].ConnectionString;

Your assembly also needs a reference to System.Configuration.dll

bootstrap multiselect get selected values

$('#multiselect1').on('change', function(){
    var selected = $(this).find("option:selected");
    var arrSelected = [];
    selected.each(function(){
       arrSelected.push($(this).val());
    });
});

Remove Backslashes from Json Data in JavaScript

tl;dr: You don't have to remove the slashes, you have nested JSON, and hence have to decode the JSON twice: DEMO (note I used double slashes in the example, because the JSON is inside a JS string literal).


I assume that your actual JSON looks like

{"data":"{\n \"taskNames\" : [\n \"01 Jan\",\n \"02 Jan\",\n \"03 Jan\",\n \"04 Jan\",\n \"05 Jan\",\n \"06 Jan\",\n \"07 Jan\",\n \"08 Jan\",\n \"09 Jan\",\n \"10 Jan\",\n \"11 Jan\",\n \"12 Jan\",\n \"13 Jan\",\n \"14 Jan\",\n \"15 Jan\",\n \"16 Jan\",\n \"17 Jan\",\n \"18 Jan\",\n \"19 Jan\",\n \"20 Jan\",\n \"21 Jan\",\n \"22 Jan\",\n \"23 Jan\",\n \"24 Jan\",\n \"25 Jan\",\n \"26 Jan\",\n \"27 Jan\"]}"}

I.e. you have a top level object with one key, data. The value of that key is a string containing JSON itself. This is usually because the server side code didn't properly create the JSON. That's why you see the \" inside the string. This lets the parser know that " is to be treated literally and doesn't terminate the string.

So you can either fix the server side code, so that you don't double encode the data, or you have to decode the JSON twice, e.g.

var data = JSON.parse(JSON.parse(json).data));

Increasing nesting function calls limit

Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.

I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.

Laravel Eloquent update just if changes have been made

You're already doing it!

save() will check if something in the model has changed. If it hasn't it won't run a db query.

Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate:

protected function performUpdate(Builder $query, array $options = [])
{
    $dirty = $this->getDirty();

    if (count($dirty) > 0)
    {
        // runs update query
    }

    return true;
}

The getDirty() method simply compares the current attributes with a copy saved in original when the model is created. This is done in the syncOriginal() method:

public function __construct(array $attributes = array())
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}

public function syncOriginal()
{
    $this->original = $this->attributes;

    return $this;
}

If you want to check if the model is dirty just call isDirty():

if($product->isDirty()){
    // changes have been made
}

Or if you want to check a certain attribute:

if($product->isDirty('price')){
    // price has changed
}

How to disable sort in DataGridView?

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
      for (int i = 0; i < dataGridView1.Columns.Count; i++)
      {
           dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
      }
}

Laravel assets url

You have to put all your assets in app/public folder, and to access them from your views you can use asset() helper method.

Ex. you can retrieve assets/images/image.png in your view as following:

<img src="{{asset('assets/images/image.png')}}">

Set style for TextView programmatically

You can create a generic style and re-use it on multiple textviews like the one below:

textView.setTextAppearance(this, R.style.MyTextStyle);

Edit: this refers to Context

javascript: detect scroll end

The accepted answer was fundamentally flawed, it has since been deleted. The correct answer is:

function scrolled(e) {
  if (myDiv.offsetHeight + myDiv.scrollTop >= myDiv.scrollHeight) {
    scrolledToBottom(e);
  }
}

Tested this in Firefox, Chrome and Opera. It works.

How do I select between the 1st day of the current month and current day in MySQL?

The key here is to get the first day of the month. For that, there are several options. In terms of performance, our tests show that there isn't a significant difference between them - we wrote a whole blog article on the topic. Our findings show that what really matters is whether you need the result to be VARCHAR, DATETIME, or DATE.

The fastest solution to the real problem of getting the first day of the month returns VARCHAR:

SELECT CONCAT(LEFT(CURRENT_DATE, 7), '-01') AS first_day_of_month;

The second fastest solution gives a DATETIME result - this runs about 3x slower than the previous:

SELECT TIMESTAMP(CONCAT(LEFT(CURRENT_DATE, 7), '-01')) AS first_day_of_month;

The slowest solutions return DATE objects. Don't believe me? Run this SQL Fiddle and see for yourself

In your case, since you need to compare the value with other DATE values in your table, it doesn't really matter what methodology you use because MySQL will do the conversion implicitly even if your formula doesn't return a DATE object.

So really, take your pick. Which is most readable for you? I'd pick the first since it's the shortest and arguably the simplest:

SELECT * FROM table_name 
WHERE date BETWEEN CONCAT(LEFT(CURRENT_DATE, 7), '-01') AND CURDATE;

SELECT * FROM table_name 
WHERE date BETWEEN DATE(CONCAT(LEFT(CURRENT_DATE, 7), '-01')) AND CURDATE;

SELECT * FROM table_name 
WHERE date BETWEEN (LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 1 MONTH) AND CURDATE;

SELECT * FROM table_name 
WHERE date BETWEEN (DATE(CURRENT_DATE) - INTERVAL (DAYOFMONTH(CURRENT_DATE) - 1) DAY) AND CURDATE;

SELECT * FROM table_name 
WHERE date BETWEEN (DATE(CURRENT_DATE) - INTERVAL (DAYOFMONTH(CURRENT_DATE)) DAY + INTERVAL 1 DAY) AND CURDATE;

SELECT * FROM table_name 
WHERE date BETWEEN DATE_FORMAT(CURRENT_DATE,'%Y-%m-01') AND CURDATE;

Mod of negative number is melting my brain

You're expecting a behaviour that is contrary to the documented behaviour of the % operator in c# - possibly because you're expecting it to work in a way that it works in another language you are more used to. The documentation on c# states (emphasis mine):

For the operands of integer types, the result of a % b is the value produced by a - (a / b) * b. The sign of the non-zero remainder is the same as that of the left-hand operand

The value you want can be calculated with one extra step:

int GetArrayIndex(int i, int arrayLength){
    int mod = i % arrayLength;
    return (mod>=0) : mod ? mod + arrayLength;
}

How to catch a unique constraint error in a PL/SQL block?

I suspect the condition you are looking for is DUP_VAL_ON_INDEX

EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
        DBMS_OUTPUT.PUT_LINE('OH DEAR. I THINK IT IS TIME TO PANIC!')

MySql server startup error 'The server quit without updating PID file '

For me the solution was to override/correct the data directory in /etc/my/cnf.

I built MySQL 5.5.27 from source with the directions provided in the readme file:


# Preconfiguration setup
shell> groupadd mysql
shell> useradd -r -g mysql mysql
# Beginning of source-build specific instructions
shell> tar zxvf mysql-VERSION.tar.gz
shell> cd mysql-VERSION
shell> cmake .
shell> make
shell> make install
# End of source-build specific instructions

# Postinstallation setup
shell> cd /usr/local/mysql
shell> chown -R mysql .
shell> chgrp -R mysql .
shell> scripts/mysql_install_db --user=mysql
shell> chown -R root .
shell> chown -R mysql data

# Next command is optional
shell> cp support-files/my-medium.cnf /etc/my.cnf
shell> bin/mysqld_safe --user=mysql &

# Next command is optional
shell> cp support-files/mysql.server /etc/init.d/mysql.server

mysqld_safe terminated itself without explanation. running /etc/init.d/mysql.server start resulted in the error:

"The server quit without updating PID file"

I noticed something odd in the installation instructions though. It has ownership changed to mysql for the directory "data", but not to "var"; this is unusual because for years I have had to ensure that var directory was mysql writable. So I manually ran chown -R mysql /usr/local/mysql/var and then attempted to start it again. Still no luck. But worse, no .err file in the var dir - it was in the "data" dir! so scripts/mysql_install_db sets up camp in /usr/local/mysql/var, but the rest of the application seems to want to do its work in /usr/local/mysql/data!

So I just edited /etc/my.cnf and under the section [mysqld] I added a directive to explicitly point mysql's data directory to var (as I normally expect it to be any how), and after doing so, mysqld starts up just fine. The directive to add looks like this:

datadir = /usr/local/mysql/var

Worked for me. Hope it helps for you.

Convert Pandas column containing NaNs to dtype `int`

Try this:

df[['id']] = df[['id']].astype(pd.Int64Dtype())

If you print it's dtypes, you will get id Int64 instead of normal one int64

How to convert a const char * to std::string

std::string str(c_str, strnlen(c_str, max_length));

At Christian Rau's request:

strnlen is specified in POSIX.1-2008 and available in GNU's glibc and the Microsoft run-time library. It is not yet found in some other systems; you may fall back to Gnulib's substitute.

How to fix corrupt HDFS FIles

You can use

  hdfs fsck /

to determine which files are having problems. Look through the output for missing or corrupt blocks (ignore under-replicated blocks for now). This command is really verbose especially on a large HDFS filesystem so I normally get down to the meaningful output with

  hdfs fsck / | egrep -v '^\.+$' | grep -v eplica

which ignores lines with nothing but dots and lines talking about replication.

Once you find a file that is corrupt

  hdfs fsck /path/to/corrupt/file -locations -blocks -files

Use that output to determine where blocks might live. If the file is larger than your block size it might have multiple blocks.

You can use the reported block numbers to go around to the datanodes and the namenode logs searching for the machine or machines on which the blocks lived. Try looking for filesystem errors on those machines. Missing mount points, datanode not running, file system reformatted/reprovisioned. If you can find a problem in that way and bring the block back online that file will be healthy again.

Lather rinse and repeat until all files are healthy or you exhaust all alternatives looking for the blocks.

Once you determine what happened and you cannot recover any more blocks, just use the

  hdfs fs -rm /path/to/file/with/permanently/missing/blocks

command to get your HDFS filesystem back to healthy so you can start tracking new errors as they occur.

Simple line plots using seaborn

It's possible to get this done using seaborn.lineplot() but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:

# imports
import seaborn as sns
import numpy as np
import pandas as pd

# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])

# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)

# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>

And we get the following plot:

square plot

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:

Delivery -> Package (One -> Many)

CREATE TABLE Delivery(
    Id INT IDENTITY PRIMARY KEY,
    NoteNumber NVARCHAR(255) NOT NULL
)

CREATE TABLE Package(
    Id INT IDENTITY PRIMARY KEY,
    Status INT NOT NULL DEFAULT 0,
    Delivery_Id INT NOT NULL,
    CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)

The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).

So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.

css width: calc(100% -100px); alternative using jquery

100%-100px is the same

div.thediv {
  width: auto;
  margin-right:100px;
}

With jQuery:

$(window).resize(function(){
  $('.thediv').each(function(){
    $(this).css('width', $(this).parent().width()-100);
  })
});

Similar way is to use jQuery resize plugin

List tables in a PostgreSQL schema

In all schemas:

=> \dt *.*

In a particular schema:

=> \dt public.*

It is possible to use regular expressions with some restrictions

\dt (public|s).(s|t)
       List of relations
 Schema | Name | Type  | Owner 
--------+------+-------+-------
 public | s    | table | cpn
 public | t    | table | cpn
 s      | t    | table | cpn

Advanced users can use regular-expression notations such as character classes, for example [0-9] to match any digit. All regular expression special characters work as specified in Section 9.7.3, except for . which is taken as a separator as mentioned above, * which is translated to the regular-expression notation .*, ? which is translated to ., and $ which is matched literally. You can emulate these pattern characters at need by writing ? for ., (R+|) for R*, or (R|) for R?. $ is not needed as a regular-expression character since the pattern must match the whole name, unlike the usual interpretation of regular expressions (in other words, $ is automatically appended to your pattern). Write * at the beginning and/or end if you don't wish the pattern to be anchored. Note that within double quotes, all regular expression special characters lose their special meanings and are matched literally. Also, the regular expression special characters are matched literally in operator name patterns (i.e., the argument of \do).

System.Timers.Timer vs System.Threading.Timer

In his book "CLR Via C#", Jeff Ritcher discourages using System.Timers.Timer, this timer is derived from System.ComponentModel.Component, allowing it to be used in design surface of Visual Studio. So that it would be only useful if you want a timer on a design surface.

He prefers to use System.Threading.Timer for background tasks on a thread pool thread.

Apply CSS Style to child elements

The > selector matches direct children only, not descendants.

You want

div.test th, td, caption {}

or more likely

div.test th, div.test td, div.test caption {}

Edit:

The first one says

  div.test th, /* any <th> underneath a <div class="test"> */
  td,          /* or any <td> anywhere at all */
  caption      /* or any <caption> */

Whereas the second says

  div.test th,     /* any <th> underneath a <div class="test"> */
  div.test td,     /* or any <td> underneath a <div class="test"> */
  div.test caption /* or any <caption> underneath a <div class="test">  */

In your original the div.test > th says any <th> which is a **direct** child of <div class="test">, which means it will match <div class="test"><th>this</th></div> but won't match <div class="test"><table><th>this</th></table></div>

How can I discard remote changes and mark a file as "resolved"?

Make sure of the conflict origin: if it is the result of a git merge, see Brian Campbell's answer.

But if is the result of a git rebase, in order to discard remote (their) changes and use local changes, you would have to do a:

git checkout --theirs -- .

See "Why is the meaning of “ours” and “theirs” reversed"" to see how ours and theirs are swapped during a rebase (because the upstream branch is checked out).

Django Admin - change header 'Django administration' text

From Django 2.0 you can just add a single line in the url.py and change the name.

# url.py

from django.contrib import admin 
admin.site.site_header = "My Admin Central" # Add this

For older versions of Django. (<1.11 and earlier) you need to edit admin/base_site.html

Change this line

{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}

to

{% block title %}{{ title }} | {{ site_title|default:_('Your Site name Admin Central') }}{% endblock %}

You can check your django version by

django-admin --version

How to allow CORS in react.js?

there are 6 ways to do this in React,

number 1 and 2 and 3 are the best:

1-config CORS in the Server-Side

2-set headers manually like this:

resonse_object.header("Access-Control-Allow-Origin", "*");
resonse_object.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

3-config NGINX for proxy_pass which is explained here.

4-bypass the Cross-Origin-Policy with chrom extension(only for development and not recommended !)

5-bypass the cross-origin-policy with URL bellow(only for development)

"https://cors-anywhere.herokuapp.com/{type_your_url_here}"

6-use proxy in your package.json file:(only for development)

if this is your API: http://45.456.200.5:7000/api/profile/

add this part in your package.json file: "proxy": "http://45.456.200.5:7000/",

and then make your request with the next parts of the api:

React.useEffect(() => {
    axios
        .get('api/profile/')
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });
});

Find all files in a folder

You can try with Directory.GetFiles and fix your pattern

 string[] files = Directory.GetFiles(@"c:\", "*.txt");

 foreach (string file in files)
 {
    File.Copy(file, "....");
 }

 Or Move

 foreach (string file in files)
 {
    File.Move(file, "....");
 }     

http://msdn.microsoft.com/en-us/library/wz42302f

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

All of this assumes core.autocrlf=true

Original error:

warning: LF will be replaced by CRLF
The file will have its original line endings in your working directory.

What the error SHOULD read:

warning: LF will be replaced by CRLF in your working directory
The file will have its original LF line endings in the git repository

Explanation here:

The side-effect of this convenient conversion, and this is what the warning you're seeing is about, is that if a text file you authored originally had LF endings instead of CRLF, it will be stored with LF as usual, but when checked out later it will have CRLF endings. For normal text files this is usually just fine. The warning is a "for your information" in this case, but in case git incorrectly assesses a binary file to be a text file, it is an important warning because git would then be corrupting your binary file.

Basically, a local file that was previously LF will now have CRLF locally

Currency Formatting in JavaScript

You can use standard JS toFixed method

var num = 5.56789;
var n=num.toFixed(2);

//5.57

In order to add commas (to separate 1000's) you can add regexp as follows (where num is a number):

num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")

//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000

Complete example:

var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

//document.write(num) would write value as follows: $1,250.22

Separation character depends on country and locale. For some countries it may need to be .

Prevent wrapping of span or div

Try this:

_x000D_
_x000D_
.slideContainer {_x000D_
    overflow-x: scroll;_x000D_
    white-space: nowrap;_x000D_
}_x000D_
.slide {_x000D_
    display: inline-block;_x000D_
    width: 600px;_x000D_
    white-space: normal;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
    <span class="slide">Some content</span>_x000D_
    <span class="slide">More content. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>_x000D_
    <span class="slide">Even more content!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note that you can omit .slideContainer { overflow-x: scroll; } (which browsers may or may not support when you read this), and you'll get a scrollbar on the window instead of on this container.

The key here is display: inline-block. This has decent cross-browser support nowadays, but as usual, it's worth testing in all target browsers to be sure.

MySQL Insert with While Loop

drop procedure if exists doWhile;
DELIMITER //  
CREATE PROCEDURE doWhile()   
BEGIN
DECLARE i INT DEFAULT 2376921001; 
WHILE (i <= 237692200) DO
    INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
    SET i = i+1;
END WHILE;
END;
//  

CALL doWhile(); 

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

This requires no special permissions, and works with the Storage Access Framework, as well as the unofficial ContentProvider pattern (file path in _data field).

/**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @author paulburke
 */
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is Google Photos.
 */
public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}

See an up-to-date version of this method here.

How to disable margin-collapsing?

Every webkit based browser should support the properties -webkit-margin-collapse. There are also subproperties to only set it for the top or bottom margin. You can give it the values collapse (default), discard (sets margin to 0 if there is a neighboring margin), and separate (prevents margin collapse).

I've tested that this works on 2014 versions of Chrome and Safari. Unfortunately, I don't think this would be supported in IE because it's not based on webkit.

Read Apple's Safari CSS Reference for a full explanation.

If you check Mozilla's CSS webkit extensions page, they list these properties as proprietary and recommend not to use them. This is because they're likely not going to go into standard CSS anytime soon and only webkit based browsers will support them.

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

this problem can be solved by installing the latest libstdc++.

$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-7-dbg

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

I must have arrived at the party late, none of the solutions here seemed helpful to me - too messy and felt like too much of a workaround.

What I ended up doing is using Angular 4.0.0-beta.6's ngComponentOutlet.

This gave me the shortest, simplest solution all written in the dynamic component's file.

  • Here is a simple example which just receives text and places it in a template, but obviously you can change according to your need:
import {
  Component, OnInit, Input, NgModule, NgModuleFactory, Compiler
} from '@angular/core';

@Component({
  selector: 'my-component',
  template: `<ng-container *ngComponentOutlet="dynamicComponent;
                            ngModuleFactory: dynamicModule;"></ng-container>`,
  styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
  dynamicComponent;
  dynamicModule: NgModuleFactory<any>;

  @Input()
  text: string;

  constructor(private compiler: Compiler) {
  }

  ngOnInit() {
    this.dynamicComponent = this.createNewComponent(this.text);
    this.dynamicModule = this.compiler.compileModuleSync(this.createComponentModule(this.dynamicComponent));
  }

  protected createComponentModule (componentType: any) {
    @NgModule({
      imports: [],
      declarations: [
        componentType
      ],
      entryComponents: [componentType]
    })
    class RuntimeComponentModule
    {
    }
    // a module for just this Type
    return RuntimeComponentModule;
  }

  protected createNewComponent (text:string) {
    let template = `dynamically created template with text: ${text}`;

    @Component({
      selector: 'dynamic-component',
      template: template
    })
    class DynamicComponent implements OnInit{
       text: any;

       ngOnInit() {
       this.text = text;
       }
    }
    return DynamicComponent;
  }
}
  • Short explanation:
    1. my-component - the component in which a dynamic component is rendering
    2. DynamicComponent - the component to be dynamically built and it is rendering inside my-component

Don't forget to upgrade all the angular libraries to ^Angular 4.0.0

Hope this helps, good luck!

UPDATE

Also works for angular 5.

Error: Argument is not a function, got undefined

Could it be as simple as enclosing your asset in " " and whatever needs quotes on the inside with ' '?

<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">

becomes

<link rel="stylesheet" media="screen" href="@routes.Assets.at('stylesheets/main.css')">

That could be causing some problems with parsing

URL encoding in Android

For android, I would use String android.net.Uri.encode(String s)

Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes all other characters.

Ex/

String urlEncoded = "http://stackoverflow.com/search?q=" + Uri.encode(query);

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

np.append needs the array as the first argument and the list you want to append as the second:

mean_data = np.append(mean_data, [ur, ua, np.mean(data[samepoints,-1])])

Android Studio how to run gradle sync manually?

In Android Studio 3.3 it is here:

enter image description here

According to the answer https://stackoverflow.com/a/49576954/2914140 in Android Studio 3.1 it is here:

enter image description here

This command is moved to File > Sync Project with Gradle Files.

enter image description here

Replace multiple characters in one replace call

yourstring = '#Please send_an_information_pack_to_the_following_address:';

replace '#' with '' and replace '_' with a space

var newstring1 = yourstring.split('#').join('');
var newstring2 = newstring1.split('_').join(' ');

newstring2 is your result

How can I confirm a database is Oracle & what version it is using SQL?

You can either use

SELECT * FROM v$version;

or

SET SERVEROUTPUT ON
EXEC dbms_output.put_line( dbms_db_version.version );

if you don't want to parse the output of v$version.

How do I remove accents from characters in a PHP string?

This is a piece of code I found and use often:

function stripAccents($stripAccents){
  return strtr($stripAccents,'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ','aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
}

To find first N prime numbers in python

Here's a simple recursive version:

import datetime
import math

def is_prime(n, div=2):
    if div> int(math.sqrt(n)): return True
    if n% div == 0:
        return False
    else:
        div+=1
        return is_prime(n,div)


now = datetime.datetime.now()

until = raw_input("How many prime numbers my lord desires??? ")
until = int(until)

primelist=[]
i=1;
while len(primelist)<until:
    if is_prime(i):
        primelist.insert(0,i)
        i+=1
    else: i+=1



print "++++++++++++++++++++"
print primelist
finish = datetime.datetime.now()
print "It took your computer", finish - now , "secs to calculate it"

Here's a version using a recursive function with memory!:

import datetime
import math

def is_prime(n, div=2):
    global primelist
    if div> int(math.sqrt(n)): return True
    if div < primelist[0]:
        div = primelist[0]
        for x in primelist:
            if x ==0 or x==1: continue
            if n % x == 0:
                return False
    if n% div == 0:
        return False
    else:
        div+=1
        return is_prime(n,div)


now = datetime.datetime.now()
print 'time and date:',now

until = raw_input("How many prime numbers my lord desires??? ")
until = int(until)

primelist=[]
i=1;
while len(primelist)<until:
    if is_prime(i):
        primelist.insert(0,i)
        i+=1
    else: i+=1



print "Here you go!"
print primelist

finish = datetime.datetime.now()
print "It took your computer", finish - now , " to calculate it"

Hope it helps :)

How to print to console in pytest?

According to the pytest docs, pytest --capture=sys should work. If you want to capture standard out inside a test, refer to the capsys fixture.

Security of REST authentication schemes

Remember that your suggestions makes it difficult for clients to communicate with the server. They need to understand your innovative solution and encrypt the data accordingly, this model is not so good for public API (unless you are amazon\yahoo\google..).

Anyways, if you must encrypt the body content I would suggest you to check out existing standards and solutions like:

XML encryption (W3C standard)

XML Security

Regular expression for decimal number

As I tussled with this, TryParse in 3.5 does have NumberStyles: The following code should also do the trick without Regex to ignore thousands seperator.

double.TryParse(length, NumberStyles.AllowDecimalPoint,CultureInfo.CurrentUICulture, out lengthD))

Not relevant to the original question asked but confirming that TryParse() indeed is a good option.

Difference between classification and clustering in data mining?

I'm a new comer to Data Mining, but as my textbook says, CLASSICIATION is supposed to be supervised learning, and CLUSTERING unsupervised learning. The difference between supervised learning and unsupervised learning can be found here.

What's the whole point of "localhost", hosts and ports at all?

In computer networking, localhost (meaning "this computer") is the standard hostname given to the address of the loopback network interface.

Localhost always translates to the loopback IP address 127.0.0.1 in IPv4.

It is also used instead of the hostname of a computer. For example, directing a web browser installed on a system running an HTTP server to http://localhost will display the home page of the local web site.

Source: Wikipedia - Localhost.


The :80 part is the TCP port. You can consider these ports as communications endpoints on a particular IP address (in the case of localhost - 127.0.0.1). The IANA is responsible for maintaining the official assignments of standard port numbers for specific services. Port 80 happens to be the standard port for HTTP.