Programs & Examples On #Fileinfo

How to check if a file exists in a folder?

This helped me:

bool fileExists = (System.IO.File.Exists(filePath) ? true : false);

GetFiles with multiple extensions

I know there is a more elegant way to do this and I'm open to suggestions... this is what I did:

          try
            {


             // Set directory for list to be made of
                DirectoryInfo jpegInfo = new DirectoryInfo(destinationFolder);
                DirectoryInfo jpgInfo = new DirectoryInfo(destinationFolder);
                DirectoryInfo gifInfo = new DirectoryInfo(destinationFolder);
                DirectoryInfo tiffInfo = new DirectoryInfo(destinationFolder);
                DirectoryInfo bmpInfo = new DirectoryInfo(destinationFolder);

                // Set file type
                FileInfo[] Jpegs = jpegInfo.GetFiles("*.jpeg");
                FileInfo[] Jpgs = jpegInfo.GetFiles("*.jpg");
                FileInfo[] Gifs = gifInfo.GetFiles("*.gif");
                FileInfo[] Tiffs = gifInfo.GetFiles("*.tiff");
                FileInfo[] Bmps = gifInfo.GetFiles("*.bmp");

        //  listBox1.Items.Add(@"");  // Hack for the first list item no preview problem
        // Iterate through each file, displaying only the name inside the listbox...
        foreach (FileInfo file in Jpegs)
        {
                listBox1.Items.Add(file.Name);
                Photo curPhoto = new Photo();
                curPhoto.PhotoLocation = file.FullName;
                metaData.AddPhoto(curPhoto);
            }

          foreach (FileInfo file in Jpgs)
          {
              listBox1.Items.Add(file.Name);
                Photo curPhoto = new Photo();
                curPhoto.PhotoLocation = file.FullName;
                metaData.AddPhoto(curPhoto);
            }
          foreach (FileInfo file in Gifs)
          {
              listBox1.Items.Add(file.Name);
              Photo curPhoto = new Photo();
              curPhoto.PhotoLocation = file.FullName;
              metaData.AddPhoto(curPhoto);
          }
          foreach (FileInfo file in Tiffs)
          {
              listBox1.Items.Add(file.Name);
              Photo curPhoto = new Photo();
              curPhoto.PhotoLocation = file.FullName;
              metaData.AddPhoto(curPhoto);
          }
          foreach (FileInfo file in Bmps)
          {
              listBox1.Items.Add(file.Name);
              Photo curPhoto = new Photo();
              curPhoto.PhotoLocation = file.FullName;
              metaData.AddPhoto(curPhoto);
          }

Get all files and directories in specific path fast

There is a long history of the .NET file enumeration methods being slow. The issue is there is not an instantaneous way of enumerating large directory structures. Even the accepted answer here has its issues with GC allocations.

The best I've been able to do is wrapped up in my library and exposed as the FindFile (source) class in the CSharpTest.Net.IO namespace. This class can enumerate files and folders without unneeded GC allocations and string marshalling.

The usage is simple enough, and the RaiseOnAccessDenied property will skip the directories and files the user does not have access to:

    private static long SizeOf(string directory)
    {
        var fcounter = new CSharpTest.Net.IO.FindFile(directory, "*", true, true, true);
        fcounter.RaiseOnAccessDenied = false;

        long size = 0, total = 0;
        fcounter.FileFound +=
            (o, e) =>
            {
                if (!e.IsDirectory)
                {
                    Interlocked.Increment(ref total);
                    size += e.Length;
                }
            };

        Stopwatch sw = Stopwatch.StartNew();
        fcounter.Find();
        Console.WriteLine("Enumerated {0:n0} files totaling {1:n0} bytes in {2:n3} seconds.",
                          total, size, sw.Elapsed.TotalSeconds);
        return size;
    }

For my local C:\ drive this outputs the following:

Enumerated 810,046 files totaling 307,707,792,662 bytes in 232.876 seconds.

Your mileage may vary by drive speed, but this is the fastest method I've found of enumerating files in managed code. The event parameter is a mutating class of type FindFile.FileFoundEventArgs so be sure you do not keep a reference to it as it's values will change for each event raised.

JDBC ODBC Driver Connection

As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have

  • an implementation of ODBC itself, and
  • an appropriate ODBC driver for the target database (ACE/Jet, a.k.a. "Access")

So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).

There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see

Manipulating an Access database from Java without ODBC

PRINT statement in T-SQL

Do you have variables that are associated with these print statements been output? if so, I have found that if the variable has no value then the print statement will not be ouput.

How to make my layout able to scroll down?

For using scroll view along with Relative layout :

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@drawable/background_image"
    >

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

Return empty cell from formula in Excel

I used the following work around to make my excel looks cleaner:

When you make any calculations the "" will give you error so you want to treat it as a number so I used a nested if statement to return 0 istead of "", and then if the result is 0 this equation will return ""

=IF((IF(A5="",0,A5)+IF(B5="",0,B5)) = 0, "",(IF(A5="",0,A5)+IF(B5="",0,B5)))

This way the excel sheet will look clean...

In Python, how do I split a string and keep the separators?

Another no-regex solution that works well on Python 3

# Split strings and keep separator
test_strings = ['<Hello>', 'Hi', '<Hi> <Planet>', '<', '']

def split_and_keep(s, sep):
   if not s: return [''] # consistent with string.split()

   # Find replacement character that is not used in string
   # i.e. just use the highest available character plus one
   # Note: This fails if ord(max(s)) = 0x10FFFF (ValueError)
   p=chr(ord(max(s))+1) 

   return s.replace(sep, sep+p).split(p)

for s in test_strings:
   print(split_and_keep(s, '<'))


# If the unicode limit is reached it will fail explicitly
unicode_max_char = chr(1114111)
ridiculous_string = '<Hello>'+unicode_max_char+'<World>'
print(split_and_keep(ridiculous_string, '<'))

How can I increase the size of a bootstrap button?

You can add your own css property for button size as follows:

.btn {
    min-width: 250px;
}

Can I apply the required attribute to <select> fields in HTML5?

first you have to assign blank value in first option. i.e. Select here.than only required will work.

Reading data from XML

as per @Jon Skeet 's comment, you should use a XmlReader only if your file is very big. Here's how to use it. Assuming you have a Book class

public class Book {
    public string Title {get; set;}
    public string Author {get; set;}
}

you can read the XML file line by line with a small memory footprint, like this:

public static class XmlHelper {
    public static IEnumerable<Book> StreamBooks(string uri) {
        using (XmlReader reader = XmlReader.Create(uri)) {
            string title = null;
            string author = null;

            reader.MoveToContent();
            while (reader.Read()) {
                if (reader.NodeType == XmlNodeType.Element
                    && reader.Name == "Book") {
                    while (reader.Read()) {
                        if (reader.NodeType == XmlNodeType.Element &&
                            reader.Name == "Title") {
                            title = reader.ReadString();
                            break;
                        }
                    }
                    while (reader.Read()) {
                        if (reader.NodeType == XmlNodeType.Element &&
                            reader.Name == "Author") {
                            author =reader.ReadString();
                            break;
                        }
                    }
                    yield return new Book() {Title = title, Author = author};
                }
            }       
        }
    }

Example of usage:

string uri = @"c:\test.xml"; // your big XML file

foreach (var book in XmlHelper.StreamBooks(uri)) {
    Console.WriteLine("Title, Author: {0}, {1}", book.Title, book.Author);  
}

Composer - the requested PHP extension mbstring is missing from your system

For php 7.1

sudo apt-get install php7.1-mbstring

Cheers!

RedirectToAction with parameter

//How to use RedirectToAction in MVC

return RedirectToAction("actionName", "ControllerName", routevalue);

example

return RedirectToAction("Index", "Home", new { id = 2});

How can I solve equations in Python?

Python may be good, but it isn't God...

There are a few different ways to solve equations. SymPy has already been mentioned, if you're looking for analytic solutions.

If you're happy to just have a numerical solution, Numpy has a few routines that can help. If you're just interested in solutions to polynomials, numpy.roots will work. Specifically for the case you mentioned:

>>> import numpy
>>> numpy.roots([2,-6])
array([3.0])

For more complicated expressions, have a look at scipy.fsolve.

Either way, you can't escape using a library.

Remove and Replace Printed items

One way is to use ANSI escape sequences:

import sys
import time
for i in range(10):
    print("Loading" + "." * i)
    sys.stdout.write("\033[F") # Cursor up one line
    time.sleep(1)

Also sometimes useful (for example if you print something shorter than before):

sys.stdout.write("\033[K") # Clear to the end of line

What's the easiest way to escape HTML in Python?

cgi.escape is fine. It escapes:

  • < to &lt;
  • > to &gt;
  • & to &amp;

That is enough for all HTML.

EDIT: If you have non-ascii chars you also want to escape, for inclusion in another encoded document that uses a different encoding, like Craig says, just use:

data.encode('ascii', 'xmlcharrefreplace')

Don't forget to decode data to unicode first, using whatever encoding it was encoded.

However in my experience that kind of encoding is useless if you just work with unicode all the time from start. Just encode at the end to the encoding specified in the document header (utf-8 for maximum compatibility).

Example:

>>> cgi.escape(u'<a>bá</a>').encode('ascii', 'xmlcharrefreplace')
'&lt;a&gt;b&#225;&lt;/a&gt;

Also worth of note (thanks Greg) is the extra quote parameter cgi.escape takes. With it set to True, cgi.escape also escapes double quote chars (") so you can use the resulting value in a XML/HTML attribute.

EDIT: Note that cgi.escape has been deprecated in Python 3.2 in favor of html.escape, which does the same except that quote defaults to True.

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

Set Application pool to classic .NET appool and make sure that Classic .Net apppool working on Classic managed piple line .

Automatically running a batch file as an administrator

You can use PowerShell to run b.bat as administrator from a.bat:

set mydir=%~dp0

Powershell -Command "& { Start-Process \"%mydir%b.bat\" -verb RunAs}"

It will prompt the user with a confirmation dialog. The user chooses YES, and then b.bat will be run as administrator.

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

Find ALL tweets from a user (not just the first 3,200)

http://greptweet.com/ is an attempt to surpass the 3200 limit by backing up tweets, and besides that is useful for simple searches.

Drop all tables command

Or at a shell prompt, in just two lines, without a named temporary file, assuming $db is the SQLite database name:

echo "SELECT 'DROP TABLE ' || name ||';' FROM sqlite_master WHERE type = 'table';" |
    sqlite3 -readonly "$db" | sqlite3 "$db"

Firebase: how to generate a unique numeric ID for key?

https://firebase.google.com/docs/firestore/manage-data/transactions

Use transactions and keep a number in the database somewhere that you can increase by one. This way you can get a nice numeric and simple id.

Setting up connection string in ASP.NET to SQL SERVER

You can also use this, it's simpler. The only thing you need to set is "YourDataBaseName".

  <connectionStrings>
    <add name="ConnStringDb1" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>

Where to place the connection string

<?xml version='1.0' encoding='utf-8'?>  
  <configuration>  
    <connectionStrings>  
      <clear />  
      <add name="Name"   
       providerName="System.Data.ProviderName"   
       connectionString="Valid Connection String;" />  
    </connectionStrings>  
  </configuration>  

How do I concatenate multiple C++ strings on one line?

In C++20 you'll be able to do:

auto s = std::format("{}{}{}", "Hello world, ", myInt, niceToSeeYouString);

Until then you could do the same with the {fmt} library:

auto s = fmt::format("{}{}{}", "Hello world, ", myInt, niceToSeeYouString);

Disclaimer: I'm the author of {fmt}.

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

How to write a simple Html.DropDownListFor()?

@using (Html.BeginForm()) {
    <p>Do you like pizza?
        @Html.DropDownListFor(x => x.likesPizza, new[] {
            new SelectListItem() {Text = "Yes", Value = bool.TrueString},
            new SelectListItem() {Text = "No", Value = bool.FalseString}
        }, "Choose an option") 
    </p>
    <input type = "submit" value = "Submit my answer" />
} 

I think this answer is similar to Berat's, in that you put all the code for your DropDownList directly in the view. But I think this is an efficient way of creating a y/n (boolean) drop down list, so I wanted to share it.

Some notes for beginners:

  • Don't worry about what 'x' is called - it is created here, for the first time, and doesn't link to anything else anywhere else in the MVC app, so you can call it what you want - 'x', 'model', 'm' etc.
  • The placeholder that users will see in the dropdown list is "Choose an option", so you can change this if you want.
  • There's a bit of text preceding the drop down which says "Do you like pizza?"
  • This should be complete text for a form, including a submit button, I think

Hope this helps someone,

Running javascript in Selenium using Python

Try browser.execute_script instead of selenium.GetEval.

See this answer for example.

iOS application: how to clear notifications?

When you logout from your app, at that time you have to use a below line of code on your logout button click method.

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];

[[UIApplication sharedApplication] cancelAllLocalNotifications];

and this works perfectly in my app.

Detecting a long press with Android

The solution by MSquare works only if you hold a specific pixel, but that's an unreasonable expectation for an end user unless they use a mouse (which they don't, they use fingers).

So I added a bit of a threshold for the distance between the DOWN and the UP action in case there was a MOVE action inbetween.

final Handler longPressHandler = new Handler();
Runnable longPressedRunnable = new Runnable() {
    public void run() {
        Log.e(TAG, "Long press detected in long press Handler!");
        isLongPressHandlerActivated = true;
    }
};

private boolean isLongPressHandlerActivated = false;

private boolean isActionMoveEventStored = false;
private float lastActionMoveEventBeforeUpX;
private float lastActionMoveEventBeforeUpY;

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if(event.getAction() == MotionEvent.ACTION_DOWN) {
        longPressHandler.postDelayed(longPressedRunnable, 1000);
    }
    if(event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_HOVER_MOVE) {
        if(!isActionMoveEventStored) {
            isActionMoveEventStored = true;
            lastActionMoveEventBeforeUpX = event.getX();
            lastActionMoveEventBeforeUpY = event.getY();
        } else {
            float currentX = event.getX();
            float currentY = event.getY();
            float firstX = lastActionMoveEventBeforeUpX;
            float firstY = lastActionMoveEventBeforeUpY;
            double distance = Math.sqrt(
                    (currentY - firstY) * (currentY - firstY) + ((currentX - firstX) * (currentX - firstX)));
            if(distance > 20) {
                longPressHandler.removeCallbacks(longPressedRunnable);
            }
        }
    }
    if(event.getAction() == MotionEvent.ACTION_UP) {
        isActionMoveEventStored = false;
        longPressHandler.removeCallbacks(longPressedRunnable);
        if(isLongPressHandlerActivated) {
            Log.d(TAG, "Long Press detected; halting propagation of motion event");
            isLongPressHandlerActivated = false;
            return false;
        }
    }
    return super.dispatchTouchEvent(event);
}

Convert varchar into datetime in SQL Server

Likely you have bad data that cannot convert. Dates should never be stored in varchar becasue it will allow dates such as ASAP or 02/30/2009. Use the isdate() function on your data to find the records which can't convert.

OK I tested with known good data and still got the message. You need to convert to a different format becasue it does not know if 12302009 is mmddyyyy or ddmmyyyy. The format of yyyymmdd is not ambiguous and SQL Server will convert it correctly

I got this to work:

cast( right(@date,4) + left(@date,4) as datetime)

You will still get an error message though if you have any that are in a non-standard format like '112009' or some text value or a true out of range date.

Running java with JAVA_OPTS env variable has no effect

You can setup _JAVA_OPTIONS instead of JAVA_OPTS. This should work without $_JAVA_OPTIONS.

Efficient way to update all rows in a table

You could drop any indexes on the table, then do your insert, and then recreate the indexes.

Android Studio Gradle Already disposed Module

Sometimes gradlew clean or Invalidate Cache and Restart does not help, because these methods do not clean Android Studio specific files by themselves.

In this case, close AS and remove .idea directory and .iml file in a root project where settings.gradle file exists. This will make AS rebuild from the fresh ground.

Viewing all `git diffs` with vimdiff

You can try git difftool, it is designed to do this stuff.

First, you need to config diff tool to vimdiff

git config diff.tool vimdiff

Then, when you want to diff, just use git difftool instead of git diff. It will work as you expect.

Why do you create a View in a database?

When I want to see a snapshot of a table(s), and/or view (in a read-only way)

how to remove only one style property with jquery

You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.

iPhone hide Navigation Bar only on first page

Swift 4:

In the view controller you want to hide the navigation bar from.

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(true, animated: animated)
    super.viewWillAppear(animated)
}

override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(false, animated: animated)
    super.viewWillDisappear(animated)
}

jquery how to get the page's current screen top position?

var top = $('html').offset().top;

should do it.

edit: this is the negative of $(document).scrollTop()

How to make div follow scrolling smoothly with jQuery?

There's a fantastic jQuery tutorial for this at https://web.archive.org/web/20121012171851/http://jqueryfordesigners.com/fixed-floating-elements/.

It replicates the Apple.com shopping cart type of sidebar scrolling. The Google query that might have served you well is "fixed floating sidebar".

Drawing Circle with OpenGL

I have done it using the following code,

glBegin(GL.GL_LINE_LOOP);
     for(int i =0; i <= 300; i++){
         double angle = 2 * Math.PI * i / 300;
         double x = Math.cos(angle);
         double y = Math.sin(angle);
         gl.glVertex2d(x,y);
     }
glEnd();

What is a "slug" in Django?

Also auto slug at django-admin. Added at ModelAdmin:

prepopulated_fields = {'slug': ('title', )}

As here:

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug')
    search_fields = ('content', )

    prepopulated_fields = {'slug': ('title', )}

If '<selector>' is an Angular component, then verify that it is part of this module

Check your selector in your filename.component.ts

Using the tag in various html files I would say

<my-first-component></my-first-component>

Should be

<app-my-first-component></app-my-first-component>

Example

@Component({
  selector: 'app-my-first-component',
  templateUrl: './my-first-component.component.html',
  styleUrls: ['./my-first-component.component.scss']
})

Detect Close windows event by jQuery

There is no specific event for capturing browser close event.

You can only capture on unload of the current page.

By this method, it will be effected while refreshing / navigating the current page.

Even calculating of X Y postion of the mouse event doesn't give you good result.

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

You can see some reports in SSMS:

Right-click the instance name / reports / standard / top sessions

You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.

You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.

This article looks promising.

Some stackoverflow goodness from Mr. Ozar.

edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.

Android customized button; changing text color

Create a stateful color for your button, just like you did for background, for example:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Focused and not pressed -->
    <item android:state_focused="true" 
          android:state_pressed="false" 
          android:color="#ffffff" />

    <!-- Focused and pressed -->
    <item android:state_focused="true" 
          android:state_pressed="true" 
          android:color="#000000" />

    <!-- Unfocused and pressed -->
    <item android:state_focused="false" 
          android:state_pressed="true" 
          android:color="#000000" />

    <!-- Default color -->
    <item android:color="#ffffff" />

</selector>

Place the xml in a file at res/drawable folder i.e. res/drawable/button_text_color.xml. Then just set the drawable as text color:

android:textColor="@drawable/button_text_color"

What does "\r" do in the following script?

The '\r' character is the carriage return, and the carriage return-newline pair is both needed for newline in a network virtual terminal session.


From the old telnet specification (RFC 854) (page 11):

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

However, from the latest specification (RFC5198) (page 13):

  1. ...

  2. In Net-ASCII, CR MUST NOT appear except when immediately followed by either NUL or LF, with the latter (CR LF) designating the "new line" function. Today and as specified above, CR should generally appear only when followed by LF. Because page layout is better done in other ways, because NUL has a special interpretation in some programming languages, and to avoid other types of confusion, CR NUL should preferably be avoided as specified above.

  3. LF CR SHOULD NOT appear except as a side-effect of multiple CR LF sequences (e.g., CR LF CR LF).

So newline in Telnet should always be '\r\n' but most implementations have either not been updated, or keeps the old '\n\r' for backwards compatibility.

passing 2 $index values within nested ng-repeat

Each ng-repeat creates a child scope with the passed data, and also adds an additional $index variable in that scope.

So what you need to do is reach up to the parent scope, and use that $index.

See http://plnkr.co/edit/FvVhirpoOF8TYnIVygE6?p=preview

<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu($parent.$index)" ng-repeat="tutorial in section.tutorials">
    {{tutorial.name}}
</li>

How to remove the arrow from a select element in Firefox

A lot of Discussions Happening here & there but I don't see some proper solution for this problem. Finally Ended up by writing a small Jquery + CSS code for doing this HACK on IE & Firefox.

Calculate Element Width (SELECT Element) using Jquery. Add a Wrapper Around Select Element and Keep overflow hidden for this element. Make sure that Width of this wrapper is appox. 25px less as that of SELECT Element. This could be easily done with Jquery. So Now Our Icon is Gone..! and it is time for adding our image icon on SELECT element...!!! Just add few simple lines for adding background and you are all Done..!! Make sure to use overflow hidden for outer wrapper,

Here is a Sample of Code which was done for Drupal. However could be used for others also by removing few lines of code which is Drupal Specific.

/*
 * Jquery Code for Removing Dropdown Arrow.
 * @by: North Web Studio
 */
(function($) {
  Drupal.behaviors.nwsJS = {
    attach: function(context, settings) {
      $('.form-select').once('nws-arrow', function() {
        $wrap_width = $(this).outerWidth();
        $element_width = $wrap_width + 20;
        $(this).css('width', $element_width);
        $(this).wrap('<div class="nws-select"></div>');
        $(this).parent('.nws-select').css('width', $wrap_width);
      });
    }
  };
})(jQuery);
/*
 * CSS Code for Removing Dropdown Arrow.
 * @by: North Web Studio
 */

.nws-select {
  border: 1px solid #ccc;
  overflow: hidden;
  background: url('../images/icon.png') no-repeat 95% 50%;
}
.nws-select .form-select {
  border: none;
  background: transparent;
}

Solution works on All Browsers IE, Chrome & Firefox No need of Adding fixed Widths Hacks Using CSS. It is all being handled Dynamically using JQuery.!

More Described at:- http://northwebstudio.com/blogs/1/jquery/remove-drop-down-arrow-html-select-element-using-jquery-and-css

How to access site running apache server over lan without internet connection

nothing to be done for running your wamp sites to another computer. 1. first turn off the firewall. 2. Set Put Online in wamp by clcking in wamp icon at near to clock.

Finally run your browser in another computer and type http:\ip address or computer name e.g. http:\192.168.1.100

Can't concat bytes to str

f.write(plaintext)
f.write("\n".encode("utf-8"))

Running JAR file on Windows

PreScript: If your prompt appears and disappears immediately, the reason it does so is that your program gets executed and auto shut. Try putting a scanner in the end to terminate and it'll keep your prompt waiting for input before terminating. (Or use delay maybe)

Was in the very same situation, where running .jar from cmd was working fine, but double clicking did nothing.

Solution: Open any text editor and write the command line: java -jar Example.jar Save the file as a .bat file. Run this bat file to get the needed output.

Taking it one step forward, you can convert this bat file to exe file using a simple GUI tool like Bat To Exe Converter.

Now you can share your .jar as a distribution in .exe file which anyone can use just make sure you keep all the files together. (Especially the .jar and .bat file cause .bat is only a cmd prompt)(How it feels logical)

I am fairly new to development and learning a lot. Please excuse for any mistakes if committed. Suggestions are welcome.

React eslint error missing in props validation

I know this answer is ridiculous, but consider just disabling this rule until the bugs are worked out or you've upgraded your tooling:

/* eslint-disable react/prop-types */ // TODO: upgrade to latest eslint tooling

Or disable project-wide in your eslintrc:

"rules": {
  "react/prop-types": "off"
}

How to determine whether a substring is in a different string

You can also try find() method. It determines if string str occurs in string, or in a substring of string.

str1 = "please help me out so that I could solve this"
str2 = "please help me out"

if (str1.find(str2)>=0):
  print("True")
else:
  print ("False")

fetch gives an empty response body

Try to use response.json():

fetch('http://example.com/api/node', {
  mode: "no-cors",
  method: "GET",
  headers: {
    "Accept": "application/json"
  }
}).then((response) => {
  console.log(response.json()); // null
  return dispatch({
    type: "GET_CALL",
    response: response.json()
  });
})
.catch(error => { console.log('request failed', error); });

How to build a JSON array from mysql database

Use this

$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');

while($row = mysql_fetch_array($sql_results))
{
    $subArray[location_id]=$row['location'];  //location_id is key and $row['location'] is value which come fron database.
    $subArray[x]=$row['x'];
    $subArray[y]=$row['y'];


 $array[] =  $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';

Can a local variable's memory be accessed outside its scope?

Your problem has nothing to do with scope. In the code you show, the function main does not see the names in the function foo, so you can't access a in foo directly with this name outside foo.

The problem you are having is why the program doesn't signal an error when referencing illegal memory. This is because C++ standards does not specify a very clear boundary between illegal memory and legal memory. Referencing something in popped out stack sometimes causes error and sometimes not. It depends. Don't count on this behavior. Assume it will always result in error when you program, but assume it will never signal error when you debug.

Can I use if (pointer) instead of if (pointer != NULL)?

I think as a rule of thumb, if your if-expression can be re-written as

const bool local_predicate = *if-expression*;
if (local_predicate) ...

such that it causes NO WARNINGS, then THAT should be the preferred style for the if-expression. (I know I get warnings when I assign an old C BOOL (#define BOOL int) to a C++ bool, let alone pointers.)

WPF: Setting the Width (and Height) as a Percentage Value

I use two methods for relative sizing. I have a class called Relative with three attached properties To, WidthPercent and HeightPercent which is useful if I want an element to be a relative size of an element anywhere in the visual tree and feels less hacky than the converter approach - although use what works for you, that you're happy with.

The other approach is rather more cunning. Add a ViewBox where you want relative sizes inside, then inside that, add a Grid at width 100. Then if you add a TextBlock with width 10 inside that, it is obviously 10% of 100.

The ViewBox will scale the Grid according to whatever space it has been given, so if its the only thing on the page, then the Grid will be scaled out full width and effectively, your TextBlock is scaled to 10% of the page.

If you don't set a height on the Grid then it will shrink to fit its content, so it'll all be relatively sized. You'll have to ensure that the content doesn't get too tall, i.e. starts changing the aspect ratio of the space given to the ViewBox else it will start scaling the height as well. You can probably work around this with a Stretch of UniformToFill.

Struct with template variables in C++

template <typename T>
struct array {
  size_t x;
  T *ary;
};

How to convert Base64 String to javascript file object like as from file input form?

I had a very similar requirement (importing a base64 encoded image from an external xml import file. After using xml2json-light library to convert to a json object, I was able to leverage insight from cuixiping's answer above to convert the incoming b64 encoded image to a file object.

const imgName = incomingImage['FileName'];
const imgExt = imgName.split('.').pop();
let mimeType = 'image/png';
if (imgExt.toLowerCase() !== 'png') {
    mimeType = 'image/jpeg';
}
const imgB64 = incomingImage['_@ttribute'];
const bstr = atob(imgB64);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
  u8arr[n] = bstr.charCodeAt(n);
}
const file = new File([u8arr], imgName, {type: mimeType});

My incoming json object had two properties after conversion by xml2json-light: FileName and _@ttribute (which was b64 image data contained in the body of the incoming element.) I needed to generate the mime-type based on the incoming FileName extension. Once I had all the pieces extracted/referenced from the json object, it was a simple task (using cuixiping's supplied code reference) to generate the new File object which was completely compatible with my existing classes that expected a file object generated from the browser element.

Hope this helps connects the dots for others.

How to print the contents of RDD?

If you're running this on a cluster then println won't print back to your context. You need to bring the RDD data to your session. To do this you can force it to local array and then print it out:

linesWithSessionId.toArray().foreach(line => println(line))

Export to CSV via PHP

I personally use this function to create CSV content from any array.

function array2csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}

Then you can make your user download that file using something like:

function download_send_headers($filename) {
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download  
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}

Usage example:

download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($array);
die();

css to make bootstrap navbar transparent

Add the bg-transparent class to the navbar.

<div class="bg-primary">
    <div class="navbar navbar-dark bg-transparent">
         ...
    </div>
</div>

Receive JSON POST with PHP

Quite late.
It seems, (OP) had already tried all the answers given to him.
Still if you (OP) were not receiving what had been passed to the ".PHP" file, error could be, incorrect URL.
Check whether you are calling the correct ".PHP" file.
(spelling mistake or capital letter in URL)
and most important
Check whether your URL has "s" (secure) after "http".
Example:

"http://yourdomain.com/read_result.php"

should be

"https://yourdomain.com/read_result.php"

or either way.
add or remove the "s" to match your URL.

How can I disable a tab inside a TabControl?

Assume that you have these controls:

TabControl with name tcExemple.

TabPages with names tpEx1 and tpEx2.

Try it:

Set DrawMode of your TabPage to OwnerDrawFixed; After InitializeComponent(), make sure that tpEx2 is not enable by adding this code:

((Control)tcExemple.TabPages["tpEx2").Enabled = false;

Add to Selection tcExemple event the code below:

private void tcExemple_Selecting(object sender, TabControlCancelEventArgs e)
    {
        if (!((Control)e.TabPage).Enabled)
        {
            e.Cancel = true;
        }
    }

Attach to DrawItem event of tcExemple this code:

private void tcExemple_DrawItem(object sender, DrawItemEventArgs e)
    {
        TabPage page = tcExemple.TabPages[e.Index];
        if (!((Control)page).Enabled)
        {
            using (SolidBrush brush = new SolidBrush(SystemColors.GrayText))
            {
                e.Graphics.DrawString(page.Text, page.Font, brush, e.Bounds);
            }
        }
        else
        {
            using (SolidBrush brush = new SolidBrush(page.ForeColor))
            {
                e.Graphics.DrawString(page.Text, page.Font, brush, e.Bounds);
            }
        }
    }

It will make the second tab non-clickable.

Saving and Reading Bitmaps/Images from Internal memory in Android

/**
 * Created by Ilya Gazman on 3/6/2016.
 */
public class ImageSaver {

    private String directoryName = "images";
    private String fileName = "image.png";
    private Context context;
    private boolean external;

    public ImageSaver(Context context) {
        this.context = context;
    }

    public ImageSaver setFileName(String fileName) {
        this.fileName = fileName;
        return this;
    }

    public ImageSaver setExternal(boolean external) {
        this.external = external;
        return this;
    }

    public ImageSaver setDirectoryName(String directoryName) {
        this.directoryName = directoryName;
        return this;
    }

    public void save(Bitmap bitmapImage) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(createFile());
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @NonNull
    private File createFile() {
        File directory;
        if(external){
            directory = getAlbumStorageDir(directoryName);
        }
        else {
            directory = context.getDir(directoryName, Context.MODE_PRIVATE);
        }
        if(!directory.exists() && !directory.mkdirs()){
            Log.e("ImageSaver","Error creating directory " + directory);
        }

        return new File(directory, fileName);
    }

    private File getAlbumStorageDir(String albumName) {
        return new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), albumName);
    }

    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    public static boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }

    public Bitmap load() {
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(createFile());
            return BitmapFactory.decodeStream(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

Usage

  • To save:

    new ImageSaver(context).
            setFileName("myImage.png").
            setDirectoryName("images").
            save(bitmap);
    
  • To load:

    Bitmap bitmap = new ImageSaver(context).
            setFileName("myImage.png").
            setDirectoryName("images").
            load();
    

Edit:

Added ImageSaver.setExternal(boolean) to support saving to external storage based on googles example.

Automatically plot different colored lines

If all vectors have equal size, create a matrix and plot it. Each column is plotted with a different color automatically Then you can use legend to indicate columns:

data = randn(100, 5);

figure;
plot(data);

legend(cellstr(num2str((1:size(data,2))')))

Or, if you have a cell with kernels names, use

legend(names)

How do I flush the cin buffer?

I prefer:

cin.clear();
fflush(stdin);

There's an example where cin.ignore just doesn't cut it, but I can't think of it at the moment. It was a while ago when I needed to use it (with Mingw).

However, fflush(stdin) is undefined behavior according to the standard. fflush() is only meant for output streams. fflush(stdin) only seems to work as expected on Windows (with GCC and MS compilers at least) as an extension to the C standard.

So, if you use it, your code isn't going to be portable.

See Using fflush(stdin).

Also, see http://ubuntuforums.org/showpost.php?s=9129c7bd6e5c8fd67eb332126b59b54c&p=452568&postcount=1 for an alternative.

Writing Unicode text to a text file?

In Python 2.6+, you could use io.open() that is default (builtin open()) on Python 3:

import io

with io.open(filename, 'w', encoding=character_encoding) as file:
    file.write(unicode_text)

It might be more convenient if you need to write the text incrementally (you don't need to call unicode_text.encode(character_encoding) multiple times). Unlike codecs module, io module has a proper universal newlines support.

What are Unwind segues for and how do you use them?

In a Nutshell

An unwind segue (sometimes called exit segue) can be used to navigate back through push, modal or popover segues (as if you popped the navigation item from the navigation bar, closed the popover or dismissed the modally presented view controller). On top of that you can actually unwind through not only one but a series of push/modal/popover segues, e.g. "go back" multiple steps in your navigation hierarchy with a single unwind action.

When you perform an unwind segue, you need to specify an action, which is an action method of the view controller you want to unwind to.

Objective-C:

- (IBAction)unwindToThisViewController:(UIStoryboardSegue *)unwindSegue
{
}

Swift:

@IBAction func unwindToThisViewController(segue: UIStoryboardSegue) {
}

The name of this action method is used when you create the unwind segue in the storyboard. Furthermore, this method is called just before the unwind segue is performed. You can get the source view controller from the passed UIStoryboardSegue parameter to interact with the view controller that initiated the segue (e.g. to get the property values of a modal view controller). In this respect, the method has a similar function as the prepareForSegue: method of UIViewController.

iOS 8 update: Unwind segues also work with iOS 8's adaptive segues, such as Show and Show Detail.

An Example

Let us have a storyboard with a navigation controller and three child view controllers:

enter image description here

From Green View Controller you can unwind (navigate back) to Red View Controller. From Blue you can unwind to Green or to Red via Green. To enable unwinding you must add the special action methods to Red and Green, e.g. here is the action method in Red:

Objective-C:

@implementation RedViewController

- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue
{
}

@end

Swift:

@IBAction func unwindToRed(segue: UIStoryboardSegue) {
}

After the action method has been added, you can define the unwind segue in the storyboard by control-dragging to the Exit icon. Here we want to unwind to Red from Green when the button is pressed:

enter image description here

You must select the action which is defined in the view controller you want to unwind to:

enter image description here

You can also unwind to Red from Blue (which is "two steps away" in the navigation stack). The key is selecting the correct unwind action.

Before the the unwind segue is performed, the action method is called. In the example I defined an unwind segue to Red from both Green and Blue. We can access the source of the unwind in the action method via the UIStoryboardSegue parameter:

Objective-C:

- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue
{
    UIViewController* sourceViewController = unwindSegue.sourceViewController;

    if ([sourceViewController isKindOfClass:[BlueViewController class]])
    {
        NSLog(@"Coming from BLUE!");
    }
    else if ([sourceViewController isKindOfClass:[GreenViewController class]])
    {
        NSLog(@"Coming from GREEN!");
    }
}

Swift:

@IBAction func unwindToRed(unwindSegue: UIStoryboardSegue) {
    if let blueViewController = unwindSegue.sourceViewController as? BlueViewController {
        println("Coming from BLUE")
    }
    else if let redViewController = unwindSegue.sourceViewController as? RedViewController {
        println("Coming from RED")
    }
}

Unwinding also works through a combination of push/modal segues. E.g. if I added another Yellow view controller with a modal segue, we could unwind from Yellow all the way back to Red in a single step:

enter image description here

Unwinding from Code

When you define an unwind segue by control-dragging something to the Exit symbol of a view controller, a new segue appears in the Document Outline:

enter image description here

Selecting the segue and going to the Attributes Inspector reveals the "Identifier" property. Use this to give a unique identifier to your segue:

enter image description here

After this, the unwind segue can be performed from code just like any other segue:

Objective-C:

[self performSegueWithIdentifier:@"UnwindToRedSegueID" sender:self];

Swift:

performSegueWithIdentifier("UnwindToRedSegueID", sender: self)

presentViewController and displaying navigation bar

It is true that if you present a view controller modally on the iPhone, it will always be presented full screen no matter how you present it on the top view controller of a navigation controller or any other way around. But you can always show the navigation bar with the following workaround way:

Rather than presenting that view controller modally present a navigation controller modally with its root view controller set as the view controller you want:

MyViewController *myViewController = [[MyViewController alloc] initWithNibName:nil bundle:nil];
UINavigationController *navigationController = 
    [[UINavigationController alloc] initWithRootViewController:myViewController];

//now present this navigation controller modally 
[self presentViewController:navigationController
                   animated:YES
                   completion:^{

                        }];

You should see a navigation bar when your view is presented modally.

How to put img inline with text

Please make use of the code below to display images inline:

<img style='vertical-align:middle;' src='somefolder/icon.gif'>
<div style='vertical-align:middle; display:inline;'>
Your text here
</div>

Getting CheckBoxList Item values

This ended up being quite simple. chBoxListTables.Item[i] is a string value, and an explicit convert allowed it to be loaded into a variable. The following code works:

private void btnGO_Click(object sender, EventArgs e)
{
    for (int i = 0; i < chBoxListTables.Items.Count; i++)
    {
          if (chBoxListTables.GetItemChecked(i))
        {
            string str = (string)chBoxListTables.Items[i];
            MessageBox.Show(str);
        }
    }
}

How good is Java's UUID.randomUUID?

The original generation scheme for UUIDs was to concatenate the UUID version with the MAC address of the computer that is generating the UUID, and with the number of 100-nanosecond intervals since the adoption of the Gregorian calendar in the West. By representing a single point in space (the computer) and time (the number of intervals), the chance of a collision in values is effectively nil.

What is boilerplate code?

Boilerplate is what good programmers avoid: repetition.

Managing SSH keys within Jenkins for Git

This works for me if you have config and the private key file in the /Jenkins/.ssh/ you need to chown (change owner) for these 2 files then restart jenkins in order for the jenkins instance to read these 2 files.

TextFX menu is missing in Notepad++

Plugins -> Plugin Manager -> Show Plugin Manager -> Setting -> Check mark On Force HTTP instead of HTTPS for downloading Plugin List & Use development plugin list (may contain untested, unvalidated or un-installable plugins). -> OK.

SELECT * WHERE NOT EXISTS

You can do a LEFT JOIN and assert the joined column is NULL.

Example:

SELECT * FROM employees a LEFT JOIN eotm_dyn b on (a.joinfield=b.joinfield) WHERE b.name IS NULL

htaccess - How to force the client's browser to clear the cache?

You can not force the browsers to clear the cache.

Your .html file seems to be re-loaded sooner as it expires after 10 days. What you have to do is to update your .html file and move all your files to a new folder such as version-2/ or append a version identifier to each file such as mypicture-2.jpg. Then you reference these new files in your .html file and the browser will load them again because the location changed.

How to enable Google Play App Signing

I had to do following:

  1. Create an app in google play console enter image description here

2.Go to App releases -> Manage production -> Create release

3.Click continue on Google Play App Signing enter image description here

4.Create upload certificate by running "keytool -genkey -v -keystore c:\path\to\cert.keystore -alias uploadKey -keyalg RSA -keysize 2048 -validity 10000"

5.Sign your apk with generated certificate (c:\path\to\cert.keystore)

6.Upload signed apk in App releases -> Manage production -> Edit release

7.By uploading apk, certificate generated in step 4 has been added to App Signing certificates and became your signing cert for all future builds.

How to check if image exists with given url?

if it doesnt exist load default image or handle error

$('img[id$=imgurl]').load(imgurl, function(response, status, xhr) {
    if (status == "error") 
        $(this).attr('src', 'images/DEFAULT.JPG');
    else
        $(this).attr('src', imgurl);
    });

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

You have mentioned "user" twice in your FROM clause. You must provide a table alias to at least one mention so each mention of user. can be pinned to one or the other instance:

FROM article INNER JOIN section
ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user **AS user1** ON article.author\_id = **user1**.id
LEFT JOIN user **AS user2** ON article.modified\_by = **user2**.id
WHERE article.id = '1'

(You may need something different - I guessed which user is which, but the SQL engine won't guess.)

Also, maybe you only needed one "user". Who knows?

Deploying Java webapp to Tomcat 8 running in Docker container

Tomcat will only extract the war which is copied to webapps directory. Change Dockerfile as below:

FROM tomcat:8.0.20-jre8
COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war

You might need to access the url as below unless you have specified the webroot

http://192.168.59.103:8888/myapp/getData

Get absolute path to workspace directory in Jenkins Pipeline plugin

For me WORKSPACE was a valid property of the pipeline itself. So when I handed over this to a Groovy method as parameter context from the pipeline script itself, I was able to access the correct value using "... ${context.WORKSPACE} ..."

(on Jenkins 2.222.3, Build Pipeline Plugin 1.5.8, Pipeline: Nodes and Processes 2.35)

Replacing column values in a pandas DataFrame

You can edit a subset of a dataframe by using loc:

df.loc[<row selection>, <column selection>]

In this case:

w.loc[w.female != 'female', 'female'] = 0
w.loc[w.female == 'female', 'female'] = 1

Interop type cannot be embedded

Expanding on Jon's correct answer.

The problem here is that your are combining the new "Embed Interop Types" (or NoPIA) feature with use of a class type. The "Embed Interop Types" feature works by essentially statically linking in all of the types from a PIA (Primary Interop Assembly) into the referencing assembly removing the overhead of deploying it.

This feature works great for most types in a PIA but it does have restrictions. One of them is that you cannot embed classes (it's a servicing issue). Misha has a detailed blog article on why this is not allowed

Why do we use $rootScope.$broadcast in AngularJS?

What does $rootScope.$broadcast do?

It broadcasts the message to respective listeners all over the angular app, a very powerful means to transfer messages to scopes at different hierarchical level(be it parent , child or siblings)

Similarly, we have $rootScope.$emit, the only difference is the former is also caught by $scope.$on while the latter is caught by only $rootScope.$on .

refer for examples :- http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

How to use a switch case 'or' in PHP

Try

switch($value) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

Changing an element's ID with jQuery

Your syntax is incorrect, you should pass the value as the second parameter:

jQuery(this).prev("li").attr("id","newId");

Stock ticker symbol lookup API

You can use the "Company Search" operation in the Company Fundamentals API here: http://www.mergent.com/servius/

How to create nested directories using Mkdir in Golang?

An utility method like the following can be used to solve this.

import (
  "os"
  "path/filepath"
  "log"
)

func ensureDir(fileName string) {
  dirName := filepath.Dir(fileName)
  if _, serr := os.Stat(dirName); serr != nil {
    merr := os.MkdirAll(dirName, os.ModePerm)
    if merr != nil {
        panic(merr)
    }
  }
}



func main() {
  _, cerr := os.Create("a/b/c/d.txt")
  if cerr != nil {
    log.Fatal("error creating a/b/c", cerr)
  }
  log.Println("created file in a sub-directory.")
}

What is the significance of 1/1/1753 in SQL Server?

Your great great great great great great great grandfather should upgrade to SQL Server 2008 and use the DateTime2 data type, which supports dates in the range: 0001-01-01 through 9999-12-31.

What is the maximum length of a Push Notification alert text?

Apple Updated Doc:

Each remote notification includes a payload. The payload contains information about how the system should alert the user as well as any custom data you provide. The maximum size allowed for a notification payload depends on which provider API you employ. When using the HTTP/2 provider API, maximum payload size is 4096 bytes. Using the legacy binary interface, maximum payload size is 2048 bytes. Apple Push Notification service (APNs) refuses any notification that exceeds the maximum size.

Static methods in Python?

Python Static methods can be created in two ways.

  1. Using staticmethod()

    class Arithmetic:
        def add(x, y):
            return x + y
    # create add static method
    Arithmetic.add = staticmethod(Arithmetic.add)
    
    print('Result:', Arithmetic.add(15, 10))
    

Output:

Result: 25

  1. Using @staticmethod

    class Arithmetic:
    
    # create add static method
    @staticmethod
    def add(x, y):
        return x + y
    
    print('Result:', Arithmetic.add(15, 10))
    

Output:

Result: 25

Failed Apache2 start, no error log

I also just ran in to a similar problem, that is service apache2 reload fails but prints no useful information. This is because the script in /etc/init.d/apache (on Debian, at least) eats the output of the apache2ctl configtest command it runs to sanitize the Apache config.

An easy solution to get a more meaningful explanation for the failure is to run apache2ctl configtest again yourself, which will print the (hopefully useful) error messages to the console.

Eclipse Error: "Failed to connect to remote VM"

Have you setup the remote VM to accept connections?

java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=10000,suspend=n yourServer

Is there a firewall in the way?

Are you specifying the correct host / port?

Are you connected to a VPN?

Add more than one parameter in Twig path

You can pass as many arguments as you want, separating them by commas:

{{ path('_files_manage', {project: project.id, user: user.id}) }}

Convert all first letter to upper case, rest lower for each word

One of the possible solution you might be interested in. Traversing an array of chars from right to left and vise versa in one loop.

public static string WordsToCapitalLetter(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            throw new ArgumentException("value");
        }

        int inputValueCharLength = value.Length;
        var valueAsCharArray = value.ToCharArray();

        int min = 0;
        int max = inputValueCharLength - 1;

        while (max > min)
        {
            char left = value[min];
            char previousLeft = (min == 0) ? left : value[min - 1];

            char right = value[max];
            char nextRight = (max == inputValueCharLength - 1) ? right : value[max - 1];

            if (char.IsLetter(left) && !char.IsUpper(left) && char.IsWhiteSpace(previousLeft))
            {
                valueAsCharArray[min] = char.ToUpper(left);
            }

            if (char.IsLetter(right) && !char.IsUpper(right) && char.IsWhiteSpace(nextRight))
            {
                valueAsCharArray[max] = char.ToUpper(right);
            }

            min++;
            max--;
        }

        return new string(valueAsCharArray);
    }

Adding item to Dictionary within loop

As per my understanding you want data in dictionary as shown below:

key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3

for this you can use list for each dictionary keys:

case_list = {}
for entry in entries_list:
    if key in case_list:
        case_list[key1].append(value)
    else:
        case_list[key1] = [value]

Get multiple elements by Id

Here is a function I came up with

function getElementsById(elementID){
    var elementCollection = new Array();
    var allElements = document.getElementsByTagName("*");
    for(i = 0; i < allElements.length; i++){
        if(allElements[i].id == elementID)
            elementCollection.push(allElements[i]);

    }
    return elementCollection;
}

Apparently there is a convention supported by prototype, and probably other major JavaScript libraries.

However, I have come to discover that dollar sign function has become the more-or-less de facto shortcut to document.getElementById(). Let’s face it, we all use document.getElementById() a lot. Not only does it take time to type, but it adds bytes to your code as well.

here is the function from prototype:

function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (Object.isString(element))
    element = document.getElementById(element);
  return Element.extend(element);
}

[Source]

cartesian product in pandas

Minimal code needed for this one. Create a common 'key' to cartesian merge the two:

df1['key'] = 0
df2['key'] = 0

df_cartesian = df1.merge(df2, how='outer')

.includes() not working in Internet Explorer

I had the same problem when working in Angular 5. In order to make it work directly without writing a polyfill yourself, just add the following line to polyfills.ts file:

import "core-js/es7/array"

Also, tsconfig.json lib section might be relevant:

"lib": [
  "es2017",
  "dom"
],

Postgresql: error "must be owner of relation" when changing a owner object

This solved my problem : Sample alter table statement to change the ownership.

ALTER TABLE databasechangelog OWNER TO arwin_ash;
ALTER TABLE databasechangeloglock OWNER TO arwin_ash;

File Upload ASP.NET MVC 3.0

file upload using formdata

.cshtml file

     var files = $("#file").get(0).files;
     if (files.length > 0) {
                data.append("filekey", files[0]);}


   $.ajax({
            url: '@Url.Action("ActionName", "ControllerName")', type: "POST", processData: false,
            data: data, dataType: 'json',
            contentType: false,
            success: function (data) {
                var response=data.JsonData;               
            },
            error: function (er) { }

        });

Server side code

if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    var pic = System.Web.HttpContext.Current.Request.Files["filekey"];
                    HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic);
                    var fileName = Path.GetFileName(filebase.FileName);


                    string fileExtension = System.IO.Path.GetExtension(fileName);

                    if (fileExtension == ".xls" || fileExtension == ".xlsx")
                    {
                        string FileName = Guid.NewGuid().GetHashCode().ToString("x");
                        string dirLocation = Server.MapPath("~/Content/PacketExcel/");
                        if (!Directory.Exists(dirLocation))
                        {
                            Directory.CreateDirectory(dirLocation);
                        }
                        string fileLocation = Server.MapPath("~/Content/PacketExcel/") + FileName + fileExtension;
                        filebase.SaveAs(fileLocation);
}
}

How to export data from Excel spreadsheet to Sql Server 2008 table

From your SQL Server Management Studio, you open Object Explorer, go to your database where you want to load the data into, right click, then pick Tasks > Import Data.

This opens the Import Data Wizard, which typically works pretty well for importing from Excel. You can pick an Excel file, pick what worksheet to import data from, you can choose what table to store it into, and what the columns are going to be. Pretty flexible indeed.

You can run this as a one-off, or you can store it as a SQL Server Integration Services (SSIS) package into your file system, or into SQL Server itself, and execute it over and over again (even scheduled to run at a given time, using SQL Agent).

Update: yes, yes, yes, you can do all those things you keep asking - have you even tried at least once to run that wizard??

OK, here it comes - step by step:

Step 1: pick your Excel source

enter image description here

Step 2: pick your SQL Server target database

enter image description here

Step 3: pick your source worksheet (from Excel) and your target table in your SQL Server database; see the "Edit Mappings" button!

enter image description here

Step 4: check (and change, if needed) your mappings of Excel columns to SQL Server columns in the table:

enter image description here

Step 5: if you want to use it later on, save your SSIS package to SQL Server:

enter image description here

Step 6: - success! This is on a 64-bit machine, works like a charm - just do it!!

adding line break

string[] abcd = obj.show(); 

Response.Write(string.join("</br>", abcd));

SQL Stored Procedure set variables using SELECT

select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
    from table1
    where IsCurrent = 1

How to display length of filtered ng-repeat data

Since AngularJS 1.3 you can use aliases:

item in items | filter:x as results

and somewhere:

<span>Total {{results.length}} result(s).</span>

From docs:

You can also provide an optional alias expression which will then store the intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message when a filter is active on the repeater, but the filtered result set is empty.

For example: item in items | filter:x as results will store the fragment of the repeated items as results, but only after the items have been processed through the filter.

What's the idiomatic syntax for prepending to a short python list?

Lets go over 4 methods

  1. Using insert()
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l.insert(0, 5)
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using [] and +
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = [5] + l
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using Slicing
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l[:0] = [5]
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using collections.deque.appendleft()
>>> 
>>> from collections import deque
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = deque(l)
>>> l.appendleft(5)
>>> l = list(l)
>>> l
[5, 0, 1, 2, 3, 4]
>>> 

Javascript add leading zeroes to date

function formatDate(jsDate){
  // add leading zeroes to jsDate when days or months are < 10.. 
  // i.e.
  //     formatDate(new Date("1/3/2013")); 
  // returns
  //    "01/03/2103"
  ////////////////////
  return (jsDate.getDate()<10?("0"+jsDate.getDate()):jsDate.getDate()) + "/" + 
      ((jsDate.getMonth()+1)<10?("0"+(jsDate.getMonth()+1)):(jsDate.getMonth()+1)) + "/" + 
      jsDate.getFullYear();
}

what is the difference between GROUP BY and ORDER BY in sql

It should be noted GROUP BY is not always necessary as (at least in PostgreSQL, and likely in other SQL variants) you can use ORDER BY with a list and you can still use ASC or DESC per column...

SELECT name_first, name_last, dob 
FROM those_guys 
ORDER BY name_last ASC, name_first ASC, dob DESC;

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

Getting data from Yahoo Finance

Since Yahoo Finances API was disabled, I found Alpha Vantage API

This a stock query sample that I'm using with Excel's Power Query:

https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=15min&outputsize=full&apikey=demo

Validate form field only on submit or user input

You can use angularjs form state form.$submitted. Initially form.$submitted value will be false and will became true after successful form submit.

Hiding axis text in matplotlib plots

If you want to hide just the axis text keeping the grid lines:

frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])

Doing set_visible(False) or set_ticks([]) will also hide the grid lines.

How do I sum values in a column that match a given condition using pandas?

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :

df[df['a']==1]['b'].sum()

or you can also try :

sum(df[df['a']==1]['b'])

Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())

How to get table list in database, using MS SQL 2008?

This should give you a list of all the tables in your database

SELECT Distinct TABLE_NAME FROM information_schema.TABLES

So you can use it similar to your database check.

If NOT EXISTS(SELECT Distinct TABLE_NAME FROM information_schema.TABLES Where TABLE_NAME = 'Your_Table')
BEGIN
    --CREATE TABLE Your_Table
END
GO

What CSS selector can be used to select the first div within another div

If we can assume that the H1 is always going to be there, then

div h1+div {...}

but don't be afraid to specify the id of the content div:

#content h1+div {...}

That's about as good as you can get cross-browser right now without resorting to a JavaScript library like jQuery. Using h1+div ensures that only the first div after the H1 gets the style. There are alternatives, but they rely on CSS3 selectors, and thus won't work on most IE installs.

Could not find server 'server name' in sys.servers. SQL Server 2014

At first check out that your linked server is in the list by this query

select name from sys.servers

If it not exists then try to add to the linked server

EXEC sp_addlinkedserver @server = 'SERVER_NAME' --or may be server ip address

After that login to that linked server by

EXEC sp_addlinkedsrvlogin 'SERVER_NAME'
                         ,'false'
                         ,NULL
                         ,'USER_NAME'
                         ,'PASSWORD'

Then you can do whatever you want ,treat it like your local server

exec [SERVER_NAME].[DATABASE_NAME].dbo.SP_NAME @sample_parameter

Finally you can drop that server from linked server list by

sp_dropserver 'SERVER_NAME', 'droplogins'

If it will help you then please upvote.

what is trailing whitespace and how can I handle this?

Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline.

In your posted question, there is one extra space after try:, and there are 12 extra spaces after pass:

>>> post_text = '''\
...             if self.tagname and self.tagname2 in list1:
...                 try: 
...                     question = soup.find("div", "post-text")
...                     title = soup.find("a", "question-hyperlink")
...                     self.list2.append(str(title)+str(question)+url)
...                     current += 1
...                 except AttributeError:
...                     pass            
...             logging.info("%s questions passed, %s questions \
...                 collected" % (count, current))
...             count += 1
...         return self.list2
... '''
>>> for line in post_text.splitlines():
...     if line.rstrip() != line:
...         print(repr(line))
... 
'                try: '
'                    pass            '

See where the strings end? There are spaces before the lines (indentation), but also spaces after.

Use your editor to find the end of the line and backspace. Many modern text editors can also automatically remove trailing whitespace from the end of the line, for example every time you save a file.

In C#, how to check if a TCP port is available?

If I'm not very much mistaken, you can use System.Network.whatever to check.

However, this will always incur a race condition.

The canonical way of checking is try to listen on that port. If you get an error that port wasn't open.

I think this is part of why bind() and listen() are two separate system calls.

MVVM Passing EventArgs As Command Parameter

What I do is to use InvokeCommandAction to bind the control loaded event to a command in the view model, give the control a x:Name in Xaml and pass as CommandParameter, then in said loaded command hook view model handlers up to the events where I need to get the event args.

Force an SVN checkout command to overwrite current files

Pull from the repository to a new directory, then rename the old one to old_crufty, and the new one to my_real_webserver_directory, and you're good to go.

If your intention is that every single file is in SVN, then this is a good way to test your theory. If your intention is that some files are not in SVN, then use Brian's copy/paste technique.

Get UTC time in seconds

You say you're using:

time.asctime(time.localtime(date_in_seconds_from_bash))

where date_in_seconds_from_bash is presumably the output of date +%s.

The time.localtime function, as the name implies, gives you local time.

If you want UTC, use time.gmtime() rather than time.localtime().

As JamesNoonan33's answer says, the output of date +%s is timezone invariant, so date +%s is exactly equivalent to date -u %s. It prints the number of seconds since the "epoch", which is 1970-01-01 00:00:00 UTC. The output you show in your question is entirely consistent with that:

date -u
Thu Jul 3 07:28:20 UTC 2014

date +%s
1404372514   # 14 seconds after "date -u" command

date -u +%s
1404372515   # 15 seconds after "date -u" command

how to change text in Android TextView

:) Your using the thread in a wrong way. Just do the following:

private void runthread()
{

splashTread = new Thread() {
            @Override
            public void run() {
                try {
                    synchronized(this){

                        //wait 5 sec
                        wait(_splashTime);
                    }

                } catch(InterruptedException e) {}
                finally {
                    //call the handler to set the text
                }
            }
        };

        splashTread.start(); 
}

That's it.

Flask example with POST

Here is the example in which you can easily find the way to use Post,GET method and use the same way to add other curd operations as well..

#libraries to include

import os
from flask import request, jsonify
from app import app, mongo
import logger
ROOT_PATH = os.environ.get('ROOT_PATH')<br>
@app.route('/get/questions/', methods=['GET', 'POST','DELETE', 'PATCH'])
    def question():
    # request.args is to get urls arguments 


    if request.method == 'GET':
        start = request.args.get('start', default=0, type=int)
        limit_url = request.args.get('limit', default=20, type=int)
        questions = mongo.db.questions.find().limit(limit_url).skip(start);
        data = [doc for doc in questions]
        return jsonify(isError= False,
                    message= "Success",
                    statusCode= 200,
                    data= data), 200

# request.form to get form parameter

    if request.method == 'POST':
        average_time = request.form.get('average_time')
        choices = request.form.get('choices')
        created_by = request.form.get('created_by')
        difficulty_level = request.form.get('difficulty_level')
        question = request.form.get('question')
        topics = request.form.get('topics')

    ##Do something like insert in DB or Render somewhere etc. it's up to you....... :)

How to encode text to base64 in python

Use the below code:

import base64

#Taking input through the terminal.
welcomeInput= raw_input("Enter 1 to convert String to Base64, 2 to convert Base64 to String: ") 

if(int(welcomeInput)==1 or int(welcomeInput)==2):
    #Code to Convert String to Base 64.
    if int(welcomeInput)==1:
        inputString= raw_input("Enter the String to be converted to Base64:") 
        base64Value = base64.b64encode(inputString.encode())
        print "Base64 Value = " + base64Value
    #Code to Convert Base 64 to String.
    elif int(welcomeInput)==2:
        inputString= raw_input("Enter the Base64 value to be converted to String:") 
        stringValue = base64.b64decode(inputString).decode('utf-8')
        print "Base64 Value = " + stringValue

else:
    print "Please enter a valid value."

How to Truncate a string in PHP to the word closest to a certain number of characters?

Keep in mind whenever you're splitting by "word" anywhere that some languages such as Chinese and Japanese do not use a space character to split words. Also, a malicious user could simply enter text without any spaces, or using some Unicode look-alike to the standard space character, in which case any solution you use may end up displaying the entire text anyway. A way around this may be to check the string length after splitting it on spaces as normal, then, if the string is still above an abnormal limit - maybe 225 characters in this case - going ahead and splitting it dumbly at that limit.

One more caveat with things like this when it comes to non-ASCII characters; strings containing them may be interpreted by PHP's standard strlen() as being longer than they really are, because a single character may take two or more bytes instead of just one. If you just use the strlen()/substr() functions to split strings, you may split a string in the middle of a character! When in doubt, mb_strlen()/mb_substr() are a little more foolproof.

How do I detect if software keyboard is visible on Android Device or not?

If you support apis for AndroidR in your app then you can use the below method.

In kotlin :
    var imeInsets = view.rootWindowInsets.getInsets(Type.ime()) 
    if (imeInsets.isVisible) { 
        view.translationX = imeInsets.bottom 
    }

Note: This is only available for the AndroidR and below android version needs to follow some of other answer or i will update it for that.

Converting String to Double in Android

I would do it this way:

try {
  txtProt = (EditText) findViewById(R.id.Protein); // Same
  p = txtProt.getText().toString(); // Same
  protein = Double.parseDouble(p); // Make use of autoboxing.  It's also easier to read.
} catch (NumberFormatException e) {
  // p did not contain a valid double
}

EDIT: "the program force closes immediately without leaving any info in the logcat"

I don't know bout not leaving information in the logcat output, but a force-close generally means there's an uncaught exception - like a NumberFormatException.

Datagrid binding in WPF

Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
    <DataGrid.Columns>                
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

CSS :: child set to change color on parent hover, but changes also when hovered itself

If you don't care about supporting old browsers, you can use :not() to exclude that element:

.parent:hover span:not(:hover) {
    border: 10px solid red;
}

Demo: http://jsfiddle.net/vz9A9/1/

If you do want to support them, the I guess you'll have to either use JavaScript or override the CSS properties again:

.parent span:hover {
    border: 10px solid green;
}

How do I use Spring Boot to serve static content located in Dropbox folder?

  • OS: Win 10
  • Spring Boot: 2.1.2

I wanted to serve static content from c:/images

Adding this property worked for me:

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:///C:/images/

I found the original value of the property in the Spring Boot Doc Appendix A

This will make c:/images/image.jpg to be accessible as http://localhost:8080/image.jpg

Ideal way to cancel an executing AsyncTask

Our global AsyncTask class variable

LongOperation LongOperationOdeme = new LongOperation();

And KEYCODE_BACK action which interrupt AsyncTask

   @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LongOperationOdeme.cancel(true);
        }
        return super.onKeyDown(keyCode, event);
    }

It works for me.

HTML: how to force links to open in a new tab, not new window

I didn't try this but I think it works in all browsers:

target="_parent"

How to redirect the output of print to a TXT file

Redirect sys.stdout to an open file handle and then all printed output goes to a file:

import sys
filename  = open("outputfile",'w')
sys.stdout = filename
print "Anything printed will go to the output file"

What is a stack trace, and how can I use it to debug my application errors?

To add on to what Rob has mentioned. Setting break points in your application allows for the step-by-step processing of the stack. This enables the developer to use the debugger to see at what exact point the method is doing something that was unanticipated.

Since Rob has used the NullPointerException (NPE) to illustrate something common, we can help to remove this issue in the following manner:

if we have a method that takes parameters such as: void (String firstName)

In our code we would want to evaluate that firstName contains a value, we would do this like so: if(firstName == null || firstName.equals("")) return;

The above prevents us from using firstName as an unsafe parameter. Therefore by doing null checks before processing we can help to ensure that our code will run properly. To expand on an example that utilizes an object with methods we can look here:

if(dog == null || dog.firstName == null) return;

The above is the proper order to check for nulls, we start with the base object, dog in this case, and then begin walking down the tree of possibilities to make sure everything is valid before processing. If the order were reversed a NPE could potentially be thrown and our program would crash.

How can I increase the JVM memory?

When starting the JVM, two parameters can be adjusted to suit your memory needs :

-Xms<size>

specifies the initial Java heap size and

-Xmx<size>

the maximum Java heap size.

http://www.rgagnon.com/javadetails/java-0131.html

Open web in new tab Selenium + Python

You can achieve the opening/closing of a tab by the combination of keys COMMAND + T or COMMAND + W (OSX). On other OSs you can use CONTROL + T / CONTROL + W.

In selenium you can emulate such behavior. You will need to create one webdriver and as many tabs as the tests you need.

Here it is the code.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.google.com/")

#open tab
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't') 
# You can use (Keys.CONTROL + 't') on other OSs

# Load a page 
driver.get('http://stackoverflow.com/')
# Make the tests...

# close the tab
# (Keys.CONTROL + 'w') on other OSs.
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 'w') 


driver.close()

How to set java.net.preferIPv4Stack=true at runtime?

well,

I used System.setProperty("java.net.preferIPv4Stack" , "true"); and it works from JAVA, but it doesn't work on JBOSS AS7.

Here is my work around solution,

Add the below line to the end of the file ${JBOSS_HOME}/bin/standalone.conf.bat (just after :JAVA_OPTS_SET )

set "JAVA_OPTS=%JAVA_OPTS% -Djava.net.preferIPv4Stack=true"

Note: restart JBoss server

Naming convention - underscore in C++ and C# variables

Now the notation using "this" as in this.foobarbaz is acceptable for C# class member variables. It replaces the old "m_" or just "__" notation. It does make the code more readable because there is no doubt what is being reference.

Grant Select on a view not base table when base table is in a different database

You can grant permissions on a view and not the base table. This is one of the reasons people like using views.

Have a look here: GRANT Object Permissions (Transact-SQL)

What does a question mark represent in SQL queries?

I don't think that has any meaning in SQL. You might be looking at Prepared Statements in JDBC or something. In that case, the question marks are placeholders for parameters to the statement.

How to get all Windows service names starting with a common word?

Using PowerShell, you can use the following

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name

This will show a list off all services which displayname starts with "NATION-".

You can also directly stop or start the services;

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service

or simply

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service

How to declare a global variable in C++

You declare the variable as extern in a common header:

//globals.h
extern int x;

And define it in an implementation file.

//globals.cpp
int x = 1337;

You can then include the header everywhere you need access to it.

I suggest you also wrap the variable inside a namespace.

How to read all of Inputstream in Server Socket JAVA

int c;
    String raw = "";
    do {
        c = inputstream.read();
        raw+=(char)c;
    } while(inputstream.available()>0);

InputStream.available() shows the available bytes only after one byte is read, hence do .. while

Save child objects automatically using JPA Hibernate

in your setChilds, you might want to try looping thru the list and doing something like

child.parent = this;

you also should set up the cascade on the parent to the appropriate values.

How to use enums in C++

If you are still using C++03 and want to use enums, you should be using enums inside a namespace. Eg:

namespace Daysofweek{
enum Days {Saturday, Sunday, Tuesday,Wednesday, Thursday, Friday};
}

You can use the enum outside the namespace like,

Daysofweek::Days day = Daysofweek::Saturday;

if (day == Daysofweek::Saturday)
{
    std::cout<<"Ok its Saturday";
}

Extract a part of the filepath (a directory) in Python

This is what I did to extract the piece of the directory:

for path in file_list:
  directories = path.rsplit('\\')
  directories.reverse()
  line_replace_add_directory = line_replace+directories[2]

Thank you for your help.

Trim a string in C

You can use the standard isspace() function in ctype.h to achieve this. Simply compare the beginning and end characters of your character array until both ends no longer have spaces.

"spaces" include:

' ' (0x20) space (SPC)

'\t' (0x09) horizontal tab (TAB)

'\n' (0x0a) newline (LF)

'\v' (0x0b) vertical tab (VT)

'\f' (0x0c) feed (FF)

'\r' (0x0d) carriage return (CR)

although there is no function which will do all of the work for you, you will have to roll your own solution to compare each side of the given character array repeatedly until no spaces remain.

Edit:

Since you have access to C++, Boost has a trim implementation waiting for you to make your life a lot easier.

Convert double to float in Java

First of all, the fact that the value in the database is a float does not mean that it also fits in a Java float. Float is short for floating point, and floating point types of various precisions exist. Java types float and double are both floating point types of different precision. In a database both are called FLOAT. Since double has a higher precision than float, it probably is a better idea not to cast your value to a float, because you might lose precision.

You might also use BigDecimal, which represent an arbitrary-precision number.

How to set limits for axes in ggplot2 R plots?

Basically you have two options

scale_x_continuous(limits = c(-5000, 5000))

or

coord_cartesian(xlim = c(-5000, 5000)) 

Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.

You can also use the shorthand function xlim (or ylim), which like the first option removes data points outside of the given range:

+ xlim(-5000, 5000)

For more information check the description of coord_cartesian.

The RStudio cheatsheet for ggplot2 makes this quite clear visually. Here is a small section of that cheatsheet:

enter image description here

Distributed under CC BY.

What does Visual Studio mean by normalize inconsistent line endings?

It means that, for example, some of your lines of text with a <Carriage Return><Linefeed> (the Windows standard), and some end with just a <Linefeed> (the Unix standard).

If you click 'yes' these the end-of-lines in your source file will be converted to have all the same format.

This won't make any difference to the compiler (because end-of-lines count as mere whitespace), but it might make some difference to other tools (e.g. the 'diff' on your version control system).

How to access shared folder without giving username and password

You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'

The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.

Best way to compare 2 XML documents in Java

Using JExamXML with java application

    import com.a7soft.examxml.ExamXML;
    import com.a7soft.examxml.Options;

       .................

       // Reads two XML files into two strings
       String s1 = readFile("orders1.xml");
       String s2 = readFile("orders.xml");

       // Loads options saved in a property file
       Options.loadOptions("options");

       // Compares two Strings representing XML entities
       System.out.println( ExamXML.compareXMLString( s1, s2 ) );

Fastest way to add an Item to an Array

For those who didn't know what next, just add new module file and put @jor code (with my little hacked, supporting 'nothing' array) below.

Module ArrayExtension
    <Extension()> _
    Public Sub Add(Of T)(ByRef arr As T(), item As T)
        If arr IsNot Nothing Then
            Array.Resize(arr, arr.Length + 1)
            arr(arr.Length - 1) = item
        Else
            ReDim arr(0)
            arr(0) = item
        End If

    End Sub
End Module

How to check for empty value in Javascript?

Comment as an answer:

if (timetime[0].value)

This works because any variable in JS can be evaluated as a boolean, so this will generally catch things that are empty, null, or undefined.

Reset Excel to default borders

I had this issue, grid lines appeared to be missing on some cells.

Took me awhile to figure out that the color of those cells were white. I clicked format cell, pattern and then selected "no color" (instead of white) The the grid lines were visible again.

I hope this helps others as it took me a while to figure out why.

Java 8 List<V> into Map<K, V>

Map<String,Choice> map=list.stream().collect(Collectors.toMap(Choice::getName, s->s));

Even serves this purpose for me,

Map<String,Choice> map=  list1.stream().collect(()-> new HashMap<String,Choice>(), 
            (r,s) -> r.put(s.getString(),s),(r,s) -> r.putAll(s));

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

You have a view model to which your view is strongly typed => use strongly typed helpers:

<%= Html.DropDownListFor(
    x => x.SelectedAccountId, 
    new SelectList(Model.Accounts, "Value", "Text")
) %>

Also notice that I use a SelectList for the second argument.

And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:

public ActionResult AccountTransaction()
{
    var accounts = Services.AccountServices.GetAccounts(false);
    var viewModel = new AccountTransactionView
    {
        Accounts = accounts.Select(a => new SelectListItem
        {
            Text = a.Description,
            Value = a.AccountId.ToString()
        })
    };
    return View(viewModel);
}

Type.GetType("namespace.a.b.ClassName") returns null

Type.GetType("namespace.qualified.TypeName") only works when the type is found in either mscorlib.dll or the currently executing assembly.

If neither of those things are true, you'll need an assembly-qualified name:

Type.GetType("namespace.qualified.TypeName, Assembly.Name")

What is the default value for Guid?

The default value for a GUID is empty. (eg: 00000000-0000-0000-0000-000000000000)

This can be invoked using Guid.Empty or new Guid()

If you want a new GUID, you use Guid.NewGuid()

Find and replace - Add carriage return OR Newline

Just a minor word of warning... a lot of environments use, or need, "\r\n" and not just "\n". I ran into an issue with Visual Studio not matching my regex string at the end of the line because I left off the "\r" of "\r\n", so my string couldn't match with a missing invisible character.

So, if you are doing a find, or a replace, consider the "\r".

For a little more detail on "\r" and "\n", see: https://stackoverflow.com/a/3451192/4427457

JQuery Bootstrap Multiselect plugin - Set a value as selected in the multiselect dropdown

I got a better solution from jquery-multiselect documentation.

var data = [101,102];

$("#data").multiSelect('deselect_all');

$("#data").multiSelect("select",data);

How do I replace a character at a particular index in JavaScript?

You can extend the string type to include the inset method:

_x000D_
_x000D_
String.prototype.append = function (index,value) {_x000D_
  return this.slice(0,index) + value + this.slice(index);_x000D_
};_x000D_
_x000D_
var s = "New string";_x000D_
alert(s.append(4,"complete "));
_x000D_
_x000D_
_x000D_

Then you can call the function:

No server in Eclipse; trying to install Tomcat

Eclipse IDE for Java Developers 'Servers' doesn't exist. Therefore download correct Eclipse IDE. It is Eclipse IDE for Enterprise Java Developers(Eclipse IDE for Java EE Developers). This way is easy.

How can I add JAR files to the web-inf/lib folder in Eclipse?

add the jar to WEB-INF/lib from file structure refresh the project, you should see the jar now visible under the WEB-INF/lib folder.

this is the best solution that worked for me

Remove characters from a String in Java

Kotlin Solution

Kotlin has a built-in function for this, removeSuffix (Documentation)

var text = "filename.xml"
text = text.removeSuffix(".xml") // "filename"

If the suffix does not exist in the string, it just returns the original

var text = "not_a_filename"
text = text.removeSuffix(".xml") // "not_a_filename"

You can also check out removePrefix and removeSurrounding which are similar

Access cell value of datatable

You can also try (first cell in 4th column):

dt.Rows[0][3]

Maven2: Missing artifact but jars are in place

I used the below code in pom.xml to download the jar

<dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.FINAL</version>
</dependency>

But in the .m2 folder under validation folder...the jar didnt get downloaded. I am not sure about the issue. But i downloaded the same jar from maven official website and placed in the .m2 folder under respective folder and cleaned the project. The error gone and it started working now.

Difference between npx and npm?

Simple Definition:

npm - Javascript package manager

npx - Execute npm package binaries

What issues should be considered when overriding equals and hashCode in Java?

equals() method is used to determine the equality of two objects.

as int value of 10 is always equal to 10. But this equals() method is about equality of two objects. When we say object, it will have properties. To decide about equality those properties are considered. It is not necessary that all properties must be taken into account to determine the equality and with respect to the class definition and context it can be decided. Then the equals() method can be overridden.

we should always override hashCode() method whenever we override equals() method. If not, what will happen? If we use hashtables in our application, it will not behave as expected. As the hashCode is used in determining the equality of values stored, it will not return the right corresponding value for a key.

Default implementation given is hashCode() method in Object class uses the internal address of the object and converts it into integer and returns it.

public class Tiger {
  private String color;
  private String stripePattern;
  private int height;

  @Override
  public boolean equals(Object object) {
    boolean result = false;
    if (object == null || object.getClass() != getClass()) {
      result = false;
    } else {
      Tiger tiger = (Tiger) object;
      if (this.color == tiger.getColor()
          && this.stripePattern == tiger.getStripePattern()) {
        result = true;
      }
    }
    return result;
  }

  // just omitted null checks
  @Override
  public int hashCode() {
    int hash = 3;
    hash = 7 * hash + this.color.hashCode();
    hash = 7 * hash + this.stripePattern.hashCode();
    return hash;
  }

  public static void main(String args[]) {
    Tiger bengalTiger1 = new Tiger("Yellow", "Dense", 3);
    Tiger bengalTiger2 = new Tiger("Yellow", "Dense", 2);
    Tiger siberianTiger = new Tiger("White", "Sparse", 4);
    System.out.println("bengalTiger1 and bengalTiger2: "
        + bengalTiger1.equals(bengalTiger2));
    System.out.println("bengalTiger1 and siberianTiger: "
        + bengalTiger1.equals(siberianTiger));

    System.out.println("bengalTiger1 hashCode: " + bengalTiger1.hashCode());
    System.out.println("bengalTiger2 hashCode: " + bengalTiger2.hashCode());
    System.out.println("siberianTiger hashCode: "
        + siberianTiger.hashCode());
  }

  public String getColor() {
    return color;
  }

  public String getStripePattern() {
    return stripePattern;
  }

  public Tiger(String color, String stripePattern, int height) {
    this.color = color;
    this.stripePattern = stripePattern;
    this.height = height;

  }
}

Example Code Output:

bengalTiger1 and bengalTiger2: true 
bengalTiger1 and siberianTiger: false 
bengalTiger1 hashCode: 1398212510 
bengalTiger2 hashCode: 1398212510 
siberianTiger hashCode: –1227465966

Visual Studio C# IntelliSense not automatically displaying

Steps to fix are:

      Tools
      Import and Export Settings
      Reset all settings
      Back up your config
      Select your environment settings and finish

How to use (install) dblink in PostgreSQL?

# or even faster copy paste answer if you have sudo on the host 
sudo su - postgres  -c "psql template1 -c 'CREATE EXTENSION IF NOT EXISTS \"dblink\";'"

Remove the last line from a file in Bash

awk 'NR>1{print buf}{buf = $0}'

Essentially, this code says the following:

For each line after the first, print the buffered line

for each line, reset the buffer

The buffer is lagged by one line, hence you end up printing lines 1 to n-1

addEventListener for keydown on Canvas

encapsulate all of your js code within a window.onload function. I had a similar issue. Everything is loaded asynchronously in javascript so some parts load quicker than others, including your browser. Putting all of your code inside the onload function will ensure everything your code will need from the browser will be ready to use before attempting to execute.

How Long Does it Take to Learn Java for a Complete Newbie?

For java, you also need to learn how to use an IDE and setup your environment and this kind of this to make java works...

Then for J2ME, you'll need to know things about embedded/mobile systems....

10 weeks with the tutorials would be ok but it also depends on what you're going to do in your j2me course...

I would go head first in a j2me tutorial (assuming you know a minimum concerning variables functions and OO)...

good luck...

What version of Java is running in Eclipse?

String runtimeVersion = System.getProperty("java.runtime.version");

should return you a string along the lines of:

1.5.0_01-b08

That's the version of Java that Eclipse is using to run your code which is not necessarily the same version that's being used to run Eclipse itself.

Strip first and last character from C string

Further to @pmg's answer, note that you can do both operations in one statement:

char mystr[] = "Nmy stringP";
char *p = mystr;
p++[strlen(p)-1] = 0;

This will likely work as expected but behavior is undefined in C standard.

RuntimeWarning: DateTimeField received a naive datetime

The problem is not in Django settings, but in the date passed to the model. Here's how a timezone-aware object looks like:

>>> from django.utils import timezone
>>> import pytz
>>> timezone.now()
datetime.datetime(2013, 11, 20, 20, 8, 7, 127325, tzinfo=pytz.UTC)

And here's a naive object:

>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2013, 11, 20, 20, 9, 26, 423063)

So if you are passing email date anywhere (and it eventually gets to some model), just use Django's now(). If not, then it's probably an issue with an existing package that fetches date without timezone and you can patch the package, ignore the warning or set USE_TZ to False.

C++11 reverse range-based for-loop

If you can use range v3 , you can use the reverse range adapter ranges::view::reverse which allows you to view the container in reverse.

A minimal working example:

#include <iostream>
#include <vector>
#include <range/v3/view.hpp>

int main()
{
    std::vector<int> intVec = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    for (auto const& e : ranges::view::reverse(intVec)) {
        std::cout << e << " ";   
    }
    std::cout << std::endl;

    for (auto const& e : intVec) {
        std::cout << e << " ";   
    }
    std::cout << std::endl;
}

See DEMO 1.

Note: As per Eric Niebler, this feature will be available in C++20. This can be used with the <experimental/ranges/range> header. Then the for statement will look like this:

for (auto const& e : view::reverse(intVec)) {
       std::cout << e << " ";   
}

See DEMO 2

Python extending with - using super() Python 3 vs Python 2

Just to have a simple and complete example for Python 3, which most people seem to be using now.

class MySuper(object):
    def __init__(self,a):
        self.a = a

class MySub(MySuper):
    def __init__(self,a,b):
        self.b = b
        super().__init__(a)

my_sub = MySub(42,'chickenman')
print(my_sub.a)
print(my_sub.b)

gives

42
chickenman

How to smooth a curve in the right way?

If you are plotting time series graph and if you have used mtplotlib for drawing graphs then use median method to smooth-en the graph

smotDeriv = timeseries.rolling(window=20, min_periods=5, center=True).median()

where timeseries is your set of data passed you can alter windowsize for more smoothining.

Counting unique / distinct values by group in a data frame

Few years old .. although had similar requirement and ended up writing my own solution. Applying here:

 x<-data.frame(
 
 "Name"=c("Amy","Jack","Jack","Dave","Amy","Jack","Tom","Larry","Tom","Dave","Jack","Tom","Amy","Jack"),
 "OrderNo"=c(12,14,16,11,12,16,19,22,19,11,17,20,23,16)
)

table(sub("~.*","",unique(paste(x$Name,x$OrderNo,sep="~",collapse=NULL))))

  Amy  Dave  Jack Larry   Tom
    2     1     3     1     2

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

you may use this - https://github.com/chanakyachatterjee/JSLightGrid ..JSLightGrid. have a look.. I found this one really very useful. Good performance, very light weight, all important browser friendly and fluid in itself, so you don't really need bootstrap for the grid.

Returning Arrays in Java

You have a couple of basic misconceptions about Java:

I want it to return the array without having to explicitly tell the console to print.

1) Java does not work that way. Nothing ever gets printed implicitly. (Java does not support an interactive interpreter with a "repl" loop ... like Python, Ruby, etc.)

2) The "main" doesn't "return" anything. The method signature is:

  public static void main(String[] args)

and the void means "no value is returned". (And, sorry, no you can't replace the void with something else. If you do then the java command won't recognize the "main" method.)

3) If (hypothetically) you did want your "main" method to return something, and you altered the declaration to allow that, then you still would need to use a return statement to tell it what value to return. Unlike some language, Java does not treat the value of the last statement of a method as the return value for the method. You have to use a return statement ...

Restricting JTextField input to Integers

I used to use the Key Listener for this but I failed big time with that approach. Best approach as recommended already is to use a DocumentFilter. Below is a utility method I created for building textfields with only number input. Just beware that it'll also take single '.' character as well since it's usable for decimal input.

public static void installNumberCharacters(AbstractDocument document) {
        document.setDocumentFilter(new DocumentFilter() {
            @Override
            public void insertString(FilterBypass fb, int offset,
                    String string, AttributeSet attr)
                    throws BadLocationException {
                try {
                    if (string.equals(".")
                            && !fb.getDocument()
                                    .getText(0, fb.getDocument().getLength())
                                    .contains(".")) {
                        super.insertString(fb, offset, string, attr);
                        return;
                    }
                    Double.parseDouble(string);
                    super.insertString(fb, offset, string, attr);
                } catch (Exception e) {
                    Toolkit.getDefaultToolkit().beep();
                }

            }

            @Override
            public void replace(FilterBypass fb, int offset, int length,
                    String text, AttributeSet attrs)
                    throws BadLocationException {
                try {
                    if (text.equals(".")
                            && !fb.getDocument()
                                    .getText(0, fb.getDocument().getLength())
                                    .contains(".")) {
                        super.insertString(fb, offset, text, attrs);
                        return;
                    }
                    Double.parseDouble(text);
                    super.replace(fb, offset, length, text, attrs);
                } catch (Exception e) {
                    Toolkit.getDefaultToolkit().beep();
                }
            }
        });
    }

Powershell command to hide user from exchange address lists

"WARNING: The command completed successfully but no settings of '[user id here]' have been modified."

This warning means the setting was already set like what you want it to be. So it didn't change anything for that object.

Intellij JAVA_HOME variable

In my case I needed a lower JRE, so I had to tell IntelliJ to use a different one in "Platform Settings"

  • Platform Settings > SDKs ( +; )
  • Click the + button to add a new SDK (or rename and load an existing one)
  • Choose the /Contents/Home directory from the appropriate SDK
    (i.e. /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home)

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

Convenient C++ struct initialisation

I know this question is old, but there is a way to solve this until C++20 finally brings this feature from C to C++. What you can do to solve this is use preprocessor macros with static_asserts to check your initialization is valid. (I know macros are generally bad, but here I don't see another way.) See example code below:

#define INVALID_STRUCT_ERROR "Instantiation of struct failed: Type, order or number of attributes is wrong."

#define CREATE_STRUCT_1(type, identifier, m_1, p_1) \
{ p_1 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\

#define CREATE_STRUCT_2(type, identifier, m_1, p_1, m_2, p_2) \
{ p_1, p_2 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\

#define CREATE_STRUCT_3(type, identifier, m_1, p_1, m_2, p_2, m_3, p_3) \
{ p_1, p_2, p_3 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_3) >= (offsetof(type, m_2) + sizeof(identifier.m_2)), INVALID_STRUCT_ERROR);\

#define CREATE_STRUCT_4(type, identifier, m_1, p_1, m_2, p_2, m_3, p_3, m_4, p_4) \
{ p_1, p_2, p_3, p_4 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_3) >= (offsetof(type, m_2) + sizeof(identifier.m_2)), INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_4) >= (offsetof(type, m_3) + sizeof(identifier.m_3)), INVALID_STRUCT_ERROR);\

// Create more macros for structs with more attributes...

Then when you have a struct with const attributes, you can do this:

struct MyStruct
{
    const int attr1;
    const float attr2;
    const double attr3;
};

const MyStruct test = CREATE_STRUCT_3(MyStruct, test, attr1, 1, attr2, 2.f, attr3, 3.);

It's a bit inconvenient, because you need macros for every possible number of attributes and you need to repeat the type and name of your instance in the macro call. Also you cannot use the macro in a return statement, because the asserts come after the initialization.

But it does solve your problem: When you change the struct, the call will fail at compile-time.

If you use C++17, you can even make these macros more strict by forcing the same types, e.g.:

#define CREATE_STRUCT_3(type, identifier, m_1, p_1, m_2, p_2, m_3, p_3) \
{ p_1, p_2, p_3 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_3) >= (offsetof(type, m_2) + sizeof(identifier.m_2)), INVALID_STRUCT_ERROR);\
static_assert(typeid(p_1) == typeid(identifier.m_1), INVALID_STRUCT_ERROR);\
static_assert(typeid(p_2) == typeid(identifier.m_2), INVALID_STRUCT_ERROR);\
static_assert(typeid(p_3) == typeid(identifier.m_3), INVALID_STRUCT_ERROR);\

How to use ClassLoader.getResources() correctly?

The Spring Framework has a class which allows to recursively search through the classpath:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:some/package/name/**/*.xml");

How can I save an image with PIL?

The error regarding the file extension has been handled, you either use BMP (without the dot) or pass the output name with the extension already. Now to handle the error you need to properly modify your data in the frequency domain to be saved as an integer image, PIL is telling you that it doesn't accept float data to save as BMP.

Here is a suggestion (with other minor modifications, like using fftshift and numpy.array instead of numpy.asarray) for doing the conversion for proper visualization:

import sys
import numpy
from PIL import Image

img = Image.open(sys.argv[1]).convert('L')

im = numpy.array(img)
fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im)))

visual = numpy.log(fft_mag)
visual = (visual - visual.min()) / (visual.max() - visual.min())

result = Image.fromarray((visual * 255).astype(numpy.uint8))
result.save('out.bmp')

Does WGET timeout?

According to the man page of wget, there are a couple of options related to timeouts -- and there is a default read timeout of 900s -- so I say that, yes, it could timeout.


Here are the options in question :

-T seconds
--timeout=seconds

Set the network timeout to seconds seconds. This is equivalent to specifying --dns-timeout, --connect-timeout, and --read-timeout, all at the same time.


And for those three options :

--dns-timeout=seconds

Set the DNS lookup timeout to seconds seconds.
DNS lookups that don't complete within the specified time will fail.
By default, there is no timeout on DNS lookups, other than that implemented by system libraries.

--connect-timeout=seconds

Set the connect timeout to seconds seconds.
TCP connections that take longer to establish will be aborted.
By default, there is no connect timeout, other than that implemented by system libraries.

--read-timeout=seconds

Set the read (and write) timeout to seconds seconds.
The "time" of this timeout refers to idle time: if, at any point in the download, no data is received for more than the specified number of seconds, reading fails and the download is restarted.
This option does not directly affect the duration of the entire download.


I suppose using something like

wget -O - -q -t 1 --timeout=600 http://www.example.com/cron/run

should make sure there is no timeout before longer than the duration of your script.

(Yeah, that's probably the most brutal solution possible ^^ )

What does the 'standalone' directive mean in XML?

standalone describes if the current XML document depends on an external markup declaration.

W3C describes its purpose in "Extensible Markup Language (XML) 1.0 (Fifth Edition)":

Disable future dates in jQuery UI Datepicker

you can use the following.

$("#selector").datepicker({
    maxDate: 0
});

Connecting client to server using Socket.io

Have you tried loading the socket.io script not from a relative URL?

You're using:

<script src="socket.io/socket.io.js"></script>

And:

socket.connect('http://127.0.0.1:8080');

You should try:

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

And:

socket.connect('http://localhost:8080');

Switch localhost:8080 with whatever fits your current setup.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).