Programs & Examples On #Square bracket

The symbols "[" and "]", commonly used in programming languages. Please use this tag only if the specific usage of these symbols is a relevant part of the question.

How do I overload the square-bracket operator in C#?

Operators                           Overloadability

+, -, *, /, %, &, |, <<, >>         All C# binary operators can be overloaded.

+, -, !,  ~, ++, --, true, false    All C# unary operators can be overloaded.

==, !=, <, >, <= , >=               All relational operators can be overloaded, 
                                    but only as pairs.

&&, ||                  They can't be overloaded

() (Conversion operator)        They can't be overloaded

+=, -=, *=, /=, %=                  These compound assignment operators can be 
                                    overloaded. But in C#, these operators are
                                    automatically overloaded when the respective
                                    binary operator is overloaded.

=, . , ?:, ->, new, is, as, sizeof  These operators can't be overloaded

    [ ]                             Can be overloaded but not always!

Source of the information

For bracket:

public Object this[int index]
{

}

BUT

The array indexing operator cannot be overloaded; however, types can define indexers, properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indices, but indexer parameters can be declared to be of any type (unlike array indices, which must be integral).

From MSDN

Underscore prefix for property and method names in JavaScript

JSDoc 3 allows you to annotate your functions with the @access private (previously the @private tag) which is also useful for broadcasting your intent to other developers - http://usejsdoc.org/tags-access.html

Basic http file downloading and saving to disk in python?

For Python3+ URLopener is deprecated. And when used you will get error as below:

url_opener = urllib.URLopener() AttributeError: module 'urllib' has no attribute 'URLopener'

So, try:

import urllib.request 
urllib.request.urlretrieve(url, filename)

How to print a certain line of a file with PowerShell?

It's as easy as using select:

Get-Content file.txt | Select -Index (line - 1)

E.g. to get line 5

Get-Content file.txt | Select -Index 4

Or you can use:

(Get-Content file.txt)[4]

How to ignore whitespace in a regular expression subject string?

Addressing Steven's comment to Sam Dufel's answer

Thanks, sounds like that's the way to go. But I just realized that I only want the optional whitespace characters if they follow a newline. So for example, "c\n ats" or "ca\n ts" should match. But wouldn't want "c ats" to match if there is no newline. Any ideas on how that might be done?

This should do the trick:

/c(?:\n\s*)?a(?:\n\s*)?t(?:\n\s*)?s/

See this page for all the different variations of 'cats' that this matches.

You can also solve this using conditionals, but they are not supported in the javascript flavor of regex.

SQL Error with Order By in Subquery

In this example ordering adds no information - the COUNT of a set is the same whatever order it is in!

If you were selecting something that did depend on order, you would need to do one of the things the error message tells you - use TOP or FOR XML

How to connect android wifi to adhoc wifi?

If you specifically want to use an ad hoc wireless network, then Andy's answer seems to be your only option. However, if you just want to share your laptop's internet connection via Wi-fi using any means necessary, then you have at least two more options:

  1. Use your laptop as a router to create a wifi hotspot using Virtual Router or Connectify. A nice set of instructions can be found here.
  2. Use the Wi-fi Direct protocol which creates a direct connection between any devices that support it, although with Android devices support is limited* and with Windows the feature seems likely to be Windows 8 only.

*Some phones with Android 2.3 have proprietary OS extensions that enable Wi-fi Direct (mostly newer Samsung phones), but Android 4 should fully support this (source).

Drawing rotated text on a HTML5 canvas

Posting this in an effort to help others with similar problems. I solved this issue with a five step approach -- save the context, translate the context, rotate the context, draw the text, then restore the context to its saved state.

I think of translations and transforms to the context as manipulating the coordinate grid overlaid on the canvas. By default the origin (0,0) starts in the upper left hand corner of the canvas. X increases from left to right, Y increases from top to bottom. If you make an "L" w/ your index finger and thumb on your left hand and hold it out in front of you with your thumb down, your thumb would point in the direction of increasing Y and your index finger would point in the direction of increasing X. I know it's elementary, but I find it helpful when thinking about translations and rotations. Here's why:

When you translate the context, you move the origin of the coordinate grid to a new location on the canvas. When you rotate the context, think of rotating the "L" you made with your left hand in a clockwise direction the amount indicated by the angle you specify in radians about the origin. When you strokeText or fillText, specify your coordinates in relation to the newly aligned axes. To orient your text so it's readable from bottom to top, you would translate to a position below where you want to start your labels, rotate by -90 degrees and fill or strokeText, offsetting each label along the rotated x axis. Something like this should work:

 context.save();
 context.translate(newx, newy);
 context.rotate(-Math.PI/2);
 context.textAlign = "center";
 context.fillText("Your Label Here", labelXposition, 0);
 context.restore();

.restore() resets the context back to the state it had when you called .save() -- handy for returning things back to "normal".


Shell Script: How to write a string to file and to stdout on console?

You can use >> to print in another file.

echo "hello" >> logfile.txt

How do I compare two Integers?

Use the equals method. Why are you so worried that it's expensive?

How do I iterate through the files in a directory in Java?

For Java 7+, there is also https://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html

Example taken from the Javadoc:

List<Path> listSourceFiles(Path dir) throws IOException {
   List<Path> result = new ArrayList<>();
   try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{c,h,cpp,hpp,java}")) {
       for (Path entry: stream) {
           result.add(entry);
       }
   } catch (DirectoryIteratorException ex) {
       // I/O error encounted during the iteration, the cause is an IOException
       throw ex.getCause();
   }
   return result;
}

How do I copy a range of formula values and paste them to a specific range in another sheet?

How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...

How to keep the spaces at the end and/or at the beginning of a String?

Working well I'm using \u0020

<string name="hi"> Hi \u0020 </string>
<string name="ten"> \u0020 out of 10  </string>
<string name="youHaveScored">\u0020 you have Scored \u0020</string>

Java file

String finalScore = getString(R.string.hi) +name+ getString(R.string.youHaveScored)+score+ getString(R.string.ten);
               Toast.makeText(getApplicationContext(),finalScore,Toast.LENGTH_LONG).show();

Screenshot here Image of Showing Working of this code

Remove Android App Title Bar

Just change the theme in the design view of your activity to NoActionBar like the one here

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

--version is a valid option from JDK 9 and it is not a valid option until JDK 8 hence you get the below:

Unrecognized option: --version
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

You can try installing JDK 9 or any version later and check for java --version it will work.

Alternately, from the installed JDK 9 or later versions you can see from java -help the below two options will be available:

    -version      print product version to the error stream and exit
    --version     print product version to the output stream and exit

where as in JDK 8 you will only have below when you execute java -help

    -version      print product version and exit

I hope it answers your question.

What is the difference between const int*, const int * const, and int const *?

  1. const int* - pointer to constant int object.

You can change the value of the pointer; you can not change the value of the int object, the pointer points to.


  1. const int * const - constant pointer to constant int object.

You can not change the value of the pointer nor the value of the int object the pointer points to.


  1. int const * - pointer to constant int object.

This statement is equivalent to 1. const int* - You can change the value of the pointer but you can not change the value of the int object, the pointer points to.


Actually, there is a 4th option:

  1. int * const - constant pointer to int object.

You can change the value of the object the pointer points to but you can not change the value of the pointer itself. The pointer will always point to the same int object but this value of this int object can be changed.


If you want to determine a certain type of C or C++ construct you can use the Clockwise/Spiral Rule made by David Anderson; but not to confuse with Anderson`s Rule made by Ross J. Anderson, which is something quite distinct.

Difference between PCDATA and CDATA in DTD

From here (Google is your friend):

In a DTD, PCDATA and CDATA are used to assert something about the allowable content of elements and attributes, respectively. In an element's content model, #PCDATA says that the element contains (may contain) "any old text." (With exceptions as noted below.) In an attribute's declaration, CDATA is one sort of constraint you can put on the attribute's allowable values (other sorts, all mutually exclusive, include ID, IDREF, and NMTOKEN). An attribute whose allowable values are CDATA can (like PCDATA in an element) contain "any old text."

A potentially really confusing issue is that there's another "CDATA," also referred to as marked sections. A marked section is a portion of element (#PCDATA) content delimited with special strings: to close it. If you remember that PCDATA is "parsed character data," a CDATA section is literally the same thing, without the "parsed." Parsers transmit the content of a marked section to downstream applications without hiccupping every time they encounter special characters like < and &. This is useful when you're coding a document that contains lots of those special characters (like scripts and code fragments); it's easier on data entry, and easier on reading, than the corresponding entity reference.

So you can infer that the exception to the "any old text" rule is that PCDATA cannot include any of these unescaped special characters, UNLESS they fall within the scope of a CDATA marked section.

When to use MongoDB or other document oriented database systems?

Who needs distributed, sharded forums? Maybe Facebook, but unless you're creating a Facebook-competitor, just use Mysql, Postgres or whatever you are most comfortable with. If you want to try MongoDB, ok, but don't expect it to do magic for you. It'll have its quirks and general nastiness, just as everything else, as I'm sure you've already discovered if you really have been working on it already.

Sure, MongoDB may be hyped and seem easy on the surface, but you'll run into problems which more mature products have already overcome. Don't be lured so easily, but rather wait until "nosql" matures, or dies.

Personally, I think "nosql" will wither and die from fragmentation, as there are no set standards (almost by definition). So I will not personally bet on it for any long-term projects.

Only thing that can save "nosql" in my book, is if it can integrate into Ruby or similar languages seamlessly, and make the language "persistent", almost without any overhead in coding and design. That may come to pass, but I'll wait until then, not now, AND it needs to be more mature of course.

Btw, why are you creating a forum from scratch? There are tons of open source forums which can be tweaked to fit most requirements, unless you really are creating The Next Generation of Forums (which I doubt).

Ubuntu - Run command on start-up with "sudo"

Nice answers. You could also set Jobs (i.e., commands) with "Crontab" for more flexibility (which provides different options to run scripts, loggin the outputs, etc.), although it requires more time to be understood and set properly:

Using '@reboot' you can Run a command once, at startup.

Wrapping up: run $ sudo crontab -e -u root

And add a line at the end of the file with your command as follows:

@reboot sudo searchd

C# How to change font of a label

You need to create a new Font

mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

How to get margin value of a div in plain JavaScript?

The properties on the style object are only the styles applied directly to the element (e.g., via a style attribute or in code). So .style.marginTop will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).

To get the current calculated style of the object, you use either the currentStyle property (Microsoft) or the getComputedStyle function (pretty much everyone else).

Example:

var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);

display("Current marginTop: " + style.marginTop);

Fair warning: What you get back may not be in pixels. For instance, if I run the above on a p element in IE9, I get back "1em".

Live Copy | Source

How to send a JSON object using html form data

The accepted answer is out of date; nowadays you can simply add enctype="application/json" to your form tag and the browser will jsonify the data automatically.

The spec for this behavior is here: https://www.w3.org/TR/html-json-forms/

How to resolve git stash conflict without commit?

According to git stash questions, after fixing the conflict, git add <file> is the right course of action.

It was after reading this comment that I understood that the changes are automatically added to the index (by design). That's why git add <file> completes the conflict resolution process.

iReport not starting using JRE 8

don't uninstall anything. a system with multiple versions of java works just fine. and you don't need to update your environment varables (e.g. java_home, path, etc..).

yes, ireports 3.6.1 needs java 7 (doesn't work with java 8).

all you have to do is edit C:\Program Files\Jaspersoft\iReport-nb-3.6.1\etc\ireport.conf:

# default location of JDK/JRE, can be overridden by using --jdkhome <dir> switch
jdkhome="C:/Program Files/Java/jdk1.7.0_45"

on linux (no spaces and standard file paths) its that much easier. keep your java 8 for other interesting projects...

Android, getting resource ID from string?

In MonoDroid / Xamarin.Android you can do:

 var resourceId = Resources.GetIdentifier("icon", "drawable", PackageName);

But since GetIdentifier it's not recommended in Android - you can use Reflection like this:

 var resourceId = (int)typeof(Resource.Drawable).GetField("icon").GetValue(null);

where I suggest to put a try/catch or verify the strings you are passing.

loading json data from local file into React JS

If you have couple of json files:

import data from 'sample.json';

If you were to dynamically load one of the many json file, you might have to use a fetch instead:

fetch(`${fileName}.json`)
  .then(response => response.json())
  .then(data => console.log(data))

How to draw border on just one side of a linear layout?

As an alternative (if you don't want to use background), you can easily do it by making a view as follows:

<View
    android:layout_width="2dp"
    android:layout_height="match_parent"
    android:background="#000000" />

For having a right border only, place this after the layout (where you want to have the border):

<View
    android:layout_width="2dp"
    android:layout_height="match_parent"
    android:background="#000000" />

For having a left border only, place this before the layout (where you want to have the border):

Worked for me...Hope its of some help....

Quickly create a large file on a Linux system

I don't think you're going to get much faster than dd. The bottleneck is the disk; writing hundreds of GB of data to it is going to take a long time no matter how you do it.

But here's a possibility that might work for your application. If you don't care about the contents of the file, how about creating a "virtual" file whose contents are the dynamic output of a program? Instead of open()ing the file, use popen() to open a pipe to an external program. The external program generates data whenever it's needed. Once the pipe is open, it acts just like a regular file in that the program that opened the pipe can fseek(), rewind(), etc. You'll need to use pclose() instead of close() when you're done with the pipe.

If your application needs the file to be a certain size, it will be up to the external program to keep track of where in the "file" it is and send an eof when the "end" has been reached.

How do I get the current mouse screen coordinates in WPF?

You may use combination of TimerDispatcher (WPF Timer analog) and Windows "Hooks" to catch cursor position from operational system.

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetCursorPos(out POINT pPoint);

Point is a light struct. It contains only X, Y fields.

    public MainWindow()
    {
        InitializeComponent();

        DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
        dt.Tick += new EventHandler(timer_tick);
        dt.Interval = new TimeSpan(0,0,0,0, 50);
        dt.Start();
    }

    private void timer_tick(object sender, EventArgs e)
    {
        POINT pnt;
        GetCursorPos(out pnt);
        current_x_box.Text = (pnt.X).ToString();
        current_y_box.Text = (pnt.Y).ToString();
    }

    public struct POINT
    {
        public int X;
        public int Y;

        public POINT(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    }

This solution is also resolving the problem with too often or too infrequent parameter reading so you can adjust it by yourself. But remember about WPF method overload with one arg which is representing ticks not milliseconds.

TimeSpan(50); //ticks

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You're talking about template literals.

They allow for both multiline strings and string interpolation.

Multiline strings:

_x000D_
_x000D_
console.log(`foo_x000D_
bar`);_x000D_
// foo_x000D_
// bar
_x000D_
_x000D_
_x000D_

String interpolation:

_x000D_
_x000D_
var foo = 'bar';_x000D_
console.log(`Let's meet at the ${foo}`);_x000D_
// Let's meet at the bar
_x000D_
_x000D_
_x000D_

Using Mockito, how do I verify a method was a called with a certain argument?

First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:

ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");

Then inject the mock into m_orderSvc and call your method.

m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work(); 

Finally, verify that the mock was called properly:

verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");

Passing command line arguments in Visual Studio 2010?

Visual Studio 2015:

Project => Your Application Properties. Each argument can be separated using space. If you have a space in between for the same argument, put double quotes as shown in the example below.

enter image description here

        static void Main(string[] args)
        {
            if(args == null || args.Length == 0)
            {
                Console.WriteLine("Please specify arguments!");
            }
            else
            {
                Console.WriteLine(args[0]);     // First
                Console.WriteLine(args[1]);     // Second Argument
            }
        }

Adding Text to DataGridView Row Header

yes you can

DataGridView1.Rows[0].HeaderCell.Value = "my text";

Passing struct to function

You need to specify a type on person:

void addStudent(struct student person) {
...
}

Also, you can typedef your struct to avoid having to type struct every time you use it:

typedef struct student{
...
} student_t;

void addStudent(student_t person) {
...
}

How to grep (search) committed code in the Git history

Jeet's answer works in PowerShell.

git grep -n <regex> $(git rev-list --all)

The following displays all files, in any commit, that contain a password.

# Store intermediate result
$result = git grep -n "password" $(git rev-list --all)

# Display unique file names
$result | select -unique { $_ -replace "(^.*?:)|(:.*)", "" }

Java: Retrieving an element from a HashSet

First of all convert your set to Array. Then, get item by index of array .

Set uniqueItem = new HashSet() ;
uniqueItem.add("0");
uniqueItem.add("1");
uniqueItem.add("0");

Object[] arrayItem = uniqueItem.toArray(); 
for(int i = 0; i < uniqueItem.size();i++){
    System.out.println("Item "+i+" "+arrayItem[i].toString());
}

Add a link to an image in a css style sheet

You can not do that...

via css the URL you put on the background-image is just for the image.

Via HTML you have to add the href for your hyperlink in this way:

<a href="http://home.com" id="logo">Your logo</a>

With text-indent and some other css you can adjust your a element to show just the image and clicking on it you will go to your link.


EDIT:

I'm here again to show you and explain why my solution is much better:

<a href="http://home.com" id="logo">Your logo name</a>

This block of HTML is SEO friendly because you have some text inside your link!

How to style it with css:

#logo {
  background-image: url(images/logo.png);
  display: block;
  margin: 0 auto;
  text-indent: -9999px;
  width: 981px;
  height: 180px;
}

Then if you don't care about SEO good to choose the other answer.

How do I put variables inside javascript strings?

util.format does this.

It will be part of v0.5.3 and can be used like this:

var uri = util.format('http%s://%s%s', 
      (useSSL?'s':''), apiBase, path||'/');

How to get 30 days prior to current date?

I use date.js. It handles this easily and takes care of all the leap-year nastiness.

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified his example to do this here: http://jsfiddle.net/QLfMU/116/

How to insert spaces/tabs in text using HTML/CSS

In cases wherein the width/height of the space is beyond &nbsp; I usually use:

For horizontal spacer:

<span style="display:inline-block; width: YOURWIDTH;"></span>

For vertical spacer:

<span style="display:block; height: YOURHEIGHT;"></span>

How can I get a side-by-side diff when I do "git diff"?

I use colordiff.

On Mac OS X, install it with

$ sudo port install colordiff

On Linux is possibly apt get install colordiff or something like that, depending on your distro.

Then:

$ git difftool --extcmd="colordiff -ydw" HEAD^ HEAD

Or create an alias

$ git alias diffy "difftool --extcmd=\"colordiff -ydw\""

Then you can use it

$ git diffy HEAD^ HEAD

I called it "diffy" because diff -y is the side-by-side diff in unix. Colordiff also adds colors, that are nicer. In the option -ydw, the y is for the side-by-side, the w is to ignore whitespaces, and the d is to produce the minimal diff (usually you get a better result as diff)

How do you add an ActionListener onto a JButton in Java

I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?

VHDL - How should I create a clock in a testbench?

My favoured technique:

signal clk : std_logic := '0'; -- make sure you initialise!
...
clk <= not clk after half_period;

I usually extend this with a finished signal to allow me to stop the clock:

clk <= not clk after half_period when finished /= '1' else '0';

Gotcha alert: Care needs to be taken if you calculate half_period from another constant by dividing by 2. The simulator has a "time resolution" setting, which often defaults to nanoseconds... In which case, 5 ns / 2 comes out to be 2 ns so you end up with a period of 4ns! Set the simulator to picoseconds and all will be well (until you need fractions of a picosecond to represent your clock time anyway!)

Bash script prints "Command Not Found" on empty lines

for executing that you must provide full path of that for example

/home/Manuel/mywrittenscript

Git copy changes from one branch to another

This is 2 step process

  • git checkout BranchB ( destination branch is BranchB, so we need the head on this branch)
  • git merge BranchA (it will merge BranchB with BranchA. Here you have merged code in branch B)

If you want to push your branch code to remote repo then do

  • git push origin master (it will push your BranchB code to remote repo)

JavaScript Adding an ID attribute to another created Element

Since id is an attribute don't create an id element, just do this:

myPara.setAttribute("id", "id_you_like");

How do I upload a file with the JS fetch API?

The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using

data.append('fileData', {
  uri : pickerResponse.uri,
  type: pickerResponse.type,
  name: pickerResponse.fileName
 });

Fetch seems to recognize that format and send the file where the uri is pointing.

Slidedown and slideup layout with animation

I had a similar requirement in the app I am working on. And, I found a third-party library which does a slide-up, slide-down and slide-right in Android.

Refer to the link for more details: https://github.com/mancj/SlideUp-Android

To set up the library(copied from the ReadMe portion of its Github page on request):

Get SlideUp library

Add the JitPack repository to your build file. Add it in your root build.gradle at the end of repositories:

allprojects {
  repositories {
    ...
    maven { url 'https://jitpack.io' }
    maven { url "https://maven.google.com" } // or google() in AS 3.0
  }
}

Add the dependency (in the Module gradle)

dependencies {
    compile 'com.github.mancj:SlideUp-Android:2.2.1'
    compile 'ru.ztrap:RxSlideUp2:2.x.x' //optional, for reactive listeners based on RxJava-2
    compile 'ru.ztrap:RxSlideUp:1.x.x' //optional, for reactive listeners based on RxJava
}

To add the SlideUp into your project, follow these three simple steps:

Step 1:

create any type of layout

<LinearLayout
  android:id="@+id/slideView"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

Step 2:

Find that view in your activity/fragment

View slideView = findViewById(R.id.slideView);

Step 3:

Create a SlideUp object and pass in your view

slideUp = new SlideUpBuilder(slideView)
                .withStartState(SlideUp.State.HIDDEN)
                .withStartGravity(Gravity.BOTTOM)

                //.withSlideFromOtherView(anotherView)
                //.withGesturesEnabled()
                //.withHideSoftInputWhenDisplayed()
                //.withInterpolator()
                //.withAutoSlideDuration()
                //.withLoggingEnabled()
                //.withTouchableAreaPx()
                //.withTouchableAreaDp()
                //.withListeners()
                //.withSavedState()
                .build();

You may also refer to the sample project on the link. I found it quite useful.

Netbeans how to set command line arguments in Java

This worked for me, use the VM args in NetBeans:

@Value("${a.b.c:#{abc}}"
...

@Value("${e.f.g:#{efg}}"
...

Netbeans:

-Da.b.c="..." -De.f.g="..."

Properties -> Run -> VM Options -> -De.f.g=efg -Da.b.c=abc

From the commandline

java -jar <yourjar> --Da.b.c="abc" 

Can you install and run apps built on the .NET framework on a Mac?

  • .NET Core will install and run on macOS - and just about any other desktop OS.
    IDEs are available for the mac, including:

  • Mono is a good option that I've used in the past. But with Core 3.0 out now, I would go that route.

AngularJS directive does not update on scope variable changes

I needed a solution for this issue as well and I used the answers in this thread to come up with the following:

.directive('tpReport', ['$parse', '$http', '$compile', '$templateCache', function($parse, $http, $compile, $templateCache)
    {
        var getTemplateUrl = function(type)
        {
            var templateUrl = '';

            switch (type)
            {
                case 1: // Table
                    templateUrl = 'modules/tpReport/directives/table-report.tpl.html';
                    break;
                case 0:
                    templateUrl = 'modules/tpReport/directives/default.tpl.html';
                    break;
                default:
                    templateUrl = '';
                    console.log("Type not defined for tpReport");
                    break;
            }

            return templateUrl;
        };

        var linker = function (scope, element, attrs)
        {

            scope.$watch('data', function(){
                var templateUrl = getTemplateUrl(scope.data[0].typeID);
                var data = $templateCache.get(templateUrl);
                element.html(data);
                $compile(element.contents())(scope);

            });



        };

        return {
            controller: 'tpReportCtrl',
            template: '<div>{{data}}</div>',
            // Remove all existing content of the directive.
            transclude: true,
            restrict: "E",
            scope: {
                data: '='
            },
            link: linker
        };
    }])
    ;

Include in your html:

<tp-report data='data'></tp-report>

This directive is used for dynamically loading report templates based on the dataset retrieved from the server.

It sets a watch on the scope.data property and whenever this gets updated (when the users requests a new dataset from the server) it loads the corresponding directive to show the data.

Why is there no xrange function in Python3?

comp:~$ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2

>>> import timeit
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.656799077987671

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.579368829727173

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

21.54827117919922

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

22.014557123184204

With timeit number=1 param:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.2245171070098877

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=1)

0.10750913619995117

comp:~$ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.113872020003328

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.07014398300089

With timeit number=1,2,3,4 param works quick and in linear way:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.09329321900440846

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=2)

0.18501482300052885

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=3)

0.2703447980020428

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=4)

0.36209142999723554

So it seems if we measure 1 running loop cycle like timeit.timeit("[x for x in range(1000000) if x%4]",number=1) (as we actually use in real code) python3 works quick enough, but in repeated loops python 2 xrange() wins in speed against range() from python 3.

Spark dataframe: collect () vs select ()

calling select will result is lazy evaluation: for example:

val df1 = df.select("col1")
val df2 = df1.filter("col1 == 3")

both above statements create lazy path that will be executed when you call action on that df, such as show, collect etc.

val df3 = df2.collect()

use .explain at the end of your transformation to follow its plan here is more detailed info Transformations and Actions

Error: Java: invalid target release: 11 - IntelliJ IDEA

I was recently facing the same problem. This Error was showing on my screen after running my project main file. Error:java: invalid source release: 11 Follow the steps to resolve this error

  1. File->Project Structure -> Project
  2. Click New button under Project SDK: Add the latest SDK and Click OK.

enter image description here

After running You will see error is resolved..

enter image description here

enter image description here

You can see it's work perfectly.. Please approach me If you find any problem

How can I get a JavaScript stack trace when I throw an exception?

You could use this library http://www.stacktracejs.com/ . It's very good

From documentation

You can also pass in your own Error to get a stacktrace not available in IE or Safari 5-

<script type="text/javascript" src="https://rawgithub.com/stacktracejs/stacktrace.js/master/stacktrace.js"></script>
<script type="text/javascript">
    try {
        // error producing code
    } catch(e) {
        var trace = printStackTrace({e: e});
        alert('Error!\n' + 'Message: ' + e.message + '\nStack trace:\n' + trace.join('\n'));
        // do something else with error
    }
</script>

How can I see which Git branches are tracking which remote / upstream branch?

For the current branch, you could also say git checkout (w/o any branch). This is a no-op with a side-effects to show the tracking information, if exists, for the current branch.

$ git checkout 
Your branch is up-to-date with 'origin/master'.

cat, grep and cut - translated to python

You need to have better understanding of the python language and its standard library to translate the expression

cat "$filename": Reads the file cat "$filename" and dumps the content to stdout

|: pipe redirects the stdout from previous command and feeds it to the stdin of the next command

grep "something": Searches the regular expressionsomething plain text data file (if specified) or in the stdin and returns the matching lines.

cut -d'"' -f2: Splits the string with the specific delimiter and indexes/splices particular fields from the resultant list

Python Equivalent

cat "$filename"  | with open("$filename",'r') as fin:        | Read the file Sequentially
                 |     for line in fin:                      |   
-----------------------------------------------------------------------------------
grep 'something' | import re                                 | The python version returns
                 | line = re.findall(r'something', line)[0]  | a list of matches. We are only
                 |                                           | interested in the zero group
-----------------------------------------------------------------------------------
cut -d'"' -f2    | line = line.split('"')[1]                 | Splits the string and selects
                 |                                           | the second field (which is
                 |                                           | index 1 in python)

Combining

import re
with open("filename") as origin_file:
    for line in origin_file:
        line = re.findall(r'something', line)
        if line:
           line = line[0].split('"')[1]
        print line

CSS3 :unchecked pseudo-class

There is no :unchecked pseudo class however if you use the :checked pseudo class and the sibling selector you can differentiate between both states. I believe all of the latest browsers support the :checked pseudo class, you can find more info from this resource: http://www.whatstyle.net/articles/18/pretty_form_controls_with_css

Your going to get better browser support with jquery... you can use a click function to detect when the click happens and if its checked or not, then you can add a class or remove a class as necessary...

How to set the timeout for a TcpClient?

Here is a code improvement based on mcandal solution. Added exception catching for any exception generated from the client.ConnectAsync task (e.g: SocketException when server is unreachable)

var timeOut = TimeSpan.FromSeconds(5);     
var cancellationCompletionSource = new TaskCompletionSource<bool>();

try
{
    using (var cts = new CancellationTokenSource(timeOut))
    {
        using (var client = new TcpClient())
        {
            var task = client.ConnectAsync(hostUri, portNumber);

            using (cts.Token.Register(() => cancellationCompletionSource.TrySetResult(true)))
            {
                if (task != await Task.WhenAny(task, cancellationCompletionSource.Task))
                {
                    throw new OperationCanceledException(cts.Token);
                }

                // throw exception inside 'task' (if any)
                if (task.Exception?.InnerException != null)
                {
                    throw task.Exception.InnerException;
                }
            }

            ...

        }
    }
}
catch (OperationCanceledException operationCanceledEx)
{
    // connection timeout
    ...
}
catch (SocketException socketEx)
{
    ...
}
catch (Exception ex)
{
    ...
}

How do I analyze a program's core dump file with GDB when it has command-line parameters?

You can use the core with GDB in many ways, but passing parameters which is to be passed to the executable to GDB is not the way to use the core file. This could also be the reason you got that error. You can use the core file in the following ways:

gdb <executable> <core-file> or gdb <executable> -c <core-file> or

gdb <executable>
...
(gdb) core <core-file>

When using the core file you don't have to pass arguments. The crash scenario is shown in GDB (checked with GDB version 7.1 on Ubuntu).

For example:

$ ./crash -p param1 -o param2
Segmentation fault (core dumped)
$ gdb ./crash core
GNU gdb (GDB) 7.1-ubuntu
...
Core was generated by `./crash -p param1 -o param2'. <<<<< See this line shows crash scenario
Program terminated with signal 11, Segmentation fault.
#0  __strlen_ia32 () at ../sysdeps/i386/i686/multiarch/../../i586/strlen.S:99
99    ../sysdeps/i386/i686/multiarch/../../i586/strlen.S: No such file or directory.
    in ../sysdeps/i386/i686/multiarch/../../i586/strlen.S
(gdb)

If you want to pass parameters to the executable to be debugged in GDB, use --args.

For example:

$ gdb --args ./crash -p param1 -o param2
GNU gdb (GDB) 7.1-ubuntu
...
(gdb) r
Starting program: /home/@@@@/crash -p param1 -o param2

Program received signal SIGSEGV, Segmentation fault.
__strlen_ia32 () at ../sysdeps/i386/i686/multiarch/../../i586/strlen.S:99
99    ../sysdeps/i386/i686/multiarch/../../i586/strlen.S: No such file or directory.
    in ../sysdeps/i386/i686/multiarch/../../i586/strlen.S
(gdb)

Man pages will be helpful to see other GDB options.

How do I vertically align text in a div?

A simple solution to an element of not knowing values:

HTML

<div class="main">
    <div class="center">
        whatever
    </div>
</div>

CSS

.main {
    position: relative
}

.center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
}

SQL Update to the SUM of its joined values

This is a valid error. See this. Following (and others suggested below) are the ways to achieve this:-

UPDATE P 
SET extrasPrice = t.TotalPrice
FROM BookingPitches AS P INNER JOIN
 (
  SELECT
    PitchID,
    SUM(Price) TotalPrice
  FROM
     BookingPitchExtras
  GROUP BY PitchID
  ) t
ON t.PitchID = p.ID

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

There are multiple packages available for formatting console text in Node.js. The most popular are:

Usage:

CHALK:

const chalk = require('chalk');
console.log(chalk.red('Text in red'));

COLORS:

const colors = require('colors');
console.log('Text in red'.red);

CLI-COLOR:

const clc = require('cli-color');
console.log(clc.red('Text in red'));

Many people have noted their disapproval of colors altering the String prototype. If you prefer your prototypes to be left alone, use the following code instead:

const colors = require('colors/safe');
console.log(colors.red('Text in red'));

A transport-level error has occurred when receiving results from the server

All you need is to Stop the ASP.NET Development Server and run the project again

Matrix Transpose in Python

#generate matrix
matrix=[]
m=input('enter number of rows, m = ')
n=input('enter number of columns, n = ')
for i in range(m):
    matrix.append([])
    for j in range(n):
        elem=input('enter element: ')
        matrix[i].append(elem)

#print matrix
for i in range(m):
    for j in range(n):
        print matrix[i][j],
    print '\n'

#generate transpose
transpose=[]
for j in range(n):
    transpose.append([])
    for i in range (m):
        ent=matrix[i][j]
        transpose[j].append(ent)

#print transpose
for i in range (n):
    for j in range (m):
        print transpose[i][j],
    print '\n'

How to undo a git merge with conflicts

Latest Git:

git merge --abort

This attempts to reset your working copy to whatever state it was in before the merge. That means that it should restore any uncommitted changes from before the merge, although it cannot always do so reliably. Generally you shouldn't merge with uncommitted changes anyway.

Prior to version 1.7.4:

git reset --merge

This is older syntax but does the same as the above.

Prior to version 1.6.2:

git reset --hard

which removes all uncommitted changes, including the uncommitted merge. Sometimes this behaviour is useful even in newer versions of Git that support the above commands.

How can I monitor the thread count of a process on linux?

To get the number of threads for a given pid:

$ ps -o nlwp <pid>

Where nlwp stands for Number of Light Weight Processes (threads). Thus ps aliases nlwp to thcount, which means that

$ ps -o thcount <pid>

does also work.

If you want to monitor the thread count, simply use watch:

$ watch ps -o thcount <pid>

To get the sum of all threads running in the system:

$ ps -eo nlwp | tail -n +2 | awk '{ num_threads += $1 } END { print num_threads }'

libclntsh.so.11.1: cannot open shared object file.

I had to install the dependency

oracle-instantclient12.2-basic-12.2.0.1.0-1.x86_64

How can I indent multiple lines in Xcode?

For those of you with Spanish keyboard on mac this are the shortcuts:

? + ? + [ for un-indent

? + ? + ] for indent

Ansible - read inventory hosts and variables to group_vars/all file

If you want to refer one host define under /etc/ansible/host in a task or role, the bellow link might help:

https://www.middlewareinventory.com/blog/ansible-get-ip-address/

PHP, MySQL error: Column count doesn't match value count at row 1

You have 9 fields listed, but only 8 values. Try adding the method.

jQuery Validation using the class instead of the name value

Here's my solution (requires no jQuery... just JavaScript):

function argsToArray(args) {
  var r = []; for (var i = 0; i < args.length; i++)
    r.push(args[i]);
  return r;
}
function bind() {
  var initArgs = argsToArray(arguments);
  var fx =        initArgs.shift();
  var tObj =      initArgs.shift();
  var args =      initArgs;
  return function() {
    return fx.apply(tObj, args.concat(argsToArray(arguments)));
  };
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
  checkbox.addEventListener('change', bind(function(checkbox, salutation) {
    var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
    if (numChecked >= 4)
      checkbox.checked = false;
  }, null, checkbox, salutation), false);
});

Put this in a script block at the end of <body> and the snippet will do its magic, limiting the number of checkboxes checked in maximum to three (or whatever number you specify).

Here, I'll even give you a test page (paste it into a file and try it):

<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<script>
    function argsToArray(args) {
      var r = []; for (var i = 0; i < args.length; i++)
        r.push(args[i]);
      return r;
    }
    function bind() {
      var initArgs = argsToArray(arguments);
      var fx =        initArgs.shift();
      var tObj =      initArgs.shift();
      var args =      initArgs;
      return function() {
        return fx.apply(tObj, args.concat(argsToArray(arguments)));
      };
    }
    var salutation = argsToArray(document.getElementsByClassName('salutation'));
    salutation.forEach(function(checkbox) {
      checkbox.addEventListener('change', bind(function(checkbox, salutation) {
        var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
        if (numChecked >= 3)
          checkbox.checked = false;
      }, null, checkbox, salutation), false);
    });
</script></body></html>

How do I set session timeout of greater than 30 minutes

Setting session timeout through the deployment descriptor should work - it sets the default session timeout for the web app. Calling session.setMaxInactiveInterval() sets the timeout for the particular session it is called on, and overrides the default. Be aware of the unit difference, too - the deployment descriptor version uses minutes, and session.setMaxInactiveInterval() uses seconds.

So

<session-config>
    <session-timeout>60</session-timeout>
</session-config>

sets the default session timeout to 60 minutes.

And

session.setMaxInactiveInterval(600);

sets the session timeout to 600 seconds - 10 minutes - for the specific session it's called on.

This should work in Tomcat or Glassfish or any other Java web server - it's part of the spec.

jQuery detect if string contains something

You can use javascript's indexOf function.

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
   alert(str2 + " found");
}

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

Copy files from one directory into an existing directory

cp dir1/* dir2

Or if you have directories inside dir1 that you'd want to copy as well

cp -r dir1/* dir2

select and echo a single field from mysql db using PHP

And escape your values with mysql_real_escape_string since PHP6 won't do that for you anymore! :)

Model Binding to a List MVC 4

~Controller

namespace ListBindingTest.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            List<String> tmp = new List<String>();
            tmp.Add("one");
            tmp.Add("two");
            tmp.Add("Three");
            return View(tmp);
        }

        [HttpPost]
        public ActionResult Send(IList<String> input)
        {
            return View(input);
        }    
    }
}

~ Strongly Typed Index View

@model IList<String>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
    <div>
    @using(Html.BeginForm("Send", "Home", "POST"))
    {
        @Html.EditorFor(x => x)
        <br />
        <input type="submit" value="Send" />
    }
    </div>
</body>
</html>

~ Strongly Typed Send View

@model IList<String>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Send</title>
</head>
<body>
    <div>
    @foreach(var element in @Model)
    {
        @element
        <br />
    }
    </div>
</body>
</html>

This is all that you had to do man, change his MyViewModel model to IList.

Regex doesn't work in String.matches()

I have faced the same problem once:

Pattern ptr = Pattern.compile("^[a-zA-Z][\\']?[a-zA-Z\\s]+$");

The above failed!

Pattern ptr = Pattern.compile("(^[a-zA-Z][\\']?[a-zA-Z\\s]+$)");

The above worked with pattern within ( and ).

Hive External Table Skip First Row

I also struggled with this and found no way to tell hive to skip first row, like there is e.g. in Greenplum. So finally I had to remove it from the files. e.g. "cat File.csv | grep -v RecordId > File_no_header.csv"

LINQ's Distinct() on a particular property

I think it is enough:

list.Select(s => s.MyField).Distinct();

std::queue iteration

In short: No.

There is a hack, use vector as underlaid container, so queue::front will return valid reference, convert it to pointer an iterate until <= queue::back

Inserting a value into all possible locations in a list

Simplest is use list[i:i]

    a = [1,2, 3, 4]
    a[2:2] = [10]

Print a to check insertion

    print a
    [1, 2, 10, 3, 4]

How do I print an IFrame from javascript in Safari/Chrome

You can also use

top.iframeName.print();

or

parent.iframeName.print();

MATLAB error: Undefined function or method X for input arguments of type 'double'

As others have pointed out, this is very probably a problem with the path of the function file not being in Matlab's 'path'.

One easy way to verify this is to open your function in the Editor and press the F5 key. This would make the Editor try to run the file, and in case the file is not in path, it will prompt you with a message box. Choose Add to Path in that, and you must be fine to go.

One side note: at the end of the above process, Matlab command window will give an error saying arguments missing: obviously, we didn't provide any arguments when we tried to run from the editor. But from now on you can use the function from the command line giving the correct arguments.

What is size_t in C?

From my understanding, size_t is an unsigned integer whose bit size is large enough to hold a pointer of the native architecture.

So:

sizeof(size_t) >= sizeof(void*)

How to get the selected item of a combo box to a string variable in c#

You can use as below:

string selected = cmbbox.Text;
MessageBox.Show(selected);

HTML/CSS--Creating a banner/header

You have a type-o:

its: height: 200x;

and it should be: height: 200px; also check the image url; it should be in the same directory it seems.

Also, dont use 'px' at null (aka '0') values. 0px, 0em, 0% is still 0. :)

top: 0px;

is the same with:

top: 0;

Good Luck!

jQuery Array of all selected checkboxes (by class)

You can also add underscore.js to your project and will be able to do it in one line:

_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

Change color of bootstrap navbar on hover link?

Sorry for late reply. You can only use:

   nav a:hover{

                   background-color:color name !important;


                 }

Define a struct inside a class in C++

The other answers here have demonstrated how to define structs inside of classes. There’s another way to do this, and that’s to declare the struct inside the class, but define it outside. This can be useful, for example, if the struct is decently complex and likely to be used standalone in a way that would benefit from being described in detail somewhere else.

The syntax for this is as follows:

class Container {

    ...

    struct Inner; // Declare, but not define, the struct.

    ...

};

struct Container::Inner {
   /* Define the struct here. */
};

You more commonly would see this in the context of defining nested classes rather than structs (a common example would be defining an iterator type for a collection class), but I thought for completeness it would be worth showing off here.

What does .class mean in Java?

Just to clarify, this '.class' method is not referring to the bytecode file you see after compiling java code nor a confusion between the concepts of Class vs. Object in OOP theory.

This '.class' method is used in Java for code Reflection. Generally you can gather meta data for your class such as the full qualified class name, list of constants, list of public fields, etc, etc.

Check these links (already mentioned above) to get all the details:
https://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html

Normally you don't plan on using Reflection right away when you start building your project. It's something that you know you need after trying to manage already working code. Many times you need it to manage multiple instances of your program. Maybe you want to identify each particular 'clone' to determine if something is already defined, or count the number of functions, or just simply log the details of a particular instance of your class.

Detect merged cells in VBA Excel with MergeArea

While working with selected cells as shown by @tbur can be useful, it's also not the only option available.

You can use Range() like so:

If Worksheets("Sheet1").Range("A1").MergeCells Then
  Do something
Else
  Do something else
End If

Or:

If Worksheets("Sheet1").Range("A1:C1").MergeCells Then
  Do something
Else
  Do something else
End If

Alternately, you can use Cells():

If Worksheets("Sheet1").Cells(1, 1).MergeCells Then
  Do something
Else
  Do something else
End If

How to use the switch statement in R functions?

I hope this example helps. You ca use the curly braces to make sure you've got everything enclosed in the switcher changer guy (sorry don't know the technical term but the term that precedes the = sign that changes what happens). I think of switch as a more controlled bunch of if () {} else {} statements.

Each time the switch function is the same but the command we supply changes.

do.this <- "T1"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)
#########################################################
do.this <- "T2"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)
########################################################
do.this <- "T3"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)

Here it is inside a function:

FUN <- function(df, do.this){
    switch(do.this,
        T1={X <- t(df)
            P <- colSums(df)%*%X
        },
        T2={X <- colMeans(df)
            P <- outer(X, X)
        },
        stop("Enter something that switches me!")
    )
    return(P)
}

FUN(mtcars, "T1")
FUN(mtcars, "T2")
FUN(mtcars, "T3")

Comparing two maps

As long as you override equals() on each key and value contained in the map, then m1.equals(m2) should be reliable to check for maps equality.

The same result can be obtained also by comparing toString() of each map as you suggested, but using equals() is a more intuitive approach.

May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays.equals(). More details about this see here.

How to save SELECT sql query results in an array in C# Asp.net

    public void ChargingArraySelect()
    {
        int loop = 0;
        int registros = 0;

        OdbcConnection conn = WebApiConfig.conn();
        OdbcCommand query = conn.CreateCommand();

        query.CommandText = "select dataA, DataB, dataC, DataD FROM table  where dataA = 'xpto'";

        try
        {
            conn.Open();
            OdbcDataReader dr = query.ExecuteReader();

            //take the number the registers, to use into next step
            registros = dr.RecordsAffected;

            //calls an array to be populated
            Global.arrayTest = new string[registros, 4];

            while (dr.Read())
            {
                if (loop < registros)
                {
                    Global.arrayTest[i, 0] = Convert.ToString(dr["dataA"]);
                    Global.arrayTest[i, 1] = Convert.ToString(dr["dataB"]);
                    Global.arrayTest[i, 2] = Convert.ToString(dr["dataC"]);
                    Global.arrayTest[i, 3] = Convert.ToString(dr["dataD"]);
                }
                loop++;
            }
        }
    }


    //Declaration the Globais Array in Global Classs
    private static string[] uso_internoArray1;
    public static string[] arrayTest
    {
        get { return uso_internoArray1; }
        set { uso_internoArray1 = value; }
    }

Scanner is skipping nextLine() after using next() or nextFoo()?

It does that because input.nextInt(); doesn't capture the newline. you could do like the others proposed by adding an input.nextLine(); underneath.
Alternatively you can do it C# style and parse a nextLine to an integer like so:

int number = Integer.parseInt(input.nextLine()); 

Doing this works just as well, and it saves you a line of code.

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

Found transport-attribute in binding-element which tells us that this is the WSDL 1.1 binding for the SOAP 1.1 HTTP binding.

ex.

<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

How can I select item with class within a DIV?

If you want to select every element that has class attribute "myclass" use

$('#mydiv .myclass');

If you want to select only div elements that has class attribute "myclass" use

$("div#mydiv div.myclass");

find more about jquery selectors refer these articles

PHP "php://input" vs $_POST

If post data is malformed, $_POST will not contain anything. Yet, php://input will have the malformed string.

For example there is some ajax applications, that do not form correct post key-value sequence for uploading a file, and just dump all the file as post data, without variable names or anything. $_POST will be empty, $_FILES empty also, and php://input will contain exact file, written as a string.

Using python's eval() vs. ast.literal_eval()?

Python's eager in its evaluation, so eval(input(...)) (Python 3) will evaluate the user's input as soon as it hits the eval, regardless of what you do with the data afterwards. Therefore, this is not safe, especially when you eval user input.

Use ast.literal_eval.


As an example, entering this at the prompt could be very bad for you:

__import__('os').system('rm -rf /a-path-you-really-care-about')

How to pass a view's onClick event to its parent on Android?

If your TextView create click issues, than remove android:inputType="" from your xml file.

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

No signing certificate "iOS Distribution" found

I got the "No signing certificate" error when running Xcode 11.3 on macOS 10.14.x Mojave. (but after Xcode 12 was released.)

I was also using Fastlane. My fix was to set generate_apple_certs to false when running Match. This seemed to generate signing certificates that were backwards-compatible with Xcode 11.3

Match documentation - https://docs.fastlane.tools/actions/match/

This is the relevant section of my Fastfile:

platform :ios do
  lane :certs do
    force = false
    match(type: "development", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.dev")
    match(type: "adhoc",       generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.beta")
    match(type: "appstore",    generate_apple_certs: false, force: force, app_identifier: "your.app.identifier")
  end

  ...

Loading DLLs at runtime in C#

Members must be resolvable at compile time to be called directly from C#. Otherwise you must use reflection or dynamic objects.

Reflection

namespace ConsoleApplication1
{
    using System;
    using System.Reflection;

    class Program
    {
        static void Main(string[] args)
        {
            var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

            foreach(Type type in DLL.GetExportedTypes())
            {
                var c = Activator.CreateInstance(type);
                type.InvokeMember("Output", BindingFlags.InvokeMethod, null, c, new object[] {@"Hello"});
            }

            Console.ReadLine();
        }
    }
}

Dynamic (.NET 4.0)

namespace ConsoleApplication1
{
    using System;
    using System.Reflection;

    class Program
    {
        static void Main(string[] args)
        {
            var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

            foreach(Type type in DLL.GetExportedTypes())
            {
                dynamic c = Activator.CreateInstance(type);
                c.Output(@"Hello");
            }

            Console.ReadLine();
        }
    }
}

Comparing the contents of two files in Sublime Text

No one is talking about Linux but all above answers will work. Just use Ctrl to select more than one file. If you are looking to compare side by side, Meld is lovely.

Sum of two input value by jquery

if in multiple class you want to change additional operation in perticular class that show in below example

$('.like').click(function(){    
var like= $(this).text();
$(this).text(+like + +1);
});

How to hide a TemplateField column in a GridView

A slight improvement using column name, IMHO:

    Private Sub GridView1_Init(sender As Object, e As System.EventArgs) Handles GridView1.Init
    For Each dcf As DataControlField In GridView1.Columns
        Select Case dcf.HeaderText.ToUpper
            Case "CBSELECT"
                dcf.Visible = Me.CheckBoxVisible
                dcf.HeaderText = "<small>Select</small>"
        End Select
    Next
End Sub

This allows control over multiple column. I initially use a 'technical' column name, matching the control name within. This makes it obvious within the ASCX page that it's a control column. Then swap out the name as desired for presentation. If I spy the odd name in production, I know I skipped something. The "ToUpper" avoids case-issues.

Finally, this runs ONE time on any post instead of capturing the event during row-creation.

Why am I not getting a java.util.ConcurrentModificationException in this example?

This runs fine on Java 1.6

~ % javac RemoveListElementDemo.java
~ % java RemoveListElementDemo
~ % cat RemoveListElementDemo.java

import java.util.*;
public class RemoveListElementDemo {    
    private static final List<Integer> integerList;

    static {
        integerList = new ArrayList<Integer>();
        integerList.add(1);
        integerList.add(2);
        integerList.add(3);
    }

    public static void remove(Integer remove) {
        for(Integer integer : integerList) {
            if(integer.equals(remove)) {                
                integerList.remove(integer);
            }
        }
    }

    public static void main(String... args) {                
        remove(Integer.valueOf(2));

        Integer remove = Integer.valueOf(3);
        for(Integer integer : integerList) {
            if(integer.equals(remove)) {                
                integerList.remove(integer);
            }
        }
    }
}

~ %

How do I detect unsigned integer multiply overflow?

mozilla::CheckedInt<T> provides overflow-checked integer math for integer type T (using compiler intrinsics on clang and gcc as available). The code is under MPL 2.0 and depends on three (IntegerTypeTraits.h, Attributes.h and Compiler.h) other header-only non-standard library headers plus Mozilla-specific assertion machinery. You probably want to replace the assertion machinery if you import the code.

How to use font-family lato?

Please put this code in head section

<link href='http://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>

and use font-family: 'Lato', sans-serif; in your css. For example:

h1 {
    font-family: 'Lato', sans-serif;
    font-weight: 400;
}

Or you can use manually also

Generate .ttf font from fontSquiral

and can try this option

    @font-face {
        font-family: "Lato";
        src: url('698242188-Lato-Bla.eot');
        src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
        url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
        url('698242188-Lato-Bla.woff') format('woff'),
        url('698242188-Lato-Bla.ttf') format('truetype');
        font-weight: normal;
        font-style: normal;
}

Called like this

body {
  font-family: 'Lato', sans-serif;
}

VBA Macro to compare all cells of two Excel files

A very simple check you can do with Cell formulas:

Sheet 1 (new - old)

=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")

Sheet 2 (old - new)

=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")

This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)

You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".

Doe the same for Sheet two.

Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.

But two cases are not covered here:

  1. In the compared cell of New and Old is the same data (Resulting Cell will be empty)
  2. In the compared cell of New and Old is diffe data (Resulting Cell will be empty)

To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com

How to use XPath preceding-sibling correctly

You don't need to go level up and use .. since all buttons are on the same level:

//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']

Soft keyboard open and close listener in an activity in Android

For use in Kotlin inside fragment, which is a common use case it is very easy with KeyboardVisibilityEvent library.

In build.gradle:

implementation 'net.yslibrary.keyboardvisibilityevent:keyboardvisibilityevent:3.0.0-RC2'

In Fragment:

activity?.let {
    KeyboardVisibilityEvent.setEventListener(it,object: KeyboardVisibilityEventListener {
        override fun onVisibilityChanged(isOpen: Boolean) {
            if (isOpen) Toast.makeText(context,"Keyboard is opened",Toast.LENGTH_SHORT).show()
            else Toast.makeText(context,"Keyboard is closed",Toast.LENGTH_SHORT).show()
        }
    })
}

Source and credits

BackgroundWorker vs background Thread

A background worker is a class that works in a separate thread, but it provides additional functionality that you don't get with a simple Thread (like task progress report handling).

If you don't need the additional features given by a background worker - and it seems you don't - then a Thread would be more appropriate.

Postgres: check if array field contains value?

This worked for me

let exampleArray = [1, 2, 3, 4, 5];
let exampleToString = exampleArray.toString(); //convert to toString
let query = `Select * from table_name where column_name in (${exampleToString})`; //Execute the query to get response

I have got the same problem, then after an hour of effort I got to know that the array should not be directly accessed in the query. So I then found that the data should be sent in the paranthesis it self, then again I have converted that array to string using toString method in js. So I have worked by executing the above query and got my expected result

Oracle SQL - DATE greater than statement

You need to convert the string to date using the to_date() function

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31-Dec-2014','DD-MON-YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014','DD MON YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('2014-12-31','yyyy-MM-dd');

This will work only if OrderDate is stored in Date format. If it is Varchar you should apply to_date() func on that column also like

 SELECT * FROM OrderArchive
    WHERE to_date(OrderDate,'yyyy-Mm-dd') <= to_date('2014-12-31','yyyy-MM-dd');

Regular expression to match non-ASCII characters?

Unicode Property Escapes are among the features of ES2018.

Basic Usage

With Unicode Property Escapes, you can match a letter from any language with the following simple regular expression:

/\p{Letter}/u

Or with the shorthand, even terser:

/\p{L}/u

Matching Words

Regarding the question's concrete use case (matching words), note that you can use Unicode Property Escapes in character classes, making it easy to match letters together with other word-characters like hyphens:

/[\p{L}-]/u

Stitching it all together, you could match words of all[1] languages with this beautifully short RegEx:

/[\p{L}-]+/ug

Example (shamelessly plugged from the answer above):

'Düsseldorf, Köln, ??????, ???, ??????? !@#$'.match(/[\p{L}-]+/ug)

// ["Düsseldorf", "Köln", "??????", "???", "???????"]

[1] Note that I'm not an expert on languages. You may still want to do your own research regarding other characters that might be parts of words besides letters and hyphens.

Browser Support

This feature is available in all major evergreen browsers.

Transpiling

If support for older browsers is needed, Unicode Property Escapes can be transpiled to ES5 with a tool called regexpu. There's an online demo available here. As you can see in the demo, you can in fact match non-latin letters today with the following (horribly long) ES5 regular expression:

/(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D])/

If you're using Babel, there's also a regexpu-powered plugin for that (Babel v6 plugin, Babel v7 plugin).

Python convert csv to xlsx

How I do it with openpyxl lib:

import csv
from openpyxl import Workbook

def convert_csv_to_xlsx(self):
    wb = Workbook()
    sheet = wb.active

    CSV_SEPARATOR = "#"

    with open("my_file.csv") as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                for idx, val in enumerate(col.split(CSV_SEPARATOR)):
                    cell = sheet.cell(row=r+1, column=idx+1)
                    cell.value = val

    wb.save("my_file.xlsx")

.ssh/config file for windows (git)

There is an option IdentityFile which you can use in your ~/.ssh/config file and specify key file for each host.

Host host_with_key1.net
  IdentityFile ~/.ssh/id_rsa

Host host_with_key2.net
  IdentityFile ~/.ssh/id_rsa_test

More info: http://linux.die.net/man/5/ssh_config

Also look at http://nerderati.com/2011/03/17/simplify-your-life-with-an-ssh-config-file/

Align DIV to bottom of the page

Nathan Lee's answer is perfect. I just wanted to add something about position:absolute;. If you wanted to use position:absolute; like you had in your code, you have to think of it as pushing it away from one side of the page.

For example, if you wanted your div to be somewhere in the bottom, you would have to use position:absolute; top:500px;. That would push your div 500px from the top of the page. Same rule applies for all other directions.

DEMO

Is it possible to remove the hand cursor that appears when hovering over a link? (or keep it set as the normal pointer)

That's exactly what cursor: pointer; is supposed to do.

If you want the cursor to remain normal, you should be using cursor: default

Render a string in HTML and preserve spaces and linebreaks

Wrap the description in a textarea element.

Using curl POST with variables defined in bash script functions

Existing answers point out that curl can post data from a file, and employ heredocs to avoid excessive quote escaping and clearly break the JSON out onto new lines. However there is no need to define a function or capture output from cat, because curl can post data from standard input. I find this form very readable:

curl -X POST -H 'Content-Type:application/json' --data '$@-' ${API_URL} << EOF
{
  "account": {
    "email": "$email",
    "screenName": "$screenName",
    "type": "$theType",
    "passwordSettings": {
      "password": "$password",
      "passwordConfirm": "$password"
    }
  },
  "firstName": "$firstName",
  "lastName": "$lastName",
  "middleName": "$middleName",
  "locale": "$locale",
  "registrationSiteId": "$registrationSiteId",
  "receiveEmail": "$receiveEmail",
  "dateOfBirth": "$dob",
  "mobileNumber": "$mobileNumber",
  "gender": "$gender",
  "fuelActivationDate": "$fuelActivationDate",
  "postalCode": "$postalCode",
  "country": "$country",
  "city": "$city",
  "state": "$state",
  "bio": "$bio",
  "jpFirstNameKana": "$jpFirstNameKana",
  "jpLastNameKana": "$jpLastNameKana",
  "height": "$height",
  "weight": "$weight",
  "distanceUnit": "MILES",
  "weightUnit": "POUNDS",
  "heightUnit": "FT/INCHES"
}
EOF

C# Help reading foreign characters using StreamReader

I solved my problem of reading portuguese characters, changing the source file on notepad++.

enter image description here

C#

    var url = System.Web.HttpContext.Current.Server.MapPath(@"~/Content/data.json");
    string s = string.Empty;
    using (System.IO.StreamReader sr = new System.IO.StreamReader(url, System.Text.Encoding.UTF8,true))
    {
          s = sr.ReadToEnd();
    }

Found conflicts between different versions of the same dependent assembly that could not be resolved

You could run the Dotnet CLI with full diagnostic verbosity to help find the issue.

dotnet run --verbosity diagnostic >> full_build.log

Once the build is complete you can search through the log file (full_build.log) for the error. Searching for "a conflict" for example, should take you right to the problem.

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }
}

What is the preferred syntax for defining enums in JavaScript?

your answers are far too complicated

var buildSet = function(array) {
  var set = {};
  for (var i in array) {
    var item = array[i];
    set[item] = item;
  }
  return set;
}

var myEnum = buildSet(['RED','GREEN','BLUE']);
// myEnum.RED == 'RED' ...etc

How to use zIndex in react-native

I finally solved this by creating a second object that imitates B.

My schema now looks like this:

enter image description here

I now have B1 (within parent of A) and B2 outside of it.

B1 and B2 are right next to one another, so to the naked eye it looks as if it's just 1 object.

Loop through list with both content and index

enumerate() makes this prettier:

for index, value in enumerate(S):
    print index, value

See here for more.

Find CRLF in Notepad++

I've not had much luck with \r\n regular expressions from the find/replace window.

However, this works in Notepad++ v4.1.2:

  1. Use the "View | Show end of line" menu to enable display of end of line characters. (Carriage return line feeds should show up as a single shaded CRLF 'character'.)

  2. Select one of the CRLF 'characters' (put the cursor just in front of one, hold down the SHIFT key, and then pressing the RIGHT CURSOR key once).

  3. Copy the CRLF character to the clipboard.

  4. Make sure that you don't have the find or find/replace dialog open.

  5. Open the find/replace dialog. The 'Find what' field shows the contents of the clipboard: in this case the CRLF character - which shows up as 2 'box characters' (presumably it's an unprintable character?)

  6. Ensure that the 'Regular expression' option is OFF.

Now you should be able to count, find, or replace as desired.

How to parse/format dates with LocalDateTime? (Java 8)

GET CURRENT UTC TIME IN REQUIRED FORMAT

// Current UTC time
        OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);

        // GET LocalDateTime 
        LocalDateTime localDateTime = utc.toLocalDateTime();
        System.out.println("*************" + localDateTime);

        // formated UTC time
        DateTimeFormatter dTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF.format(localDateTime));

        //GET UTC time for current date
        Date now= new Date();
        LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
        DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));

How to convert an Instant to a date format?

try Parsing and Formatting

Take an example Parsing

String input = ...;
try {
    DateTimeFormatter formatter =
                      DateTimeFormatter.ofPattern("MMM d yyyy");
    LocalDate date = LocalDate.parse(input, formatter);
    System.out.printf("%s%n", date);
}
catch (DateTimeParseException exc) {
    System.out.printf("%s is not parsable!%n", input);
    throw exc;      // Rethrow the exception.
}

Formatting

ZoneId leavingZone = ...;
ZonedDateTime departure = ...;

try {
    DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
    String out = departure.format(format);
    System.out.printf("LEAVING:  %s (%s)%n", out, leavingZone);
}
catch (DateTimeException exc) {
    System.out.printf("%s can't be formatted!%n", departure);
    throw exc;
}

The output for this example, which prints both the arrival and departure time, is as follows:

LEAVING:  Jul 20 2013  07:30 PM (America/Los_Angeles)
ARRIVING: Jul 21 2013  10:20 PM (Asia/Tokyo)

For more details check this page- https://docs.oracle.com/javase/tutorial/datetime/iso/format.html

How to create named and latest tag in Docker?

ID=$(docker build -t creack/node .) doesn't work for me since ID will contain the output from the build.

SO I'm using this small BASH script:

#!/bin/bash

set -o pipefail

IMAGE=...your image name...
VERSION=...the version...

docker build -t ${IMAGE}:${VERSION} . | tee build.log || exit 1
ID=$(tail -1 build.log | awk '{print $3;}')
docker tag $ID ${IMAGE}:latest

docker images | grep ${IMAGE}

docker run --rm ${IMAGE}:latest /opt/java7/bin/java -version

How to add new activity to existing project in Android Studio?

In Android Studio 2, just right click on app and select New > Activity > ... to create desired activity type.

enter image description here

How do I break a string in YAML over multiple lines?

1. Block Notation(plain, flow-style, scalar): Newlines become spaces and extra newlines after the block are removed

---
# Note: It has 1 new line after the string
content:
    Arbitrary free text
    over multiple lines stopping
    after indentation changes...

...

Equivalent JSON

{
 "content": "Arbitrary free text over multiple lines stopping after indentation changes..."
}

2. Literal Block Scalar: A Literal Block Scalar | will include the newlines and any trailing spaces. but removes extra

newlines after the block.

---
# After string we have 2 spaces and 2 new lines
content1: |
 Arbitrary free text
 over "multiple lines" stopping
 after indentation changes...  


...

Equivalent JSON

{
 "content1": "Arbitrary free text\nover \"multiple lines\" stopping\nafter indentation changes...  \n"
}

3. + indicator with Literal Block Scalar: keep extra newlines after block

---
# After string we have 2 new lines
plain: |+
 This unquoted scalar
 spans many lines.


...

Equivalent JSON

{
 "plain": "This unquoted scalar\nspans many lines.\n\n\n"
}

4. – indicator with Literal Block Scalar: – means that the newline at the end of the string is removed.

---
# After string we have 2 new lines
plain: |-
 This unquoted scalar
 spans many lines.


...

Equivalent JSON

{
 "plain": "This unquoted scalar\nspans many lines."
}

5. Folded Block Scalar(>):

will fold newlines to spaces and but removes extra newlines after the block.

---
folded_newlines: >
 this is really a
 single line of text
 despite appearances


...

Equivalent JSON

{
 "fold_newlines": "this is really a single line of text despite appearances\n"
}

for more you can visit my Blog

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

enumerate() for dictionary in python

  1. Iterating over a Python dict means to iterate over its keys exactly the same way as with dict.keys()
  2. The order of the keys is determined by the implementation code and you cannot expect some specific order:

    Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.

That's why you see the indices 0 to 7 in the first column. They are produced by enumerate and are always in the correct order. Further you see the dict's keys 0 to 7 in the second column. They are not sorted.

ArrayList: how does the size increase?

Sun's JDK6:

I believe that it grows to 15 elements. Not coding it out, but looking at the grow() code in the jdk.

int newCapacity then = 10 + (10 >> 1) = 15.

/**
 * Increases the capacity to ensure that it can hold at least the
 * number of elements specified by the minimum capacity argument.
 *
 * @param minCapacity the desired minimum capacity
 */
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}

From the Javadoc, it says this is from Java 2 and on, so its a safe bet in the Sun JDK.

EDIT : for those who didn't get what's the connection between multiplying factor 1.5 and int newCapacity = oldCapacity + (oldCapacity >> 1);

>> is right shift operator which reduces a number to its half. Thus,
int newCapacity = oldCapacity + (oldCapacity >> 1);
=> int newCapacity = oldCapacity + 0.5*oldCapacity;
=> int newCapacity = 1.5*oldCapacity ;

Select all DIV text with single mouse click

How about this simple solution? :)

<input style="background-color:white; border:1px white solid;" onclick="this.select();" id="selectable" value="http://example.com/page.htm">

Sure it is not div-construction, like you mentioned, but still it is worked for me.

Android: Bitmaps loaded from gallery are rotated in ImageView

Use the following code to rotate an image correctly:

private Bitmap rotateImage(Bitmap bitmap, String filePath)
{
    Bitmap resultBitmap = bitmap;

    try
    {
        ExifInterface exifInterface = new ExifInterface(filePath);
        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

        Matrix matrix = new Matrix();

        if (orientation == ExifInterface.ORIENTATION_ROTATE_90)
        {
            matrix.postRotate(ExifInterface.ORIENTATION_ROTATE_90);
        }
        else if (orientation == ExifInterface.ORIENTATION_ROTATE_180)
        {
            matrix.postRotate(ExifInterface.ORIENTATION_ROTATE_180);
        }
        else if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
        {
            matrix.postRotate(ExifInterface.ORIENTATION_ROTATE_270);
        }

        // Rotate the bitmap
        resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }
    catch (Exception exception)
    {
        Logger.d("Could not rotate the image");
    }
    return resultBitmap;
}

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I had Microsoft Access Database Engine 2010 Redistributable already installed on my machine but was still receiving the Microsoft ACE OLEDB Provider error.

Then I recalled that I had upgraded to Office 2016 recently, so, may be I should try reinstalling Microsoft Access Database Engine 2010 Redistributable. And that fixed the problem on my machine.

So, if you have upgraded to different version of MS Office or even repaired/reinstalled your MS Office then try reinstalling Microsoft Access Database Engine 2010 Redistributable before wasting time with finding other fixes. Good luck!

How to see data from .RData file?

I think the problem is that you load isfar data.frame but you overwrite it by value returned by load.

Try either:

load("C:/Users/isfar.RData") 
head(isfar)

Or more general way

load("C:/Users/isfar.RData", ex <- new.env())
ls.str(ex) 

How to get ID of button user just clicked?

You can also try this simple one-liner code. Just call the alert method on onclick attribute.

<button id="some_id1" onclick="alert(this.id)"></button>

C++ equivalent of StringBuffer/StringBuilder?

std::string is the C++ equivalent: It's mutable.

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

Leave only two decimal places after the dot

string.Format is your friend.

String.Format("{0:0.00}", 123.4567);      // "123.46"

What is Node.js' Connect, Express and "middleware"?

[Update: As of its 4.0 release, Express no longer uses Connect. However, Express is still compatible with middleware written for Connect. My original answer is below.]

I'm glad you asked about this, because it's definitely a common point of confusion for folks looking at Node.js. Here's my best shot at explaining it:

  • Node.js itself offers an http module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server prototype.

  • Connect also offers a createServer method, which returns an object that inherits an extended version of http.Server. Connect's extensions are mainly there to make it easy to plug in middleware. That's why Connect describes itself as a "middleware framework," and is often analogized to Ruby's Rack.

  • Express does to Connect what Connect does to the http module: It offers a createServer method that extends Connect's Server prototype. So all of the functionality of Connect is there, plus view rendering and a handy DSL for describing routes. Ruby's Sinatra is a good analogy.

  • Then there are other frameworks that go even further and extend Express! Zappa, for instance, which integrates support for CoffeeScript, server-side jQuery, and testing.

Here's a concrete example of what's meant by "middleware": Out of the box, none of the above serves static files for you. But just throw in connect.static (a middleware that comes with Connect), configured to point to a directory, and your server will provide access to the files in that directory. Note that Express provides Connect's middlewares also; express.static is the same as connect.static. (Both were known as staticProvider until recently.)

My impression is that most "real" Node.js apps are being developed with Express these days; the features it adds are extremely useful, and all of the lower-level functionality is still there if you want it.

ngModel cannot be used to register form controls with a parent formGroup directive

I just got this error because I did not enclose all my form controls within a div with a formGroup attribute.

For example, this will throw an error

<div [formGroup]='formGroup'>
</div>
<input formControlName='userName' />

This can be quite easy to miss if its a particularly long form.

adding a datatable in a dataset

DataSet ds = new DataSet();

DataTable activity = DTsetgvActivity.Copy();
activity.TableName = "activity";
ds.Tables.Add(activity);

DataTable Honer = DTsetgvHoner.Copy();
Honer.TableName = "Honer";
ds.Tables.Add(Honer);

DataTable Property = DTsetgvProperty.Copy();
Property.TableName = "Property";
ds.Tables.Add(Property);


DataTable Income = DTsetgvIncome.Copy();
Income.TableName = "Income";
ds.Tables.Add(Income);

DataTable Dependant = DTsetgvDependant.Copy();
Dependant.TableName = "Dependant";
ds.Tables.Add(Dependant);

DataTable Insurance = DTsetgvInsurance.Copy();
Insurance.TableName = "Insurance";
ds.Tables.Add(Insurance);

DataTable Sacrifice = DTsetgvSacrifice.Copy();
Sacrifice.TableName = "Sacrifice";
ds.Tables.Add(Sacrifice);

DataTable Request = DTsetgvRequest.Copy();
Request.TableName = "Request";
ds.Tables.Add(Request);

DataTable Branchs = DTsetgvBranchs.Copy();
Branchs.TableName = "Branchs";
ds.Tables.Add(Branchs);

What is difference between monolithic and micro kernel?

Monolithic kernel is a single large process running entirely in a single address space. It is a single static binary file. All kernel services exist and execute in the kernel address space. The kernel can invoke functions directly. Examples of monolithic kernel based OSs: Unix, Linux.

In microkernels, the kernel is broken down into separate processes, known as servers. Some of the servers run in kernel space and some run in user-space. All servers are kept separate and run in different address spaces. Servers invoke "services" from each other by sending messages via IPC (Interprocess Communication). This separation has the advantage that if one server fails, other servers can still work efficiently. Examples of microkernel based OSs: Mac OS X and Windows NT.

$.widget is not a function

I got this error recently by introducing an old plugin to wordpress. It loaded an older version of jquery, which happened to be placed before the jquery mouse file. There was no jquery widget file loaded with the second version, which caused the error.

No error for using the extra jquery library -- that's a problem especially if a silent fail might have happened, causing a not so silent fail later on.

A potential way around it for wordpress might be to be explicit about the dependencies that way the jquery mouse would follow the widget which would follow the correct core leaving the other jquery to be loaded afterwards. Still might cause a production error later if you don't catch that and change the default function for jquery for the second version in all the files associated with it.

Store output of subprocess.Popen call in a string

In Python 3.7 a new keyword argument capture_output was introduced for subprocess.run. Enabling the short and simple:

import subprocess

p = subprocess.run("echo 'hello world!'", capture_output=True, shell=True, encoding="utf8")
assert p.stdout == 'hello world!\n'

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

In my case, just using flex-shrink: 0 didn't work. But adding flex-grow: 1 to it worked.

.item {
    flex-shrink: 0;
    flex-grow: 1;
}

How does strtok() split the string into tokens in C?

So, this is a code snippet to help better understand this topic.

Printing Tokens

Task: Given a sentence, s, print each word of the sentence in a new line.

char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
//logic to print the tokens of the sentence.
for (char *p = strtok(s," "); p != NULL; p = strtok(NULL, " "))
{
    printf("%s\n",p);
}

Input: How is that

Result:

How
is
that

Explanation: So here, "strtok()" function is used and it's iterated using for loop to print the tokens in separate lines.

The function will take parameters as 'string' and 'break-point' and break the string at those break-points and form tokens. Now, those tokens are stored in 'p' and are used further for printing.

What is the best way to iterate over multiple lists at once?

The usual way is to use zip():

for x, y in zip(a, b):
    # x is from a, y is from b

This will stop when the shorter of the two iterables a and b is exhausted. Also worth noting: itertools.izip() (Python 2 only) and itertools.izip_longest() (itertools.zip_longest() in Python 3).

How to calculate cumulative normal distribution?

To build upon Unknown's example, the Python equivalent of the function normdist() implemented in a lot of libraries would be:

def normcdf(x, mu, sigma):
    t = x-mu;
    y = 0.5*erfcc(-t/(sigma*sqrt(2.0)));
    if y>1.0:
        y = 1.0;
    return y

def normpdf(x, mu, sigma):
    u = (x-mu)/abs(sigma)
    y = (1/(sqrt(2*pi)*abs(sigma)))*exp(-u*u/2)
    return y

def normdist(x, mu, sigma, f):
    if f:
        y = normcdf(x,mu,sigma)
    else:
        y = normpdf(x,mu,sigma)
    return y

WebAPI to Return XML

If you return a serializable object, WebAPI will automatically send JSON or XML based on the Accept header that your client sends.

If you return a string, you'll get a string.

Datatable select with multiple conditions

Do you have to use DataTable.Select()? I prefer to write a linq query for this kind of thing.

var dValue=  from row in myDataTable.AsEnumerable()
             where row.Field<int>("A") == 1 
                   && row.Field<int>("B") == 2 
                   && row.Field<int>("C") == 3
             select row.Field<string>("D");

Angular-cli from css to scss

In ng6 you need to use this command, according to a similar post:

ng config schematics.@schematics/angular:component '{ styleext: "scss"}'

Remove 'b' character do in front of a string literal in Python 3

Decoding is redundant

You only had this "error" in the first place, because of a misunderstanding of what's happening.

You get the b because you encoded to utf-8 and now it's a bytes object.

 >> type("text".encode("utf-8"))
 >> <class 'bytes'>

Fixes:

  1. You can just print the string first
  2. Redundantly decode it after encoding

Watermark / hint text / placeholder TextBox

You can create a watermark that can be added to any TextBox with an Attached Property. Here is the source for the Attached Property:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;

/// <summary>
/// Class that provides the Watermark attached property
/// </summary>
public static class WatermarkService
{
    /// <summary>
    /// Watermark Attached Dependency Property
    /// </summary>
    public static readonly DependencyProperty WatermarkProperty = DependencyProperty.RegisterAttached(
       "Watermark",
       typeof(object),
       typeof(WatermarkService),
       new FrameworkPropertyMetadata((object)null, new PropertyChangedCallback(OnWatermarkChanged)));

    #region Private Fields

    /// <summary>
    /// Dictionary of ItemsControls
    /// </summary>
    private static readonly Dictionary<object, ItemsControl> itemsControls = new Dictionary<object, ItemsControl>();

    #endregion

    /// <summary>
    /// Gets the Watermark property.  This dependency property indicates the watermark for the control.
    /// </summary>
    /// <param name="d"><see cref="DependencyObject"/> to get the property from</param>
    /// <returns>The value of the Watermark property</returns>
    public static object GetWatermark(DependencyObject d)
    {
        return (object)d.GetValue(WatermarkProperty);
    }

    /// <summary>
    /// Sets the Watermark property.  This dependency property indicates the watermark for the control.
    /// </summary>
    /// <param name="d"><see cref="DependencyObject"/> to set the property on</param>
    /// <param name="value">value of the property</param>
    public static void SetWatermark(DependencyObject d, object value)
    {
        d.SetValue(WatermarkProperty, value);
    }

    /// <summary>
    /// Handles changes to the Watermark property.
    /// </summary>
    /// <param name="d"><see cref="DependencyObject"/> that fired the event</param>
    /// <param name="e">A <see cref="DependencyPropertyChangedEventArgs"/> that contains the event data.</param>
    private static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Control control = (Control)d;
        control.Loaded += Control_Loaded;

        if (d is ComboBox)
        {
            control.GotKeyboardFocus += Control_GotKeyboardFocus;
            control.LostKeyboardFocus += Control_Loaded;
        }
        else if (d is TextBox)
        {
            control.GotKeyboardFocus += Control_GotKeyboardFocus;
            control.LostKeyboardFocus += Control_Loaded;
            ((TextBox)control).TextChanged += Control_GotKeyboardFocus;
        }

        if (d is ItemsControl && !(d is ComboBox))
        {
            ItemsControl i = (ItemsControl)d;

            // for Items property  
            i.ItemContainerGenerator.ItemsChanged += ItemsChanged;
            itemsControls.Add(i.ItemContainerGenerator, i);

            // for ItemsSource property  
            DependencyPropertyDescriptor prop = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, i.GetType());
            prop.AddValueChanged(i, ItemsSourceChanged);
        }
    }

    #region Event Handlers

    /// <summary>
    /// Handle the GotFocus event on the control
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">A <see cref="RoutedEventArgs"/> that contains the event data.</param>
    private static void Control_GotKeyboardFocus(object sender, RoutedEventArgs e)
    {
        Control c = (Control)sender;
        if (ShouldShowWatermark(c))
        {
            ShowWatermark(c);
        }
        else
        {
            RemoveWatermark(c);
        }
    }

    /// <summary>
    /// Handle the Loaded and LostFocus event on the control
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">A <see cref="RoutedEventArgs"/> that contains the event data.</param>
    private static void Control_Loaded(object sender, RoutedEventArgs e)
    {
        Control control = (Control)sender;
        if (ShouldShowWatermark(control))
        {
            ShowWatermark(control);
        }
    }

    /// <summary>
    /// Event handler for the items source changed event
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">A <see cref="EventArgs"/> that contains the event data.</param>
    private static void ItemsSourceChanged(object sender, EventArgs e)
    {
        ItemsControl c = (ItemsControl)sender;
        if (c.ItemsSource != null)
        {
            if (ShouldShowWatermark(c))
            {
                ShowWatermark(c);
            }
            else
            {
                RemoveWatermark(c);
            }
        }
        else
        {
            ShowWatermark(c);
        }
    }

    /// <summary>
    /// Event handler for the items changed event
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">A <see cref="ItemsChangedEventArgs"/> that contains the event data.</param>
    private static void ItemsChanged(object sender, ItemsChangedEventArgs e)
    {
        ItemsControl control;
        if (itemsControls.TryGetValue(sender, out control))
        {
            if (ShouldShowWatermark(control))
            {
                ShowWatermark(control);
            }
            else
            {
                RemoveWatermark(control);
            }
        }
    }

    #endregion

    #region Helper Methods

    /// <summary>
    /// Remove the watermark from the specified element
    /// </summary>
    /// <param name="control">Element to remove the watermark from</param>
    private static void RemoveWatermark(UIElement control)
    {
        AdornerLayer layer = AdornerLayer.GetAdornerLayer(control);

        // layer could be null if control is no longer in the visual tree
        if (layer != null)
        {
            Adorner[] adorners = layer.GetAdorners(control);
            if (adorners == null)
            {
                return;
            }

            foreach (Adorner adorner in adorners)
            {
                if (adorner is WatermarkAdorner)
                {
                    adorner.Visibility = Visibility.Hidden;
                    layer.Remove(adorner);
                }
            }
        }
    }

    /// <summary>
    /// Show the watermark on the specified control
    /// </summary>
    /// <param name="control">Control to show the watermark on</param>
    private static void ShowWatermark(Control control)
    {
        AdornerLayer layer = AdornerLayer.GetAdornerLayer(control);

        // layer could be null if control is no longer in the visual tree
        if (layer != null)
        {
            layer.Add(new WatermarkAdorner(control, GetWatermark(control)));
        }
    }

    /// <summary>
    /// Indicates whether or not the watermark should be shown on the specified control
    /// </summary>
    /// <param name="c"><see cref="Control"/> to test</param>
    /// <returns>true if the watermark should be shown; false otherwise</returns>
    private static bool ShouldShowWatermark(Control c)
    {
        if (c is ComboBox)
        {
            return (c as ComboBox).Text == string.Empty;
        }
        else if (c is TextBoxBase)
        {
            return (c as TextBox).Text == string.Empty;
        }
        else if (c is ItemsControl)
        {
            return (c as ItemsControl).Items.Count == 0;
        }
        else
        {
            return false;
        }
    }

    #endregion
}

The Attached Property uses a class called WatermarkAdorner, here is that source:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;

/// <summary>
/// Adorner for the watermark
/// </summary>
internal class WatermarkAdorner : Adorner
{
    #region Private Fields

    /// <summary>
    /// <see cref="ContentPresenter"/> that holds the watermark
    /// </summary>
    private readonly ContentPresenter contentPresenter;

    #endregion

    #region Constructor

    /// <summary>
    /// Initializes a new instance of the <see cref="WatermarkAdorner"/> class
    /// </summary>
    /// <param name="adornedElement"><see cref="UIElement"/> to be adorned</param>
    /// <param name="watermark">The watermark</param>
    public WatermarkAdorner(UIElement adornedElement, object watermark) :
       base(adornedElement)
    {
        this.IsHitTestVisible = false;

        this.contentPresenter = new ContentPresenter();
        this.contentPresenter.Content = watermark;
        this.contentPresenter.Opacity = 0.5;
        this.contentPresenter.Margin = new Thickness(Control.Margin.Left + Control.Padding.Left, Control.Margin.Top + Control.Padding.Top, 0, 0);

        if (this.Control is ItemsControl && !(this.Control is ComboBox))
        {
            this.contentPresenter.VerticalAlignment = VerticalAlignment.Center;
            this.contentPresenter.HorizontalAlignment = HorizontalAlignment.Center;
        }

        // Hide the control adorner when the adorned element is hidden
        Binding binding = new Binding("IsVisible");
        binding.Source = adornedElement;
        binding.Converter = new BooleanToVisibilityConverter();
        this.SetBinding(VisibilityProperty, binding);
    }

    #endregion

    #region Protected Properties

    /// <summary>
    /// Gets the number of children for the <see cref="ContainerVisual"/>.
    /// </summary>
    protected override int VisualChildrenCount
    {
        get { return 1; }
    }

    #endregion

    #region Private Properties

    /// <summary>
    /// Gets the control that is being adorned
    /// </summary>
    private Control Control
    {
        get { return (Control)this.AdornedElement; }
    }

    #endregion

    #region Protected Overrides

    /// <summary>
    /// Returns a specified child <see cref="Visual"/> for the parent <see cref="ContainerVisual"/>.
    /// </summary>
    /// <param name="index">A 32-bit signed integer that represents the index value of the child <see cref="Visual"/>. The value of index must be between 0 and <see cref="VisualChildrenCount"/> - 1.</param>
    /// <returns>The child <see cref="Visual"/>.</returns>
    protected override Visual GetVisualChild(int index)
    {
        return this.contentPresenter;
    }

    /// <summary>
    /// Implements any custom measuring behavior for the adorner.
    /// </summary>
    /// <param name="constraint">A size to constrain the adorner to.</param>
    /// <returns>A <see cref="Size"/> object representing the amount of layout space needed by the adorner.</returns>
    protected override Size MeasureOverride(Size constraint)
    {
        // Here's the secret to getting the adorner to cover the whole control
        this.contentPresenter.Measure(Control.RenderSize);
        return Control.RenderSize;
    }

    /// <summary>
    /// When overridden in a derived class, positions child elements and determines a size for a <see cref="FrameworkElement"/> derived class. 
    /// </summary>
    /// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
    /// <returns>The actual size used.</returns>
    protected override Size ArrangeOverride(Size finalSize)
    {
        this.contentPresenter.Arrange(new Rect(finalSize));
        return finalSize;
    }

    #endregion
}

Now you can put a watermark on any TextBox like this:

<AdornerDecorator>
   <TextBox x:Name="SearchTextBox">
      <controls:WatermarkService.Watermark>
         <TextBlock>Type here to search text</TextBlock>
      </controls:WatermarkService.Watermark>
   </TextBox>
</AdornerDecorator>

The watermark can be anything you want (text, images ...). In addition to working for TextBoxes, this watermark also works for ComboBoxes and ItemControls.

This code was adapted from this blog post.

Check list of words in another string

If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):

>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])

How to add an object to an ArrayList in Java

Try this one:

Data objt = new Data(name, address, contact);
Contacts.add(objt);

How to Convert UTC Date To Local time Zone in MySql Select Query

In my case, where the timezones are not available on the server, this works great:

SELECT CONVERT_TZ(`date_field`,'+00:00',@@global.time_zone) FROM `table`

Note: global.time_zone uses the server timezone. You have to make sure, that it has the desired timezone!

Destroy or remove a view in Backbone.js

I think this should work

destroyView : function () {
    this.$el.remove();
}

a href link for entire div in HTML/CSS

Going off of what Surreal Dreams said, it's probably best to style the anchor tag in my experience, but it really does depend on what you are doing. Here's an example:

Html:

<div class="parent-div">
  <a href="#">Test</a>
  <a href="#">Test</a>
  <a href="#">Test</a>
</div>

Then the CSS:

.parent-div {
  width: 200px;
}
a {
  display:block;
  background-color: #ccc;
  color: #000;
  text-decoration:none;
  padding:10px;
  margin-bottom:1px;
}
a:hover {
  background-color: #ddd;
}

http://jsbin.com/zijijuduqo/1/edit?html,css,output

MySQL: Invalid use of group function

You need to use HAVING, not WHERE.

The difference is: the WHERE clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT function.

HAVING is like WHERE, only it happens after the COUNT value has been computed, so it'll work as you expect. Rewrite your subquery as:

(                  -- where that pid is in the set:
SELECT c2.pid                  -- of pids
FROM Catalog AS c2             -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)

Accessing localhost:port from Android emulator

I would like to show you the way I access IISExpress Web APIs from my Android Emulator. I'm using Visual Studio 2015. And I call the Android Emulator from Android Studio.

All of what I need to do is adding the following line to the binding configuration in my applicationhost.config file

<binding protocol="http" bindingInformation="*:<your-port>:" />

Then I check and use the IP4 Address to access my API from Android emulator

Requirement: you must run Visual Studio as Administrator. This post gives a perfect way to do this.

For more details, please visit my post on github

Hope this helps.

Use latest version of Internet Explorer in the webbrowser control

var appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe";

using (var Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true))
    Key.SetValue(appName, 99999, RegistryValueKind.DWord);

According to what I read here (Controlling WebBrowser Control Compatibility:

What Happens if I Set the FEATURE_BROWSER_EMULATION Document Mode Value Higher than the IE Version on the Client?

Obviously, the browser control can only support a document mode that is less than or equal to the IE version installed on the client. Using the FEATURE_BROWSER_EMULATION key works best for enterprise line of business apps where there is a deployed and support version of the browser. In the case you set the value to a browser mode that is a higher version than the browser version installed on the client, the browser control will choose the highest document mode available.

The simplest thing is to put a very high decimal number ...

String concatenation of two pandas columns

df['bar'] = df.bar.map(str) + " is " + df.foo.

Format date as dd/MM/yyyy using pipes

Angular: 8.2.11

<td>{{ data.DateofBirth | date }}</td>

Output: Jun 9, 1973

<td>{{ data.DateofBirth | date: 'dd/MM/yyyy' }}</td>

Output: 09/06/1973

<td>{{ data.DateofBirth | date: 'dd/MM/yyyy hh:mm a' }}</td>

Output: 09/06/1973 12:00 AM

How to set transparent background for Image Button in code?

This should work - imageButton.setBackgroundColor(android.R.color.transparent);

ImportError: No Module named simplejson

On Ubuntu/Debian, you can install it with apt-get install python-simplejson

What is the Difference Between read() and recv() , and Between send() and write()?

"Performance and speed"? Aren't those kind of ... synonyms, here?

Anyway, the recv() call takes flags that read() doesn't, which makes it more powerful, or at least more convenient. That is one difference. I don't think there is a significant performance difference, but haven't tested for it.

Maven: How to rename the war file for the project?

You can follow the below step to modify the .war file name if you are using maven project.

Open pom.xml file of your maven project and go to the tag <build></build>,

  1. In that give your desired name between this tag : <finalName></finalName>.

    ex. : <finalName>krutik</finalName>

    After deploying this .war you will be able to access url with:
    http://localhost:8080/krutik/

  2. If you want to access the url with slash '/' then you will have to specify then name as below:

    e.x. : <finalName>krutik#maheta</finalName>

    After deploying this .war you will be able to access url with:
    http://localhost:8080/krutik/maheta

Configuring Log4j Loggers Programmatically

You can add/remove Appender programmatically to Log4j:

  ConsoleAppender console = new ConsoleAppender(); //create appender
  //configure the appender
  String PATTERN = "%d [%p|%c|%C{1}] %m%n";
  console.setLayout(new PatternLayout(PATTERN)); 
  console.setThreshold(Level.FATAL);
  console.activateOptions();
  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(console);

  FileAppender fa = new FileAppender();
  fa.setName("FileLogger");
  fa.setFile("mylog.log");
  fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
  fa.setThreshold(Level.DEBUG);
  fa.setAppend(true);
  fa.activateOptions();

  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(fa);
  //repeat with all other desired appenders

I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with

 Logger.getRootLogger().getLoggerRepository().resetConfiguration();

and start with adding your own. You need log4j in the classpath of course for this to work.

Remark:
You can take any Logger.getLogger(...) you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).

If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:

  Logger fizz = LoggerFactory.getLogger("com.fizz")

will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to Logger.getLogger("com.fizz").addAppender(newAppender) then logging from fizz will be handled by alle the appenders from the root logger and the newAppender.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.

How do I change an HTML selected option using JavaScript?

Change

document.getElementById('personlist').getElementsByTagName('option')[11].selected = 'selected'

to

document.getElementById('personlist').value=Person_ID;

How to set time to a date object in java

Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")

Compare if BigDecimal is greater than zero

This works too:

value > BigDecimal.ZERO

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).

How to right-align and justify-align in Markdown?

As mentioned here, markdown do not support right aligned text or blocks. But the HTML result does it, via Cascading Style Sheets (CSS).

On my Jekyll Blog is use a syntax which works in markdown as well. To "terminate" a block use two spaces at the end or two times new line.

Of course you can also add a css-class with {: .right } instead of {: style="text-align: right" }.

Text to right

{: style="text-align: right" }
This text is on the right

Text as block

{: style="text-align: justify" }
This text is a block

How do I create a branch?

  • Create a new folder outside of your current project. You can give it any name. (Example: You have a checkout for a project named "Customization". And it has many projects, like "Project1", "Project2"....And you want to create a branch of "Project1". So first open the "Customization", right click and create a new folder and give it a name, "Project1Branch").
  • Right click on "Myproject1"....TortoiseSVN -> Branch/Tag.
  • Choose working copy.
  • Open browser....Just right of parallel on "To URL".
  • Select customization.....right click then Add Folder. and go through the folder which you have created. Here it is "Project1Branch". Now clik the OK button to add.
  • Take checkout of this new banch.
  • Again go to your project which branch you want to create. Right click TorotoiseSVN -> branch/tag. Then select working copy. And you can give the URL as your branch name. like {your IP address/svn/AAAA/Customization/Project1Branch}. And you can set the name in the URL so it will create the folder with this name only. Like {Your IP address/svn/AAAA/Customization/Project1Branch/MyProject1Branch}.
  • Press the OK button. Now you can see the logs in ...your working copy will be stored in your branch.
  • Now you can take a check out...and let you enjoy your work. :)

Undefined reference to sqrt (or other mathematical functions)

I had the same issue, but I simply solved it by adding -lm after the command that runs my code. Example. gcc code.c -lm

What __init__ and self do in Python?

In this code:

class Cat:
    def __init__(self, name):
        self.name = name
    def info(self):
        print 'I am a cat and I am called', self.name

Here __init__ acts as a constructor for the class and when an object is instantiated, this function is called. self represents the instantiating object.

c = Cat('Kitty')
c.info()

The result of the above statements will be as follows:

I am a cat and I am called Kitty

Get keys of a Typescript interface as array of strings

// declarations.d.ts
export interface IMyTable {
      id: number;
      title: string;
      createdAt: Date;
      isDeleted: boolean
}
declare var Tes: IMyTable;
// call in annother page
console.log(Tes.id);

Updating an object with setState in React

Try with this:

const { jasper } = this.state; //Gets the object from state
jasper.name = 'A new name'; //do whatever you want with the object
this.setState({jasper}); //Replace the object in state

How to open the second form?

If you want to open Form2 modally (meaning you can't click on Form1 while Form2 is open), you can do this:

using (Form2 f2 = new Form2()) 
{
    f2.ShowDialog(this);
}

If you want to open Form2 non-modally (meaning you can still click on Form1 while Form2 is open), you can create a form-level reference to Form2 like this:

private Form2 _f2;

public void openForm2()
{
    _f2 = new Form2();
    _f2.Show(this); // the "this" is important, as this will keep Form2 open above 
                    // Form1.
}

public void closeForm2()
{
    _f2.Close();
    _f2.Dispose();
}

How can I rename a project folder from within Visual Studio?

Open .sln in a text editor, and in the following line change <FolderName> to your new folder name Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ricky", "\.csproj", "{021CC6B0-8CFB-4194-A103-C19AF869D965}"

How can I solve the error 'TS2532: Object is possibly 'undefined'?

For others facing a similar problem to mine, where you know a particular object property cannot be null, you can use the non-null assertion operator (!) after the item in question. This was my code:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci.certificateStatus = "";
    }
  }

And because dataToSend.naci cannot be undefined in the switch statement, the code can be updated to include exclamation marks as follows:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci!.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci!.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci!.certificateStatus = "";
    }
  }

HTML: How to limit file upload to be only images?

Here is the HTML for image upload. By default it will show image files only in the browsing window because we have put accept="image/*". But we can still change it from the dropdown and it will show all files. So the Javascript part validates whether or not the selected file is an actual image.

 <div class="col-sm-8 img-upload-section">
     <input name="image3" type="file" accept="image/*" id="menu_images"/>
     <img id="menu_image" class="preview_img" />
     <input type="submit" value="Submit" />
 </div> 

Here on the change event we first check the size of the image. And in the second if condition we check whether or not it is an image file.

this.files[0].type.indexOf("image") will be -1 if it is not an image file.

document.getElementById("menu_images").onchange = function () {
    var reader = new FileReader();
    if(this.files[0].size>528385){
        alert("Image Size should not be greater than 500Kb");
        $("#menu_image").attr("src","blank");
        $("#menu_image").hide();  
        $('#menu_images').wrap('<form>').closest('form').get(0).reset();
        $('#menu_images').unwrap();     
        return false;
    }
    if(this.files[0].type.indexOf("image")==-1){
        alert("Invalid Type");
        $("#menu_image").attr("src","blank");
        $("#menu_image").hide();  
        $('#menu_images').wrap('<form>').closest('form').get(0).reset();
        $('#menu_images').unwrap();         
        return false;
    }   
    reader.onload = function (e) {
        // get loaded data and render thumbnail.
        document.getElementById("menu_image").src = e.target.result;
        $("#menu_image").show(); 
    };

    // read the image file as a data URL.
    reader.readAsDataURL(this.files[0]);
};

Delete files older than 10 days using shell script in Unix

Just spicing up the shell script above to delete older files but with logging and calculation of elapsed time

#!/bin/bash

path="/data/backuplog/"
timestamp=$(date +%Y%m%d_%H%M%S)    
filename=log_$timestamp.txt    
log=$path$filename
days=7

START_TIME=$(date +%s)

find $path -maxdepth 1 -name "*.txt"  -type f -mtime +$days  -print -delete >> $log

echo "Backup:: Script Start -- $(date +%Y%m%d_%H%M)" >> $log


... code for backup ...or any other operation .... >> $log


END_TIME=$(date +%s)

ELAPSED_TIME=$(( $END_TIME - $START_TIME ))


echo "Backup :: Script End -- $(date +%Y%m%d_%H%M)" >> $log
echo "Elapsed Time ::  $(date -d 00:00:$ELAPSED_TIME +%Hh:%Mm:%Ss) "  >> $log

The code adds a few things.

  • log files named with a timestamp
  • log folder specified
  • find looks for *.txt files only in the log folder
  • type f ensures you only deletes files
  • maxdepth 1 ensures you dont enter subfolders
  • log files older than 7 days are deleted ( assuming this is for a backup log)
  • notes the start / end time
  • calculates the elapsed time for the backup operation...

Note: to test the code, just use -print instead of -print -delete. But do check your path carefully though.

Note: Do ensure your server time is set correctly via date - setup timezone/ntp correctly . Additionally check file times with 'stat filename'

Note: mtime can be replaced with mmin for better control as mtime discards all fractions (older than 2 days (+2 days) actually means 3 days ) when it deals with getting the timestamps of files in the context of days

-mtime +$days  --->  -mmin  +$((60*24*$days))

How to set background image in Java?

Firstly create a new class that extends the WorldView class. I called my new class Background. So in this new class import all the Java packages you will need in order to override the paintBackground method. This should be:

import city.soi.platform.*;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import java.awt.geom.AffineTransform;

Next after the class name make sure that it says extends WorldView. Something like this:

public class Background extends WorldView

Then declare the variables game of type Game and an image variable of type Image something like this:

private Game game;
private Image image;

Then in the constructor of this class make sure the game of type Game is in the signature of the constructor and that in the call to super you will have to initialise the WorldView, initialise the game and initialise the image variables, something like this:

super(game.getCurrentLevel().getWorld(), game.getWidth(), game.getHeight());
this.game = game;
bg = (new ImageIcon("lol.png")).getImage();

Then you just override the paintBackground method in exactly the same way as you did when overriding the paint method in the Player class. Just like this:

public void paintBackground(Graphics2D g)
{
float x = getX();
float y = getY();
AffineTransform transform = AffineTransform.getTranslateInstance(x,y);
g.drawImage(bg, transform, game.getView());
}

Now finally you have to declare a class level reference to the new class you just made in the Game class and initialise this in the Game constructor, something like this:

private Background image;

And in the Game constructor:
image = new Background(this);

Lastly all you have to do is add the background to the frame! That's the thing I'm sure we were all missing. To do that you have to do something like this after the variable frame has been declared:

frame.add(image);

Make sure you add this code just before frame.pack();. Also make sure you use a background image that isn't too big!

Now that's it! Ive noticed that the game engines can handle JPEG and PNG image formats but could also support others. Even though this helps include a background image in your game, it is not perfect! Because once you go to the next level all your platforms and sprites are invisible and all you can see is your background image and any JLabels/Jbuttons you have included in the game.

multiple ways of calling parent method in php

There are three scenarios (that I can think of) where you would call a method in a subclass where the method exits in the parent class:

  1. Method is not overwritten by subclass, only exists in parent.

    This is the same as your example, and generally it's better to use $this -> get_species(); You are right that in this case the two are effectively the same, but the method has been inherited by the subclass, so there is no reason to differentiate. By using $this you stay consistent between inherited methods and locally declared methods.

  2. Method is overwritten by the subclass and has totally unique logic from the parent.

    In this case, you would obviously want to use $this -> get_species(); because you don't want the parent's version of the method executed. Again, by consistently using $this, you don't need to worry about the distinction between this case and the first.

  3. Method extends parent class, adding on to what the parent method achieves.

    In this case, you still want to use `$this -> get_species(); when calling the method from other methods of the subclass. The one place you will call the parent method would be from the method that is overwriting the parent method. Example:

    abstract class Animal {
    
        function get_species() {
    
            echo "I am an animal.";
    
        }
    
     }
    
     class Dog extends Animal {
    
         function __construct(){
    
             $this->get_species();
         }
    
         function get_species(){
    
             parent::get_species();
             echo "More specifically, I am a dog.";
         }
    }
    

The only scenario I can imagine where you would need to call the parent method directly outside of the overriding method would be if they did two different things and you knew you needed the parent's version of the method, not the local. This shouldn't be the case, but if it did present itself, the clean way to approach this would be to create a new method with a name like get_parentSpecies() where all it does is call the parent method:

function get_parentSpecies(){

     parent::get_species();
}

Again, this keeps everything nice and consistent, allowing for changes/modifications to the local method rather than relying on the parent method.

Get yesterday's date in bash on Linux, DST-safe

Here a solution that will work with Solaris and AIX as well.

Manipulating the Timezone is possible for changing the clock some hours. Due to the daylight saving time, 24 hours ago can be today or the day before yesterday.

You are sure that yesterday is 20 or 30 hours ago. Which one? Well, the most recent one that is not today.

echo -e "$(TZ=GMT+30 date +%Y-%m-%d)\n$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1

The -e parameter used in the echo command is needed with bash, but will not work with ksh. In ksh you can use the same command without the -e flag.

When your script will be used in different environments, you can start the script with #!/bin/ksh or #!/bin/bash. You could also replace the \n by a newline:

echo "$(TZ=GMT+30 date +%Y-%m-%d)
$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1

What is the scope of variables in JavaScript?

Global Scope :

Global variables are exactly like global stars (Jackie Chan, Nelson Mandela). You can access them (get or set the value), from any part of your application. Global functions are like global events (New Year, Christmas). You can execute (call) them from any part of your application.

//global variable
var a = 2;

//global function
function b(){
   console.log(a);  //access global variable
}

Local Scope :

If you are in the USA, you may know Kim Kardashian, infamous celebrity ( she somehow manages to make the tabloids). But people outside of the USA will not recognize her. She is a local star, bound to her territory.

Local variables are like local stars. You can only access them (get or set the value) inside the scope. A local function is like local events - you can execute only (celebrate) inside that scope. If you want to access them from outside of the scope, you will get a reference error

function b(){
   var d = 21; //local variable
   console.log(d);

   function dog(){  console.log(a); }
     dog(); //execute local function
}

 console.log(d); //ReferenceError: dddddd is not defined    

Check this article for in-depth understanding of scope