Programs & Examples On #Data linking

Dynamically access object property using variable

Whenever you need to access property dynamically you have to use square bracket for accessing property not "." operator
Syntax: object[propery}

_x000D_
_x000D_
const something = { bar: "Foobar!" };_x000D_
const foo = 'bar';_x000D_
// something.foo; -- not correct way at it is expecting foo as proprty in  something={ foo: "value"};_x000D_
// correct way is  something[foo]_x000D_
alert( something[foo])
_x000D_
_x000D_
_x000D_

What is the right way to debug in iPython notebook?

You can always add this in any cell:

import pdb; pdb.set_trace()

and the debugger will stop on that line. For example:

In[1]: def fun1(a):
           def fun2(a):
               import pdb; pdb.set_trace() # debugging starts here
           return fun2(a)

In[2]: fun1(1)

Pausing a batch file for amount of time

If choice is available, use this:

choice /C X /T 10 /D X > nul

where /T 10 is the number of seconds to delay. Note the syntax can vary depending on your Windows version, so use CHOICE /? to be sure.

Build a basic Python iterator

Include the following code in your class code.

 def __iter__(self):
        for x in self.iterable:
            yield x

Make sure that you replace self.iterablewith the iterable which you iterate through.

Here's an example code

class someClass:
    def __init__(self,list):
        self.list = list
    def __iter__(self):
        for x in self.list:
            yield x


var = someClass([1,2,3,4,5])
for num in var: 
    print(num) 

Output

1
2
3
4
5

Note: Since strings are also iterable, they can also be used as an argument for the class

foo = someClass("Python")
for x in foo:
    print(x)

Output

P
y
t
h
o
n

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

Simply :

$(".leaderMultiSelctdropdown").val()

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

Numpy arrays do not have an append method. Use the Numpy append function instead:

import numpy as np

array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely

For example, if array_1 and array_2 have the following values:

array_1 = np.array([1, 2])
array_2 = np.array([3, 4])

If you call np.append without specifying an axis value, like so:

array_3 = np.append(array_1, array_2)

array_3 will have the following value:

array([1, 2, 3, 4])

Else, if you call np.append with an axis value of 0, like so:

array_3 = np.append(array_1, array_2, axis=0)

array_3 will have the following value:

 array([[1, 2],
        [3, 4]]) 

More information on the append function here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html

How can I convert a string to upper- or lower-case with XSLT?

upper-case(string) and lower-case(string)

How to include js file in another js file?

It is not possible directly. You may as well write some preprocessor which can handle that.

If I understand it correctly then below are the things that can be helpful to achieve that:

  • Use a pre-processor which will run through your JS files for example looking for patterns like "@import somefile.js" and replace them with the content of the actual file. Nicholas Zakas(Yahoo) wrote one such library in Java which you can use (http://www.nczonline.net/blog/2009/09/22/introducing-combiner-a-javascriptcss-concatenation-tool/)

  • If you are using Ruby on Rails then you can give Jammit asset packaging a try, it uses assets.yml configuration file where you can define your packages which can contain multiple files and then refer them in your actual webpage by the package name.

  • Try using a module loader like RequireJS or a script loader like LabJs with the ability to control the loading sequence as well as taking advantage of parallel downloading.

JavaScript currently does not provide a "native" way of including a JavaScript file into another like CSS ( @import ), but all the above mentioned tools/ways can be helpful to achieve the DRY principle you mentioned. I can understand that it may not feel intuitive if you are from a Server-side background but this is the way things are. For front-end developers this problem is typically a "deployment and packaging issue".

Hope it helps.

No module named pkg_resources

I ran into this problem after updating my Ubuntu build. It seems to have gone through and removed set up tools in all of my virtual environments.

To remedy this I reinstalled the virtual environment back into the target directory. This cleaned up missing setup tools and got things running again.

e.g.:

~/RepoDir/TestProject$ virtualenv TestEnvironmentDir

Forward declaration of a typedef in C++

For those of you like me, who are looking to forward declare a C-style struct that was defined using typedef, in some c++ code, I have found a solution that goes as follows...

// a.h
 typedef struct _bah {
    int a;
    int b;
 } bah;

// b.h
 struct _bah;
 typedef _bah bah;

 class foo {
   foo(bah * b);
   foo(bah b);
   bah * mBah;
 };

// b.cpp
 #include "b.h"
 #include "a.h"

 foo::foo(bah * b) {
   mBah = b;
 }

 foo::foo(bah b) {
   mBah = &b;
 }

Taking screenshot on Emulator from Android Studio

1.First run your Application 2.Go to Tool-->Android-->Android Device Monitor Check image for more detail

What are the lengths of Location Coordinates, latitude and longitude?

I am aware there are already several answers, but I added this, as this adds substantial information about the decimal places and hence the asked maximum length.

The length of latitude and langitude depend on precision. The absolute maximum length for each is:

  • Latitude: 12 characters (example: -90.00000001)
  • Longitude: 13 characters (example: -180.00000001)

For both holds: a maximum of 8 decial places is possible (though not commonly used).

Explanation for the dependency on precision:

enter image description here

See the full table at Decimal degrees article on Wikipedia

What does "restore purchases" in In-App purchases mean?

You typically restore purchases with this code:

[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];

It will reinvoke -paymentQueue:updatedTransactions on the observer(s) for the purchased items. This is useful for users who reinstall the app after deletion or install it on a different device.

Not all types of In-App purchases can be restored.

Can constructors throw exceptions in Java?

Yes, constructors are allowed to throw exceptions.

However, be very wise in choosing what exceptions they should be - checked exceptions or unchecked. Unchecked exceptions are basically subclasses of RuntimeException.

In almost all cases (I could not come up with an exception to this case), you'll need to throw a checked exception. The reason being that unchecked exceptions (like NullPointerException) are normally due to programming errors (like not validating inputs sufficiently).

The advantage that a checked exception offers is that the programmer is forced to catch the exception in his instantiation code, and thereby realizes that there can be a failure to create the object instance. Of course, only a code review will catch the poor programming practice of swallowing an exception.

How to initialize an array of custom objects

Maybe you mean like this? I like to make an object and use Format-Table:

> $array = @()
> $object = New-Object -TypeName PSObject
> $object | Add-Member -Name 'Name' -MemberType Noteproperty -Value 'Joe'
> $object | Add-Member -Name 'Age' -MemberType Noteproperty -Value 32
> $object | Add-Member -Name 'Info' -MemberType Noteproperty -Value 'something about him'
> $array += $object
> $array | Format-Table

Name                                                                        Age Info
----                                                                        --- ----
Joe                                                                          32  something about him

This will put all objects you have in the array in columns according to their properties.

Tip: Using -auto sizes the table better

> $array | Format-Table -Auto

Name Age Info
---- --- ----
Joe   32 something about him

You can also specify which properties you want in the table. Just separate each property name with a comma:

> $array | Format-Table Name, Age -Auto

Name Age
---- ---
Joe   32

Why doesn't file_get_contents work?

If PHP's allow_url_fopen ini directive is set to true, and if curl doesn't work either (see this answer for an example of how to use it instead of file_get_contents), then the problem could be that your server has a firewall preventing scripts from getting the contents of arbitrary urls (which could potentially allow malicious code to fetch things).

I had this problem, and found that the solution for me was to edit the firewall settings to explicitly allow requests to the domain (or IP address) in question.

How to convert ASCII code (0-255) to its corresponding character?

An easier way of doing the same:

Type cast integer to character, let int n be the integer, then:

Char c=(char)n;
System.out.print(c)//char c will store the converted value.

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

Change the following line

$(document).ready(function() {

To

jQuery.noConflict();
jQuery(document).ready(function($) {

Best approach to real time http streaming to HTML5 video client

Take a look at this solution. As I know, Flashphoner allows to play Live audio+video stream in the pure HTML5 page.

They use MPEG1 and G.711 codecs for playback. The hack is rendering decoded video to HTML5 canvas element and playing decoded audio via HTML5 audio context.

How do I pass along variables with XMLHTTPRequest

Following is correct way:

xmlhttp.open("GET","getuser.php?fname="+abc ,true);

How to do scanf for single char in C

Use string instead of char like

char c[10];
scanf ("%s", c);

I belive it works nice.

Get AVG ignoring Null or Zero values

worked for me:

AVG(CASE WHEN SecurityW <> 0 THEN SecurityW ELSE NULL END)

Why is my xlabel cut off in my matplotlib plot?

plt.autoscale() worked for me.

How do you send a Firebase Notification to all devices via CURL?

EDIT: It appears that this method is not supported anymore (thx to @FernandoZamperin). Please take a look at the other answers!

Instead of subscribing to a topic you could instead make use of the condition key and send messages to instances, that are not in a group. Your data might look something like this:

{
    "data": {
        "foo": "bar"
    },
    "condition": "!('anytopicyoudontwanttouse' in topics)"
}

See https://firebase.google.com/docs/cloud-messaging/send-message#send_messages_to_topics_2

compression and decompression of string data in java

Another example of correct compression and decompression:

@Slf4j
public class GZIPCompression {
    public static byte[] compress(final String stringToCompress) {
        if (isNull(stringToCompress) || stringToCompress.length() == 0) {
            return null;
        }

        try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOutput = new GZIPOutputStream(baos)) {
            gzipOutput.write(stringToCompress.getBytes(UTF_8));
            gzipOutput.finish();
            return baos.toByteArray();
        } catch (IOException e) {
            throw new UncheckedIOException("Error while compression!", e);
        }
    }

    public static String decompress(final byte[] compressed) {
        if (isNull(compressed) || compressed.length == 0) {
            return null;
        }

        try (final GZIPInputStream gzipInput = new GZIPInputStream(new ByteArrayInputStream(compressed));
             final StringWriter stringWriter = new StringWriter()) {
            IOUtils.copy(gzipInput, stringWriter, UTF_8);
            return stringWriter.toString();
        } catch (IOException e) {
            throw new UncheckedIOException("Error while decompression!", e);
        }
    }
}

Regex how to match an optional character

You can make the single letter optional by adding a ? after it as:

([A-Z]{1}?)

The quantifier {1} is redundant so you can drop it.

How to check if an array value exists?

Assuming you are using a simple array

. i.e.

$MyArray = array("red","blue","green");

You can use this function

function val_in_arr($val,$arr){
  foreach($arr as $arr_val){
    if($arr_val == $val){
      return true;
    }
  }
  return false;
}

Usage:

val_in_arr("red",$MyArray); //returns true
val_in_arr("brown",$MyArray); //returns false

How to make html <select> element look like "disabled", but pass values?

If you can supply a default value for your selects, then you can use the same approach for unchecked check boxes which requires a hidden input before the actual element, as these don't post a value if left unchecked:

<input type="hidden" name="myfield" value="default" />
<select name="myfield">
    <option value="default" selected="selected">Default</option>
    <option value="othervalue">Other value</option>
    <!-- ... //-->
</select>

This will actually post the value "default" (without quotes, obviously) if the select is disabled by javascript (or jQuery) or even if your code writes the html disabling the element itself with the attribute: disabled="disabled".

Search for highest key/index in an array

I had a situation where I needed to obtain the next available key in an array, which is the highest+1.

For example, if the array is $data=['1'=>'something,'34'=>'something else'] then I needed to calculate 35 to add a new element to the array that had a key higher than any of the others. In the case of an empty array I needed 1 as next available key.

This is the solution that worked:

    $highest = 0;
    foreach($data as $idx=>$dummy)
    {
        if($idx > $highest)$highest=$idx;
    }
    $highest++;

It will work in all cases, empty array or not. If you only need to find the highest key rather than highest key + 1, delete the last line. You will then get a value of 0 if the array is empty.

What's the syntax for mod in java

As others have pointed out, the % (remainder) operator is not the same as the mathematical mod modulus operation/function.

mod vs %

The x mod n function maps x to n in the range of [0,n).
Whereas the x % n operator maps x to n in the range of (-n,n).

In order to have a method to use the mathematical modulus operation and not care about the sign in front of x one can use:

((x % n) + n) % n

Maybe this picture helps understand it better (I had a hard time wrapping my head around this first)

enter image description here

Average of multiple columns

You could simply do:

Select Req_ID, (avg(R1)+avg(R2)+avg(R3)+avg(R4)+avg(R5))/5 as Average
from Request
Group by Req_ID

Right?

I'm assuming that you may have multiple rows with the same Req_ID and in these cases you want to calculate the average across all columns and rows for those rows with the same Req_ID

Insert content into iFrame

If you want all the CSS thats on your webpage in your IFrame, try this:

var headClone, iFrameHead;

// Create a clone of the web-page head
headClone = $('head').clone();

// Find the head of the the iFrame we are looking for
iFrameHead = $('#iframe').contents().find('head');

// Replace 'iFrameHead with your Web page 'head'
iFrameHead.replaceWith(headClone);

// You should now have all the Web page CSS in the Iframe

Good Luck.

Android Studio does not show layout preview

For me this problem keeps appearing after I run the APK at first time. Invalidating did not help.
However, I came with a workaround:
Just run the APK, and while it's running you can submit your changes clicking the "Lightning" button (Apply changes) next to to the "Run" button at the top right panel. Works charming for me, when making changes to the layout.

Changing navigation bar color in Swift

Swift 3

UINavigationBar.appearance().barTintColor = UIColor(colorLiteralRed: 51/255, green: 90/255, blue: 149/255, alpha: 1)

This will set your navigation bar color like Facebook bar color :)

Ajax passing data to php script

You can also use bellow code for pass data using ajax.

var dataString = "album" + title;
$.ajax({  
    type: 'POST',  
    url: 'test.php', 
    data: dataString,
    success: function(response) {
        content.html(response);
    }
});

Setting Django up to use MySQL

If you are using python3.x then Run below command

pip install mysqlclient

Then change setting.py like

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'DB',
     'USER': 'username',
    'PASSWORD': 'passwd',
  }
  }

How to get past the login page with Wget?

If they're using basic authentication:

wget http://username:[email protected]/page.html

If they're using POSTed form data, you'll need to use something like cURL instead.

Javascript set img src

You need to set

document["pic1"].src = searchPic.src;

The searchPic itself is your Image(), you need to read the src that you set.

What is Activity.finish() method doing exactly?

In addition to @rommex answer above, I have also noticed that finish() does queue the destruction of the Activity and that it depends on Activity priority.

If I call finish() after onPause(), I see onStop(), and onDestroy() immediately called.

If I call finish() after onStop(), I don't see onDestroy() until 5 minutes later.

From my observation, it looks like finish is queued up and when I looked at the adb shell dumpsys activity activities it was set to finishing=true, but since it is no longer in the foreground, it wasn't prioritized for destruction.

In summary, onDestroy() is never guaranteed to be called, but even in the case it is called, it could be delayed.

The application has stopped unexpectedly: How to Debug?

If you use the Logcat display inside the 'debug' perspective in Eclipse the lines are colour-coded. It's pretty easy to find what made your app crash because it's usually in red.

The Java (or Dalvik) virtual machine should never crash, but if your program throws an exception and does not catch it the VM will terminate your program, which is the 'crash' you are seeing.

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

lvalue required as left operand of assignment

You cannot assign an rvalue to an rvalue.

if (strcmp("hello", "hello") = 0)

is wrong. Suggestions:

if (strcmp("hello", "hello") == 0)
                              ^

= is the assign operator.
== is the equal to operator.
I know many new programmers are confused with this fact.

How to initialize static variables

That's too complex to set in the definition. You can set the definition to null though, and then in the constructor, check it, and if it has not been changed - set it:

private static $dates = null;
public function __construct()
{
    if (is_null(self::$dates)) {  // OR if (!is_array(self::$date))
         self::$dates = array( /* .... */);
    }
}

MySQL SELECT WHERE datetime matches day (and not necessarily time)

You can use %:

SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'

converting multiple columns from character to numeric format in r

I think I figured it out. Here's what I did (perhaps not the most elegant solution - suggestions on how to imp[rove this are very much welcome)

#names of columns in data frame
cols <- names(DF)
# character variables
cols.char <- c("fx_code","date")
#numeric variables
cols.num <- cols[!cols %in% cols.char]

DF.char <- DF[cols.char]
DF.num <- as.data.frame(lapply(DF[cols.num],as.numeric))
DF2 <- cbind(DF.char, DF.num)

Java count occurrence of each item in an array

It can be done in a very simple way using collections please find the code below

String[] array = {"name1","name1","name2","name2", "name2"};
List<String> sampleList=(List<String>) Arrays.asList(array);
for(String inpt:array){
int frequency=Collections.frequency(sampleList,inpt);
System.out.println(inpt+" "+frequency);
}

Here the output will be like name1 2 name1 2 name2 3 name2 3 name2 3

To avoid printing redundant keys use HashMap and get your desired output

Python Requests library redirect new url

You are looking for the request history.

The response.history attribute is a list of responses that led to the final URL, which can be found in response.url.

response = requests.get(someurl)
if response.history:
    print("Request was redirected")
    for resp in response.history:
        print(resp.status_code, resp.url)
    print("Final destination:")
    print(response.status_code, response.url)
else:
    print("Request was not redirected")

Demo:

>>> import requests
>>> response = requests.get('http://httpbin.org/redirect/3')
>>> response.history
(<Response [302]>, <Response [302]>, <Response [302]>)
>>> for resp in response.history:
...     print(resp.status_code, resp.url)
... 
302 http://httpbin.org/redirect/3
302 http://httpbin.org/redirect/2
302 http://httpbin.org/redirect/1
>>> print(response.status_code, response.url)
200 http://httpbin.org/get

Delete the first three rows of a dataframe in pandas

df = df.iloc[n:]

n drops the first n rows.

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as the solution. You'd like to avoid them. If all you want is to concatenate strings in EL and you discovered that the + operator fails for strings in EL (which is correct), then just do:

<c:out value="abc${test}" />

Or if abc is to obtained from another scoped variable named ${resp}, then do:

<c:out value="${resp}${test}" />

How to check if ZooKeeper is running or up from command prompt?

Go to bin directory of Zookeeper and type

./zkServer.sh status

For More info go through below link:

http://www.ibm.com/developerworks/library/bd-zookeeper/

Hope this could help you.

Bootstrap 3 Flush footer to bottom. not fixed

Use any class and make it's height fixed. It solved my issue.

<div class="container"></div>
<footer></footer>

CSS:

.container{
    min-height: 60vh;
}

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

Add-on software packages.

See http://www.pathname.com/fhs/2.2/fhs-3.12.html for details.

Also described at Wikipedia.

Its use dates back at least to the late 1980s, when it was a standard part of System V UNIX. These days, it's also seen in Linux, Solaris (which is SysV), OSX Cygwin, etc. Other BSD unixes (FreeBSD, NetBSD, etc) tend to follow other rules, so you don't usually see BSD systems with an /opt unless they're administered by someone who is more comfortable in other environments.

Java: How to insert CLOB into oracle database

You can very well do it with below code, i am giving you just the code to insert xml hope u are done with rest of other things..

import oracle.xdb.XMLType;

//now inside the class......
// this will be to convert xml into string

File file = new File(your file path);
FileReader fileR = new FileReader(file);
fileR.read(data);
String str = new String(data);

// now to enter it into db

conn = DriverManager.getConnection(serverName, userId, password);

XMLType objXml = XMLType.createXML(conn, str);

// inside the query statement put this code

objPreparedstatmnt.setObject(your value index, objXml);

I have done like this and it is working fine.

How can I store and retrieve images from a MySQL database using PHP?

First you create a MySQL table to store images, like for example:

create table testblob (
    image_id        tinyint(3)  not null default '0',
    image_type      varchar(25) not null default '',
    image           blob        not null,
    image_size      varchar(25) not null default '',
    image_ctgy      varchar(25) not null default '',
    image_name      varchar(50) not null default ''
);

Then you can write an image to the database like:

/***
 * All of the below MySQL_ commands can be easily
 * translated to MySQLi_ with the additions as commented
 ***/ 
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli 
// $link = mysqli_connect("localhost", $username, $password,$dbname); 
$sql = sprintf("INSERT INTO testblob
    (image_type, image, image_size, image_name)
    VALUES
    ('%s', '%s', '%d', '%s')",
    /***
     * For all mysqli_ functions below, the syntax is:
     * mysqli_whartever($link, $functionContents); 
     ***/
    mysql_real_escape_string($size['mime']),
    mysql_real_escape_string($imgData),
    $size[3],
    mysql_real_escape_string($_FILES['userfile']['name'])
    );
mysql_query($sql);

You can display an image from the database in a web page with:

$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);

How to add a new row to an empty numpy array

using an custom dtype definition, what worked for me was:

import numpy

# define custom dtype
type1 = numpy.dtype([('freq', numpy.float64, 1), ('amplitude', numpy.float64, 1)])
# declare empty array, zero rows but one column
arr = numpy.empty([0,1],dtype=type1)
# store row data, maybe inside a loop
row = numpy.array([(0.0001, 0.002)], dtype=type1)
# append row to the main array
arr = numpy.row_stack((arr, row))
# print values stored in the row 0
print float(arr[0]['freq'])
print float(arr[0]['amplitude'])

What's the difference between ViewData and ViewBag?

ViewData
  1. ViewData is used to pass data from controller to view
  2. It is derived from ViewDataDictionary class
  3. It is available for the current request only
  4. Requires typecasting for complex data type and checks for null values to avoid error
  5. If redirection occurs, then its value becomes null
ViewBag
  1. ViewBag is also used to pass data from the controller to the respective view
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
  3. It is also available for the current request only
  4. If redirection occurs, then its value becomes null
  5. Doesn’t require typecasting for complex data type

ValueError: not enough values to unpack (expected 11, got 1)

Looks like something is wrong with your data, it isn't in the format you are expecting. It could be a new line character or a blank space in the data that is tinkering with your code.

How to center a subview of UIView

Another solution with PureLayout using autoCenterInSuperview.

// ...
UIView *innerView = [UIView newAutoLayoutView];
innerView.backgroundColor = [UIColor greenColor];
[innerView autoSetDimensionsToSize:CGSizeMake(100, 30)];

[outerview addSubview:innerView];

[innerView autoCenterInSuperview];

This is it how it looks like:

Center with PureLayout

What's the best free C++ profiler for Windows?

I use AQTime, it is one of the best profiling tools I've ever used. It isn't free but you can get a 30 day trial, so if you plan on a optimizing and profiling only one project and 30 days are enough for you then I would recommend using this application. (http://www.automatedqa.com/downloads/aqtime/index.asp)

How to update Ruby to 1.9.x on Mac?

As previously mentioned, the bundler version may be too high for your version of rails.

I ran into the same problem using Rails 3.0.1 which requires Bundler v1.0.0 - v1.0.22

Check your bundler version using: gem list bundler

If your bundler version is not within the appropriate range, I found this solution to work: rvm @global do gem uninstall bundler

Note: rvm is required for this solution... another case for why you should be using rvm in the first place.

How to rename a file using svn?

It can be if you created new directory at the disk BEFORE create/commit it in the SVN. All that you need is just create it in SVN and do move after:

$ svn mv etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/
svn: E155010: Path '/home/dyr/svn/nagioscore/etc/nagios/hosts/us0101/ccs' is not a directory

$ svn status
?       etc/nagios/hosts/us0101/ccs

$ rm -rvf etc/nagios/hosts/us0101/ccs
removed directory 'etc/nagios/hosts/us0101/ccs'

$ svn mkdir etc/nagios/hosts/us0101/ccs
A         etc/nagios/hosts/us0101/ccs

$ svn move etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
A         etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
D         etc/nagios/hosts/us0101/cs/us0101ccs001.cfg

$ svn status
A       etc/nagios/hosts/us0101/ccs
A  +    etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
        > moved from etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
D       etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
        > moved to etc/nagios/hosts/us0101/ccs/us0101accs001.cfg

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

Not tested, but something like this:

var now = new Date();
var str = now.getUTCFullYear().toString() + "/" +
          (now.getUTCMonth() + 1).toString() +
          "/" + now.getUTCDate() + " " + now.getUTCHours() +
          ":" + now.getUTCMinutes() + ":" + now.getUTCSeconds();

Of course, you'll need to pad the hours, minutes, and seconds to two digits or you'll sometimes get weird looking times like "2011/12/2 19:2:8."

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

Have you tried adding a magic comment in the script where you use non-ASCII chars? It should go on top of the script.

#!/bin/env ruby
# encoding: utf-8

It worked for me like a charm.

How do I grant myself admin access to a local SQL Server instance?

I adopted a SQL 2012 database where I was not a sysadmin but was an administrator on the machine. I used SSMS with "Run as Administrator", added my NT account as a SQL login and set the server role to sysadmin. No problem.

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

Here are the functions I used for this end:

function localToGMTStingTime(localTime = null) {
    var date = localTime ? new Date(localTime) : new Date();
    return new Date(date.getTime() + (date.getTimezoneOffset() * 60000)).toISOString();
};

function GMTToLocalStingTime(GMTTime = null) {
    var date = GMTTime ? new Date(GMTTime) : new Date();;
    return new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();
};

Re-sign IPA (iPhone)

I tried all the Solution but finally I am able to create resign ipa with these commands

Resign Certificates

  • *is the ipa name and also app name $PROVISION is the path of the provision profile $CERTIFICATE is the name of the certificate in key chain full name (Common name when double click on the certificate)
  1. Go the Directory where want to create the new ipa with resign certificates . Pase all the files there ipa, certificate and mobileprovision and also install the certificate

  2. security cms -D -i path/to/MyProfile.mobileprovision > provision.plist (Call this command and replace mobile provision with path of the file)

  3. /usr/libexec/PlistBuddy -x -c 'Print :Entitlements' provision.plist > entitlements.plist (Hit this command)

  4. unzip -q *.ipa

  5. rm -rf Payload/*.app/_CodeSignature/

  6. /usr/libexec/PlistBuddy Payload/*.app/Info.plist (After this command we have to add new bundle ID if we don’t need to change bundle id Then we can ignore these 3 steps)

7.  Set :CFBundleIdentifier “com.mycompany.newbundleidentifier” (This should be new bundle ID)
8.  save
9.  quit
  1. cp $PROVISION Payload/*.app/embedded.mobileprovision

  2. codesign -d --entitlements :entitlements.plist Payload/*.app/ (Try to ignore this command if app doesn’t work then next time use this command)

  3. codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/.app/Frameworks/

  4. codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/*.app/

  5. zip -qr resigned.ipa Payload

https://stackoverflow.com/a/37172815 https://stackoverflow.com/a/50392448 https://coderwall.com/p/qwqpnw/resign-ipa-with-new-cfbundleidentifier-and-certificate

PowerShell Connect to FTP server and get files

The AlexFTPS library used in the question seems to be dead (was not updated since 2011).


With no external libraries

You can try to implement this without any external library. But unfortunately, neither the .NET Framework nor PowerShell have any explicit support for downloading all files in a directory (let only recursive file downloads).

You have to implement that yourself:

  • List the remote directory
  • Iterate the entries, downloading files (and optionally recursing into subdirectories - listing them again, etc.)

Tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the .NET framework (FtpWebRequest or WebClient). The .NET framework unfortunately does not support the MLSD command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.

Your options are:

  • If you know that the directory does not contain any subdirectories, use the ListDirectory method (NLST FTP command) and simply download all the "names" as files.
  • Do an operation on a file name that is certain to fail for file and succeeds for directories (or vice versa). I.e. you can try to download the "name".
  • You may be lucky and in your specific case, you can tell a file from a directory by a file name (i.e. all your files have an extension, while subdirectories do not)
  • You use a long directory listing (LIST command = ListDirectoryDetails method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by the d at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)
function DownloadFtpDirectory($url, $credentials, $localPath)
{
    $listRequest = [Net.WebRequest]::Create($url)
    $listRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
    $listRequest.Credentials = $credentials

    $lines = New-Object System.Collections.ArrayList

    $listResponse = $listRequest.GetResponse()
    $listStream = $listResponse.GetResponseStream()
    $listReader = New-Object System.IO.StreamReader($listStream)
    while (!$listReader.EndOfStream)
    {
        $line = $listReader.ReadLine()
        $lines.Add($line) | Out-Null
    }
    $listReader.Dispose()
    $listStream.Dispose()
    $listResponse.Dispose()

    foreach ($line in $lines)
    {
        $tokens = $line.Split(" ", 9, [StringSplitOptions]::RemoveEmptyEntries)
        $name = $tokens[8]
        $permissions = $tokens[0]

        $localFilePath = Join-Path $localPath $name
        $fileUrl = ($url + $name)

        if ($permissions[0] -eq 'd')
        {
            if (!(Test-Path $localFilePath -PathType container))
            {
                Write-Host "Creating directory $localFilePath"
                New-Item $localFilePath -Type directory | Out-Null
            }

            DownloadFtpDirectory ($fileUrl + "/") $credentials $localFilePath
        }
        else
        {
            Write-Host "Downloading $fileUrl to $localFilePath"

            $downloadRequest = [Net.WebRequest]::Create($fileUrl)
            $downloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
            $downloadRequest.Credentials = $credentials

            $downloadResponse = $downloadRequest.GetResponse()
            $sourceStream = $downloadResponse.GetResponseStream()
            $targetStream = [System.IO.File]::Create($localFilePath)
            $buffer = New-Object byte[] 10240
            while (($read = $sourceStream.Read($buffer, 0, $buffer.Length)) -gt 0)
            {
                $targetStream.Write($buffer, 0, $read);
            }
            $targetStream.Dispose()
            $sourceStream.Dispose()
            $downloadResponse.Dispose()
        }
    }
}

Use the function like:

$credentials = New-Object System.Net.NetworkCredential("user", "mypassword") 
$url = "ftp://ftp.example.com/directory/to/download/"
DownloadFtpDirectory $url $credentials "C:\target\directory"

The code is translated from my C# example in C# Download all files and subdirectories through FTP.


Using 3rd party library

If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the MLSD command and/or parsing various LIST listing formats. And ideally with a support for downloading all files from a directory or even recursive downloads.

For example with WinSCP .NET assembly you can download whole directory with a single call to Session.GetFiles:

# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Ftp
    HostName = "ftp.example.com"
    UserName = "user"
    Password = "mypassword"
}

$session = New-Object WinSCP.Session

try
{
    # Connect
    $session.Open($sessionOptions)

    # Download files
    $session.GetFiles("/directory/to/download/*", "C:\target\directory\*").Check()
}
finally
{
    # Disconnect, clean up
    $session.Dispose()
}    

Internally, WinSCP uses the MLSD command, if supported by the server. If not, it uses the LIST command and supports dozens of different listing formats.

The Session.GetFiles method is recursive by default.

(I'm the author of WinSCP)

How to execute a raw update sql with dynamic binding in rails

You should just use something like:

YourModel.update_all(
  ActiveRecord::Base.send(:sanitize_sql_for_assignment, {:value => "'wow'"})
)

That would do the trick. Using the ActiveRecord::Base#send method to invoke the sanitize_sql_for_assignment makes the Ruby (at least the 1.8.7 version) skip the fact that the sanitize_sql_for_assignment is actually a protected method.

How to get all privileges back to the root user in MySQL?

If you facing grant permission access denied problem, you can try mysql_upgrade to fix the problem:

/usr/bin/mysql_upgrade -u root -p

Login as root:

mysql -u root -p

Run this commands:

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
mysql> FLUSH PRIVILEGES;

PHP Call to undefined function

Presently I am working on web services where my function is defined and it was throwing an error undefined function.I just added this in autoload.php in codeigniter

$autoload['helper'] = array('common','security','url');

common is the name of my controller.

How to search all loaded scripts in Chrome Developer Tools?

Search All Files with Control+Shift+F or Console->[Search tab]

enter image description here

NOTE: Global Search shows up next to the CONSOLE menu

Bootstrap 3 select input form inline

Based on spacebean's answer, this modification also changes the displayed text when the user selects a different item (just as a <select> would do):

http://www.bootply.com/VxVlaebtnL

HTML:

<div class="container">
  <div class="col-sm-7 pull-right well">
    <form class="form-inline" action="#" method="get">
      <div class="input-group col-sm-8">
        <input class="form-control" type="text" value="" placeholder="Search" name="q">
        <div class="input-group-btn">
          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span id="mydropdowndisplay">Choice 1</span> <span class="caret"></span></button>
          <ul class="dropdown-menu" id="mydropdownmenu">
            <li><a href="#">Choice 1</a></li>
            <li><a href="#">Choice 2</a></li>
            <li><a href="#">Choice 3</a></li>
          </ul>
          <input type="hidden" id="mydropwodninput" name="category">
        </div><!-- /btn-group -->
      </div>
    <button class="btn btn-primary col-sm-3 pull-right" type="submit">Search</button>
    </form>
  </div>
</div>

Jquery:

$('#mydropdownmenu > li').click(function(e){
  e.preventDefault();
  var selected = $(this).text();
  $('#mydropwodninput').val(selected);
  $('#mydropdowndisplay').text(selected);
});

passing several arguments to FUN of lapply (and others *apply)

As suggested by Alan, function 'mapply' applies a function to multiple Multiple Lists or Vector Arguments:

mapply(myfun, arg1, arg2)

See man page: https://stat.ethz.ch/R-manual/R-devel/library/base/html/mapply.html

Javascript string replace with regex to strip off illegal characters

You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");

Modifying local variable from inside lambda

I know that's an old question, but if you are comfortable with a workaround, considering the fact that the external variable should be final, you can simply do this:

final int[] ordinal = new int[1];
list.forEach(s -> {
    s.setOrdinal(ordinal[0]);
    ordinal[0]++;
});

Maybe not the most elegant, or even the most correct, but it will do.

YAML mapping values are not allowed in this context

This is valid YAML:

jobs:
 - name: A
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120
 - name: B
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120

Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

iOS: Compare two dates

I don't know exactly if you have asked this but if you only want to compare the date component of a NSDate you have to use NSCalendar and NSDateComponents to remove the time component.

Something like this should work as a category for NSDate:

- (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {
    NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
    NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];
    NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];

    NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];
    NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];
    return [selfDateOnly compare:otherDateOnly];
}

Difference between "and" and && in Ruby?

and has lower precedence, mostly we use it as a control-flow modifier such as if:

next if widget = widgets.pop

becomes

widget = widgets.pop and next

For or:

raise "Not ready!" unless ready_to_rock?

becomes

ready_to_rock? or raise "Not ready!"

I prefer to use if but not and, because if is more intelligible, so I just ignore and and or.

Refer to "Using “and” and “or” in Ruby" for more information.

Getting the parameters of a running JVM

JConsole can do it. Also you can use a powerful jvisualVM tool, which also is included in JDK since 1.6.0.8.

Simplest way to serve static data from outside the application server in a Java web application

This is story from my workplace:
- We try to upload multiply images and document files use Struts 1 and Tomcat 7.x.
- We try to write uploaded files to file system, filename and full path to database records.
- We try to separate file folders outside web app directory. (*)

The below solution is pretty simple, effective for requirement (*):

In file META-INF/context.xml file with the following content: (Example, my application run at http://localhost:8080/ABC, my application / project named ABC). (this is also full content of file context.xml)

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/ABC" aliases="/images=D:\images,/docs=D:\docs"/>

(works with Tomcat version 7 or later)

Result: We have been created 2 alias. For example, we save images at: D:\images\foo.jpg and view from link or using image tag:

<img src="http://localhost:8080/ABC/images/foo.jsp" alt="Foo" height="142" width="142">

or

<img src="/images/foo.jsp" alt="Foo" height="142" width="142">

(I use Netbeans 7.x, Netbeans seem auto create file WEB-INF\context.xml)

What is the proper way to test if a parameter is empty in a batch file?

Empty string is a pair of double-quotes/"", we can just test the length:

set ARG=%1
if not defined ARG goto nomore

set CHAR=%ARG:~2,1%
if defined CHAR goto goon

then test it's 2 characters against double-quotes:

if ^%ARG:~1,1% == ^" if ^%ARG:~0,1% == ^" goto blank
::else
goto goon

Here's a batch script you can play with. I think it properly catches the empty string.

This is just an example, you just need to customize 2 (or 3?) steps above according to your script.

@echo off
if not "%OS%"=="Windows_NT" goto EOF
:: I guess we need enableExtensions, CMIIW
setLocal enableExtensions
set i=0
set script=%0

:LOOP
set /a i=%i%+1

set A1=%1
if not defined A1 goto nomore

:: Assumption:
:: Empty string is (exactly) a pair of double-quotes ("")

:: Step out if str length is more than 2
set C3=%A1:~2,1%
if defined C3 goto goon

:: Check the first and second char for double-quotes
:: Any characters will do fine since we test it *literally*
if ^%A1:~1,1% == ^" if ^%A1:~0,1% == ^" goto blank
goto goon

:goon
echo.args[%i%]: [%1]
shift
goto LOOP

:blank
echo.args[%i%]: [%1] is empty string
shift
goto LOOP

:nomore
echo.
echo.command line:
echo.%script% %*

:EOF

This torture test result:

.test.bat :: ""  ">"""bl" " "< "">"  (")(") "" :: ""-"  " "( )"">\>" ""
args[1]: [::]
args[2]: [""] is empty string
args[3]: [">"""bl" "]
args[4]: ["< "">"]
args[5]: [(")(")]
args[6]: [""] is empty string
args[7]: [::]
args[8]: [""-"  "]
args[9]: ["( )"">\>"]
args[10]: [""] is empty string

command line:
.test.bat :: ""  ">"""bl" " "< "">"  (")(") "" :: ""-"  " "( )"">\>" ""

How do you properly use WideCharToMultiByte

You use the lpMultiByteStr [out] parameter by creating a new char array. You then pass this char array in to get it filled. You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.

Here are a couple of useful helper functions for you, they show the usage of all parameters.

#include <string>

std::string wstrtostr(const std::wstring &wstr)
{
    // Convert a Unicode string to an ASCII string
    std::string strTo;
    char *szTo = new char[wstr.length() + 1];
    szTo[wstr.size()] = '\0';
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
    strTo = szTo;
    delete[] szTo;
    return strTo;
}

std::wstring strtowstr(const std::string &str)
{
    // Convert an ASCII string to a Unicode String
    std::wstring wstrTo;
    wchar_t *wszTo = new wchar_t[str.length() + 1];
    wszTo[str.size()] = L'\0';
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
    wstrTo = wszTo;
    delete[] wszTo;
    return wstrTo;
}

--

Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it. The function will use that pointer to fill your variable.

So you can understand this better:

//pX is an out parameter, it fills your variable with 10.
void fillXWith10(int *pX)
{
  *pX = 10;
}

int main(int argc, char ** argv)
{
  int X;
  fillXWith10(&X);
  return 0;
}

C# how to create a Guid value?

Guid.NewGuid() creates a new random guid.

Angular: conditional class with *ngClass

[ngClass]=... instead of *ngClass.

* is only for the shorthand syntax for structural directives where you can for example use

<div *ngFor="let item of items">{{item}}</div>

instead of the longer equivalent version

<template ngFor let-item [ngForOf]="items">
  <div>{{item}}</div>
</template>

See also https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

<some-element [ngClass]="'first second'">...</some-element>
<some-element [ngClass]="['first', 'second']">...</some-element>
<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>

See also https://angular.io/docs/ts/latest/guide/template-syntax.html

<!-- toggle the "special" class on/off with a property -->
<div [class.special]="isSpecial">The class binding is special</div>

<!-- binding to `class.special` trumps the class attribute -->
<div class="special"
     [class.special]="!isSpecial">This one is not so special</div>
<!-- reset/override all class names with a binding  -->
<div class="bad curly special"
     [class]="badCurly">Bad curly</div>

What does body-parser do with express?

If you don't want to use seperate npm package body-parser, latest express (4.16+) has built-in body-parser middleware and can be used like this,

const app = express();
app.use(express.json({ limit: '100mb' }));

p.s. Not all functionalities of body parse are present in the express. Refer documentation for full usage here

Getting Image from API in Angular 4/5+?

You should set responseType: ResponseContentType.Blob in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.

Here is an working example:

Create image.service.ts and put following code:

Angular 4:

getImage(imageUrl: string): Observable<File> {
    return this.http
        .get(imageUrl, { responseType: ResponseContentType.Blob })
        .map((res: Response) => res.blob());
}

Angular 5+:

getImage(imageUrl: string): Observable<Blob> {
  return this.httpClient.get(imageUrl, { responseType: 'blob' });
}

Important: Since Angular 5+ you should use the new HttpClient.

The new HttpClient returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'. Read more about that here.

Now you need to create some function in your image.component.ts to get image and show it in html.

For creating an image from Blob you need to use JavaScript's FileReader. Here is function which creates new FileReader and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:

imageToShow: any;

createImageFromBlob(image: Blob) {
   let reader = new FileReader();
   reader.addEventListener("load", () => {
      this.imageToShow = reader.result;
   }, false);

   if (image) {
      reader.readAsDataURL(image);
   }
}

Now you should use your created ImageService to get image from api. You should to subscribe to data and give this data to createImageFromBlob-function. Here is an example function:

getImageFromService() {
      this.isImageLoading = true;
      this.imageService.getImage(yourImageUrl).subscribe(data => {
        this.createImageFromBlob(data);
        this.isImageLoading = false;
      }, error => {
        this.isImageLoading = false;
        console.log(error);
      });
}

Now you can use your imageToShow-variable in HTML template like this:

<img [src]="imageToShow"
     alt="Place image title"
     *ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
     <img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>

I hope this description is clear to understand and you can use it in your project.

See the working example for Angular 5+ here.

How should I choose an authentication library for CodeIgniter?

Also take a look at BackendPro

Ultimately you will probably end up writing something custom, but there's nothing wrong with borrowing concepts from DX Auth, Freak Auth, BackendPro, etc.

My experiences with the packaged apps is they are specific to certain structures and I have had problems integrating them into my own applications without requiring hacks, then if the pre-package has an update, I have to migrate them in.

I also use Smarty and ADOdb in my CI code, so no matter what I would always end up making major code changes.

What's a .sh file?

If you open your second link in a browser you'll see the source code:

#!/bin/bash
# Script to download individual .nc files from the ORNL
# Daymet server at: http://daymet.ornl.gov

[...]

# For ranges use {start..end}
# for individul vaules, use: 1 2 3 4 
for year in {2002..2003}
do
   for tile in {1159..1160}
        do wget --limit-rate=3m http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc -O ${tile}_${year}_vp.nc
        # An example using curl instead of wget
    #do curl --limit-rate 3M -o ${tile}_${year}_vp.nc http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc
     done
done

So it's a bash script. Got Linux?


In any case, the script is nothing but a series of HTTP retrievals. Both wget and curl are available for most operating systems and almost all language have HTTP libraries so it's fairly trivial to rewrite in any other technology. There're also some Windows ports of bash itself (git includes one). Last but not least, Windows 10 now has native support for Linux binaries.

Regex to remove all special characters from string?

Depending on your definition of "special character", I think "[^a-zA-Z0-9]" would probably do the trick. That would find anything that is not a small letter, a capital letter, or a digit.

Define an alias in fish shell

make a function in ~/.config/fish/functions called mkalias.fish and put this in

function mkalias --argument key value
  echo alias $key=$value
  alias $key=$value
  funcsave $key
end

and this will create aliases automatically.

Running multiple commands in one line in shell

Why not cp to location 1, then mv to location 2. This takes care of "removing" the original.

And no, it's not the correct syntax. | is used to "pipe" output from one program and turn it into input for the next program. What you want is ;, which seperates multiple commands.

cp file1 file2 ; cp file1 file3 ; rm file1

If you require that the individual commands MUST succeed before the next can be started, then you'd use && instead:

cp file1 file2 && cp file1 file3 && rm file1

That way, if either of the cp commands fails, the rm will not run.

Accessing a property in a parent Component

You could:

  • Define a userStatus parameter for the child component and provide the value when using this component from the parent:

    @Component({
      (...)
    })
    export class Profile implements OnInit {
      @Input()
      userStatus:UserStatus;
    
      (...)
    }
    

    and in the parent:

    <profile [userStatus]="userStatus"></profile>
    
  • Inject the parent into the child component:

    @Component({
      (...)
    })
    export class Profile implements OnInit {
      constructor(app:App) {
        this.userStatus = app.userStatus;
      }
    
      (...)
    }
    

    Be careful about cyclic dependencies between them.

Java AES encryption and decryption

If for a block cipher you're not going to use a Cipher transformation that includes a padding scheme, you need to have the number of bytes in the plaintext be an integral multiple of the block size of the cipher.

So either pad out your plaintext to a multiple of 16 bytes (which is the AES block size), or specify a padding scheme when you create your Cipher objects. For example, you could use:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

Unless you have a good reason not to, use a padding scheme that's already part of the JCE implementation. They've thought out a number of subtleties and corner cases you'll have to realize and deal with on your own otherwise.


Ok, your second problem is that you are using String to hold the ciphertext.

In general,

String s = new String(someBytes);
byte[] retrievedBytes = s.getBytes();

will not have someBytes and retrievedBytes being identical.

If you want/have to hold the ciphertext in a String, base64-encode the ciphertext bytes first and construct the String from the base64-encoded bytes. Then when you decrypt you'll getBytes() to get the base64-encoded bytes out of the String, then base64-decode them to get the real ciphertext, then decrypt that.

The reason for this problem is that most (all?) character encodings are not capable of mapping arbitrary bytes to valid characters. So when you create your String from the ciphertext, the String constructor (which applies a character encoding to turn the bytes into characters) essentially has to throw away some of the bytes because it can make no sense of them. Thus, when you get bytes out of the string, they are not the same bytes you put into the string.

In Java (and in modern programming in general), you cannot assume that one character = one byte, unless you know absolutely you're dealing with ASCII. This is why you need to use base64 (or something like it) if you want to build strings from arbitrary bytes.

Eclipse : Failed to connect to remote VM. Connection refused.

I faced the same issue. But i resolved it by changing my port numbers to different one.

How to remove numbers from string using Regex.Replace?

text= re.sub('[0-9\n]',' ',text)

install regex in python which is re then do the following code.

Call an activity method from a fragment

In kotlin you can call activity method from fragment like below:

var mainActivity: MainActivity = activity as MainActivity
        mainActivity.showToast() //Calling show toast method of activity

Try/catch does not seem to have an effect

Edit: As stated in the comments, the following solution applies to PowerShell V1 only.

See this blog post on "Technical Adventures of Adam Weigert" for details on how to implement this.

Example usage (copy/paste from Adam Weigert's blog):

Try {
    echo " ::Do some work..."
    echo " ::Try divide by zero: $(0/0)"
} -Catch {
    echo "  ::Cannot handle the error (will rethrow): $_"
    #throw $_
} -Finally {
    echo " ::Cleanup resources..."
}

Otherwise you'll have to use exception trapping.

CSS force image resize and keep aspect ratio

To force image that fit in a exact size, you don't need to write too many codes. It's so simple

_x000D_
_x000D_
img{_x000D_
    width: 200px;_x000D_
    height: auto;_x000D_
    object-fit: contain; /* Fit logo in the image size */_x000D_
        -o-object-fit: contain; /* Fit logo fro opera browser */_x000D_
    object-position: top; /* Set logo position */_x000D_
        -o-object-position: top; /* Logo position for opera browser */_x000D_
    }
_x000D_
<img src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png" alt="Logo">
_x000D_
_x000D_
_x000D_

How to resolve conflicts in EGit

To resolve the conflicts, use Git stash to save away your uncommitted changes; then pull down the remote repository change set; then pop your local stash to reapply your uncommitted changes.

In Eclipse v4.5 (Mars) to stash changes (a relatively recent addition, wasn't in previous EGit) I do this: right-click on a top-level Eclipse project that's in Git control, pick Team, pick Stashes, pick Stash Changes; a dialog opens to request a stash commit message.

You must use the context menu on a top level project! If I right click on a directory or file within a Git-controlled project I don't get the appropriate context menu.

Can I dynamically add HTML within a div tag from C# on load event?

You want to put code in the master page code behind that inserts HTML into the contents of a page that is using that master page?

I would not search for the control via FindControl as this is a fragile solution that could easily be broken if the name of the control changed.

Your best bet is to declare an event in the master page that any child page could handle. The event could pass the HTML as an EventArg.

get size of json object

Consider using underscore.js. It will allow you to check the size i.e. like that:

var data = {one : 1, two : 2, three : 3};
_.size(data);
//=> 3
_.keys(data);
//=> ["one", "two", "three"]
_.keys(data).length;
//=> 3

VBA module that runs other modules

I just learned something new thanks to Artiso. I gave each module a name in the properties box. These names were also what I declared in the module. When I tried to call my second module, I kept getting an error: Compile error: Expected variable or procedure, not module

After reading Artiso's comment above about not having the same names, I renamed my second module, called it from the first, and problem solved. Interesting stuff! Thanks for the info Artiso!

In case my experience is unclear:

Module Name: AllFSGroupsCY Public Sub AllFSGroupsCY()

Module Name: AllFSGroupsPY Public Sub AllFSGroupsPY()

From AllFSGroupsCY()

Public Sub FSGroupsCY()

    AllFSGroupsPY 'will error each time until the properties name is changed

End Sub

Android WebView not loading an HTTPS URL

I followed the answers above but still it seems not to be working for me below code did a trick for me when integrating payment gatways which are usually https requests :

public class MainActivity extends Activity {

    WebView webView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView) findViewById(R.id.webView1);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        webView.setWebViewClient(new MyWebViewClient());
        String postData = "amount=1000&firstname=mtetno&[email protected]&phone=2145635784&productinfo=android&surl=success.php"
                + "&furl=failure.php&lastname=qwerty&curl=dsdsd.com&address1=dsdsds&address2=dfdfd&city=dsdsds&state=dfdfdfd&"
                + "country=fdfdf&zipcode=123456&udf1=dsdsds&udf2=fsdfdsf&udf3=jhghjg&udf4=fdfd&udf5=fdfdf&pg=dfdf";
        webView.postUrl(
                "http://host/payment.php",
                EncodingUtils.getBytes(postData, "BASE64"));

    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            webView.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler,
                SslError error) {
            handler.proceed();
        }
    }
}

Above code is doing a post request in webview and redirecting to payment gateway.

Setting settings.setDomStorageEnabled(true); did a trick for me Hope this helps .

Compiling LaTex bib source

I am using texmaker as the editor. you have to compile it in terminal as following:

  1. pdflatex filename (with or without extensions)
  2. bibtex filename (without extensions)
  3. pdflatex filename (with or without extensions)
  4. pdflatex filename (with or without extensions)

but sometimes, when you use \citep{}, the names of the references don't show up. In this case, I had to open the references.bib file , so that texmaker could capture the references from the references.bib file. After every edition of the bib file, I had to close and reopen it!! So that texmaker could capture the content of new .bbl file each time. But remember, you have to also run your code in texmaker too.

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

Settings->Additional Settings->Developer Options

1) Turn ON Developer Options
2) Turn ON USB Debugging
3) Turn OFF MIUI optimization
4) Turn ON Install via USB

React JS get current date

OPTION 1: if you want to make a common utility function then you can use this

export function getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

and use it by just importing it as

import {getCurrentDate} from './utils'
console.log(getCurrentDate())

OPTION 2: or define and use in a class directly

getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

Append an object to a list in R in amortized constant time, O(1)?

This is a straightforward way to add items to an R List:

# create an empty list:
small_list = list()

# now put some objects in it:
small_list$k1 = "v1"
small_list$k2 = "v2"
small_list$k3 = 1:10

# retrieve them the same way:
small_list$k1
# returns "v1"

# "index" notation works as well:
small_list["k2"]

Or programmatically:

kx = paste(LETTERS[1:5], 1:5, sep="")
vx = runif(5)
lx = list()
cn = 1

for (itm in kx) { lx[itm] = vx[cn]; cn = cn + 1 }

print(length(lx))
# returns 5

"pip install unroll": "python setup.py egg_info" failed with error code 1

I got this same error while installing mitmproxy using pip3. The below command fixed this:

pip3 install --upgrade setuptools

jQuery select option elements by value

You can use .val() to select the value, like the following:

function select_option(i) {
    $("#span_id select").val(i);
}

Here is a jsfiddle: https://jsfiddle.net/tweissin/uscq42xh/8/

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

Any logic having to do with what is displayed in the view should be delegated to a helper method, as methods in the model are strictly for handling data.

Here is what you could do:

# In the helper...

def link_to_thing(text, thing)
  (thing.url?) ? link_to(text, thing_path(thing)) : link_to(text, thing.url)
end

# In the view...

<%= link_to_thing("text", @thing) %>

LinearLayout not expanding inside a ScrollView

I know this post is very old, For those who don't want to use android:fillViewport="true" because it sometimes doesn't bring up the edittext above keyboard. Use Relative layout instead of LinearLayout it solves the purpose.

C: socket connection timeout

The two socket options SO_RCVTIMEO and SO_SNDTIMEO have no effect on connect. Below is a link to the screenshot which includes this explanation, here I am just briefing it. The apt way of implementing timeouts with connect are using signal or select or poll.

Signals

connect can be interrupted by a self generated signal SIGALRM by using syscall (wrapper) alarm. But, a signal disposition should be installed for the same signal otherwise the program would be terminated. The code goes like this...

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<signal.h>
#include<errno.h>

static void signal_handler(int signo)
{
    return; // Do nothing just interrupt.
}

int main()
{
    /* Register signal handler */

    struct sigaction act, oact;

    act.sa_handler = signal_handler;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;

#ifdef SA_INTERRUPT
    act.sa_flags |= SA_INTERRUPT;
#endif

    if(sigaction(SIGALRM, &act, &oact) < 0)  // Error registering signal handler.
    {
        fprintf(stderr, "Error registering signal disposition\n");
        exit(1);
    }

    /* Prepare your socket and sockaddr structures */

    int sockfd;
    struct sockaddr* servaddr;

    /* Implementing timeout connect */

    int sec = 30;

    if(alarm(sec) != 0)
        fprintf(stderr, "Already timer was set\n");

    if(connect(sockfd, servaddr, sizeof(struct sockaddr)) < 0)
    {
        if(errno == EINTR)
            fprintf(stderr, "Connect timeout\n");
        else
            fprintf(stderr, "Connect failed\n");

        close(sockfd);

        exit(1);
    }

    alarm(0);  /* turn off the alarm */

    sigaction(SIGALRM, &oact, NULL);  /* Restore the default actions of SIGALRM */

    /* Use socket */


    /* End program */

    close(sockfd);
    return 0;
}

Select or Poll

As already some users provided nice explanation on how to use select to achieve connect timeout, it would not be necessary for me to reiterate the same. poll can be used in the same way. However, there are few mistakes that are common in all of the answers, which I would like to address.

  • Even though socket is non-blocking, if the server to which we are connecting is on the same local machine, connect may return with success. So it is advised to check the return value of connect before calling select.

  • Berkeley-derived implementations (and POSIX) have the following rules for non-blocking sockets and connect.

    1) When the connection completes successfully, the descriptor becomes writable (p. 531 of TCPv2).

    2) When the connection establishment encounters an error, the descriptor becomes both readable and writable (p. 530 of TCPv2).

So the code should handle these cases, here I just code the necessary modifications.

/* All the code stays */

/* Modifications at connect */

int conn_ret = connect(sockfd, servaddr, sizeof(struct sockdaddr));

if(conn_ret == 0)
    goto done;

/* Modifications at select */

int sec = 30;
for( ; ; )
{
    struct timeval timeo;
    timeo.tv_sec = sec;
    timeo.tv_usec = 0;

    fd_set wr_set, rd_set;
    FDZERO(&wr_set);
    FD_SET(sockfd, &wr_set);
    rd_set = wr_set;
    int sl_ret = select(sockfd + 1, &rd_set, &wr_set, NULL, &timeo);

    /* All the code stays */
}


done:

    /* Use your socket */

Text from Unix Network Programming Volume 1

How to write into a file in PHP?

I use the following code to write files on my web directory.

write_file.html

<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>

write_file.php

<?php
// strip slashes before putting the form data into target file
$cd = stripslashes($_POST['code']);

// Show the msg, if the code string is empty
if (empty($cd))
    echo "Nothing to write";

// if the code string is not empty then open the target file and put form data in it
else
{
    $file = fopen("demo.php", "w");
    echo fwrite($file, $cd);

    // show a success msg 
    echo "data successfully entered";
    fclose($file);
}
?>

This is a working script. be sure to change the url in form action and the target file in fopen() function if you want to use it on your site.

Good luck.

Best way to check if a URL is valid

Using filter_var() will fail for urls with non-ascii chars, e.g. (http://pt.wikipedia.org/wiki/Guimarães). The following function encode all non-ascii chars (e.g. http://pt.wikipedia.org/wiki/Guimar%C3%A3es) before calling filter_var().

Hope this helps someone.

<?php

function validate_url($url) {
    $path = parse_url($url, PHP_URL_PATH);
    $encoded_path = array_map('urlencode', explode('/', $path));
    $url = str_replace($path, implode('/', $encoded_path), $url);

    return filter_var($url, FILTER_VALIDATE_URL) ? true : false;
}

// example
if(!validate_url("http://somedomain.com/some/path/file1.jpg")) {
    echo "NOT A URL";
}
else {
    echo "IS A URL";
}

What is the most efficient way of finding all the factors of a number in Python?

For n up to 10**16 (maybe even a bit more), here is a fast pure Python 3.6 solution,

from itertools import compress

def primes(n):
    """ Returns  a list of primes < n for n > 2 """
    sieve = bytearray([True]) * (n//2)
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = bytearray((n-i*i-1)//(2*i)+1)
    return [2,*compress(range(3,n,2), sieve[1:])]

def factorization(n):
    """ Returns a list of the prime factorization of n """
    pf = []
    for p in primeslist:
      if p*p > n : break
      count = 0
      while not n % p:
        n //= p
        count += 1
      if count > 0: pf.append((p, count))
    if n > 1: pf.append((n, 1))
    return pf

def divisors(n):
    """ Returns an unsorted list of the divisors of n """
    divs = [1]
    for p, e in factorization(n):
        divs += [x*p**k for k in range(1,e+1) for x in divs]
    return divs

n = 600851475143
primeslist = primes(int(n**0.5)+1) 
print(divisors(n))

How do you deploy Angular apps?

To Deploy your application in IIS follow the below steps.

Step 1: Build your Angular application using command ng build --prod

Step 2: After build all files are stored in dist folder of your application path.

Step 3: Create a folder in C:\inetpub\wwwroot by name QRCode.

Step 4: Copy the contents of dist folder to C:\inetpub\wwwroot\QRCode folder.

Step 5: Open IIS Manager using command (Window + R) and type inetmgr click OK.

Step 6: Right click on Default Web Site and click on Add Application.

Step 7: Enter Alias name 'QRCode' and set the physical path to C:\inetpub\wwwroot\QRCode.

Step 8: Open index.html file and find the line href="\" and remove '\'.

Step 9: Now browse application in any browser.

You can also follow the video for better understanding.

Video url: https://youtu.be/F8EI-8XUNZc

CSS3 transform: rotate; in IE9

Try this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body {
    margin-left: 50px;
    margin-top: 50px;
    margin-right: 50px;
    margin-bottom: 50px;
}
.rotate {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    -webkit-transform: rotate(-10deg);
    -moz-transform: rotate(-10deg);
    -o-transform: rotate(-10deg);
    -ms-transform: rotate(-10deg);
    -sand-transform: rotate(10deg);
    display: block;
    position: fixed;
}
</style>
</head>

<body>
<div class="rotate">Alpesh</div>
</body>
</html>

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

C++ String array sorting

My solution is slightly different to any of those above and works as I just ran it.So for interest:

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
  char *name[] = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
  vector<string> v(name, name + 14);

  sort(v.begin(),v.end());
  for(vector<string>::const_iterator i = v.begin(); i != v.end(); ++i) cout << *i << ' ';
  return 0;
}

How do you enable auto-complete functionality in Visual Studio C++ express edition?

I came across over the following post: http://blogs.msdn.com/b/raulperez/archive/2010/03/19/c-intellisense-options.aspx

The issue is that the "IntelliSense" option in c++ is disabled. This link explains about the IntelliSense database configuration and options.

After enabling the database you must close and reopen visual studio for autocomplete use 'ctrl'+'space'

Preventing iframe caching in browser

Make the URL of the iframe point to a page on your site which acts as a proxy to retrieve and return the actual contents of the iframe. Now you are no longer bound by the same-origin policy (EDIT: does not prevent the iframe caching issue).

What is the reason for a red exclamation mark next to my project in Eclipse?

I had a maven project giving me same thing. It showed that it couldnt find the jar with that version (dependency) and I knew its there and is correct -

So, for me the solution was to 1 delete the local repository. 2 Clean the project. 3 Disable the maven nature. 4 Generate eclipse artifacts and 5 re-configure as maven project.

(in order)

Reporting Services export to Excel with Multiple Worksheets

Group your report data based on the category that you want your sheets to be based on. Specify that you want that grouping to start a new page for every new category. Each page becomes a new worksheet in the Excel workbook.

Note: I use SQL Server 2003 and Excel 2003.

Concatenate two string literals

The difference between a string (or to be precise, std::string) and a character literal is that for the latter there is no + operator defined. This is why the second example fails.

In the first case, the compiler can find a suitable operator+ with the first argument being a string and the second a character literal (const char*) so it used that. The result of that operation is again a string, so it repeats the same trick when adding "!" to it.

CSS endless rotation animation

@keyframes rotate {
    100% {
        transform: rotate(1turn);
    }
}

div{
   animation: rotate 4s linear infinite;
}

Is there a destructor for Java?

There is no exactly destructor class in Java, class destroyed in java automatically by garbage collector . but you could do that using below one but it's not exact same thing :

finalize()

There was a question that spawned in-depth discussion of finalize , so that you should get more depth if required...

Find the index of a char in string?

The String class exposes some methods to enable this, such as IndexOf and LastIndexOf, so that you may do this:

Dim myText = "abcde"
Dim dIndex = myText.IndexOf("d")
If (dIndex > -1) Then

End If

How to match any non white space character except a particular one?

This worked for me using sed [Edit: comment below points out sed doesn't support \s]

[^ ]

while

[^\s] 

didn't

# Delete everything except space and 'g'
echo "ghai ghai" | sed "s/[^\sg]//g"
gg

echo "ghai ghai" | sed "s/[^ g]//g"
g g

MySQL SELECT statement for the "length" of the field is greater than 1

select * from [tbl] where [link] is not null and len([link]) > 1

For MySQL user:

LENGTH([link]) > 1

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

MacOSX homebrew mysql root password

In case you have inadvertently set and forgot the root password, and you don't want to wipe all your databases and start over because you are lazy and forgot to have a back up solution in place, and you are using a fairly recent Homebrew install (Winter 2013), here are steps to reset your password for MySQL.

Stop the currently running MySQL instance

launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

Now start mysql by hand skipping the grant tables and networking

$(brew --prefix mysql)/bin/mysqld_safe --skip-grant-tables --skip-networking

Note that if when you run echo $(brew --prefix mysql) and it does not respond as "/usr/local/opt/mysql" in bash, you will need to adjust the path accordingly.

Once you have done this, you now should have a running, unprotected MySQL instance up.

Log in and set the password

mysql -u root

At the prompt, enter the following MySQL command to set a new password for the effected user.

mysql> update mysql.user set password=PASSWORD('new_password_here') WHERE user='root';

If all went to plan it should say:

Query OK, 1 row affected (0.02 sec)
Rows matched: 4  Changed: 1  Warnings: 0

Exit out of the MySQL prompt.

mysql> exit
Bye

Stop server:

mysqladmin -u root shutdown

Now, lets put back the launch daemon so we have our MySQL at the ready again:

launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

Congratulations. You've just reset your mysql root password. Pour yourself a coffee and get a backup solution in place!

Return a "NULL" object if search result not found

You are unable to return NULL because the return type of the function is an object reference and not a pointer.

oracle varchar to number

If you want formated number then use

SELECT TO_CHAR(number, 'fmt')
   FROM DUAL;

SELECT TO_CHAR('123', 999.99)
   FROM DUAL;

Result 123.00

How to get a shell environment variable in a makefile?

for those who want some official document to confirm the behavior

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.

https://www.gnu.org/software/make/manual/html_node/Environment.html

How do I plot in real-time in a while loop using matplotlib?

If you're interested in realtime plotting, I'd recommend looking into matplotlib's animation API. In particular, using blit to avoid redrawing the background on every frame can give you substantial speed gains (~10x):

#!/usr/bin/env python

import numpy as np
import time
import matplotlib
matplotlib.use('GTKAgg')
from matplotlib import pyplot as plt


def randomwalk(dims=(256, 256), n=20, sigma=5, alpha=0.95, seed=1):
    """ A simple random walk with memory """

    r, c = dims
    gen = np.random.RandomState(seed)
    pos = gen.rand(2, n) * ((r,), (c,))
    old_delta = gen.randn(2, n) * sigma

    while True:
        delta = (1. - alpha) * gen.randn(2, n) * sigma + alpha * old_delta
        pos += delta
        for ii in xrange(n):
            if not (0. <= pos[0, ii] < r):
                pos[0, ii] = abs(pos[0, ii] % r)
            if not (0. <= pos[1, ii] < c):
                pos[1, ii] = abs(pos[1, ii] % c)
        old_delta = delta
        yield pos


def run(niter=1000, doblit=True):
    """
    Display the simulation using matplotlib, optionally using blit for speed
    """

    fig, ax = plt.subplots(1, 1)
    ax.set_aspect('equal')
    ax.set_xlim(0, 255)
    ax.set_ylim(0, 255)
    ax.hold(True)
    rw = randomwalk()
    x, y = rw.next()

    plt.show(False)
    plt.draw()

    if doblit:
        # cache the background
        background = fig.canvas.copy_from_bbox(ax.bbox)

    points = ax.plot(x, y, 'o')[0]
    tic = time.time()

    for ii in xrange(niter):

        # update the xy data
        x, y = rw.next()
        points.set_data(x, y)

        if doblit:
            # restore background
            fig.canvas.restore_region(background)

            # redraw just the points
            ax.draw_artist(points)

            # fill in the axes rectangle
            fig.canvas.blit(ax.bbox)

        else:
            # redraw everything
            fig.canvas.draw()

    plt.close(fig)
    print "Blit = %s, average FPS: %.2f" % (
        str(doblit), niter / (time.time() - tic))

if __name__ == '__main__':
    run(doblit=False)
    run(doblit=True)

Output:

Blit = False, average FPS: 54.37
Blit = True, average FPS: 438.27

Can't connect to MySQL server error 111

If all the previous answers didn't give any solution, you should check your user privileges.

If you could login as root to mysql then you should add this:

CREATE USER 'root'@'192.168.1.100' IDENTIFIED BY  '***';
GRANT ALL PRIVILEGES ON * . * TO  'root'@'192.168.1.100' IDENTIFIED BY  '***' WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;

Then try to connect again using mysql -ubeer -pbeer -h192.168.1.100. It should work.

S3 - Access-Control-Allow-Origin Header

This is a simple way to make this work.

I know this is an old question, but still is hard to find a solution.

To start, this worked for me on a project built with Rails 4, Paperclip 4, CamanJS, Heroku and AWS S3.


You have to request your image using the crossorigin: "anonymous" parameter.

    <img href="your-remote-image.jpg" crossorigin="anonymous"> 

Add your site URL to CORS in AWS S3. Here is a refference from Amazon about that. Pretty much, just go to your bucket, and then select "Properties" from the tabs on the right, open "Permissions tab and then, click on "Edit CORS Configuration".

Originally, I had < AllowedOrigin> set to *. Just change that asterisk to your URL, be sure to include options like http:// and https:// in separate lines. I was expecting that the asterisk accepts "All", but apparently we have to be more specific than that.

This is how it looks for me.

enter image description here

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

No.

If the user is sophisticated or determined enough to:

  1. Open the Excel VBA editor
  2. Use the object browser to see the list of all sheets, including VERYHIDDEN ones
  3. Change the property of the sheet to VISIBLE or just HIDDEN

then they are probably sophisticated or determined enough to:

  1. Search the internet for "remove Excel 2007 project password"
  2. Apply the instructions they find.

So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.

How to append elements into a dictionary in Swift?

Up till now the best way I have found to append data to a dictionary by using one of the higher order functions of Swift i.e. "reduce". Follow below code snippet:

newDictionary = oldDictionary.reduce(*newDictionary*) { r, e in var r = r; r[e.0] = e.1; return r }

@Dharmesh In your case, it will be,

newDictionary = dict.reduce([3 : "efg"]) { r, e in var r = r; r[e.0] = e.1; return r }

Please let me know if you find any issues in using above syntax.

Bootstrap: Open Another Modal in Modal

Why not just change the content of the modal body?

    window.switchContent = function(myFile){
        $('.modal-body').load(myFile);
    };

In the modal just put a link or a button

    <a href="Javascript: switchContent('myFile.html'); return false;">
     click here to load another file</a>

If you just want to switch beetween 2 modals:

    window.switchModal = function(){
        $('#myModal-1').modal('hide');
        setTimeout(function(){ $('#myModal-2').modal(); }, 500);
        // the setTimeout avoid all problems with scrollbars
    };

In the modal just put a link or a button

    <a href="Javascript: switchModal(); return false;">
     click here to switch to the second modal</a>

Add error bars to show standard deviation on a plot in R

You can use arrows:

arrows(x,y-sd,x,y+sd, code=3, length=0.02, angle = 90)

Various ways to remove local Git changes

For discard all i like to stash and drop that stash, it's the fastest way to discard all, especially if you work between multiple repos.

This will stash all changes in {0} key and instantly drop it from {0}

git stash && git stash drop

INSERT INTO...SELECT for all MySQL columns

Addition to Mark Byers answer :

Sometimes you also want to insert Hardcoded details else there may be Unique constraint fail etc. So use following in such situation where you override some values of the columns.

INSERT INTO matrimony_domain_details (domain, type, logo_path)
SELECT 'www.example.com', type, logo_path
FROM matrimony_domain_details
WHERE id = 367

Here domain value is added by me me in Hardcoded way to get rid from Unique constraint.

Turn off deprecated errors in PHP 5.3

To only get those errors that cause the application to stop working, use:

error_reporting(E_ALL ^ (E_NOTICE | E_WARNING | E_DEPRECATED));

This will stop showing notices, warnings, and deprecated errors.

How do I change column default value in PostgreSQL?

'SET' is forgotten

ALTER TABLE ONLY users ALTER COLUMN lang SET DEFAULT 'en_GB';

Calling onclick on a radiobutton list using javascript

I agree with @annakata that this question needs some more clarification, but here is a very, very basic example of how to setup an onclick event handler for the radio buttons:

<html>
 <head>
  <script type="text/javascript">
    window.onload = function() {

        var ex1 = document.getElementById('example1');
        var ex2 = document.getElementById('example2');
        var ex3 = document.getElementById('example3');

        ex1.onclick = handler;
        ex2.onclick = handler;
        ex3.onclick = handler;

    }

    function handler() {
        alert('clicked');
    }
  </script>
 </head>
 <body>
  <input type="radio" name="example1" id="example1" value="Example 1" />
  <label for="example1">Example 1</label>
  <input type="radio" name="example2" id="example2" value="Example 2" />
  <label for="example1">Example 2</label>
  <input type="radio" name="example3" id="example3" value="Example 3" />
  <label for="example1">Example 3</label>
 </body>
</html>

Get keys from HashMap in Java

A HashMap contains more than one key. You can use keySet() to get the set of all keys.

team1.put("foo", 1);
team1.put("bar", 2);

will store 1 with key "foo" and 2 with key "bar". To iterate over all the keys:

for ( String key : team1.keySet() ) {
    System.out.println( key );
}

will print "foo" and "bar".

Is there a Google Voice API?

Be nice if there was a Javascript API version. That way can integrate w/ other AJAX apps or browser extensions/gadgets/widgets.

Right now, current APIs restrict to web app technologies that support Java, .NET, or Python, more for server side, unless may use Google Web Toolkit to translate Java code to Javascript.

How to "add existing frameworks" in Xcode 4?

I would like to point out that if you can't find "Link Binaries With Libraries" in your build phases tab click the "Add build phase" button in the lower right corner.

Bigger Glyphicons

The .btn-lg class has the following CSS in Bootstrap 3 (link):

.btn-lg {
  padding: 10px 16px;
  font-size: 18px;
  line-height: 1.33;
  border-radius: 6px;
}

If you apply the same font-size and line-height to your span (either .glyphicon-link or a newly created .glyphicons-lg if you're going to use this effect in more than one instance), you'll get a Glyphicon the same size as the large button.

Command for restarting all running docker containers?

To start multiple containers with the only particular container id's $ docker restart contianer-id1 container-id2 container-id3 ...

Store boolean value in SQLite

In SQLite the best you can do is use the integers 0 and 1 to represent false and true. You could declare the column type like this:

CREATE TABLE foo(mycolumn BOOLEAN NOT NULL CHECK (mycolumn IN (0,1)));

Omit the NOT NULL if you want to allow NULL in addition to 0 and 1.

The use of the type name BOOLEAN here is for readability, to SQLite it's just a type with NUMERIC affinity.

Note that CHECK constraints have been supported since SQLite 3.3.0 (2006).

Here are some example INSERTs that will work: (note how strings and floating point numbers are parsed as integers)

sqlite> INSERT INTO foo VALUES(0);
sqlite> INSERT INTO foo VALUES(1);
sqlite> INSERT INTO foo VALUES(0.0);
sqlite> INSERT INTO foo VALUES(1.0);
sqlite> INSERT INTO foo VALUES("0.0");
sqlite> INSERT INTO foo VALUES("1.0");
sqlite> select mycolumn, typeof(mycolumn) from foo;
0|integer
1|integer
0|integer
1|integer
0|integer
1|integer

and some that will fail:

sqlite> INSERT INTO foo VALUES("-1");
Error: constraint failed
sqlite> INSERT INTO foo VALUES(0.24);
Error: constraint failed
sqlite> INSERT INTO foo VALUES(100);
Error: constraint failed
sqlite> INSERT INTO foo VALUES(NULL);
Error: foo.mycolumn may not be NULL
sqlite> INSERT INTO foo VALUES("true");
Error: constraint failed
sqlite> INSERT INTO foo VALUES("false");
Error: constraint failed

Embedding Base64 Images

Most modern desktop browsers such as Chrome, Mozilla and Internet Explorer support images encoded as data URL. But there are problems displaying data URLs in some mobile browsers: Android Stock Browser and Dolphin Browser won't display embedded JPEGs.

I reccomend you to use the following tools for online base64 encoding/decoding:

Check the "Format as Data URL" option to format as a Data URL.

Why does my 'git branch' have no master?

It seems there must be at least one local commit on the master branch to do:

git push -u origin master

So if you did git init . and then git remote add origin ..., you still need to do:

git add ...
git commit -m "..."

java.util.Date vs java.sql.Date

LATE EDIT: Starting with Java 8 you should use neither java.util.Date nor java.sql.Date if you can at all avoid it, and instead prefer using the java.time package (based on Joda) rather than anything else. If you're not on Java 8, here's the original response:


java.sql.Date - when you call methods/constructors of libraries that use it (like JDBC). Not otherwise. You don't want to introduce dependencies to the database libraries for applications/modules that don't explicitly deal with JDBC.

java.util.Date - when using libraries that use it. Otherwise, as little as possible, for several reasons:

  • It's mutable, which means you have to make a defensive copy of it every time you pass it to or return it from a method.

  • It doesn't handle dates very well, which backwards people like yours truly, think date handling classes should.

  • Now, because j.u.D doesn't do it's job very well, the ghastly Calendar classes were introduced. They are also mutable, and awful to work with, and should be avoided if you don't have any choice.

  • There are better alternatives, like the Joda Time API (which might even make it into Java 7 and become the new official date handling API - a quick search says it won't).

If you feel it's overkill to introduce a new dependency like Joda, longs aren't all that bad to use for timestamp fields in objects, although I myself usually wrap them in j.u.D when passing them around, for type safety and as documentation.

Relation between CommonJS, AMD and RequireJS?

The short answer would be:

CommonJS and AMD are specifications (or formats) on how modules and their dependencies should be declared in javascript applications.

RequireJS is a script loader library that is AMD compliant, curljs being another example.

CommonJS compliant:

Taken from Addy Osmani's book.

// package/lib is a dependency we require
var lib = require( "package/lib" );

// behavior for our module
function foo(){
    lib.log( "hello world!" );
}

// export (expose) foo to other modules as foobar
exports.foobar = foo;

AMD compliant:

// package/lib is a dependency we require
define(["package/lib"], function (lib) {

    // behavior for our module
    function foo() {
        lib.log( "hello world!" );
    }

    // export (expose) foo to other modules as foobar
    return {
        foobar: foo
    }
});

Somewhere else the module can be used with:

require(["package/myModule"], function(myModule) {
    myModule.foobar();
});

Some background:

Actually, CommonJS is much more than an API declaration and only a part of it deals with that. AMD started as a draft specification for the module format on the CommonJS list, but full consensus wasn't reached and further development of the format moved to the amdjs group. Arguments around which format is better state that CommonJS attempts to cover a broader set of concerns and that it's better suited for server side development given its synchronous nature, and that AMD is better suited for client side (browser) development given its asynchronous nature and the fact that it has its roots in Dojo's module declaration implementation.

Sources:

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

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

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

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

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

java.lang.UnsupportedClassVersionError

The code was most likely compiled with a later JDK (without using cross-compilation options) and is being run on an earlier JRE. While upgrading the JRE is one solution, it would be better to use the cross-compilation options to ensure the code will run on whatever JRE is intended as the minimum version for the app.

Getting the .Text value from a TextBox

Did you try using t.Text?

Google Drive as FTP Server

With google-drive-ftp-adapter I have been able to access the My Drive area of Google Drive with the FileZilla FTP client. However, I have not been able to access the Shared with me area.

You can configure which Google account credentials it uses by changing the account property in the configuration.properties file from default to the desired Google account name. See the instructions at http://www.andresoviedo.org/google-drive-ftp-adapter/

How to use PHP to connect to sql server

Try this to be able to catch the thrown exception:

$server_name = "your server name";
$database_name = "your database name";
try {
   $conn = new PDO("sqlsrv:Server=$server_name;Database=$database_name;ConnectionPooling=0", "user_name", "password");
   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    $e->getMessage();
}

What is Unicode, UTF-8, UTF-16?

Unicode is a fairly complex standard. Don’t be too afraid, but be prepared for some work! [2]

Because a credible resource is always needed, but the official report is massive, I suggest reading the following:

  1. The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) An introduction by Joel Spolsky, Stack Exchange CEO.
  2. To the BMP and beyond! A tutorial by Eric Muller, Technical Director then, Vice President later, at The Unicode Consortium. (first 20 slides and you are done)

A brief explanation:

Computers read bytes and people read characters, so we use encoding standards to map characters to bytes. ASCII was the first widely used standard, but covers only Latin (7 bits/character can represent 128 different characters). Unicode is a standard with the goal to cover all possible characters in the world (can hold up to 1,114,112 characters, meaning 21 bits/character max. Current Unicode 8.0 specifies 120,737 characters in total, and that's all).

The main difference is that an ASCII character can fit to a byte (8 bits), but most Unicode characters cannot. So encoding forms/schemes (like UTF-8 and UTF-16) are used, and the character model goes like this:

Every character holds an enumerated position from 0 to 1,114,111 (hex: 0-10FFFF) called code point.
An encoding form maps a code point to a code unit sequence. A code unit is the way you want characters to be organized in memory, 8-bit units, 16-bit units and so on. UTF-8 uses 1 to 4 units of 8 bits, and UTF-16 uses 1 or 2 units of 16 bits, to cover the entire Unicode of 21 bits max. Units use prefixes so that character boundaries can be spotted, and more units mean more prefixes that occupy bits. So, although UTF-8 uses 1 byte for the Latin script it needs 3 bytes for later scripts inside Basic Multilingual Plane, while UTF-16 uses 2 bytes for all these. And that's their main difference.
Lastly, an encoding scheme (like UTF-16BE or UTF-16LE) maps (serializes) a code unit sequence to a byte sequence.

character: p
code point: U+03C0
encoding forms (code units):
      UTF-8: CF 80
      UTF-16: 03C0
encoding schemes (bytes):
      UTF-8: CF 80
      UTF-16BE: 03 C0
      UTF-16LE: C0 03

Tip: a hex digit represents 4 bits, so a two-digit hex number represents a byte
Also take a look at Plane maps in Wikipedia to get a feeling of the character set layout

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

I removed C:\ProgramData\Oracle\Java\javapath from my path, and it worked for me. Perfect Answer, Thanks Nikil.

Converting of Uri to String

String to Uri

Uri myUri = Uri.parse("https://www.google.com");

Uri to String

Uri uri;
String stringUri = uri.toString();

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

Intellij idea subversion checkout error: `Cannot run program "svn"`

Disabling Use command-line client from the settings worked well form me on IntelliJ Ultimate 14.0.

How to append contents of multiple files into one file

You need the cat (short for concatenate) command, with shell redirection (>) into your output file

cat 1.txt 2.txt 3.txt > 0.txt

How to find the nearest parent of a Git branch?

vbc=$(git rev-parse --abbrev-ref HEAD)
vbc_col=$(( $(git show-branch | grep '^[^\[]*\*' | head -1 | cut -d* -f1 | wc -c) - 1 )) 
swimming_lane_start_row=$(( $(git show-branch | grep -n "^[\-]*$" | cut -d: -f1) + 1 )) 
git show-branch | tail -n +$swimming_lane_start_row | grep -v "^[^\[]*\[$vbc" | grep "^.\{$vbc_col\}[^ ]" | head -n1 | sed 's/.*\[\(.*\)\].*/\1/' | sed 's/[\^~].*//'

Achieves the same ends as Mark Reed's answer, but uses a much safer approach that doesn't misbehave in a number of scenarios:

  1. Parent branch's last commit is a merge, making the column show - not *
  2. Commit message contains branch name
  3. Commit message contains *

Blur or dim background when Android PopupWindow active

You can use android:theme="@android:style/Theme.Dialog" to do that. Create an activity and in your AndroidManifest.xml define the activity as:

    <activity android:name=".activities.YourActivity"
              android:label="@string/your_activity_label"
              android:theme="@android:style/Theme.Dialog">

Replace HTML page with contents retrieved via AJAX

Can't you just try to replace the body content with the document.body handler?

if your page is this:

<html>
<body>
blablabla
<script type="text/javascript">
document.body.innerHTML="hi!";
</script>
</body>
</html>

Just use the document.body to replace the body.

This works for me. All the content of the BODY tag is replaced by the innerHTML you specify. If you need to even change the html tag and all childs you should check out which tags of the 'document.' are capable of doing so.

An example with javascript scripting inside it:

<html>
<body>
blablabla
<script type="text/javascript">
var changeme = "<button onClick=\"document.bgColor = \'#000000\'\">click</button>";
document.body.innerHTML=changeme;
</script>
</body>

This way you can do javascript scripting inside the new content. Don't forget to escape all double and single quotes though, or it won't work. escaping in javascript can be done by traversing your code and putting a backslash in front of all singe and double quotes.

Bare in mind that server side scripting like php doesn't work this way. Since PHP is server-side scripting it has to be processed before a page is loaded. Javascript is a language which works on client-side and thus can not activate the re-processing of php code.

PLS-00103: Encountered the symbol when expecting one of the following:

The IF statement has these forms in PL/SQL:

IF THEN

IF THEN ELSE

IF THEN ELSIF

You have used elseif which in terms of PL/SQL is wrong. That need to be replaced with ELSIF.

DECLARE
  mark NUMBER :=50;
BEGIN
  mark :=& mark;
  IF (mark BETWEEN 85 AND 100) THEN
    dbms_output.put_line('mark is A ');
  elsif (mark BETWEEN 50 AND 65) THEN
    dbms_output.put_line('mark is D ');
  elsif (mark BETWEEN 66 AND 75) THEN
    dbms_output.put_line('mark is C ');
  elsif (mark BETWEEN 76 AND 84) THEN
    dbms_output.put_line('mark is B');
  ELSE
    dbms_output.put_line('mark is F');
  END IF;
END;
/

Understanding PIVOT function in T-SQL

    SELECT <non-pivoted column>,
    [first pivoted column] AS <column name>,
    [second pivoted column] AS <column name>,
    ...
    [last pivoted column] AS <column name>
FROM
    (<SELECT query that produces the data>)
    AS <alias for the source query>
PIVOT
(
    <aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
    IN ( [first pivoted column], [second pivoted column],
    ... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;

USE AdventureWorks2008R2 ;
GO
SELECT DaysToManufacture, AVG(StandardCost) AS AverageCost 
FROM Production.Product
GROUP BY DaysToManufacture;

    DaysToManufacture          AverageCost
0                          5.0885
1                          223.88
2                          359.1082
4                          949.4105

    -- Pivot table with one row and five columns
SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days, 
[0], [1], [2], [3], [4]
FROM
(SELECT DaysToManufacture, StandardCost 
    FROM Production.Product) AS SourceTable
PIVOT
(
AVG(StandardCost)
FOR DaysToManufacture IN ([0], [1], [2], [3], [4])
) AS PivotTable;




Here is the result set.
Cost_Sorted_By_Production_Days    0         1         2           3       4       
AverageCost                       5.0885    223.88    359.1082    NULL    949.4105

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

Use this regular expression if you don't want to start with zero:

^[1-9]([0-9]{1,45}$)

If you don't mind starting with zero, use:

^[0-9]{1,45}$

Why is vertical-align:text-top; not working in CSS

something like

  position:relative;
  top:-5px;

just on the inline element itself works for me. Have to play with the top to get it centered vertically...

How can I require at least one checkbox be checked before a form can be submitted?

Using this you can check at least one checkbox is selected or not in different checkbox groups or multiple checkboxes.

Reference : Link

<label class="control-label col-sm-4">Check Box 1</label>
    <input type="checkbox" name="checkbox1" id="checkbox1" value=Male /> Male<br />
    <input type="checkbox" name="checkbox1" id="checkbox1" value=Female /> Female<br />

<label class="control-label col-sm-4">Check Box 2</label>
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />

<label class="control-label col-sm-4">Check Box 3</label>
    <input type="checkbox" name="checkbox3" id="checkbox3" value=ck3 /> ck3<br />
    <input type="checkbox" name="checkbox3" id="checkbox3" value=ck4 /> ck4<br />

<script>
function checkFormData() {
    if (!$('input[name=checkbox1]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 1 can not be null";
        return false;
    }
    if (!$('input[name=checkbox2]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
        return false;
    }
    if (!$('input[name=checkbox3]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 3 can not be null";
        return false;
    }
    alert("Success");
    return true;
}
</script>

How can I fix MySQL error #1064?

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

MySQL: Enable LOAD DATA LOCAL INFILE

in case your flavor of mysql on ubuntu does NOT under any circumstances work and you still get the 1148 error, you can run the load data infile command via command line

open a terminal window

run mysql -u YOURUSERNAME -p --local-infile YOURDBNAME

you will be requested to insert mysqluser password

you will be running MySQLMonitor and your command prompt will be mysql>

run your load data infile command (dont forget to end with a semicolon ; )

like this:

load data local infile '/home/tony/Desktop/2013Mini.csv' into table Reading_Table FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

Jar mismatch! Fix your dependencies

I agree with pjco. The best way is the official method explained in Support Library Setup in the tutorial at developer.android.com.

Then, in the Eclipse "package explorer", expand your main project and delete android-support-v4.jar from the "libs" folder (as Pratik Butani suggested).

This worked for me.

Convert JSONObject to Map

This is what worked for me:

    public static Map<String, Object> toMap(JSONObject jsonobj)  throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();
        Iterator<String> keys = jsonobj.keys();
        while(keys.hasNext()) {
            String key = keys.next();
            Object value = jsonobj.get(key);
            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            } else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }   
            map.put(key, value);
        }   return map;
    }

    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }
            else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }   return list;
}

Most of this is from this question: How to convert JSONObject to new Map for all its keys using iterator java

What is the best way to remove the first element from an array?

You can't do it at all, let alone quickly. Arrays in Java are fixed size. Two things you could do are:

  1. Shift every element up one, then set the last element to null.
  2. Create a new array, then copy it.

You can use System.arraycopy for either of these. Both of these are O(n), since they copy all but 1 element.

If you will be removing the first element often, consider using LinkedList instead. You can use LinkedList.remove, which is from the Queue interface, for convenience. With LinkedList, removing the first element is O(1). In fact, removing any element is O(1) once you have a ListIterator to that position. However, accessing an arbitrary element by index is O(n).

Excel VBA date formats

Format converts the values to strings. IsDate still returns true because it can parse that string and get a valid date.

If you don't want to change the cells to string, don't use Format. (IOW, don't convert them to strings in the first place.) Use the Cell.NumberFormat, and set it to the date format you want displayed.

ActiveCell.NumberFormat = "mm/dd/yy"   ' Outputs 10/28/13
ActiveCell.NumberFormat = "dd/mm/yyyy" ' Outputs 28/10/2013

REST API - why use PUT DELETE POST GET?

This is a security and maintainability question.

safe methods

Whenever possible, you should use 'safe' (unidirectional) methods such as GET and HEAD in order to limit potential vulnerability.

idempotent methods

Whenever possible, you should use 'idempotent' methods such as GET, HEAD, PUT and DELETE, which can't have side effects and are therefore less error prone/easier to control.

Source

Using cURL with a username and password?

You can use command like,

curl -u user-name -p http://www.example.com/path-to-file/file-name.ext > new-file-name.ext

Then HTTP password will be triggered.

Reference: http://www.asempt.com/article/how-use-curl-http-password-protected-site

String contains - ignore case

You can use

org.apache.commons.lang3.StringUtils.containsIgnoreCase(CharSequence str,
                                     CharSequence searchStr);

Checks if CharSequence contains a search CharSequence irrespective of case, handling null. Case-insensitivity is defined as by String.equalsIgnoreCase(String).

A null CharSequence will return false.

This one will be better than regex as regex is always expensive in terms of performance.

For official doc, refer to : StringUtils.containsIgnoreCase

Update :

If you are among the ones who

  • don't want to use Apache commons library
  • don't want to go with the expensive regex/Pattern based solutions,
  • don't want to create additional string object by using toLowerCase,

you can implement your own custom containsIgnoreCase using java.lang.String.regionMatches

public boolean regionMatches(boolean ignoreCase,
                             int toffset,
                             String other,
                             int ooffset,
                             int len)

ignoreCase : if true, ignores case when comparing characters.

public static boolean containsIgnoreCase(String str, String searchStr)     {
    if(str == null || searchStr == null) return false;

    final int length = searchStr.length();
    if (length == 0)
        return true;

    for (int i = str.length() - length; i >= 0; i--) {
        if (str.regionMatches(true, i, searchStr, 0, length))
            return true;
    }
    return false;
}

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

If you have UTF8, use this (actually works with SVG source), like:

btoa(unescape(encodeURIComponent(str)))

example:

 var imgsrc = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(markup)));
 var img = new Image(1, 1); // width, height values are optional params 
 img.src = imgsrc;

If you need to decode that base64, use this:

var str2 = decodeURIComponent(escape(window.atob(b64)));
console.log(str2);

Example:

var str = "äöüÄÖÜçéèñ";
var b64 = window.btoa(unescape(encodeURIComponent(str)))
console.log(b64);

var str2 = decodeURIComponent(escape(window.atob(b64)));
console.log(str2);

Note: if you need to get this to work in mobile-safari, you might need to strip all the white-space from the base64 data...

function b64_to_utf8( str ) {
    str = str.replace(/\s/g, '');    
    return decodeURIComponent(escape(window.atob( str )));
}

2017 Update

This problem has been bugging me again.
The simple truth is, atob doesn't really handle UTF8-strings - it's ASCII only.
Also, I wouldn't use bloatware like js-base64.
But webtoolkit does have a small, nice and very maintainable implementation:

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info
*
**/
var Base64 = {

    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="

    // public method for encoding
    , encode: function (input)
    {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length)
        {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2))
            {
                enc3 = enc4 = 64;
            }
            else if (isNaN(chr3))
            {
                enc4 = 64;
            }

            output = output +
                this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
                this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        } // Whend 

        return output;
    } // End Function encode 


    // public method for decoding
    ,decode: function (input)
    {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length)
        {
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64)
            {
                output = output + String.fromCharCode(chr2);
            }

            if (enc4 != 64)
            {
                output = output + String.fromCharCode(chr3);
            }

        } // Whend 

        output = Base64._utf8_decode(output);

        return output;
    } // End Function decode 


    // private method for UTF-8 encoding
    ,_utf8_encode: function (string)
    {
        var utftext = "";
        string = string.replace(/\r\n/g, "\n");

        for (var n = 0; n < string.length; n++)
        {
            var c = string.charCodeAt(n);

            if (c < 128)
            {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048))
            {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else
            {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        } // Next n 

        return utftext;
    } // End Function _utf8_encode 

    // private method for UTF-8 decoding
    ,_utf8_decode: function (utftext)
    {
        var string = "";
        var i = 0;
        var c, c1, c2, c3;
        c = c1 = c2 = 0;

        while (i < utftext.length)
        {
            c = utftext.charCodeAt(i);

            if (c < 128)
            {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224))
            {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else
            {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        } // Whend 

        return string;
    } // End Function _utf8_decode 

}

https://www.fileformat.info/info/unicode/utf8.htm

  • For any character equal to or below 127 (hex 0x7F), the UTF-8 representation is one byte. It is just the lowest 7 bits of the full unicode value. This is also the same as the ASCII value.

  • For characters equal to or below 2047 (hex 0x07FF), the UTF-8 representation is spread across two bytes. The first byte will have the two high bits set and the third bit clear (i.e. 0xC2 to 0xDF). The second byte will have the top bit set and the second bit clear (i.e. 0x80 to 0xBF).

  • For all characters equal to or greater than 2048 but less that 65535 (0xFFFF), the UTF-8 representation is spread across three bytes.

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

"SELECT ... IN (SELECT ...)" query in CodeIgniter

Look here.

Basically you have to do bind params:

$sql = "SELECT username FROM users WHERE locationid IN (SELECT locationid FROM locations WHERE countryid=?)"; 

$this->db->query($sql, '__COUNTRY_NAME__');

But, like Mr.E said, use joins:

$sql = "select username from users inner join locations on users.locationid = locations.locationid where countryid = ?"; 

$this->db->query($sql, '__COUNTRY_NAME__');

Git Cherry-Pick and Conflicts

Do, I need to resolve all the conflicts before proceeding to next cherry -pick

Yes, at least with the standard git setup. You cannot cherry-pick while there are conflicts.

Furthermore, in general conflicts get harder to resolve the more you have, so it's generally better to resolve them one by one.

That said, you can cherry-pick multiple commits at once, which would do what you are asking for. See e.g. How to cherry-pick multiple commits . This is useful if for example some commits undo earlier commits. Then you'd want to cherry-pick all in one go, so you don't have to resolve conflicts for changes that are undone by later commits.

Further, is it suggested to do cherry-pick or branch merge in this case?

Generally, if you want to keep a feature branch up to date with main development, you just merge master -> feature branch. The main advantage is that a later merge feature branch -> master will be much less painful.

Cherry-picking is only useful if you must exclude some changes in master from your feature branch. Still, this will be painful so I'd try to avoid it.

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"defer</script>

Add Defer to the end of your Script tag, it worked for me (;

Everything needs to be loaded in the correct order (:

Comparing strings in C# with OR in an if statement

try

if (testString.Equals(testString2)){
}

Add column to dataframe with constant value

Single liner works

df['Name'] = 'abc'

Creates a Name column and sets all rows to abc value

Capturing a single image from my webcam in Java or Python

@thebjorn has given a good answer. But if you want more options, you can try OpenCV, SimpleCV.

using SimpleCV (not supported in python3.x):

from SimpleCV import Image, Camera

cam = Camera()
img = cam.getImage()
img.save("filename.jpg")

using OpenCV:

from cv2 import *
# initialize the camera
cam = VideoCapture(0)   # 0 -> index of camera
s, img = cam.read()
if s:    # frame captured without any errors
    namedWindow("cam-test",CV_WINDOW_AUTOSIZE)
    imshow("cam-test",img)
    waitKey(0)
    destroyWindow("cam-test")
    imwrite("filename.jpg",img) #save image

using pygame:

import pygame
import pygame.camera

pygame.camera.init()
pygame.camera.list_cameras() #Camera detected or not
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
img = cam.get_image()
pygame.image.save(img,"filename.jpg")

Install OpenCV:

install python-opencv bindings, numpy

Install SimpleCV:

install python-opencv, pygame, numpy, scipy, simplecv

get latest version of SimpleCV

Install pygame:

install pygame

Detect page change on DataTable

Paging events are handled in this way,

 $(document).ready(function() {

    $('#example')
        .on( 'order.dt',  function () { console.log('Order' ); } )
        .on( 'search.dt', function () {console.log('Search' ); } )
        .on( 'page.dt',   function () { console.log('Page' ); } )
        .dataTable();
} );

documented in the official website, here http://www.datatables.net/examples/advanced_init/dt_events.html

The length.dt event is fired whenever the table's page length is changed

$('#example').dataTable();

$('#example').on( 'length.dt', function ( e, settings, len ) {
    console.log( 'New page length: '+len );
} );

http://datatables.net/reference/event/length

More events here

datatables.net/reference/event/

Eclipse comment/uncomment shortcut?

Single comment ctrl + / and also multiple line comment you can select multiple line and then ctrl + /. Then, to remove comment you can use ctrl + c for both single line and multiple line comment.

Fitting empirical distribution to theoretical ones with Scipy (Python)?

AFAICU, your distribution is discrete (and nothing but discrete). Therefore just counting the frequencies of different values and normalizing them should be enough for your purposes. So, an example to demonstrate this:

In []: values= [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4]
In []: counts= asarray(bincount(values), dtype= float)
In []: cdf= counts.cumsum()/ counts.sum()

Thus, probability of seeing values higher than 1 is simply (according to the complementary cumulative distribution function (ccdf):

In []: 1- cdf[1]
Out[]: 0.40000000000000002

Please note that ccdf is closely related to survival function (sf), but it's also defined with discrete distributions, whereas sf is defined only for contiguous distributions.

How to get response status code from jQuery.ajax?

It is probably more idiomatic jQuery to use the statusCode property of the parameter object passed to the the $.ajax function:

$.ajax({
  statusCode: {
    500: function(xhr) {
      if(window.console) console.log(xhr.responseText);
    }
  }
});

However, as Livingston Samuel said, it is not possible to catch 301 status codes in javascript.

Visual Studio: How to break on handled exceptions?

Took me a while to find the new place for expection settings, therefore a new answer.

Since Visual Studio 2015 you control which Exceptions to stop on in the Exception Settings Window (Debug->Windows->Exception Settings). The shortcut is still Ctrl-Alt-E.

The simplest way to handle custom exceptions is selecting "all exceptions not in this list".

Here is a screenshot from the english version:

enter image description here

Here is a screenshot from the german version:

enter image description here

How to replace local branch with remote branch entirely in Git?

  1. Make sure you've checked out the branch you're replacing (from Zoltán's comment).
  2. Assuming that master is the local branch you're replacing, and that "origin/master" is the remote branch you want to reset to:

    git reset --hard origin/master
    

This updates your local HEAD branch to be the same revision as origin/master, and --hard will sync this change into the index and workspace as well.