Programs & Examples On #Hebrew

The Hebrew language is written right to left (RTL), much like Arabic and Farsi, requiring special handling when mixing Roman numerals and Latin characters in order to maintain correct flow.

Adding Google Translate to a web site

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

Detect Browser Language in PHP

The following script is a modified version of Xeoncross's code (thank you for that Xeoncross) that falls-back to a default language setting if no languages match the supported ones, or if a match is found it replaces the default language setting with a new one according to the language priority.

In this scenario the user's browser is set in order of priority to Spanish, Dutch, US English and English and the application supports English and Dutch only with no regional variations and English is the default language. The order of the values in the "HTTP_ACCEPT_LANGUAGE" string is not important if for some reason the browser does not order the values correctly.

$supported_languages = array("en","nl");
$supported_languages = array_flip($supported_languages);
var_dump($supported_languages); // array(2) { ["en"]=> int(0) ["nl"]=> int(1) }

$http_accept_language = $_SERVER["HTTP_ACCEPT_LANGUAGE"]; // es,nl;q=0.8,en-us;q=0.5,en;q=0.3

preg_match_all('~([\w-]+)(?:[^,\d]+([\d.]+))?~', strtolower($http_accept_language), $matches, PREG_SET_ORDER);

$available_languages = array();

foreach ($matches as $match)
{
    list($language_code,$language_region) = explode('-', $match[1]) + array('', '');

    $priority = isset($match[2]) ? (float) $match[2] : 1.0;

    $available_languages[][$language_code] = $priority;
}

var_dump($available_languages);

/*
array(4) {
    [0]=>
    array(1) {
        ["es"]=>
        float(1)
    }
    [1]=>
    array(1) {
        ["nl"]=>
        float(0.8)
    }
    [2]=>
    array(1) {
        ["en"]=>
        float(0.5)
    }
    [3]=>
    array(1) {
        ["en"]=>
        float(0.3)
    }
}
*/

$default_priority = (float) 0;
$default_language_code = 'en';

foreach ($available_languages as $key => $value)
{
    $language_code = key($value);
    $priority = $value[$language_code];

    if ($priority > $default_priority && array_key_exists($language_code,$supported_languages))
    {
        $default_priority = $priority;
        $default_language_code = $language_code;

        var_dump($default_priority); // float(0.8)
        var_dump($default_language_code); // string(2) "nl"
    }
}

var_dump($default_language_code); // string(2) "nl" 

How do I filter ForeignKey choices in a Django ModelForm?

If you haven't created the form and want to change the queryset you can do:

formmodel.base_fields['myfield'].queryset = MyModel.objects.filter(...)

This is pretty useful when you are using generic views!

Logarithmic returns in pandas dataframe

@poulter7: I cannot comment on the other answers, so I post it as new answer: be careful with

np.log(df.price).diff() 

as this will fail for indices which can become negative as well as risk factors e.g. negative interest rates. In these cases

np.log(df.price/df.price.shift(1)).dropna()

is preferred and based on my experience generally the safer approach. It also evaluates the logarithm only once.

Whether you use +1 or -1 depends on the ordering of your time series. Use -1 for descending and +1 for ascending dates - in both cases the shift provides the preceding date's value.

Find a value in an array of objects in Javascript

Here is the solution for search and replace

function searchAndUpdate(name,replace){
    var obj = array.filter(function ( obj ) {
        return obj.name === name;
    })[0];
    obj.name = replace;
}

searchAndUpdate("string 2","New String 2");

Oracle SQL: Update a table with data from another table

If your table t1 and it's backup t2 have many columns, here's a compact way to do it.

In addition, my related problem was that only some of the columns were modified and many rows had no edits to these columns, so I wanted to leave those alone - basically restore a subset of columns from a backup of the entire table. If you want to just restore all rows, skip the where clause.

Of course the simpler way would be to delete and insert as select, but in my case I needed a solution with just updates.

The trick is that when you do select * from a pair of tables with duplicate column names, the 2nd one will get named _1. So here's what I came up with:

  update (
    select * from t1 join t2 on t2.id = t1.id
    where id in (
      select id from (
        select id, col1, col2, ... from t2
        minus select id, col1, col2, ... from t1
      )
    )
  ) set col1=col1_1, col2=col2_1, ...

How to get rid of the "No bootable medium found!" error in Virtual Box?

Follow the steps below:

1) Select your VM Instance. Go to Settings->Storage

2) Under the storage tree select the default image or "Empty"(which ever is present)

3) Under the attributes frame, click on the CD image and select "Choose a virtual CD/DVD disk file"

4) Browse and select the image file(iso or what ever format) from the system

5) Select OK.

Abishek's solution is correct. But the highlighted area in 2nd image could be misleading.

Java - Opposite of .contains (does not contain)

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}

htaccess Access-Control-Allow-Origin

Add an .htaccess file with the following directives to your fonts folder, if have problems accessing your fonts. Can easily be modified for use with .css or .js files.

<FilesMatch "\.(eot|ttf|otf|woff)$">
    Header set Access-Control-Allow-Origin "*"
</FilesMatch>

What's the difference between map() and flatMap() methods in Java 8?

Map:- This method takes one Function as an argument and returns a new stream consisting of the results generated by applying the passed function to all the elements of the stream.

Let's imagine, I have a list of integer values ( 1,2,3,4,5 ) and one function interface whose logic is square of the passed integer. ( e -> e * e ).

List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> newList = intList.stream().map( e -> e * e ).collect(Collectors.toList());

System.out.println(newList);

output:-

[1, 4, 9, 16, 25]

As you can see, an output is a new stream whose values are square of values of the input stream.

[1, 2, 3, 4, 5] -> apply e -> e * e -> [ 1*1, 2*2, 3*3, 4*4, 5*5 ] -> [1, 4, 9, 16, 25 ]

http://codedestine.com/java-8-stream-map-method/

FlatMap :- This method takes one Function as an argument, this function accepts one parameter T as an input argument and returns one stream of parameter R as a return value. When this function is applied to each element of this stream, it produces a stream of new values. All the elements of these new streams generated by each element are then copied to a new stream, which will be a return value of this method.

Let's image, I have a list of student objects, where each student can opt for multiple subjects.

List<Student> studentList = new ArrayList<Student>();

  studentList.add(new Student("Robert","5st grade", Arrays.asList(new String[]{"history","math","geography"})));
  studentList.add(new Student("Martin","8st grade", Arrays.asList(new String[]{"economics","biology"})));
  studentList.add(new Student("Robert","9st grade", Arrays.asList(new String[]{"science","math"})));

  Set<Student> courses = studentList.stream().flatMap( e -> e.getCourse().stream()).collect(Collectors.toSet());

  System.out.println(courses);

output:-

[economics, biology, geography, science, history, math]

As you can see, an output is a new stream whose values are a collection of all the elements of the streams return by each element of the input stream.

[ S1 , S2 , S3 ] -> [ {"history","math","geography"}, {"economics","biology"}, {"science","math"} ] -> take unique subjects -> [economics, biology, geography, science, history, math]

http://codedestine.com/java-8-stream-flatmap-method/

Gradle: Could not determine java version from '11.0.2'

In my case the JAVA_HOME variable was set to /usr/lib/jvm/jdk-11.0.2/. It was sufficient to unset the variable like this:

$ export JAVA_HOME=

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

The simplest approach is to use a multitouch JavaScript library like Hammer.js. Then you can write code like:

canvas
    .hammer({prevent_default: true})
    .bind('doubletap', function(e) { // And double click
        // Zoom-in
    })
    .bind('dragstart', function(e) { // And mousedown
        // Get ready to drag
    })
    .bind('drag', function(e) { // And mousemove when mousedown
        // Pan the image
    })
    .bind('dragend', function(e) { // And mouseup
        // Finish the drag
    });

And you can keep going. It supports tap, double tap, swipe, hold, transform (i.e., pinch) and drag. The touch events also fire when equivalent mouse actions happen, so you don't need to write two sets of event handlers. Oh, and you need the jQuery plugin if you want to be able to write in the jQueryish way as I did.

Text blinking jQuery

result

$('.blink').fadeIn('fast')
    .animate({
        color: "#FFCD56"
    }, 100).animate({
        color: "white"
    }, 100)
    .animate({
        color: "#FFCD56"
    }, 100).animate({
        color: "white"
    }, 100)
    .animate({
        color: "#FFCD56"
    }, 100).animate({
        color: "white"
    }, 100)
    .animate({
        color: "#FFCD56"
    }, 100).animate({
        color: "white"
    }, 100)
    .animate({
        color: "#FFCD56"
    }, 100).animate({
        color: "white"
    }, 100);

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

You can find out the option for changing browser in Window menu.

See image at below.

enter image description here

This image can be easy to understand.

Node.js client for a socket.io server

Yes you can use any client as long as it is supported by socket.io. No matter whether its node, java, android or swift. All you have to do is install the client package of socket.io.

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

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

Android difference between Two Dates

I arranged a little. This works great.

@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
    Date date = new Date();
    String dateOfDay = simpleDateFormat.format(date);

    String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();

    @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
    try {
        Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
        Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);

        printDifference(date1, date2);

    } catch (ParseException e) {
        e.printStackTrace();
    }

@SuppressLint("SetTextI18n")
private void printDifference(Date startDate, Date endDate) {
    //milliseconds
    long different = endDate.getTime() - startDate.getTime();

    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long elapsedDays = different / daysInMilli;
    different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;
    different = different % minutesInMilli;

    long elapsedSeconds = different / secondsInMilli;

Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
}

How do I get an element to scroll into view, using jQuery?

After trying to find a solution that handled every circumstance (options for animating the scroll, padding around the object once it scrolls into view, works even in obscure circumstances such as in an iframe), I finally ended up writing my own solution to this. Since it seems to work when many other solutions failed, I thought I'd share it:

function scrollIntoViewIfNeeded($target, options) {

    var options = options ? options : {},
    $win = $($target[0].ownerDocument.defaultView), //get the window object of the $target, don't use "window" because the element could possibly be in a different iframe than the one calling the function
    $container = options.$container ? options.$container : $win,        
    padding = options.padding ? options.padding : 20,
    elemTop = $target.offset().top,
    elemHeight = $target.outerHeight(),
    containerTop = $container.scrollTop(),
    //Everything past this point is used only to get the container's visible height, which is needed to do this accurately
    containerHeight = $container.outerHeight(),
    winTop = $win.scrollTop(),
    winBot = winTop + $win.height(),
    containerVisibleTop = containerTop < winTop ? winTop : containerTop,
    containerVisibleBottom = containerTop + containerHeight > winBot ? winBot : containerTop + containerHeight,
    containerVisibleHeight = containerVisibleBottom - containerVisibleTop;

    if (elemTop < containerTop) {
        //scroll up
        if (options.instant) {
            $container.scrollTop(elemTop - padding);
        } else {
            $container.animate({scrollTop: elemTop - padding}, options.animationOptions);
        }
    } else if (elemTop + elemHeight > containerTop + containerVisibleHeight) {
        //scroll down
        if (options.instant) {
            $container.scrollTop(elemTop + elemHeight - containerVisibleHeight + padding);
        } else {
            $container.animate({scrollTop: elemTop + elemHeight - containerVisibleHeight + padding}, options.animationOptions);
        }
    }
}

$target is a jQuery object containing the object you wish to scroll into view if needed.

options (optional) can contain the following options passed in an object:

options.$container - a jQuery object pointing to the containing element of $target (in other words, the element in the dom with the scrollbars). Defaults to the window that contains the $target element and is smart enough to select an iframe window. Remember to include the $ in the property name.

options.padding - the padding in pixels to add above or below the object when it is scrolled into view. This way it is not right against the edge of the window. Defaults to 20.

options.instant - if set to true, jQuery animate will not be used and the scroll will instantly pop to the correct location. Defaults to false.

options.animationOptions - any jQuery options you wish to pass to the jQuery animate function (see http://api.jquery.com/animate/). With this, you can change the duration of the animation or have a callback function executed when the scrolling is complete. This only works if options.instant is set to false. If you need to have an instant animation but with a callback, set options.animationOptions.duration = 0 instead of using options.instant = true.

Sending email from Azure

For people wanting to use the built-in .NET SmtpClient rather than the SendGrid client library (not sure if that was the OP's intent), I couldn't get it to work unless I used apikey as my username and the api key itself as the password as outlined here.

<mailSettings>
    <smtp>
        <network host="smtp.sendgrid.net" port="587" userName="apikey" password="<your key goes here>" />
    </smtp>
</mailSettings>

remove table row with specific id

Try

$('table#test tr#3').remove();

Rotating a point about another point (2D)

First subtract the pivot point (cx,cy), then rotate it, then add the point again.

Untested:

POINT rotate_point(float cx,float cy,float angle,POINT p)
{
  float s = sin(angle);
  float c = cos(angle);

  // translate point back to origin:
  p.x -= cx;
  p.y -= cy;

  // rotate point
  float xnew = p.x * c - p.y * s;
  float ynew = p.x * s + p.y * c;

  // translate point back:
  p.x = xnew + cx;
  p.y = ynew + cy;
  return p;
}

length and length() in Java

I just want to add some remarks to the great answer by Fredrik.

The Java Language Specification in Section 4.3.1 states

An object is a class instance or an array.

So array has indeed a very special role in Java. I do wonder why.

One could argue that current implementation array is/was important for a better performance. But than it is an internal structure, which should not be exposed.

They could of course have masked the property as a method call and handled it in the compiler but I think it would have been even more confusing to have a method on something that isn't a real class.

I agree with Fredrik, that a smart compiler optimazation would have been the better choice. This would also solve the problem, that even if you use a property for arrays, you have not solved the problem for strings and other (immutable) collection types, because, e.g., string is based on a char array as you can see on the class definition of String:

public final class String implements java.io.Serializable, Comparable<String>, CharSequence {           
    private final char value[]; // ...

And I do not agree with that it would be even more confusing, because array does inherit all methods from java.lang.Object.

As an engineer I really do not like the answer "Because it has been always this way." and wished there would be a better answer. But in this case it seems to be.

tl;dr

In my opinion, it is a design flaw of Java and should not have implemented this way.

Getting a union of two arrays in JavaScript

_x000D_
_x000D_
function unionArrays() {_x000D_
    var args = arguments,_x000D_
    l = args.length,_x000D_
    obj = {},_x000D_
    res = [],_x000D_
    i, j, k;_x000D_
_x000D_
    while (l--) {_x000D_
        k = args[l];_x000D_
        i = k.length;_x000D_
_x000D_
        while (i--) {_x000D_
            j = k[i];_x000D_
            if (!obj[j]) {_x000D_
                obj[j] = 1;_x000D_
                res.push(j);_x000D_
            }_x000D_
        }   _x000D_
    }_x000D_
_x000D_
    return res;_x000D_
}_x000D_
var unionArr = unionArrays([34, 35, 45, 48, 49], [44, 55]);_x000D_
console.log(unionArr);
_x000D_
_x000D_
_x000D_

Somewhat similar in approach to alejandro's method, but a little shorter and should work with any number of arrays.

How to add a custom button to the toolbar that calls a JavaScript function?

If you have customized the ckeditor toolbar then use this method:

_x000D_
_x000D_
var editor = CKEDITOR.replace("da_html", {_x000D_
  disableNativeSpellChecker: false,_x000D_
  toolbar: [{_x000D_
      name: "clipboard",_x000D_
      items: ["Cut", "Copy", "Paste", "PasteText", "PasteFromWord", "-", "Undo", "Redo"]_x000D_
    },_x000D_
    "/",_x000D_
    {_x000D_
      name: "basicstyles",_x000D_
      items: ["Italic"]_x000D_
    },_x000D_
    {_x000D_
      name: "paragraph",_x000D_
      items: ["BulletedList"]_x000D_
    },_x000D_
    {_x000D_
      name: "insert",_x000D_
      items: ["Table"]_x000D_
    },_x000D_
    "/",_x000D_
    {_x000D_
      name: "styles",_x000D_
      items: ["Styles", "Format", "Font", "FontSize"]_x000D_
    },_x000D_
    {_x000D_
      name: "colors",_x000D_
      items: ["TextColor", "BGColor"]_x000D_
    },_x000D_
    {_x000D_
      name: "tools",_x000D_
      items: ["Maximize", "saveButton"]_x000D_
    },_x000D_
  ]_x000D_
});_x000D_
_x000D_
editor.addCommand("mySaveCommand", { // create named command_x000D_
  exec: function(edt) {_x000D_
    alert(edt.getData());_x000D_
  }_x000D_
});_x000D_
_x000D_
editor.ui.addButton("saveButton", { // add new button and bind our command_x000D_
  label: "Click me",_x000D_
  command: "mySaveCommand",_x000D_
  toolbar: "insert",_x000D_
  icon: "https://i.stack.imgur.com/IWRRh.jpg?s=328&g=1"_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="http://cdn.ckeditor.com/4.5.7/standard/ckeditor.js"></script>_x000D_
_x000D_
<textarea id="da_html">How are you!</textarea>
_x000D_
_x000D_
_x000D_

Working code in jsfiddle due to some security issue of stackoverflow: http://jsfiddle.net/k2vwqoyp/

Automatically plot different colored lines

Late to the party. I was looking into this myself and just found about this axes option called ColorOrder you can specify the colour order for the session or just for the figure and then just plot an array and let MATLAB automatically cycle through the colours specified.

see Changing the Default ColorOrder

example

set(0,'DefaultAxesColorOrder',jet(5))
A=rand(10,5);
plot(A);

Understanding colors on Android (six characters)

Going off the answer from @BlondeFurious, here is some Java code to get each hexadecimal value from 100% to 0% alpha:

for (double i = 1; i >= 0; i -= 0.01) {
    i = Math.round(i * 100) / 100.0d;
    int alpha = (int) Math.round(i * 255);
    String hex = Integer.toHexString(alpha).toUpperCase();
    if (hex.length() == 1)
        hex = "0" + hex;
    int percent = (int) (i * 100);
    System.out.println(String.format("%d%% — %s", percent, hex));
}

Output:

100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00

A JavaScript version is below:

_x000D_
_x000D_
var text = document.getElementById('text');_x000D_
for (var i = 1; i >= 0; i -= 0.01) {_x000D_
    i = Math.round(i * 100) / 100;_x000D_
    var alpha = Math.round(i * 255);_x000D_
    var hex = (alpha + 0x10000).toString(16).substr(-2).toUpperCase();_x000D_
    var perc = Math.round(i * 100);_x000D_
    text.innerHTML += perc + "% — " + hex + " (" + alpha + ")</br>";_x000D_
}
_x000D_
<div id="text"></div>
_x000D_
_x000D_
_x000D_


You can also just Google "number to hex" where 'number' is any value between 0 and 255.

Git with SSH on Windows

I fought with this problem for a few hours before stumbling on the obvious answer. The problem I had was I was using different ssh implementations between when I generated my keys and when I used git.

I used ssh-keygen from the command prompt to generate my keys and but when I tried "git clone ssh://..." I got the same results as you, a prompt for the password and the message "fatal: The remote end hung up unexpectedly".

Determine which ssh windows is using by executing the Windows "where" command.

C:\where ssh
C:\Program Files (x86)\Git\bin\ssh.exe

The second line tells you which exact program will be executed.

Next you need to determine which ssh that git is using. Find this by:

C:\set GIT_SSH
GIT_SSH=C:\Program Files\TortoiseSVN\bin\TortoisePlink.exe

And now you see the problem.

To correct this simply execute:

C:\set GIT_SSH=C:\Program Files (x86)\Git\bin\ssh.exe

To check if changes are applied:

C:\set GIT_SSH
GIT_SSH=C:\Program Files (x86)\Git\bin\ssh.exe

Now git will be able to use the keys that you generated earlier.

This fix is so far only for the current window. To fix it completely you need to change your environment variable.

  1. Open Windows explorer
  2. Right-click Computer and select Properties
  3. Click Advanced System Settings link on the left
  4. Click the Environment Variables... button
  5. In the system variables section select the GIT_SSH variable and press the Edit... button
  6. Update the variable value.
  7. Press OK to close all windows

Now any future command windows you open will have the correct settings.

Hope this helps.

Iterating through a List Object in JSP

change the code to the following

<%! List eList = (ArrayList)session.getAttribute("empList");%>
....
<table>
    <%
    for(int i=0; i<eList.length;i++){%>
        <tr>
            <td><%= ((Employee)eList[i]).getEid() %></td>
            <td><%= ((Employee)eList[i]).getEname() %></td>  
        </tr>
      <%}%>
</table>

Why does this AttributeError in python occur?

This happens because the scipy module doesn't have any attribute named sparse. That attribute only gets defined when you import scipy.sparse.

Submodules don't automatically get imported when you just import scipy; you need to import them explicitly. The same holds for most packages, although a package can choose to import its own submodules if it wants to. (For example, if scipy/__init__.py included a statement import scipy.sparse, then the sparse submodule would be imported whenever you import scipy.)

JQuery Datatables : Cannot read property 'aDataSort' of undefined

For me, the bug was in DataTables itself; The code for sorting in DataTables 1.10.9 will not check for bounds; thus if you use something like

order: [[1, 'asc']]

with an empty table, there is no row idx 1 -> this exception ensures. This happened as the data for the table was being fetched asynchronously. Initially, on page loading the dataTable gets initialized without data. It should be updated later as soon as the result data is fetched.

My solution:

// add within function _fnStringToCss( s ) in datatables.js
// directly after this line
// srcCol = nestedSort[i][0];

if(srcCol >= aoColumns.length) {
    continue;
}

// this line follows:
// aDataSort = aoColumns[ srcCol ].aDataSort;

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

I understand that the answer was useful however for some reason it does not work for me however I have moved the situation with the following code and it is perfect

    <?php

$codigoarticulo = $_POST['codigoarticulo'];
$nombrearticulo = $_POST['nombrearticulo'];
$seccion        = $_POST['seccion'];
$precio         = $_POST['precio'];
$fecha          = $_POST['fecha'];
$importado      = $_POST['importado'];
$paisdeorigen   = $_POST['paisdeorigen'];
try {

  $server = 'mysql: host=localhost; dbname=usuarios';
  $user   = 'root';
  $pass   = '';
  $base   = new PDO($server, $user, $pass);

  $base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $base->query("SET character_set_results = 'utf8',
                     character_set_client = 'utf8',
                     character_set_connection = 'utf8',
                     character_set_database = 'utf8',
                     character_set_server = 'utf8'");

  $base->exec("SET character_set_results = 'utf8',
                     character_set_client = 'utf8',
                     character_set_connection = 'utf8',
                     character_set_database = 'utf8',
                     character_set_server = 'utf8'");

  $sql = "
  INSERT INTO productos
  (CÓDIGOARTÍCULO, NOMBREARTÍCULO, SECCIÓN, PRECIO, FECHA, IMPORTADO, PAÍSDEORIGEN)
  VALUES
  (:c_art, :n_art, :sec, :pre, :fecha_art, :import, :p_orig)";
// SE ejecuta la consulta ben prepare
  $result = $base->prepare($sql);
//  se pasan por parametros aqui
  $result->bindParam(':c_art', $codigoarticulo);
  $result->bindParam(':n_art', $nombrearticulo);
  $result->bindParam(':sec', $seccion);
  $result->bindParam(':pre', $precio);
  $result->bindParam(':fecha_art', $fecha);
  $result->bindParam(':import', $importado);
  $result->bindParam(':p_orig', $paisdeorigen);
  $result->execute();
  echo 'Articulo agregado';
} catch (Exception $e) {

  echo 'Error';
  echo $e->getMessage();
} finally {

}

?>

Casting a variable using a Type variable

Harm, the problem is you don't have a T.

you only have a Type variable.

Hint to MS, if you could do something like

TryCast<typeof(MyClass)>

if would solve all our problems.

Invert match with regexp

Build an expression that matches, and use !match()... (logical negation) That's probably how grep does anyway...

Easy pretty printing of floats in python?

You could use pandas.

Here is an example with a list:

In: import pandas as P
In: P.set_option('display.precision',3)
In: L = [3.4534534, 2.1232131, 6.231212, 6.3423423, 9.342342423]
In: P.Series(data=L)
Out: 
0    3.45
1    2.12
2    6.23
3    6.34
4    9.34
dtype: float64

If you have a dict d, and you want its keys as rows:

In: d
Out: {1: 0.453523, 2: 2.35423234234, 3: 3.423432432, 4: 4.132312312}

In: P.DataFrame(index=d.keys(), data=d.values())
Out:  
    0
1   0.45
2   2.35
3   3.42
4   4.13

And another way of giving dict to a DataFrame:

P.DataFrame.from_dict(d, orient='index')

Difference between 'struct' and 'typedef struct' in C++?

In this DDJ article, Dan Saks explains one small area where bugs can creep through if you do not typedef your structs (and classes!):

If you want, you can imagine that C++ generates a typedef for every tag name, such as

typedef class string string;

Unfortunately, this is not entirely accurate. I wish it were that simple, but it's not. C++ can't generate such typedefs for structs, unions, or enums without introducing incompatibilities with C.

For example, suppose a C program declares both a function and a struct named status:

int status(); struct status;

Again, this may be bad practice, but it is C. In this program, status (by itself) refers to the function; struct status refers to the type.

If C++ did automatically generate typedefs for tags, then when you compiled this program as C++, the compiler would generate:

typedef struct status status;

Unfortunately, this type name would conflict with the function name, and the program would not compile. That's why C++ can't simply generate a typedef for each tag.

In C++, tags act just like typedef names, except that a program can declare an object, function, or enumerator with the same name and the same scope as a tag. In that case, the object, function, or enumerator name hides the tag name. The program can refer to the tag name only by using the keyword class, struct, union, or enum (as appropriate) in front of the tag name. A type name consisting of one of these keywords followed by a tag is an elaborated-type-specifier. For instance, struct status and enum month are elaborated-type-specifiers.

Thus, a C program that contains both:

int status(); struct status;

behaves the same when compiled as C++. The name status alone refers to the function. The program can refer to the type only by using the elaborated-type-specifier struct status.

So how does this allow bugs to creep into programs? Consider the program in Listing 1. This program defines a class foo with a default constructor, and a conversion operator that converts a foo object to char const *. The expression

p = foo();

in main should construct a foo object and apply the conversion operator. The subsequent output statement

cout << p << '\n';

should display class foo, but it doesn't. It displays function foo.

This surprising result occurs because the program includes header lib.h shown in Listing 2. This header defines a function also named foo. The function name foo hides the class name foo, so the reference to foo in main refers to the function, not the class. main can refer to the class only by using an elaborated-type-specifier, as in

p = class foo();

The way to avoid such confusion throughout the program is to add the following typedef for the class name foo:

typedef class foo foo;

immediately before or after the class definition. This typedef causes a conflict between the type name foo and the function name foo (from the library) that will trigger a compile-time error.

I know of no one who actually writes these typedefs as a matter of course. It requires a lot of discipline. Since the incidence of errors such as the one in Listing 1 is probably pretty small, you many never run afoul of this problem. But if an error in your software might cause bodily injury, then you should write the typedefs no matter how unlikely the error.

I can't imagine why anyone would ever want to hide a class name with a function or object name in the same scope as the class. The hiding rules in C were a mistake, and they should not have been extended to classes in C++. Indeed, you can correct the mistake, but it requires extra programming discipline and effort that should not be necessary.

Linq select to new object

All of the grouped objects, or all of the types? It sounds like you may just want:

var query = types.GroupBy(t => t.Type)
                 .Select(g => new { Type = g.Key, Count = g.Count() });

foreach (var result in query)
{
    Console.WriteLine("{0}, {1}", result.Type, result.Count);
}

EDIT: If you want it in a dictionary, you can just use:

var query = types.GroupBy(t => t.Type)
                 .ToDictionary(g => g.Key, g => g.Count());

There's no need to select into pairs and then build the dictionary.

Firefox 'Cross-Origin Request Blocked' despite headers

For posterity, also check server logs to see if the resource being requested is returning a 200.

I ran into a similar issue, where all of the proper headers were being returned in the pre-flight ajax request, but the browser reported the actual request was blocked due to bad CORS headers.

Turns out, the page being requested was returning a 500 error due to bad code, but only when it was fetched via CORS. The browser (both Chrome and Firefox) mistakenly reported that the Access-Control-Allow-Origin header was missing instead of saying the page returned a 500.

Access a JavaScript variable from PHP

JS ist browser-based, PHP is server-based. You have to generate some browser-based request/signal to get the data from the JS into the PHP. Take a look into Ajax.

Convert Python ElementTree to string

Non-Latin Answer Extension

Extension to @Stevoisiak's answer and dealing with non-Latin characters. Only one way will display the non-Latin characters to you. The one method is different on both Python 3 and Python 2.

Input

xml = ElementTree.fromstring('<Person Name="???" />')
xml = ElementTree.Element("Person", Name="???")  # Read Note about Python 2

NOTE: In Python 2, when calling the toString(...) code, assigning xml with ElementTree.Element("Person", Name="???")will raise an error...

UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 0: ordinal not in range(128)

Output

ElementTree.tostring(xml)
# Python 3 (???): b'<Person Name="&#53356;&#47532;&#49828;" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />


ElementTree.tostring(xml, encoding='unicode')
# Python 3 (???): <Person Name="???" />             <-------- Python 3
# Python 3 (John): <Person Name="John" />

# Python 2 (???): LookupError: unknown encoding: unicode
# Python 2 (John): LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3 (???): b'<Person Name="\xed\x81\xac\xeb\xa6\xac\xec\x8a\xa4" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="???" />             <-------- Python 2
# Python 2 (John): <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 3 (John): <Person Name="John" />

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />

What is the difference between logical data model and conceptual data model?

logical data model

A logical data model describes the data in as much detail as possible, without regard to how they will be physical implemented in the database. Features of a logical data model include: · Includes all entities and relationships among them. · All attributes for each entity are specified. · The primary key for each entity is specified. · Foreign keys (keys identifying the relationship between different entities) are specified. · Normalization occurs at this level. conceptual data model

A conceptual data model identifies the highest-level relationships between the different entities. Features of conceptual data model include: · Includes the important entities and the relationships among them. · No attribute is specified. · No primary key is specified.

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

.htaccess redirect all pages to new domain

May be like this:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^OLDDOMAIN\.com$ [NC]
RewriteRule ^(.*)$ http://NEWDOMAIN.com [R=301,L]

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

Suppress command line output

You can do this instead too:

tasklist | find /I "test.exe" > nul && taskkill /f /im test.exe > nul

Default interface methods are only supported starting with Android N

As CommonsWare mentioned, for reference add this inside the android {...} closure in the build.gradle for your app module to resolve issue:

android {
...
  compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
...
}

Merge (with squash) all changes from another branch as a single commit

Another option is git merge --squash <feature branch> then finally do a git commit.

From Git merge

--squash

--no-squash

Produce the working tree and index state as if a real merge happened (except for the merge information), but do not actually make a commit or move the HEAD, nor record $GIT_DIR/MERGE_HEAD to cause the next git commit command to create a merge commit. This allows you to create a single commit on top of the current branch whose effect is the same as merging another branch (or more in case of an octopus).

Export to csv/excel from kibana

FYI : How to download data in CSV from Kibana:

In Kibana--> 1. Go to 'Discover' in left side

  1. Select Index Field (based on your dashboard data) (*** In case if you are not sure which index to select-->go to management tab-->Saved Objects-->Dashboard-->select dashboard name-->scroll down to JSON-->you will see the Index name )

  2. left side you see all the variables available in the data-->click over the variable name that you want to have in csv-->click add-->this variable will be added on the right side of the columns avaliable

  3. Top right section of the kibana-->there is the time filter-->click -->select the duration for which you want the csv

  4. Top upper right -->Reporting-->save this time/variable selection with a new report-->click generate CSV

  5. Go to 'Management' in left side--> 'Reporting'-->download your csv

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

> is not in the documentation.

< is for one-way binding.

@ binding is for passing strings. These strings support {{}} expressions for interpolated values.

= binding is for two-way model binding. The model in parent scope is linked to the model in the directive's isolated scope.

& binding is for passing a method into your directive's scope so that it can be called within your directive.

When we are setting scope: true in directive, Angular js will create a new scope for that directive. That means any changes made to the directive scope will not reflect back in parent controller.

How to hide columns in an ASP.NET GridView with auto-generated columns?

Try putting the e.Row.Cells[0].Visible = false; inside the RowCreated event of your grid.

protected void bla_RowCreated(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[0].Visible = false; // hides the first column
}

This way it auto-hides the whole column.

You don't have access to the generated columns through grid.Columns[i] in your gridview's DataBound event.

Display all post meta keys and meta values of the same post ID in wordpress

As of Jan 2020 and WordPress v5.3.2, I confirm the following works fine.

It will include the field keys with their equivalent underscore keys as well, but I guess if you properly "enum" your keys in your code, that should be no problem:

$meta_values   = get_post_meta( get_the_ID() );
$example_field = meta_values['example_field_key'][0];

//OR if you do enum style 
//(emulation of a class with a list of *const* as enum does not exist in PHP per se)
$example_field = meta_values[PostTypeEnum::FIELD_EXAMPLE_KEY][0]; 

As the print_r(meta_values); gives:

Array
(
    [_edit_lock] => Array
        (
            [0] => 1579542560:1
        )

    [_edit_last] => Array
        (
            [0] => 1
        )

    [example_field] => Array
        (
            [0] => 13
        )
)

Hope that helps someone, go make a ruckus!

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

I ran across this post today as I was running into the same issue and had the same problem of the javascript not running with the CDATA tags listed above. I corrected the CDATA tags to look like:

<script type="text/javascript">
//<![CDATA[ 

your javascript code here

//]]>
</script>

Then everything worked perfectly!

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

For anyone that is using MariaDB instead of MySQL, the solution is to install the libmariadbclient-dev package and create a symbolic link to the config file with the correct name.

For example this worked for me:

ln -s /usr/bin/mariadb_config /usr/bin/mysql_config

Server certificate verification failed: issuer is not trusted

I wouldn't use:

svn checkout

just to authorizes the server authentication, I rather use:

svn list https://your.repository.url

which will ask you to do the authentication as well.

If this is needed to get authorization to a user that can't login, run:

sudo -u username svn list https://your.repository.url

Curl error: Operation timed out

In curl request add time out 0 so its infinite time set like CURLOPT_TIMEOUT set 0

Convert date to another timezone in JavaScript

If you don't want to import some big library you could just use Intl.DateTimeFormat to convert Date objects to different timezones.

_x000D_
_x000D_
// Specifying timeZone is what causes the conversion, the rest is just formatting
const options = {
  year: '2-digit', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit', second: '2-digit',
  timeZone: 'Asia/Jakarta',
  timeZoneName: 'short'
}
const formatter = new Intl.DateTimeFormat('sv-SE', options)
const startingDate = new Date("2012/04/10 10:10:30 +0000")

const dateInNewTimezone = formatter.format(startingDate) 
console.log(dateInNewTimezone) // 12-04-10 17:10:30 GMT+7
_x000D_
_x000D_
_x000D_

Offsets, daylight saving, and changes in the past will be taken care of for you.

javascript: calculate x% of a number

In order to fully avoid floating point issues, the amount whose percent is being calculated and the percent itself need to be converted to integers. Here's how I resolved this:

function calculatePercent(amount, percent) {
    const amountDecimals = getNumberOfDecimals(amount);
    const percentDecimals = getNumberOfDecimals(percent);
    const amountAsInteger = Math.round(amount + `e${amountDecimals}`);
    const percentAsInteger = Math.round(percent + `e${percentDecimals}`);
    const precisionCorrection = `e-${amountDecimals + percentDecimals + 2}`;    // add 2 to scale by an additional 100 since the percentage supplied is 100x the actual multiple (e.g. 35.8% is passed as 35.8, but as a proper multiple is 0.358)

    return Number((amountAsInteger * percentAsInteger) + precisionCorrection);
}

function getNumberOfDecimals(number) {
    const decimals = parseFloat(number).toString().split('.')[1];

    if (decimals) {
        return decimals.length;
    }

    return 0;
}

calculatePercent(20.05, 10); // 2.005

As you can see, I:

  1. Count the number of decimals in both the amount and the percent
  2. Convert both amount and percent to integers using exponential notation
  3. Calculate the exponential notation needed to determine the proper end value
  4. Calculate the end value

The usage of exponential notation was inspired by Jack Moore's blog post. I'm sure my syntax could be shorter, but I wanted to be as explicit as possible in my usage of variable names and explaining each step.

Split value from one field to two

In MySQL this is working this option:

SELECT Substring(nameandsurname, 1, Locate(' ', nameandsurname) - 1) AS 
       firstname, 
       Substring(nameandsurname, Locate(' ', nameandsurname) + 1)    AS lastname 
FROM   emp  

Convert time fields to strings in Excel

This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it:

I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM") , drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text".

How to make RatingBar to show five stars

You can add default rating of five stars in side the xml layout

android:rating="5"

Edit:

<RatingBar
        android:id="@+id/rb_vvm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="@dimen/space2"
        android:layout_marginTop="@dimen/space1"
        style="@style/RatingBar"
        android:numStars="5"
        android:stepSize="1"
        android:rating="5" />

Removing duplicates from a String in Java

StringBuilder builderWord = new StringBuilder(word);
 for(int index=0; index < builderWord.length(); index++) {
   for(int reverseIndex=builderWord.length()-1; reverseIndex > index;reverseIndex--) {
     if (builderWord.charAt(reverseIndex) == builderWord.charAt(index)) {
       builderWord.deleteCharAt(reverseIndex);
     }
   }
}
return builderWord.toString();

How to resize the jQuery DatePicker control

We can alter in the default 'jquery-ui.css' file as below given code:

div.ui-datepicker {
font-size: 80%; 
}

However, changing the default 'jquery-ui.css' file is not recommended as it might have been used somewhere else in the project. Changing values in the default file can alter datepicker font in other webpages where it has been used.

I used the below code to alter "font-size". I placed it just after datepicker() is called as shown below.

<script>
        $(function () {
            $( "#datepicker" ).datepicker();
            $("div.ui-datepicker").css("font-size", "80%")
        });
</script>

Hope this helps...

How to pass an array into a function, and return the results with an array

Try

$waffles = foo($waffles);

Or pass the array by reference, like suggested in the other answers.

In addition, you can add new elements to an array without writing the index, e.g.

$waffles = array(1,2,3); // filling on initialization

or

$waffles = array();
$waffles[] = 1;
$waffles[] = 2;
$waffles[] = 3;

On a sidenote, if you want to sum all values in an array, use array_sum()

How to append output to the end of a text file

Use command >> file_to_append_to to append to a file.

For example echo "Hello" >> testFile.txt

CAUTION: if you only use a single > you will overwrite the contents of the file. To ensure that doesn't ever happen, you can add set -o noclobber to your .bashrc.

This ensures that if you accidentally type command > file_to_append_to to an existing file, it will alert you that the file exists already. Sample error message: file exists: testFile.txt

Thus, when you use > it will only allow you to create a new file, not overwrite an existing file.

Why can't I use switch statement on a String?

In Java 11+ it's possible with variables too. The only condition is it must be a constant.

For Example:

final String LEFT = "left";
final String RIGHT = "right";
final String UP = "up";
final String DOWN = "down";

String var = ...;

switch (var) {
    case LEFT:
    case RIGHT:
    case DOWN:
    default:
        return 0;
}

PS. I've not tried this with earlier jdks. So please update the answer if it's supported there too.

Check array position for null/empty

There is no bound checking in array in C programming. If you declare array as

int arr[50];

Then you can even write as

arr[51] = 10;

The compiler would not throw an error. Hope this answers your question.

jquery change style of a div on click

$(document).ready(function() {
  $('#div_one').bind('click', function() {
    $('#div_two').addClass('large');
  });
});

If I understood your question.

Or you can modify css directly:

var $speech = $('div.speech');
var currentSize = $speech.css('fontSize');
$speech.css('fontSize', '10px');

How can I pad a value with leading zeros?

Just an another solution, but I think it's more legible.

_x000D_
_x000D_
function zeroFill(text, size)_x000D_
{_x000D_
  while (text.length < size){_x000D_
   text = "0" + text;_x000D_
  }_x000D_
  _x000D_
  return text;_x000D_
}
_x000D_
_x000D_
_x000D_

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

Best way to Bulk Insert from a C# DataTable

If using SQL Server, SqlBulkCopy.WriteToServer(DataTable)

Or also with SQL Server, you can write it to a .csv and use BULK INSERT

If using MySQL, you could write it to a .csv and use LOAD DATA INFILE

If using Oracle, you can use the array binding feature of ODP.NET

If SQLite:

WPF Datagrid Get Selected Cell Value

you can also use this function.

 public static void GetGridSelectedView(out string tuid, ref DataGrid dataGrid,string Column)
    {
        try
        {
            // grid selected row values
            var item = dataGrid.SelectedItem as DataRowView;
            if (null == item) tuid = null;
            if (item.DataView.Count > 0)
            {
                tuid =  item.DataView[dataGrid.SelectedIndex][Column].ToString().Trim();
            }
            else { tuid = null; }
        }
        catch (Exception exc) { System.Windows.MessageBox.Show(exc.Message); tuid = null; }
    }

Truncating Text in PHP?

$mystring = "this is the text I would like to truncate";

// Pass your variable to the function
$mystring = truncate($mystring);

// Truncated tring printed out;
echo $mystring;

//truncate text function
public function truncate($text) {

    //specify number fo characters to shorten by
    $chars = 25;

    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

Count multiple columns with group by in one query

One solution is to wrap it in a subquery

SELECT *
FROM
(
    SELECT COUNT(column1),column1 FROM table GROUP BY column1
    UNION ALL
    SELECT COUNT(column2),column2 FROM table GROUP BY column2
    UNION ALL
    SELECT COUNT(column3),column3 FROM table GROUP BY column3
) s

How to define a Sql Server connection string to use in VB.NET?

Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.IO
Imports System.Configuration
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Dim cn As New SqlConnection(connectionString)
Dim cmd As New SqlCommand
Dim dr As SqlDataAdapter

Convert object array to hash map, indexed by an attribute value of the Object

try

let toHashMap = (a,f) => a.reduce((a,c)=> (a[f(c)]=c,a),{});

_x000D_
_x000D_
let arr=[_x000D_
  {id:123, name:'naveen'}, _x000D_
  {id:345, name:"kumar"}_x000D_
];_x000D_
_x000D_
let fkey = o => o.id; // function changing object to string (key)_x000D_
_x000D_
let toHashMap = (a,f) => a.reduce((a,c)=> (a[f(c)]=c,a),{});_x000D_
_x000D_
console.log( toHashMap(arr,fkey) );_x000D_
_x000D_
// Adding to prototype is NOT recommented:_x000D_
//_x000D_
// Array.prototype.toHashMap = function(f) { return toHashMap(this,f) };_x000D_
// console.log( arr.toHashMap(fkey) );
_x000D_
_x000D_
_x000D_

Execute a terminal command from a Cocoa app

There is also good old POSIX system("echo -en '\007'");

Detect all Firefox versions in JS

    <script type="text/javascript">
           var isChrome = /Chrome/.test(navigator.userAgent) && /Google 
                           Inc/.test(navigator.vendor);
           var isFirefox = 
                  navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
           if (isChrome) 
           { 
               document.write('<'+'link rel="stylesheet" 
                                  href="css/chrome.css" />');

           }
          else if(isFirefox)
           {
               document.write('<'+'link rel="stylesheet" 
                                  href="css/Firefox.css" />');
           }
           else
           {
                document.write('<'+'link rel="stylesheet" 
                                   href="css/IE.css" />');
            }

     </script>

This works perfect for IE,Firefox and Chrome.

Read MS Exchange email in C#

  1. The currently preferred (Exchange 2013 and 2016) API is EWS. It is purely HTTP based and can be accessed from any language, but there are .Net and Java specific libraries.

    You can use EWSEditor to play with the API.

  2. Extended MAPI. This is the native API used by Outlook. It ends up using the MSEMS Exchange MAPI provider, which can talk to Exchange using RPC (Exchange 2013 no longer supports it) or RPC-over-HTTP (Exchange 2007 or newer) or MAPI-over-HTTP (Exchange 2013 and newer).

    The API itself can only be accessed from unmanaged C++ or Delphi. You can also use Redemption (any language) - its RDO family of objects is an Extended MAPI wrapper. To use Extended MAPI, you need to install either Outlook or the standalone (Exchange) version of MAPI (on extended support, and it does not support Unicode PST and MSG files and cannot access Exchange 2016). Extended MAPI can be used in a service.

    You can play with the API using OutlookSpy or MFCMAPI.

  3. Outlook Object Model - not Exchange specific, but it allows access to all data available in Outlook on the machine where the code runs. Cannot be used in a service.

  4. Exchange Active Sync. Microsoft no longer invests any significant resources into this protocol.

  5. Outlook used to install CDO 1.21 library (it wraps Extended MAPI), but it had been deprecated by Microsoft and no longer receives any updates.

  6. There used to be a third-party .Net MAPI wrapper called MAPI33, but it is no longer being developed or supported.

  7. WebDAV - deprecated.

  8. Collaborative Data Objects for Exchange (CDOEX) - deprecated.

  9. Exchange OLE DB Provider (EXOLEDB) - deprecated.

Laravel form html with PUT method for PUT routes

Just use like this somewhere inside the form

@method('PUT')

Creating email templates with Django

Boys and Girls!

Since Django's 1.7 in send_email method the html_message parameter was added.

html_message: If html_message is provided, the resulting email will be a multipart/alternative email with message as the text/plain content type and html_message as the text/html content type.

So you can just:

from django.core.mail import send_mail
from django.template.loader import render_to_string


msg_plain = render_to_string('templates/email.txt', {'some_params': some_params})
msg_html = render_to_string('templates/email.html', {'some_params': some_params})

send_mail(
    'email title',
    msg_plain,
    '[email protected]',
    ['[email protected]'],
    html_message=msg_html,
)

How do I deal with certificates using cURL while trying to access an HTTPS url?

I also had the newest version of ca-certificates installed but was still getting the error:

curl: (77) error setting certificate verify locations:
  CAfile: /etc/pki/tls/certs/ca-bundle.crt
  CApath: none

The issue was that curl expected the certificate to be at the path /etc/pki/tls/certs/ca-bundle.crt but could not find it because it was at the path /etc/ssl/certs/ca-certificates.crt.

Copying my certificate to the expected destination by running

sudo cp /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt

worked for me. You will need to create folders for the target destination if they do not exist by running

sudo mkdir -p /etc/pki/tls/certs

If needed, modify the above command to make the destination file name match the path expected by curl, i.e. replace /etc/pki/tls/certs/ca-bundle.crt with the path following "CAfile:" in your error message.

Get current date in Swift 3?

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)

Handling back button in Android Navigation Component

If you use Navigation Component follow the codes below in your onCreateView() method (in this example I want just to close my app by this fragment)

 OnBackPressedCallback backPressedCallback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            new AlertDialog.Builder(Objects.requireNonNull(getActivity()))
                    .setIcon(R.drawable.icon_01)
                    .setTitle(getResources().getString(R.string.close_app_title))
                    .setMessage(getResources().getString(R.string.close_app_message))
                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            getActivity().finish();
                        }
                    })
                    .setNegativeButton(R.string.no, null)
                    .show();
        }
    };
    requireActivity().getOnBackPressedDispatcher().addCallback(this, backPressedCallback);

What's a good way to extend Error in JavaScript?

Custom Error Decorator

This is based on George Bailey's answer, but extends and simplifies the original idea. It is written in CoffeeScript, but is easy to convert to JavaScript. The idea is extend Bailey's custom error with a decorator that wraps it, allowing you to create new custom errors easily.

Note: This will only work in V8. There is no support for Error.captureStackTrace in other environments.

Define

The decorator takes a name for the error type, and returns a function that takes an error message, and encloses the error name.

CoreError = (@message) ->

    @constructor.prototype.__proto__ = Error.prototype
    Error.captureStackTrace @, @constructor
    @name = @constructor.name

BaseError = (type) ->

    (message) -> new CoreError "#{ type }Error: #{ message }"

Use

Now it is simple to create new error types.

StorageError   = BaseError "Storage"
SignatureError = BaseError "Signature"

For fun, you could now define a function that throws a SignatureError if it is called with too many args.

f = -> throw SignatureError "too many args" if arguments.length

This has been tested pretty well and seems to work perfectly on V8, maintaing the traceback, position etc.

Note: Using new is optional when constructing a custom error.

Counting duplicates in Excel

You can achieve your result in two steps. First, create a list of unique entries using Advanced Filter... from the pull down Filter menu. To do so, you have to add a name of the column to be sorted out. It is necessary, otherwise Excel will treat first row as a name rather than an entry. Highlight column that you want to filter (A in the example below), click the filter icon and chose 'Advanced Filter...'. That will bring up a window where you can select an option to "Copy to another location". Choose that one, as you will need your original list to do counts (in my example I will choose C:C). Also, select "Unique record only". That will give you a list of unique entries. Then you can count their frequencies using =COUNTIF() command. See screedshots for details.

Hope this helps!

  +--------+-------+--------+-------------------+
  |   A    |   B   |   C    |         D         |
  +--------+-------+--------+-------------------+
1 | ToSort |       | ToSort |                   |
  +--------+-------+--------+-------------------+
2 |  GL15  |       | GL15   | =COUNTIF(A:A, C2) |
  +--------+-------+--------+-------------------+
3 |  GL15  |       | GL16   | =COUNTIF(A:A, C3) |
  +--------+-------+--------+-------------------+
4 |  GL15  |       | GL17   | =COUNTIF(A:A, C4) |
  +--------+-------+--------+-------------------+
5 |  GL16  |       |        |                   |
  +--------+-------+--------+-------------------+
6 |  GL17  |       |        |                   |
  +--------+-------+--------+-------------------+
7 |  GL17  |       |        |                   |
  +--------+-------+--------+-------------------+

Step 1Step 2Step 3

Reloading submodules in IPython

http://shawnleezx.github.io/blog/2015/08/03/some-notes-on-ipython-startup-script/

To avoid typing those magic function again and again, they could be put in the ipython startup script(Name it with .py suffix under .ipython/profile_default/startup. All python scripts under that folder will be loaded according to lexical order), which looks like the following:

from IPython import get_ipython
ipython = get_ipython()

ipython.magic("pylab")
ipython.magic("load_ext autoreload")
ipython.magic("autoreload 2")

JS how to cache a variable

Use localStorage for that. It's persistent over sessions.

Writing :

localStorage['myKey'] = 'somestring'; // only strings

Reading :

var myVar = localStorage['myKey'] || 'defaultValue';

If you need to store complex structures, you might serialize them in JSON. For example :

Reading :

var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};

Writing :

localStorage['myKey'] = JSON.stringify(myVar);

Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.

Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.

Proper way to handle multiple forms on one page in Django

Here is simple way to handle the above.

In Html Template we put Post

<form action="/useradd/addnewroute/" method="post" id="login-form">{% csrf_token %}

<!-- add details of form here-->
<form>
<form action="/useradd/addarea/" method="post" id="login-form">{% csrf_token %}

<!-- add details of form here-->

<form>

In View

   def addnewroute(request):
      if request.method == "POST":
         # do something



  def addarea(request):
      if request.method == "POST":
         # do something

In URL Give needed info like

urlpatterns = patterns('',
url(r'^addnewroute/$', views.addnewroute, name='addnewroute'),
url(r'^addarea/', include('usermodules.urls')),

How to unset (remove) a collection element after fetching it?

If you know the key which you unset then put directly by comma separated

unset($attr['placeholder'], $attr['autocomplete']);

Difference between binary tree and binary search tree

A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer, and a data element. The "root" pointer points to the topmost node in the tree. The left and right pointers recursively point to smaller "subtrees" on either side. A null pointer represents a binary tree with no elements -- the empty tree. The formal recursive definition is: a binary tree is either empty (represented by a null pointer), or is made of a single node, where the left and right pointers (recursive definition ahead) each point to a binary tree.

A binary search tree (BST) or "ordered binary tree" is a type of binary tree where the nodes are arranged in order: for each node, all elements in its left subtree are less to the node (<), and all the elements in its right subtree are greater than the node (>).

    5
   / \
  3   6 
 / \   \
1   4   9    

The tree shown above is a binary search tree -- the "root" node is a 5, and its left subtree nodes (1, 3, 4) are < 5, and its right subtree nodes (6, 9) are > 5. Recursively, each of the subtrees must also obey the binary search tree constraint: in the (1, 3, 4) subtree, the 3 is the root, the 1 < 3 and 4 > 3.

Watch out for the exact wording in the problems -- a "binary search tree" is different from a "binary tree".

How to read and write excel file

You can also consider JExcelApi. I find it better designed than POI. There's a tutorial here.

What is the best way to implement "remember me" for a website?

I would store a user ID and a token. When the user comes back to the site, compare those two pieces of information against something persistent like a database entry.

As for security, just don't put anything in there that will allow someone to modify the cookie to gain extra benefits. For example, don't store their user groups or their password. Anything that can be modified that would circumvent your security should not be stored in the cookie.

Difference in make_shared and normal shared_ptr in C++

I think the exception safety part of mr mpark's answer is still a valid concern. when creating a shared_ptr like this: shared_ptr< T >(new T), the new T may succeed, while the shared_ptr's allocation of control block may fail. in this scenario, the newly allocated T will leak, since the shared_ptr has no way of knowing that it was created in-place and it is safe to delete it. or am I missing something? I don't think the stricter rules on function parameter evaluation help in any way here...

How does the compilation/linking process work?

This topic is discussed at CProgramming.com:
https://www.cprogramming.com/compilingandlinking.html

Here is what the author there wrote:

Compiling isn't quite the same as creating an executable file! Instead, creating an executable is a multistage process divided into two components: compilation and linking. In reality, even if a program "compiles fine" it might not actually work because of errors during the linking phase. The total process of going from source code files to an executable might better be referred to as a build.

Compilation

Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the creation of an 'object' file. This step doesn't create anything the user can actually run. Instead, the compiler merely produces the machine language instructions that correspond to the source code file that was compiled. For instance, if you compile (but don't link) three separate files, you will have three object files created as output, each with the name .o or .obj (the extension will depend on your compiler). Each of these files contains a translation of your source code file into a machine language file -- but you can't run them yet! You need to turn them into executables your operating system can use. That's where the linker comes in.

Linking

Linking refers to the creation of a single executable file from multiple object files. In this step, it is common that the linker will complain about undefined functions (commonly, main itself). During compilation, if the compiler could not find the definition for a particular function, it would just assume that the function was defined in another file. If this isn't the case, there's no way the compiler would know -- it doesn't look at the contents of more than one file at a time. The linker, on the other hand, may look at multiple files and try to find references for the functions that weren't mentioned.

You might ask why there are separate compilation and linking steps. First, it's probably easier to implement things that way. The compiler does its thing, and the linker does its thing -- by keeping the functions separate, the complexity of the program is reduced. Another (more obvious) advantage is that this allows the creation of large programs without having to redo the compilation step every time a file is changed. Instead, using so called "conditional compilation", it is necessary to compile only those source files that have changed; for the rest, the object files are sufficient input for the linker. Finally, this makes it simple to implement libraries of pre-compiled code: just create object files and link them just like any other object file. (The fact that each file is compiled separately from information contained in other files, incidentally, is called the "separate compilation model".)

To get the full benefits of condition compilation, it's probably easier to get a program to help you than to try and remember which files you've changed since you last compiled. (You could, of course, just recompile every file that has a timestamp greater than the timestamp of the corresponding object file.) If you're working with an integrated development environment (IDE) it may already take care of this for you. If you're using command line tools, there's a nifty utility called make that comes with most *nix distributions. Along with conditional compilation, it has several other nice features for programming, such as allowing different compilations of your program -- for instance, if you have a version producing verbose output for debugging.

Knowing the difference between the compilation phase and the link phase can make it easier to hunt for bugs. Compiler errors are usually syntactic in nature -- a missing semicolon, an extra parenthesis. Linking errors usually have to do with missing or multiple definitions. If you get an error that a function or variable is defined multiple times from the linker, that's a good indication that the error is that two of your source code files have the same function or variable.

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

How can I make a button redirect my page to another page?

Just another variation:

    <body>
    <button name="redirect" onClick="redirect()">

    <script type="text/javascript">
    function redirect()
    {
    var url = "http://www.(url).com";
    window.location(url);
    }
    </script>

Running PowerShell as another user, and launching a script

In windows server 2012 or 2016 you can search for Windows PowerShell and then "Pin to Start". After this you will see "Run as different user" option on a right click on the start page tiles.

How can I display an RTSP video stream in a web page?

I have published project on Github that help you to stream ip/network camera on to web browser real time without plugin require, which I contributed to open source project under MIT License that might be matched to your need, here you go:

Streaming IP/Network Camera on web browser using NodeJS

There is no full package of framework yet, but it is a kickstart that might give you a way to proceed further.
As a student, I hope this helpful and please contribute to this project.

Call An Asynchronous Javascript Function Synchronously

You can also convert it into callbacks.

function thirdPartyFoo(callback) {    
  callback("Hello World");    
}

function foo() {    
  var fooVariable;

  thirdPartyFoo(function(data) {
    fooVariable = data;
  });

  return fooVariable;
}

var temp = foo();  
console.log(temp);

CodeIgniter Active Record - Get number of returned rows

function getCount(){
    return $this->db->get('table_name')->num_rows();
}

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: sdetail in mydt, Duplicate key: string: , Duplicate value:

I faced this error because i had written wrong database name in my php api part......

So this error may also occurs when you are fetching the data from database base, whose name is written incorrect by you.

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

Upload folder with subfolders using S3 and the AWS console

You can upload files by dragging and dropping or by pointing and clicking. To upload folders, you must drag and drop them. Drag and drop functionality is supported only for the Chrome and Firefox browsers

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Check your short_open_tag setting (use <?php phpinfo() ?> to see its current setting).

Remove all git files from a directory?

The .git folder is only stored in the root directory of the repo, not all the sub-directories like subversion. You should be able to just delete that one folder, unless you are using Submodules...then they will have one too.

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

Answer is YES

<html>
<head>
</head>
<body>
<script language="javascript">
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\NewFile.txt", true);
var text=document.getElementById("TextArea1").innerText;
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
</script>

<form name="abc">
<textarea name="text">FIFA</textarea>
<button onclick="WriteToFile()">Click to save</Button>  
</form> 

</body>
</html>

Best way to check if object exists in Entity Framework?

I know this is a very old thread but just incase someone like myself needs this solution but in VB.NET here's what I used base on the answers above.

Private Function ValidateUniquePayroll(PropertyToCheck As String) As Boolean
    // Return true if Username is Unique
    Dim rtnValue = False
    Dim context = New CPMModel.CPMEntities
    If (context.Employees.Any()) Then ' Check if there are "any" records in the Employee table
        Dim employee = From c In context.Employees Select c.PayrollNumber ' Select just the PayrollNumber column to work with
        For Each item As Object In employee ' Loop through each employee in the Employees entity
            If (item = PropertyToCheck) Then ' Check if PayrollNumber in current row matches PropertyToCheck
                // Found a match, throw exception and return False
                rtnValue = False
                Exit For
            Else
                // No matches, return True (Unique)
                rtnValue = True
            End If
        Next
    Else
        // The is currently no employees in the person entity so return True (Unqiue)
        rtnValue = True
    End If
    Return rtnValue
End Function

What is the purpose of a plus symbol before a variable?

It is a unary "+" operator which yields a numeric expression. It would be the same as d*1, I believe.

How can I enable cURL for an installed Ubuntu LAMP stack?

From Install Curl Extension for PHP in Ubuntu:

sudo apt-get install php5-curl

After installing libcurl, you should restart the web server with one of the following commands,

sudo /etc/init.d/apache2 restart

or

sudo service apache2 restart

Textarea to resize based on content length

Use this function:

function adjustHeight(el){
    el.style.height = (el.scrollHeight > el.clientHeight) ? (el.scrollHeight)+"px" : "60px";
}

Use this html:

<textarea onkeyup="adjustHeight(this)"></textarea>

And finally use this css:

textarea {
min-height: 60px;
overflow-y: auto;
word-wrap:break-word
}

The solution simply is letting the scrollbar appears to detect that height needs to be adjusted, and whenever the scrollbar appears in your text area, it adjusts the height just as much as to hide the scrollbar again.

React js change child component's state from parent component

You can use the createRef to change the state of the child component from the parent component. Here are all the steps.

  1. Create a method to change the state in the child component.

    2 - Create a reference for the child component in parent component using React.createRef().

    3 - Attach reference with the child component using ref={}.

    4 - Call the child component method using this.yor-reference.current.method.

Parent component


class ParentComponent extends Component {
constructor()
{
this.changeChild=React.createRef()
}
  render() {
    return (
      <div>
        <button onClick={this.changeChild.current.toggleMenu()}>
          Toggle Menu from Parent
        </button>
        <ChildComponent ref={this.changeChild} />
      </div>
    );
  }
}

Child Component


class ChildComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false;
    }
  }

  toggleMenu=() => {
    this.setState({
      open: !this.state.open
    });
  }

  render() {
    return (
      <Drawer open={this.state.open}/>
    );
  }
}



Numpy: Divide each row by a vector element

Pythonic way to do this is ...

np.divide(data.T,vector).T

This takes care of reshaping and also the results are in floating point format. In other answers results are in rounded integer format.

#NOTE: No of columns in both data and vector should match

How do I force git to use LF instead of CR+LF under windows?

core.autocrlf=input is the right setting for what you want, but you might have to do a git update-index --refresh and/or a git reset --hard for the change to take effect.

With core.autocrlf set to input, git will not apply newline-conversion on check-out (so if you have LF in the repo, you'll get LF), but it will make sure that in case you mess up and introduce some CRLFs in the working copy somehow, they won't make their way into the repo.

How to check if a number is between two values?

I just implemented this bit of jQuery to show and hide bootstrap modal values. Different fields are displayed based on the value range of a users textbox entry.

$(document).ready(function () {
    jQuery.noConflict();
    var Ammount = document.getElementById('Ammount');

    $("#addtocart").click(function () {

            if ($(Ammount).val() >= 250 && $(Ammount).val() <= 499) {
                {
                    $('#myModal').modal();
                    $("#myModalLabelbronze").show();
                    $("#myModalLabelsilver").hide();
                    $("#myModalLabelgold").hide();
                    $("#myModalPbronze").show();
                    $("#myModalPSilver").hide();
                    $("#myModalPGold").hide();
                }
            }
    });

Convert character to ASCII code in JavaScript

String.prototype.charCodeAt() can convert string characters to ASCII numbers. For example:

"ABC".charCodeAt(0) // returns 65

For opposite use String.fromCharCode(10) that convert numbers to equal ASCII character. This function can accept multiple numbers and join all the characters then return the string. Example:

String.fromCharCode(65,66,67); // returns 'ABC'

Here is a quick ASCII characters reference:

{
"31": "",      "32": " ",     "33": "!",     "34": "\"",    "35": "#",    
"36": "$",     "37": "%",     "38": "&",     "39": "'",     "40": "(",    
"41": ")",     "42": "*",     "43": "+",     "44": ",",     "45": "-",    
"46": ".",     "47": "/",     "48": "0",     "49": "1",     "50": "2",    
"51": "3",     "52": "4",     "53": "5",     "54": "6",     "55": "7",    
"56": "8",     "57": "9",     "58": ":",     "59": ";",     "60": "<",    
"61": "=",     "62": ">",     "63": "?",     "64": "@",     "65": "A",    
"66": "B",     "67": "C",     "68": "D",     "69": "E",     "70": "F",    
"71": "G",     "72": "H",     "73": "I",     "74": "J",     "75": "K",    
"76": "L",     "77": "M",     "78": "N",     "79": "O",     "80": "P",    
"81": "Q",     "82": "R",     "83": "S",     "84": "T",     "85": "U",    
"86": "V",     "87": "W",     "88": "X",     "89": "Y",     "90": "Z",    
"91": "[",     "92": "\\",    "93": "]",     "94": "^",     "95": "_",    
"96": "`",     "97": "a",     "98": "b",     "99": "c",     "100": "d",    
"101": "e",    "102": "f",    "103": "g",    "104": "h",    "105": "i",    
"106": "j",    "107": "k",    "108": "l",    "109": "m",    "110": "n",    
"111": "o",    "112": "p",    "113": "q",    "114": "r",    "115": "s",    
"116": "t",    "117": "u",    "118": "v",    "119": "w",    "120": "x",    
"121": "y",    "122": "z",    "123": "{",    "124": "|",    "125": "}",    
"126": "~",    "127": ""
}

How to define a List bean in Spring?

As an addition to Jakub's answer, if you plan to use JavaConfig, you can also autowire that way:

import com.google.common.collect.Lists;

import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

<...>

@Configuration
public class MyConfiguration {

    @Bean
    public List<Stage> stages(final Stage1 stage1, final Stage2 stage2) {
        return Lists.newArrayList(stage1, stage2);
    }
}

How to determine total number of open/active connections in ms sql server 2005

Use this to get an accurate count for each connection pool (assuming each user/host process uses the same connection string)

SELECT 
DB_NAME(dbid) as DBName, 
COUNT(dbid) as NumberOfConnections,
loginame as LoginName, hostname, hostprocess
FROM
sys.sysprocesses with (nolock)
WHERE 
dbid > 0
GROUP BY 
dbid, loginame, hostname, hostprocess

move column in pandas dataframe

You can also do this as a one-liner:

df.drop(columns=['b', 'x']).assign(b=df['b'], x=df['x'])

Need to remove href values when printing in Chrome

To hide Page url .

use media="print" in style tage example :

<style type="text/css" media="print">
            @page {
                size: auto;   /* auto is the initial value */
                margin: 0;  /* this affects the margin in the printer settings */
            }
            @page { size: portrait; }
</style>

If you want to remove links :

@media print {
   a[href]:after {
      visibility: hidden !important;
   }
}

Random number c++ in some range

int range = max - min + 1;
int num = rand() % range + min;

How do I change the root directory of an Apache server?

Please note, that this only applies for Ubuntu 14.04 LTS and newer releases.

In my Ubuntu 14.04 LTS, the document root was set to /var/www/html. It was configured in the following file:

/etc/apache2/sites-available/000-default.conf

So just do a

sudo nano /etc/apache2/sites-available/000-default.conf

and change the following line to what you want:

DocumentRoot /var/www/html

Also do a

sudo nano /etc/apache2/apache2.conf

and find this

<Directory /var/www/html/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>

and change /var/www/html to your preferred directory

and save it.

After you saved your changes, just restart the apache2 webserver and you'll be done :)

sudo service apache2 restart


If you prefer a graphical text editor, you can just replace the sudo nano by a gksu gedit.

Find all elements with a certain attribute value in jquery

$('div[imageId="imageN"]').each(function() {
    // `this` is the div
});

To check for the sole existence of the attribute, no matter which value, you could use ths selector instead: $('div[imageId]')

Clicking URLs opens default browser

Add this 2 lines in your code -

mWebView.setWebChromeClient(new WebChromeClient()); 
mWebView.setWebViewClient(new WebViewClient());?

Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10)

Disabling the Program Compatibility Assistant is not the right way.

A solution that works on Windows 10 is:

  • Right-click the setup file
  • Select Properties and navigate to the Details tab.
  • There should be an entry labeled Original filename. Simply rename the file accordingly and it should run.

.datepicker('setdate') issues, in jQuery

If you would like to support really old browsers you should parse the date string, since using the ISO8601 date format with the Date constructor is not supported pre IE9:

var queryDate = '2009-11-01',
    dateParts = queryDate.match(/(\d+)/g)
    realDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);  
                                    // months are 0-based!
// For >= IE9
var realDate = new Date('2009-11-01');  

$('#datePicker').datepicker({ dateFormat: 'yy-mm-dd' }); // format to show
$('#datePicker').datepicker('setDate', realDate);

Check the above example here.

How to achieve pagination/table layout with Angular.js?

I would use table and implement the pagination in the controller to control how much is shown and buttons to move to the next page. This Fiddle might help you.

example of the pagination

 <table class="table table-striped table-condensed table-hover">
                <thead>
                    <tr>
                        <th class="id">Id&nbsp;<a ng-click="sort_by('id')"><i class="icon-sort"></i></a></th>
                        <th class="name">Name&nbsp;<a ng-click="sort_by('name')"><i class="icon-sort"></i></a></th>
                        <th class="description">Description&nbsp;<a ng-click="sort_by('description')"><i class="icon-sort"></i></a></th>
                        <th class="field3">Field 3&nbsp;<a ng-click="sort_by('field3')"><i class="icon-sort"></i></a></th>
                        <th class="field4">Field 4&nbsp;<a ng-click="sort_by('field4')"><i class="icon-sort"></i></a></th>
                        <th class="field5">Field 5&nbsp;<a ng-click="sort_by('field5')"><i class="icon-sort"></i></a></th>
                    </tr>
                </thead>
                <tfoot>
                    <td colspan="6">
                        <div class="pagination pull-right">
                            <ul>
                                <li ng-class="{disabled: currentPage == 0}">
                                    <a href ng-click="prevPage()">« Prev</a>
                                </li>
                                <li ng-repeat="n in range(pagedItems.length)"
                                    ng-class="{active: n == currentPage}"
                                ng-click="setPage()">
                                    <a href ng-bind="n + 1">1</a>
                                </li>
                                <li ng-class="{disabled: currentPage == pagedItems.length - 1}">
                                    <a href ng-click="nextPage()">Next »</a>
                                </li>
                            </ul>
                        </div>
                    </td>
                </tfoot>
                <tbody>
                    <tr ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
                        <td>{{item.id}}</td>
                        <td>{{item.name}}</td>
                        <td>{{item.description}}</td>
                        <td>{{item.field3}}</td>
                        <td>{{item.field4}}</td>
                        <td>{{item.field5}}</td>
                    </tr>
                </tbody>
            </table> 

the $scope.range in the fiddle example should be:

$scope.range = function (size,start, end) {
    var ret = [];        
    console.log(size,start, end);

       if (size < end) {
        end = size;
        if(size<$scope.gap){
             start = 0;
        }else{
             start = size-$scope.gap;
        }

    }
    for (var i = start; i < end; i++) {
        ret.push(i);
    }        
     console.log(ret);        
    return ret;
};

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

With HTML5, you can do this natively with: <input name="first_name" placeholder="First Name">

This is not supported with all browsers though (IE)

This may work:

<input type="first_name" value="First Name" onfocus="this.value==this.defaultValue?this.value='':null">

Otherwise, if you are using jQuery, you can use .focus and .css to change the color.

How do I remove my IntelliJ license in 2019.3?

Not sure about older versions, but in 2016.2 removing the .key file(s) didn't work for me.

I'm using my JetBrains account and used the 'Remove License' button found at the bottom of the registration dialog. You can find this under the Help menu or from the startup dialog via Configure -> Manage License....

How to convert a datetime to string in T-SQL

There are many different ways to convert a datetime to a string. Here is one way:

SELECT convert(varchar(25), getdate(), 121)  – yyyy-mm-dd hh:mm:ss.mmm

See Demo

Here is a website that has a list of all of the conversions:

How to Format datetime & date in SQL Server

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

If given no. of Nodes are N Then.

Different No. of BST=Catalan(N)
Different No. of Structurally Different Binary trees are = Catalan(N)

Different No. of Binary Trees are=N!*Catalan(N)

Cannot load properties file from resources directory

Using ClassLoader.getSystemClassLoader()

Sample code :

Properties prop = new Properties();
InputStream input = null;
try {
    input = ClassLoader.getSystemClassLoader().getResourceAsStream("conf.properties");
    prop.load(input);

} catch (IOException io) {
    io.printStackTrace();
}

Twitter Bootstrap button click to toggle expand/collapse text section above button

I wanted an "expand/collapse" container with a plus and minus button to open and close it. This uses the standard bootstrap event and has animation. This is BS3.

enter image description here

HTML:

<button id="button" type="button" class="btn btn-primary" 
  data-toggle="collapse" data-target="#demo">
  <span class="glyphicon glyphicon-collapse-down"></span> Show
</button>

<div id="demo" class="collapse">
  <ol class="list-group">
      <li class="list-group-item">Warrior</li>
      <li class="list-group-item">Adventurer</li>
      <li class="list-group-item">Mage</li>
  </ol>
</div>

JS:

$(function(){
  $('#demo').on('hide.bs.collapse', function () {
    $('#button').html('<span class="glyphicon glyphicon-collapse-down"></span> Show');
  })
  $('#demo').on('show.bs.collapse', function () {
    $('#button').html('<span class="glyphicon glyphicon-collapse-up"></span> Hide');
  })
})

Example:

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

Allow 2 decimal places in <input type="number">

Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places.

More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute

Can I nest a <button> element inside an <a> using HTML5?

No.

The following solution relies on JavaScript.

<button type="button" onclick="location.href='http://www.stackoverflow.com'">ABC</button>

If the button is to be placed inside an existing <form> with method="post", then ensure the button has the attribute type="button" otherwise the button will submit the POST operation. In this way you can have a <form> that contains a mixture of GET and POST operation buttons.

async at console app in C#?

As a quick and very scoped solution:

Task.Result

Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.

When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.

notasync

Is the buildSessionFactory() Configuration method deprecated in Hibernate

Yes it is deprecated. Replace your SessionFactory with the following:

In Hibernate 4.0, 4.1, 4.2

private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static SessionFactory createSessionFactory() {
    Configuration configuration = new Configuration();
    configuration.configure();
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
            configuration.getProperties()). buildServiceRegistry();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    return sessionFactory;
}

UPDATE:

In Hibernate 4.3 ServiceRegistryBuilder is deprecated. Use the following instead.

serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
            configuration.getProperties()).build();

Android Webview - Completely Clear the Cache

The edited code snippet above posted by Gaunt Face contains an error in that if a directory fails to delete because one of its files cannot be deleted, the code will keep retrying in an infinite loop. I rewrote it to be truly recursive, and added a numDays parameter so you can control how old the files must be that are pruned:

//helper method for clearCache() , recursive
//returns number of deleted files
static int clearCacheFolder(final File dir, final int numDays) {

    int deletedFiles = 0;
    if (dir!= null && dir.isDirectory()) {
        try {
            for (File child:dir.listFiles()) {

                //first delete subdirectories recursively
                if (child.isDirectory()) {
                    deletedFiles += clearCacheFolder(child, numDays);
                }

                //then delete the files and subdirectories in this dir
                //only empty directories can be deleted, so subdirs have been done first
                if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
                    if (child.delete()) {
                        deletedFiles++;
                    }
                }
            }
        }
        catch(Exception e) {
            Log.e(TAG, String.format("Failed to clean the cache, error %s", e.getMessage()));
        }
    }
    return deletedFiles;
}

/*
 * Delete the files older than numDays days from the application cache
 * 0 means all files.
 */
public static void clearCache(final Context context, final int numDays) {
    Log.i(TAG, String.format("Starting cache prune, deleting files older than %d days", numDays));
    int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
    Log.i(TAG, String.format("Cache pruning completed, %d files deleted", numDeletedFiles));
}

Hopefully of use to other people :)

Access event to call preventdefault from custom function originating from onclick attribute of tag

I believe you can pass in event into the function inline which will be the event object for the raised event in W3C compliant browsers (i.e. older versions of IE will still require detection inside of your event handler function to look at window.event).

A quick example.

_x000D_
_x000D_
function sayHi(e) {_x000D_
   e.preventDefault();_x000D_
   alert("hi");_x000D_
}
_x000D_
<a href="http://google.co.uk" onclick="sayHi(event);">Click to say Hi</a>
_x000D_
_x000D_
_x000D_

  1. Run it as is and notice that the link does no redirect to Google after the alert.
  2. Then, change the event passed into the onclick handler to something else like e, click run, then notice that the redirection does take place after the alert (the result pane goes white, demonstrating a redirect).

Importing json file in TypeScript

In your TS Definition file, e.g. typings.d.ts`, you can add this line:

declare module "*.json" {
const value: any;
export default value;
}

Then add this in your typescript(.ts) file:-

import * as data from './colors.json';
const word = (<any>data).name;

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

However, it is important to note that the mysql connector driver version must be older than 5.1.47 and later.

Executing <script> elements inserted with .innerHTML

Here's a shorter, more efficient script that also works for scripts with the src property:

function insertAndExecute(id, text) {
    document.getElementById(id).innerHTML = text;
    var scripts = Array.prototype.slice.call(document.getElementById(id).getElementsByTagName("script"));
    for (var i = 0; i < scripts.length; i++) {
        if (scripts[i].src != "") {
            var tag = document.createElement("script");
            tag.src = scripts[i].src;
            document.getElementsByTagName("head")[0].appendChild(tag);
        }
        else {
            eval(scripts[i].innerHTML);
        }
    }
}

Note: whilst eval may cause a security vulnerability if not used properly, it is much faster than creating a script tag on the fly.

ElasticSearch: Unassigned Shards, how to fix?

I was having this issue as well, and I found an easy way to resolve it.

  • Get the index of unassigned shards

    $ curl -XGET http://172.16.4.140:9200/_cat/shards
    
  • Install curator Tools, and use it to delete index

    $ curator --host 172.16.4.140 delete indices --older-than 1 \
           --timestring '%Y.%m.%d' --time-unit days --prefix logstash
    

    NOTE: In my case, the index is logstash of the day 2016-04-21

  • Then check the shards again, all the unassigned shards go away!

Iterate a list with indexes in Python

>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
...     print i, val
...
0 3
1 4
2 5
3 6
>>>

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

unable to set private key file: './cert.pem' type PEM

After reading cURL documentation on the options you used, it looks like the private key of certificate is not in the same file. If it is in different file, you need to mention it using --key file and supply passphrase.

So, please make sure that either cert.pem has private key (along with the certificate) or supply it using --key option.

Also, this documentation mentions that Note that this option assumes a "certificate" file that is the private key and the private certificate concatenated!

How they are concatenated? It is quite easy. Put them one after another in the same file.

You can get more help on this here.

I believe this might help you.

Checking for empty or null List<string>

if (myList?.Any() == true) 
{
   ...
}

I find this the most convenient way. '== true' checks the value of the nullable bool implied by '?.Any()

select records from postgres where timestamp is in certain range

Search till the seconds for the timestamp column in postgress

select * from "TableName" e
    where timestamp >= '2020-08-08T13:00:00' and timestamp < '2020-08-08T17:00:00';

How to convert LINQ query result to List?

You need to somehow convert each tbcourse object to an instance of course. For instance course could have a constructor that takes a tbcourse. You could then write the query like this:

var qry = from c in obj.tbCourses
          select new course(c);

List<course> lst = qry.ToList();

No mapping found for HTTP request with URI.... in DispatcherServlet with name

if you are using maven then do run maven install command before you run your web app on a server as it will generate a class file for your controller and in my experience that is what your application has been missing.

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ? do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

How to format a Java string with leading zero?

 StringUtils.leftPad(yourString, 8, '0');

This is from commons-lang. See javadoc

Java 8 Iterable.forEach() vs foreach loop

The advantage of Java 1.8 forEach method over 1.7 Enhanced for loop is that while writing code you can focus on business logic only.

forEach method takes java.util.function.Consumer object as an argument, so It helps in having our business logic at a separate location that you can reuse it anytime.

Have look at below snippet,

  • Here I have created new Class that will override accept class method from Consumer Class, where you can add additional functionility, More than Iteration..!!!!!!

    class MyConsumer implements Consumer<Integer>{
    
        @Override
        public void accept(Integer o) {
            System.out.println("Here you can also add your business logic that will work with Iteration and you can reuse it."+o);
        }
    }
    
    public class ForEachConsumer {
    
        public static void main(String[] args) {
    
            // Creating simple ArrayList.
            ArrayList<Integer> aList = new ArrayList<>();
            for(int i=1;i<=10;i++) aList.add(i);
    
            //Calling forEach with customized Iterator.
            MyConsumer consumer = new MyConsumer();
            aList.forEach(consumer);
    
    
            // Using Lambda Expression for Consumer. (Functional Interface) 
            Consumer<Integer> lambda = (Integer o) ->{
                System.out.println("Using Lambda Expression to iterate and do something else(BI).. "+o);
            };
            aList.forEach(lambda);
    
            // Using Anonymous Inner Class.
            aList.forEach(new Consumer<Integer>(){
                @Override
                public void accept(Integer o) {
                    System.out.println("Calling with Anonymous Inner Class "+o);
                }
            });
        }
    }
    

How to set the DefaultRoute to another Route in React Router

I was incorrectly trying to create a default path with:

<IndexRoute component={DefaultComponent} />
<Route path="/default-path" component={DefaultComponent} />

But this creates two different paths that render the same component. Not only is this pointless, but it can cause glitches in your UI, i.e., when you are styling <Link/> elements based on this.history.isActive().

The right way to create a default route (that is not the index route) is to use <IndexRedirect/>:

<IndexRedirect to="/default-path" />
<Route path="/default-path" component={DefaultComponent} />

This is based on react-router 1.0.0. See https://github.com/rackt/react-router/blob/master/modules/IndexRedirect.js.

What are valid values for the id attribute in HTML?

You can technically use colons and periods in id/name attributes, but I would strongly suggest avoiding both.

In CSS (and several JavaScript libraries like jQuery), both the period and the colon have special meaning and you will run into problems if you're not careful. Periods are class selectors and colons are pseudo-selectors (eg., ":hover" for an element when the mouse is over it).

If you give an element the id "my.cool:thing", your CSS selector will look like this:

#my.cool:thing { ... /* some rules */ ... }

Which is really saying, "the element with an id of 'my', a class of 'cool' and the 'thing' pseudo-selector" in CSS-speak.

Stick to A-Z of any case, numbers, underscores and hyphens. And as said above, make sure your ids are unique.

That should be your first concern.

How to set the margin or padding as percentage of height of parent container?

A 50% padding wont center your child, it will place it below the center. I think you really want a padding-top of 25%. Maybe you're just running out of space as your content gets taller? Also have you tried setting the margin-top instead of padding-top?

EDIT: Nevermind, the w3schools site says

% Specifies the padding in percent of the width of the containing element

So maybe it always uses width? I'd never noticed.

What you are doing can be acheived using display:table though (at least for modern browsers). The technique is explained here.

Open a selected file (image, pdf, ...) programmatically from my Android Application?

Try the following code.

File file = new File(path); // path = your file path
lastSlash = file.toString().lastIndexOf('/');

if (lastSlash >= 0)
{
    fileName = url.toString().substring(lastSlash + 1);
}


if (fileName.endsWith("pdf"))
{
    mimeType = "application/pdf";
}
else
{
    mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension
    (MimeTypeMap.getFileExtensionFromUrl(path));
}

Uri uri_path = Uri.fromFile(file);

Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.putExtra(PATH, path);
intent.putExtra(MIMETYPE, mimeType);
intent.setType(mimeType);
intent.setDataAndType(uri_path, mimeType);

startActivity(intent);

Way to go from recursion to iteration

One pattern to look for is a recursion call at the end of the function (so called tail-recursion). This can easily be replaced with a while. For example, the function foo:

void foo(Node* node)
{
    if(node == NULL)
       return;
    // Do something with node...
    foo(node->left);
    foo(node->right);
}

ends with a call to foo. This can be replaced with:

void foo(Node* node)
{
    while(node != NULL)
    {
        // Do something with node...
        foo(node->left);
        node = node->right;
     }
}

which eliminates the second recursive call.

Which is a better way to check if an array has more than one element?

isset() only checks if a variable is set.. Has got nothing to do with size or what the array contains

Could not find method android() for arguments

This error appear because the compiler could not found "my-upload-key.keystore" file in your project

After you have generated the file you need to paste it into project's andorid/app folder

this worked for me!

Streaming Audio from A URL in Android using MediaPlayer?

Use

 mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
 mediaplayer.prepareAsync();
 mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
      @Override
      public void onPrepared(MediaPlayer mp) {
          mediaplayer.start();
      }
 });

What is the origin of foo and bar?

tl;dr

  • "Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.

  • Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).

  • Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.

  • Also, it seems likely the military FUBAR contributed to their popularity.


The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)


OK, so let's find some references.

STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:

On Foo-ism

The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")

As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.

It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!

The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:

By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.

...

It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.

Hopefully yours,

Indignant Mother of Five.

And The Tech in December 1938:

General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."


The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:

FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.

These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:

Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.

And from 1996's Jargon File 4.0.0:

Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."

A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):

Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!

Also 1964's MIT Voo Doo (PDF) references the TMRC usage:

Yes! I want to be an instant success and snow customers. Send me a degree in: ...

  • Foo Counters

  • Foo Jung


Let's find "foo", "bar" and "foobar" published in code examples.

So, Jargon File 4.4.7 says of "foobar":

Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.

The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:

Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.

Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z

I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:

car[((FOO . CROCK) . GLITCH)]

It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER

For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:

EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).


Some more recallations.

@Walter Mitty recalled on this site in 2008:

I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.

John V. Everett recalls in 1996:

When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.

Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.

It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.

Daniel P. B. Smith in 1998:

Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.

Robert Schuldenfrei in 1996:

The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?

Paul M. Wexelblat in 1992:

The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.

Bruce B. Reynolds in 1996:

On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...

Here's a straight IBM "BAR" from 1955.


Other early references:


I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.

Here are a some of even earlier F00s but I think they're coincidences/false positives:

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

  1. Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR

  2. set these variables:

    export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
    export PATH=$JAVA_HOME/bin:$PATH
    
  3. Run your app and fun :)

(Minor update: put variable value in quote)

What is the purpose of the HTML "no-js" class?

This is not only applicable in Modernizer. I see some site implement like below to check whether it has javascript support or not.

<body class="no-js">
    <script>document.body.classList.remove('no-js');</script>
    ...
</body>

If javascript support is there, then it will remove no-js class. Otherwise no-js will remain in the body tag. Then they control the styles in the css when no javascript support.

.no-js .some-class-name {

}

Plotting dates on the x-axis with Python's matplotlib

You can do this more simply using plot() instead of plot_date().

First, convert your strings to instances of Python datetime.date:

import datetime as dt

dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here

Then plot:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()

Result:

enter image description here

How to set Status Bar Style in Swift 3

First step you need add a row with key: View controller-based status bar appearance and value NO to Info.plist file. After that, add 2 functions in your controller to specific only that controller will effect:

override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(animated)
       UIApplication.shared.statusBarStyle = .lightContent
}

override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        UIApplication.shared.statusBarStyle = .default    
}

How in node to split string by newline ('\n')?

a = a.split("\n");

Note that splitting returns the new array, rather than just assigning it to the original string. You need to explicitly store it in a variable.

Should I use window.navigate or document.location in JavaScript?

You can move your page using

window.location.href =Url;

Find all paths between two graph nodes

You usually don't want to, because there is an exponential number of them in nontrivial graphs; if you really want to get all (simple) paths, or all (simple) cycles, you just find one (by walking the graph), then backtrack to another.

Best Timer for using in a Windows service

Either one should work OK. In fact, System.Threading.Timer uses System.Timers.Timer internally.

Having said that, it's easy to misuse System.Timers.Timer. If you don't store the Timer object in a variable somewhere, then it is liable to be garbage collected. If that happens, your timer will no longer fire. Call the Dispose method to stop the timer, or use the System.Threading.Timer class, which is a slightly nicer wrapper.

What problems have you seen so far?

What does the variable $this mean in PHP?

I know its old question, anyway another exact explanation about $this. $this is mainly used to refer properties of a class.

Example:

Class A
{
   public $myname;    //this is a member variable of this class

function callme() {
    $myname = 'function variable';
    $this->myname = 'Member variable';
    echo $myname;                  //prints function variable
    echo $this->myname;              //prints member variable
   }
}

output:

function variable

member variable

Java 8: merge lists with stream API

I think flatMap() is what you're looking for.

For example:

 List<AClass> allTheObjects = map.values()
         .stream()
         .flatMap(listContainer -> listContainer.lst.stream())
         .collect(Collectors.toList());

How to get the Full file path from URI

String uri_path = "file:///mnt/sdcard/FileName.mp3";
File f = new removeUriFromPath(uri_path));
public static String removeUriFromPath(String uri)
{
  return  uri.substring(7, uri.length());
}

Moment.js transform to date object

moment has updated the js lib as of 06/2018.

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london     = newYork.clone().tz("Europe/London");

newYork.format();    // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format();     // 2014-06-01T17:00:00+01:00

if you have freedom to use Angular5+, then better use datePipe feature there than the timezone function here. I have to use moment.js because my project limits to Angular2 only.

Struct memory layout in C

It's implementation-specific, but in practice the rule (in the absence of #pragma pack or the like) is:

  • Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.)
  • If necessary, padding is added before each struct member, to ensure correct alignment.
  • Each primitive type T requires an alignment of sizeof(T) bytes.

So, given the following struct:

struct ST
{
   char ch1;
   short s;
   char ch2;
   long long ll;
   int i;
};
  • ch1 is at offset 0
  • a padding byte is inserted to align...
  • s at offset 2
  • ch2 is at offset 4, immediately after s
  • 3 padding bytes are inserted to align...
  • ll at offset 8
  • i is at offset 16, right after ll
  • 4 padding bytes are added at the end so that the overall struct is a multiple of 8 bytes. I checked this on a 64-bit system: 32-bit systems may allow structs to have 4-byte alignment.

So sizeof(ST) is 24.

It can be reduced to 16 bytes by rearranging the members to avoid padding:

struct ST
{
   long long ll; // @ 0
   int i;        // @ 8
   short s;      // @ 12
   char ch1;     // @ 14
   char ch2;     // @ 15
} ST;

How to convert a char array to a string?

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

using namespace std;

int main ()
{
  char *tmp = (char *)malloc(128);
  int n=sprintf(tmp, "Hello from Chile.");

  string tmp_str = tmp;


  cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
  cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;

 free(tmp); 
 return 0;
}

OUT:

H : is a char array beginning with 17 chars long

Hello from Chile. :is a string with 17 chars long

When using a Settings.settings file in .NET, where is the config actually stored?

Here is the snippet you can use to programmatically get user.config file location:

public static string GetDefaultExeConfigPath(ConfigurationUserLevel userLevel)
{
  try
  {
    var UserConfig = ConfigurationManager.OpenExeConfiguration(userLevel);
    return UserConfig.FilePath;
  }
  catch (ConfigurationException e)
  {
    return e.Filename;
  }
}

ApplicationSettings (i.e. settings.settings) use PerUserRoamingAndLocal for user settings by default (as I remembered).

Update: Strange but there are too many incorrect answers here. If you are looking for you user scoped settings file (user.config) it will be located in the following folder (for Windows XP):

C:\Documents and Settings\(username)\Local Settings\Application Data\(company-name-if-exists)\(app-name).exe_(Url|StrongName)_(hash)\(app-version)\

Url or StrongName depends on have you application assembly strong name or not.

How to make execution pause, sleep, wait for X seconds in R?

See help(Sys.sleep).

For example, from ?Sys.sleep

testit <- function(x)
{
    p1 <- proc.time()
    Sys.sleep(x)
    proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)

Yielding

> testit(3.7)
   user  system elapsed 
  0.000   0.000   3.704 

ng-mouseover and leave to toggle item using mouse in angularjs

A little late here, but I've found this to be a common problem worth a custom directive to handle. Here's how that might look:

  .directive('toggleOnHover', function(){
    return {
      restrict: 'A',
      link: link
    };

    function link(scope, elem, attrs){
      elem.on('mouseenter', applyToggleExp);
      elem.on('mouseleave', applyToggleExp);

      function applyToggleExp(){
        scope.$apply(attrs.toggleOnHover);
      }
    }

  });

You can use it like this:

<li toggle-on-hover="editableProp = !editableProp">edit</li> 

VSCode Change Default Terminal

I just type following keywords in the opened terminal;

  1. powershell
  2. bash
  3. cmd
  4. node
  5. python (or python3)

See details in the below image. (VSCode version 1.19.1 - windows 10 OS) enter image description here

It works on VS Code Mac as well. I tried it with VSCode (Version 1.20.1)

How to keep Docker container running after starting services?

Make sure that you add daemon off; to you nginx.conf or run it with CMD ["nginx", "-g", "daemon off;"] as per the official nginx image

Then use the following to run both supervisor as service and nginx as foreground process that will prevent the container from exiting

service supervisor start && nginx

In some cases you will need to have more than one process in your container, so forcing the container to have exactly one process won't work and can create more problems in deployment.

So you need to understand the trade-offs and make your decision accordingly.

Git refusing to merge unrelated histories on rebase

When doing a git pull, I got this message fatal: refusing to merge unrelated histories for a repo module where I hadn't updated the local copy for a while.

I ran this command just to refresh local from origin. I just wanted latest from remote and didn't need any local changes.

git reset --hard origin/master

This fixed it in my case.

How to fetch all Git branches

You can fetch all the branches by:

git fetch --all

or:

git fetch origin --depth=10000 $(git ls-remote -h -t origin)

The --depth=10000 parameter may help if you've shallowed repository.


To pull all the branches, use:

git pull --all

If above won't work, then precede the above command with:

git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'

as the remote.origin.fetch could support only a specific branch while fetching, especially when you cloned your repo with --single-branch. Check this by: git config remote.origin.fetch.

After that you should be able to checkout any branch.

See also:


To push all the branches to the remote, use:

git push --all

eventually --mirror to mirror all refs.


If your goal is to duplicate a repository, see: Duplicating a repository article at GitHub.

How to Add Incremental Numbers to a New Column Using Pandas

df.insert(0, 'New_ID', range(880, 880 + len(df)))
df

enter image description here

Implementing a Custom Error page on an ASP.Net website

<customErrors defaultRedirect="~/404.aspx" mode="On">
    <error statusCode="404" redirect="~/404.aspx"/>
</customErrors>

Code above is only for "Page Not Found Error-404" if file extension is known(.html,.aspx etc)

Beside it you also have set Customer Errors for extension not known or not correct as

.aspwx or .vivaldo. You have to add httperrors settings in web.config

<httpErrors  errorMode="Custom"> 
       <error statusCode="404" prefixLanguageFilePath="" path="/404.aspx"         responseMode="Redirect" />
</httpErrors>
<modules runAllManagedModulesForAllRequests="true"/>

it must be inside the <system.webServer> </system.webServer>

How can I show three columns per row?

This may be what you are looking for:

http://jsfiddle.net/L4L67/

_x000D_
_x000D_
body>div {_x000D_
  background: #aaa;_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
body>div>div {_x000D_
  flex-grow: 1;_x000D_
  width: 33%;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(even) {_x000D_
  background: #23a;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(odd) {_x000D_
  background: #49b;_x000D_
}
_x000D_
<div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Check if a row exists, otherwise insert

I assume a single row for each flight? If so:

IF EXISTS (SELECT * FROM Bookings WHERE FLightID = @Id)
BEGIN
    --UPDATE HERE
END
ELSE
BEGIN
   -- INSERT HERE
END

I assume what I said, as your way of doing things can overbook a flight, as it will insert a new row when there are 10 tickets max and you are booking 20.

Disable cross domain web security in Firefox

Best Firefox Addon to disable CORS as of September 2016: https://github.com/fredericlb/Force-CORS/releases

You can even configure it by Referrers (Website).

Basic HTTP and Bearer Token Authentication

Try this one to push basic authentication at url:

curl -i http://username:[email protected]/api/users -H "Authorization: Bearer mytoken123"
               ^^^^^^^^^^^^^^^^^^

If above one doesn't work, then you have nothing to do with it. So try the following alternates.

You can pass the token under another name. Because you are handling the authorization from your Application. So you can easily use this flexibility for this special purpose.

curl -i http://dev.myapp.com/api/users \
  -H "Authorization: Basic Ym9zY236Ym9zY28=" \
  -H "Application-Authorization: mytoken123"

Notice I have changed the header into Application-Authorization. So from your application catch the token under that header and process what you need to do.

Another thing you can do is, to pass the token through the POST parameters and grab the parameter's value from the Server side. For example passing token with curl post parameter:

-d "auth-token=mytoken123"

Beginner Python: AttributeError: 'list' object has no attribute

You need to pass the values of the dict into the Bike constructor before using like that. Or, see the namedtuple -- seems more in line with what you're trying to do.

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

For Swift 3 and XCode 8, this worked. Follow below steps to achieve this:-

{
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    let width = UIScreen.main.bounds.width
    layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    layout.itemSize = CGSize(width: width / 2, height: width / 2)
    layout.minimumInteritemSpacing = 0
    layout.minimumLineSpacing = 0
    collectionView!.collectionViewLayout = layout
}

Place this code into viewDidLoad() function.

Non greedy (reluctant) regex matching in sed?

sed certainly has its place but this not not one of them !

As Dee has pointed out: Just use cut. It is far simpler and much more safe in this case. Here's an example where we extract various components from the URL using Bash syntax:

url="http://www.suepearson.co.uk/product/174/71/3816/"

protocol=$(echo "$url" | cut -d':' -f1)
host=$(echo "$url" | cut -d'/' -f3)
urlhost=$(echo "$url" | cut -d'/' -f1-3)
urlpath=$(echo "$url" | cut -d'/' -f4-)

gives you:

protocol = "http"
host = "www.suepearson.co.uk"
urlhost = "http://www.suepearson.co.uk"
urlpath = "product/174/71/3816/"

As you can see this is a lot more flexible approach.

(all credit to Dee)

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

How to check if an app is installed from a web-page on an iPhone?

To further the accepted answer, you sometimes need to add extra code to handle people returning the browser after launching the app- that setTimeout function will run whenever they do. So, I do something like this:

var now = new Date().valueOf();
setTimeout(function () {
    if (new Date().valueOf() - now > 100) return;
    window.location = "https://itunes.apple.com/appdir";
}, 25);
window.location = "appname://";

That way, if there has been a freeze in code execution (i.e., app switching), it won't run.

How can I calculate divide and modulo for integers in C#?

Read two integers from the user. Then compute/display the remainder and quotient,

// When the larger integer is divided by the smaller integer
Console.WriteLine("Enter integer 1 please :");
double a5 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter integer 2 please :");
double b5 = double.Parse(Console.ReadLine());

double div = a5 / b5;
Console.WriteLine(div);

double mod = a5 % b5;
Console.WriteLine(mod);

Console.ReadLine();

How to verify if nginx is running or not?

For Mac users

I found out one more way: You can check if /usr/local/var/run/nginx.pid exists. If it is - nginx is running. Useful way for scripting.

Example:

if [ -f /usr/local/var/run/nginx.pid ]; then
   echo "Nginx is running"

fi

Can an Android Toast be longer than Toast.LENGTH_LONG?

Why eat Toast, when you can have the entire Snackbar: https://developer.android.com/reference/android/support/design/widget/Snackbar.html

Snackbar > Toast, Custom Toast, Crouton

Moving items around in an ArrayList

A simple swap is far better for "moving something up" in an ArrayList:

if(i > 0) {
    Item toMove = arrayList.get(i);
    arrayList.set(i, arrayList.get(i-1));
    arrayList.set(i-1, toMove);
}

Because an ArrayList uses an array, if you remove an item from an ArrayList, it has to "shift" all the elements after that item upward to fill in the gap in the array. If you insert an item, it has to shift all the elements after that item to make room to insert it. These shifts can get very expensive if your array is very big. Since you know that you want to end up with the same number of elements in the list, doing a swap like this allows you to "move" an element to another location in the list very efficiently.

As Chris Buckler and Michal Kreuzman point out, there is even a handy method in the Collections class to reduce these three lines of code to one:

Collections.swap(arrayList, i, i-1);

Extract csv file specific columns to list in Python

This looks like a problem with line endings in your code. If you're going to be using all these other scientific packages, you may as well use Pandas for the CSV reading part, which is both more robust and more useful than just the csv module:

import pandas
colnames = ['year', 'name', 'city', 'latitude', 'longitude']
data = pandas.read_csv('test.csv', names=colnames)

If you want your lists as in the question, you can now do:

names = data.name.tolist()
latitude = data.latitude.tolist()
longitude = data.longitude.tolist()

openssl s_client using a proxy

Even with openssl v1.1.0 I had some problems passing our proxy, e.g. s_client: HTTP CONNECT failed: 400 Bad Request That forced me to write a minimal Java-class to show the SSL-Handshake

    public static void main(String[] args) throws IOException, URISyntaxException {
    HttpHost proxy = new HttpHost("proxy.my.company", 8080);
    DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
    CloseableHttpClient httpclient = HttpClients.custom()
            .setRoutePlanner(routePlanner)
            .build();
    URI uri = new URIBuilder()
            .setScheme("https")
            .setHost("www.myhost.com")
            .build();
    HttpGet httpget = new HttpGet(uri);
    httpclient.execute(httpget);
}

With following dependency:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
        <type>jar</type>
    </dependency>

you can run it with Java SSL Logging turned on

This should produce nice output like

trustStore provider is :
init truststore
adding as trusted cert:
  Subject: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
  Issuer:  CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
  Algorithm: RSA; Serial number: 0xc3517
  Valid from Mon Jun 21 06:00:00 CEST 1999 until Mon Jun 22 06:00:00 CEST 2020

adding as trusted cert:
  Subject: CN=SecureTrust CA, O=SecureTrust Corporation, C=US
  Issuer:  CN=SecureTrust CA, O=SecureTrust Corporation, C=US
(....)

Rotate an image in image source in html

This CSS seems to work in Safari and Chrome:

div#div2
{
-webkit-transform:rotate(90deg); /* Chrome, Safari, Opera */
transform:rotate(90deg); /* Standard syntax */
}

and in the body:

<div id="div2"><img src="image.jpg"  ></div>

But this (and the .rotate90 example above) pushes the rotated image higher up on the page than if it were un-rotated. Not sure how to control placement of the image relative to text or other rotated images.

How do I start an activity from within a Fragment?

The difference between starting an Activity from a Fragment and an Activity is how you get the context, because in both cases it has to be an activity.

From an activity: The context is the current activity (this)

Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);

From a fragment: The context is the parent activity (getActivity()). Notice, that the fragment itself can start the activity via startActivity(), this is not necessary to be done from the activity.

Intent intent = new Intent(getActivity(), NewActivity.class);
startActivity(intent);

Credentials for the SQL Server Agent service are invalid

In my case password was expired. Change the password and try the step again.

How to execute a command in a remote computer?

IMO, in your case you can try this:

  1. Map the shared folder to a drive or folder on your machine. (here's how)
  2. Access the mapped drive/folder as you normally would local files.

Nothing needs to be installed. No services need to be running except those that enable folder sharing.

If you can access the shared folder and maps it on your machine, most things should work just like local files, including command prompts and all explorer-enhancement tools.

This is different from using PsExec (or RDP-ing in) in that you do not need to have administrative rights and/or remote desktop/terminal services connection rights on the remote server, you just need to be able to access those shared folders.

Also make sure you have all the necessary security permissions to run whatever commands/tools you want to run on those shared folders as well.


If, however you wish the processing to be done on the target machine, then you can try PsExec as @divo and @recursive pointed out, something alongs:

PsExec \\yourServerName -u yourUserName cmd.exe

Which will brings gives you a command prompt at the remote machine. And from there you can execute whatever you want.

I am not sure but I think you need either the Server (lanmanserver) or the Terminal Services (TermService) service to be running (which should have already be running).