Programs & Examples On #Mbstring

MultiByte String in PHP

How to enable mbstring from php.ini?

All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.

If you have accidentally removed DLL file from php/ext folder, just add it back (get the copy from XAMPP zip archive - its downloadable).

If you have deleted the accompanying INI configuration line from php.ini file, add it back as well:

extension=php_mbstring.dll

Also, ensure to restart your webserver (Apache) using XAMPP control panel.

Additional Info on Enabling PHP Extensions

  • install extension (e.g. put php_mbstring.dll into /XAMPP/php/ext directory)
  • in php.ini, ensure extension directory specified (e.g. extension_dir = "ext")
  • ensure correct build of DLL file (e.g. 32bit thread-safe VC9 only works with DLL files built using exact same tools and configuration: 32bit thread-safe VC9)
  • ensure PHP API versions match (If not, once you restart the webserver you will receive related error.)

Fatal error: Call to undefined function mb_detect_encoding()

The problem could also be that Apache can't find php.ini If you set PHPIniDir incorrectly. Mine was set to: PHPIniDir "c:/php7" But, the folder is actually just "php" The clue was viewing phpinfo() Which showed: Configuration File (php.ini) Path C:\windows

How to install PHP mbstring on CentOS 6.2

yum install php-mbstring (as per http://php.net/manual/en/mbstring.installation.php)

I think you have to install the EPEL repository http://fedoraproject.org/wiki/EPEL

Unable to call the built in mb_internal_encoding method?

apt-get install php7.3-mbstring solved the issue on ubuntu, php version is php-fpm 7.3

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

sudo apt-get install php-mbstring

# if your are using php 7.1
sudo apt-get install php7.1-mbstring

# if your are using php 7.2
sudo apt-get install php7.2-mbstring

phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

just run these command

sudo apt-get install phpmyadmin php-mbstring php-gettext

sudo service apache2 restart

Or you can follow this post...

Check This Post

How to write file in UTF-8 format?

//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));

I got this line from Cool

phpMyAdmin mbstring error

Another reason for this problem is Php version. When I changed the running PHP version to 7.0.0, problem has gone.

enter image description here

How to replace all spaces in a string

VERY EASY:

just use this to replace all white spaces with -:

myString.replace(/ /g,"-")

How to center Font Awesome icons horizontally?

OP you can use attribute selectors to get the result you desire. Here is the extra code you add

tr td i[class*="icon"] {
    display: block;
    height: 100%;
    width: 100%;
    margin: auto;
}

Here is the updated jsFiddle http://jsfiddle.net/kB6Ju/5/

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

How do I detach objects in Entity Framework Code First?

This is an option:

dbContext.Entry(entity).State = EntityState.Detached;

When should an IllegalArgumentException be thrown?

When talking about "bad input", you should consider where the input is coming from.

Is the input entered by a user or another external system you don't control, you should expect the input to be invalid, and always validate it. It's perfectly ok to throw a checked exception in this case. Your application should 'recover' from this exception by providing an error message to the user.

If the input originates from your own system, e.g. your database, or some other parts of your application, you should be able to rely on it to be valid (it should have been validated before it got there). In this case it's perfectly ok to throw an unchecked exception like an IllegalArgumentException, which should not be caught (in general you should never catch unchecked exceptions). It is a programmer's error that the invalid value got there in the first place ;) You need to fix it.

"And" and "Or" troubles within an IF statement

I like assylias' answer, however I would refactor it as follows:

Sub test()

Dim origNum As String
Dim creditOrDebit As String

origNum = "30062600006"
creditOrDebit = "D"

If creditOrDebit = "D" Then
  If origNum = "006260006" Then
    MsgBox "OK"
  ElseIf origNum = "30062600006" Then
    MsgBox "OK"
  End If
End If

End Sub

This might save you some CPU cycles since if creditOrDebit is <> "D" there is no point in checking the value of origNum.

Update:

I used the following procedure to test my theory that my procedure is faster:

Public Declare Function timeGetTime Lib "winmm.dll" () As Long

Sub DoTests2()

  Dim startTime1 As Long
  Dim endTime1 As Long
  Dim startTime2 As Long
  Dim endTime2 As Long
  Dim i As Long
  Dim msg As String

  Const numberOfLoops As Long = 10000
  Const origNum As String = "006260006"
  Const creditOrDebit As String = "D"

  startTime1 = timeGetTime
  For i = 1 To numberOfLoops
    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        ' do something here
        Debug.Print "OK"
      ElseIf origNum = "30062600006" Then
        ' do something here
        Debug.Print "OK"
      End If
    End If
  Next i
  endTime1 = timeGetTime

  startTime2 = timeGetTime
  For i = 1 To numberOfLoops
    If (origNum = "006260006" Or origNum = "30062600006") And _
      creditOrDebit = "D" Then
      ' do something here
      Debug.Print "OK"
    End If
  Next i
  endTime2 = timeGetTime

  msg = "number of iterations: " & numberOfLoops & vbNewLine
  msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
       " ms" & vbNewLine
  msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
       " ms"

  MsgBox msg

End Sub

I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)

After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit is <>"D", my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.

And that is why I refactored it - to short-circuit the logic so that origNum doesn't need to be evaluated when creditOrDebit <> "D".

At this point, the rest depends on the OP's spreadsheet. If creditOrDebit is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit has a wide range of possible values, and D is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.

Java HTML Parsing

The HTMLParser project (http://htmlparser.sourceforge.net/) might be a possibility. It seems to be pretty decent at handling malformed HTML. The following snippet should do what you need:

Parser parser = new Parser(htmlInput);
CssSelectorNodeFilter cssFilter = 
    new CssSelectorNodeFilter("DIV.targetClassName");
NodeList nodes = parser.parse(cssFilter);

How to Logout of an Application Where I Used OAuth2 To Login With Google?

You can log out and rediret to your site:

var logout = function() {
    document.location.href = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://www.example.com";
}

How to pass credentials to the Send-MailMessage command for sending emails

So..it was SSL problem. Whatever I was doing was absolutely correct. Only that I was not using the ssl option. So I added "-Usessl true" to my original command and it worked.

When should you use 'friend' in C++?

At work we use friends for testing code, extensively. It means we can provide proper encapsulation and information hiding for the main application code. But also we can have separate test code that uses friends to inspect internal state and data for testing.

Suffice to say I wouldn't use the friend keyword as an essential component of your design.

jQuery append() and remove() element

Since this is an open-ended question, I will just give you an idea of how I would go about implementing something like this myself.

<span class="inputname">
    Project Images:
    <a href="#" class="add_project_file">
        <img src="images/add_small.gif" border="0" />
    </a>
</span>

<ul class="project_images">
    <li><input name="upload_project_images[]" type="file" /></li>
</ul>

Wrapping the file inputs inside li elements allows to easily remove the parent of our 'remove' links when clicked. The jQuery to do so is close to what you have already:

// Add new input with associated 'remove' link when 'add' button is clicked.
$('.add_project_file').click(function(e) {
    e.preventDefault();

    $(".project_images").append(
        '<li>'
      + '<input name="upload_project_images[]" type="file" class="new_project_image" /> '
      + '<a href="#" class="remove_project_file" border="2"><img src="images/delete.gif" /></a>'
      + '</li>');
});

// Remove parent of 'remove' link when link is clicked.
$('.project_images').on('click', '.remove_project_file', function(e) {
    e.preventDefault();

    $(this).parent().remove();
});

Why is my CSS style not being applied?

I know this is an old post but I thought I might add a thought for people who come across a similar problem. I'm assuming that you are using ASP.NET MVC since you mentioned site.css.

Check your Bundles.config file to see if you have BundleTable.EnableOptimizations = true; If you don't, then it can be your problem since this allows the program to be bundles and "minified". Depending on if you run in debug mode or not this could have an effect.

JavaScript: Difference between .forEach() and .map()

Performance Analysis For loops performs faster than map or foreach as number of elements in a array increases.

let array = [];
for (var i = 0; i < 20000000; i++) {
  array.push(i)
}

console.time('map');
array.map(num => {
  return num * 4;
});
console.timeEnd('map');


console.time('forEach');
array.forEach((num, index) => {
  return array[index] = num * 4;
});
console.timeEnd('forEach');

console.time('for');
for (i = 0; i < array.length; i++) {
  array[i] = array[i] * 2;

}
console.timeEnd('for');

Time complexity of nested for-loop

Yes, the time complexity of this is O(n^2).

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

The livereload plugin fails to serve cordova.js file and serves // mock cordova file during development.

FIX: You need go to node_modules/@ionic/app-scripts/dist/dev-server/serve-config.js

and replace

exports.ANDROID_PLATFORM_PATH = path.join('platforms', 'android', 'assets', 'www');

to

exports.ANDROID_PLATFORM_PATH = path.join('platforms', 'android', 'app', 'src', 'main', 'assets', 'www');

What's wrong with using == to compare floats in Java?

Just to give the reason behind what everyone else is saying.

The binary representation of a float is kind of annoying.

In binary, most programmers know the correlation between 1b=1d, 10b=2d, 100b=4d, 1000b=8d

Well it works the other way too.

.1b=.5d, .01b=.25d, .001b=.125, ...

The problem is that there is no exact way to represent most decimal numbers like .1, .2, .3, etc. All you can do is approximate in binary. The system does a little fudge-rounding when the numbers print so that it displays .1 instead of .10000000000001 or .999999999999 (which are probably just as close to the stored representation as .1 is)

Edit from comment: The reason this is a problem is our expectations. We fully expect 2/3 to be fudged at some point when we convert it to decimal, either .7 or .67 or .666667.. But we don't automatically expect .1 to be rounded in the same way as 2/3--and that's exactly what's happening.

By the way, if you are curious the number it stores internally is a pure binary representation using a binary "Scientific Notation". So if you told it to store the decimal number 10.75d, it would store 1010b for the 10, and .11b for the decimal. So it would store .101011 then it saves a few bits at the end to say: Move the decimal point four places right.

(Although technically it's no longer a decimal point, it's now a binary point, but that terminology wouldn't have made things more understandable for most people who would find this answer of any use.)

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

Remove Existing/Configured System Library: Eclipse(IDE) -> Project Explorer -> Project Name-> (Option) Build Path -> Configure Build Path -> Java Build Path -> Libraries -> (Select) JRE System Library [(For me)jre1.8.0_231] -> Remove.

Currently you are at same location: Eclipse(IDE) -> Project Explorer -> Project Name-> (Option) Build Path -> Configure Build Path -> Java Build Path -> Libraries

Now Add Same System Library Again: Add Library -> JRE System Library -> Workspace default JRE ((For me)jre1.8.0_231) -> Finish -> Apply -> Close.

Now wait to finish it.

Get UTC time in seconds

I bet this is what was intended as a result.

$ date -u --date=@1404372514
Thu Jul  3 07:28:34 UTC 2014

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

just do

ALTER TABLE `some_table` 
CHARACTER SET = utf8 , COLLATE = utf8_general_ci ;

ALTER TABLE `some_table` 
CHANGE COLUMN `description_with_latin_or_something` `description` TEXT CHARACTER SET 'utf8' NOT NULL ;

Recursive search and replace in text files on Mac and Linux

This is my workable one. on mac OS X 10.10.4

grep -e 'this' -rl . | xargs sed -i '' 's/this/that/g'

The above ones use find will change the files that do not contain the search text (add a new line at the file end), which is verbose.

JavaScript query string

tl;dr solution on a single(ish) line of code using vanilla javascript

var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {
    queryDict[item.split("=")[0]] = item.split("=")[1]
})

For querystring ?a=1&b=2&c=3&d&eit returns:

> queryDict
a: "1"
b: "2"
c: "3"
d: undefined
e: undefined

multi-valued keys and encoded characters?

See the original answer at How can I get query string values in JavaScript?

"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> queryDict
a: ["1", "5", "t e x t"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]

When to use 'raise NotImplementedError'?

You might want to you use the @property decorator,

>>> class Foo():
...     @property
...     def todo(self):
...             raise NotImplementedError("To be implemented")
... 
>>> f = Foo()
>>> f.todo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in todo
NotImplementedError: To be implemented

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

I use this:

var app = express();

app
.use(function(req, res, next){
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With');
    next();
})
.options('*', function(req, res, next){
    res.end();
})
;

h.readFiles('controllers').forEach(function(file){
  require('./controllers/' + file)(app);
})
;

app.listen(port);
console.log('server listening on port ' + port);

this code assumes that your controllers are located in the controllers directory. each file in this directory should be something like this:

module.exports = function(app){

    app.get('/', function(req, res, next){
        res.end('hi');
    });

}

I get exception when using Thread.sleep(x) or wait()

public static void main(String[] args) throws InterruptedException {
  //type code


  short z=1000;
  Thread.sleep(z);/*will provide 1 second delay. alter data type of z or value of z for longer delays required */

  //type code
}

eg:-

class TypeCasting {

  public static void main(String[] args) throws InterruptedException {
    short f = 1;
    int a = 123687889;
    short b = 2;
    long c = 4567;
    long d=45;
    short z=1000;
    System.out.println("Value of a,b and c are\n" + a + "\n" + b + "\n" + c + "respectively");
    c = a;
    b = (short) c;
    System.out.println("Typecasting...........");
    Thread.sleep(z);
    System.out.println("Value of B after Typecasting" + b);
    System.out.println("Value of A is" + a);


  }
}

How to Install pip for python 3.7 on Ubuntu 18?

When i use apt install python3-pip, i get a lot of packages need install, but i donot need them. So, i DO like this:

apt update
apt-get install python3-setuptools
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py
rm -f get-pip.py

How can I split a text file using PowerShell?

Many of these answers were too slow for my source files. My source files were SQL files between 10 MB and 800 MB that needed to split into files of roughly equal line counts.

I found some of the previous answers which use Add-Content to be quite slow. Waiting many hours for a split to finish wasn't uncommon.

I didn't try Typhlosaurus's answer, but it looks to only do splits by file size, not line count.

The following has suited my purposes.

$sw = new-object System.Diagnostics.Stopwatch
$sw.Start()
Write-Host "Reading source file..."
$lines = [System.IO.File]::ReadAllLines("C:\Temp\SplitTest\source.sql")
$totalLines = $lines.Length

Write-Host "Total Lines :" $totalLines

$skip = 0
$count = 100000; # Number of lines per file

# File counter, with sort friendly name
$fileNumber = 1
$fileNumberString = $filenumber.ToString("000")

while ($skip -le $totalLines) {
    $upper = $skip + $count - 1
    if ($upper -gt ($lines.Length - 1)) {
        $upper = $lines.Length - 1
    }

    # Write the lines
    [System.IO.File]::WriteAllLines("C:\Temp\SplitTest\result$fileNumberString.txt",$lines[($skip..$upper)])

    # Increment counters
    $skip += $count
    $fileNumber++
    $fileNumberString = $filenumber.ToString("000")
}

$sw.Stop()

Write-Host "Split complete in " $sw.Elapsed.TotalSeconds "seconds"

For a 54 MB file, I get the output...

Reading source file...
Total Lines : 910030
Split complete in  1.7056578 seconds

I hope others looking for a simple, line-based splitting script that matches my requirements will find this useful.

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

C# Ignore certificate errors?

If you are using sockets directly and are authenticating as the client, then the Service Point Manager callback method won't work. Here's what did work for me. PLEASE USE FOR TESTING PURPOSES ONLY.

var activeStream = new SslStream(networkStream, false, (a, b, c, d) => { return true; });
await activeStream.AuthenticateAsClientAsync("computer.local");

The key here, is to provide the remote certificate validation callback right in the constructor of the SSL stream.

PHP - Merging two arrays into one array (also Remove Duplicates)

The best solution above faces a problem when using the same associative keys, array_merge() will merge array elements together when they have the same NON-NUMBER key, so it is not suitable for the following case

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("c"=>"red","d"=>"black","e"=>"green");

If you are able output your value to the keys of your arrays instead (e.g ->pluck('name', 'id')->toArray() in Eloquent), you can use the following merge method instead

array_keys(array_merge($a1, $a2))

Basically what the code does is it utilized the behavior of array_merge() to get rid of duplicated keys and return you a new array with keys as array elements, hope it helps

How can I change the text color with jQuery?

Place the following in your jQuery mouseover event handler:

$(this).css('color', 'red');

To set both color and size at the same time:

$(this).css({ 'color': 'red', 'font-size': '150%' });

You can set any CSS attribute using the .css() jQuery function.

How to use java.net.URLConnection to fire and handle HTTP requests?

Update

The new HTTP Client shipped with Java 9 but as part of an Incubator module named jdk.incubator.httpclient. Incubator modules are a means of putting non-final APIs in the hands of developers while the APIs progress towards either finalization or removal in a future release.

In Java 9, you can send a GET request like:

// GET
HttpResponse response = HttpRequest
    .create(new URI("http://www.stackoverflow.com"))
    .headers("Foo", "foovalue", "Bar", "barvalue")
    .GET()
    .response();

Then you can examine the returned HttpResponse:

int statusCode = response.statusCode();
String responseBody = response.body(HttpResponse.asString());

Since this new HTTP Client is in java.httpclient jdk.incubator.httpclient module, you should declare this dependency in your module-info.java file:

module com.foo.bar {
    requires jdk.incubator.httpclient;
}

What do the return values of Comparable.compareTo mean in Java?

Official Definition

From the reference docs of Comparable.compareTo(T):

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)

The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.

Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.

My Version

In short:

this.compareTo(that)

returns

  • a negative int if this < that
  • 0 if this == that
  • a positive int if this > that

where the implementation of this method determines the actual semantics of < > and == (I don't mean == in the sense of java's object identity operator)

Examples

"abc".compareTo("def")

will yield something smaller than 0 as abc is alphabetically before def.

Integer.valueOf(2).compareTo(Integer.valueOf(1))

will yield something larger than 0 because 2 is larger than 1.

Some additional points

Note: It is good practice for a class that implements Comparable to declare the semantics of it's compareTo() method in the javadocs.

Note: you should read at least one of the following:

Warning: you should never rely on the return values of compareTo being -1, 0 and 1. You should always test for x < 0, x == 0, x > 0, respectively.

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

How could I create a function with a completion handler in Swift?

Swift 5.0 + , Simple and Short

example:

Style 1

    func methodName(completionBlock: () -> Void)  {

          print("block_Completion")
          completionBlock()
    }

Style 2

    func methodName(completionBlock: () -> ())  {

        print("block_Completion")
        completionBlock()
    }

Use:

    override func viewDidLoad() {
        super.viewDidLoad()
        
        methodName {

            print("Doing something after Block_Completion!!")
        }
    }

Output

block_Completion

Doing something after Block_Completion!!

jQuery OR Selector?

I have written an incredibly simple (5 lines of code) plugin for exactly this functionality:

http://byrichardpowell.github.com/jquery-or/

It allows you to effectively say "get this element, or if that element doesnt exist, use this element". For example:

$( '#doesntExist' ).or( '#exists' );

Whilst the accepted answer provides similar functionality to this, if both selectors (before & after the comma) exist, both selectors will be returned.

I hope it proves helpful to anyone who might land on this page via google.

How to pause in C?

you can put

getchar();

before the return from the main function. That will wait for a character input before exiting the program.

Alternatively you could run your program from a command line and the output would be visible.

How to remove all elements in String array in java?

list.clear() is documented for clearing the ArrayList.

list.removeAll() has no documentation at all in Eclipse.

Logger slf4j advantages of formatting with {} instead of string concatenation

It is about string concatenation performance. It's potentially significant if your have dense logging statements.

(Prior to SLF4J 1.7) But only two parameters are possible

Because the vast majority of logging statements have 2 or fewer parameters, so SLF4J API up to version 1.6 covers (only) the majority of use cases. The API designers have provided overloaded methods with varargs parameters since API version 1.7.

For those cases where you need more than 2 and you're stuck with pre-1.7 SLF4J, then just use either string concatenation or new Object[] { param1, param2, param3, ... }. There should be few enough of them that the performance is not as important.

How to connect Android app to MySQL database?

Yes you can connect your android app to your PHP to grab results from your database. Use a webservice to connect to your backend script via ASYNC task and http post requests. Check this link for more information Connecting to MySQL

How to get MD5 sum of a string using python?

You can use b character in front of a string literal:

import hashlib
print(hashlib.md5(b"Hello MD5").hexdigest())
print(hashlib.md5("Hello MD5".encode('utf-8')).hexdigest())

Out:

e5dadf6524624f79c3127e247f04b548
e5dadf6524624f79c3127e247f04b548

trigger click event from angularjs directive

This is more the Angular way to do it: http://plnkr.co/edit/xYNX47EsYvl4aRuGZmvo?p=preview

  1. I added $scope.selectedItem that gets you past your first problem (defaulting the image)
  2. I added $scope.setSelectedItem and called it in ng-click. Your final requirements may be different, but using a directive to bind click and change src was overkill, since most of it can be handled with template
  3. Notice use of ngSrc to avoid errant server calls on initial load
  4. You'll need to adjust some styles to get the image positioned right in the div. If you really need to use background-image, then you'll need a directive like ngSrc that defers setting the background-image style until after real data has loaded.

What does the servlet <load-on-startup> value signify

The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute "load-on-startup" in "web.xml" file. If the attribute has a positive integer(0 to 128) then the servlet is load with the loading of the container otherwise it loads when the first request comes for service.

When the servlet is loaded once it gets request then it is called "Lazy loading".

How to change a css class style through Javascript?

I'd highly recommend jQuery. It then becomes as simple as:

$('#mydiv').addClass('newclass');

You don't have to worry about removing the old class then as addClass() will only append to it. You also have removeClass();

The other advantage over the getElementById() method is you can apply it to multiple elements at the same time with a single line of code.

$('div').addClass('newclass');
$('.oldclass').addClass('newclass');

The first example will add the class to all DIV elements on the page. The second example will add the new class to all elements that currently have the old class.

C# Public Enums in Classes

Currently, your enum is nested inside of your Card class. All you have to do is move the definition of the enum out of the class:

// A better name which follows conventions instead of card_suits is
public enum CardSuit
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
}

To Specify:

The name change from card_suits to CardSuit was suggested because Microsoft guidelines suggest Pascal Case for Enumerations and the singular form is more descriptive in this case (as a plural would suggest that you're storing multiple enumeration values by ORing them together).

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

If origin points to a bare repository on disk, this error can happen if that directory has been moved (even if you update the working copy's remotes). For example

$ mv /path/to/origin /somewhere/else
$ git remote set-url origin /somewhere/else
$ git diff origin/master
fatal: ambiguous argument 'origin': unknown revision or path not in the working tree.

Pulling once from the new origin solves the problem:

$ git stash
$ git pull origin master
$ git stash pop

CSS3 100vh not constant in mobile browser

Here's a work around I used for my React app.

iPhone 11 Pro & iPhone Pro Max - 120px

iPhone 8 - 80px

max-height: calc(100vh - 120px);

It's a compromise but relatively simple fix

Why am I getting a NoClassDefFoundError in Java?

I have found that sometimes I get a NoClassDefFound error when code is compiled with an incompatible version of the class found at runtime. The specific instance I recall is with the apache axis library. There were actually 2 versions on my runtime classpath and it was picking up the out of date and incompatible version and not the correct one, causing a NoClassDefFound error. This was in a command line app where I was using a command similar to this.

set classpath=%classpath%;axis.jar

I was able to get it to pick up the proper version by using:

set classpath=axis.jar;%classpath%;

hadoop copy a local file system folder to HDFS

To copy a folder file from local to hdfs, you can the below command

hadoop fs -put /path/localpath  /path/hdfspath

or

hadoop fs -copyFromLocal /path/localpath  /path/hdfspath

How to get first two characters of a string in oracle query?

Try select substr(orderno, 1,2) from shipment;

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

Using the solution of Slauma, I created some generic functions to help update child objects and collections of child objects.

All my persistent objects implement this interface

/// <summary>
/// Base interface for all persisted entries
/// </summary>
public interface IBase
{
    /// <summary>
    /// The Id
    /// </summary>
    int Id { get; set; }
}

With this I implemented these two functions in my Repository

    /// <summary>
    /// Check if orgEntry is set update it's values, otherwise add it
    /// </summary>
    /// <param name="set">The collection</param>
    /// <param name="entry">The entry</param>
    /// <param name="orgEntry">The original entry found in the database (can be <code>null</code> is this is a new entry)</param>
    /// <returns>The added or updated entry</returns>
    public T AddOrUpdateEntry<T>(DbSet<T> set, T entry, T orgEntry) where T : class, IBase
    {
        if (entry.Id == 0 || orgEntry == null)
        {
            entry.Id = 0;
            return set.Add(entry);
        }
        else
        {
            Context.Entry(orgEntry).CurrentValues.SetValues(entry);
            return orgEntry;
        }
    }

    /// <summary>
    /// check if each entry of the new list was in the orginal list, if found, update it, if not found add it
    /// all entries found in the orignal list that are not in the new list are removed
    /// </summary>
    /// <typeparam name="T">The type of entry</typeparam>
    /// <param name="set">The database set</param>
    /// <param name="newList">The new list</param>
    /// <param name="orgList">The original list</param>
    public void AddOrUpdateCollection<T>(DbSet<T> set, ICollection<T> newList, ICollection<T> orgList) where T : class, IBase
    {
        // attach or update all entries in the new list
        foreach (T entry in newList)
        {
            // Find out if we had the entry already in the list
            var orgEntry = orgList.SingleOrDefault(e => e.Id != 0 && e.Id == entry.Id);

            AddOrUpdateEntry(set, entry, orgEntry);
        }

        // Remove all entries from the original list that are no longer in the new list
        foreach (T orgEntry in orgList.Where(e => e.Id != 0).ToList())
        {
            if (!newList.Any(e => e.Id == orgEntry.Id))
            {
                set.Remove(orgEntry);
            }
        }
    }

To use it i do the following:

var originalParent = _dbContext.ParentItems
    .Where(p => p.Id == parent.Id)
    .Include(p => p.ChildItems)
    .Include(p => p.ChildItems2)
    .SingleOrDefault();

// Add the parent (including collections) to the context or update it's values (except the collections)
originalParent = AddOrUpdateEntry(_dbContext.ParentItems, parent, originalParent);

// Update each collection
AddOrUpdateCollection(_dbContext.ChildItems, parent.ChildItems, orgiginalParent.ChildItems);
AddOrUpdateCollection(_dbContext.ChildItems2, parent.ChildItems2, orgiginalParent.ChildItems2);

Hope this helps


EXTRA: You could also make a seperate DbContextExtentions (or your own context inferface) class:

public static void DbContextExtentions {
    /// <summary>
    /// Check if orgEntry is set update it's values, otherwise add it
    /// </summary>
    /// <param name="_dbContext">The context object</param>
    /// <param name="set">The collection</param>
    /// <param name="entry">The entry</param>
    /// <param name="orgEntry">The original entry found in the database (can be <code>null</code> is this is a new entry)</param>
    /// <returns>The added or updated entry</returns>
    public static T AddOrUpdateEntry<T>(this DbContext _dbContext, DbSet<T> set, T entry, T orgEntry) where T : class, IBase
    {
        if (entry.IsNew || orgEntry == null) // New or not found in context
        {
            entry.Id = 0;
            return set.Add(entry);
        }
        else
        {
            _dbContext.Entry(orgEntry).CurrentValues.SetValues(entry);
            return orgEntry;
        }
    }

    /// <summary>
    /// check if each entry of the new list was in the orginal list, if found, update it, if not found add it
    /// all entries found in the orignal list that are not in the new list are removed
    /// </summary>
    /// <typeparam name="T">The type of entry</typeparam>
    /// <param name="_dbContext">The context object</param>
    /// <param name="set">The database set</param>
    /// <param name="newList">The new list</param>
    /// <param name="orgList">The original list</param>
    public static void AddOrUpdateCollection<T>(this DbContext _dbContext, DbSet<T> set, ICollection<T> newList, ICollection<T> orgList) where T : class, IBase
    {
        // attach or update all entries in the new list
        foreach (T entry in newList)
        {
            // Find out if we had the entry already in the list
            var orgEntry = orgList.SingleOrDefault(e => e.Id != 0 && e.Id == entry.Id);

            AddOrUpdateEntry(_dbContext, set, entry, orgEntry);
        }

        // Remove all entries from the original list that are no longer in the new list
        foreach (T orgEntry in orgList.Where(e => e.Id != 0).ToList())
        {
            if (!newList.Any(e => e.Id == orgEntry.Id))
            {
                set.Remove(orgEntry);
            }
        }
    }
}

and use it like:

var originalParent = _dbContext.ParentItems
    .Where(p => p.Id == parent.Id)
    .Include(p => p.ChildItems)
    .Include(p => p.ChildItems2)
    .SingleOrDefault();

// Add the parent (including collections) to the context or update it's values (except the collections)
originalParent = _dbContext.AddOrUpdateEntry(_dbContext.ParentItems, parent, originalParent);

// Update each collection
_dbContext.AddOrUpdateCollection(_dbContext.ChildItems, parent.ChildItems, orgiginalParent.ChildItems);
_dbContext.AddOrUpdateCollection(_dbContext.ChildItems2, parent.ChildItems2, orgiginalParent.ChildItems2);

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325

Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.

Make sure that you have checked it to work properly with the IE version you specify.

Select data from date range between two dates

interval intersection description

As you can see, there are two ways to get things done:

  • enlist all acceptable options
  • exclude all wrong options

Obviously, second way is much more simple (only two cases against four).

Your SQL will look like:

SELECT * FROM Product_sales 
WHERE NOT (From_date > @RangeTill OR To_date < @RangeFrom)

How do you select the entire excel sheet with Range using VBA?

I have found that the Worksheet ".UsedRange" method is superior in many instances to solve this problem. I struggled with a truncation issue that is a normal behaviour of the ".CurrentRegion" method. Using [ Worksheets("Sheet1").Range("A1").CurrentRegion ] does not yield the results I desired when the worksheet consists of one column with blanks in the rows (and the blanks are wanted). In this case, the ".CurrentRegion" will truncate at the first record. I implemented a work around but recently found an even better one; see code below that allows copying the whole set to another sheet or to identify the actual address (or just rows and columns):

Sub mytest_GetAllUsedCells_in_Worksheet()
    Dim myRange

    Set myRange = Worksheets("Sheet1").UsedRange
    'Alternative code:  set myRange = activesheet.UsedRange

   'use msgbox or debug.print to show the address range and counts
   MsgBox myRange.Address      
   MsgBox myRange.Columns.Count
   MsgBox myRange.Rows.Count

  'Copy the Range of data to another sheet
  'Note: contains all the cells with that are non-empty
   myRange.Copy (Worksheets("Sheet2").Range("A1"))
   'Note:  transfers all cells starting at "A1" location.  
   '       You can transfer to another area of the 2nd sheet
   '       by using an alternate starting location like "C5".

End Sub

Batch - If, ElseIf, Else

Recommendation. Do not use user-added REM statements to block batch steps. Use conditional GOTO instead. That way you can predefine and test the steps and options. The users also get much simpler changes and better confidence.

@Echo on
rem Using flags to control command execution

SET ExecuteSection1=0
SET ExecuteSection2=1

@echo off

IF %ExecuteSection1%==0 GOTO EndSection1
ECHO Section 1 Here

:EndSection1

IF %ExecuteSection2%==0 GOTO EndSection2
ECHO Section 2 Here
:EndSection2

c# datagridview doubleclick on row with FullRowSelect

I think you are looking for this: RowHeaderMouseDoubleClick event

private void DgwModificar_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
...
}

to get the row index:

int indice = e.RowIndex

How to enumerate an enum

I think this is more efficient than other suggestions because GetValues() is not called each time you have a loop. It is also more concise. And you get a compile-time error, not a runtime exception if Suit is not an enum.

EnumLoop<Suit>.ForEach((suit) => {
    DoSomethingWith(suit);
});

EnumLoop has this completely generic definition:

class EnumLoop<Key> where Key : struct, IConvertible {
    static readonly Key[] arr = (Key[])Enum.GetValues(typeof(Key));
    static internal void ForEach(Action<Key> act) {
        for (int i = 0; i < arr.Length; i++) {
            act(arr[i]);
        }
    }
}

How to get current route in Symfony 2?

All I'm getting from that is _internal

I get the route name from inside a controller with $this->getRequest()->get('_route'). Even the code tuxedo25 suggested returns _internal

This code is executed in what was called a 'Component' in Symfony 1.X; Not a page's controller but part of a page which needs some logic.

The equivalent code in Symfony 1.X is: sfContext::getInstance()->getRouting()->getCurrentRouteName();

In Angular, how to pass JSON object/array into directive?

What you need is properly a service:

.factory('DataLayer', ['$http',

    function($http) {

        var factory = {};
        var locations;

        factory.getLocations = function(success) {
            if(locations){
                success(locations);
                return;
            }
            $http.get('locations/locations.json').success(function(data) {
                locations = data;
                success(locations);
            });
        };

        return factory;
    }
]);

The locations would be cached in the service which worked as singleton model. This is the right way to fetch data.

Use this service DataLayer in your controller and directive is ok as following:

appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
    DataLayer.getLocations(function(data){
        $scope.locations = data;
    });
});

.directive('map', function(DataLayer) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function(scope, element, attrs) {

            DataLayer.getLocations(function(data) {
                angular.forEach(data, function(location, key){
                    //do something
                });
            });
        }
    };
});

How do I add python3 kernel to jupyter (IPython)

This worked for me on Ubuntu 16.04:

python2 -m pip install ipykernel
python2 -m ipykernel install --user

python3 -m pip install ipykernel
python3 -m ipykernel install --user

Reference to the documentation:
Kernels for Python 2 and 3. Installing the IPython kernel - IPython Docs.

Javascript How to define multiple variables on a single line?

Here is the new ES6 method of declaration multiple variables in one line:

_x000D_
_x000D_
const person = { name: 'Prince', age: 22, id: 1 };_x000D_
_x000D_
let {name, age, id} = person;_x000D_
_x000D_
console.log(name);_x000D_
console.log(age);_x000D_
console.log(id);
_x000D_
_x000D_
_x000D_

* Your variable name and object index need be same

Difference between INNER JOIN and LEFT SEMI JOIN

Trying to depict with venn diagrams for better understanding..

Left Semi join : A semi join returns values from the left side of the relation that has a match with the right. It is also referred to as a left semi join.

enter image description here

Note : There is another thing called left anti join : An anti join returns values from the left relation that has no match with the right. It is also referred to as a left anti join.

Inner join : It selects rows that have matching values in both relations.

enter image description here

Google Chrome default opening position and size

You should just grab the window by the title bar and snap it to the left side of your screen (close browser) then reopen the browser ans snap it to the top... problem is over.

C# how to wait for a webpage to finish loading before continuing

Best way to do this without blocking the UI thread is to use Async and Await introduced in .net 4.5.
You can paste this in your code just change the Browser to your webbrowser name. This way, your thread awaits the page to load, if it doesnt on time, it stops waiting and your code continues to run:

private async Task PageLoad(int TimeOut)
    {
        TaskCompletionSource<bool> PageLoaded = null;
        PageLoaded = new TaskCompletionSource<bool>();
        int TimeElapsed = 0;
        Browser.DocumentCompleted += (s, e) =>
        {
            if (Browser.ReadyState != WebBrowserReadyState.Complete) return;
            if (PageLoaded.Task.IsCompleted) return; PageLoaded.SetResult(true);
        };
        //
        while (PageLoaded.Task.Status != TaskStatus.RanToCompletion)
        {
            await Task.Delay(10);//interval of 10 ms worked good for me
            TimeElapsed++;
            if (TimeElapsed >= TimeOut * 100) PageLoaded.TrySetResult(true);
        }
    }

And you can use it like this, with in an async method, or in a button click event, just make it async:

private async void Button1_Click(object sender, EventArgs e)
{
   Browser.Navigate("www.example.com");
   await PageLoad(10);//await for page to load, timeout 10 seconds.
   //your code will run after the page loaded or timeout.
}

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

Your target SDK might be higher than SDK of the device, change that. For example, your device is running API 23 but your target SDK is 25. Change 25 to 23.

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

How to JSON serialize sets?

I adapted Raymond Hettinger's solution to python 3.

Here is what has changed:

  • unicode disappeared
  • updated the call to the parents' default with super()
  • using base64 to serialize the bytes type into str (because it seems that bytes in python 3 can't be converted to JSON)
from decimal import Decimal
from base64 import b64encode, b64decode
from json import dumps, loads, JSONEncoder
import pickle

class PythonObjectEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (list, dict, str, int, float, bool, type(None))):
            return super().default(obj)
        return {'_python_object': b64encode(pickle.dumps(obj)).decode('utf-8')}

def as_python_object(dct):
    if '_python_object' in dct:
        return pickle.loads(b64decode(dct['_python_object'].encode('utf-8')))
    return dct

data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'}, Decimal('3.14')]
j = dumps(data, cls=PythonObjectEncoder)
print(loads(j, object_hook=as_python_object))
# prints: [1, 2, 3, {'knights', 'who', 'say', 'ni'}, {'key': 'value'}, Decimal('3.14')]

Page unload event in asp.net

Refer to the ASP.NET page lifecycle to help find the right event to override. It really depends what you want to do. But yes, there is an unload event.

    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);

        // your code
    }

But just remember (from the above link): During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Conditional formatting based on another cell's value

change the background color of cell B5 based on the value of another cell - C5. If C5 is greater than 80% then the background color is green but if it's below, it will be amber/red.

There is no mention that B5 contains any value so assuming 80% is .8 formatted as percentage without decimals and blank counts as "below":

Select B5, colour "amber/red" with standard fill then Format - Conditional formatting..., Custom formula is and:

=C5>0.8

with green fill and Done.

CF rule example

ascending/descending in LINQ - can one change the order via parameter?

In terms of how this is implemented, this changes the method - from OrderBy/ThenBy to OrderByDescending/ThenByDescending. However, you can apply the sort separately to the main query...

var qry = from .... // or just dataList.AsEnumerable()/AsQueryable()

if(sortAscending) {
    qry = qry.OrderBy(x=>x.Property);
} else {
    qry = qry.OrderByDescending(x=>x.Property);
}

Any use? You can create the entire "order" dynamically, but it is more involved...

Another trick (mainly appropriate to LINQ-to-Objects) is to use a multiplier, of -1/1. This is only really useful for numeric data, but is a cheeky way of achieving the same outcome.

Commenting out code blocks in Atom

You can use Ctrl + /. This works for me.

java.io.FileNotFoundException: the system cannot find the file specified

Your file should directly be under the project folder, and not inside any other sub-folder.

If the folder of your project is named for e.g. AProject, it should be in the same place as your src folder.

Aproject
        src
        word.txt

pip install mysql-python fails with EnvironmentError: mysql_config not found

You can use the MySQL Connector/Python

Installation via PyPip

pip install mysql-connector-python

Further information can be found on the MySQL Connector/Python 1.0.5 beta announcement blog.

On Launchpad there's a good example of how to add-, edit- or remove data with the library.

What causes: "Notice: Uninitialized string offset" to appear?

The error may occur when the number of times you iterate the array is greater than the actual size of the array. for example:

 $one="909";
 for($i=0;$i<10;$i++)
    echo ' '.$one[$i];

will show the error. first case u can take the mod of i.. for example

function mod($i,$length){
  $m = $i % $size;
  if ($m > $size)
  mod($m,$size)
  return $m;
}

for($i=0;$i<10;$i++)
{
  $k=mod($i,3);
  echo ' '.$one[$k];
}

or might be it not an array (maybe it was a value and you tried to access it like an array) for example:

$k = 2;
$k[0];

How to import a class from default package

  1. Create a new package.
  2. Move your files from the default package to the new one.

Detect iPhone/iPad purely by css

I use these:

/* Non-Retina */
@media screen and (-webkit-max-device-pixel-ratio: 1) {
}

/* Retina */
@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (-o-min-device-pixel-ratio: 3/2),
only screen and (min--moz-device-pixel-ratio: 1.5),
only screen and (min-device-pixel-ratio: 1.5) {
}

/* iPhone Portrait */
@media screen and (max-device-width: 480px) and (orientation:portrait) {
} 

/* iPhone Landscape */
@media screen and (max-device-width: 480px) and (orientation:landscape) {
}

/* iPad Portrait */
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
}

/* iPad Landscape */
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
}

http://zsprawl.com/iOS/2012/03/css-for-iphone-ipad-and-retina-displays/

How to find the port for MS SQL Server 2008?

This may also be done via a port scan, which is the only possible method if you don't have admin access to a remote server.

Using Nmap (http://nmap.org/zenmap/) to do an "Intense TCP scan" will give you results like this for all instances on the server:

[10.0.0.1\DATABASE]    
Instance name: DATABASE
Version: Microsoft SQL Server 2008 R2 RTM    
Product: Microsoft SQL Server 2008 R2    
Service pack level: RTM    
TCP port: 49843    
Named pipe: \\10.0.0.1\pipe\MSSQL$DATABASE\sql\query

Important note: To test with query analyzer or MS SQL Server Management Studio you must form your server name and port differently than you would normally connect to a port, over HTTP for instance, using a comma instead of a colon.

  • Management Studio Server Name: 10.0.0.1,49843
  • Connection String: Data Source=10.0.0.1,49843

however

  • JDBC Connection String: jdbc:microsoft:sqlserver://10.0.0.1:49843;DatabaseName=DATABASE

Getting list of parameter names inside python function

import inspect

def func(a,b,c=5):
    pass

inspect.getargspec(func)  # inspect.signature(func) in Python 3

(['a', 'b', 'c'], None, None, (5,))

Difference between F5, Ctrl + F5 and click on refresh button?

I did small research regarding this topic and found different behavior for the browsers:

enter image description here

See my blog post "Behind refresh button" for more details.

Set form backcolor to custom color

If you want to set the form's back color to some arbitrary RGB value, you can do this:

this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish

Case objects vs Enumerations in Scala

I prefer case objects (it's a matter of personal preference). To cope with the problems inherent to that approach (parse string and iterate over all elements), I've added a few lines that are not perfect, but are effective.

I'm pasting you the code here expecting it could be useful, and also that others could improve it.

/**
 * Enum for Genre. It contains the type, objects, elements set and parse method.
 *
 * This approach supports:
 *
 * - Pattern matching
 * - Parse from name
 * - Get all elements
 */
object Genre {
  sealed trait Genre

  case object MALE extends Genre
  case object FEMALE extends Genre

  val elements = Set (MALE, FEMALE) // You have to take care this set matches all objects

  def apply (code: String) =
    if (MALE.toString == code) MALE
    else if (FEMALE.toString == code) FEMALE
    else throw new IllegalArgumentException
}

/**
 * Enum usage (and tests).
 */
object GenreTest extends App {
  import Genre._

  val m1 = MALE
  val m2 = Genre ("MALE")

  assert (m1 == m2)
  assert (m1.toString == "MALE")

  val f1 = FEMALE
  val f2 = Genre ("FEMALE")

  assert (f1 == f2)
  assert (f1.toString == "FEMALE")

  try {
    Genre (null)
    assert (false)
  }
  catch {
    case e: IllegalArgumentException => assert (true)
  }

  try {
    Genre ("male")
    assert (false)
  }
  catch {
    case e: IllegalArgumentException => assert (true)
  }

  Genre.elements.foreach { println }
}

Bootstrap 3: Text overlay on image

Is this what you're after?

http://jsfiddle.net/dCNXU/1/

I added :text-align:center to the div and image

Google Chrome Full Black Screen

Disable Nvidia's nView Desktop Manager and the problem should resolve.

Convert boolean to int in Java

int val = b? 1 : 0;

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

Single Result from Database by using mySQLi

If you assume just one result you could do this as in Edwin suggested by using specific users id.

$someUserId = 'abc123';

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);

$stmt->execute();

$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.

OR as "Your Common Sense" which selects just one user.

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");

$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

Nothing really different from the above except for PHP v.5

How can I add a line to a file in a shell script?

As far as I understand, you want to prepend column1, column2, column3 to your existing one, two, three.

I would use ed in place of sed, since sed write on the standard output and not in the file.

The command:

printf '0a\ncolumn1, column2, column3\n.\nw\n' | ed testfile.csv

should do the work.

perl -i is worth taking a look as well.

replace String with another in java

Try this: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29

String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");

System.out.println(r);

This would print out "Brother How are you!"

length and length() in Java

Let me first highlight three different ways for similar purpose.

length -- arrays (int[], double[], String[]) -- to know the length of the arrays

length() -- String related Object (String, StringBuilder, etc) -- to know the length of the String

size() -- Collection Object (ArrayList, Set, etc) -- to know the size of the Collection

Now forget about length() consider just length and size().

length is not a method, so it completely makes sense that it will not work on objects. It only works on arrays.
size() its name describes it better and as it is a method, it will be used in the case of those objects who work with collection (collection frameworks) as I said up there.

Now come to length():
String is not a primitive array (so we can't use .length) and also not a Collection (so we cant use .size()) that's why we also need a different one which is length() (keep the differences and serve the purpose).

As answer to Why?
I find it useful, easy to remember and use and friendly.

Generate a random number in the range 1 - 10

The correct version of hythlodayr's answer.

-- ERROR:  operator does not exist: double precision % integer
-- LINE 1: select (trunc(random() * 10) % 10) + 1

The output from trunc has to be converted to INTEGER. But it can be done without trunc. So it turns out to be simple.

select (random() * 9)::INTEGER + 1

Generates an INTEGER output in range [1, 10] i.e. both 1 & 10 inclusive.

For any number (floats), see user80168's answer. i.e just don't convert it to INTEGER.

How should I import data from CSV into a Postgres table using pgAdmin 3?

You may have a table called 'test'

COPY test(gid, "name", the_geom)
FROM '/home/data/sample.csv'
WITH DELIMITER ','
CSV HEADER

Adding a module (Specifically pymorph) to Spyder (Python IDE)

I faced the same problem when trying to add the seaborn module in Spyder. I installed seaborn into my anaconda directory in ubuntu 14.04. The seaborn module would load if I added the entire anaconda/lib/python2.7/site-packages/ directory which contained the 'seaborn' and seaborn-0.5.1-py2.7.egg-info folders. The problem was this anaconda site-packages folder also contained many other modules which Spyder did not like.

My solution: I created a new directory in my personal Home folder that I named 'spyderlibs' where I placed seaborn and seaborn-0.5.1-py2.7.egg-info folders. Adding my new spyderlib directory in Spyder's PYTHONPATH manager worked!

What is the symbol for whitespace in C?

#include <stdio.h>
main()
{
int c,sp,tb,nl;
sp = 0;
tb = 0;
nl = 0;
while((c = getchar()) != EOF)
{
   switch( c )
{
   case ' ':
        ++sp;
     printf("space:%d\n", sp);
     break;
   case  '\t':
        ++tb;
     printf("tab:%d\n", tb);
     break;
   case '\n':
        ++nl;
     printf("new line:%d\n", nl);
     break;
  }
 }
}

SQL Server using wildcard within IN

  1. I firstly added one off static table with ALL possibilities of my wildcard results (this company has a 4 character nvarchar code as their localities and they wildcard their locals) i.e. they may have 456? which would give them 456[1] to 456[Z] i.e 0-9 & a-z

  2. I had to write a script to pull the current user (declare them) and pull the masks for the declared user.

  3. Create some temporary tables just basic ones to rank the row numbers for this current user

  4. loop through each result (YOUR Or this Or that etc...)

  5. Insert into the test Table.

Here is the script I used:

Drop Table #UserMasks 
Drop Table #TESTUserMasks 

Create Table #TESTUserMasks (
    [User] [Int] NOT NULL,
    [Mask] [Nvarchar](10) NOT NULL)

Create Table #UserMasks (
    [RN] [Int] NOT NULL,
    [Mask] [Nvarchar](10) NOT NULL)

DECLARE @User INT
SET @User = 74054

Insert Into #UserMasks 
select ROW_NUMBER() OVER ( PARTITION BY ProntoUserID ORDER BY Id DESC) AS RN,
       REPLACE(mask,'?','') Mask
from dbo.Access_Masks 
where prontouserid = @User

DECLARE @TopFlag INT
SET @TopFlag = 1

WHILE (@TopFlag <=(select COUNT(*) from #UserMasks))
BEGIN
    Insert Into #TestUserMasks 
    select (@User),Code from dbo.MaskArrayLookupTable 
    where code like (select Mask + '%' from #UserMasks Where RN = @TopFlag)

    SET @TopFlag = @TopFlag + 1
END
GO

select * from #TESTUserMasks

How do I call a specific Java method on a click/submit event of a specific button in JSP?

Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.

You only need to make sure that the button inputs have type="submit" as in <input type="submit"> and <button type="submit"> and not type="button", which only renders a "dead" button purely for onclick stuff and all.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
    <input type="submit" name="button2" value="Button 2" />
    <input type="submit" name="button3" value="Button 3" />
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();

        if (request.getParameter("button1") != null) {
            myClass.method1();
        } else if (request.getParameter("button2") != null) {
            myClass.method2();
        } else if (request.getParameter("button3") != null) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

Alternatively, use <button type="submit"> instead of <input type="submit">, then you can give them all the same name, but an unique value. The value of the <button> won't be used as label, you can just specify that yourself as child.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <button type="submit" name="button" value="button1">Button 1</button>
    <button type="submit" name="button" value="button2">Button 2</button>
    <button type="submit" name="button" value="button3">Button 3</button>
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();
        String button = request.getParameter("button");

        if ("button1".equals(button)) {
            myClass.method1();
        } else if ("button2".equals(button)) {
            myClass.method2();
        } else if ("button3".equals(button)) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

See also:

How do you change the size of figures drawn with matplotlib?

If you've already got the figure created you can quickly do this:

fig = matplotlib.pyplot.gcf()
fig.set_size_inches(18.5, 10.5)
fig.savefig('test2png.png', dpi=100)

To propagate the size change to an existing gui window add forward=True

fig.set_size_inches(18.5, 10.5, forward=True)

When to use static classes in C#

I use static classes as a means to define "extra functionality" that an object of a given type could use under a specific context. Usually they turn out to be utility classes.

Other than that, I think that "Use a static class as a unit of organization for methods not associated with particular objects." describe quite well their intended usage.

Bootstrap Navbar toggle button not working

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

You need the jQuery and Boostrap Javascript files included in your HTML page for the toggle to work. (Make sure you include jQuery before Bootstrap.)

<html>
   <head>
       // stylesheets here
       <link rel="stylesheet" href=""/> 
   </head>
   <body>
      //your html code here

      // js scripts here
      // note jquery tag has to go before boostrap
      <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
   </body>
</html>

How do I get a specific range of numbers from rand()?

Taking the modulo of the result, as the other posters have asserted will give you something that's nearly random, but not perfectly so.

Consider this extreme example, suppose you wanted to simulate a coin toss, returning either 0 or 1. You might do this:

isHeads = ( rand() % 2 ) == 1;

Looks harmless enough, right? Suppose that RAND_MAX is only 3. It's much higher of course, but the point here is that there's a bias when you use a modulus that doesn't evenly divide RAND_MAX. If you want high quality random numbers, you're going to have a problem.

Consider my example. The possible outcomes are:

rand()  freq. rand() % 2
0       1/3   0
1       1/3   1
2       1/3   0

Hence, "tails" will happen twice as often as "heads"!

Mr. Atwood discusses this matter in this Coding Horror Article

If input value is blank, assign a value of "empty" with Javascript

You can do this:

var getValue  = function (input, defaultValue) {
    return input.value || defaultValue;
};

Function or sub to add new row and data to table

I needed this same solution, but if you use the native ListObject.Add() method then you avoid the risk of clashing with any data immediately below the table. The below routine checks the last row of the table, and adds the data in there if it's blank; otherwise it adds a new row to the end of the table:

Sub AddDataRow(tableName As String, values() As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = ActiveWorkbook.Worksheets("Sheet1")
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        For col = 1 To lastRow.Columns.Count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                table.ListRows.Add
                Exit For
            End If
        Next col
    Else
        table.ListRows.Add
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(values) + 1 Then lastRow.Cells(1, col) = values(col - 1)
    Next col
End Sub

To call the function, pass the name of the table and an array of values, one value per column. You can get / set the name of the table from the Design tab of the ribbon, in Excel 2013 at least: enter image description here

Example code for a table with three columns:

Dim x(2)
x(0) = 1
x(1) = "apple"
x(2) = 2
AddDataRow "Table1", x

php: how to get associative array key from numeric index?

Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array. You can create the following function,

    function get_key($array, $index){
      $idx=0;
      while($idx!=$index  && next($array)) $idx++;
      if($idx==$index) return key($array);
      else return '';
    }

How to change the datetime format in pandas

Below is the code worked for me, And we need to be very careful for format. Below link will be definitely useful for knowing your exiting format and changing into desired format(Follow strftime() and strptime() Format Codes on below link):

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior.

data['date_new_format'] = pd.to_datetime(data['date_to_be_changed'] , format='%b-%y')

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

Go to

C:\ drive

or that drive where xampp is installed click on xampp find php and open it , there you find php.ini folder open php.ini file with notepad and find upload_max_filesize and post_max_size in both "up and down find option",change both values to 1000M

Java: how to represent graphs?

A simple representation written by 'Robert Sedgwick' and 'Kevin Wayne' is available at http://algs4.cs.princeton.edu/41graph/Graph.java.html

Explanation copied from the above page.

The Graph class represents an undirected graph of vertices named 0 through V - 1.

It supports the following two primary operations: add an edge to the graph, iterate over all of the vertices adjacent to a vertex. It also provides methods for returning the number of vertices V and the number of edges E. Parallel edges and self-loops are permitted. By convention, a self-loop v-v appears in the adjacency list of v twice and contributes two to the degree of v.

This implementation uses an adjacency-lists representation, which is a vertex-indexed array of Bag objects. All operations take constant time (in the worst case) except iterating over the vertices adjacent to a given vertex, which takes time proportional to the number of such vertices.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

I was getting the same error after adding an unnecessary reference to System.Web.Mvc. I removed all the references I could find, but nothing seemed to work. I finally deleted the project's bin folder and the error went away after a rebuild.

How to exit from Python without traceback?

# Pygame Example  

import pygame, sys  
from pygame.locals import *

pygame.init()  
DISPLAYSURF = pygame.display.set_mode((400, 300))  
pygame.display.set_caption('IBM Emulator')

BLACK = (0, 0, 0)  
GREEN = (0, 255, 0)

fontObj = pygame.font.Font('freesansbold.ttf', 32)  
textSurfaceObj = fontObj.render('IBM PC Emulator', True, GREEN,BLACK)  
textRectObj = textSurfaceObj.get_rect()  
textRectObj = (10, 10)

try:  
    while True: # main loop  
        DISPLAYSURF.fill(BLACK)  
        DISPLAYSURF.blit(textSurfaceObj, textRectObj)  
        for event in pygame.event.get():  
            if event.type == QUIT:  
                pygame.quit()  
                sys.exit()  
        pygame.display.update()  
except SystemExit:  
    pass

What killed my process and why?

In an lsf environment (interactive or otherwise) if the application exceeds memory utilization beyond some preset threshold by the admins on the queue or the resource request in submit to the queue the processes will be killed so other users don't fall victim to a potential run away. It doesn't always send an email when it does so, depending on how its set up.

One solution in this case is to find a queue with larger resources or define larger resource requirements in the submission.

You may also want to review man ulimit

Although I don't remember ulimit resulting in Killed its been a while since I needed that.

Python - abs vs fabs

math.fabs() always returns float, while abs() may return integer.

How can I display a modal dialog in Redux that performs asynchronous actions?

A lot of good solutions and valuable commentaries by known experts from JS community on the topic could be found here. It could be an indicator that it's not that trivial problem as it may seem. I think this is why it could be the source of doubts and uncertainty on the issue.

Fundamental problem here is that in React you're only allowed to mount component to its parent, which is not always the desired behavior. But how to address this issue?

I propose the solution, addressed to fix this issue. More detailed problem definition, src and examples can be found here: https://github.com/fckt/react-layer-stack#rationale

Rationale

react/react-dom comes comes with 2 basic assumptions/ideas:

  • every UI is hierarchical naturally. This why we have the idea of components which wrap each other
  • react-dom mounts (physically) child component to its parent DOM node by default

The problem is that sometimes the second property isn't what you want in your case. Sometimes you want to mount your component into different physical DOM node and hold logical connection between parent and child at the same time.

Canonical example is Tooltip-like component: at some point of development process you could find that you need to add some description for your UI element: it'll render in fixed layer and should know its coordinates (which are that UI element coord or mouse coords) and at the same time it needs information whether it needs to be shown right now or not, its content and some context from parent components. This example shows that sometimes logical hierarchy isn't match with the physical DOM hierarchy.

Take a look at https://github.com/fckt/react-layer-stack/blob/master/README.md#real-world-usage-example to see the concrete example which is answer to your question:

import { Layer, LayerContext } from 'react-layer-stack'
// ... for each `object` in array of `objects`
  const modalId = 'DeleteObjectConfirmation' + objects[rowIndex].id
  return (
    <Cell {...props}>
        // the layer definition. The content will show up in the LayerStackMountPoint when `show(modalId)` be fired in LayerContext
        <Layer use={[objects[rowIndex], rowIndex]} id={modalId}> {({
            hideMe, // alias for `hide(modalId)`
            index } // useful to know to set zIndex, for example
            , e) => // access to the arguments (click event data in this example)
          <Modal onClick={ hideMe } zIndex={(index + 1) * 1000}>
            <ConfirmationDialog
              title={ 'Delete' }
              message={ "You're about to delete to " + '"' + objects[rowIndex].name + '"' }
              confirmButton={ <Button type="primary">DELETE</Button> }
              onConfirm={ this.handleDeleteObject.bind(this, objects[rowIndex].name, hideMe) } // hide after confirmation
              close={ hideMe } />
          </Modal> }
        </Layer>

        // this is the toggle for Layer with `id === modalId` can be defined everywhere in the components tree
        <LayerContext id={ modalId }> {({showMe}) => // showMe is alias for `show(modalId)`
          <div style={styles.iconOverlay} onClick={ (e) => showMe(e) }> // additional arguments can be passed (like event)
            <Icon type="trash" />
          </div> }
        </LayerContext>
    </Cell>)
// ...

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

There is a new library called ipyvolume that may do what you want, the documentation shows live demos. The current version doesn't do meshes and lines, but master from the git repo does (as will version 0.4). (Disclaimer: I'm the author)

How to join on multiple columns in Pyspark?

An alternative approach would be:

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x4"))

df = df1.join(df2, ['x1','x2'])
df.show()

which outputs:

+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
|  2|  b|3.0|0.0|
+---+---+---+---+

With the main advantage being that the columns on which the tables are joined are not duplicated in the output, reducing the risk of encountering errors such as org.apache.spark.sql.AnalysisException: Reference 'x1' is ambiguous, could be: x1#50L, x1#57L.


Whenever the columns in the two tables have different names, (let's say in the example above, df2 has the columns y1, y2 and y4), you could use the following syntax:

df = df1.join(df2.withColumnRenamed('y1','x1').withColumnRenamed('y2','x2'), ['x1','x2'])

How can I connect to MySQL on a WAMP server?

Just Change the Connection mysql string to 127.0.0.1 and it will work

continuing execution after an exception is thrown in java

Try this:

try
{
    throw new InvalidEmployeeTypeException();
    input.nextLine();
}
catch(InvalidEmployeeTypeException ex)
{
      //do error handling
}

continue;

How to create a directive with a dynamic template in AngularJS?

You should move your switch into the template by using the 'ng-switch' directive:

module.directive('testForm', function() {
    return {
        restrict: 'E',
        controllerAs: 'form',
        controller: function ($scope) {
            console.log("Form controller initialization");
            var self = this;
            this.fields = {};
            this.addField = function(field) {
                console.log("New field: ", field);
                self.fields[field.name] = field;
            };
        }
    }
});

module.directive('formField', function () {
    return {
        require: "^testForm",
        template:
            '<div ng-switch="field.fieldType">' +
            '    <span>{{title}}:</span>' +
            '    <input' +
            '        ng-switch-when="text"' +
            '        name="{{field.name}}"' +
            '        type="text"' +
            '        ng-model="field.value"' +
            '    />' +
            '    <select' +
            '        ng-switch-when="select"' +
            '        name="{{field.name}}"' +
            '        ng-model="field.value"' +
            '        ng-options="option for option in options">' +
            '        <option value=""></option>' +
            '    </select>' +
            '</div>',
        restrict: 'E',
        replace: true,
        scope: {
            fieldType: "@",
            title: "@",
            name: "@",
            value: "@",
            options: "=",
        },
        link: function($scope, $element, $attrs, form) {
            $scope.field = $scope;
            form.addField($scope);
        }
    };
});

It can be use like this:

<test-form>
    <div>
        User '{{!form.fields.email.value}}' will be a {{!form.fields.role.value}}
    </div>
    <form-field title="Email" name="email" field-type="text" value="[email protected]"></form-field>
    <form-field title="Role" name="role" field-type="select" options="['Cook', 'Eater']"></form-field>
    <form-field title="Sex" name="sex" field-type="select" options="['Awesome', 'So-so', 'awful']"></form-field>
</test-form>

How to use BeanUtils.copyProperties?

As you can see in the below source code, BeanUtils.copyProperties internally uses reflection and there's additional internal cache lookup steps as well which is going to add cost wrt performance

 private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
                @Nullable String... ignoreProperties) throws BeansException {

            Assert.notNull(source, "Source must not be null");
            Assert.notNull(target, "Target must not be null");

            Class<?> actualEditable = target.getClass();
            if (editable != null) {
                if (!editable.isInstance(target)) {
                    throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
                            "] not assignable to Editable class [" + editable.getName() + "]");
                }
                actualEditable = editable;
            }
            **PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);**
            List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

            for (PropertyDescriptor targetPd : targetPds) {
                Method writeMethod = targetPd.getWriteMethod();
                if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
                    PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                    if (sourcePd != null) {
                        Method readMethod = sourcePd.getReadMethod();
                        if (readMethod != null &&
                                ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                            try {
                                if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                    readMethod.setAccessible(true);
                                }
                                Object value = readMethod.invoke(source);
                                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                    writeMethod.setAccessible(true);
                                }
                                writeMethod.invoke(target, value);
                            }
                            catch (Throwable ex) {
                                throw new FatalBeanException(
                                        "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                            }
                        }
                    }
                }
            }
        }

So it's better to use plain setters given the cost reflection

Entity framework code-first null foreign key

I prefer this (below):

public class User
{
    public int Id { get; set; }
    public int? CountryId { get; set; }
    [ForeignKey("CountryId")]
    public virtual Country Country { get; set; }
}

Because EF was creating 2 foreign keys in the database table: CountryId, and CountryId1, but the code above fixed that.

Search all tables, all columns for a specific value SQL Server

The below Query works but very slow... copied from vyaskn.tripod.com

Declare @SearchStr nvarchar(100)

SET  @SearchStr='Search String' BEGIN

CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128),
 @SearchStr2 nvarchar(110)  SET  @TableName = ''    SET @SearchStr2 =
 QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL    
BEGIN       
  SET @ColumnName = ''      
  SET @TableName =  (
    SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' +
    QUOTENAME(TABLE_NAME)) FROM INFORMATION_SCHEMA.TABLES 
    WHERE
    TABLE_TYPE = 'BASE TABLE'
    AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
    AND OBJECTPROPERTY(
      OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)),
        'IsMSShipped') = 0)

  WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)      
  BEGIN
    SET @ColumnName = (
      SELECT MIN(QUOTENAME(COLUMN_NAME))
      FROM INFORMATION_SCHEMA.COLUMNS
      WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
        AND TABLE_NAME = PARSENAME(@TableName, 1)
      AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
      AND QUOTENAME(COLUMN_NAME) > @ColumnName)
      IF @ColumnName IS NOT NULL            
      BEGIN
      INSERT INTO #Results
      EXEC
      (
        'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + 
          ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
        ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
      )             
      END       
    END     
  END

  SELECT ColumnName, ColumnValue FROM #Results END

How can I get date in application run by node.js?

Node.js is a server side JS platform build on V8 which is chrome java-script runtime.

It leverages the use of java-script on servers too.

You can use JS Date() function or Date class.

Removing special characters VBA Excel

Here is how removed special characters.

I simply applied regex

Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object    
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters

' Configure the regex object
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
End With

' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)

How to work with string fields in a C struct?

I think this solution uses less code and is easy to understand even for newbie.

For string field in struct, you can use pointer and reassigning the string to that pointer will be straightforward and simpler.

Define definition of struct:

typedef struct {
  int number;
  char *name;
  char *address;
  char *birthdate;
  char gender;
} Patient;

Initialize variable with type of that struct:

Patient patient;
patient.number = 12345;
patient.address = "123/123 some road Rd.";
patient.birthdate = "2020/12/12";
patient.gender = "M";

It is that simple. Hope this answer helps many developers.

Install opencv for Python 3.3

Here a solution for (I believe as seen by 'cp34' on the link below) Python 3.4.

Go to to http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv.

Download the appropriate .whl.

Go to the directory where the .whl is saved.

Use pip to install the .whl. e.g. pip install opencv_python-3.0.0-cp34-none-win_amd64.whl

Then just use import cv2.

When using SASS how can I import a file from a different directory?

Importing a .scss file that has a nested import with a different relative position won't work. the top proposed answer (using a lot of ../) is just a dirty hack that will work as long as you added enough ../ to reach the root of your project's deployment OS.

  1. Add the target SCSS path as a search target for SCSS compiler. This can be achieved by adding the stylesheets folder into the scss config file, this is function of the framework you are using,

use :load_paths at config.rd for compass-based frameworks (Ex. rails)

use the following code at scss-config.json for fourseven/meteor-scss

{
  "includePaths": [
    "{}/node_modules/ionicons/dist/scss/"
  ]
}
  1. Use absolute paths (vs. relative paths).

Example, with fourseven/meteor-scss, you can use {} to highlight top level of your project as per the following examplI

@import "{}/node_modules/module-name/stylesheet";

Built in Python hash() function

The value of PYTHONHASHSEED might be used to initialize the hash values.

Try:

PYTHONHASHSEED python -c 'print(hash('http://stackoverflow.com'))'

Download files from server php

Here is the code that will not download courpt files

$filename = "myfile.jpg";
$file = "/uploads/images/".$filename;

header('Content-type: application/octet-stream');
header("Content-Type: ".mime_content_type($file));
header("Content-Disposition: attachment; filename=".$filename);
while (ob_get_level()) {
    ob_end_clean();
}
readfile($file);

I have included mime_content_type which will return content type of file .

To prevent from corrupt file download i have added ob_get_level() and ob_end_clean();

Qt. get part of QString

If you do not need to modify the substring, then you can use QStringRef. The QStringRef class is a read only wrapper around an existing QString that references a substring within the existing string. This gives much better performance than creating a new QString object to contain the sub-string. E.g.

QString myString("This is a string");
QStringRef subString(&myString, 5, 2); // subString contains "is"

If you do need to modify the substring, then left(), mid() and right() will do what you need...

QString myString("This is a string");
QString subString = myString.mid(5,2); // subString contains "is"
subString.append("n't"); // subString contains "isn't"

Filtering a spark dataframe based on date

I find the most readable way to express this is using a sql expression:

df.filter("my_date < date'2015-01-01'")

we can verify this works correctly by looking at the physical plan from .explain()

+- *(1) Filter (isnotnull(my_date#22) && (my_date#22 < 16436))

Difference between del, remove, and pop on lists

The remove operation on a list is given a value to remove. It searches the list to find an item with that value and deletes the first matching item it finds. It is an error if there is no matching item, raises a ValueError.

>>> x = [1, 0, 0, 0, 3, 4, 5]
>>> x.remove(4)
>>> x
[1, 0, 0, 0, 3, 5]
>>> del x[7]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[7]
IndexError: list assignment index out of range

The del statement can be used to delete an entire list. If you have a specific list item as your argument to del (e.g. listname[7] to specifically reference the 8th item in the list), it'll just delete that item. It is even possible to delete a "slice" from a list. It is an error if there index out of range, raises a IndexError.

>>> x = [1, 2, 3, 4]
>>> del x[3]
>>> x
[1, 2, 3]
>>> del x[4]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[4]
IndexError: list assignment index out of range

The usual use of pop is to delete the last item from a list as you use the list as a stack. Unlike del, pop returns the value that it popped off the list. You can optionally give an index value to pop and pop from other than the end of the list (e.g listname.pop(0) will delete the first item from the list and return that first item as its result). You can use this to make the list behave like a queue, but there are library routines available that can provide queue operations with better performance than pop(0) does. It is an error if there index out of range, raises a IndexError.

>>> x = [1, 2, 3] 
>>> x.pop(2) 
3 
>>> x 
[1, 2]
>>> x.pop(4)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    x.pop(4)
IndexError: pop index out of range

See collections.deque for more details.

String escape into XML

Using a third-party library (Newtonsoft.Json) as alternative:

public static string XmlEscape(string unescaped)
{
    if (unescaped == null) return null;
    return JsonConvert.SerializeObject(unescaped); ;
}

public static string XmlUnescape(string escaped)
{
    if (escaped == null) return null;
    return JsonConvert.DeserializeObject(escaped, typeof(string)).ToString();
}

Examples of escaped string:

a<b ==> "a&lt;b"

<foo></foo> ==> "foo&gt;&lt;/foo&gt;"

NOTE: In newer versions, the code written above may not work with escaping, so you need to specify how the strings will be escaped:

public static string XmlEscape(string unescaped)
{
    if (unescaped == null) return null;
    return JsonConvert.SerializeObject(unescaped, new JsonSerializerSettings()
    {
        StringEscapeHandling = StringEscapeHandling.EscapeHtml
    });
}

Examples of escaped string:

a<b ==> "a\u003cb"

<foo></foo> ==> "\u003cfoo\u003e\u003c/foo\u003e"

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

If you have desired permissions saved to string then do

s = '660'
os.chmod(file_path, int(s, base=8))

Error message Strict standards: Non-static method should not be called statically in php

Your methods are missing the static keyword. Change

function getInstanceByName($name=''){

to

public static function getInstanceByName($name=''){

if you want to call them statically.

Note that static methods (and Singletons) are death to testability.

Also note that you are doing way too much work in the constructor, especially all that querying shouldn't be in there. All your constructor is supposed to do is set the object into a valid state. If you have to have data from outside the class to do that consider injecting it instead of pulling it. Also note that constructors cannot return anything. They will always return void so all these return false statements do nothing but end the construction.

How to get a JavaScript object's class?

getClass() function using constructor.prototype.name

I found a way to access the class that is much cleaner than some of the solutions above; here it is.

function getClass(obj) {

   // if the type is not an object return the type
   if((let type = typeof obj) !== 'object') return type; 
    
   //otherwise, access the class using obj.constructor.name
   else return obj.constructor.name;   
}

How it works

the constructor has a property called name accessing that will give you the class name.

cleaner version of the code:

function getClass(obj) {

   // if the type is not an object return the type
   let type = typeof obj
   if((type !== 'object')) { 
      return type; 
   } else { //otherwise, access the class using obj.constructor.name
      return obj.constructor.name; 
   }   
}

How can I find last row that contains data in a specific column?

How about:

Function GetLastRow(strSheet, strColumn) As Long
    Dim MyRange As Range

    Set MyRange = Worksheets(strSheet).Range(strColumn & "1")
    GetLastRow = Cells(Rows.Count, MyRange.Column).End(xlUp).Row
End Function

Regarding a comment, this will return the row number of the last cell even when only a single cell in the last row has data:

Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

Remove first 4 characters of a string with PHP

$num = "+918883967576";

$str = substr($num, 3);

echo $str;

Output:8883967576

How can I remove a commit on GitHub?

You need to know your commit hash from the commit you want to revert to. You can get it from a GitHub URL like: https://github.com/your-organization/your-project/commits/master

Let's say the hash from the commit (where you want to go back to) is "99fb454" (long version "99fb45413eb9ca4b3063e07b40402b136a8cf264"), then all you have to do is:

git reset --hard 99fb45413eb9ca4b3063e07b40402b136a8cf264
git push --force

checking for typeof error in JS

var myError = new Error('foo');
myError instanceof Error // true
var myString = "Whatever";
myString instanceof Error // false

Only problem with this is

myError instanceof Object // true

An alternative to this would be to use the constructor property.

myError.constructor === Object // false
myError.constructor === String // false
myError.constructor === Boolean // false
myError.constructor === Symbol // false
myError.constructor === Function // false
myError.constructor === Error // true

Although it should be noted that this match is very specific, for example:

myError.constructor === TypeError // false

How to get tf.exe (TFS command line client)?

In Visual Studio 2017 & 2019, it can be found here :

-Replace {YEAR} by the appropriate year ("2017", "2019").

-Replace {EDITION} by the appropriate edition name ("Enterprise", "Professional", or "Community")

C:\Program Files (x86)\Microsoft Visual Studio\{YEAR}\{EDITION}\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\tf.exe

Replace String in all files in Eclipse

  • "Search"->"File"
  • Enter text, file pattern and projects
  • "Replace"
  • Enter new text

Voilà...

How to create an email form that can send email using html

As the others said, you can't. You can find good examples of HTML-php forms on the web, here's a very useful link that combines HTML with javascript for validation and php for sending the email.

Please check the full article (includes zip example) in the source: http://www.html-form-guide.com/contact-form/php-email-contact-form.html

HTML:

<form method="post" name="contact_form"
action="contact-form-handler.php">
    Your Name:
    <input type="text" name="name">
    Email Address:
    <input type="text" name="email">
    Message:
    <textarea name="message"></textarea>
    <input type="submit" value="Submit">
</form>

JS:

<script language="JavaScript">
var frmvalidator  = new Validator("contactform");
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email",
  "Please enter a valid email address");
</script>

PHP:

<?php
$errors = '';
$myemail = '[email protected]';//<-----Put Your email address here.
if(empty($_POST['name'])  ||
   empty($_POST['email']) ||
   empty($_POST['message']))
{
    $errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
    $errors .= "\n Error: Invalid email address";
}

if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

Drawing a simple line graph in Java

There exist many open source projects that handle all the drawing of line charts for you with a couple of lines of code. Here's how you can draw a line chart from data in a couple text (CSV) file with the XChart library. Disclaimer: I'm the lead developer of the project.

In this example, two text files exist in ./CSV/CSVChartRows/. Notice that each row in the files represents a data point to be plotted and that each file represents a different series. series1 contains x, y, and error bar data, whereas series2 contains just x and y, data.

series1.csv

1,12,1.4
2,34,1.12
3,56,1.21
4,47,1.5

series2.csv

1,56
2,34
3,12
4,26

Source Code

public class CSVChartRows {

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

    // import chart from a folder containing CSV files
    XYChart chart = CSVImporter.getChartFromCSVDir("./CSV/CSVChartRows/", DataOrientation.Rows, 600, 400);

    // Show it
    new SwingWrapper(chart).displayChart();
  }
}

Resulting Plot

enter image description here

Select all text inside EditText when it gets focus

editText.setSelectAllOnFocus(true);

This works if you want to do it programatically.

How to add double quotes to a string that is inside a variable?

If you want to add double quotes to a string that contains dynamic values also. For the same in place of CodeId[i] and CodeName[i] you can put your dynamic values.

data = "Test ID=" + "\"" + CodeId[i] + "\"" + " Name=" + "\"" + CodeName[i] + "\"" + " Type=\"Test\";

Html/PHP - Form - Input as array

Simply add [] to those names like

 <input type="text" class="form-control" placeholder="Titel" name="levels[level][]">
 <input type="text" class="form-control" placeholder="Titel" name="levels[build_time][]">

Take that template and then you can add those even using a loop.

Then you can add those dynamically as much as you want, without having to provide an index. PHP will pick them up just like your expected scenario example.

Edit

Sorry I had braces in the wrong place, which would make every new value as a new array element. Use the updated code now and this will give you the following array structure

levels > level (Array)
levels > build_time (Array)

Same index on both sub arrays will give you your pair. For example

echo $levels["level"][5];
echo $levels["build_time"][5];

Evenly distributing n points on a sphere

In this example code node[k] is just the kth node. You are generating an array N points and node[k] is the kth (from 0 to N-1). If that is all that is confusing you, hopefully you can use that now.

(in other words, k is an array of size N that is defined before the code fragment starts, and which contains a list of the points).

Alternatively, building on the other answer here (and using Python):

> cat ll.py
from math import asin
nx = 4; ny = 5
for x in range(nx):
    lon = 360 * ((x+0.5) / nx)
    for y in range(ny):                                                         
        midpt = (y+0.5) / ny                                                    
        lat = 180 * asin(2*((y+0.5)/ny-0.5))                                    
        print lon,lat                                                           
> python2.7 ll.py                                                      
45.0 -166.91313924                                                              
45.0 -74.0730322921                                                             
45.0 0.0                                                                        
45.0 74.0730322921                                                              
45.0 166.91313924                                                               
135.0 -166.91313924                                                             
135.0 -74.0730322921                                                            
135.0 0.0                                                                       
135.0 74.0730322921                                                             
135.0 166.91313924                                                              
225.0 -166.91313924                                                             
225.0 -74.0730322921                                                            
225.0 0.0                                                                       
225.0 74.0730322921                                                             
225.0 166.91313924
315.0 -166.91313924
315.0 -74.0730322921
315.0 0.0
315.0 74.0730322921
315.0 166.91313924

If you plot that, you'll see that the vertical spacing is larger near the poles so that each point is situated in about the same total area of space (near the poles there's less space "horizontally", so it gives more "vertically").

This isn't the same as all points having about the same distance to their neighbours (which is what I think your links are talking about), but it may be sufficient for what you want and improves on simply making a uniform lat/lon grid.

how to loop through each row of dataFrame in pyspark

Give A Try Like this

    result = spark.createDataFrame([('SpeciesId','int'), ('SpeciesName','string')],["col_name", "data_type"]); 
    for f in result.collect(): 
        print (f.col_name)

When is the init() function run?

Something to add to this (which I would've added as a comment but the time of writing this post I'd not yet enough reputation)

Having multiple inits in the same package I've not yet found any guaranteed way to know what order in which they will be run. For example I have:

package config
    - config.go
    - router.go

Both config.go and router.go contain init() functions, but when running router.go's function ran first (which caused my app to panic).

If you're in a situation where you have multiple files, each with its own init() function be very aware that you aren't guaranteed to get one before the other. It is better to use a variable assignment as OneToOne shows in his example. Best part is: This variable declaration will happen before ALL init() functions in the package.

For example

config.go:

var ConfigSuccess = configureApplication()

func init() {
    doSomething()
}

func configureApplication() bool {
    l4g.Info("Configuring application...")
    if valid := loadCommandLineFlags(); !valid {
        l4g.Critical("Failed to load Command Line Flags")
        return false
    }
    return true
}

router.go:

func init() {
    var (
        rwd string
        tmp string
        ok  bool
    )
    if metapath, ok := Config["fs"]["metapath"].(string); ok {
        var err error
        Conn, err = services.NewConnection(metapath + "/metadata.db")
        if err != nil {
            panic(err)
        }
    }
}

regardless of whether var ConfigSuccess = configureApplication() exists in router.go or config.go, it will be run before EITHER init() is run.

Visual Studio: LINK : fatal error LNK1181: cannot open input file

I created a bin directory at the project_dir level, then created a release/debug directory inside the bin folder, which solved the problem for me.

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

This is how I did it and it seems to work pretty well.

In you webpack.config.js file add the following:

devServer: {
    inline:true,
    port: 8008
  },

Obviously you can use any port that is not conflicting with another. I mention the conflict issue only because I spent about 4 hrs. fighting an issue only to discover that my services were running on the same port.

JavaScript or jQuery browser back button click detector

Found this to work well cross browser and mobile back_button_override.js .

(Added a timer for safari 5.0)

// managage back button click (and backspace)
var count = 0; // needed for safari
window.onload = function () { 
    if (typeof history.pushState === "function") { 
        history.pushState("back", null, null);          
        window.onpopstate = function () { 
            history.pushState('back', null, null);              
            if(count == 1){window.location = 'your url';}
         }; 
     }
 }  
setTimeout(function(){count = 1;},200);

How to export a Hive table into a CSV file?

There are ways to change the default delimiter, as shown by other answers.

There are also ways to convert the raw output to csv with some bash scripting. There are 3 delimiters to consider though, not just \001. Things get a bit more complicated when your hive table has maps.

I wrote a bash script that can handle all 3 default delimiters (\001 \002 and \003) from hive and output a csv. The script and some more info are here:

Hive Default Delimiters to CSV

Hive's default delimiters are

Row Delimiter => Control-A ('\001')
Collection Item Delimiter => Control-B ('\002')
Map Key Delimiter => Control-C ('\003')

There are ways to change these delimiters when exporting tables but sometimes you might still get stuck needing to convert this to csv.

Here's a quick bash script that can handle a DB export that's segmented in multiple files and has the default delimiters. It will output a single CSV file.

It is assumed that the segments all have the naming convention 000*_0

INDIRECTORY="path/to/input/directory"
for f in $INDIRECTORY/000*_0; do 
  echo "Processing $f file.."; 
  cat -v $f | 
      LC_ALL=C sed -e "s/^/\"/g" | 
      LC_ALL=C sed -e "s/\^A/\",\"/g" | 
      LC_ALL=C sed -e "s/\^C\^B/\"\":\"\"\"\",\"\"/g" | 
      LC_ALL=C sed -e "s/\^B/\"\",\"\"/g" |  
      LC_ALL=C sed -e "s/\^C/\"\":\"\"/g" | 
      LC_ALL=C sed -e "s/$/\"/g" > $f-temp
done
echo "you,can,echo,your,header,here,if,you,like" > $INDIRECTORY/final_output.csv
cat $INDIRECTORY/*-temp >> $INDIRECTORY/final_output.csv
rm $INDIRECTORY/*-temp

More explanation on the gist

How to install libusb in Ubuntu

First,

sudo apt-get install libusb-1.0-0-dev

updatedb && locate libusb.h.

Second, replace <libusb.h> with <libusb-1.0/libusb.h>.

update:

don't need to change any file.just add this to your Makefile.

`pkg-config libusb-1.0 --libs --cflags`

its result is that -I/usr/include/libusb-1.0 -lusb-1.0

regular expression for anything but an empty string

You could also use:

public static bool IsWhiteSpace(string s) 
{
    return s.Trim().Length == 0;
}

Default behavior of "git push" without a branch specified

You can change that default behavior in your .gitconfig, for example:

[push]
  default = current

To check the current settings, run:

git config --global --get push.default

What are the complexity guarantees of the standard containers?

I found the nice resource Standard C++ Containers. Probably this is what you all looking for.

VECTOR

Constructors

vector<T> v;              Make an empty vector.                                     O(1)
vector<T> v(n);           Make a vector with N elements.                            O(n)
vector<T> v(n, value);    Make a vector with N elements, initialized to value.      O(n)
vector<T> v(begin, end);  Make a vector and copy the elements from begin to end.    O(n)

Accessors

v[i]          Return (or set) the I'th element.                        O(1)
v.at(i)       Return (or set) the I'th element, with bounds checking.  O(1)
v.size()      Return current number of elements.                       O(1)
v.empty()     Return true if vector is empty.                          O(1)
v.begin()     Return random access iterator to start.                  O(1)
v.end()       Return random access iterator to end.                    O(1)
v.front()     Return the first element.                                O(1)
v.back()      Return the last element.                                 O(1)
v.capacity()  Return maximum number of elements.                       O(1)

Modifiers

v.push_back(value)         Add value to end.                                                O(1) (amortized)
v.insert(iterator, value)  Insert value at the position indexed by iterator.                O(n)
v.pop_back()               Remove value from end.                                           O(1)
v.assign(begin, end)       Clear the container and copy in the elements from begin to end.  O(n)
v.erase(iterator)          Erase value indexed by iterator.                                 O(n)
v.erase(begin, end)        Erase the elements from begin to end.                            O(n)

For other containers, refer to the page.

How to Change Margin of TextView

TextView forgot_pswrd = (TextView) findViewById(R.id.ForgotPasswordText);
forgot_pswrd.setOnTouchListener(this);     
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);
forgot_pswrd.setLayoutParams(llp);

I did this and it worked perfectly. Maybe as you are giving the value in -ve, that's why your code is not working. You just put this code where you are creating the reference of the view.

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

The way you can exclude a destination directory while using the /mir is by making sure the destination directory also exists on the source. I went into my source drive and created blank directories with the same name as on the destination, and then added that directory name to the /xd. It successfully mirrored everything while excluding the directory on the source, thereby leaving the directory on the destination intact.

Print range of numbers on same line

for i in range(10):
    print(i, end = ' ')

You can provide any delimiter to the end field (space, comma etc.)

This is for Python 3

CSS hide scroll bar if not needed

.container {overflow:auto;} will do the trick. If you want to control specific direction, you should set auto for that specific axis. A.E.

.container {overflow-y:auto;} .container {overflow-x:hidden;}

The above code will hide any overflow in the x-axis and generate a scroll-bar when needed on the y-axis.But you have to make sure that you content default height smaller than the container height; if not, the scroll-bar will not be hidden.

Passing parameters to click() & bind() event in jquery?

var someParam = xxxxxxx;

commentbtn.click(function(){

    alert(someParam );
});

What does asterisk * mean in Python?

See Function Definitions in the Language Reference.

If the form *identifier is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form **identifier is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.

Also, see Function Calls.

Assuming that one knows what positional and keyword arguments are, here are some examples:

Example 1:

# Excess keyword argument (python 2) example:
def foo(a, b, c, **args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

foo(a="testa", d="excess", c="testc", b="testb", k="another_excess")

As you can see in the above example, we only have parameters a, b, c in the signature of the foo function. Since d and k are not present, they are put into the args dictionary. The output of the program is:

a = testa
b = testb
c = testc
{'k': 'another_excess', 'd': 'excess'}

Example 2:

# Excess positional argument (python 2) example:
def foo(a, b, c, *args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

foo("testa", "testb", "testc", "excess", "another_excess")

Here, since we're testing positional arguments, the excess ones have to be on the end, and *args packs them into a tuple, so the output of this program is:

a = testa
b = testb
c = testc
('excess', 'another_excess')

You can also unpack a dictionary or a tuple into arguments of a function:

def foo(a,b,c,**args):
    print "a=%s" % (a,)
    print "b=%s" % (b,)
    print "c=%s" % (c,)
    print "args=%s" % (args,)

argdict = dict(a="testa", b="testb", c="testc", excessarg="string")
foo(**argdict)

Prints:

a=testa
b=testb
c=testc
args={'excessarg': 'string'}

And

def foo(a,b,c,*args):
    print "a=%s" % (a,)
    print "b=%s" % (b,)
    print "c=%s" % (c,)
    print "args=%s" % (args,)

argtuple = ("testa","testb","testc","excess")
foo(*argtuple)

Prints:

a=testa
b=testb
c=testc
args=('excess',)

C#: New line and tab characters in strings

    StringBuilder SqlScript = new StringBuilder();

    foreach (var file in lstScripts)
    {
        var input = File.ReadAllText(file.FilePath);
        SqlScript.AppendFormat(input, Environment.NewLine);
    }

http://afzal-gujrat.blogspot.com/

How can I make an "are you sure" prompt in a Windows batchfile?

Here a bit easier:

@echo off
set /p var=Are You Sure?[Y/N]: 
if %var%== Y goto ...
if not %var%== Y exit

or

@echo off
echo Are You Sure?[Y/N]
choice /c YN
if %errorlevel%==1 goto yes
if %errorlevel%==2 goto no
:yes
echo yes
goto :EOF
:no
echo no

Local storage in Angular 2

install

npm install --save @ngx-pwa/local-storage

first of all you need to Install "angular-2-local-storage"

import { LocalStorageService } from 'angular-2-local-storage';

Save into LocalStorage:

localStorage.setItem('key', value);

Get From Local Storage:

localStorage.getItem('key');

How to remove border of drop down list : CSS

select#xyz {
  border:0px;
  outline:0px;
}

Exact solution.

What is the best practice for creating a favicon on a web site?

  1. you can work with this website for generate favin.ico
  2. I recommend use .ico format because the png don't work with method 1 and ico could have more detail!
  3. both method work with all browser but when it's automatically work what you want type a code for it? so i think method 1 is better.

Select top 10 records for each category

If we use SQL Server >= 2005, then we can solve the task with one select only:

declare @t table (
    Id      int ,
    Section int,
    Moment  date
);

insert into @t values
(   1   ,   1   , '2014-01-01'),
(   2   ,   1   , '2014-01-02'),
(   3   ,   1   , '2014-01-03'),
(   4   ,   1   , '2014-01-04'),
(   5   ,   1   , '2014-01-05'),

(   6   ,   2   , '2014-02-06'),
(   7   ,   2   , '2014-02-07'),
(   8   ,   2   , '2014-02-08'),
(   9   ,   2   , '2014-02-09'),
(   10  ,   2   , '2014-02-10'),

(   11  ,   3   , '2014-03-11'),
(   12  ,   3   , '2014-03-12'),
(   13  ,   3   , '2014-03-13'),
(   14  ,   3   , '2014-03-14'),
(   15  ,   3   , '2014-03-15');


-- TWO earliest records in each Section

select top 1 with ties
    Id, Section, Moment 
from
    @t
order by 
    case 
        when row_number() over(partition by Section order by Moment) <= 2 
        then 0 
        else 1 
    end;


-- THREE earliest records in each Section

select top 1 with ties
    Id, Section, Moment 
from
    @t
order by 
    case 
        when row_number() over(partition by Section order by Moment) <= 3 
        then 0 
        else 1 
    end;


-- three LATEST records in each Section

select top 1 with ties
    Id, Section, Moment 
from
    @t
order by 
    case 
        when row_number() over(partition by Section order by Moment desc) <= 3 
        then 0 
        else 1 
    end;

Embedding Windows Media Player for all browsers

I found a good article about using the WMP with Firefox on MSDN.

Based on MSDN's article and after doing some trials and errors, I found using JavaScript is better than using conditional comments or nested "EMBED/OBJECT" tags.

I made a JS function that generate WMP object based on given arguments:

<script type="text/javascript">
    function generateWindowsMediaPlayer(
        holderId,   // String
        height,     // Number
        width,      // Number
        videoUrl    // String
        // you can declare more arguments for more flexibility
        ) {
        var holder = document.getElementById(holderId);

        var player = '<object ';
        player += 'height="' + height.toString() + '" ';
        player += 'width="' + width.toString() + '" ';

        videoUrl = encodeURI(videoUrl); // Encode for special characters

        if (navigator.userAgent.indexOf("MSIE") < 0) {
            // Chrome, Firefox, Opera, Safari
            //player += 'type="application/x-ms-wmp" '; //Old Edition
            player += 'type="video/x-ms-wmp" '; //New Edition, suggested by MNRSullivan (Read Comments)
            player += 'data="' + videoUrl + '" >';
        }
        else {
            // Internet Explorer
            player += 'classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" >';
            player += '<param name="url" value="' + videoUrl + '" />';
        }

        player += '<param name="autoStart" value="false" />';
        player += '<param name="playCount" value="1" />';
        player += '</object>';

        holder.innerHTML = player;
    }
</script>

Then I used that function by writing some markups and inline JS like these:

<div id='wmpHolder'></div>

<script type="text/javascript">        
    window.addEventListener('load', generateWindowsMediaPlayer('wmpHolder', 240, 320, 'http://mysite.com/path/video.ext'));
</script>

You can use jQuery.ready instead of window load event to making the codes more backward-compatible and cross-browser.

I tested the codes over IE 9-10, Chrome 27, Firefox 21, Opera 12 and Safari 5, on Windows 7/8.

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

This might seem stupid to some people but it got me. I was getting this error and the problem for me was that I was trying to use static cells but then dynamically add more stuff. If you are calling this method your cells need to be dynamic prototypes. Select the cell in storyboard and under the Attributes inspector, the very first thing says 'Content' and you should select dynamic prototypes not static.

Reading a file line by line in Go

EDIT: As of go1.1, the idiomatic solution is to use bufio.Scanner

I wrote up a way to easily read each line from a file. The Readln(*bufio.Reader) function returns a line (sans \n) from the underlying bufio.Reader struct.

// Readln returns a single line (without the ending \n)
// from the input buffered reader.
// An error is returned iff there is an error with the
// buffered reader.
func Readln(r *bufio.Reader) (string, error) {
  var (isPrefix bool = true
       err error = nil
       line, ln []byte
      )
  for isPrefix && err == nil {
      line, isPrefix, err = r.ReadLine()
      ln = append(ln, line...)
  }
  return string(ln),err
}

You can use Readln to read every line from a file. The following code reads every line in a file and outputs each line to stdout.

f, err := os.Open(fi)
if err != nil {
    fmt.Printf("error opening file: %v\n",err)
    os.Exit(1)
}
r := bufio.NewReader(f)
s, e := Readln(r)
for e == nil {
    fmt.Println(s)
    s,e = Readln(r)
}

Cheers!

Is background-color:none valid CSS?

.class {
    background-color:none;
}

This is not a valid property. W3C validator will display following error:

Value Error : background-color none is not a background-color value : none

transparent may have been selected as better term instead of 0 or none values during the development of specification of CSS.

Regular Expression to match only alphabetic characters

If you need to include non-ASCII alphabetic characters, and if your regex flavor supports Unicode, then

\A\pL+\z

would be the correct regex.

Some regex engines don't support this Unicode syntax but allow the \w alphanumeric shorthand to also match non-ASCII characters. In that case, you can get all alphabetics by subtracting digits and underscores from \w like this:

\A[^\W\d_]+\z

\A matches at the start of the string, \z at the end of the string (^ and $ also match at the start/end of lines in some languages like Ruby, or if certain regex options are set).

Initialize static variables in C++ class?

Static member variables must be declared in the class and then defined outside of it!

There's no workaround, just put their actual definition in a source file.


From your description it smells like you're not using static variables the right way. If they never change you should use constant variable instead, but your description is too generic to say something more.

Static member variables always hold the same value for any instance of your class: if you change a static variable of one object, it will change also for all the other objects (and in fact you can also access them without an instance of the class - ie: an object).

How to do a Jquery Callback after form submit?

I just did this -

 $("#myform").bind('ajax:complete', function() {

         // tasks to do 


   });

And things worked perfectly .

See this api documentation for more specific details.

How to shutdown my Jenkins safely?

The full list of commands is available at http://your-jenkins/cli

The command for a clean shutdown is http://your-jenkins/safe-shutdown

You may also want to use http://your-jenkins/safe-restart

How to replace four spaces with a tab in Sublime Text 2?

create a keybinding for quickest way

{ "keys": ["super+alt+t"], "command": "unexpand_tabs", "args": { "set_translate_tabs": true } }

add this to Preferences > Key Bindings (user) when you press super+alt+t it will convert spaces to tabs

How to extract base URL from a string in JavaScript?

Instead of having to account for window.location.protocol and window.location.origin, and possibly missing a specified port number, etc., just grab everything up to the 3rd "/":

// get nth occurrence of a character c in the calling string
String.prototype.nthIndex = function (n, c) {
    var index = -1;
    while (n-- > 0) {
        index++;
        if (this.substring(index) == "") return -1; // don't run off the end
        index += this.substring(index).indexOf(c);
    }
    return index;
}

// get the base URL of the current page by taking everything up to the third "/" in the URL
function getBaseURL() {
    return document.URL.substring(0, document.URL.nthIndex(3,"/") + 1);
}

MySQL root access from all hosts

Update the bind-address = 0.0.0.0 in the /etc/mysql/mysql.conf.d/mysqld.cnf and from the mysql command line allow the root user to connect from any Ip.

Below was the only commands worked for mysql-8.0 as other were failing with error syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY 'abcd'' at line 1

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
UPDATE mysql.user SET host='%' WHERE user='root';

Restart the mysql client

sudo service mysql restart

How can you customize the numbers in an ordered list?

This is the solution I have working in Firefox 3, Opera and Google Chrome. The list still displays in IE7 (but without the close bracket and left align numbers):

_x000D_
_x000D_
ol {_x000D_
  counter-reset: item;_x000D_
  margin-left: 0;_x000D_
  padding-left: 0;_x000D_
}_x000D_
li {_x000D_
  display: block;_x000D_
  margin-bottom: .5em;_x000D_
  margin-left: 2em;_x000D_
}_x000D_
li::before {_x000D_
  display: inline-block;_x000D_
  content: counter(item) ") ";_x000D_
  counter-increment: item;_x000D_
  width: 2em;_x000D_
  margin-left: -2em;_x000D_
}
_x000D_
<ol>_x000D_
  <li>One</li>_x000D_
  <li>Two</li>_x000D_
  <li>Three</li>_x000D_
  <li>Four</li>_x000D_
  <li>Five</li>_x000D_
  <li>Six</li>_x000D_
  <li>Seven</li>_x000D_
  <li>Eight</li>_x000D_
  <li>Nine<br>Items</li>_x000D_
  <li>Ten<br>Items</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

EDIT: Included multiple line fix by strager

Also is there a CSS solution to change from numbers to alphabetic/roman lists instead of using the type attribute on the ol element.

Refer to list-style-type CSS property. Or when using counters the second argument accepts a list-style-type value. For example the following will use upper roman:

li::before {
  content: counter(item, upper-roman) ") ";
  counter-increment: item;
/* ... */

Default FirebaseApp is not initialized

We do not need to call FirebaseApp.initializeApp(this); anywhere manually. and we should not too.

I just faced same issue about it and got unexpected and strange solution.

From this answer:

I have removed tools:node="replace" and it's working like charm.

mysql command for showing current configuration variables

What you are looking for is this:

SHOW VARIABLES;  

You can modify it further like any query:

SHOW VARIABLES LIKE '%max%';  

Python Script to convert Image into Byte array

i don't know about converting into a byte array, but it's easy to convert it into a string:

import base64

with open("t.png", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    print str

Source

How to search a string in multiple files and return the names of files in Powershell?

I modified one of the answers above to give me a bit more information. This spared me a second query later on. It was something like this:

Get-ChildItem `
        -Path "C:\data\path" -Filter "Example*.dat" -recurse | `
    Select-String -pattern "dummy" | `
    Select-Object -Property Path,LineNumber,Line | `
    Export-CSV "C:\ResultFile.csv"

I can specify the path and file wildcards with this structures, and it saves the filename, line number and relevant line to an output file.

How can I remove space (margin) above HTML header?

It is probably the h1 tag causing the problem. Applying margin: 0; should fix the problem.

But you should use a CSS reset for every new project to eliminate browser consistencies and problems like yours. Probably the most famous one is Eric Meyer's: http://meyerweb.com/eric/tools/css/reset/

Node.js global variables

I agree that using the global/GLOBAL namespace for setting anything global is bad practice and don't use it at all in theory (in theory being the operative word). However (yes, the operative) I do use it for setting custom Error classes:

// Some global/configuration file that gets called in initialisation

global.MyError = [Function of MyError];

Yes, it is taboo here, but if your site/project uses custom errors throughout the place, you would basically need to define it everywhere, or at least somewhere to:

  1. Define the Error class in the first place
  2. In the script where you're throwing it
  3. In the script where you're catching it

Defining my custom errors in the global namespace saves me the hassle of require'ing my customer error library. Imaging throwing a custom error where that custom error is undefined.

How to give color to each class in scatter plot in R?

Here is a solution using traditional graphics (and Dirk's data):

> DF <- data.frame(x=1:10, y=rnorm(10)+5, z=sample(letters[1:3], 10, replace=TRUE)) 
> DF
    x        y z
1   1 6.628380 c
2   2 6.403279 b
3   3 6.708716 a
4   4 7.011677 c
5   5 6.363794 a
6   6 5.912945 b
7   7 2.996335 a
8   8 5.242786 c
9   9 4.455582 c
10 10 4.362427 a
> attach(DF); plot(x, y, col=c("red","blue","green")[z]); detach(DF)

This relies on the fact that DF$z is a factor, so when subsetting by it, its values will be treated as integers. So the elements of the color vector will vary with z as follows:

> c("red","blue","green")[DF$z]
 [1] "green" "blue"  "red"   "green" "red"   "blue"  "red"   "green" "green" "red"    

You can add a legend using the legend function:

legend(x="topright", legend = levels(DF$z), col=c("red","blue","green"), pch=1)

Java: How to stop thread?

JavaSun recomendation is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread to terminate.

You can that way kill the other process, and the current one afterwards.

SQL Server: Attach incorrect version 661

To clarify, a database created under SQL Server 2008 R2 was being opened in an instance of SQL Server 2008 (the version prior to R2). The solution for me was to simply perform an upgrade installation of SQL Server 2008 R2. I can only speak for the Express edition, but it worked.

Oddly, though, the Web Platform Installer indicated that I had Express R2 installed. The better way to tell is to ask the database server itself:

SELECT @@VERSION

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

If this is a personal script, rather than one you're planning on distributing, it might be simpler to write a shell function for this:

function warextract { jar xf $1 $2 && mv $2 $3 }

which you could then call from python like so:

warextract /home/foo/bar/Portal.ear Binaries.war /home/foo/bar/baz/

If you really feel like it, you could use sed to parse out the filename from the path, so that you'd be able to call it with

warextract /home/foo/bar/Portal.ear /home/foo/bar/baz/Binaries.war

I'll leave that as an excercise to the reader, though.

Of course, since this will extract the .war out into the current directory first, and then move it, it has the possibility of overwriting something with the same name where you are.

Changing directory, extracting it, and cd-ing back is a bit cleaner, but I find myself using little one-line shell functions like this all the time when I want to reduce code clutter.

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

Here's a case example that should handle nulls and will work with older versions of MSSQL. This is based on the inline function in one one of the popular examples:

case
  when a >= b then a
  else isnull(b,a)
end

How to increase scrollback buffer size in tmux?

Open tmux configuration file with the following command:

vim ~/.tmux.conf

In the configuration file add the following line:

set -g history-limit 5000

Log out and log in again, start a new tmux windows and your limit is 5000 now.

Testing if value is a function

using a string based variable as example and making use instanceof Function You register the function..assign the variable...check the variable is the name of function...do pre-process... assign the function to new var...then call the function.

function callMe(){
   alert('You rang?');
}

var value = 'callMe';

if (window[value] instanceof Function) { 
    // do pre-process stuff
    // FYI the function has not actually been called yet
    console.log('callable function');
    //now call function
   var fn = window[value];
   fn();
}

Can't type in React input text field

Once I ran into a similar error. Let me describe it.

Edit.js

   // components returns edit form 
   
   function EditVideo({id}) {
   .....
   
   // onChange event listener 
    const handleChange = (e) => {
       setTextData({
           ...textData,
           [e.target.name]: e.target.value.trim()
        });
     }
  
   ....
   ...
   }
)

ImportEdit.js

   import Edit from './Edit';
   
    function ImportEdit() {
    ......
     ...
    return (
        <div>
            <EditVideo id={id}/>
        </div>
       )
    }

    export default ImportEdit

The Problem was: I was unable to use spacebar (i.e. if i press spacekey, i didn't see space input)

The Bug: .trim()

.trim() method was trimming all the white space i typed

Note: Edit.js worked fine when used sepeartely without import

How to select distinct query using symfony2 doctrine query builder?

Just open your repository file and add this new function, then call it inside your controller:

 public function distinctCategories(){
        return $this->createQueryBuilder('cc')
        ->where('cc.contenttype = :type')
        ->setParameter('type', 'blogarticle')
        ->groupBy('cc.blogarticle')
        ->getQuery()
        ->getResult()
        ;
    }

Then within your controller:

public function index(YourRepository $repo)
{
    $distinctCategories = $repo->distinctCategories();


    return $this->render('your_twig_file.html.twig', [
        'distinctCategories' => $distinctCategories
    ]);
}

Good luck!

Count all duplicates of each value

SELECT number, COUNT(*)
    FROM YourTable
    GROUP BY number
    ORDER BY number

Laravel eloquent update record without loading from database

The common way is to load the row to update:

$post = Post::find($id);

I your case

$post = Post::find(3);
$post->title = "Updated title";
$post->save();

But in one step (just update) you can do this:

$affectedRows = Post::where("id", 3)->update(["title" => "Updated title"]);

Creating an iframe with given HTML dynamically

Allthough your src = encodeURI should work, I would have gone a different way:

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

As this has no x-domain restraints and is completely done via the iframe handle, you may access and manipulate the contents of the frame later on. All you need to make sure of is, that the contents have been rendered, which will (depending on browser type) start during/after the .write command is issued - but not nescessarily done when close() is called.

A 100% compatible way of doing a callback could be this approach:

<html><body onload="parent.myCallbackFunc(this.window)"></body></html>

Iframes has the onload event, however. Here is an approach to access the inner html as DOM (js):

iframe.onload = function() {
   var div=iframe.contentWindow.document.getElementById('mydiv');
};

How do I make a text go onto the next line if it overflows?

As long as you specify a width on the element, it should wrap itself without needing anything else.