Programs & Examples On #Two way

Two-way SSL clarification

In two way ssl the client asks for servers digital certificate and server ask for the same from the client. It is more secured as it is both ways, although its bit slow. Generally we dont follow it as the server doesnt care about the identity of the client, but a client needs to make sure about the integrity of server it is connecting to.

Two way sync with rsync

Try this,

get-music:
 rsync -avzru --delete-excluded server:/media/10001/music/ /media/Incoming/music/

put-music:
 rsync -avzru --delete-excluded /media/Incoming/music/ server:/media/10001/music/

sync-music: get-music put-music

I just test this and it worked for me. I'm doing a 2-way sync between Windows7 (using cygwin with the rsync package installed) and FreeNAS fileserver (FreeNAS runs on FreeBSD with rsync package pre-installed).

Argument list too long error for rm, cp, mv commands

you can try this:

for f in *.pdf
do
  rm "$f"
done

EDIT: ThiefMaster comment suggest me not to disclose such dangerous practice to young shell's jedis, so I'll add a more "safer" version (for the sake of preserving things when someone has a "-rf . ..pdf" file)

echo "# Whooooo" > /tmp/dummy.sh
for f in '*.pdf'
do
   echo "rm -i \"$f\""
done >> /tmp/dummy.sh

After running the above, just open the /tmp/dummy.sh file in your favorite editor and check every single line for dangerous filenames, commenting them out if found.

Then copy the dummy.sh script in your working dir and run it.

All this for security reasons.

Android canvas draw rectangle

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

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

public class MyView extends View {

 Paint paint;
 Path path;

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

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

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

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

 }

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

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

 }

}

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

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

For more details you can visit here

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

Generating random numbers with Swift

My implementation as an Int extension. Will generate random numbers in range from..<to

public extension Int {
    static func random(from: Int, to: Int) -> Int {
        guard to > from else {
            assertionFailure("Can not generate negative random numbers")
            return 0
        }
        return Int(arc4random_uniform(UInt32(to - from)) + UInt32(from))
    }
}

Storing C++ template function definitions in a .CPP file

This is definitely not a nasty hack, but be aware of the fact that you will have to do it (the explicit template specialization) for every class/type you want to use with the given template. In case of MANY types requesting template instantiation there can be A LOT of lines in your .cpp file. To remedy this problem you can have a TemplateClassInst.cpp in every project you use so that you have greater control what types will be instantiated. Obviously this solution will not be perfect (aka silver bullet) as you might end up breaking the ODR :).

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

At terminal run this command with root permission:

sudo /etc/init.d/apache2 start

You must be root for starting a webserver otherwise you would get similar error.

Mod of negative number is melting my brain

A single line implementation of dcastro's answer (the most compliant with other languages):

int Mod(int a, int n)
{
    return (((a %= n) < 0) && n > 0) || (a > 0 && n < 0) ? a + n : a;
}

If you'd like to keep the use of % operator (you can't overload native operators in C#):

public class IntM
{
    private int _value;

    private IntM(int value)
    {
        _value = value;
    }

    private static int Mod(int a, int n)
    {
        return (((a %= n) < 0) && n > 0) || (a > 0 && n < 0) ? a + n : a;
    }

    public static implicit operator int(IntM i) => i._value;
    public static implicit operator IntM(int i) => new IntM(i);
    public static int operator %(IntM a, int n) => Mod(a, n);
    public static int operator %(int a, IntM n) => Mod(a, n);
}

Use case, both works:

int r = (IntM)a % n;

// Or
int r = a % n(IntM);

How to grep for contents after pattern?

grep 'potato:' file.txt | sed 's/^.*: //'

grep looks for any line that contains the string potato:, then, for each of these lines, sed replaces (s/// - substitute) any character (.*) from the beginning of the line (^) until the last occurrence of the sequence : (colon followed by space) with the empty string (s/...// - substitute the first part with the second part, which is empty).

or

grep 'potato:' file.txt | cut -d\   -f2

For each line that contains potato:, cut will split the line into multiple fields delimited by space (-d\ - d = delimiter, \ = escaped space character, something like -d" " would have also worked) and print the second field of each such line (-f2).

or

grep 'potato:' file.txt | awk '{print $2}'

For each line that contains potato:, awk will print the second field (print $2) which is delimited by default by spaces.

or

grep 'potato:' file.txt | perl -e 'for(<>){s/^.*: //;print}'

All lines that contain potato: are sent to an inline (-e) Perl script that takes all lines from stdin, then, for each of these lines, does the same substitution as in the first example above, then prints it.

or

awk '{if(/potato:/) print $2}' < file.txt

The file is sent via stdin (< file.txt sends the contents of the file via stdin to the command on the left) to an awk script that, for each line that contains potato: (if(/potato:/) returns true if the regular expression /potato:/ matches the current line), prints the second field, as described above.

or

perl -e 'for(<>){/potato:/ && s/^.*: // && print}' < file.txt

The file is sent via stdin (< file.txt, see above) to a Perl script that works similarly to the one above, but this time it also makes sure each line contains the string potato: (/potato:/ is a regular expression that matches if the current line contains potato:, and, if it does (&&), then proceeds to apply the regular expression described above and prints the result).

user authentication libraries for node.js?

Also have a look at everyauth if you want third party/social network login integration.

How to do jquery code AFTER page loading?

You can avoid get undefined in '$' this way

window.addEventListener("DOMContentLoaded", function(){
    // Your code
});

EDIT: Using 'DOMContentLoaded' is faster than just 'load' because load wait page fully loaded, imgs included... while DomContentLoaded waits just the structure

Extracting Path from OpenFileDialog path/filename

Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.

Usage is simple.

string directoryPath = Path.GetDirectoryName(filePath);

Multiple Inheritance in C#

Multiple inheritance is one of those things that generally causes more problems than it solves. In C++ it fits the pattern of giving you enough rope to hang yourself, but Java and C# have chosen to go the safer route of not giving you the option. The biggest problem is what to do if you inherit multiple classes that have a method with the same signature that the inheritee doesn't implement. Which class's method should it choose? Or should that not compile? There is generally another way to implement most things that doesn't rely on multiple inheritance.

JavaFX 2.1 TableView refresh items

Since JavaFX 8u60 you can use(assuming tableView is an instance of TableView class):

tableView.refresh();

From the documentation:

Calling refresh() forces the TableView control to recreate and repopulate the cells necessary to populate the visual bounds of the control. In other words, this forces the TableView to update what it is showing to the user. This is useful in cases where the underlying data source has changed in a way that is not observed by the TableView itself.

Programmatically add new column to DataGridView

Here's a sample method that adds two extra columns programmatically to the grid view:

    private void AddColumnsProgrammatically()
    {
        // I created these columns at function scope but if you want to access 
        // easily from other parts of your class, just move them to class scope.
        // E.g. Declare them outside of the function...
        var col3 = new DataGridViewTextBoxColumn();
        var col4 = new DataGridViewCheckBoxColumn();

        col3.HeaderText = "Column3";
        col3.Name = "Column3";

        col4.HeaderText = "Column4";
        col4.Name = "Column4";

        dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
    }

A great way to figure out how to do this kind of process is to create a form, add a grid view control and add some columns. (This process will actually work for ANY kind of form control. All instantiation and initialization happens in the Designer.) Then examine the form's Designer.cs file to see how the construction takes place. (Visual Studio does everything programmatically but hides it in the Form Designer.)

For this example I created two columns for the view named Column1 and Column2 and then searched Form1.Designer.cs for Column1 to see everywhere it was referenced. The following information is what I gleaned and, copied and modified to create two more columns dynamically:

// Note that this info scattered throughout the designer but can easily collected.

        System.Windows.Forms.DataGridViewTextBoxColumn Column1;
        System.Windows.Forms.DataGridViewCheckBoxColumn Column2;

        this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();

        this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
        this.Column1,
        this.Column2});

        this.Column1.HeaderText = "Column1";
        this.Column1.Name = "Column1";

        this.Column2.HeaderText = "Column2";
        this.Column2.Name = "Column2";

AngularJs: How to set radio button checked based on model

As discussed somewhat in the question comments, this is one way you could do it:

  • When you first retrieve the data, loop through all locations and set storeDefault to the store that is currently the default.
  • In the markup: <input ... ng-model="$parent.storeDefault" value="{{location.id}}">
  • Before you save the data, loop through all the merchant.storeLocations and set isDefault to false except for the store where location.id compares equal to storeDefault.

The above assumes that each location has a field (e.g., id) that holds a unique value.

Note that $parent.storeDefault is used because ng-repeat creates a child scope, and we want to manipulate the storeDefault parameter on the parent scope.

Fiddle.

How can I create an observable with a delay

It's little late to answer ... but just in case may be someone return to this question looking for an answer

'delay' is property(function) of an Observable

fakeObservable = Observable.create(obs => {
  obs.next([1, 2, 3]);
  obs.complete();
}).delay(3000);

This worked for me ...

Round a divided number in Bash

If you have integer division of positive numbers which rounds toward zero, then you can add one less than the divisor to the dividend to make it round up.

That is to say, replace X / Y with (X + Y - 1) / Y.

Proof:

  • Case 1: X = k * Y (X is integer multiple of Y): In this case, we have (k * Y + Y - 1) / Y, which splits into (k * Y) / Y + (Y - 1) / Y. The (Y - 1)/Y part rounds to zero, and we are left with a quotient of k. This is exactly what we want: when the inputs are divisible, we want the adjusted calculation to still produce the correct exact quotient.

  • Case 2: X = k * Y + m where 0 < m < Y (X is not a multiple of Y). In this case we have a numerator of k * Y + m + Y - 1, or k * Y + Y + m - 1, and we can write the division out as (k * Y)/Y + Y/Y + (m - 1)/Y. Since 0 < m < Y, 0 <= m - 1 < Y - 1, and so the last term (m - 1)/Y goes to zero. We are left with (k * Y)/Y + Y/Y which work out to k + 1. This shows that the behavior rounds up. If we have an X which is a k multiple of Y, if we add just 1 to it, the division rounds up to k + 1.

But this rounding is extremely opposite; all inexact divisions go away from zero. How about something in between?

That can be achieved by "priming" the numerator with Y/2. Instead of X/Y, calculate (X+Y/2)/Y. Instead of proof, let's go empirical on this one:

$ round()
> {
>   echo $((($1 + $2/2) / $2))
> }
$ round 4 10
0
$ round 5 10
1
$ round 6 10
1
$ round 9 10
1
$ round 10 10
1
$ round 14 10
1
$ round 15 10
2

Whenever the divisor is an even, positive number, if the numerator is congruent to half that number, it rounds up, and rounds down if it is one less than that.

For instance, round 6 12 goes to 1, as do all values which are equal to 6, modulo 12, like 18 (which goes to 2) and so on. round 5 12 goes down to 0.

For odd numbers, the behavior is correct. None of the exact rational numbers are midway between two consecutive multiples. For instance, with a denominator of 11 we have 5/11 < 5.5/11 (exact middle) < 6/11; and round 5 11 rounds down, whereas round 6 11 rounds up.

How do I redirect with JavaScript?

To redirect to another page, you can use:

window.location = "http://www.yoururl.com";

Reading a string with spaces with sscanf

The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]).

sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer);

including parameters in OPENQUERY

Combine Dynamic SQL with OpenQuery. (This goes to a Teradata server)

DECLARE 
    @dayOfWk    TINYINT = DATEPART(DW, GETDATE()),
    @qSQL       NVARCHAR(MAX) = '';

SET @qSQL = '
SELECT
    *
FROM
    OPENQUERY(TERASERVER,''
        SELECT DISTINCT
            CASE
                WHEN ' + CAST(@dayOfWk AS NCHAR(1)) + ' = 2
                THEN ''''Monday''''
                ELSE ''''Not Monday''''
            END
        '');';

EXEC sp_executesql @qSQL;

ASP.NET MVC - passing parameters to the controller

Using the ASP.NET Core Tag Helper feature:

<a asp-controller="Home" asp-action="SetLanguage" asp-route-yourparam1="@item.Value">@item.Text</a>

How to get Django and ReactJS to work together?

Hoping to provide a more nuanced answer than any of the ones here, especially as some things have changed since this was originally asked ~4 years ago, and because many of the top-voted answers claiming that you have to set this up as two separate applications are not accurate.

You have two primary architecture options:

  1. A completely decoupled client/server approach using something like create-react-app and Django REST Framework
  2. A hybrid architecture where you set up a React build pipeline (likely using webpack) and then include the compiled files as static files in your Django templates.

These might look something like this:

Option 1 (Client/Server Architecture):

Client / Server Architecture

Option 2 (Hybrid Architecture):

Hybrid Architecture

The decision between these two will depend on your / your team's experience, as well as the complexity of your UI. The first option is good if you have a lot of JS experience, want to keep your front-end / back-end developers separate, or want to write your entire application as a React single-page-app. The second option is generally better if you are more familiar with Django and want to move quickly while also using React for some parts of your app. I find it's a particularly good fit for full-stack solo-developers.

There is a lot more information in the series "Modern JavaScript for Django Developers", including choosing your architecture, integrating your JS build into a Django project and building a single-page React app.

Full disclosure, I'm the author of that series.

Angular window resize event

@Günter's answer is correct. I just wanted to propose yet another method.

You could also add the host-binding inside the @Component()-decorator. You can put the event and desired function call in the host-metadata-property like so:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  host: {
    '(window:resize)': 'onResize($event)'
  }
})
export class AppComponent{
   onResize(event){
     event.target.innerWidth; // window width
   }
}

Converting NSData to NSString in Objective c

Swift:

let jsonString = String(data: jsonData, encoding: .ascii)

or .utf8 or whatever encoding appropriate

PHP date() with timezone?

It should like this:

date_default_timezone_set('America/New_York');

How to convert Varchar to Int in sql server 2008?

There are two type of convert method in SQL.

CAST and CONVERT have similar functionality. CONVERT is specific to SQL Server, and allows for a greater breadth of flexibility when converting between date and time values, fractional numbers, and monetary signifiers. CAST is the more ANSI-standard of the two functions.

Using Convert

Select convert(int,[Column1])

Using Cast

Select cast([Column1] as int)

Proxy Basic Authentication in C#: HTTP 407 error

You can use like this, it works!

        WebProxy proxy = new WebProxy
        {
            Address = new Uri(""),
            Credentials = new NetworkCredential("", "")
        };

        HttpClientHandler httpClientHandler = new HttpClientHandler
        {
            Proxy = proxy,
            UseProxy = true
        };

        HttpClient client = new HttpClient(httpClientHandler);

        HttpResponseMessage response = await client.PostAsync("...");

How do you reinstall an app's dependencies using npm?

The right way is to execute npm update. It's a really powerful command, it updates the missing packages and also checks if a newer version of package already installed can be used.

Read Intro to NPM to understand what you can do with npm.

Angular no provider for NameService

You need to add it to providers array, which includes all depency on your component.

Look at this section in angular documentation:

Registering providers in a component

Here's a revised HeroesComponent that registers the HeroService in its providers array.

import { Component } from '@angular/core';

import { HeroService } from './hero.service';

@Component({
  selector: 'my-heroes',
  providers: [HeroService],
  template: `
  <h2>Heroes</h2>
  <hero-list></hero-list>
  `
})
export class HeroesComponent { }

When to use NgModule versus an application component

On the one hand, a provider in an NgModule is registered in the root injector. That means that every provider registered within an NgModule will be accessible in the entire application.

On the other hand, a provider registered in an application component is available only on that component and all its children.

Here, the APP_CONFIG service needs to be available all across the application, so it's registered in the AppModule @NgModule providers array. But since the HeroService is only used within the Heroes feature area and nowhere else, it makes sense to register it in the HeroesComponent.

Also see "Should I add app-wide providers to the root AppModule or the root AppComponent?" in the NgModule FAQ.

So in your case, simply change injectables to providers like below:

@Component({
  selector: 'my-app',
  providers: [NameService]
})

Also in the new versions of Angular, @View and some other stuffs gone.

For more info ,visit here.

Clear contents of cells in VBA using column reference

I found this an easy way of cleaning in a shape between the desired row and column. I am not sure if this is what you are looking for. Hope it helps.

Sub sbClearCellsOnlyData()
Range("A1:C10").ClearContents
End Sub

What is the syntax meaning of RAISERROR()

16 is severity and 1 is state, more specifically following example might give you more detail on syntax and usage:

BEGIN TRY
    -- RAISERROR with severity 11-19 will cause execution to 
    -- jump to the CATCH block.
    RAISERROR ('Error raised in TRY block.', -- Message text.
               16, -- Severity.
               1 -- State.
               );
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

You can follow and try out more examples from http://msdn.microsoft.com/en-us/library/ms178592.aspx

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

I also had a similar issue. After copying and pasting to a sheet I wanted the cursor/ selected cell to be A1 not the range that I just pasted into.

Dim wkSheet as Worksheet
Set wkSheet = Worksheets(<sheetname>)

wkSheet("A1").Select

but got a 400 error which was actually a 1004 error

You need to activate the sheet before changing the selected cell this worked

Dim wkSheet as Worksheet
Set wkSheet = Worksheets(<sheetname>)

wkSheet.Activate
wkSheet("A1").Select

pip install: Please check the permissions and owner of that directory

What is the problem here is that you somehow installed into virtualenv using sudo. Probably by accident. This means root user will rewrite Python package data, making all file owned by root and your normal user cannot write those files anymore. Usually virtualenv should be used and owned by your normal UNIX user only.

You can fix the issue by changing UNIX file permissions pack to your user. Try:

$ sudo chown -R USERNAME /Users/USERNAME/Library/Logs/pip
$ sudo chown -R USERNAME /Users/USERNAME/Library/Caches/pip

then pip should be able to write those files again.

More information about UNIX file permission management

Change select box option background color

You need to put background-color on the option tag and not the select tag...

select option {
    margin: 40px;
    background: rgba(0, 0, 0, 0.3);
    color: #fff;
    text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
}

If you want to style each one of the option tags.. use the css attribute selector:

_x000D_
_x000D_
select option {_x000D_
  margin: 40px;_x000D_
  background: rgba(0, 0, 0, 0.3);_x000D_
  color: #fff;_x000D_
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);_x000D_
}_x000D_
_x000D_
select option[value="1"] {_x000D_
  background: rgba(100, 100, 100, 0.3);_x000D_
}_x000D_
_x000D_
select option[value="2"] {_x000D_
  background: rgba(150, 150, 150, 0.3);_x000D_
}_x000D_
_x000D_
select option[value="3"] {_x000D_
  background: rgba(200, 200, 200, 0.3);_x000D_
}_x000D_
_x000D_
select option[value="4"] {_x000D_
  background: rgba(250, 250, 250, 0.3);_x000D_
}
_x000D_
<select>_x000D_
  <option value="">Please choose</option>_x000D_
  <option value="1">Option 1</option>_x000D_
  <option value="2">Option 2</option>_x000D_
  <option value="3">Option 3</option>_x000D_
  <option value="4">Option 4</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

"if not exist" command in batch file

if not exist "%USERPROFILE%\.qgis-custom\" (
    mkdir "%USERPROFILE%\.qgis-custom" 2>nul
    if not errorlevel 1 (
        xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
    )
)

You have it almost done. The logic is correct, just some little changes.

This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).

If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.

If everyting is ok, files are copied.

All paths are quoted to avoid problems with spaces.

It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files

mkdir "%USERPROFILE%\.qgis-custom" 2>nul 
if not errorlevel 1 (
    xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)

In both code samples, files are not copied if the folder is not being created during the script execution.

EDITED - As dbenham comments, the same code can be written as a single line

md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e

The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.

Best Practice: Access form elements by HTML id or name attribute?

It’s not really answering your question, but just on this part:

[3] requires both an id and a name... having both is somewhat redundant

You’ll most likely need to have an id attribute on each form field anyway, so that you can associate its <label> element with it, like this:

<label for="foo">Foo:</label>
<input type="text" name="foo" id="foo" />

This is required for accessibility (i.e. if you don’t associate form labels and controls, why do you hate blind people so much?).

It is somewhat redundant, although less so when you have checkboxes/radio buttons, where several of them can share a name. Ultimately, id and name are for different purposes, even if both are often set to the same value.

SQL (MySQL) vs NoSQL (CouchDB)

Here's a quote from a recent blog post from Dare Obasanjo.

SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.

However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.

To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.

Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.

Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)

I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL

Make WPF Application Fullscreen (Cover startmenu)

You can also do it at run time as follows :

  • Assign name to the window (x:Name = "HomePage")
  • In constructor just set WindowState property to Maximized as follows

HomePage.WindowState = WindowState.Maximized;

How to get the URL of the current page in C#

Try this :

string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx

string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx

string host = HttpContext.Current.Request.Url.Host;
// localhost

vector vs. list in STL

Well the students of my class seems quite unable to explain to me when it is more effective to use vectors, but they look quite happy when advising me to use lists.

This is how I understand it

Lists: Each item contains an address to the next or previous element, so with this feature, you can randomize the items, even if they aren't sorted, the order won't change: it's efficient if you memory is fragmented. But it also has an other very big advantage: you can easily insert/remove items, because the only thing you need to do is change some pointers. Drawback: To read a random single item, you have to jump from one item to another until you find the correct address.

Vectors: When using vectors, the memory is much more organized like regular arrays: each n-th items is stored just after (n-1)th item and before (n+1)th item. Why is it better than list ? Because it allow fast random access. Here is how: if you know the size of an item in a vector, and if they are contiguous in memory, you can easily predict where the n-th item is; you don't have to browse all the item of a list to read the one you want, with vector, you directly read it, with a list you can't. On the other hand, modify the vector array or change a value is much more slow.

Lists are more appropriate to keep track of objects which can be added/removed in memory. Vectors are more appropriate when you want to access an element from a big quantity of single items.

I don't know how lists are optimized, but you have to know that if you want fast read access, you should use vectors, because how good the STL fasten lists, it won't be as fast in read-access than vector.

Is there a way to get colored text in GitHubflavored Markdown?

You cannot include style directives in GFM.

The most complete documentation/example is "Markdown Cheatsheet", and it illustrates that this element <style> is missing.

If you manage to include your text in one of the GFM elements, then you can play with a github.css stylesheet in order to colors that way, meaning to color using inline CSS style directives, referring to said css stylesheet.

Remove 'standalone="yes"' from generated XML

You can use: marshaller.setProperty("jaxb.fragment", Boolean.TRUE);

It works for me on Java 8

Is there a better way to do optional function parameters in JavaScript?

  1. arg || 'default' is a great way and works for 90% of cases

  2. It fails when you need to pass values that might be 'falsy'

    • false
    • 0
    • NaN
    • ""

    For these cases you will need to be a bit more verbose and check for undefined

  3. Also be careful when you have optional arguments first, you have to be aware of the types of all of your arguments

Alphabet range in Python

In Python 2.7 and 3 you can use this:

import string
string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

As @Zaz says: string.lowercase is deprecated and no longer works in Python 3 but string.ascii_lowercase works in both

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

In Angular, how to redirect with $location.path as $http.post success callback

I am doing the below for page redirection(from login to home page). I have to pass the user object also to the home page. so, i am using windows localstorage.

    $http({
        url:'/login/user',
        method : 'POST',
        headers: {
            'Content-Type': 'application/json'
          },
        data: userData
    }).success(function(loginDetails){
        $scope.updLoginDetails = loginDetails;
        if($scope.updLoginDetails.successful == true)
            {
                loginDetails.custId = $scope.updLoginDetails.customerDetails.cust_ID;
                loginDetails.userName = $scope.updLoginDetails.customerDetails.cust_NM;
                window.localStorage.setItem("loginDetails", JSON.stringify(loginDetails));
                $window.location='/login/homepage';
            }
        else
        alert('No access available.');

    }).error(function(err,status){
        alert('No access available.');      
    });

And it worked for me.

jQuery’s .bind() vs. .on()

Internally, .bind maps directly to .on in the current version of jQuery. (The same goes for .live.) So there is a tiny but practically insignificant performance hit if you use .bind instead.

However, .bind may be removed from future versions at any time. There is no reason to keep using .bind and every reason to prefer .on instead.

multiple conditions for filter in spark data frames

This question has been answered but for future reference, I would like to mention that, in the context of this question, the where and filter methods in Dataset/Dataframe supports two syntaxes: The SQL string parameters:

df2 = df1.filter(("Status = 2 or Status = 3"))

and Col based parameters (mentioned by @David ):

df2 = df1.filter($"Status" === 2 || $"Status" === 3)

It seems the OP'd combined these two syntaxes. Personally, I prefer the first syntax because it's cleaner and more generic.

How to get the last characters in a String in Java, regardless of String size

This question is the top Google result for "Java String Right".

Surprisingly, no-one has yet mentioned Apache Commons StringUtils.right():

String numbers = org.apache.commons.lang.StringUtils.right( text, 7 );

This also handles the case where text is null, where many of the other answers would throw a NullPointerException.

Abstract Class vs Interface in C++

An abstract class would be used when some common implementation was required. An interface would be if you just want to specify a contract that parts of the program have to conform too. By implementing an interface you are guaranteeing that you will implement certain methods. By extending an abstract class you are inheriting some of it's implementation. Therefore an interface is just an abstract class with no methods implemented (all are pure virtual).

What is the use of the square brackets [] in sql statements?

I believe it adds them there for consistency... they're only required when you have a space or special character in the column name, but it's cleaner to just include them all the time when the IDE generates SQL.

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

This problem bugs me for a long time since none of the work-around worked for me :(

But good news is, the following method works fine for my application.

The basic idea is to register a EventManager in App.xmal.cs to sniff PreviewMouseLeftButtonDownEvent for all ComboBoxItem, then trigger the SelectionChangedEvent if the selecting item is the same as the selected item, i.e. the selection is performed without changing index.

In App.xmal.cs:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        // raise selection change event even when there's no change in index
        EventManager.RegisterClassHandler(typeof(ComboBoxItem), UIElement.PreviewMouseLeftButtonDownEvent,
                                          new MouseButtonEventHandler(ComboBoxSelfSelection), true);

        base.OnStartup(e);
    }

    private static void ComboBoxSelfSelection(object sender, MouseButtonEventArgs e)
    {
        var item = sender as ComboBoxItem;

        if (item == null) return;

        // find the combobox where the item resides
        var comboBox = ItemsControl.ItemsControlFromItemContainer(item) as ComboBox;

        if (comboBox == null) return;

        // fire SelectionChangedEvent if two value are the same
        if ((string)comboBox.SelectedValue == (string)item.Content)
        {
            comboBox.IsDropDownOpen = false;
            comboBox.RaiseEvent(new SelectionChangedEventArgs(Selector.SelectionChangedEvent, new ListItem(), new ListItem()));
        }
    }
}

Then, for all combo boxes, register SelectionChangedEvent in a normal way:

<ComboBox ItemsSource="{Binding BindList}"
          SelectionChanged="YourSelectionChangedEventHandler"/>

Now, if two indices are different, nothing special but the ordinary event handling process; if two indices are the same, the Mouse Event on the item will first be handled, and thus trigger the SelectionChangedEvent. In this way, both situations will trigger SelectionChangedEvent :)

Test file upload using HTTP PUT method

If you're using PHP you can test your PUT upload using the code below:

#Initiate cURL object
$curl = curl_init();
#Set your URL
curl_setopt($curl, CURLOPT_URL, 'https://local.simbiat.ru');
#Indicate, that you plan to upload a file
curl_setopt($curl, CURLOPT_UPLOAD, true);
#Indicate your protocol
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#Set flags for transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
#Disable header (optional)
curl_setopt($curl, CURLOPT_HEADER, false);
#Set HTTP method to PUT
curl_setopt($curl, CURLOPT_PUT, 1);
#Indicate the file you want to upload
curl_setopt($curl, CURLOPT_INFILE, fopen('path_to_file', 'rb'));
#Indicate the size of the file (it does not look like this is mandatory, though)
curl_setopt($curl, CURLOPT_INFILESIZE, filesize('path_to_file'));
#Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#Execute
curl_exec($curl);

html form - make inputs appear on the same line

Try just putting a div around the first and last name inputs/labels like this:

<div class="name">
        <label for="First_Name">First Name:</label>
        <input name="first_name" id="First_Name" type="text" />

        <label for="Name">Last Name:</label>
        <input name="last_name" id="Last_Name" type="text" /> 
</div>

Look at the fiddle here: http://jsfiddle.net/XAkXg/

Using curl to upload POST data with files

After a lot of tries this command worked for me:

curl -v -F filename=image.jpg -F [email protected] http://localhost:8080/api/upload

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

Is there a rule-of-thumb for how to divide a dataset into training and validation sets?

Suppose you have less data, I suggest to try 70%, 80% and 90% and test which is giving better result. In case of 90% there are chances that for 10% test you get poor accuracy.

How to get current date & time in MySQL?

In database design, iIhighly recommend using Unixtime for consistency and indexing / search / comparison performance.

UNIX_TIMESTAMP() 

One can always convert to human readable formats afterwards, internationalizing as is individually most convenient.

FROM_ UNIXTIME (unix_timestamp, [format ])

Download File Using Javascript/jQuery

Simple example using an iframe

function downloadURL(url) {
    var hiddenIFrameID = 'hiddenDownloader',
        iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
        iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;
};

Then just call the function wherever you want:

downloadURL('path/to/my/file');

How do I release memory used by a pandas dataframe?

It seems there is an issue with glibc that affects the memory allocation in Pandas: https://github.com/pandas-dev/pandas/issues/2659

The monkey patch detailed on this issue has resolved the problem for me:

# monkeypatches.py

# Solving memory leak problem in pandas
# https://github.com/pandas-dev/pandas/issues/2659#issuecomment-12021083
import pandas as pd
from ctypes import cdll, CDLL
try:
    cdll.LoadLibrary("libc.so.6")
    libc = CDLL("libc.so.6")
    libc.malloc_trim(0)
except (OSError, AttributeError):
    libc = None

__old_del = getattr(pd.DataFrame, '__del__', None)

def __new_del(self):
    if __old_del:
        __old_del(self)
    libc.malloc_trim(0)

if libc:
    print('Applying monkeypatch for pd.DataFrame.__del__', file=sys.stderr)
    pd.DataFrame.__del__ = __new_del
else:
    print('Skipping monkeypatch for pd.DataFrame.__del__: libc or malloc_trim() not found', file=sys.stderr)

Make a dictionary with duplicate keys in Python

You can change the behavior of the built in types in Python. For your case it's really easy to create a dict subclass that will store duplicated values in lists under the same key automatically:

class Dictlist(dict):
    def __setitem__(self, key, value):
        try:
            self[key]
        except KeyError:
            super(Dictlist, self).__setitem__(key, [])
        self[key].append(value)

Output example:

>>> d = dictlist.Dictlist()
>>> d['test'] = 1
>>> d['test'] = 2
>>> d['test'] = 3
>>> d
{'test': [1, 2, 3]}
>>> d['other'] = 100
>>> d
{'test': [1, 2, 3], 'other': [100]}

How to produce an csv output file from stored procedure in SQL Server

You can do this using OPENROWSET as suggested in this answer. Reposting Slogmeister Extrarodinare answer:

Use T-SQL

INSERT INTO OPENROWSET ('Microsoft.ACE.OLEDB.12.0','Text;Database=D:\;HDR=YES;FMT=Delimited','SELECT * FROM [FileName.csv]')
SELECT Field1, Field2, Field3 FROM DatabaseName

But, there are couple of caveats:

  1. You need to have the Microsoft.ACE.OLEDB.12.0 provider available. The Jet 4.0 provider will work, too, but it's ancient, so I used this one instead.

  2. The .CSV file will have to exist already. If you're using headers (HDR=YES), make sure the first line of the .CSV file is a delimited list of all the fields.

Difference between adjustResize and adjustPan in android?

As doc says also keep in mind the correct value combination:

The setting must be one of the values listed in the following table, or a combination of one "state..." value plus one "adjust..." value. Setting multiple values in either group — multiple "state..." values, for example — has undefined results. Individual values are separated by a vertical bar (|). For example:

<activity android:windowSoftInputMode="stateVisible|adjustResize" . . . >

Get root password for Google Cloud Engine VM

This work at least in the Debian Jessie image hosted by Google:

The way to enable to switch from you regular to the root user (AKA “super user”) after authentificating with your Google Computer Engine (GCE) User in the local environment (your Linux server in GCE) is pretty straight forward, in fact it just involves just one command to enable it and another every time to use it:

$ sudo passwd
Enter the new UNIX password: <your new root password>
Retype the new UNIX password: <your new root password>
passwd: password updated successfully

After executing the previous command and once logged with your GCE User you will be able to switch to root anytime by just entering the following command:

$ su
Password: <your newly created root password>
root@intance:/#

As we say in economics “caveat emptor” or buyer be aware: Using the root user is far from a best practice in system’s administration. Using it can be the cause a lot of trouble, from wiping everything in your drives and boot disks without a hiccup to many other nasty stuff that would be laborious to backtrack, troubleshoot and rebuilt. On the other hand, I have never met a SysAdmin that doesn’t think he knows better and root more than he should.

REMEMBER: We humans are programmed in such a way that given enough time at one at some point or another are going to press enter without taking into account that we have escalated to root and I can assure you that it will great source of pain, regret and extra work. PLEASE USE ROOT PRIVILEGES SPARSELY AND WITH EXTREME CARE.

Having said all the boring stuff, Have fun, live on the edge, life is short, you only get to live it once, the more you break the more you learn.

Get current working directory in a Qt application

I'm running Qt 5.5 under Windows and the default constructor of QDir appears to pick up the current working directory, not the application directory.

I'm not sure if the getenv PWD will work cross-platform and I think it is set to the current working directory when the shell launched the application and doesn't include any working directory changes done by the app itself (which might be why the OP is seeing this behavior).

So I thought I'd add some other ways that should give you the current working directory (not the application's binary location):

// using where a relative filename will end up
QFileInfo fi("temp");
cout << fi.absolutePath() << endl;

// explicitly using the relative name of the current working directory
QDir dir(".");
cout << dir.absolutePath() << endl;

How to extract .war files in java? ZIP vs JAR

If you using Linux or Ubuntu than you can directly extract data from .war file.

A war file is just a jar file, to extract it, just issue following command using the jar program:

jar -xvf yourWARfileName.war

How do I change Android Studio editor's background color?

How do I change Android Studio editor's background color?

Changing Editor's Background

Open Preference > Editor (In IDE Settings Section) > Colors & Fonts > Darcula or Any item available there

IDE will display a dialog like this, Press 'No'

Darcula color scheme has been set for editors. Would you like to set Darcula as default Look and Feel?

Changing IDE's Theme

Open Preference > Appearance (In IDE Settings Section) > Theme > Darcula or Any item available there

Press OK. Android Studio will ask you to restart the IDE.

Android saving file to external storage

Click Here for full description and source code

public void saveImage(Context mContext, Bitmap bitmapImage) {

  File sampleDir = new File(Environment.getExternalStorageDirectory() + "/" + "ApplicationName");

  TextView tvImageLocation = (TextView) findViewById(R.id.tvImageLocation);
  tvImageLocation.setText("Image Store At : " + sampleDir);

  if (!sampleDir.exists()) {
      createpathForImage(mContext, bitmapImage, sampleDir);
  } else {
      createpathForImage(mContext, bitmapImage, sampleDir);
  }
}

$rootScope.$broadcast vs. $scope.$emit

enter image description here

$scope.$emit: This method dispatches the event in the upwards direction (from child to parent)

enter image description here $scope.$broadcast: Method dispatches the event in the downwards direction (from parent to child) to all the child controllers.

enter image description here $scope.$on: Method registers to listen to some event. All the controllers which are listening to that event get notification of the broadcast or emit based on the where those fit in the child-parent hierarchy.

The $emit event can be cancelled by any one of the $scope who is listening to the event.

The $on provides the "stopPropagation" method. By calling this method the event can be stopped from propagating further.

Plunker :https://embed.plnkr.co/0Pdrrtj3GEnMp2UpILp4/

In case of sibling scopes (the scopes which are not in the direct parent-child hierarchy) then $emit and $broadcast will not communicate to the sibling scopes.

enter image description here

For more details please refer to http://yogeshtutorials.blogspot.in/2015/12/event-based-communication-between-angularjs-controllers.html

ASP.Net MVC 4 Form with 2 submit buttons/actions

That's what we have in our applications:
Attribute

public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
            return true;

        var request = controllerContext.RequestContext.HttpContext.Request;
        return request[methodInfo.Name] != null;
    }
}

Actions decorated with it:


[HttpParamAction]
public ActionResult Save(MyModel model)
{
    // ...
}

[HttpParamAction]
public ActionResult Publish(MyModel model)
{
    // ...
}

HTML/Razor

@using (@Html.BeginForm())
{
    <!-- form content here -->
    <input type="submit" name="Save" value="Save" />
    <input type="submit" name="Publish" value="Publish" />
}

name attribute of submit button should match action/method name

This way you do not have to hard-code urls in javascript

Base table or view not found: 1146 Table Laravel 5

If your error is not related to the issue of

Laravel can't determine the plural form of the word you used for your table name.

with this solution

and still have this error, try my approach. you should find the problem in the default "AppServiceProvider.php" or other ServiceProviders defined for that application specifically or even in Kernel.php in App\Console

This error happened for me and I solved it temporary and still couldn't figure out the exact origin and description.

In my case the main problem for causing my table unable to migrate, is that I have running code/query on my "PermissionsServiceProvider.php" in the boot() method.

In the same way, maybe, you defined something in boot() method of AppServiceProvider.php or in the Kernel.php

So first check your Serviceproviders and disable code for a while, and run php artisan migrate and then undo changes in your code.

Breaking out of a nested loop

Well, goto, but that is ugly, and not always possible. You can also place the loops into a method (or an anon-method) and use return to exit back to the main code.

    // goto
    for (int i = 0; i < 100; i++)
    {
        for (int j = 0; j < 100; j++)
        {
            goto Foo; // yeuck!
        }
    }
Foo:
    Console.WriteLine("Hi");

vs:

// anon-method
Action work = delegate
{
    for (int x = 0; x < 100; x++)
    {
        for (int y = 0; y < 100; y++)
        {
            return; // exits anon-method
        }
    }
};
work(); // execute anon-method
Console.WriteLine("Hi");

Note that in C# 7 we should get "local functions", which (syntax tbd etc) means it should work something like:

// local function (declared **inside** another method)
void Work()
{
    for (int x = 0; x < 100; x++)
    {
        for (int y = 0; y < 100; y++)
        {
            return; // exits local function
        }
    }
};
Work(); // execute local function
Console.WriteLine("Hi");

Android Paint: .measureText() vs .getTextBounds()

Sorry for answering again on that question... I needed to embed the image.

I think the results @mice found are missleading. The observations might be correct for the font size of 60 but they turn much more different when the text is smaller. Eg. 10px. In that case the text is actually drawn BEYOND the bounds.

enter image description here

Sourcecode of the screenshot:

  @Override
  protected void onDraw( Canvas canvas ) {
    for( int i = 0; i < 20; i++ ) {
      int startSize = 10;
      int curSize = i + startSize;
      paint.setTextSize( curSize );
      String text = i + startSize + " - " + TEXT_SNIPPET;
      Rect bounds = new Rect();
      paint.getTextBounds( text, 0, text.length(), bounds );
      float top = STEP_DISTANCE * i + curSize;
      bounds.top += top;
      bounds.bottom += top;
      canvas.drawRect( bounds, bgPaint );
      canvas.drawText( text, 0, STEP_DISTANCE * i + curSize, paint );
    }
  }

What's the best practice for primary keys in tables?

I follow a few rules:

  1. Primary keys should be as small as necessary. Prefer a numeric type because numeric types are stored in a much more compact format than character formats. This is because most primary keys will be foreign keys in another table as well as used in multiple indexes. The smaller your key, the smaller the index, the less pages in the cache you will use.
  2. Primary keys should never change. Updating a primary key should always be out of the question. This is because it is most likely to be used in multiple indexes and used as a foreign key. Updating a single primary key could cause of ripple effect of changes.
  3. Do NOT use "your problem primary key" as your logic model primary key. For example passport number, social security number, or employee contract number as these "primary key" can change for real world situations.

On surrogate vs natural key, I refer to the rules above. If the natural key is small and will never change it can be used as a primary key. If the natural key is large or likely to change I use surrogate keys. If there is no primary key I still make a surrogate key because experience shows you will always add tables to your schema and wish you'd put a primary key in place.

Mysql database sync between two databases

SymmetricDS is the answer. It supports multiple subscribers with one direction or bi-directional asynchronous data replication. It uses web and database technologies to replicate tables between relational databases, in near real time if desired.

Comprehensive and robust Java API to suit your needs.

How to escape a single quote inside awk

For small scripts an optional way to make it readable is to use a variable like this:

awk -v fmt="'%s'\n" '{printf fmt, $1}'

I found it conveninet in a case where I had to produce many times the single-quote character in the output and the \047 were making it totally unreadable

How to uninstall Eclipse?

There is no automated uninstaller.

You have to remove Eclipse manually. At least Eclipse does not write anything in the system registry, so deleting some directories and files is enough.

Note: I use Unix style paths in this answer but the locations should be the same on Windows or Unix systems, so ~ refers to the user home directory even on Windows.

Why is there no uninstaller?

According to this discussion about uninstalling Eclipse, the reasoning for not providing an uninstaller is that the Eclipse installer is supposed to just automate a few tasks that in the past had to be done manually (like downloading and extracting Eclipse and adding shortcuts), so they also can be undone manually. There is no entry in "Programs and Features" because the installer does not register anything in the system registry.

How to quickly uninstall Eclipse

Just delete the Eclipse directory and any desktop and start menu shortcuts and be done with it, if you don't mind a few leftover files.

In my opinion this is generally enough and I would stop here, because multiple Eclipse installations can share some files and you don't accidentally want to delete those shared files. You also keep all your projects.

How to completely uninstall Eclipse

If you really want to remove Eclipse without leaving any traces, you have to manually delete

  • all desktop and start menu shortcuts
  • the installation directory (e.g. ~/eclipse/photon/)
  • the p2 bundle pool (which is often shared with other eclipse installations)

The installer has a "Bundle Pools" menu entry which lists the locations of all bundle pools. If you have other Eclipse installations on your system you can use the "Cleanup Agent" to clean up unused bundles. If you don't have any other Eclipse installations you can delete the whole bundle pool directory instead (by default ~/p2/).

If you want to completely remove the Eclipse installer too, delete the installer's executable and the ~/.eclipse/ directory.

Depending on what kind of work you did with Eclipse, there can be more directories that you may want to delete. If you used Maven, then ~/.m2/ contains the Maven cache and settings (shared with Maven CLI and other IDEs). If you develop Eclipse plugins, then there might be JUnit workspaces from test runs, next to you Eclipse workspace. Likewise other build tools and development environments used in Eclipse could have created similar directories.

How to delete all projects

If you want to delete your projects and workspace metadata, you have to delete your workspace(s). The default workspace location is ´~/workspace/´. You can also search for the .metadata directory to get all Eclipse workspaces on your machine.

If you are working with Git projects, these are generally not saved in the workspace but in the ~/git/ directory.

Using dig to search for SPF records

The dig utility is pretty convenient to use. The order of the arguments don't really matter.I'll show you some easy examples.
To get all root name servers use

# dig

To get a TXT record of a specific host use

# dig example.com txt
# dig host.example.com txt

To query a specific name server just add @nameserver.tld

# dig host.example.com txt @a.iana-servers.net

The SPF RFC4408 says that SPF records can be stored as SPF or TXT. However nearly all use only TXT records at the moment. So you are pretty safe if you only fetch TXT records.

I made a SPF checker for visualising the SPF records of a domain. It might help you to understand SPF records better. You can find it here: http://spf.myisp.ch

MySQL direct INSERT INTO with WHERE clause

INSERT syntax cannot have WHERE but you can use UPDATE.

The syntax is as follows:

UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;

How to sort a data frame by date

Nowadays, it is the most efficient and comfortable to use lubridate and dplyr libraries.

lubridate contains a number of functions that make parsing dates into POSIXct or Date objects easy. Here we use dmy which automatically parses dates in Day, Month, Year formats. Once your data is in a date format, you can sort it with dplyr::arrange (or any other ordering function) as desired:

d$V3 <- lubridate::dmy(d$V3)
dplyr::arrange(d, V3)

javascript regex for special characters

How about this:-

var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,}$/;

It will allow a minimum of 6 characters including numbers, alphabets, and special characters

span with onclick event inside a tag

<a href="http://the.url.com/page.html">
    <span onclick="hide(); return false">Hide me</span>
</a>

This is the easiest solution.

Convert a python UTC datetime to a local datetime using only python standard library?

A simple (but maybe flawed) way that works in Python 2 and 3:

import time
import datetime

def utc_to_local(dt):
    return dt - datetime.timedelta(seconds = time.timezone)

Its advantage is that it's trivial to write an inverse function

Youtube - How to force 480p video quality in embed link / <iframe>

You can also use for 1080 hd values:

240p: &vq=small , 360p: &vq=medium , 480p: &vq=large , 720p: &vq=hd720 , &vq=hd1080

What does 'wb' mean in this code, using Python?

That is the mode with which you are opening the file. "wb" means that you are writing to the file (w), and that you are writing in binary mode (b).

Check out the documentation for more: clicky

Shell Scripting: Using a variable to define a path

Don't use spaces...

(Incorrect)

SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'

(Correct)

SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'

How to remove all click event handlers using jQuery?

Is there a way to remove all previous click events that have been assigned to a button?

$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});

Laravel Eloquent where field is X or null

Using coalesce() converts null to 0:

$query = Model::where('field1', 1)
    ->whereNull('field2')
    ->where(DB::raw('COALESCE(datefield_at,0)'), '<', $date)
;

How do I replace whitespaces with underscore?

You don't need regular expressions. Python has a built-in string method that does what you need:

mystring.replace(" ", "_")

IF function with 3 conditions

Using INDEX and MATCH for binning. Easier to maintain if we have more bins.

=INDEX({"Text 1","Text 2","Text 3"},MATCH(A2,{0,5,21,100}))

enter image description here

%matplotlib line magic causes SyntaxError in Python script

There are several reasons as to why this wouldn't work.

It is possible that matplotlib is not properly installed. have you tried running:

conda install matplotlib

If that doesn't work, look at your %PATH% environment variable, does it contain your libraries and python paths?

Similar problem on github anaconda

Make ABC Ordered List Items Have Bold Style

You could do something like this also:

ol {
  font-weight: bold;
}

ol > li > * {
  font-weight: normal;
}

So you have no "style" attributes in your HTML

How to align a <div> to the middle (horizontally/width) of the page

If you have some regular content, and not only one line of text, the only possible reason I know is to calculate margin.

Here is an example:

HTML

<div id="supercontainer">
  <div id="middlecontainer">
    <div class="common" id="first">first</div>
    <div id="container">
      <div class="common" id="second">second</div>
      <div class="common" id="third">third</div>
    </div>
  </div>
</div>

CSS

body {
  margin: 0;
  padding: 0;
}

.common {
  border: 1px solid black;
}

#supercontainer {
  width: 1200px;
  background: aqua;
  float: left;
}

#middlecontainer {
  float: left;
  width: 104px;
  margin: 0 549px;
}

#container {
  float: left;
}

#first {
  background: red;
  height: 102px;
  width: 50px;
  float: left;
}

#second {
  background: green;
  height: 50px;
  width: 50px;
}

#third {
  background: yellow;
  height: 50px;
  width: 50px;
}

So, #supercontainer is your "whole page" and its width is 1200px.

#middlecontainer is div with content of your site; it's width 102px. In case the width of content is known, you need to divide the page's size to 2, and subtract half of content's width from the result: 1200 / 2 - (102 / 2) = 549;

Yes, I'm also seeing that this is der grosse fail of CSS.

Sort a List of objects by multiple fields

You have to write your own compareTo() method that has the Java code needed to perform the comparison.

If we wanted for example to compare two public fields, campus, then faculty, we might do something like:

int compareTo(GraduationCeremony gc)
{
    int c = this.campus.compareTo(gc.campus);

    if( c != 0 )
    {
        //sort by campus if we can
        return c;
    }
    else
    {
        //campus equal, so sort by faculty
        return this.faculty.compareTo(gc.faculty);
    }
}

This is simplified but hopefully gives you an idea. Consult the Comparable and Comparator docs for more info.

"Fatal error: Cannot redeclare <function>"

I'd recommend using get_included_files - as Pascal says you're either looking at the wrong file somehow or this function is already defined in a file that's been included.

require_once is also useful if the file you're attempting to include is essential.

Wildcard string comparison in Javascript

I used the answer by @Spenhouet and added more "replacements"-possibilities than "*". For example "?". Just add your needs to the dict in replaceHelper.

/**
 * @param {string} str
 * @param {string} rule
 * checks match a string to a rule
 * Rule allows * as zero to unlimited numbers and ? as zero to one character
 * @returns {boolean}
 */
function matchRule(str, rule) {
  const escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
  return new RegExp("^" + replaceHelper(rule, {"*": "\\d*", "?": ".?"}, escapeRegex) + "$").test(str);
}

function replaceHelper(input, replace_dict, last_map) {
  if (Object.keys(replace_dict).length === 0) {
    return last_map(input);
  }
  const split_by = Object.keys(replace_dict)[0];
  const replace_with = replace_dict[split_by];
  delete replace_dict[split_by];
  return input.split(split_by).map((next_input) => replaceHelper(next_input, replace_dict, last_map)).join(replace_with);
}

How can I handle the warning of file_get_contents() function in PHP?

You can prepend an @: $content = @file_get_contents($site);

This will supress any warning - use sparingly!. See Error Control Operators

Edit: When you remove the 'http://' you're no longer looking for a web page, but a file on your disk called "www.google....."

curl : (1) Protocol https not supported or disabled in libcurl

Got the answer HERE for windows, it says there that:

curl -XPUT 'http://localhost:9200/api/twittervnext/tweet'

Woops, first try and already an error:

curl: (1) Protocol 'http not supported or disabled in libcurl

The reason for this error is kind of stupid, Windows doesn’t like it when you are using single quotes for commands. So the correct command is:

curl –XPUT "http://localhost:9200/api/twittervnext/tweet"

What is the difference between 'protected' and 'protected internal'?

The "protected internal" access modifier is a union of both the "protected" and "internal" modifiers.

From MSDN, Access Modifiers (C# Programming Guide):

protected:

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

internal:

The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal:

The type or member can be accessed by any code in the assembly in which it is declared, OR from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

Note that: protected internal means "protected OR internal" (any class in the same assembly, or any derived class - even if it is in a different assembly).

...and for completeness:

private:

The type or member can be accessed only by code in the same class or struct.

public:

The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private protected:

Access is limited to the containing class or types derived from the containing class within the current assembly.
(Available since C# 7.2)

How to remove html special chars?

<?php
function strip_only($str, $tags, $stripContent = false) {
    $content = '';
    if(!is_array($tags)) {
        $tags = (strpos($str, '>') !== false
                 ? explode('>', str_replace('<', '', $tags))
                 : array($tags));
        if(end($tags) == '') array_pop($tags);
    }
    foreach($tags as $tag) {
        if ($stripContent)
             $content = '(.+</'.$tag.'[^>]*>|)';
         $str = preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is', '', $str);
    }
    return $str;
}

$str = '<font color="red">red</font> text';
$tags = 'font';
$a = strip_only($str, $tags); // red text
$b = strip_only($str, $tags, true); // text
?> 

Spring MVC Multipart Request with JSON

This is how I implemented Spring MVC Multipart Request with JSON Data.

Multipart Request with JSON Data (also called Mixed Multipart):

Based on RESTful service in Spring 4.0.2 Release, HTTP request with the first part as XML or JSON formatted data and the second part as a file can be achieved with @RequestPart. Below is the sample implementation.

Java Snippet:

Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
    consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
        @RequestPart("properties") @Valid ConnectionProperties properties,
        @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
    return projectService.executeSampleService(properties, file);
}

Front End (JavaScript) Snippet:

  1. Create a FormData object.

  2. Append the file to the FormData object using one of the below steps.

    1. If the file has been uploaded using an input element of type "file", then append it to the FormData object. formData.append("file", document.forms[formName].file.files[0]);
    2. Directly append the file to the FormData object. formData.append("file", myFile, "myfile.txt"); OR formData.append("file", myBob, "myfile.txt");
  3. Create a blob with the stringified JSON data and append it to the FormData object. This causes the Content-type of the second part in the multipart request to be "application/json" instead of the file type.

  4. Send the request to the server.

  5. Request Details:
    Content-Type: undefined. This causes the browser to set the Content-Type to multipart/form-data and fill the boundary correctly. Manually setting Content-Type to multipart/form-data will fail to fill in the boundary parameter of the request.

Javascript Code:

formData = new FormData();

formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
                "name": "root",
                "password": "root"                    
            })], {
                type: "application/json"
            }));

Request Details:

method: "POST",
headers: {
         "Content-Type": undefined
  },
data: formData

Request Payload:

Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB

------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: application/txt


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="properties"; filename="blob"
Content-Type: application/json


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN--

Python using enumerate inside list comprehension

Be explicit about the tuples.

[(i, j) for (i, j) in enumerate(mylist)]

How do I read a large csv file with pandas?

If you use pandas read large file into chunk and then yield row by row, here is what I have done

import pandas as pd

def chunck_generator(filename, header=False,chunk_size = 10 ** 5):
   for chunk in pd.read_csv(filename,delimiter=',', iterator=True, chunksize=chunk_size, parse_dates=[1] ): 
        yield (chunk)

def _generator( filename, header=False,chunk_size = 10 ** 5):
    chunk = chunck_generator(filename, header=False,chunk_size = 10 ** 5)
    for row in chunk:
        yield row

if __name__ == "__main__":
filename = r'file.csv'
        generator = generator(filename=filename)
        while True:
           print(next(generator))

Do AJAX requests retain PHP Session info?

Well, not always. Using cookies, you are good. But the "can I safely rely on the id being present" urged me to extend the discussion with an important point (mostly for reference, as the visitor count of this page seems quite high).

PHP can be configured to maintain sessions by URL-rewriting, instead of cookies. (How it's good or bad (<-- see e.g. the topmost comment there) is a separate question, let's now stick to the current one, with just one side-note: the most prominent issue with URL-based sessions -- the blatant visibility of the naked session ID -- is not an issue with internal Ajax calls; but then, if it's turned on for Ajax, it's turned on for the rest of the site, too, so there...)

In case of URL-rewriting (cookieless) sessions, Ajax calls must take care of it themselves that their request URLs are properly crafted. (Or you can roll your own custom solution. You can even resort to maintaining sessions on the client side, in less demanding cases.) The point is the explicit care needed for session continuity, if not using cookies:

  1. If the Ajax calls just extract URLs verbatim from the HTML (as received from PHP), that should be OK, as they are already cooked (umm, cookified).

  2. If they need to assemble request URIs themselves, the session ID needs to be added to the URL manually. (Check here, or the page sources generated by PHP (with URL-rewriting on) to see how to do it.)


From OWASP.org:

Effectively, the web application can use both mechanisms, cookies or URL parameters, or even switch from one to the other (automatic URL rewriting) if certain conditions are met (for example, the existence of web clients without cookies support or when cookies are not accepted due to user privacy concerns).

From a Ruby-forum post:

When using php with cookies, the session ID will automatically be sent in the request headers even for Ajax XMLHttpRequests. If you use or allow URL-based php sessions, you'll have to add the session id to every Ajax request url.

Getting value from appsettings.json in .net core

For ASP.NET Core 3.1 you can follow this guide:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

When you create a new ASP.NET Core 3.1 project you will have the following configuration line in Program.cs:

Host.CreateDefaultBuilder(args)

This enables the following:

  1. ChainedConfigurationProvider : Adds an existing IConfiguration as a source. In the default configuration case, adds the host configuration and setting it as the first source for the app configuration.
  2. appsettings.json using the JSON configuration provider.
  3. appsettings.Environment.json using the JSON configuration provider. For example, appsettings.Production.json and appsettings.Development.json.
  4. App secrets when the app runs in the Development environment.
  5. Environment variables using the Environment Variables configuration provider.
  6. Command-line arguments using the Command-line configuration provider.

This means you can inject IConfiguration and fetch values with a string key, even nested values. Like IConfiguration["Parent:Child"];

Example:

appsettings.json

{
  "ApplicationInsights":
    {
        "Instrumentationkey":"putrealikeyhere"
    }
}

WeatherForecast.cs

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IConfiguration _configuration;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var key = _configuration["ApplicationInsights:InstrumentationKey"];

        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

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

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);

Fastest way to find second (third...) highest/lowest value in vector or column

Here you go... kit is the obvious winner!

N = 1e6
x = rnorm(N)

maxN <- function(x, N=2){
  len <- length(x)
  if(N>len){
    warning('N greater than length(x).  Setting N=length(x)')
    N <- length(x)
  }
  sort(x,partial=len-N+1)[len-N+1]
}

microbenchmark::microbenchmark(
  Rfast = Rfast::nth(x,5,descending = T),
  maxN = maxN(x,5),
  order = x[order(x, decreasing = T)[5]],
  kit = x[kit::topn(x, 5L,decreasing = T)[5L]]
) 
# Unit: milliseconds
# expr       min        lq     mean    median        uq        max neval
# Rfast 12.311168 12.473771 16.36982 12.702134 16.110779 102.749873   100
# maxN  12.922118 13.124358 17.49628 18.977537 20.053139  28.928694   100
# order 50.443100 50.926975 52.54067 51.270163 52.323116  66.561606   100
# kit    1.177202  1.216371  1.29542  1.240228  1.297286   2.771715   100

Edit: I forgot that kit::topn has hasna option...let's do another run.

microbenchmark::microbenchmark(
  Rfast = Rfast::nth(x,5,descending = T),
  maxN = maxN(x,5),
  order = x[order(x, decreasing = T)[5]],
  kit = x[kit::topn(x, 5L,decreasing = T)[5L]],
  kit2 = x[kit::topn(x, 5L,decreasing = T,hasna = F)[5L]],
  unit = "ms"
) 
# Unit: milliseconds
# expr       min        lq       mean     median        uq       max neval
# Rfast 13.194314 13.358787 14.7227116 13.4560340 14.551194 24.524105   100
# maxN   7.378960  7.527661 10.0747803  7.7119715 12.217756 67.409526   100
# order 50.088927 50.488832 52.4714347 50.7415680 52.267003 70.062662   100
# kit    1.180698  1.217237  1.2975441  1.2429790  1.278243  3.263202   100
# kit2   0.842354  0.876329  0.9398055  0.9109095  0.944407  2.135903   100

How to keep one variable constant with other one changing with row in excel

=(B0+4)/($A$0)

$ means keep same (press a few times F4 after typing A4 to flip through combos quick!)

How to play videos in android from assets folder or raw folder?

PlayVideoActivity.java:

public class PlayVideoActivity extends Activity {

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

        VideoView videoView = (VideoView) findViewById(R.id.video_view);
        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);
        videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.documentariesandyou));
        videoView.start();
    }
}

activity_play_video.xml:

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

    <VideoView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </VideoView>

</LinearLayout>

Error in contrasts when defining a linear model in R

From my experience ten minutes ago this situation can happen where there are more than one category but with a lot of NAs. Taking the Kaggle Houseprice Dataset as example, if you loaded data and run a simple regression,

train.df = read.csv('train.csv')
lm1 = lm(SalePrice ~ ., data = train.df)

you will get same error. I also tried testing the number of levels of each factor, but none of them says it has less than 2 levels.

cols = colnames(train.df)
for (col in cols){
  if(is.factor(train.df[[col]])){
    cat(col, ' has ', length(levels(train.df[[col]])), '\n')
  }
}

So after a long time I used summary(train.df) to see details of each col, and removed some, and it finally worked:

train.df = subset(train.df, select=-c(Id, PoolQC,Fence, MiscFeature, Alley, Utilities))
lm1 = lm(SalePrice ~ ., data = train.df)

and removing any one of them the regression fails to run again with same error (which I have tested myself).

And above attributes generally have 1400+ NAs and 10 useful values, so you might want to remove these garbage attributes, even they have 3 or 4 levels. I guess a function counting how many NAs in each column will help.

Get the contents of a table row with a button click

The selector ".nr:first" is specifically looking for the first, and only the first, element having class "nr" within the selected table element. If you instead call .find(".nr") you will get all of the elements within the table having class "nr". Once you have all of those elements, you could use the .each method to iterate over them. For example:

$(".use-address").click(function() {
    $("#choose-address-table").find(".nr").each(function(i, nrElt) {
        var id = nrElt.text();
        $("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
    });
});

However, that would get you all of the td.nr elements in the table, not just the one in the row that was clicked. To further limit your selection to the row containing the clicked button, use the .closest method, like so:

$(".use-address").click(function() {
    $(this).closest("tr").find(".nr").each(function(i, nrElt) {
        var id = nrElt.text();
        $("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
    });
});

How to make a 3D scatter plot in Python?

Use the following code it worked for me:

# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]

# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

plt.show()

while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.

Google Apps Script to open a URL

Building of off an earlier example, I think there is a cleaner way of doing this. Create an index.html file in your project and using Stephen's code from above, just convert it into an HTML doc.

<!DOCTYPE html>
<html>
  <base target="_top">
  <script>
    function onSuccess(url) {
      var a = document.createElement("a"); 
      a.href = url;
      a.target = "_blank";
      window.close = function () {
        window.setTimeout(function() {
          google.script.host.close();
        }, 9);
      };
      if (document.createEvent) {
        var event = document.createEvent("MouseEvents");
        if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
          window.document.body.append(a);
        }                        
        event.initEvent("click", true, true); 
        a.dispatchEvent(event);
      } else {
        a.click();
      }
      close();
    }

    function onFailure(url) {
      var div = document.getElementById('failureContent');
      var link = '<a href="' + url + '" target="_blank">Process</a>';
      div.innerHtml = "Failure to open automatically: " + link;
    }

    google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).getUrl();
  </script>
  <body>
    <div id="failureContent"></div>
  </body>
  <script>
    google.script.host.setHeight(40);
    google.script.host.setWidth(410);
  </script>
</html>

Then, in your Code.gs script, you can have something like the following,

function getUrl() {
  return 'http://whatever.com';
}

function openUrl() {
  var html = HtmlService.createHtmlOutputFromFile("index");
  html.setWidth(90).setHeight(1);
  var ui = SpreadsheetApp.getUi().showModalDialog(html, "Opening ..." );
}

MySql Table Insert if not exist otherwise update

I had a situation where I needed to update or insert on a table according to two fields (both foreign keys) on which I couldn't set a UNIQUE constraint (so INSERT ... ON DUPLICATE KEY UPDATE won't work). Here's what I ended up using:

replace into last_recogs (id, hasher_id, hash_id, last_recog) 
  select l.* from 
    (select id, hasher_id, hash_id, [new_value] from last_recogs 
     where hasher_id in (select id from hashers where name=[hasher_name])
     and hash_id in (select id from hashes where name=[hash_name]) 
     union 
     select 0, m.id, h.id, [new_value] 
     from hashers m cross join hashes h 
     where m.name=[hasher_name] 
     and h.name=[hash_name]) l 
  limit 1;

This example is cribbed from one of my databases, with the input parameters (two names and a number) replaced with [hasher_name], [hash_name], and [new_value]. The nested SELECT...LIMIT 1 pulls the first of either the existing record or a new record (last_recogs.id is an autoincrement primary key) and uses that as the value input into the REPLACE INTO.

Running conda with proxy

One mistake I was making was saving the file as a.condarc or b.condarc.

Save it only as .condarc and paste the following code in the file and save the file in your home directory. Make necessary changes to hostname, user etc.

channels:
- defaults

show_channel_urls: True
allow_other_channels: True

proxy_servers:
    http: http://user:pass@hostname:port
    https: http://user:pass@hostname:port


ssl_verify: False

Wget output document and headers to STDOUT

This will not work:

wget -q -S -O - google.com 1>wget.txt 2>&1

since redirects are evaluated right to left, this sends html to wget.txt and the header to STDOUT:

wget -q -S -O - google.com 2>&1 1>wget.txt

Can I change the color of Font Awesome's icon color?

This worked for me:

.icon-cog {
  color: black;
}

For versions of Font Awesome above 4.7.0, it looks this:

.fa-cog {
  color: black;
}

What to do with commit made in a detached head

An easy fix is to just create a new branch for that commit and checkout to it: git checkout -b <branch-name> <commit-hash>.

In this way, all the changes you made will be saved in that branch. In case you need to clean up your master branch from leftover commits be sure to run git reset --hard master.

With this, you will be rewriting your branches so be sure not to disturb anyone with these changes. Be sure to take a look at this article for a better illustration of detached HEAD state.

Batch file to delete files older than N days

Expanding on aku's answer, I see a lot of people asking about UNC paths. Simply mapping the unc path to a drive letter will make forfiles happy. Mapping and unmapping of drives can be done programmatically in a batch file, for example.

net use Z: /delete
net use Z: \\unc\path\to\my\folder
forfiles /p Z: /s /m *.gz /D -7 /C "cmd /c del @path"

This will delete all files with a .gz extension that are older than 7 days. If you want to make sure Z: isn't mapped to anything else before using it you could do something simple as

net use Z: \\unc\path\to\my\folder
if %errorlevel% equ 0 (
    forfiles /p Z: /s /m *.gz /D -7 /C "cmd /c del @path"
) else (
    echo "Z: is already in use, please use another drive letter!"
)

Moment Js UTC to Local Time

This is what worked for me, it required moment-tz as well as moment though.

_x000D_
_x000D_
const guess = moment.utc(date).tz(moment.tz.guess());
const correctTimezone = guess.format()
_x000D_
_x000D_
_x000D_

How do I create a multiline Python string with inline variables?

If anyone came here from python-graphql client looking for a solution to pass an object as variable here's what I used:

query = """
{{
  pairs(block: {block} first: 200, orderBy: trackedReserveETH, orderDirection: desc) {{
    id
    txCount
    reserveUSD
    trackedReserveETH
    volumeUSD
  }}
}}
""".format(block=''.join(['{number: ', str(block), '}']))

 query = gql(query)

Make sure to escape all curly braces like I did: "{{", "}}"

How to convert CSV file to multiline JSON?

You can use Pandas DataFrame to achieve this, with the following Example:

import pandas as pd
csv_file = pd.DataFrame(pd.read_csv("path/to/file.csv", sep = ",", header = 0, index_col = False))
csv_file.to_json("/path/to/new/file.json", orient = "records", date_format = "epoch", double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None)

'const int' vs. 'int const' as function parameters in C++ and C

The trick is to read the declaration backwards (right-to-left):

const int a = 1; // read as "a is an integer which is constant"
int const a = 1; // read as "a is a constant integer"

Both are the same thing. Therefore:

a = 2; // Can't do because a is constant

The reading backwards trick especially comes in handy when you're dealing with more complex declarations such as:

const char *s;      // read as "s is a pointer to a char that is constant"
char c;
char *const t = &c; // read as "t is a constant pointer to a char"

*s = 'A'; // Can't do because the char is constant
s++;      // Can do because the pointer isn't constant
*t = 'A'; // Can do because the char isn't constant
t++;      // Can't do because the pointer is constant

How can I create database tables from XSD files?

Create a Java Model using Axis wsdl2java (which can take in .xsd files).

Use a database generation tool for Java that takes in a Java Model. Surely something like Hibernate can do this? I wrote my own tool (takes a couple of days, also generates CRUD code in Java too) to save myself time at work, maybe this would be a nice personal project?

Or just do it manually so that you can check everything is correct and good! Database tools are good enough now that you can zip through creating tables for a model without too many problems.

AngularJS routing without the hash '#'

Lets write answer that looks simple and short

In Router at end add html5Mode(true);

app.config(function($routeProvider,$locationProvider) {

    $routeProvider.when('/home', {
        templateUrl:'/html/home.html'
    });

    $locationProvider.html5Mode(true);
})

In html head add base tag

<html>
<head>
    <meta charset="utf-8">    
    <base href="/">
</head>

thanks To @plus- for detailing the above answer

Copy existing project with a new name in Android Studio

When refactoring the package name in Android Studio, you may need to click the little cogwheel up to the right by the package/android/project/etc - navigator and uncheck 'compact empty middle packages' in order to see each part of the package name as an own directory. Then for individual directories do refactor.

This is important if you need to change all parts of the package name. For example, from com.example.originalproject to org.mydomain.newproject. Otherwise, the refactor/rename operation will only let you change "originalproject" to "newproject", and it will leave "com.example" unchanged. There is a good video that shows this: https://www.youtube.com/watch?v=dMK-RBVLeIY

Checking that a List is not empty in Hamcrest

This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, is(not(empty())));

But if you have to use older version - instead of bugged empty() you could use:

hasSize(greaterThan(0))
(import static org.hamcrest.number.OrderingComparison.greaterThan; or
import static org.hamcrest.Matchers.greaterThan;)

Example:

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, hasSize(greaterThan(0)));

The most important thing about above solutions is that it does not generate any warnings. The second solution is even more useful if you would like to estimate minimum result size.

changing visibility using javascript

Use display instead of visibility. display: none for invisible and no setting for visible.

How to manipulate arrays. Find the average. Beginner Java

If we want to add numbers of an Array and find the average of them follow this easy way! .....

public class Array {

    public static void main(String[] args) {

        int[]array = {1,3,5,7,9,6,3};
        int i=0;
        int sum=0;
        double average=0;
        for( i=0;i<array.length;i++){
            System.out.println(array[i]);
            sum=sum+array[i];
        }
        System.out.println("sum is:"+sum);
        System.out.println("average is: "+(double)sum/vargu.length);



    }

}

How to get access to raw resources that I put in res folder?

getClass().getResourcesAsStream() works fine on Android. Just make sure the file you are trying to open is correctly embedded in your APK (open the APK as ZIP).

Normally on Android you put such files in the assets directory. So if you put the raw_resources.dat in the assets subdirectory of your project, it will end up in the assets directory in the APK and you can use:

getClass().getResourcesAsStream("/assets/raw_resources.dat");

It is also possible to customize the build process so that the file doesn't land in the assets directory in the APK.

Why do I get a warning icon when I add a reference to an MEF plugin project?

It's been a long time since this question was asked but if someone is still interested - I recently ran into similar icons. I was compiling a C#.net project using VS 2008. I found VS could not locate the assemblies for those references. When I double clicked VS refreshed the references and removed the icons on some of those[EDIT: which it could NOW locate]. For remaining references, I had to compile the respective assemblies.

How to create timer events using C++ 11?

This is the code I have so far:

I am using VC++ 2012 (no variadic templates)

//header
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <chrono>
#include <memory>
#include <algorithm>

template<class T>
class TimerThread
{
  typedef std::chrono::high_resolution_clock clock_t;

  struct TimerInfo
  {
    clock_t::time_point m_TimePoint;
    T m_User;

    template <class TArg1>
    TimerInfo(clock_t::time_point tp, TArg1 && arg1)
      : m_TimePoint(tp)
      , m_User(std::forward<TArg1>(arg1))
    {
    }

    template <class TArg1, class TArg2>
    TimerInfo(clock_t::time_point tp, TArg1 && arg1, TArg2 && arg2)
      : m_TimePoint(tp)
      , m_User(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2))
    {
    }
  };

  std::unique_ptr<std::thread> m_Thread;
  std::vector<TimerInfo>       m_Timers;
  std::mutex                   m_Mutex;
  std::condition_variable      m_Condition;
  bool                         m_Sort;
  bool                         m_Stop;

  void TimerLoop()
  {
    for (;;)
    {
      std::unique_lock<std::mutex>  lock(m_Mutex);

      while (!m_Stop && m_Timers.empty())
      {
        m_Condition.wait(lock);
      }

      if (m_Stop)
      {
        return;
      }

      if (m_Sort)
      {
        //Sort could be done at insert
        //but probabily this thread has time to do
        std::sort(m_Timers.begin(),
                  m_Timers.end(),
                  [](const TimerInfo & ti1, const TimerInfo & ti2)
        {
          return ti1.m_TimePoint > ti2.m_TimePoint;
        });
        m_Sort = false;
      }

      auto now = clock_t::now();
      auto expire = m_Timers.back().m_TimePoint;

      if (expire > now) //can I take a nap?
      {
        auto napTime = expire - now;
        m_Condition.wait_for(lock, napTime);

        //check again
        auto expire = m_Timers.back().m_TimePoint;
        auto now = clock_t::now();

        if (expire <= now)
        {
          TimerCall(m_Timers.back().m_User);
          m_Timers.pop_back();
        }
      }
      else
      {
        TimerCall(m_Timers.back().m_User);
        m_Timers.pop_back();
      }
    }
  }

  template<class T, class TArg1>
  friend void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1);

  template<class T, class TArg1, class TArg2>
  friend void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1, TArg2 && arg2);

public:
  TimerThread() : m_Stop(false), m_Sort(false)
  {
    m_Thread.reset(new std::thread(std::bind(&TimerThread::TimerLoop, this)));
  }

  ~TimerThread()
  {
    m_Stop = true;
    m_Condition.notify_all();
    m_Thread->join();
  }
};

template<class T, class TArg1>
void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1)
{
  {
    std::unique_lock<std::mutex> lock(timerThread.m_Mutex);
    timerThread.m_Timers.emplace_back(TimerThread<T>::TimerInfo(TimerThread<T>::clock_t::now() + std::chrono::milliseconds(ms),
                                      std::forward<TArg1>(arg1)));
    timerThread.m_Sort = true;
  }
  // wake up
  timerThread.m_Condition.notify_one();
}

template<class T, class TArg1, class TArg2>
void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1, TArg2 && arg2)
{
  {
    std::unique_lock<std::mutex> lock(timerThread.m_Mutex);
    timerThread.m_Timers.emplace_back(TimerThread<T>::TimerInfo(TimerThread<T>::clock_t::now() + std::chrono::milliseconds(ms),
                                      std::forward<TArg1>(arg1),
                                      std::forward<TArg2>(arg2)));
    timerThread.m_Sort = true;
  }
  // wake up
  timerThread.m_Condition.notify_one();
}

//sample
#include <iostream>
#include <string>

void TimerCall(int i)
{
  std::cout << i << std::endl;
}

int main()
{
  std::cout << "start" << std::endl;
  TimerThread<int> timers;

  CreateTimer(timers, 2000, 1);
  CreateTimer(timers, 5000, 2);
  CreateTimer(timers, 100, 3);

  std::this_thread::sleep_for(std::chrono::seconds(5));
  std::cout << "end" << std::endl;
}

Select All distinct values in a column using LINQ

Interestingly enough I tried both of these in LinqPad and the variant using group from Dmitry Gribkov by appears to be quicker. (also the final distinct is not required as the result is already distinct.

My (somewhat simple) code was:

public class Pair 
{ 
    public int id {get;set;}
    public string Arb {get;set;}
}

void Main()
{

    var theList = new List<Pair>();
    var randomiser = new Random();
    for (int count = 1; count < 10000; count++)
    {
        theList.Add(new Pair 
        {
            id = randomiser.Next(1, 50),
            Arb = "not used"
        });
    }

    var timer = new Stopwatch();
    timer.Start();
    var distinct = theList.GroupBy(c => c.id).Select(p => p.First().id);
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);

    timer.Start();
    var otherDistinct = theList.Select(p => p.id).Distinct();
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);
}

How to assign a select result to a variable?

DECLARE @tmp_key int
DECLARE @get_invckey cursor 

SET @get_invckey = CURSOR FOR 
    SELECT invckey FROM tarinvoice WHERE confirmtocntctkey IS NULL AND tranno LIKE '%115876'

OPEN @get_invckey 

FETCH NEXT FROM @get_invckey INTO @tmp_key

DECLARE @PrimaryContactKey int --or whatever datatype it is

WHILE (@@FETCH_STATUS = 0) 
BEGIN 
    SELECT @PrimaryContactKey=c.PrimaryCntctKey
    FROM tarcustomer c, tarinvoice i
    WHERE i.custkey = c.custkey AND i.invckey = @tmp_key

    UPDATE tarinvoice SET confirmtocntctkey = @PrimaryContactKey WHERE invckey = @tmp_key
    FETCH NEXT FROM @get_invckey INTO @tmp_key
END 

CLOSE @get_invckey
DEALLOCATE @get_invckey

EDIT:
This question has gotten a lot more traction than I would have anticipated. Do note that I'm not advocating the use of the cursor in my answer, but rather showing how to assign the value based on the question.

changing permission for files and folder recursively using shell command in mac

I do not have a Mac OSx machine to test this on but in bash on Linux I use something like the following to chmod only directories:

find . -type d -exec chmod 755 {} \+

but this also does the same thing:

chmod 755 `find . -type d`

and so does this:

chmod 755 $(find . -type d)

The last two are using different forms of subcommands. The first is using backticks (older and depreciated) and the other the $() subcommand syntax.

So I think in your case that the following will do what you want.

chmod 777 $(find "/Users/Test/Desktop/PATH")

How to set a hidden value in Razor

If I understand correct you will have something like this:

<input value="default" id="sth" name="sth" type="hidden">

And to get it you have to write:

@Html.HiddenFor(m => m.sth, new { Value = "default" })

for Strongly-typed view.

CodeIgniter: "Unable to load the requested class"

If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.

Ex.

Filename: csvsample.php

class csvsample {

}

Please add a @Pipe/@Directive/@Component annotation. Error

In my case, I accidentally added the package in the declaration but it should be in imports.

OS specific instructions in CMAKE: How to?

Use

if (WIN32)
    #do something
endif (WIN32)

or

if (UNIX)
    #do something
endif (UNIX)

or

if (MSVC)
    #do something
endif (MSVC)

or similar

see CMake Useful Variables and CMake Checking Platform

How do I modify fields inside the new PostgreSQL JSON datatype?

To build upon @pozs's answers, here are a couple more PostgreSQL functions which may be useful to some. (Requires PostgreSQL 9.3+)

Delete By Key: Deletes a value from JSON structure by key.

CREATE OR REPLACE FUNCTION "json_object_del_key"(
  "json"          json,
  "key_to_del"    TEXT
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_to_del") IS NULL THEN "json"
  ELSE (SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')
          FROM (SELECT *
                  FROM json_each("json")
                 WHERE "key" <> "key_to_del"
               ) AS "fields")::json
END
$function$;

Recursive Delete By Key: Deletes a value from JSON structure by key-path. (requires @pozs's json_object_set_key function)

CREATE OR REPLACE FUNCTION "json_object_del_path"(
  "json"          json,
  "key_path"      TEXT[]
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_path"[l] ) IS NULL THEN "json"
  ELSE
     CASE COALESCE(array_length("key_path", 1), 0)
         WHEN 0 THEN "json"
         WHEN 1 THEN "json_object_del_key"("json", "key_path"[l])
         ELSE "json_object_set_key"(
           "json",
           "key_path"[l],
           "json_object_del_path"(
             COALESCE(NULLIF(("json" -> "key_path"[l])::text, 'null'), '{}')::json,
             "key_path"[l+1:u]
           )
         )
       END
    END
  FROM array_lower("key_path", 1) l,
       array_upper("key_path", 1) u
$function$;

Usage examples:

s1=# SELECT json_object_del_key ('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 'foo'),
            json_object_del_path('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 '{"foo","moe"}');

 json_object_del_key |          json_object_del_path
---------------------+-----------------------------------------
 {"hello":[7,3,1]}   | {"hello":[7,3,1],"foo":{"mofu":"fuwa"}}

How can I use mySQL replace() to replace strings in multiple records?

UPDATE some_table SET some_field = REPLACE(some_field, '&lt;', '<')

Setting environment variables on OS X

One thing to note in addition to the approaches suggested is that, in OS X 10.5 (Leopard) at least, the variables set in launchd.conf will be merged with the settings made in .profile. I suppose this is likely to be valid for the settings in ~/.MacOSX/environment.plist too, but I haven't verified.

Python: access class property from string

Extending Alex's answer slightly:

class User:
    def __init__(self):
        self.data = [1,2,3]
        self.other_data = [4,5,6]
    def doSomething(self, source):
        dataSource = getattr(self,source)
        return dataSource

A = User()
print A.doSomething("data")
print A.doSomething("other_data")

will yield:

[1, 2, 3]
[4, 5, 6]

However, personally I don't think that's great style - getattr will let you access any attribute of the instance, including things like the doSomething method itself, or even the __dict__ of the instance. I would suggest that instead you implement a dictionary of data sources, like so:

class User:
    def __init__(self):

        self.data_sources = {
            "data": [1,2,3],
            "other_data":[4,5,6],
        }

    def doSomething(self, source):
        dataSource = self.data_sources[source]
        return dataSource

A = User()

print A.doSomething("data")
print A.doSomething("other_data")

again yielding:

[1, 2, 3]
[4, 5, 6]

How do I find all the files that were created today in Unix/Linux?

This worked for me. Lists the files created on May 30 in the current directory.

ls -lt | grep 'May 30'

SyntaxError: expected expression, got '<'

May be this helps someone. The error I was getting was

SyntaxError: expected expression, got '<'

What I did clicked on view source in chrome and there I found this error

Notice: Undefined variable: string in D:\Projects\demo\ge.php on line 66

The issue was this snippet of code,

$string= ''; <---- this should be declared outside the loop

while($row = mysql_fetch_assoc($result))
    {
        $string .= '{ id:'.$row['menu_id'].', pId:'.$row['parent_id'].', name:"'.$row['menu_name'].'"},';
    }

which fixed the problem.

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

I see you have all the settings right. You just need to end the local web server and start it again with

php artisan serve

Everytime you change your .env file, you need tor restart the server for the new options to take effect.

Or clear and cache your configuration with

php artisan config:cache

Test process.env with Jest

Another option is to add it to the jest.config.js file after the module.exports definition:

process.env = Object.assign(process.env, {
  VAR_NAME: 'varValue',
  VAR_NAME_2: 'varValue2'
});

This way it's not necessary to define the environment variables in each .spec file and they can be adjusted globally.

What is the instanceof operator in JavaScript?

I just found a real-world application and will use it more often now, I think.

If you use jQuery events, sometimes you want to write a more generic function which may also be called directly (without event). You can use instanceof to check if the first parameter of your function is an instance of jQuery.Event and react appropriately.

var myFunction = function (el) {                
    if (el instanceof $.Event) 
        // event specific code
    else
        // generic code
};

$('button').click(recalc);    // Will execute event specific code
recalc('myParameter');  // Will execute generic code

In my case, the function needed to calculate something either for all (via click event on a button) or only one specific element. The code I used:

var recalc = function (el) { 
    el = (el == undefined || el instanceof $.Event) ? $('span.allItems') : $(el);
    // calculate...
};

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

I have got the same error, but in my case I wrote class names for carousel item as .carousel-item the bootstrap.css is referring .item. SO ERROR solved. carosel-item is renamed to item

<div class="carousel-item active"></div>

RENAMED To the following:

<div class="item active"></div>

C++ IDE for Linux?

For me Ultimate++ seems to be the best solution to write cross-os program

Error: Can't set headers after they are sent to the client

Sometimes you may get this error when you try to call next() function after res.end or res.send , try to delete if you have next() after res.send or res.end in your function. Note: here next() means after responding to the client with your response(i.e res.send or res.end) you are still trying to execute some code to respond again so it is not legal.

Example :

router.get('/',function (req,res,next){
     res.send("request received");
     next(); // this will give you the above exception 
});

remove next() from above function and it will work.

SQL Server 2005 Using CHARINDEX() To split a string

Create FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(200), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(10) 
) 
BEGIN 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO @output (splitdata)  
        VALUES(SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END 
    RETURN 

END**strong text**

Appending to 2D lists in Python

Came here to see how to append an item to a 2D array, but the title of the thread is a bit misleading because it is exploring an issue with the appending.

The easiest way I found to append to a 2D list is like this:

list=[[]]

list.append((var_1,var_2))

This will result in an entry with the 2 variables var_1, var_2. Hope this helps!

How to get start and end of previous month in VB

firstDay = DateSerial(Year(DateAdd("m", -1, Now)), Month(DateAdd("m", -1, Now)), 1)
lastDay = DateAdd("d", -1, DateSerial(Year(Now), Month(Now), 1))

This is another way to do it, but I think Remou's version looks cleaner.

How to insert newline in string literal?

I like more the "pythonic way"

List<string> lines = new List<string> {
    "line1",
    "line2",
    String.Format("{0} - {1} | {2}", 
        someVar,
        othervar, 
        thirdVar
    )
};

if(foo)
    lines.Add("line3");

return String.Join(Environment.NewLine, lines);

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

If you are using MasterPages and Content pages in your app - you also have the option of putting the ScriptManager on the Masterpage and then every ContentPage that uses that MasterPage will NOT need a script manager added. If you need some of the special configurations of the ScriptManager - like javascript file references - you can use a ScriptManagerProxy control on the content page that needs it.

Iterating through a golang map

For example,

package main

import "fmt"

func main() {
    type Map1 map[string]interface{}
    type Map2 map[string]int
    m := Map1{"foo": Map2{"first": 1}, "boo": Map2{"second": 2}}
    //m = map[foo:map[first: 1] boo: map[second: 2]]
    fmt.Println("m:", m)
    for k, v := range m {
        fmt.Println("k:", k, "v:", v)
    }
}

Output:

m: map[boo:map[second:2] foo:map[first:1]]
k: boo v: map[second:2]
k: foo v: map[first:1]

When should we use intern method of String on String literals

String literals and constants are interned by default. That is, "foo" == "foo" (declared by the String literals), but new String("foo") != new String("foo").

Javascript: The prettiest way to compare one value against multiple values

I like the pretty form of testing indexOf with an array, but be aware, this doesn't work in all browsers (because Array.prototype.indexOf is not present in old IExplorers).

However, there is a similar way by using jQuery with the $.inArray() function :

if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
    alert('value ' + field + ' is into the list'); 
}

It could be better, so you should not test if indexOf exists.

Be careful with the comparison (don't use == true/false), because $.inArray returns the index of matching position where the value has been found, and if the index is 0, it would be false when it really exist into the array.

Location of my.cnf file on macOS

In my case, the file did not exist. In MySQL Workbench I went to OPTIONS FILE and found some default values. I clicked apply. It asked for permission. It then created the my.cnf file under /etc. However, it is very important to keep in mind that the first time you click "apply", you do not make any changes to the default configuration. Once the file has been created, you can make changes which will be applied when you click "apply". Otherwise you will not be shown the apply button when you make changes.

Auto number column in SharePoint list

So I am not sure I can really think of why you would actually need a "site collection unique" id, so maybe you can comment and let us know what is actually trying to be accomplished here...

Either way, all items have a UniqueID property that is a GUID if you really need it: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.uniqueid.aspx

How do I auto size a UIScrollView to fit its content

it depends on the content really : content.frame.height might give you what you want ? Depends if content is a single thing, or a collection of things.

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

H2 in-memory database. Table not found

Had the exact same issue, tried all the above, but without success. The rather funny cause of the error was that the JVM started too fast, before the DB table was created (using a data.sql file in src.main.resources). So I've put a Thread.sleep(1000) timer to wait for just a second before calling "select * from person". Working flawlessly now.

application.properties:

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

data.sql:

create table person
(
id integer not null,
name varchar(255) not null,
location varchar(255),
birth_date timestamp,
primary key(id)
);

insert into person values (
10001, 'Tofu', 'home', sysdate()
);

PersonJdbcDAO.java:

    public List<Person> findAllPersons(){
    return jdbcTemplate.query("select * from person", 
        new BeanPropertyRowMapper<Person>(Person.class));
}

main class:

Thread.sleep(1000);
logger.info("All users -> {}", dao.findAllPersons());

Tokenizing strings in C

Here's an example of strtok usage, keep in mind that strtok is destructive of its input string (and therefore can't ever be used on a string constant

char *p = strtok(str, " ");
while(p != NULL) {
    printf("%s\n", p);
    p = strtok(NULL, " ");
}

Basically the thing to note is that passing a NULL as the first parameter to strtok tells it to get the next token from the string it was previously tokenizing.

How do I export a project in the Android studio?

Follow this steps:

-Build
-Generate Signed Apk
-Create new

Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)

enter image description here

enter image description here enter image description here

enter image description here enter image description here

SQL Server: Get table primary key using sql query

This should list all the constraints and at the end you can put your filters

/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/
WITH   ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME) 
AS
(
SELECT  CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,
        PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE=  oParentColDtl.DATA_TYPE,        
        REFERENCE_TABLE_NAME='' ,
        REFERENCE_COL_NAME='' 

FROM sys.key_constraints as PKnUKEY
    INNER JOIN sys.tables as PKnUTable
            ON PKnUTable.object_id = PKnUKEY.parent_object_id
    INNER JOIN sys.index_columns as PKnUColIdx
            ON PKnUColIdx.object_id = PKnUTable.object_id
            AND PKnUColIdx.index_id = PKnUKEY.unique_index_id
    INNER JOIN sys.columns as PKnUKEYCol
            ON PKnUKEYCol.object_id = PKnUTable.object_id
            AND PKnUKEYCol.column_id = PKnUColIdx.column_id
     INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=PKnUTable.name
            AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name
UNION ALL
SELECT  CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE='FK',
        PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,     
        REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,
        REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30)) 
FROM sys.foreign_key_columns FKC
    INNER JOIN sys.sysobjects oConstraint
            ON FKC.constraint_object_id=oConstraint.id 
    INNER JOIN sys.sysobjects oParent
            ON FKC.parent_object_id=oParent.id
    INNER JOIN sys.all_columns oParentCol
            ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
    INNER JOIN sys.sysobjects oReference
            ON FKC.referenced_object_id=oReference.id
    INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=oParent.name
            AND oParentColDtl.COLUMN_NAME=oParentCol.name
    INNER JOIN sys.all_columns oReferenceCol
            ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/

)

select * from   ALL_KEYS_IN_TABLE
where   
    PARENT_TABLE_NAME  in ('YOUR_TABLE_NAME') 
    or REFERENCE_TABLE_NAME  in ('YOUR_TABLE_NAME')
ORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;

For reference please read thru - http://blogs.msdn.com/b/sqltips/archive/2005/09/16/469136.aspx

Using jquery to get all checked checkboxes with a certain class name

$('input:checkbox.class').each(function () {
       var sThisVal = (this.checked ? $(this).val() : "");
  });

An example to demonstrate.

:checkbox is a selector for checkboxes (in fact, you could omit the input part of the selector, although I found niche cases where you would get strange results doing this in earlier versions of the library. I'm sure they are fixed in later versions). .class is the selector for element class attribute containing class.

Using Pairs or 2-tuples in Java

As an extension to @maerics nice answer, I've added a few useful methods:

public class Tuple<X, Y> { 
    public final X x; 
    public final Y y; 
    public Tuple(X x, Y y) { 
        this.x = x; 
        this.y = y; 
    }

    @Override
    public String toString() {
        return "(" + x + "," + y + ")";
    }

    @Override
    public boolean equals(Object other) {
        if (other == this) {
            return true;
        }

        if (!(other instanceof Tuple)){
            return false;
        }

        Tuple<X,Y> other_ = (Tuple<X,Y>) other;

        // this may cause NPE if nulls are valid values for x or y. The logic may be improved to handle nulls properly, if needed.
        return other_.x.equals(this.x) && other_.y.equals(this.y);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((x == null) ? 0 : x.hashCode());
        result = prime * result + ((y == null) ? 0 : y.hashCode());
        return result;
    }
}

Bash function to find newest file matching pattern

The ls command has a parameter -t to sort by time. You can then grab the first (newest) with head -1.

ls -t b2* | head -1

But beware: Why you shouldn't parse the output of ls

My personal opinion: parsing ls is only dangerous when the filenames can contain funny characters like spaces or newlines. If you can guarantee that the filenames will not contain funny characters then parsing ls is quite safe.

If you are developing a script which is meant to be run by many people on many systems in many different situations then I very much do recommend to not parse ls.

Here is how to do it "right": How can I find the latest (newest, earliest, oldest) file in a directory?

unset -v latest
for file in "$dir"/*; do
  [[ $file -nt $latest ]] && latest=$file
done

How to display special characters in PHP

After much banging-head-on-table, I have a bit better understanding of the issue that I wanted to post for anyone else who may have had this issue.

While the UTF-8 character set will display special characters on the client, the server, on the other hand, may not be so accomodating and would print special characters such as à and è as ? and ?.

To make sure your server will print them correctly, use the ISO-8859-1 charset:

<?php
    /*Just for your server-side code*/
    header('Content-Type: text/html; charset=ISO-8859-1');
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"><!-- Your HTML file can still use UTF-8-->
        <title>Untitled Document</title>
    </head>
    <body>
        <?= "àè" ?>
    </body>
</html>

This will print correctly: àè


Edit (4 years later):

I have a little better understanding now. The reason this works is that the client (browser) is being told, through the response header(), to expect an ISO-8859-1 text/html file. (As others have mentioned, you can also do this by updating your .ini or .htaccess files.) Then, once the browser begins to parse that given file into the DOM, the output will obey any <meta charset=""> rule but keep your ISO characters intact.

How to split() a delimited string to a List<String>

Include using namespace System.Linq

List<string> stringList = line.Split(',').ToList();

you can make use of it with ease for iterating through each item.

foreach(string str in stringList)
{

}

String.Split() returns an array, hence convert it to a list using ToList()

Facebook Open Graph Error - Inferred Property

In case it helps anyone I had the same error. It turns out my page had not been scrapped by Facebook in awhile and it was an old error. There was a scrape again button on the page that fixed it.

Create a folder inside documents folder in iOS apps

I don't like "[paths objectAtIndex:0]" because if Apple adds a new folder starting with "A", "B" oder "C", the "Documents"-folder isn't the first folder in the directory.

Better:

NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

How to write an XPath query to match two attributes?

or //div[@id='id-74385'][@class='guest clearfix']

How to check if ping responded or not in a batch file

The following checklink.cmd program is a good place to start. It relies on the fact that you can do a single-shot ping and that, if successful, the output will contain the line:

Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),

By extracting tokens 5 and 7 and checking they're respectively "Received" and "1,", you can detect the success.

@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
:loop
set state=down
for /f "tokens=5,6,7" %%a in ('ping -n 1 !ipaddr!') do (
    if "x%%b"=="xunreachable." goto :endloop
    if "x%%a"=="xReceived" if "x%%c"=="x1,"  set state=up
)
:endloop
echo.Link is !state!
ping -n 6 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal

Call it with the name (or IP address) you want to test:

checklink 127.0.0.1
checklink localhost
checklink nosuchaddress

Take into account that, if your locale is not English, you must replace Received with the corresponding keyword in your locale, for example recibidos for Spanish. Do a test ping to discover what keyword is used in your locale.


To only notify you when the state changes, you can use:

@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
set oldstate=neither
:loop
set state=down
for /f "tokens=5,7" %%a in ('ping -n 1 !ipaddr!') do (
    if "x%%a"=="xReceived" if "x%%b"=="x1," set state=up
)
if not !state!==!oldstate! (
    echo.Link is !state!
    set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal

However, as Gabe points out in a comment, you can just use ERRORLEVEL so the equivalent of that second script above becomes:

@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
set oldstate=neither
:loop
set state=up
ping -n 1 !ipaddr! >nul: 2>nul:
if not !errorlevel!==0 set state=down
if not !state!==!oldstate! (
    echo.Link is !state!
    set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal

Checking for Undefined In React

In case you also need to check if nextProps.blog is not undefined ; you can do that in a single if statement, like this:

if (typeof nextProps.blog !== "undefined" && typeof nextProps.blog.content !== "undefined") {
    //
}

And, when an undefined , empty or null value is not expected; you can make it more concise:

if (nextProps.blog && nextProps.blog.content) {
    //
}

How to query a CLOB column in Oracle

If it's a CLOB why can't we to_char the column and then search normally ?

Create a table

CREATE TABLE MY_TABLE(Id integer PRIMARY KEY, Name varchar2(20), message clob);

Create few records in this table

INSERT INTO MY_TABLE VALUES(1,'Tom','Hi This is Row one');
INSERT INTO MY_TABLE VALUES(2,'Lucy', 'Hi This is Row two');
INSERT INTO MY_TABLE VALUES(3,'Frank', 'Hi This is Row three');
INSERT INTO MY_TABLE VALUES(4,'Jane', 'Hi This is Row four');
INSERT INTO MY_TABLE VALUES(5,'Robert', 'Hi This is Row five');
COMMIT;

Search in the clob column

SELECT * FROM MY_TABLE where to_char(message) like '%e%';

Results

ID   NAME    MESSAGE   
===============================  
1    Tom     Hi This is Row one         
3    Frank   Hi This is Row three
5    Robert  Hi This is Row five

Remove char at specific index - python

This is my generic solution for any string s and any index i:

def remove_at(i, s):
    return s[:i] + s[i+1:]

"break;" out of "if" statement?

As already mentioned that, break-statement works only with switches and loops. Here is another way to achieve what is being asked. I am reproducing https://stackoverflow.com/a/257421/1188057 as nobody else mentioned it. It's just a trick involving the do-while loop.

do {
  // do something
  if (error) {
    break;
  }
  // do something else
  if (error) {
    break;
  }
  // etc..
} while (0);

Though I would prefer the use of goto-statement.

FIX CSS <!--[if lt IE 8]> in IE

If you want this to work in IE 8 and below, use

<!--[if lte IE 8]>

lte meaning "Less than or equal".

For more on conditional comments, see e.g. the quirksmode.org page.

INSERT INTO @TABLE EXEC @query with SQL Server 2000

The documentation is misleading.
I have the following code running in production

DECLARE @table TABLE (UserID varchar(100))
DECLARE @sql varchar(1000)
SET @sql = 'spSelUserIDList'
/* Will also work
   SET @sql = 'SELECT UserID FROM UserTable'
*/

INSERT INTO @table
EXEC(@sql)

SELECT * FROM @table

Python: avoiding pylint warnings about too many arguments

I came across the same nagging error, which I realized has something to do with a cool feature PyCharm automatically detects...just add the @staticmethod decorator, and it will automatically remove that error where the method is used

How to add property to a class dynamically?

You can use the following code to update class attributes using a dictionary object:

class ExampleClass():
    def __init__(self, argv):
        for key, val in argv.items():
            self.__dict__[key] = val

if __name__ == '__main__':
    argv = {'intro': 'Hello World!'}
    instance = ExampleClass(argv)
    print instance.intro

How to reset form body in bootstrap modal box?

This is a variance of need to reset body to original content. It doesn't deal with a form but I feel it might be of some use. If the original content was a ton of html, it is very difficult to string out the html and store it to a variable. Javascript does not take kindly to the line breaks that VS 2015/whatever allows. So I store original ton of html in default modal like this on page load:

var stylesString = $('#DefaultModal .modal-body').html();

Which allows me to to reuse this content when original default button for modal is pressed (there are other buttons that show other content in same modal).

$("#btnStyles").click(function () {
    //pass the data in the modal body adding html elements
    $('#DefaultModal .modal-body').html(stylesString);
 $('#DefaultModal').modal('show');
})

If I put an alert for the styleString variable it would have an endless string of all the html with no breaks but does it for me and keeps it out of VS editor.

Here is how it looks in Visual Studio inside default modal. Saved in the string variable whether automatic (.html) or by hand in VS, it would be one big line:

<div class="modal-body" id="modalbody">


    <div class="whatdays"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">All Styles</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/ballroom.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Ballroom</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/blues.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Blues</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/contra.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Contra</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/countrywestern.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Country</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/english-country.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">English Country</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/israeli.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Israeli</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/lindyhop.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Lindy Hop/Swing</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/miscvariety.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Misch/Variety</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/neo-square.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Neo-Square</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/polka.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Polka</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/salsa.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Salsa</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/scottish.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Scottish</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/square.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Square</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/tango.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Tango</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/waltz.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Waltz</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/wcswing.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">WCS</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/zyedeco-gator.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Zydeco/Cajun</span></div>

@Media min-width & max-width

If website on small devices behavior like desktop screen then you have to put this meta tag into header before

<meta name="viewport" content="width=device-width, initial-scale=1">

For media queries you can set this as

this will cover your all mobile/cellphone widths

 @media only screen and (min-width: 200px) and (max-width: 767px)  {
    //Put your CSS here for 200px to 767px width devices (cover all width between 200px to 767px //
   
    }

For iPad and iPad pro you have to use

  @media only screen and (min-width: 768px) and (max-width: 1024px)  {
        //Put your CSS here for 768px to 1024px width devices(covers all width between 768px to 1024px //   
  }

If you want to add css for Landscape mode you can add this

and (orientation : landscape)

  @media only screen and (min-width: 200px) and (max-width: 767px) and (orientation : portrait) {
        //Put your CSS here for 200px to 767px width devices (cover all mobile portrait width //        
  }

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

No mapping found for HTTP request with URI Spring MVC

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Hey Please use / in your web.xml (instead of /*)

LoDash: Get an array of values from an array of object properties

Simple and even faster way to get it via ES6

let newArray = users.flatMap(i => i.ID) // -> [ 12, 13, 14, 15 ]

ASP.NET: Session.SessionID changes between requests

Another possibility that causes the SessionID to change between requests, even when Session_OnStart is defined and/or a Session has been initialized, is that the URL hostname contains an invalid character (such as an underscore). I believe this is IE specific (not verified), but if your URL is, say, http://server_name/app, then IE will block all cookies and your session information will not be accessible between requests.

In fact, each request will spin up a separate session on the server, so if your page contains multiple images, script tags, etc., then each of those GET requests will result in a different session on the server.

Further information: http://support.microsoft.com/kb/316112

How to install and use "make" in Windows?

GNU make is available on chocolatey.

  • Install chocolatey from here.

  • Then, choco install make.

Now you will be able to use Make on windows.
I've tried using it on MinGW, but it should work on CMD as well.

UTF-8 encoding in JSP page

You have to make sure the file is been saved with UTF-8 encoding. You can do it with several plain text editors. With Notepad++, i.e., you can choose in the menu Encoding-->Encode in UTF-8. You can also do it even with Windows' Notepad (Save As --> Encoding UTF-8). If you are using Eclipse, you can set it in the file's Properties.

Also, check if the problem is that you have to escape those characters. It wouldn't be strange that were your problem, as one of the characters is &.

jQuery: How can I show an image popup onclick of the thumbnail?

There are a lot of jQuery plugins available for this

Thickbox

LightBox

FancyBox

FaceBox

NyroModal

PiroBox

Thickbox Examples

For a single image

  1. Create a link element ()
  2. Give the link a class attribute with a value of thickbox (class="thickbox")
  3. Provide a path in the href attribute to an image file (.jpg .jpeg .png .gif .bmp)

File name without extension name VBA

This gets the file type as from the last character (so avoids the problem with dots in file names)

Function getFileType(fn As String) As String

''get last instance of "." (full stop) in a filename then returns the part of the filename starting at that dot to the end
Dim strIndex As Integer
Dim x As Integer
Dim myChar As String

strIndex = Len(fn)
For x = 1 To Len(fn)

    myChar = Mid(fn, strIndex, 1)

    If myChar = "." Then
        Exit For
    End If

    strIndex = strIndex - 1

Next x

getFileType = UCase(Mid(fn, strIndex, Len(fn) - x + 1))

End Function

Android XXHDPI resources

A set of four generalized sizes: small, normal, large, and xlarge Note: Beginning with Android 3.2 (API level 13), these size groups are deprecated in favor of a new technique for managing screen sizes based on the available screen width. If you're developing for Android 3.2 and greater, see Declaring Tablet Layouts for Android 3.2 for more information.

A set of six generalized densities:

ldpi (low) ~120dpi

mdpi (medium) ~160dpi

hdpi (high) ~240dpi

xhdpi (extra-high) ~320dpi

xxhdpi (extra-extra-high) ~480dpi

xxxhdpi (extra-extra-extra-high) ~640dpi

From developer.android.com : http://developer.android.com/guide/practices/screens_support.html

How to change the Spyder editor background to dark?

At First click on preferences(Ctrl+Shift+alt+p) then click the option of syntax coloring and change the scheme to "Monokai".Now apply it and you will get the dark scheme.