Programs & Examples On #Jmenuitem

JMenuItem is an implementation of an item in a menu. A menu item is essentially a button sitting in a list. When the user selects the "button", the action associated with the menu item is performed.

Java: Local variable mi defined in an enclosing scope must be final or effectively final

The error means you cannot use the local variable mi inside an inner class.


To use a variable inside an inner class you must declare it final. As long as mi is the counter of the loop and final variables cannot be assigned, you must create a workaround to get mi value in a final variable that can be accessed inside inner class:

final Integer innerMi = new Integer(mi);

So your code will be like this:

for (int mi=0; mi<colors.length; mi++){

    String pos = Character.toUpperCase(colors[mi].charAt(0)) + colors[mi].substring(1);
    JMenuItem Jmi =new JMenuItem(pos);
    Jmi.setIcon(new IconA(colors[mi]));

    // workaround:
    final Integer innerMi = new Integer(mi);

    Jmi.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JMenuItem item = (JMenuItem) e.getSource();
                IconA icon = (IconA) item.getIcon();
                // HERE YOU USE THE FINAL innerMi variable and no errors!!!
                Color kolorIkony = getColour(colors[innerMi]); 
                textArea.setForeground(kolorIkony);
            }
        });

        mnForeground.add(Jmi);
    }
}

How to make FileFilter in java?

Try something like this...

String yourPath = "insert here your path..";
File directory = new File(yourPath);
String[] myFiles = directory.list(new FilenameFilter() {
    public boolean accept(File directory, String fileName) {
        return fileName.endsWith(".txt");
    }
});

UIView touch event in controller

Swift 4 / 5:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction))
self.myView.addGestureRecognizer(gesture)

@objc func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

Swift 3:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction(sender:)))
self.myView.addGestureRecognizer(gesture)

func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

How to create a drop shadow only on one side of an element?

UPDATE 4

Same like update 3 but with modern css (=less rules) so that no special positioning on the pseudo element is required.

_x000D_
_x000D_
#box {_x000D_
    background-color: #3D6AA2;_x000D_
    width: 160px;_x000D_
    height: 90px;_x000D_
    position: absolute;_x000D_
    top: calc(10% - 10px);_x000D_
    left: calc(50% - 80px);_x000D_
}_x000D_
_x000D_
.box-shadow:after {_x000D_
    content:"";_x000D_
    position:absolute;_x000D_
    width:100%;_x000D_
    bottom:1px;_x000D_
    z-index:-1;_x000D_
    transform:scale(.9);_x000D_
    box-shadow: 0px 0px 8px 2px #000000;_x000D_
}
_x000D_
<div id="box" class="box-shadow"></div>
_x000D_
_x000D_
_x000D_

UPDATE 3

All my previous answers have been using extra markup to get create this effect, which is not necessarily needed. I think this a much cleaner solution... the only trick is playing around with the values to get the right positioning of the shadow as well as the right strength/opacity of the shadow. Here's a new fiddle, using pseudo-elements:

http://jsfiddle.net/UnsungHero97/ARRRZ/2/

HTML

<div id="box" class="box-shadow"></div>

CSS

#box {
    background-color: #3D6AA2;
    width: 160px;
    height: 90px;
    margin-top: -45px;
    margin-left: -80px;
    position: absolute;
    top: 50%;
    left: 50%;
}

.box-shadow:after {
    content: "";
    width: 150px;
    height: 1px;
    margin-top: 88px;
    margin-left: -75px;
    display: block;
    position: absolute;
    left: 50%;
    z-index: -1;
    -webkit-box-shadow: 0px 0px 8px 2px #000000;
       -moz-box-shadow: 0px 0px 8px 2px #000000;
            box-shadow: 0px 0px 8px 2px #000000;
}

UPDATE 2

Apparently, you can do this with just an extra parameter to the box-shadow CSS as everyone else just pointed out. Here's the demo:

http://jsfiddle.net/K88H9/821/

CSS

-webkit-box-shadow: 0 4px 4px -2px #000000;
   -moz-box-shadow: 0 4px 4px -2px #000000;
        box-shadow: 0 4px 4px -2px #000000;

This would be a better solution. The extra parameter that is added is described as:

The fourth length is a spread distance. Positive values cause the shadow shape to expand in all directions by the specified radius. Negative values cause the shadow shape to contract.

UPDATE

Check out the demo at jsFiddle: http://jsfiddle.net/K88H9/4/

What I did was create a "shadow element" that would hide behind the actual element that you would want to have a shadow. I made the width of the "shadow element" to be exactly less wide than the actual element by 2 times the shadow you specify; then I aligned it properly.

HTML

<div id="wrapper">
    <div id="element"></div>
    <div id="shadow"></div>
</div>

CSS

#wrapper {
    width: 84px;
    position: relative;
}
#element {
    background-color: #3D668F;
    height: 54px;
    width: 100%;
    position: relative;
    z-index: 10;
}
#shadow {
    background-color: #3D668F;
    height: 8px;
    width: 80px;
    margin-left: -40px;
    position: absolute;
    bottom: 0px;
    left: 50%;
    z-index: 5;
    -webkit-box-shadow: 0px 2px 4px #000000;
       -moz-box-shadow: 0px 2px 4px #000000;
            box-shadow: 0px 2px 4px #000000;
}

Original Answer

Yes, you can do this with the same syntax you have provided. The first value controls the horizontal positioning and the second value controls the vertical positioning. So just set the first value to 0px and the second to whatever offset you'd like as follows:

-webkit-box-shadow: 0px 5px #000000;
   -moz-box-shadow: 0px 5px #000000;
        box-shadow: 0px 5px #000000;

For more info on box shadows, check out these:

I hope this helps.

PHP Get all subdirectories of a given directory

Here is how you can retrieve only directories with GLOB:

$directories = glob($somePath . '/*' , GLOB_ONLYDIR);

How to flush route table in windows?

You can open a command prompt and do a

route print

and see your current routing table.

You can modify it by

route add    d.d.d.d mask m.m.m.m g.g.g.g 
route delete d.d.d.d mask m.m.m.m g.g.g.g 
route change d.d.d.d mask m.m.m.m g.g.g.g

these seem to work

I run a ping d.d.d.d -t change the route and it changes. (my test involved routing to a dead route and the ping stopped)

Convert string with comma to integer

If someone is looking to sub out more than a comma I'm a fan of:

"1,200".chars.grep(/\d/).join.to_i

dunno about performance but, it is more flexible than a gsub, ie:

"1-200".chars.grep(/\d/).join.to_i

How to set a Header field on POST a form?

You could use $.ajax to avoid the natural behaviour of <form method="POST">. You could, for example, add an event to the submission button and treat the POST request as AJAX.

How do I import a sql data file into SQL Server?

If you are talking about an actual database (an mdf file) you would Attach it

.sql files are typically run using SQL Server Management Studio. They are basically saved SQL statements, so could be anything. You don't "import" them. More precisely, you "execute" them. Even though the script may indeed insert data.

Also, to expand on Jamie F's answer, don't run a SQL file against your database unless you know what it is doing. SQL scripts can be as dangerous as unchecked exe's

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

If you have crash with popBackStack() or popBackStackImmediate() method please try fixt with:

        if (!fragmentManager.isStateSaved()) {
            fragmentManager.popBackStackImmediate();
        }

This is worked for me as well.

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

I had the same issue. When compared the java version mentioned in the pom.xml file is different and the JAVA_HOME env variable was pointing to different version of jdk.

Have the JAVA_HOME and pom.xml updated to the same jdk installation path

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Short answer @SuppressWarnings is the right way to go.

Long answer, Hibernate returns a raw List from the Query.list method, see here. This is not a bug with Hibernate or something the can be solved, the type returned by the query is not known at compile time.

Therefore when you write

final List<MyObject> list = query.list();

You are doing an unsafe cast from List to List<MyObject> - this cannot be avoided.

There is no way you can safely carry out the cast as the List could contain anything.

The only way to make the error go away is the even more ugly

final List<MyObject> list = new LinkedList<>();
for(final Object o : query.list()) {
    list.add((MyObject)o);
}

Git Pull While Ignoring Local Changes?

.gitignore

"Adding unwanted files to .gitignore works as long as you have not initially committed them to any branch. "

Also you can run:

git update-index --assume-unchanged filename

https://chamindac.blogspot.com/2017/07/ignoring-visual-studio-2017-created.html

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

Create a string with n characters

If you want only spaces, then how about:

String spaces = (n==0)?"":String.format("%"+n+"s", "");

which will result in abs(n) spaces;

javascript jquery radio button click

this should be good

$(document).ready(function() {
    $('input:radio').change(function() {
       alert('ole');
    });
});

Get the last non-empty cell in a column in Google Sheets

My favorite is:

=INDEX(A2:A,COUNTA(A2:A),1)

So, for the OP's need:

=DAYS360(A2,INDEX(A2:A,COUNTA(A2:A),1))

Appending a list to a list of lists in R

By putting an assignment of list on a variable first

myVar <- list()

it opens the possibility of hiearchial assignments by

myVar[[1]] <- list()
myVar[[2]] <- list()

and so on... so now it's possible to do

myVar[[1]][[1]] <- c(...)
myVar[[1]][[2]] <- c(...)

or

myVar[[1]][['subVar']] <- c(...)

and so on

it is also possible to assign directly names (instead of $)

myVar[['nameofsubvar]] <- list()

and then

myVar[['nameofsubvar]][['nameofsubsubvar']] <- c('...')

important to remember is to always use double brackets to make the system work

then to get information is simple

myVar$nameofsubvar$nameofsubsubvar

and so on...

example:

a <-list()
a[['test']] <-list()
a[['test']][['subtest']] <- c(1,2,3)
a
$test
$test$subtest
[1] 1 2 3


a[['test']][['sub2test']] <- c(3,4,5)
a
$test
$test$subtest
[1] 1 2 3

$test$sub2test
[1] 3 4 5

a nice feature of the R language in it's hiearchial definition...

I used it for a complex implementation (with more than two levels) and it works!

Mime type for WOFF fonts?

Reference for adding font mime types to .NET/IIS

via web.config

<system.webServer>
  <staticContent>
     <!-- remove first in case they are defined in IIS already, which would cause a runtime error -->
     <remove fileExtension=".woff" />
     <remove fileExtension=".woff2" />
     <mimeMap fileExtension=".woff" mimeType="font/woff" />
     <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
  </staticContent>
</system.webServer>

via IIS Manager

screenshot of adding woff mime types to IIS

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

You can use code like:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>window.jQuery || document.write('<script type="text/javascript" src="./scripts/jquery.min.js">\x3C/script>')</script>

But also there are libraries you can use to setup several possible fallbacks for your scripts and optimize the loading process:

  • basket.js
  • RequireJS
  • yepnope

Examples:

basket.js I think the best variant for now. Will cach your script in the localStorage, that will speed up next loadings. The simplest call:

basket.require({ url: '/path/to/jquery.js' });

This will return a promise and you can do next call on error, or load dependencies on success:

basket
    .require({ url: '/path/to/jquery.js' })
    .then(function () {
        // Success
    }, function (error) {
        // There was an error fetching the script
        // Try to load jquery from the next cdn
    });

RequireJS

requirejs.config({
    enforceDefine: true,
    paths: {
        jquery: [
            '//ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min',
            //If the CDN location fails, load from this location
            'js/jquery-2.0.0.min'
        ]
    }
});

//Later
require(['jquery'], function ($) {
});

yepnope

yepnope([{
  load: 'http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js',
  complete: function () {
    if (!window.jQuery) {
      yepnope('js/jquery-2.0.0.min.js');
    }
  }
}]);

Detect page change on DataTable

An alternative approach would be to register an event handler on the pagination link like so:

$("#dataTableID_paginate").on("click", "a", function() { alert("clicked") });

Replace "#dataTableID_" with the ID of your table, of course. And I'm using JQuery's ON method as that is the current best practice.

String replacement in batch file

This works fine

@echo off    
set word=table    
set str=jump over the chair    
set rpl=%str:chair=%%word%    
echo %rpl%

Where does the slf4j log file get saved?

It does not write to a file by default. You would need to configure something like the RollingFileAppender and have the root logger write to it (possibly in addition to the default ConsoleAppender).

How can I hide the Android keyboard using JavaScript?

Angular version:

export component FooComponent {
  @ViewChild('bsDatePicker') calendarInput: ElementRef;

  focus(): void {
    const nativeElement = this.calendarInput.nativeElement;

    setTimeout(() => {
      nativeElement.blur();
    }, 100);
  }
}

and template:

<input
   #bsDatePicker
   bsDatepicker
   type="text"
   (focus)="focus()"/>

Get difference between two lists

This is another solution:

def diff(a, b):
    xa = [i for i in set(a) if i not in b]
    xb = [i for i in set(b) if i not in a]
    return xa + xb

Extract file basename without path and extension in bash

Here are oneliners:

  1. $(basename "${s%.*}")
  2. $(basename "${s}" ".${s##*.}")

I needed this, the same as asked by bongbang and w4etwetewtwet.

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

Install pdo for postgres Ubuntu

If you are using PHP 5.6, the command is:

sudo apt-get install php5.6-pgsql

Delete everything in a MongoDB database

In the mongo shell:

use [database];
db.dropDatabase();

And to remove the users:

db.dropAllUsers();

macro - open all files in a folder

You can use Len(StrFile) > 0 in loop check statement !

Sub openMyfile()

    Dim Source As String
    Dim StrFile As String

    'do not forget last backslash in source directory.
    Source = "E:\Planning\03\"
    StrFile = Dir(Source)

    Do While Len(StrFile) > 0                        
        Workbooks.Open Filename:=Source & StrFile
        StrFile = Dir()
    Loop
End Sub

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Please, ckeck this simple example. You can get values in select2 multi.

var values = $('#id-select2-multi').val();
console.log(values);

How to detect Windows 64-bit platform with .NET?

If you're using .NET Framework 4.0, it's easy:

Environment.Is64BitOperatingSystem

See Environment.Is64BitOperatingSystem Property (MSDN).

MongoDB: Is it possible to make a case-insensitive query?

TL;DR

Correct way to do this in mongo

Do not Use RegExp

Go natural And use mongodb's inbuilt indexing , search

Step 1 :

db.articles.insert(
   [
     { _id: 1, subject: "coffee", author: "xyz", views: 50 },
     { _id: 2, subject: "Coffee Shopping", author: "efg", views: 5 },
     { _id: 3, subject: "Baking a cake", author: "abc", views: 90  },
     { _id: 4, subject: "baking", author: "xyz", views: 100 },
     { _id: 5, subject: "Café Con Leche", author: "abc", views: 200 },
     { _id: 6, subject: "???????", author: "jkl", views: 80 },
     { _id: 7, subject: "coffee and cream", author: "efg", views: 10 },
     { _id: 8, subject: "Cafe con Leche", author: "xyz", views: 10 }
   ]
)
 

Step 2 :

Need to create index on whichever TEXT field you want to search , without indexing query will be extremely slow

db.articles.createIndex( { subject: "text" } )

step 3 :

db.articles.find( { $text: { $search: "coffee",$caseSensitive :true } } )  //FOR SENSITIVITY
db.articles.find( { $text: { $search: "coffee",$caseSensitive :false } } ) //FOR INSENSITIVITY


 

How to add a named sheet at the end of all Excel sheets?

Try to use:

Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = "MySheet"

If you want to check whether a sheet with the same name already exists, you can create a function:

Function funcCreateList(argCreateList)
    For Each Worksheet In ThisWorkbook.Worksheets
        If argCreateList = Worksheet.Name Then
            Exit Function ' if found - exit function
        End If
    Next Worksheet
    Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = argCreateList
End Function

When the function is created, you can call it from your main Sub, e.g.:

Sub main

    funcCreateList "MySheet"

Exit Sub

"Gradle Version 2.10 is required." Error

I had Android Studio version 1.5.1 installed and was running into this error. I have the following buildscript (which was working on Ubuntu but not Windows):

buildscript {
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'
    }
}

I tried:

  1. gradlew clean
  2. Use default gradle wrapper (recommended)
  3. Use local distribution and linked to downloaded gradle 2.2.1 binary

None of these solutions worked unfortunately. It should be worth noting that upgrading Android Studio from 1.5.1 to 2.1.1 also failed with errors about 2.10 missing so could not be performed.

Solution: What I ended up doing was simply downloaded the latest stable version of Android Studio and installing that instead (2.1.1 at the time). After doing that gradle synced succesfully

How to find tag with particular text with Beautiful Soup?

Since Beautiful Soup 4.4.0. a parameter called string does the work that text used to do in the previous versions.

string is for finding strings, you can combine it with arguments that find tags: Beautiful Soup will find all tags whose .string matches your value for the string. This code finds the tags whose .string is “Elsie”:

soup.find_all("td", string="Elsie")

For more information about string have a look this section https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-string-argument

Set a DateTime database field to "Now"

In SQL you need to use GETDATE():

UPDATE table SET date = GETDATE();

There is no NOW() function.


To answer your question:

In a large table, since the function is evaluated for each row, you will end up getting different values for the updated field.

So, if your requirement is to set it all to the same date I would do something like this (untested):

DECLARE @currDate DATETIME;
SET @currDate = GETDATE();

UPDATE table SET date = @currDate;

Model summary in pytorch

You can just use x.shape, in order to measure tensor's x dimensions

A cycle was detected in the build path of project xxx - Build Path Problem

I faced similar problem a while ago and decided to write Eclipse plug-in that shows complete build path dependency tree of a Java project (although not in graphic mode - result is written into file). The plug-in's sources are here http://github.com/PetrGlad/dependency-tree

MAVEN_HOME, MVN_HOME or M2_HOME

I have solved same issue with following:

export M2_HOME=/usr/share/maven

Explain the different tiers of 2 tier & 3 tier architecture?

Wikipedia explains it better then I could

From the article - Top is 1st Tier: alt text

Is there an opposite to display:none?

visibility:hidden will hide the element but element is their with DOM. And in case of display:none it'll remove the element from the DOM.

So you have option for element to either hide or unhide. But once you delete it ( I mean display none) it has not clear opposite value. display have several values like display:block,display:inline, display:inline-block and many other. you can check it out from W3C.

EnterKey to press button in VBA Userform

This one worked for me

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        If KeyCode = 13 Then
             Button1_Click
        End If
End Sub

WPF loading spinner

The approach is to use geometry with animations applied. Add the required geometry to the Path and animate its RotateTransform from 0-360°.

My spinner support two types of spinners:

  1. Circles :
  2. Rings :

And the central logic looks like:

if(spinner.SpinnerType == SpinnerType.Ring)
{
 double innerRad = spinner.Radius - spinner.ItemRadius;
 Point center = new Point(0, 0);
 grp.Children.Add(new EllipseGeometry( center, spinner.Radius, spinner.Radius));
 grp.Children.Add(new EllipseGeometry(center, innerRad, innerRad));                
 return;
}
var points = GetPointsOnCircle( spinner.Diameter/ 2);
double r = spinner.ItemRadius;
foreach (var point in points)
{
 grp.Children.Add(new EllipseGeometry(point, r, r));
 r -= spinner.ContinuousSizeReduction;
}

Usage is as simple as follows:

<local:SpinnerControl Diameter="60" Fill="#FFE8B311"/>

Here is the source code!

How to Apply Corner Radius to LinearLayout

You can create an XML file in the drawable folder. Call it, for example, shape.xml

In shape.xml:

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

    <solid
        android:color="#888888" >
    </solid>

    <stroke
        android:width="2dp"
        android:color="#C4CDE0" >
    </stroke>

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"    >
    </padding>

    <corners
        android:radius="11dp"   >
    </corners>

</shape>

The <corner> tag is for your specific question.

Make changes as required.

And in your whatever_layout_name.xml:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_margin="5dp"
    android:background="@drawable/shape"    >
</LinearLayout>

This is what I usually do in my apps. Hope this helps....

MSVCP120d.dll missing

I downloaded msvcr120d.dll and msvcp120d.dll for 32-bit version and then, I put them into Debug folder of my project. It worked well. (My computer is 64-bit version)

How to create two columns on a web page?

I found a real cool Grid which I also use for columns. Check it out Simple Grid. Wich this CSS you can simply use:

<div class="grid">
    <div class="col-1-2">
       <div class="content">
           <p>...insert content left side...</p>
       </div>
    </div>
    <div class="col-1-2">
       <div class="content">
           <p>...insert content right side...</p>
       </div>
    </div>
</div>

I use it for all my projects.

python: urllib2 how to send cookie with urlopen request

Use cookielib. The linked doc page provides examples at the end. You'll also find a tutorial here.

How do I parse JSON with Objective-C?

Don't reinvent the wheel. Use json-framework or something similar.

If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary:

SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];

// now you can grab data out of the dictionary using objectForKey or another dictionary method

How can I make a countdown with NSTimer?

Swift 3

private let NUMBER_COUNT_DOWN   = 3

var countDownLabel = UILabel()
var countDown = NUMBER_COUNT_DOWN
var timer:Timer?


private func countDown(time: Double)
{
    countDownLabel.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
    countDownLabel.font = UIFont.systemFont(ofSize: 300)
    countDownLabel.textColor = .black
    countDownLabel.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)

    countDownLabel.textAlignment = .center
    self.view.addSubview(countDownLabel)
    view.bringSubview(toFront: countDownLabel)

    timer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(updateCountDown), userInfo: nil, repeats: true)
}

func updateCountDown() {
    if(countDown > 0) {
        countDownLabel.text = String(countDown)
        countDown = countDown - 1
    } else {
        removeCountDownLable()
    }
}

private func removeCountDownLable() {
    countDown = NUMBER_COUNT_DOWN
    countDownLabel.text = ""
    countDownLabel.removeFromSuperview()

    timer?.invalidate()
    timer = nil
}

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

display: inline-block extra margin

There are a number of workarounds for this issue which involve word-spacing or font size but this article suggests removing the margin with a right margin of -4px;

http://designshack.net/articles/css/whats-the-deal-with-display-inline-block/

Clicking HTML 5 Video element to play, pause video, breaks play button

The simplest form is to use the onclick listener:

<video height="auto" controls="controls" preload="none" onclick="this.play()">
 <source type="video/mp4" src="vid.mp4">
</video>

No jQuery or complicated Javascript code needed.

Play/Pause can be done with onclick="this.paused ? this.play() : this.pause();".

failed to find target with hash string android-23

Nothing worked for me. I changed SDK path to new SDK location and reinstalled SDK.Its working perfectly.

Custom Listview Adapter with filter Android

Just an update.

If the ticked answer is working fine for you but it shows nothing when the search text is empty. Here is the solution:

private class ItemFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        
        String filterString = constraint.toString().toLowerCase();
        
        FilterResults results = new FilterResults();

        if(constraint.length() == 0)
        {
            results.count = originalData.size();
            results.values = originalData;
        }else {

        
        final List<String> list = originalData;

        int count = list.size();
        final ArrayList<String> nlist = new ArrayList<String>(count);

        String filterableString ;
        
        for (int i = 0; i < count; i++) {
            filterableString = list.get(i);
            if (filterableString.toLowerCase().contains(filterString)) {
                nlist.add(filterableString);
            }
        }
        
        results.values = nlist;
        results.count = nlist.size();
     }
        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        filteredData = (ArrayList<String>) results.values;
        notifyDataSetChanged();
      }

   }

For any query comment below

Singleton design pattern vs Singleton beans in Spring container

A singleton bean in Spring and the singleton pattern are quite different. Singleton pattern says that one and only one instance of a particular class will ever be created per classloader.

The scope of a Spring singleton is described as "per container per bean". It is the scope of bean definition to a single object instance per Spring IoC container. The default scope in Spring is Singleton.

Even though the default scope is singleton, you can change the scope of bean by specifying the scope attribute of <bean ../> element.

<bean id=".." class=".." scope="prototype" />

How to get the name of the current method from code

Call System.Reflection.MethodBase.GetCurrentMethod().Name from within the method.

How to set conditional breakpoints in Visual Studio?

  1. Set a breakpoint as usual
  2. Right click on the breakpoint and select Condition
  3. You'll see a dialog that says "Breakpoint Condition"
  4. Put a condition in the field e.g. "i==5"

The breakpoint will only get hit when i is 5.

WebView link click open default browser

WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl(https://whatoplay.com/);

You don't have to include this code.

// webview.setWebViewClient(new WebViewClient());

Instead use below code.

webview.setWebViewClient(new WebViewClient()
{
  public boolean shouldOverrideUrlLoading(WebView view, String url)
  {
    String url2="https://whatoplay.com/";
     // all links  with in ur site will be open inside the webview 
     //links that start ur domain example(http://www.example.com/)
    if (url != null && url.startsWith(url2)){
      return false;
    } 
     // all links that points outside the site will be open in a normal android browser
    else
    {
      view.getContext().startActivity(
      new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
      return true;
    }
  }
});

Javascript/jQuery detect if input is focused

Using jQuery's .is( ":focus" )

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }

Error "package android.support.v7.app does not exist"

try to copy C:\Program Files\Java\jdk1.8.0_121 && C:\Program Files\Java\jre1.8.0_121 from other working PC then all (clean && rebuild)

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

It depends on the encoding of your string (ASCII, UTF-8, ...).

For example:

byte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString);
byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString);

A small sample why encoding matters:

string pi = "\u03a0";
byte[] ascii = System.Text.Encoding.ASCII.GetBytes (pi);
byte[] utf8 = System.Text.Encoding.UTF8.GetBytes (pi);

Console.WriteLine (ascii.Length); //Will print 1
Console.WriteLine (utf8.Length); //Will print 2
Console.WriteLine (System.Text.Encoding.ASCII.GetString (ascii)); //Will print '?'

ASCII simply isn't equipped to deal with special characters.

Internally, the .NET framework uses UTF-16 to represent strings, so if you simply want to get the exact bytes that .NET uses, use System.Text.Encoding.Unicode.GetBytes (...).

See Character Encoding in the .NET Framework (MSDN) for more information.

How to format a Java string with leading zero?

You can use:

String.format("%08d", "Apple");

It seems to be the simplest method and there is no need of any external library.

On linux SUSE or RedHat, how do I load Python 2.7

If you get an error when at the ./configure stage that says

configure: error: in `/home//Downloads/Python-2.7.14': configure: error: no acceptable C compiler found in $PATH

then try this.

no acceptable C compiler found in $PATH when installing python

Non-recursive depth first search algorithm

DFS:

list nodes_to_visit = {root};
while( nodes_to_visit isn't empty ) {
  currentnode = nodes_to_visit.take_first();
  nodes_to_visit.prepend( currentnode.children );
  //do something
}

BFS:

list nodes_to_visit = {root};
while( nodes_to_visit isn't empty ) {
  currentnode = nodes_to_visit.take_first();
  nodes_to_visit.append( currentnode.children );
  //do something
}

The symmetry of the two is quite cool.

Update: As pointed out, take_first() removes and returns the first element in the list.

Add and remove multiple classes in jQuery

Add multiple classes:

$("p").addClass("class1 class2 class3");

or in cascade:

$("p").addClass("class1").addClass("class2").addClass("class3");

Very similar also to remove more classes:

$("p").removeClass("class1 class2 class3");

or in cascade:

$("p").removeClass("class1").removeClass("class2").removeClass("class3");

SSIS Connection Manager Not Storing SQL Password

That answer points to this article: http://support.microsoft.com/kb/918760

Here are the proposed solutions - have you evaluated them?

  • Method 1: Use a SQL Server Agent proxy account

Create a SQL Server Agent proxy account. This proxy account must use a credential that lets SQL Server Agent run the job as the account that created the package or as an account that has the required permissions.

This method works to decrypt secrets and satisfies the key requirements by user. However, this method may have limited success because the SSIS package user keys involve the current user and the current computer. Therefore, if you move the package to another computer, this method may still fail, even if the job step uses the correct proxy account. Back to the top

  • Method 2: Set the SSIS Package ProtectionLevel property to ServerStorage

Change the SSIS Package ProtectionLevel property to ServerStorage. This setting stores the package in a SQL Server database and allows access control through SQL Server database roles. Back to the top

  • Method 3: Set the SSIS Package ProtectionLevel property to EncryptSensitiveWithPassword

Change the SSIS Package ProtectionLevel property to EncryptSensitiveWithPassword. This setting uses a password for encryption. You can then modify the SQL Server Agent job step command line to include this password.

  • Method 4: Use SSIS Package configuration files

Use SSIS Package configuration files to store sensitive information, and then store these configuration files in a secured folder. You can then change the ProtectionLevel property to DontSaveSensitive so that the package is not encrypted and does not try to save secrets to the package. When you run the SSIS package, the required information is loaded from the configuration file. Make sure that the configuration files are adequately protected if they contain sensitive information.

  • Method 5: Create a package template

For a long-term resolution, create a package template that uses a protection level that differs from the default setting. This problem will not occur in future packages.

asynchronous vs non-blocking

synchronous / asynchronous is to describe the relation between two modules.
blocking / non-blocking is to describe the situation of one module.

An example:
Module X: "I".
Module Y: "bookstore".
X asks Y: do you have a book named "c++ primer"?

  1. blocking: before Y answers X, X keeps waiting there for the answer. Now X (one module) is blocking. X and Y are two threads or two processes or one thread or one process? we DON'T know.

  2. non-blocking: before Y answers X, X just leaves there and do other things. X may come back every two minutes to check if Y has finished its job? Or X won't come back until Y calls him? We don't know. We only know that X can do other things before Y finishes its job. Here X (one module) is non-blocking. X and Y are two threads or two processes or one process? we DON'T know. BUT we are sure that X and Y couldn't be one thread.

  3. synchronous: before Y answers X, X keeps waiting there for the answer. It means that X can't continue until Y finishes its job. Now we say: X and Y (two modules) are synchronous. X and Y are two threads or two processes or one thread or one process? we DON'T know.

  4. asynchronous: before Y answers X, X leaves there and X can do other jobs. X won't come back until Y calls him. Now we say: X and Y (two modules) are asynchronous. X and Y are two threads or two processes or one process? we DON'T know. BUT we are sure that X and Y couldn't be one thread.


Please pay attention on the two bold-sentences above. Why does the bold-sentence in the 2) contain two cases whereas the bold-sentence in the 4) contains only one case? This is a key of the difference between non-blocking and asynchronous.

Here is a typical example about non-blocking & synchronous:

// thread X
while (true)
{
    msg = recv(Y, NON_BLOCKING_FLAG);
    if (msg is not empty)
    {
        break;
    }
    else
    {
        sleep(2000); // 2 sec
    }
}

// thread Y
// prepare the book for X
send(X, book);

You can see that this design is non-blocking (you can say that most of time this loop does something nonsense but in CPU's eyes, X is running, which means that X is non-blocking) whereas X and Y are synchronous because X can't continue to do any other things(X can't jump out of the loop) until it gets the book from Y.
Normally in this case, make X blocking is much better because non-blocking spends much resource for a stupid loop. But this example is good to help you understand the fact: non-blocking doesn't mean asynchronous.

The four words do make us confused easily, what we should remember is that the four words serve for the design of architecture. Learning about how to design a good architecture is the only way to distinguish them.

For example, we may design such a kind of architecture:

// Module X = Module X1 + Module X2
// Module X1
while (true)
{
    msg = recv(many_other_modules, NON_BLOCKING_FLAG);
    if (msg is not null)
    {
        if (msg == "done")
        {
            break;
        }
        // create a thread to process msg
    }
    else
    {
        sleep(2000); // 2 sec
    }
}
// Module X2
broadcast("I got the book from Y");


// Module Y
// prepare the book for X
send(X, book);

In the example here, we can say that

  • X1 is non-blocking
  • X1 and X2 are synchronous
  • X and Y are asynchronous

If you need, you can also describe those threads created in X1 with the four words.

The more important things are: when do we use synchronous instead of asynchronous? when do we use blocking instead of non-blocking? Is making X1 blocking better than non-blocking? Is making X and Y synchronous better than asynchronous? Why is Nginx non-blocking? Why is Apache blocking? These questions are what you must figure out.

To make a good choice, you must analyze your need and test the performance of different architectures. There is no such an architecture that is suitable for various of needs.

How to measure the a time-span in seconds using System.currentTimeMillis()?

TimeUnit

Use the TimeUnit enum built into Java 5 and later.

long timeMillis = System.currentTimeMillis();
long timeSeconds = TimeUnit.MILLISECONDS.toSeconds(timeMillis);

Select method of Range class failed via VBA

This worked for me.

RowCounter = Sheets(3).UsedRange.Rows.Count + 1

Sheets(1).Rows(rowNum).EntireRow.Copy
Sheets(3).Activate
Sheets(3).Cells(RowCounter, 1).Select
Sheets(3).Paste
Sheets(1).Activate

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Difference between checkout and export in SVN

As you stated, a checkout includes the .svn directories. Thus it is a working copy and will have the proper information to make commits back (if you have permission). If you do an export you are just taking a copy of the current state of the repository and will not have any way to commit back any changes.

How do you set up use HttpOnly cookies in PHP

A more elegant solution since PHP >=7.0

session_start(['cookie_lifetime' => 43200,'cookie_secure' => true,'cookie_httponly' => true]);

session_start

session_start options

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

I just get my application move from ActionBarSherlock to ActionBarCompat. Try declare your old theme like this:

<style name="Theme.Event" parent="Theme.AppCompat">

Then set the theme in your AndroidManifest.xml:

<application
    android:debuggable="true"
    android:name=".activity.MyApplication"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.Event.Home"
     >

How do you rename a MongoDB database?

There is no mechanism to re-name databases. The currently accepted answer at time of writing is factually correct and offers some interesting background detail as to the excuse upstream, but offers no suggestions for replicating the behavior. Other answers point at copyDatabase, which is no longer an option as the functionality has been removed in 4.0. I've updated SERVER-701 with my notes and incredulity.

Equivalent behavior involves mongodump and mongorestore in a bit of a dance:

  1. Export your data, making note of the "namespaces" in use. For example, on one of my datasets, I have a collection with the namespace byzmcbehoomrfjcs9vlj.Analytics — that prefix (actually the database name) will be needed in the next step.

  2. Import your data, supplying --nsFrom and --nsTo arguments. (Documentation.) Continuing with my above hypothetical (and extremely unreadable) example, to restore to a more sensical name, I invoke:

mongorestore --archive=backup.agz --gzip --drop \
    --nsFrom 'byzmcbehoomrfjcs9vlj.*' --nsTo 'rita.*'

Some may also point at the --db argument to mongorestore, however this, too, is deprecated and triggers a warning against use on non-BSON folder backups with a completely erroneous suggestion to "use --nsInclude instead". The above namespace translation is equivalent to use of the --db option, and is the correct namespace manipulation setup to use as we are not attempting to filter what is being restored.

Jquery - How to get the style display attribute "none / block"

If you're using jquery 1.6.2 you only need to code

$('#theid').css('display')

for example:

if($('#theid').css('display') == 'none'){ 
   $('#theid').show('slow'); 
} else { 
   $('#theid').hide('slow'); 
}

How do I concatenate two text files in PowerShell?

To keep encoding and line endings:

Get-Content files.* -Raw | Set-Content newfile.file -NoNewline

Note: AFAIR, whose parameters aren't supported by old Powershells (<3? <4?)

How can I rotate an HTML <div> 90 degrees?

We can add the following to a particular tag in CSS:

-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);

In case of half rotation change 90 to 45.

Returning a C string from a function

A char is only a single one-byte character. It can't store the string of characters, nor is it a pointer (which you apparently cannot have). Therefore you cannot solve your problem without using pointers (which char[] is syntactic sugar for).

How do you append rows to a table using jQuery?

The following code works

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function AddRow()
{
    $('#myTable').append('<tr><td>test 2</td></tr>')
}
</script>
<title></title>
</head>
<body>
<input type="button" id="btnAdd" onclick="AddRow()"/>
<a href="">test</a>
<table id="myTable">
  <tbody >
    <tr>
      <td>
        test
      </td>
    </tr>
  </tbody>
</table>
</body>
</html>

Note this will work as of jQuery 1.4 even if the table includes a <tbody> element:

jQuery since version 1.4(?) automatically detects if the element you are trying to insert (using any of the append(), prepend(), before(), or after() methods) is a <tr> and inserts it into the first <tbody> in your table or wraps it into a new <tbody> if one doesn't exist.

How do I install Keras and Theano in Anaconda Python on Windows?

install by this command given below conda install -c conda-forge keras

this is error "CondaError: Cannot link a source that does not exist" ive get in win 10. for your error put this command in your command line.

conda update conda

this work for me .

JAVA_HOME and PATH are set but java -version still shows the old one

check available Java versions on your Linux system by using update-alternatives command:

 $ sudo update-alternatives --display java

Now that there are suitable candidates to change to, you can switch the default Java version among available Java JREs by running the following command:

 $ sudo update-alternatives --config java

When prompted, select the Java version you would like to use.1 or 2 or 3 or etc..

Now you can verify the default Java version changed as follows.

 $ java -version

What is the correct way to write HTML using Javascript?

There are many ways to write html with JavaScript.

document.write is only useful when you want to write to page before it has actually loaded. If you use document.write() after the page has loaded (at onload event) it will create new page and overwrite the old content. Also it doesn't work with XML, that includes XHTML.

From other hand other methods can't be used before DOM has been created (page loaded), because they work directly with DOM.

These methods are:

  • node.innerHTML = "Whatever";
  • document.createElement('div'); and node.appendChild(), etc..

In most cases node.innerHTML is better since it's faster then DOM functions. Most of the time it also make code more readable and smaller.

is there any PHP function for open page in new tab

You can use both PHP and javascript. Perform your php codes in the backend and redirect to a php page. On the php page you redirected to add the code below:

<?php if(condition_to_check_for){ ?>

    <script type="text/javascript">
       window.open('url_goes_here', '_blank');
    </script>

<?  } ?>

What does the star operator mean, in a function call?

I find this particularly useful for when you want to 'store' a function call.

For example, suppose I have some unit tests for a function 'add':

def add(a, b): return a + b
tests = { (1,4):5, (0, 0):0, (-1, 3):3 }
for test, result in tests.items():
    print 'test: adding', test, '==', result, '---', add(*test) == result

There is no other way to call add, other than manually doing something like add(test[0], test[1]), which is ugly. Also, if there are a variable number of variables, the code could get pretty ugly with all the if-statements you would need.

Another place this is useful is for defining Factory objects (objects that create objects for you). Suppose you have some class Factory, that makes Car objects and returns them. You could make it so that myFactory.make_car('red', 'bmw', '335ix') creates Car('red', 'bmw', '335ix'), then returns it.

def make_car(*args):
    return Car(*args)

This is also useful when you want to call a superclass' constructor.

onchange event for html.dropdownlist

If you don't want jquery then you can do it with javascript :-

@Html.DropDownList("Sortby", new SelectListItem[] 
{ 
     new SelectListItem() { Text = "Newest to Oldest", Value = "0" }, 
     new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},
     new { @onchange="callChangefunc(this.value)" 
});

<script>
    function callChangefunc(val){
        window.location.href = "/Controller/ActionMethod?value=" + val;
    }
</script>

Removing duplicates from a String in Java

Convert the string to an array of char, and store it in a LinkedHashSet. That will preserve your ordering, and remove duplicates. Something like:

String string = "aabbccdefatafaz";

char[] chars = string.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
    charSet.add(c);
}

StringBuilder sb = new StringBuilder();
for (Character character : charSet) {
    sb.append(character);
}
System.out.println(sb.toString());

How to print a linebreak in a python function?

You can print a native linebreak using the standard os library

import os
with open('test.txt','w') as f:
    f.write(os.linesep)

How to delete a row from GridView?

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Default3 : System.Web.UI.Page
{
   DataTable dt = new DataTable();
    DataSet Gds = new DataSet();
   // DataColumn colm1 = new DataColumn();
   //DataColumn colm2 = new DataColumn();

    protected void Page_Load(object sender, EventArgs e)
    {
        dt.Columns.Add("ExpId", typeof(int));
        dt.Columns.Add("FirstName", typeof(string));

    }


    protected void BtnLoad_Click(object sender, EventArgs e)
    {
        //   gvLoad is Grid View Id
        if (gvLoad.Rows.Count == 0)
        {
            Gds.Tables.Add(tblLoad());
        }
        else
        {
            dt = tblGridRow();
            dt.Rows.Add(tblRow());
            Gds.Tables.Add(dt);
        }
        gvLoad.DataSource = Gds;
        gvLoad.DataBind();
    }

    protected DataTable tblLoad()
    {
        dt.Rows.Add(tblRow());
        return dt;
    }
    protected DataRow tblRow()
    {
        DataRow dr;
        dr = dt.NewRow();
        dr["Exp Id"] = Convert.ToInt16(txtId.Text);
        dr["First Name"] = Convert.ToString(txtName.Text);
        return dr;
    }

    protected DataTable tblGridRow()
    {
        DataRow dr;
        for (int i = 0; i < gvLoad.Rows.Count; i++)
        {
            if (gvLoad.Rows[i].Cells[0].Text != null)
            {

                dr = dt.NewRow();
                dr["Exp Id"] = gvLoad.Rows[i].Cells[1].Text.ToString();
                dr["First Name"] = gvLoad.Rows[i].Cells[2].Text.ToString();
                dt.Rows.Add(dr);

            }

        }
        return dt;
    }

    protected void btn_Click(object sender, EventArgs e)
    {
        dt = tblGridRow();
        dt.Rows.Add(tblRow());
        Session["tab"] = dt;
        // Response.Redirect("Default.aspx");
    }

    protected void gvLoad_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        dt = tblGridRow();
        dt.Rows.RemoveAt(e.RowIndex);
        gvLoad.DataSource = dt;
        gvLoad.DataBind();
    }
}

pip broke. how to fix DistributionNotFound error?

I replaced 0.8.1 in 0.8.2 in /usr/local/bin/pip and everything worked again.

__requires__ = 'pip==0.8.2'
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.exit(
        load_entry_point('pip==0.8.2', 'console_scripts', 'pip')()
    )

I installed pip through easy_install which probably caused me this headache. I think this is how you should do it nowadays..

$ sudo apt-get install python-pip python-dev build-essential 
$ sudo pip install --upgrade pip 
$ sudo pip install --upgrade virtualenv

svn list of files that are modified in local copy

If you really want to list modified files only you can reduce the output of svn st by leading "M" that indicates a file has been modified. I would do this like that:

svn st | grep ^M

Difference between null and empty string

String s1 = ""; means that the empty String is assigned to s1. In this case, s1.length() is the same as "".length(), which will yield 0 as expected.

String s2 = null; means that (null) or "no value at all" is assigned to s2. So this one, s2.length() is the same as null.length(), which will yield a NullPointerException as you can't call methods on null variables (pointers, sort of) in Java.

Also, a point, the statement

String s1;

Actually has the same effect as:

String s1 = null;

Whereas

String s1 = "";

Is, as said, a different thing.

De-obfuscate Javascript code to make it readable again

I have tried both of online jsbeautifier(jsbeautifier, jsnice), these tools gave me beautiful js code,

but couldn't copy for very large js (must be bug, when i copy, copied buffer contains only one character '-').

I found that only working solution was prettyjs:

http://www.thaoh.net/prettyjs/

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

A possibility is that the git server you are pushing to is down/crashed, and the solution lies in restarting the git server.

Is there a function to round a float in C or do I need to write my own?

To print a rounded value, @Matt J well answers the question.

float x = 45.592346543;
printf("%0.1f\n", x);  // 45.6

As most floating point (FP) is binary based, exact rounding to one decimal place is not possible when the mathematically correct answer is x.1, x.2, ....

To convert the FP number to the nearest 0.1 is another matter.

Overflow: Approaches that first scale by 10 (or 100, 1000, etc) may overflow for large x.

float round_tenth1(float x) {
  x = x * 10.0f;
  ...
}

Double rounding: Adding 0.5f and then using floorf(x*10.0f + 0.5f)/10.0 returns the wrong result when the intermediate sum x*10.0f + 0.5f rounds up to a new integer.

// Fails to round 838860.4375 correctly, comes up with 838860.5 
// 0.4499999880790710449 fails as it rounds to 0.5
float round_tenth2(float x) {
  if (x < 0.0) {
    return ceilf(x*10.0f + 0.5f)/10.0f;
  }
  return floorf(x*10.0f + 0.5f)/10.0f;
}

Casting to int has the obvious problem when float x is much greater than INT_MAX.


Using roundf() and family, available in <math.h> is the best approach.

float round_tenthA(float x) {
  double x10 = 10.0 * x;
  return (float) (round(x10)/10.0);
}

To avoid using double, simply test if the number needs rounding.

float round_tenthB(float x) {
  const float limit = 1.0/FLT_EPSILON;
  if (fabsf(x) < limit) {
    return roundf(x*10.0f)/10.0f;
  }
  return x;
}

How to test which port MySQL is running on and whether it can be connected to?

I agree with @bortunac's solution. my.conf is mysql specific while netstat will provide you with all the listening ports.

Perhaps use both, one to confirm which is port set for mysql and the other to check that the system is listening through that port.

My client uses CentOS 6.6 and I have found the my.conf file under /etc/, so I used:

grep port /etc/my.conf (CentOS 6.6)

grunt: command not found when running from terminal

I'm guessing you used Brew to install Node, so the guide here might be helpful http://madebyhoundstooth.com/blog/install-node-with-homebrew-on-os-x/.

You need to ensure that the npm/bin is in your path as it describes export PATH="/usr/local/share/npm/bin:$PATH". This is the location that npm will install the bin stubs for the installed packages.


The nano version will also work as described here http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/ but a restart of Terminal may be required to have the new path picked up.

How to search a string in String array

If the array is sorted, you can use BinarySearch. This is a O(log n) operation, so it is faster as looping. If you need to apply multiple searches and speed is a concern, you could sort it (or a copy) before using it.

Can I use GDB to debug a running process?

ps -elf doesn't seem to show the PID. I recommend using instead:

ps -ld | grep foo
gdb -p PID

How to Get the HTTP Post data in C#?

You are missing a step. You need to log / store the values on your server (mailgun is a client). Then you need to retrieve those values on your server (your pc with your web browser will be a client). These will be two totally different aspx files (or the same one with different parameters).

aspx page 1 (the one that mailgun has):

var val = Request.Form["recipient"];
var file = new File(filename);
file.write(val);
close(file);

aspx page 2:

var contents = "";
if (File.exists(filename))
  var file = File.open(filename);
  contents = file.readtoend();
  file.close()

Request.write(contents);

Exit while loop by user hitting ENTER key

The following works from me:

i = '0'
while len(i) != 0:
    i = list(map(int, input(),split()))

onclick on a image to navigate to another page using Javascript

You can define a a click function and then set the onclick attribute for the element.

function imageClick(url) {
    window.location = url;
}

<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" onclick="imageClick('../images/bottle.html')" />

This approach lets you get rid of the surrounding <a> element. If you want to keep it, then define the onclick attribute on <a> instead of on <img>.

Share application "link" in Android

Actually the best way to sheared you app between users , google (firebase) proved new technology Firebase Dynamic Link Through several lines you can make it this is documentation https://firebase.google.com/docs/dynamic-links/ and the code is

  Uri dynamicLinkUri = dynamicLink.getUri();
      Task<ShortDynamicLink> shortLinkTask = FirebaseDynamicLinks.getInstance().createDynamicLink()
            .setLink(Uri.parse("https://www.google.jo/"))
            .setDynamicLinkDomain("rw4r7.app.goo.gl")
            .buildShortDynamicLink()
            .addOnCompleteListener(this, new OnCompleteListener<ShortDynamicLink>() {
                @Override
                public void onComplete(@NonNull Task<ShortDynamicLink> task) {
                    if (task.isSuccessful()) {
                        // Short link created
                        Uri shortLink = task.getResult().getShortLink();
                        Uri flowchartLink = task.getResult().getPreviewLink();
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_SEND);
                        intent.putExtra(Intent.EXTRA_TEXT,  shortLink.toString());
                        intent.setType("text/plain");
                        startActivity(intent);
                    } else {
                        // Error
                        // ...
                    }
                }
            });

Eclipse plugin for generating a class diagram

Must it be an Eclipse plug-in? I use doxygen, just supply your code folder, it handles the rest.

How to remove symbols from a string with Python?

Sometimes it takes longer to figure out the regex than to just write it out in python:

import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
    s = s.replace(char, ' ')

If you need other characters you can change it to use a white-list or extend your black-list.

Sample white-list:

whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
    if char in whitelist:
        new_s += char
    else:
        new_s += ' '

Sample white-list using a generator-expression:

whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)

EditText, clear focus on touch outside

I really think it's a more robust way to use getLocationOnScreen than getGlobalVisibleRect. Because I meet a problem. There is a Listview which contain some Edittext and and set ajustpan in the activity. I find getGlobalVisibleRect return a value that looks like including the scrollY in it, but the event.getRawY is always by the screen. The below code works well.

public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if ( v instanceof EditText) {
            if (!isPointInsideView(event.getRawX(), event.getRawY(), v)) {
                Log.i(TAG, "!isPointInsideView");

                Log.i(TAG, "dispatchTouchEvent clearFocus");
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }
    return super.dispatchTouchEvent( event );
}

/**
 * Determines if given points are inside view
 * @param x - x coordinate of point
 * @param y - y coordinate of point
 * @param view - view object to compare
 * @return true if the points are within view bounds, false otherwise
 */
private boolean isPointInsideView(float x, float y, View view) {
    int location[] = new int[2];
    view.getLocationOnScreen(location);
    int viewX = location[0];
    int viewY = location[1];

    Log.i(TAG, "location x: " + location[0] + ", y: " + location[1]);

    Log.i(TAG, "location xWidth: " + (viewX + view.getWidth()) + ", yHeight: " + (viewY + view.getHeight()));

    // point is inside view bounds
    return ((x > viewX && x < (viewX + view.getWidth())) &&
            (y > viewY && y < (viewY + view.getHeight())));
}

Pyspark replace strings in Spark dataframe column

For scala

import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))

Convert base64 png data to javascript file objects

Way 1: only works for dataURL, not for other types of url.

function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}

//Usage example:
var file = dataURLtoFile('data:image/png;base64,......', 'a.png');
console.log(file);

Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)

//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
    mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
    return (fetch(url)
        .then(function(res){return res.arrayBuffer();})
        .then(function(buf){return new File([buf], filename, {type:mimeType});})
    );
}

//Usage example:
urltoFile('data:image/png;base64,......', 'a.png')
.then(function(file){
    console.log(file);
})

Both works in Chrome and Firefox.

Get age from Birthdate

JsFiddle

You can calculate with Dates.

var birthdate = new Date("1990/1/1");
var cur = new Date();
var diff = cur-birthdate; // This is the difference in milliseconds
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25

Entity framework code-first null foreign key

I recommend to read Microsoft guide for use Relationships, Navigation Properties and Foreign Keys in EF Code First, like this picture.

enter image description here

Guide link below:

https://docs.microsoft.com/en-gb/ef/ef6/fundamentals/relationships?redirectedfrom=MSDN

Initialize array of strings

Its fine to just do char **strings;, char **strings = NULL, or char **strings = {NULL}

but to initialize it you'd have to use malloc:

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

int main(){
    // allocate space for 5 pointers to strings
    char **strings = (char**)malloc(5*sizeof(char*));
    int i = 0;
    //allocate space for each string
    // here allocate 50 bytes, which is more than enough for the strings
    for(i = 0; i < 5; i++){
        printf("%d\n", i);
        strings[i] = (char*)malloc(50*sizeof(char));
    }
    //assign them all something
    sprintf(strings[0], "bird goes tweet");
    sprintf(strings[1], "mouse goes squeak");
    sprintf(strings[2], "cow goes moo");
    sprintf(strings[3], "frog goes croak");
    sprintf(strings[4], "what does the fox say?");
    // Print it out
    for(i = 0; i < 5; i++){
        printf("Line #%d(length: %lu): %s\n", i, strlen(strings[i]),strings[i]);
    } 
    //Free each string
    for(i = 0; i < 5; i++){
        free(strings[i]);
    }
    //finally release the first string
    free(strings);
    return 0;
}

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

require 'alien'

if alien.platform == "windows" then
  kernel32 = alien.load("kernel32.dll")
  sleep = kernel32.Sleep
  sleep:types{ret="void",abi="stdcall","uint"}
else
  -- untested !!!
  libc = alien.default
  local usleep = libc.usleep
  usleep:types('int', 'uint')
  sleep = function(ms)
    while ms > 1000 do
      usleep(1000)
      ms = ms - 1000
    end
    usleep(1000 * ms)
  end
end 

print('hello')
sleep(500)  -- sleep 500 ms
print('world')

How to break lines in PowerShell?

Try "`n" with double quotes. (not single quotes '`n' )

For a complete list of escaping characters see:

Help about_Escape_character

The code should be

$str += "`n"

Pythonic way to find maximum value and its index in a list?

max([(value,index) for index,value in enumerate(your_list)]) #if maximum value is present more than once in your list then this will return index of the last occurrence

If maximum value in present more than once and you want to get all indices,

max_value = max(your_list)
maxIndexList = [index for index,value in enumerate(your_list) if value==max(your_list)]

How to retrieve the last autoincremented ID from a SQLite table?

I've had issues with using SELECT last_insert_rowid() in a multithreaded environment. If another thread inserts into another table that has an autoinc, last_insert_rowid will return the autoinc value from the new table.

Here's where they state that in the doco:

If a separate thread performs a new INSERT on the same database connection while the sqlite3_last_insert_rowid() function is running and thus changes the last insert rowid, then the value returned by sqlite3_last_insert_rowid() is unpredictable and might not equal either the old or the new last insert rowid.

That's from sqlite.org doco

Variable length (Dynamic) Arrays in Java

Arrays are fixed size once instantiated. You can use a List instead.

Autoboxing make a List usable similar to an array, you can put simply int-values into it:

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);

Which maven dependencies to include for spring 3.0?

You can try this

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>
</dependencies>`

Pass multiple complex objects to a post/put Web API method

Here I found a workaround to pass multiple generic objects (as json) from jquery to a WEB API using JObject, and then cast back to your required specific object type in api controller. This objects provides a concrete type specifically designed for working with JSON.

var combinedObj = {}; 
combinedObj["obj1"] = [your json object 1]; 
combinedObj["obj2"] = [your json object 2];

$http({
       method: 'POST',
       url: 'api/PostGenericObjects/',
       data: JSON.stringify(combinedObj)
    }).then(function successCallback(response) {
         // this callback will be called asynchronously
         // when the response is available
         alert("Saved Successfully !!!");
    }, function errorCallback(response) {
         // called asynchronously if an error occurs
         // or server returns response with an error status.
         alert("Error : " + response.data.ExceptionMessage);
});

and then you can get this object in your controller

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public [OBJECT] PostGenericObjects(object obj)
    {
        string[] str = GeneralMethods.UnWrapObjects(obj);
        var item1 = JsonConvert.DeserializeObject<ObjectType1>(str[0]);
        var item2 = JsonConvert.DeserializeObject<ObjectType2>(str[1]);

        return *something*;
    } 

I have made a generic function to unwrap the complex object, so there is no limitation of number of objects while sending and unwrapping. We can even send more than two objects

public class GeneralMethods
{
    public static string[] UnWrapObjects(object obj)
    {
        JObject o = JObject.Parse(obj.ToString());

        string[] str = new string[o.Count];

        for (int i = 0; i < o.Count; i++)
        {
            string var = "obj" + (i + 1).ToString();
            str[i] = o[var].ToString(); 
        }

        return str;
    }

}

I have posted the solution to my blog with a little more description with simpler code to integrate easily.

Pass multiple complex objects to Web API

I hope it would help someone. I would be interested to hear from the experts here regarding the pros and cons of using this methodology.

Going to a specific line number using Less in Unix

For editing this is possible in nano via +n from command line, e.g.,

nano +16 file.txt

To open file.txt to line 16.

Add animated Gif image in Iphone UIImageView

With Swift and KingFisher

   lazy var animatedPart: AnimatedImageView = {
        let img = AnimatedImageView()
        if let src = Bundle.main.url(forResource: "xx", withExtension: "gif"){
            img.kf.setImage(with: src)
        }
        return img
   }()

Set type for function parameters?

Check out the new Flow library from Facebook, "a static type checker, designed to find type errors in JavaScript programs"

Definition:

/* @flow */
function foo(x: string, y: number): string {
  return x.length * y;
}
foo('Hello', 42);

Type checking:

$> flow
hello.js:3:10,21: number
This type is incompatible with
  hello.js:2:37,42: string

And here is how to run it.

Pandas read in table without headers

In order to read a csv in that doesn't have a header and for only certain columns you need to pass params header=None and usecols=[3,6] for the 4th and 7th columns:

df = pd.read_csv(file_path, header=None, usecols=[3,6])

See the docs

How to run function in AngularJS controller on document ready?

$scope.$on('$ViewData', function(event) {
//Your code.
});

How do I set the background color of my main screen in Flutter?

There are many ways of doing it, I am listing few here.

  1. Using backgroundColor

    Scaffold(
      backgroundColor: Colors.black,
      body: Center(...),
    )
    
  2. Using Container in SizedBox.expand

    Scaffold(
      body: SizedBox.expand(
        child: Container(
          color: Colors.black,
          child: Center(...)
        ),
      ),
    )
    
  3. Using Theme

    Theme(
      data: Theme.of(context).copyWith(scaffoldBackgroundColor: Colors.black),
      child: Scaffold(
        body: Center(...),
      ),
    )
    

How to monitor network calls made from iOS Simulator

A free and open source proxy tool that runs easily on a Mac is mitmproxy.

The website includes links to a Mac binary, as well as the source code on Github.

The docs contain a very helpful intro to loading a cert into your test device to view HTTPS traffic.

Not quite as GUI-tastic as Charles, but it does everything I need and its free and maintained. Good stuff, and pretty straightforward if you've used some command line tools before.

UPDATE: I just noticed on the website that mitmproxy is available as a homebrew install. Couldn't be easier.

CSS white space at bottom of page despite having both min-height and height tag

I faced this issue because my web page was zoomed out to 90% and as I was viewing my page in responsive mode through the browser developer tools, I did not notice it right away.

How to free memory in Java?

I have done experimentation on this.

It's true that System.gc(); only suggests to run the Garbage Collector.

But calling System.gc(); after setting all references to null, will improve performance and memory occupation.

javascript date + 7 days

Using the Date object's methods will could come in handy.

e.g.:

myDate = new Date();
plusSeven = new Date(myDate.setDate(myDate.getDate() + 7));

How do I convert from BLOB to TEXT in MySQL?

That's unnecessary. Just use SELECT CONVERT(column USING utf8) FROM..... instead of just SELECT column FROM...

Why in C++ do we use DWORD rather than unsigned int?

DWORD is not a C++ type, it's defined in <windows.h>.

The reason is that DWORD has a specific range and format Windows functions rely on, so if you require that specific range use that type. (Or as they say "When in Rome, do as the Romans do.") For you, that happens to correspond to unsigned int, but that might not always be the case. To be safe, use DWORD when a DWORD is expected, regardless of what it may actually be.

For example, if they ever changed the range or format of unsigned int they could use a different type to underly DWORD to keep the same requirements, and all code using DWORD would be none-the-wiser. (Likewise, they could decide DWORD needs to be unsigned long long, change it, and all code using DWORD would be none-the-wiser.)


Also note unsigned int does not necessary have the range 0 to 4,294,967,295. See here.

Parse JSON String into a Particular Object Prototype in JavaScript

A blog post that I found useful: Understanding JavaScript Prototypes

You can mess with the __proto__ property of the Object.

var fooJSON = jQuery.parseJSON({"a":4, "b": 3});
fooJSON.__proto__ = Foo.prototype;

This allows fooJSON to inherit the Foo prototype.

I don't think this works in IE, though... at least from what I've read.

How to dynamically add a class to manual class names?

getBadgeClasses() {
    let classes = "badge m-2 ";
    classes += (this.state.count === 0) ? "badge-warning" : "badge-primary";
    return classes;
}

<span className={this.getBadgeClasses()}>Total Count</span>

How to clear gradle cache?

UPDATE

cleanBuildCache no longer works.

Android Gradle plugin now utilizes Gradle cache feature
https://guides.gradle.org/using-build-cache/

TO CLEAR CACHE

Clean the cache directory to avoid any hits from previous builds

 rm -rf $GRADLE_HOME/caches/build-cache-*

https://guides.gradle.org/using-build-cache/#caching_android_projects

Other digressions: see here (including edits).


=== OBSOLETE INFO ===

Newest solution using Gradle task:

cleanBuildCache

Available via Android plugin for Gradle, revision 2.3.0 (February 2017)

Dependencies:

  1. Gradle 3.3 or higher.
  2. Build Tools 25.0.0 or higher.

More info at:
https://developer.android.com/studio/build/build-cache.html#clear_the_build_cache

Background

Build cache
Stores certain outputs that the Android plugin generates when building your project (such as unpackaged AARs and pre-dexed remote dependencies). Your clean builds are much faster while using the cache because the build system can simply reuse those cached files during subsequent builds, instead of recreating them. Projects using Android plugin 2.3.0 and higher use the build cache by default. To learn more, read Improve Build Speed with Build Cache.

NOTE: The cleanBuildCache task is not available if you disable the build cache.


USAGE

Windows:

gradlew cleanBuildCache

Linux / Mac:

gradle cleanBuildCache

Android Studio / IntelliJ:

gradle tab (default on right) select and run the task or add it via the configuration window 

NOTE: gradle / gradlew are system specific files containing scripts. Please see the related system info how to execute the scripts:

What is the meaning of "POSIX"?

This standard provides a common basis for Unix-like operating systems. It specifies how the shell should work, what to expect from commands like ls and grep, and a number of C libraries that C authors can expect to have available.

For example, the pipes that command-line users use to string together commands are specified in detail here, which means C’s popen (pipe open) function is POSIX-standard, not ISO C-standard.

Find empty or NaN entry in Pandas Dataframe

Partial solution: for a single string column tmp = df['A1'].fillna(''); isEmpty = tmp=='' gives boolean Series of True where there are empty strings or NaN values.

Delete a closed pull request from GitHub

There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.

However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.

Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]

UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact

Handling 'Sequence has no elements' Exception

I had the same issue, i realized i had deleted the default image that was in the folder just update the media missing, on the specific file

How can I convert the "arguments" object to an array in JavaScript?

Try using Object.setPrototypeOf()

Explanation: Set prototype of arguments to Array.prototype

_x000D_
_x000D_
function toArray() {_x000D_
  return Object.setPrototypeOf(arguments, Array.prototype)_x000D_
} _x000D_
_x000D_
console.log(toArray("abc", 123, {def:456}, [0,[7,[14]]]))
_x000D_
_x000D_
_x000D_


Explanation: Take each index of arguments , place item into an array at corresponding index of array.

could alternatively use Array.prototype.map()

_x000D_
_x000D_
function toArray() {_x000D_
  return [].map.call(arguments, (_,k,a) => a[k])_x000D_
} _x000D_
_x000D_
console.log(toArray("abc", 123, {def:456}, [0,[7,[14]]]))
_x000D_
_x000D_
_x000D_


Explanation: Take each index of arguments , place item into an array at corresponding index of array.

for..of loop

_x000D_
_x000D_
function toArray() {_x000D_
 let arr = []; for (let prop of arguments) arr.push(prop); return arr_x000D_
} _x000D_
_x000D_
console.log(toArray("abc", 123, {def:456}, [0,[7,[14]]]))
_x000D_
_x000D_
_x000D_


or Object.create()

Explanation: Create object, set properties of object to items at each index of arguments; set prototype of created object to Array.prototype

_x000D_
_x000D_
function toArray() {_x000D_
  var obj = {};_x000D_
  for (var prop in arguments) {_x000D_
    obj[prop] = {_x000D_
      value: arguments[prop],_x000D_
      writable: true,_x000D_
      enumerable: true,_x000D_
      configurable: true_x000D_
    }_x000D_
  } _x000D_
  return Object.create(Array.prototype, obj);_x000D_
}_x000D_
_x000D_
console.log(toArray("abc", 123, {def: 456}, [0, [7, [14]]]))
_x000D_
_x000D_
_x000D_

How can a file be copied?

You could use os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')

or as I did it,

os.system('cp '+ rawfile + ' rawdata.dat')

where rawfile is the name that I had generated inside the program.

This is a Linux only solution

Log4Net configuring log level

Use threshold.

For example:

   <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <threshold value="WARN"/>
        <param name="File" value="File.log" />
        <param name="AppendToFile" value="true" />
        <param name="RollingStyle" value="Size" />
        <param name="MaxSizeRollBackups" value="10" />
        <param name="MaximumFileSize" value="1024KB" />
        <param name="StaticLogFileName" value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <param name="Header" value="[Server startup]&#13;&#10;" />
            <param name="Footer" value="[Server shutdown]&#13;&#10;" />
            <param name="ConversionPattern" value="%d %m%n" />
        </layout>
    </appender>
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
        <threshold value="ERROR"/>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread]- %message%newline" />
        </layout>
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <threshold value="INFO"/>
        <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d [%thread] %m%n" />
        </layout>
    </appender>

In this example all INFO and above are sent to Console, all WARN are sent to file and ERRORs are sent to the Event-Log.

What is a good Hash Function?

What you're saying here is you want to have one that uses has collision resistance. Try using SHA-2. Or try using a (good) block cipher in a one way compression function (never tried that before), like AES in Miyaguchi-Preenel mode. The problem with that is that you need to:

1) have an IV. Try using the first 256 bits of the fractional parts of Khinchin's constant or something like that. 2) have a padding scheme. Easy. Barrow it from a hash like MD5 or SHA-3 (Keccak [pronounced 'ket-chak']). If you don't care about the security (a few others said this), look at FNV or lookup2 by Bob Jenkins (actually I'm the first one who reccomends lookup2) Also try MurmurHash, it's fast (check this: .16 cpb).

Reset IntelliJ UI to Default

On Mac OS for IntelliJ v12, shut down the IDE, and then you can execute:

rm -rf ~/Library/Preferences/IdeaIC12/*

Restart the IDE, or open a pom.xml of your choosing. You will be asked whether you want to import the preferences from an existing IntelliJ instance. Select the "No, I do not have a previous IntelliJ version" radio button.

Get the current user, within an ApiController action, without passing the userID as a parameter

In WebApi 2 you can use RequestContext.Principal from within a method on ApiController

Detect when input has a 'readonly' attribute

Check the current value of your "readonly" attribute, if it's "false" (a string) or empty (undefined or "") then it's not readonly.

$('input').each(function() {
    var readonly = $(this).attr("readonly");
    if(readonly && readonly.toLowerCase()!=='false') { // this is readonly
        alert('this is a read only field');
    }
});

How to import Angular Material in project?

UPDATE for Angular 9.0.1

Since this version there is no barrel file for massive exports in the root index.d.ts. The assets imports should be:

import { NgModule } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule} from '@angular/material/button';
import { MatMenuModule } from '@angular/material/menu';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatIconModule } from '@angular/material/icon';

import {
  MatButtonModule,
  MatMenuModule,
  MatToolbarModule,
  MatIconModule,
  MatCardModule
} from '@angular/material';

@NgModule({
  imports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ],
  exports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ]
})
export class MaterialModule {}

source: @angular/material/index.d.ts' is not a module


MaterialModule was depreciated in version 2.0.0-beta.3 and it has been removed completely in version 2.0.0-beta.11. See this CHANGELOG for more details. Please go through the breaking changes.

Breaking changes

  • Angular Material now requires Angular 4.4.3 or greater
  • MaterialModule has been removed.
  • For beta.11, we've made the decision to deprecate the "md" prefix completely and use "mat" moving forward.

Please go through CHANGELOG we will get more answer!

Example shown below cmd

npm install --save @angular/material @angular/animations @angular/cdk
npm install --save angular/material2-builds angular/cdk-builds

Create file (material.module.ts) inside the 'app' folder

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

import {
  MatButtonModule,
  MatMenuModule,
  MatToolbarModule,
  MatIconModule,
  MatCardModule
} from '@angular/material';

@NgModule({
  imports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ],
  exports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ]
})
export class MaterialModule {}

import on app.module.ts

import { MaterialModule } from './material.module';

Your component html file

<div>
  <mat-toolbar color="primary">
    <span><mat-icon>mood</mat-icon></span>

    <span>Yay, Material in Angular 2!</span>

    <button mat-icon-button [mat-menu-trigger-for]="menu">
      <mat-icon>more_vert</mat-icon>
    </button>
  </mat-toolbar>
  <mat-menu x-position="before" #menu="matMenu">
    <button mat-menu-item>Option 1</button>
    <button mat-menu-item>Option 2</button>
  </mat-menu>

  <mat-card>
    <button mat-button>All</button>
    <button mat-raised-button>Of</button>
    <button mat-raised-button color="primary">The</button>
    <button mat-raised-button color="accent">Buttons</button>
  </mat-card>

  <span class="done">
    <button mat-fab>
      <mat-icon>check circle</mat-icon>
    </button>
  </span>
</div>

Add global css 'style.css'

@import 'https://fonts.googleapis.com/icon?family=Material+Icons';
@import '~@angular/material/prebuilt-themes/indigo-pink.css'; 

Your component css

body {
  margin: 0;
  font-family: Roboto, sans-serif;
}

mat-card {
  max-width: 80%;
  margin: 2em auto;
  text-align: center;
}

mat-toolbar-row {
  justify-content: space-between;
}

.done {
  position: fixed;
  bottom: 20px;
  right: 20px;
  color: white;
}

If any one didn't get output use below instruction

instead of above interface (material.module.ts) u can directly use below code also in the app.module.ts.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MdButtonModule, MdCardModule, MdMenuModule, MdToolbarModule, MdIconModule, MatAutocompleteModule, MatInputModule,MatFormFieldModule } from '@angular/material';

So this case u don't want to import

import { MaterialModule } from './material.module';

in the app.module.ts

How do I alter the precision of a decimal column in Sql Server?

ALTER TABLE `tableName` CHANGE  `columnName` DECIMAL(16,1) NOT NULL;

I uses This for the alterration

How to handle an IF STATEMENT in a Mustache template?

I have a simple and generic hack to perform key/value if statement instead of boolean-only in mustache (and in an extremely readable fashion!) :

function buildOptions (object) {
    var validTypes = ['string', 'number', 'boolean'];
    var value;
    var key;
    for (key in object) {
        value = object[key];
        if (object.hasOwnProperty(key) && validTypes.indexOf(typeof value) !== -1) {
            object[key + '=' + value] = true;
        }
    }
    return object;
}

With this hack, an object like this:

var contact = {
  "id": 1364,
  "author_name": "Mr Nobody",
  "notified_type": "friendship",
  "action": "create"
};

Will look like this before transformation:

var contact = {
  "id": 1364,
  "id=1364": true,
  "author_name": "Mr Nobody",
  "author_name=Mr Nobody": true,
  "notified_type": "friendship",
  "notified_type=friendship": true,
  "action": "create",
  "action=create": true
};

And your mustache template will look like this:

{{#notified_type=friendship}}
    friendship…
{{/notified_type=friendship}}

{{#notified_type=invite}}
    invite…
{{/notified_type=invite}}

How to loop through elements of forms with JavaScript?

You can iterate named fields somehow like this:

let jsonObject = {};
for(let field of form.elements) {
  if (field.name) {
      jsonObject[field.name] = field.value;
  }
}

Or, if you need only submiting fields:

function formDataToJSON(form) {
  let jsonObject = {};
  let formData = new FormData(form);
  for(let field of formData) {
      jsonObject[field[0]] = field[1];
  }
  return JSON.stringify(jsonObject);
}

How to import a new font into a project - Angular 5

You need to put the font files in assets folder (may be a fonts sub-folder within assets) and refer to it in the styles:

@font-face {
  font-family: lato;
  src: url(assets/font/Lato.otf) format("opentype");
}

Once done, you can apply this font any where like:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'lato', 'arial', sans-serif;
}

You can put the @font-face definition in your global styles.css or styles.scss and you would be able to refer to the font anywhere - even in your component specific CSS/SCSS. styles.css or styles.scss is already defined in angular-cli.json. Or, if you want you can create a separate CSS/SCSS file and declare it in angular-cli.json along with the styles.css or styles.scss like:

"styles": [
  "styles.css",
  "fonts.css"
],

MySQL pivot table query with dynamic columns

The only way in MySQL to do this dynamically is with Prepared statements. Here is a good article about them:

Dynamic pivot tables (transform rows to columns)

Your code would look like this:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(pa.fieldname = ''',
      fieldname,
      ''', pa.fieldvalue, NULL)) AS ',
      fieldname
    )
  ) INTO @sql
FROM product_additional;

SET @sql = CONCAT('SELECT p.id
                    , p.name
                    , p.description, ', @sql, ' 
                   FROM product p
                   LEFT JOIN product_additional AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

See Demo

NOTE: GROUP_CONCAT function has a limit of 1024 characters. See parameter group_concat_max_len

Getting a directory name from a filename

Just use this: ExtractFilePath(your_path_file_name)

cannot find module "lodash"

Maybe loadash needs to be installed. Usually these things are handled by the package manager. On your command line:

npm install lodash 

or maybe it needs to be globally installed

npm install -g lodash

remove attribute display:none; so the item will be visible

The removeAttr() function only removes HTML attributes. The display is not a HTML attribute, it's a CSS property. You'd like to use css() function instead to manage CSS properties.

But jQuery offers a show() function which does exactly what you want in a concise call:

$("span").show();

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

you should be using the .Value of the datetime parameter. All Nullable structs have a value property which returns the concrete type of the object. but you must check to see if it is null beforehand otherwise you will get a runtime error.

i.e:

datetime.Value

but check to see if it has a value first!

if (datetime.HasValue)
{
   // work with datetime.Value
}

Looping over elements in jQuery

Depending on what you need each child for (if you're looking to post it somewhere via AJAX) you can just do...

$("#formID").serialize()

It creates a string for you with all of the values automatically.

As for looping through objects, you can also do this.

$.each($("input, select, textarea"), function(i,v) {
    var theTag = v.tagName;
    var theElement = $(v);
    var theValue = theElement.val();
});

How do I import/include MATLAB functions?

If the folder just contains functions then adding the folders to the path at the start of the script will suffice.

addpath('../folder_x/');
addpath('../folder_y/');

If they are Packages, folders starting with a '+' then they also need to be imported.

import package_x.*
import package_y.*

You need to add the package folders parent to the search path.

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

For a Node.js app, in the server.js file before registering all of my own routes, I put the code below. It sets the headers for all responses. It also ends the response gracefully if it is a pre-flight "OPTIONS" call and immediately sends the pre-flight response back to the client without "nexting" (is that a word?) down through the actual business logic routes. Here is my server.js file. Relevant sections highlighted for Stackoverflow use.

// server.js

// ==================
// BASE SETUP

// import the packages we need
var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var morgan     = require('morgan');
var jwt        = require('jsonwebtoken'); // used to create, sign, and verify tokens

// ====================================================
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Logger
app.use(morgan('dev'));

// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------

//Set CORS header and intercept "OPTIONS" preflight call from AngularJS
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    if (req.method === "OPTIONS") 
        res.send(200);
    else 
        next();
}

// -------------------------------------------------------------
// STACKOVERFLOW -- END OF THIS SECTION, ONE MORE SECTION BELOW
// -------------------------------------------------------------


// =================================================
// ROUTES FOR OUR API

var route1 = require("./routes/route1");
var route2 = require("./routes/route2");
var error404 = require("./routes/error404");


// ======================================================
// REGISTER OUR ROUTES with app

// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------

app.use(allowCrossDomain);

// -------------------------------------------------------------
//  STACKOVERFLOW -- OK THAT IS THE LAST THING.
// -------------------------------------------------------------

app.use("/api/v1/route1/", route1);
app.use("/api/v1/route2/", route2);
app.use('/', error404);

// =================
// START THE SERVER

var port = process.env.PORT || 8080;        // set our port
app.listen(port);
console.log('API Active on port ' + port);

PostgreSQL Error: Relation already exists

There should be no single quotes here 'A'. Single quotes are for string literals: 'some value'.
Either use double quotes to preserve the upper case spelling of "A":

CREATE TABLE "A" ...

Or don't use quotes at all:

CREATE TABLE A ...

which is identical to

CREATE TABLE a ...

because all unquoted identifiers are folded to lower case automatically in PostgreSQL.


You could avoid problems with the index name completely by using simpler syntax:

CREATE TABLE csd_relationship (
    csd_relationship_id serial PRIMARY KEY,
    type_id integer NOT NULL,
    object_id integer NOT NULL
);

Does the same as your original query, only it avoids naming conflicts automatically. It picks the next free identifier automatically. More about the serial type in the manual.

Copy all values from fields in one class to another through reflection

If you don't mind using a third party library, BeanUtils from Apache Commons will handle this quite easily, using copyProperties(Object, Object).

Select distinct using linq

myList.GroupBy(test => test.id)
      .Select(grp => grp.First());

Edit: as getting this IEnumerable<> into a List<> seems to be a mystery to many people, you can simply write:

var result = myList.GroupBy(test => test.id)
                   .Select(grp => grp.First())
                   .ToList();

But one is often better off working with the IEnumerable rather than IList as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)

The flipside to this advice is that each time you enumerate such an IEnumerable the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable or to realize it into a List, Set, Dictionary or whatnot.

Defining an abstract class without any abstract methods

Actually there is no mean if an abstract class doesnt have any abstract method . An abstract class is like a father. This father have some properties and behaviors,when you as a child want to be a child of the father, father says the child(you)that must be this way, its our MOTO, and if you don`t want to do, you are not my child.

Load CSV data into MySQL in Python

If it is a pandas data frame you could do:

Sending the data

csv_data.to_sql=(con=mydb, name='<the name of your table>',
  if_exists='replace', flavor='mysql')

to avoid the use of the for.

fatal: does not appear to be a git repository

I have a similar problem, but now I know the reason.

After we use git init, we should add a remote repository using

git remote add name url

Pay attention to the word name, if we change it to origin, then this problem will not happen.

Of course, if we change it to py, then using git pull py branch and git push py branch every time you pull and push something will also be OK.

When should I use h:outputLink instead of h:commandLink?

I also see that the page loading (performance) takes a long time on using h:commandLink than h:link. h:link is faster compared to h:commandLink

C# RSA encryption/decryption with transmission

well there are really enough examples for this, but anyway, here you go

using System;
using System.Security.Cryptography;

namespace RsaCryptoExample
{
  static class Program
  {
    static void Main()
    {
      //lets take a new CSP with a new 2048 bit rsa key pair
      var csp = new RSACryptoServiceProvider(2048);

      //how to get the private key
      var privKey = csp.ExportParameters(true);

      //and the public key ...
      var pubKey = csp.ExportParameters(false);

      //converting the public key into a string representation
      string pubKeyString;
      {
        //we need some buffer
        var sw = new System.IO.StringWriter();
        //we need a serializer
        var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
        //serialize the key into the stream
        xs.Serialize(sw, pubKey);
        //get the string from the stream
        pubKeyString = sw.ToString();
      }

      //converting it back
      {
        //get a stream from the string
        var sr = new System.IO.StringReader(pubKeyString);
        //we need a deserializer
        var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
        //get the object back from the stream
        pubKey = (RSAParameters)xs.Deserialize(sr);
      }

      //conversion for the private key is no black magic either ... omitted

      //we have a public key ... let's get a new csp and load that key
      csp = new RSACryptoServiceProvider();
      csp.ImportParameters(pubKey);

      //we need some data to encrypt
      var plainTextData = "foobar";

      //for encryption, always handle bytes...
      var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(plainTextData);

      //apply pkcs#1.5 padding and encrypt our data 
      var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);

      //we might want a string representation of our cypher text... base64 will do
      var cypherText = Convert.ToBase64String(bytesCypherText);


      /*
       * some transmission / storage / retrieval
       * 
       * and we want to decrypt our cypherText
       */

      //first, get our bytes back from the base64 string ...
      bytesCypherText = Convert.FromBase64String(cypherText);

      //we want to decrypt, therefore we need a csp and load our private key
      csp = new RSACryptoServiceProvider();
      csp.ImportParameters(privKey);

      //decrypt and strip pkcs#1.5 padding
      bytesPlainTextData = csp.Decrypt(bytesCypherText, false);

      //get our original plainText back...
      plainTextData = System.Text.Encoding.Unicode.GetString(bytesPlainTextData);
    }
  }
}

as a side note: the calls to Encrypt() and Decrypt() have a bool parameter that switches between OAEP and PKCS#1.5 padding ... you might want to choose OAEP if it's available in your situation

How can I read large text files in Python, line by line, without loading it into memory?

This might be useful when you want to work in parallel and read only chunks of data but keep it clean with new lines.

def readInChunks(fileObj, chunkSize=1024):
    while True:
        data = fileObj.read(chunkSize)
        if not data:
            break
        while data[-1:] != '\n':
            data+=fileObj.read(1)
        yield data

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

I, too, have need for this! My situation involves comparing actuals with budget for cost centers, where expenses may have been mis-applied and therefore need to be re-allocated to the correct cost center so as to match how they were budgeted. It is very time consuming to try and scan row-by-row to see if each expense item has been correctly allocated. I decided that I should apply conditional formatting to highlight any cells where the actuals did not match the budget. I set up the conditional formatting to change the background color if the actual amount under the cost center did not match the budgeted amount.

Here's what I did:

Start in cell A1 (or the first cell you want to have the formatting). Open the Conditional Formatting dialogue box and select Apply formatting based on a formula. Then, I wrote a formula to compare one cell to another to see if they match:

=A1=A50

If the contents of cells A1 and A50 are equal, the conditional formatting will be applied. NOTICE: no $$, so the cell references are RELATIVE! Therefore, you can copy the formula from cell A1 and PasteSpecial (format). If you only click on the cells that you reference as you write your conditional formatting formula, the cells are by default locked, so then you wouldn't be able to apply them anywhere else (you would have to write out a new rule for each line- YUK!)

What is really cool about this is that if you insert rows under the conditionally formatted cell, the conditional formatting will be applied to the inserted rows as well!

Something else you could also do with this: Use ISBLANK if the amounts are not going to be exact matches, but you want to see if there are expenses showing up in columns where there are no budgeted amounts (i.e., BLANK) .

This has been a real time-saver for me. Give it a try and enjoy!

XPath OR operator for different nodes

If you want to select only one of two nodes with union operator, you can use this solution: (//bookstore/book/title | //bookstore/city/zipcode/title)[1]

JavaScript query string

Building on the answer by @CMS I have the following (in CoffeeScript which can easily be converted to JavaScript):

String::to_query = ->
  [result, re, d] = [{}, /([^&=]+)=([^&]*)/g, decodeURIComponent]
  while match = re.exec(if @.match /^\?/ then @.substring(1) else @)
    result[d(match[1])] = d match[2] 
  result

You can easily grab what you need with:

location.search.to_query()['my_param']

The win here is an object-oriented interface (instead of functional) and it can be done on any string (not just location.search).

If you are already using a JavaScript library this function make already exist. For example here is Prototype's version

What does the restrict keyword mean in C++?

Nothing. It was added to the C99 standard.

'npm' is not recognized as internal or external command, operable program or batch file

I installed nodejs following this AngularJS tutorial. the npm command did work when I open a new cmd window but not in the current one.
So the fix was to close and open a new cmd window.

Asp.net Hyperlink control equivalent to <a href="#"></a>

I agree with SLaks, but here you go

   <asp:HyperLink id="hyperlink1" 
                  NavigateUrl="#"
                  Text=""
                  runat="server"/> 

or you can alter the href using

hyperlink1.NavigateUrl = "#"; 
hyperlink1.Text = string.empty;

Getting cursor position in Python

sudo add-apt-repository ppa:deadsnakes
sudo apt-get update
sudo apt-get install python3.5 python3.5-tk
# or 2.7, 3.6 etc
# sudo apt-get install python2.7 python2.7-tk
# mouse_position.py
import Tkinter
p=Tkinter.Tk()
print(p.winfo_pointerxy()

Or with one-liner from the command line:

python -c "import Tkinter; p=Tkinter.Tk(); print(p.winfo_pointerxy())"
(1377, 379)

How can I list all commits that changed a specific file?

The --follow works for a particular file

git log --follow -- filename

Difference to other solutions given

Note that other solutions include git log path (without the --follow). That approach is handy if you want to track e.g. changes in a directory, but stumbles when files were renamed (thus use --follow filename).

Using ng-if as a switch inside ng-repeat?

I will suggest move all templates to separate files, and don't do spagetti inside repeat

take a look here:

html:

<div ng-repeat = "data in comments">
    <div ng-include src="buildUrl(data.type)"></div>
 </div>

js:

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {

  $scope.comments = [
    {"_id":"52fb84fac6b93c152d8b4569",
       "post_id":"52fb84fac6b93c152d8b4567",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"hoot"},  
    {"_id":"52fb798cc6b93c74298b4568",
       "post_id":"52fb798cc6b93c74298b4567",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"story"},        
    {"_id":"52fb7977c6b93c5c2c8b456b",
       "post_id":"52fb7977c6b93c5c2c8b456a",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"article"}
  ];

  $scope.buildUrl = function(type) {
    return type + '.html';
  }
});

http://plnkr.co/edit/HxnirSvMHNQ748M2WeRt?p=preview

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

Column values from the SELECT statement are assigned into @low and @day local variables; the @adjustedLow value is not assigned into any variable and it causes the problem:

The problem is here:

select 
    top 1 @low = low
    , @day = day
    , @adjustedLow  -- causes error!
--select high
from 
    securityquote sq
...

Detailed explanation and workaround: SQL Server Error Messages - Msg 141 - A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.

Activity has leaked window that was originally added

You can get this exception by just a simple/dumb mistake, by (for example) accidentally calling finish() after having displayed an AlertDialog, if you miss a break call statement in a switch statement...

   @Override
   public void onClick(View v) {
    switch (v.getId()) {
        case R.id.new_button:
            openMyAlertDialog();
            break; <-- If you forget this the finish() method below 
                       will be called while the dialog is showing!
        case R.id.exit_button:
            finish();
            break;
        }
    }

The finish() method will close the Activity, but the AlertDialog is still displaying!

So when you're staring intently at the code, looking for bad threading issues or complex coding and such, don't lose sight of the forest for the trees. Sometimes it can be just something as simple and dumb as a missing break statement. :)

Better way to represent array in java properties file

I highly recommend using Apache Commons (http://commons.apache.org/configuration/). It has the ability to use an XML file as a configuration file. Using an XML structure makes it easy to represent arrays as lists of values rather than specially numbered properties.

How do I export a project in the Android studio?

1.- Export signed packages:

  • Use the Extract a Signed Android Application Package Wizard (On the main menu, choose Build | Generate Signed APK). The package will be signed during extraction.

    OR

  • Configure the .apk file as an artifact by creating an artifact definition of the type Android application with the Release signed package mode.

2.- Export unsigned packages: this can only be done through artifact definitions with the Debug or Release unsigned package mode specified.

How do I scroll to an element using JavaScript?

To scroll to a given element, just made this javascript only solution below.

Simple usage:

EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);

Engine object (you can fiddle with filter, fps values):

/**
 *
 * Created by Borbás Geri on 12/17/13
 * Copyright (c) 2013 eppz! development, LLC.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */


var EPPZScrollTo =
{
    /**
     * Helpers.
     */
    documentVerticalScrollPosition: function()
    {
        if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari.
        if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode).
        if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8.
        return 0; // None of the above.
    },

    viewportHeight: function()
    { return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; },

    documentHeight: function()
    { return (document.height !== undefined) ? document.height : document.body.offsetHeight; },

    documentMaximumScrollPosition: function()
    { return this.documentHeight() - this.viewportHeight(); },

    elementVerticalClientPositionById: function(id)
    {
        var element = document.getElementById(id);
        var rectangle = element.getBoundingClientRect();
        return rectangle.top;
    },

    /**
     * Animation tick.
     */
    scrollVerticalTickToPosition: function(currentPosition, targetPosition)
    {
        var filter = 0.2;
        var fps = 60;
        var difference = parseFloat(targetPosition) - parseFloat(currentPosition);

        // Snap, then stop if arrived.
        var arrived = (Math.abs(difference) <= 0.5);
        if (arrived)
        {
            // Apply target.
            scrollTo(0.0, targetPosition);
            return;
        }

        // Filtered position.
        currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter);

        // Apply target.
        scrollTo(0.0, Math.round(currentPosition));

        // Schedule next tick.
        setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps));
    },

    /**
     * For public use.
     *
     * @param id The id of the element to scroll to.
     * @param padding Top padding to apply above element.
     */
    scrollVerticalToElementById: function(id, padding)
    {
        var element = document.getElementById(id);
        if (element == null)
        {
            console.warn('Cannot find element with id \''+id+'\'.');
            return;
        }

        var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding;
        var currentPosition = this.documentVerticalScrollPosition();

        // Clamp.
        var maximumScrollPosition = this.documentMaximumScrollPosition();
        if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition;

        // Start animation.
        this.scrollVerticalTickToPosition(currentPosition, targetPosition);
    }
};

JavaScript push to array

var array = new Array(); // or the shortcut: = []
array.push ( {"cool":"34.33","also cool":"45454"} );
array.push (  {"cool":"34.39","also cool":"45459"} );

Your variable is a javascript object {} not an array [].

You could do:

var o = {}; // or the longer form: = new Object()
o.SomeNewProperty = "something";
o["SomeNewProperty"] = "something";

and

var o = { SomeNewProperty: "something" };
var o2 = { "SomeNewProperty": "something" };

Later, you add those objects to your array: array.push (o, o2);

Also JSON is simply a string representation of a javascript object, thus:

var json = '{"cool":"34.33","alsocool":"45454"}'; // is JSON
var o = JSON.parse(json); // is a javascript object
json = JSON.stringify(o); // is JSON again

Get decimal portion of a number with JavaScript

A simple way of doing it is:

_x000D_
_x000D_
var x = 3.2;_x000D_
var decimals = x - Math.floor(x);_x000D_
console.log(decimals); //Returns 0.20000000000000018
_x000D_
_x000D_
_x000D_

Unfortunately, that doesn't return the exact value. However, that is easily fixed:

_x000D_
_x000D_
var x = 3.2;_x000D_
var decimals = x - Math.floor(x);_x000D_
console.log(decimals.toFixed(1)); //Returns 0.2
_x000D_
_x000D_
_x000D_

You can use this if you don't know the number of decimal places:

_x000D_
_x000D_
var x = 3.2;_x000D_
var decimals = x - Math.floor(x);_x000D_
_x000D_
var decimalPlaces = x.toString().split('.')[1].length;_x000D_
decimals = decimals.toFixed(decimalPlaces);_x000D_
_x000D_
console.log(decimals); //Returns 0.2
_x000D_
_x000D_
_x000D_

Reading NFC Tags with iPhone 6 / iOS 8

The only information currently available is that Apple Pay will be available in ios8, but that doesn't shed any light on whether RFID tags or rather NFC tags specifically will be able to be detected/read.

IMO it would be a shortsighted move not to allow that possibility, but really the money is in Apple Pay, not necessarily in allowing developers access to those features - we've seen it before with tethering, Bluetooth SPP, and diminished access to certain functions.

...but then again, it's been about 5 hours since the first announcement.

Passing data between view controllers

Swift

There are tons and tons of explanations here and around Stack Overflow, but if you are a beginner just trying to get something basic to work, try watching this YouTube tutorial (It's what helped me to finally understand how to do it).

Passing data forward to the next View Controller

The following is an example based on the video. The idea is to pass a string from the text field in the First View Controller to the label in the Second View Controller.

Enter image description here

Create the storyboard layout in the Interface Builder. To make the segue, you just Control click on the button and drag over to the Second View Controller.

First View Controller

The code for the First View Controller is

import UIKit

class FirstViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    // This function is called before the segue
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get a reference to the second view controller
        let secondViewController = segue.destination as! SecondViewController

        // Set a variable in the second view controller with the String to pass
        secondViewController.receivedString = textField.text!
    }

}

Second View Controller

And the code for the Second View Controller is

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    // This variable will hold the data being passed from the First View Controller
    var receivedString = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // Used the text from the First View Controller to set the label
        label.text = receivedString
    }

}

Don't forget

  • Hook up the outlets for the UITextField and the UILabel.
  • Set the first and second View Controllers to the appropriate Swift files in Interface Builder.

Passing data back to the previous View Controller

To pass data back from the second view controller to the first view controller, you use a protocol and a delegate. This video is a very clear walk though of that process:

The following is an example based on the video (with a few modifications).

Enter image description here

Create the storyboard layout in the Interface Builder. Again, to make the segue, you just Control drag from the button to the Second View Controller. Set the segue identifier to showSecondViewController. Also, don't forget to hook up the outlets and actions using the names in the following code.

First View Controller

The code for the First View Controller is

import UIKit

class FirstViewController: UIViewController, DataEnteredDelegate {

    @IBOutlet weak var label: UILabel!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showSecondViewController" {
            let secondViewController = segue.destination as! SecondViewController
            secondViewController.delegate = self
        }
    }

    func userDidEnterInformation(info: String) {
        label.text = info
    }
}

Note the use of our custom DataEnteredDelegate protocol.

Second View Controller and Protocol

The code for the second view controller is

import UIKit

// Protocol used for sending data back
protocol DataEnteredDelegate: AnyObject {
    func userDidEnterInformation(info: String)
}

class SecondViewController: UIViewController {

    // Making this a weak variable, so that it won't create a strong reference cycle
    weak var delegate: DataEnteredDelegate? = nil

    @IBOutlet weak var textField: UITextField!

    @IBAction func sendTextBackButton(sender: AnyObject) {

        // Call this method on whichever class implements our delegate protocol
        delegate?.userDidEnterInformation(info: textField.text!)

        // Go back to the previous view controller
        _ = self.navigationController?.popViewController(animated: true)
    }
}

Note that the protocol is outside of the View Controller class.

That's it. Running the app now, you should be able to send data back from the second view controller to the first.

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

Spring schemaLocation fails when there is no internet connection

If there is no internet connection in your platform and you use Eclipse, follow these steps (it solves my problem)

  1. Find the exact xsd files (You can unzip these files from their jars. For example, spring-beans-x.y.xsd in spring-beans-x.y.z.RELEASE.jar)
  2. Add these xsd files to Eclipse XML Catalog. (Preferences->XML->XML Catalog, Add files)
  3. Add these files location to configuration file. (Be careful, write the exact version of file)

Example:

xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-x.y.xsd "

When to use .First and when to use .FirstOrDefault with LINQ?

First()

When you know that result contain more than 1 element expected and you should only the first element of sequence.

FirstOrDefault()

FirstOrDefault() is just like First() except that, if no element match the specified condition than it returns default value of underlying type of generic collection. It does not throw InvalidOperationException if no element found. But collection of element or a sequence is null than it throws an exception.

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

You should supply the SqlParameter instances in the following way:

context.Database.SqlQuery<myEntityType>(
    "mySpName @param1, @param2, @param3",
    new SqlParameter("param1", param1),
    new SqlParameter("param2", param2),
    new SqlParameter("param3", param3)
);

How do I execute a stored procedure once for each row returned by query?

Can this not be done with a user-defined function to replicate whatever your stored procedure is doing?

SELECT udfMyFunction(user_id), someOtherField, etc FROM MyTable WHERE WhateverCondition

where udfMyFunction is a function you make that takes in the user ID and does whatever you need to do with it.

See http://www.sqlteam.com/article/user-defined-functions for a bit more background

I agree that cursors really ought to be avoided where possible. And it usually is possible!

(of course, my answer presupposes that you're only interested in getting the output from the SP and that you're not changing the actual data. I find "alters user data in a certain way" a little ambiguous from the original question, so thought I'd offer this as a possible solution. Utterly depends on what you're doing!)

How to use Apple's new San Francisco font on a webpage

If the user is running El Capitan or higher, it will work in Chrome with

font-family: 'BlinkMacSystemFont';

How can I get the values of data attributes in JavaScript code?

You need to access the dataset property:

document.getElementById("the-span").addEventListener("click", function() {
  var json = JSON.stringify({
    id: parseInt(this.dataset.typeid),
    subject: this.dataset.type,
    points: parseInt(this.dataset.points),
    user: "Luïs"
  });
});

Result:

// json would equal:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

So many answers.... all bad!

Regular expressions don't have an AND operator, so it's pretty hard to write a regex that matches valid passwords, when validity is defined by something AND something else AND something else...

But, regular expressions do have an OR operator, so just apply DeMorgan's theorem, and write a regex that matches invalid passwords.

anything with less than 8 characters OR anything with no numbers OR anything with no uppercase OR anything with no special characters

So:

^(.{0,7}|[^0-9]*|[^A-Z]*|[a-zA-Z0-9]*)$

If anything matches that, then it's an invalid password.

Java SimpleDateFormat for time zone with a colon separator?

if you used the java 7, you could have used the following Date Time Pattern. Seems like this pattern is not supported in the Earlier version of java.

String dateTimeString  = "2010-03-01T00:00:00-08:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date date = df.parse(dateTimeString);

For More information refer to the SimpleDateFormat documentation.

Python Pandas Replacing Header with Top Row

@ostrokach answer is best. Most likely you would want to keep that throughout any references to the dataframe, thus would benefit from inplace = True.
df.rename(columns=df.iloc[0], inplace = True) df.drop([0], inplace = True)

Convert a Unicode string to an escaped ASCII string

This goes back and forth to and from the \uXXXX format.

class Program {
    static void Main( string[] args ) {
        string unicodeString = "This function contains a unicode character pi (\u03a0)";

        Console.WriteLine( unicodeString );

        string encoded = EncodeNonAsciiCharacters(unicodeString);
        Console.WriteLine( encoded );

        string decoded = DecodeEncodedNonAsciiCharacters( encoded );
        Console.WriteLine( decoded );
    }

    static string EncodeNonAsciiCharacters( string value ) {
        StringBuilder sb = new StringBuilder();
        foreach( char c in value ) {
            if( c > 127 ) {
                // This character is too big for ASCII
                string encodedValue = "\\u" + ((int) c).ToString( "x4" );
                sb.Append( encodedValue );
            }
            else {
                sb.Append( c );
            }
        }
        return sb.ToString();
    }

    static string DecodeEncodedNonAsciiCharacters( string value ) {
        return Regex.Replace(
            value,
            @"\\u(?<Value>[a-zA-Z0-9]{4})",
            m => {
                return ((char) int.Parse( m.Groups["Value"].Value, NumberStyles.HexNumber )).ToString();
            } );
    }
}

Outputs:

This function contains a unicode character pi (p)

This function contains a unicode character pi (\u03a0)

This function contains a unicode character pi (p)

How to disable Google Chrome auto update?

  1. On your Chrome browser's address bar, type in 'about:plugins' and hit ENTER.

  2. Find the plugin called 'Google Update' and click disable.

  3. Restart your browser for the changes to take effect.

Post a json object to mvc controller with jquery and ajax

instead of receiving the json string a model binding is better. For example:

[HttpPost]       
public ActionResult AddUser(UserAddModel model)
{
    if (ModelState.IsValid) {
        return Json(new { Response = "Success" });
    }
    return Json(new { Response = "Error" });
}

<script>
function submitForm() {    
    $.ajax({
        type: 'POST',
        url: "@Url.Action("AddUser")",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: $("form[name=UserAddForm]").serialize(),
        success: function (data) {
            console.log(data);
        }
    });
}
</script>