Programs & Examples On #Msg

msg is the extension of Microsoft Outlook message files

message box in jquery

Do you mean just? alert()

function hello_world(){ alert("hello world"); }

How to avoid "RuntimeError: dictionary changed size during iteration" error?

The reason for the runtime error is that you cannot iterate through a data structure while its structure is changing during iteration.

One way to achieve what you are looking for is to use list to append the keys you want to remove and then use pop function on dictionary to remove the identified key while iterating through the list.

d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
pop_list = []

for i in d:
        if not d[i]:
                pop_list.append(i)

for x in pop_list:
        d.pop(x)
print (d)

Only numbers. Input number in React

You can try this solution, since onkeypress will be attached directly to the DOM element and will prevent users from entering invalid data to begin with.

So no side-effects on react side.

<input type="text" onKeyPress={onNumberOnlyChange}/>

const onNumberOnlyChange = (event: any) => {
    const keyCode = event.keyCode || event.which;
    const keyValue = String.fromCharCode(keyCode);
    const isValid = new RegExp("[0-9]").test(keyValue);
    if (!isValid) {
       event.preventDefault();
       return;
    }
};

CSS Background Opacity

The following methods can be used to solve your problem:

  1. CSS alpha transparency method (doesn't work in Internet Explorer 8):

    #div{background-color:rgba(255,0,0,0.5);}
    
  2. Use a transparent PNG image according to your choice as background.

  3. Use the following CSS code snippet to create a cross-browser alpha-transparent background. Here is an example with #000000 @ 0.4% opacity

    .div {
        background:rgb(0,0,0);
        background: transparent\9;
        background:rgba(0,0,0,0.4);
        filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#66000000,endColorstr=#66000000);
        zoom: 1;
    }
    .div:nth-child(n) {
        filter: none;
    }
    

For more details regarding this technique, see this, which has an online CSS generator.

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

As of iOS 11 this is publicly available in UITableViewDelegate. Here's some sample code:

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    UIContextualAction *delete = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive
                                                                         title:@"DELETE"
                                                                       handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
                                                                           NSLog(@"index path of delete: %@", indexPath);
                                                                           completionHandler(YES);
                                                                       }];

    UIContextualAction *rename = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal
                                                                         title:@"RENAME"
                                                                       handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
                                                                           NSLog(@"index path of rename: %@", indexPath);
                                                                           completionHandler(YES);
                                                                       }];

    UISwipeActionsConfiguration *swipeActionConfig = [UISwipeActionsConfiguration configurationWithActions:@[rename, delete]];
    swipeActionConfig.performsFirstActionWithFullSwipe = NO;

    return swipeActionConfig;
}

Also available:

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView leadingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath;

Docs: https://developer.apple.com/documentation/uikit/uitableviewdelegate/2902367-tableview?language=objc

How to submit http form using C#

I had a similar issue in MVC (which lead me to this problem).

I am receiving a FORM as a string response from a WebClient.UploadValues() request, which I then have to submit - so I can't use a second WebClient or HttpWebRequest. This request returned the string.

using (WebClient client = new WebClient())
  {
    byte[] response = client.UploadValues(urlToCall, "POST", new NameValueCollection()
    {
        { "test", "value123" }
    });

    result = System.Text.Encoding.UTF8.GetString(response);
  }

My solution, which could be used to solve the OP, is to append a Javascript auto submit to the end of the code, and then using @Html.Raw() to render it on a Razor page.

result += "<script>self.document.forms[0].submit()</script>";
someModel.rawHTML = result;
return View(someModel);

Razor Code:

@model SomeModel

@{
    Layout = null;
}

@Html.Raw(@Model.rawHTML)

I hope this can help anyone who finds themselves in the same situation.

Get size of all tables in database

-- Show the size of all the tables in a database sort by data size descending
SET NOCOUNT ON
DECLARE @TableInfo TABLE (tablename varchar(255), rowcounts int, reserved varchar(255), DATA varchar(255), index_size varchar(255), unused varchar(255))
DECLARE @cmd1 varchar(500)
SET @cmd1 = 'exec sp_spaceused ''?'''

INSERT INTO @TableInfo (tablename,rowcounts,reserved,DATA,index_size,unused)
EXEC sp_msforeachtable @command1=@cmd1

SELECT * FROM @TableInfo ORDER BY Convert(int,Replace(DATA,' KB','')) DESC

How to iterate through LinkedHashMap with lists as values

for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
    String key = entry.getKey();
    ArrayList<String> value = entry.getValue();
    // now work with key and value...
}

By the way, you should really declare your variables as the interface type instead, such as Map<String, List<String>>.

ShowAllData method of Worksheet class failed

I have just experienced the same problem. After some trial-and-error I discovered that if the selection was to the right of my filter area AND the number of shown records was zero, ShowAllData would fail.

A little more context is probably relevant. I have a number of sheets, each with a filter. I would like to set up some standard filters on all sheets, therefore I use some VBA like this

Sheets("Server").Select
col = Range("1:1").Find("In Selected SLA").Column
ActiveSheet.ListObjects("Srv").Range.AutoFilter Field:=col, Criteria1:="TRUE"

This code will adjust the filter on the column with heading "In Selected SLA", and leave all other filters unchanged. This has the unfortunate side effect that I can create a filter that shows zero records. This is not possible using the UI alone.

To avoid that situation, I would like to reset all filters before I apply the filtering above. My reset code looked like this

Sheets("Server").Select
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData

Note how I did not move the selected cell. If the selection was to the right, it would not remove filters, thus letting the filter code build a zero-row filter. The second time the code is run (on a zero-row filter) ShowAllData will fail.

The workaround is simple: Move the selection inside the filter columns before calling ShowAllData

Application.Goto (Sheets("Server").Range("A1"))
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData

This was on Excel version 14.0.7128.5000 (32-bit) = Office 2010

How do I reverse a C++ vector?

All containers offer a reversed view of their content with rbegin() and rend(). These two functions return so-calles reverse iterators, which can be used like normal ones, but it will look like the container is actually reversed.

#include <vector>
#include <iostream>

template<class InIt>
void print_range(InIt first, InIt last, char const* delim = "\n"){
  --last;
  for(; first != last; ++first){
    std::cout << *first << delim;
  }
  std::cout << *first;
}

int main(){
  int a[] = { 1, 2, 3, 4, 5 };
  std::vector<int> v(a, a+5);
  print_range(v.begin(), v.end(), "->");
  std::cout << "\n=============\n";
  print_range(v.rbegin(), v.rend(), "<-");
}

Live example on Ideone. Output:

1->2->3->4->5
=============
5<-4<-3<-2<-1

Update all objects in a collection using LINQ

While you can use a ForEach extension method, if you want to use just the framework you can do

collection.Select(c => {c.PropertyToSet = value; return c;}).ToList();

The ToList is needed in order to evaluate the select immediately due to lazy evaluation.

How to edit binary file on Unix systems

I used to use bvi.

I am developing hexvi to overcome :%!xxd and bvi's limitations.

hexvi

Features

  • vim-like keybindings and commands
  • going to specific offsets
  • inserting, replacing, deleting
  • searching for stuff (PCRE regexes)
  • everything is a command, and can be mapped in hexvirc
  • color schemes
  • support for large files
  • support for multiple files (via tabs)
  • Python so the entry level to hack around should be lower than C's
  • CLI through and through

Cons

  • as of March 2016, it's alpha so features are missing, but I'm working on those:
    • file saving
    • undo/redo
    • command history
    • visual selection
    • man page
  • no autocomplete

bvi

Features

  • vim-like keybindings and commands
  • going to specific offsets
  • inserting, deleting, replacing
  • searching for stuff (text and hex)
  • undo/redo
  • CLI through and through

Cons

  • regarding its vim capabilities - unfortunately, it understands only the most basic things and definitely needs more love in this regard (example: doesn't understand :wq, but understands :w and :q)
  • no visual selection support whatsoever
  • no tab/split screen support
  • crashes often
  • no support for large files
  • no command history
  • no autocomplete

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

This error occurs when you are sending JSON data to server. Maybe in your string you are trying to add new line character by using /n.

If you add / before /n, it should work, you need to escape new line character.

"Hello there //n start coding"

The result should be as following

Hello there
start coding

Why use Select Top 100 Percent?

No reason but indifference, I'd guess.

Such query strings are usually generated by a graphical query tool. The user joins a few tables, adds a filter, a sort order, and tests the results. Since the user may want to save the query as a view, the tool adds a TOP 100 PERCENT. In this case, though, the user copies the SQL into his code, parameterized the WHERE clause, and hides everything in a data access layer. Out of mind, out of sight.

How to get next/previous record in MySQL?

I had the same problem as Dan, so I used his answer and improved it.

First select the row index, nothing different here.

SELECT row
FROM 
(SELECT @rownum:=@rownum+1 row, a.* 
FROM articles a, (SELECT @rownum:=0) r
ORDER BY date, id) as article_with_rows
WHERE id = 50;

Now use two separate queries. For example if the row index is 21, the query to select the next record will be:

SELECT * 
FROM articles
ORDER BY date, id
LIMIT 21, 1

To select the previous record use this query:

SELECT * 
FROM articles
ORDER BY date, id
LIMIT 19, 1

Keep in mind that for the first row (row index is 1), the limit will go to -1 and you will get a MySQL error. You can use an if-statement to prevent this. Just don't select anything, since there is no previous record anyway. In the case of the last record, there will be next row and therefor there will be no result.

Also keep in mind that if you use DESC for ordering, instead of ASC, you queries to select the next and previous rows are still the same, but switched.

"Full screen" <iframe>

You can use this piece of code:

  <iframe src="http://example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0%;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

expand/collapse table rows with JQuery

I would say using the data- attribute to match the headers with the elements inside it. Fiddle : http://jsfiddle.net/GbRAZ/1/

A preview of the HTML alteration :

   <tr class="header" id="header1">
    <td colspan="2">Header</td>
   </tr>
   <tr data-for="header1" style="display:none">
     <td>data</td>
     <td>data</td>
   </tr>
   <tr data-for="header1" style="display:none">
     <td>data</td>
     <td>data</td>
   </tr>

JS code :

$(".header").click(function () {
   $("[data-for="+this.id+"]").slideToggle("slow");
});

EDIT: But, it involves some HTML changes. so I dunno if thats what you wanted. A better way to structure this would be using <th> or by changing the entire html to use ul, ol, etc or even a div > span setup.

How do you get current active/default Environment profile programmatically in Spring?

Seems there is some demand to be able to access this statically.

How can I get such thing in static methods in non-spring-managed classes? – Aetherus

It's a hack, but you can write your own class to expose it. You must be careful to ensure that nothing will call SpringContext.getEnvironment() before all beans have been created, since there is no guarantee when this component will be instantiated.

@Component
public class SpringContext
{
    private static Environment environment;

    public SpringContext(Environment environment) {
        SpringContext.environment = environment;
    }

    public static Environment getEnvironment() {
        if (environment == null) {
            throw new RuntimeException("Environment has not been set yet");
        }
        return environment;
    }
}

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

How to initialize a vector of vectors on a struct?

You use new to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.

You have no reason to use new, since A is an automatic variable. You can simply initialise A using its constructor:

vector<vector<int> > A(dimension, vector<int>(dimension));

Use of Application.DoEvents()

Check out the MSDN Documentation for the Application.DoEvents method.

How to save DataFrame directly to Hive?

Here is PySpark version to create Hive table from parquet file. You may have generated Parquet files using inferred schema and now want to push definition to Hive metastore. You can also push definition to the system like AWS Glue or AWS Athena and not just to Hive metastore. Here I am using spark.sql to push/create permanent table.

   # Location where my parquet files are present.
    df = spark.read.parquet("s3://my-location/data/")
    cols = df.dtypes
    buf = []
    buf.append('CREATE EXTERNAL TABLE test123 (')
    keyanddatatypes =  df.dtypes
    sizeof = len(df.dtypes)
    print ("size----------",sizeof)
    count=1;
    for eachvalue in keyanddatatypes:
        print count,sizeof,eachvalue
        if count == sizeof:
            total = str(eachvalue[0])+str(' ')+str(eachvalue[1])
        else:
            total = str(eachvalue[0]) + str(' ') + str(eachvalue[1]) + str(',')
        buf.append(total)
        count = count + 1

    buf.append(' )')
    buf.append(' STORED as parquet ')
    buf.append("LOCATION")
    buf.append("'")
    buf.append('s3://my-location/data/')
    buf.append("'")
    buf.append("'")
    ##partition by pt
    tabledef = ''.join(buf)

    print "---------print definition ---------"
    print tabledef
    ## create a table using spark.sql. Assuming you are using spark 2.1+
    spark.sql(tabledef);

how to configure hibernate config file for sql server

Don't forget to enable tcp/ip connections in SQL SERVER Configuration tools

HTML - Alert Box when loading page

you need a tiny bit of Javascript.

<script type="text/javascript">
window.onload = function(){ 
                alert("Hi there");
                }
</script>

This is only slightly different from Adam's answer. The effective difference is that this one alerts when the browser considers the page fully loaded, while Adam's alerts when the browser scans part the <script> tag in the text. The difference is with, for example, images, which may continue loading in parallel for a while.

Convert Go map to json

It actually tells you what's wrong, but you ignored it because you didn't check the error returned from json.Marshal.

json: unsupported type: map[int]main.Foo

JSON spec doesn't support anything except strings for object keys, while javascript won't be fussy about it, it's still illegal.

You have two options:

1 Use map[string]Foo and convert the index to string (using fmt.Sprint for example):

datas := make(map[string]Foo, N)

for i := 0; i < 10; i++ {
    datas[fmt.Sprint(i)] = Foo{Number: 1, Title: "test"}
}
j, err := json.Marshal(datas)
fmt.Println(string(j), err)

2 Simply just use a slice (javascript array):

datas2 := make([]Foo, N)
for i := 0; i < 10; i++ {
    datas2[i] = Foo{Number: 1, Title: "test"}
}
j, err = json.Marshal(datas2)
fmt.Println(string(j), err)

playground

Difference between ProcessBuilder and Runtime.exec()

The various overloads of Runtime.getRuntime().exec(...) take either an array of strings or a single string. The single-string overloads of exec() will tokenise the string into an array of arguments, before passing the string array onto one of the exec() overloads that takes a string array. The ProcessBuilder constructors, on the other hand, only take a varargs array of strings or a List of strings, where each string in the array or list is assumed to be an individual argument. Either way, the arguments obtained are then joined up into a string that is passed to the OS to execute.

So, for example, on Windows,

Runtime.getRuntime().exec("C:\DoStuff.exe -arg1 -arg2");

will run a DoStuff.exe program with the two given arguments. In this case, the command-line gets tokenised and put back together. However,

ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe -arg1 -arg2");

will fail, unless there happens to be a program whose name is DoStuff.exe -arg1 -arg2 in C:\. This is because there's no tokenisation: the command to run is assumed to have already been tokenised. Instead, you should use

ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe", "-arg1", "-arg2");

or alternatively

List<String> params = java.util.Arrays.asList("C:\DoStuff.exe", "-arg1", "-arg2");
ProcessBuilder b = new ProcessBuilder(params);

jQuery select child element by class with unknown path

Try this

$('#thisElement .classToSelect').each(function(i){
         // do stuff
});

Hope it will help

How do I compute the intersection point of two lines?

Can't stand aside,

So we have linear system:

A1 * x + B1 * y = C1
A2 * x + B2 * y = C2

let's do it with Cramer's rule, so solution can be found in determinants:

x = Dx/D
y = Dy/D

where D is main determinant of the system:

A1 B1
A2 B2

and Dx and Dy can be found from matricies:

C1 B1
C2 B2

and

A1 C1
A2 C2

(notice, as C column consequently substitues the coef. columns of x and y)

So now the python, for clarity for us, to not mess things up let's do mapping between math and python. We will use array L for storing our coefs A, B, C of the line equations and intestead of pretty x, y we'll have [0], [1], but anyway. Thus, what I wrote above will have the following form further in the code:

for D

L1[0] L1[1]
L2[0] L2[1]

for Dx

L1[2] L1[1]
L2[2] L2[1]

for Dy

L1[0] L1[2]
L2[0] L2[2]

Now go for coding:

line - produces coefs A, B, C of line equation by two points provided,
intersection - finds intersection point (if any) of two lines provided by coefs.

from __future__ import division 

def line(p1, p2):
    A = (p1[1] - p2[1])
    B = (p2[0] - p1[0])
    C = (p1[0]*p2[1] - p2[0]*p1[1])
    return A, B, -C

def intersection(L1, L2):
    D  = L1[0] * L2[1] - L1[1] * L2[0]
    Dx = L1[2] * L2[1] - L1[1] * L2[2]
    Dy = L1[0] * L2[2] - L1[2] * L2[0]
    if D != 0:
        x = Dx / D
        y = Dy / D
        return x,y
    else:
        return False

Usage example:

L1 = line([0,1], [2,3])
L2 = line([2,3], [0,4])

R = intersection(L1, L2)
if R:
    print "Intersection detected:", R
else:
    print "No single intersection point detected"

What is context in _.each(list, iterator, [context])?

The context parameter just sets the value of this in the iterator function.

var someOtherArray = ["name","patrick","d","w"];

_.each([1, 2, 3], function(num) { 
    // In here, "this" refers to the same Array as "someOtherArray"

    alert( this[num] ); // num is the value from the array being iterated
                        //    so this[num] gets the item at the "num" index of
                        //    someOtherArray.
}, someOtherArray);

Working Example: http://jsfiddle.net/a6Rx4/

It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray, which is represented by this since we passed it as the context parameter.

If you do not set the context, then this will refer to the window object.

jQuery .on('change', function() {} not triggering for dynamically created inputs

You should provide a selector to the on function:

$(document).on('change', 'input', function() {
  // Does some stuff and logs the event to the console
});

In that case, it will work as you expected. Also, it is better to specify some element instead of document.

Read this article for better understanding: http://elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

Mouseover or hover vue.js

It's possible to toggle a class on hover strictly within a component's template, however, it's not a practical solution for obvious reasons. For prototyping on the other hand, I find it useful to not have to define data properties or event handlers within the script.

Here's an example of how you can experiment with icon colors using Vuetify.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app'_x000D_
})
_x000D_
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet">_x000D_
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <v-app>_x000D_
    <v-toolbar color="black" dark>_x000D_
      <v-toolbar-items>_x000D_
        <v-btn icon>_x000D_
          <v-icon @mouseenter="e => e.target.classList.toggle('pink--text')" @mouseleave="e => e.target.classList.toggle('pink--text')">delete</v-icon>_x000D_
        </v-btn>_x000D_
        <v-btn icon>_x000D_
          <v-icon @mouseenter="e => e.target.classList.toggle('blue--text')" @mouseleave="e => e.target.classList.toggle('blue--text')">launch</v-icon>_x000D_
        </v-btn>_x000D_
        <v-btn icon>_x000D_
          <v-icon @mouseenter="e => e.target.classList.toggle('green--text')" @mouseleave="e => e.target.classList.toggle('green--text')">check</v-icon>_x000D_
        </v-btn>_x000D_
      </v-toolbar-items>_x000D_
    </v-toolbar>_x000D_
  </v-app>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Uncaught TypeError: Cannot read property 'top' of undefined

I know this is extremely old, but I understand that this error type is a common mistake for beginners to make since most beginners will call their functions upon their header element being loaded. Seeing as this solution is not addressed at all in this thread, I'll add it. It is very likely that this javascript function was placed before the actual html was loaded. Remember, if you immediately call your javascript before the document is ready then elements requiring an element from the document might find an undefined value.

How can I view live MySQL queries?

This is the easiest setup on a Linux Ubuntu machine I have come across. Crazy to see all the queries live.

Find and open your MySQL configuration file, usually /etc/mysql/my.cnf on Ubuntu. Look for the section that says “Logging and Replication”

#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.

log = /var/log/mysql/mysql.log

Just uncomment the “log” variable to turn on logging. Restart MySQL with this command:

sudo /etc/init.d/mysql restart

Now we’re ready to start monitoring the queries as they come in. Open up a new terminal and run this command to scroll the log file, adjusting the path if necessary.

tail -f /var/log/mysql/mysql.log

Now run your application. You’ll see the database queries start flying by in your terminal window. (make sure you have scrolling and history enabled on the terminal)

FROM http://www.howtogeek.com/howto/database/monitor-all-sql-queries-in-mysql/

refresh both the External data source and pivot tables together within a time schedule

I think there is a simpler way to make excel wait till the refresh is done, without having to set the Background Query property to False. Why mess with people's preferences right?

Excel 2010 (and later) has this method called CalculateUntilAsyncQueriesDone and all you have to do it call it after you have called the RefreshAll method. Excel will wait till the calculation is complete.

ThisWorkbook.RefreshAll
Application.CalculateUntilAsyncQueriesDone

I usually put these things together to do a master full calculate without interruption, before sending my models to others. Something like this:

ThisWorkbook.RefreshAll
Application.CalculateUntilAsyncQueriesDone
Application.CalculateFullRebuild
Application.CalculateUntilAsyncQueriesDone

How do you set the Content-Type header for an HttpClient request?

I end up having similar issue. So I discovered that the Software PostMan can generate code when clicking the "Code" button at upper/left corner. From that we can see what going on "under the hood" and the HTTP call is generated in many code language; curl command, C# RestShart, java, nodeJs, ...

That helped me a lot and instead of using .Net base HttpClient I ended up using RestSharp nuget package.

Hope that can help someone else!

Using prepared statements with JDBCTemplate

class Main {
    public static void main(String args[]) throws Exception {
        ApplicationContext ac = new
          ClassPathXmlApplicationContext("context.xml", Main.class);
        DataSource dataSource = (DataSource) ac.getBean("dataSource");
// DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        String prasobhName = 
        jdbcTemplate.query(
           "select first_name from customer where last_name like ?",
            new PreparedStatementSetter() {
              public void setValues(PreparedStatement preparedStatement) throws
                SQLException {
                  preparedStatement.setString(1, "nair%");
              }
            }, 
            new ResultSetExtractor<Long>() {
              public Long extractData(ResultSet resultSet) throws SQLException,
                DataAccessException {
                  if (resultSet.next()) {
                      return resultSet.getLong(1);
                  }
                  return null;
              }
            }
        );
        System.out.println(machaceksName);
    }
}

How to write a file with C in Linux?

You have to do write in the same loop as read.

How can I disable an <option> in a <select> based on its value in JavaScript?

Set an id to the option then use get element by id and disable it when x value has been selected..

example

<body>
      <select class="pull-right text-muted small" 
                 name="driveCapacity" id=driveCapacity onchange="checkRPM()">
      <option value="4000.0" id="4000">4TB</option>
      <option value="900.0" id="900">900GB</option>
      <option value="300.0" id ="300">300GB</option>
    </select>
    </body>
<script>
var perfType = document.getElementById("driveRPM").value;
if(perfType == "7200"){         
        document.getElementById("driveCapacity").value = "4000.0";
        document.getElementById("4000").disabled = false;           
    }else{          
        document.getElementById("4000").disabled = true;            
    }    
</script>

How do I get a div to float to the bottom of its container?

an alternative answer is the judicious use of tables and rowspan. by setting all table cells on the preceeding line (except the main content one) to be rowspan="2" you will always get a one cell hole at the bottom of your main table cell that you can always put valign="bottom".

You can also set its height to be the minimum you need for one line. Thus you will always get your favourite line of text at the bottom regardless of how much space the rest of the text takes up.

I tried all the div answers, I was unable to get them to do what I needed.

<table>
<tr>
   <td valign="top">
     this is just some random text
     <br> that should be a couple of lines long and
     <br> is at the top of where we need the bottom tag line
   </td>
   <td rowspan="2">
     this<br/>
     this<br/>
     this<br/>
     this<br/>
     this<br/>
     this<br/>
     this<br/>
     this<br/>
     this<br/>
     this<br/>
     this<br/>
     is really<br/>
     tall
  </td>
</tr>
<tr>
  <td valign="bottom">
      now this is the tagline we need on the bottom
  </td>
</tr>
</table>

Foreign Key to non-primary key

If you really want to create a foreign key to a non-primary key, it MUST be a column that has a unique constraint on it.

From Books Online:

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.

So in your case if you make AnotherID unique, it will be allowed. If you can't apply a unique constraint you're out of luck, but this really does make sense if you think about it.

Although, as has been mentioned, if you have a perfectly good primary key as a candidate key, why not use that?

Should composer.lock be committed to version control?

After doing it both ways for a few projects my stance is that composer.lock should not be committed as part of the project.

composer.lock is build metadata which is not part of the project. The state of dependencies should be controlled through how you're versioning them (either manually or as part of your automated build process) and not arbitrarily by the last developer to update them and commit the lock file.

If you are concerned about your dependencies changing between composer updates then you have a lack of confidence in your versioning scheme. Versions (1.0, 1.1, 1.2, etc) should be immutable and you should avoid "dev-" and "X.*" wildcards outside of initial feature development.

Committing the lock file is a regression for your dependency management system as the dependency version has now gone back to being implicitly defined.

Also, your project should never have to be rebuilt or have its dependencies reacquired in each environment, especially prod. Your deliverable (tar, zip, phar, a directory, etc) should be immutable and promoted through environments without changing.

How can I open a popup window with a fixed size using the HREF tag?

I can't comment on Esben Skov Pedersen's answer directly, but using the following notation for links:

<a href="javascript:window.open('http://www.websiteofyourchoice.com');">Click here</a>

In Internet Explorer, the new browser window appears, but the current window navigates to a page which says "[Object]". To avoid this, simple put a "void(0)" behind the JavaScript function.

Source: https://support.microsoft.com/en-us/kb/257321

Storing and displaying unicode string (??????) using PHP and MySQL

For those who are looking for PHP ( >5.3.5 ) PDO statement, we can set charset as per below:

$dbh = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');

When should we use mutex and when should we use semaphore

See "The Toilet Example" - http://pheatt.emporia.edu/courses/2010/cs557f10/hand07/Mutex%20vs_%20Semaphore.htm:

Mutex:

Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue.

Officially: "Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section." Ref: Symbian Developer Library

(A mutex is really a semaphore with value 1.)

Semaphore:

Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

Officially: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)." Ref: Symbian Developer Library

PHP session handling errors

If you use a configured vhost and find the same error then you can override the default setting of php_value session.save_path under your <VirtualHost *:80>

#
# Apache specific PHP configuration options
# those can be override in each configured vhost
#
php_value session.save_handler "files"
php_value session.save_path    "/var/lib/php/5.6/session"
php_value soap.wsdl_cache_dir  "/var/lib/php/5.6/wsdlcache"

Change the path to your own '/tmp' with chmod 777.

sql how to cast a select query

If you're using SQL (which you didn't say):

select cast(column as varchar(200)) from table 

You can use it in any statement, for example:

select value where othervalue in( select cast(column as varchar(200)) from table)
from othertable

If you want to do a join query, the answer is here already in another post :)

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

How to scroll to top of the page in AngularJS?

Ideally we should do it from either controller or directive as per applicable. Use $anchorScroll, $location as dependency injection.

Then call this two method as

$location.hash('scrollToDivID');
$anchorScroll();

Here scrollToDivID is the id where you want to scroll.

Assumed you want to navigate to a error message div as

<div id='scrollToDivID'>Your Error Message</div>

For more information please see this documentation

TypeError: got multiple values for argument

I was brought here for a reason not explicitly mentioned in the answers so far, so to save others the trouble:

The error also occurs if the function arguments have changed order - for the same reason as in the accepted answer: the positional arguments clash with the keyword arguments.

In my case it was because the argument order of the Pandas set_axis function changed between 0.20 and 0.22:

0.20: DataFrame.set_axis(axis, labels)
0.22: DataFrame.set_axis(labels, axis=0, inplace=None)

Using the commonly found examples for set_axis results in this confusing error, since when you call:

df.set_axis(['a', 'b', 'c'], axis=1)

prior to 0.22, ['a', 'b', 'c'] is assigned to axis because it's the first argument, and then the positional argument provides "multiple values".

How to tell if a file is git tracked (by shell exit code)?

using git log will give info about this. If the file is tracked in git the command shows some results(logs). Else it is empty.

For example if the file is git tracked,

root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
commit ad9180b772d5c64dcd79a6cbb9487bd2ef08cbfc
Author: User <[email protected]>
Date:   Mon Feb 20 07:45:04 2017 -0600

    fix eslint indentation errors
....
....

If the file is not git tracked,

root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
root@user-ubuntu:~/project-repo-directory#

How to know which is running in Jupyter notebook?

import sys
print(sys.executable)
print(sys.version)
print(sys.version_info)

Seen below :- output when i run JupyterNotebook outside a CONDA venv

/home/dhankar/anaconda2/bin/python
2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jul  2 2016, 17:42:40) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)
 

Seen below when i run same JupyterNoteBook within a CONDA Venv created with command --

conda create -n py35 python=3.5 ## Here - py35 , is name of my VENV

in my Jupyter Notebook it prints :-

/home/dhankar/anaconda2/envs/py35/bin/python
3.5.2 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:53:06) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)

also if you already have various VENV's created with different versions of Python you switch to the desired Kernel by choosing KERNEL >> CHANGE KERNEL from within the JupyterNotebook menu... JupyterNotebookScreencapture

Also to install ipykernel within an existing CONDA Virtual Environment -

http://ipython.readthedocs.io/en/stable/install/kernel_install.html#kernels-for-different-environments

Source --- https://github.com/jupyter/notebook/issues/1524

 $ /path/to/python -m  ipykernel install --help
 usage: ipython-kernel-install [-h] [--user] [--name NAME]
                          [--display-name DISPLAY_NAME]
                          [--profile PROFILE] [--prefix PREFIX]
                          [--sys-prefix]

Install the IPython kernel spec.

optional arguments: -h, --help show this help message and exit --user Install for the current user instead of system-wide --name NAME Specify a name for the kernelspec. This is needed to have multiple IPython kernels at the same time. --display-name DISPLAY_NAME Specify the display name for the kernelspec. This is helpful when you have multiple IPython kernels. --profile PROFILE Specify an IPython profile to load. This can be used to create custom versions of the kernel. --prefix PREFIX Specify an install prefix for the kernelspec. This is needed to install into a non-default location, such as a conda/virtual-env. --sys-prefix Install to Python's sys.prefix. Shorthand for --prefix='/Users/bussonniermatthias/anaconda'. For use in conda/virtual-envs.

Is it possible to get an Excel document's row count without loading the entire document into memory?

Python 3

import openpyxl as xl

wb = xl.load_workbook("Sample.xlsx", enumerate)

#the 2 lines under do the same. 
sheet = wb.get_sheet_by_name('sheet') 
sheet = wb.worksheets[0]

row_count = sheet.max_row
column_count = sheet.max_column

#this works fore me.

Simple example for Intent and Bundle

Try this: if you need pass values between the activities you use this...

This is code for Main_Activity put the values to intent

 String name="aaaa";
 Intent intent=new Intent(Main_Activity.this,Other_Activity.class);
 intent.putExtra("name", name);
 startActivity(intent);

This code for Other_Activity and get the values form intent

    Bundle b = new Bundle();
    b = getIntent().getExtras();
    String name = b.getString("name");

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Another, and more streamlined, approach to deserializing a camel-cased JSON string to a pascal-cased POCO object is to use the CamelCasePropertyNamesContractResolver.

It's part of the Newtonsoft.Json.Serialization namespace. This approach assumes that the only difference between the JSON object and the POCO lies in the casing of the property names. If the property names are spelled differently, then you'll need to resort to using JsonProperty attributes to map property names.

using Newtonsoft.Json; 
using Newtonsoft.Json.Serialization;

. . .

private User LoadUserFromJson(string response) 
{
    JsonSerializerSettings serSettings = new JsonSerializerSettings();
    serSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    User outObject = JsonConvert.DeserializeObject<User>(jsonValue, serSettings);

    return outObject; 
}

Disable scrolling in all mobile devices

The following works for me, although I did not test every single device there is to test :-)

$('body, html').css('overflow-y', 'hidden');
$('html, body').animate({
    scrollTop:0
}, 0);

case statement in SQL, how to return multiple variables?

You could use a subselect combined with a UNION. Whenever you can return the same fields for more than one condition use OR with the parenthesis as in this example:

SELECT * FROM
  (SELECT val1, val2 FROM table1 WHERE (condition1 is true) 
                                    OR (condition2 is true))
UNION
SELECT * FROM
  (SELECT val5, val6 FROM table7 WHERE (condition9 is true) 
                                    OR (condition4 is true))

Using COALESCE to handle NULL values in PostgreSQL

If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.

UPDATE pt.incentive_channel
SET   pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';

This will make joining and selecting substantially easier moving forward.

execute shell command from android

You should grab the standard input of the su process just launched and write down the command there, otherwise you are running the commands with the current UID.

Try something like this:

try{
    Process su = Runtime.getRuntime().exec("su");
    DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

    outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
    outputStream.flush();

    outputStream.writeBytes("exit\n");
    outputStream.flush();
    su.waitFor();
}catch(IOException e){
    throw new Exception(e);
}catch(InterruptedException e){
    throw new Exception(e);
}

Swift 3: Display Image from URL

Use extension for UIImageView to Load URL Images.

let imageCache = NSCache<NSString, UIImage>()

extension UIImageView {

    func imageURLLoad(url: URL) {

        DispatchQueue.global().async { [weak self] in
            func setImage(image:UIImage?) {
                DispatchQueue.main.async {
                    self?.image = image
                }
            }
            let urlToString = url.absoluteString as NSString
            if let cachedImage = imageCache.object(forKey: urlToString) {
                setImage(image: cachedImage)
            } else if let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
                DispatchQueue.main.async {
                    imageCache.setObject(image, forKey: urlToString)
                    setImage(image: image)
                }
            }else {
                setImage(image: nil)
            }
        }
    }
}

How to call a Parent Class's method from Child Class in Python?

Use the super() function:

class Foo(Bar):
    def baz(self, arg):
        return super().baz(arg)

For Python < 3, you must explicitly opt in to using new-style classes and use:

class Foo(Bar):
    def baz(self, arg):
        return super(Foo, self).baz(arg)

What are the obj and bin folders (created by Visual Studio) used for?

The obj folder holds object, or intermediate, files, which are compiled binary files that haven't been linked yet. They're essentially fragments that will be combined to produce the final executable. The compiler generates one object file for each source file, and those files are placed into the obj folder.

The bin folder holds binary files, which are the actual executable code for your application or library.

Each of these folders are further subdivided into Debug and Release folders, which simply correspond to the project's build configurations. The two types of files discussed above are placed into the appropriate folder, depending on which type of build you perform. This makes it easy for you to determine which executables are built with debugging symbols, and which were built with optimizations enabled and ready for release.

Note that you can change where Visual Studio outputs your executable files during a compile in your project's Properties. You can also change the names and selected options for your build configurations.

Basic http file downloading and saving to disk in python?

import urllib
urllib.request.urlretrieve("https://raw.githubusercontent.com/dnishimoto/python-deep-learning/master/list%20iterators%20and%20generators.ipynb", "test.ipynb")

downloads a single raw juypter notebook to file.

Does Go have "if x in" construct similar to Python?

Another option is using a map as a set. You use just the keys and having the value be something like a boolean that's always true. Then you can easily check if the map contains the key or not. This is useful if you need the behavior of a set, where if you add a value multiple times it's only in the set once.

Here's a simple example where I add random numbers as keys to a map. If the same number is generated more than once it doesn't matter, it will only appear in the final map once. Then I use a simple if check to see if a key is in the map or not.

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    var MAX int = 10

    m := make(map[int]bool)

    for i := 0; i <= MAX; i++ {
        m[rand.Intn(MAX)] = true
    }

    for i := 0; i <= MAX; i++ {
        if _, ok := m[i]; ok {
            fmt.Printf("%v is in map\n", i)
        } else {
            fmt.Printf("%v is not in map\n", i)
        }
    }
}

Here it is on the go playground

Binding an enum to a WinForms combo box, and then setting it

You can use a extension method

 public static void EnumForComboBox(this ComboBox comboBox, Type enumType)
 {
     var memInfo = enumType.GetMembers().Where(a => a.MemberType == MemberTypes.Field).ToList();
     comboBox.Items.Clear();
     foreach (var member in memInfo)
     {
         var myAttributes = member.GetCustomAttribute(typeof(DescriptionAttribute), false);
         var description = (DescriptionAttribute)myAttributes;
         if (description != null)
         {
             if (!string.IsNullOrEmpty(description.Description))
             {
                 comboBox.Items.Add(description.Description);
                 comboBox.SelectedIndex = 0;
                 comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
             }
         }   
     }
 }

How to use ... Declare enum

using System.ComponentModel;

public enum CalculationType
{
    [Desciption("LoaderGroup")]
    LoaderGroup,
    [Description("LadingValue")]
    LadingValue,
    [Description("PerBill")]
    PerBill
}

This method show description in Combo box items

combobox1.EnumForComboBox(typeof(CalculationType));

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

Why does Date.parse give incorrect results?

Here is a short, flexible snippet to convert a datetime-string in a cross-browser-safe fashion as nicel detailed by @drankin2112.

var inputTimestamp = "2014-04-29 13:00:15"; //example

var partsTimestamp = inputTimestamp.split(/[ \/:-]/g);
if(partsTimestamp.length < 6) {
    partsTimestamp = partsTimestamp.concat(['00', '00', '00'].slice(0, 6 - partsTimestamp.length));
}
//if your string-format is something like '7/02/2014'...
//use: var tstring = partsTimestamp.slice(0, 3).reverse().join('-');
var tstring = partsTimestamp.slice(0, 3).join('-');
tstring += 'T' + partsTimestamp.slice(3).join(':') + 'Z'; //configure as needed
var timestamp = Date.parse(tstring);

Your browser should provide the same timestamp result as Date.parse with:

(new Date(tstring)).getTime()

simple HTTP server in Java using only Java SE API

Have a look at the "Jetty" web server Jetty. Superb piece of Open Source software that would seem to meet all your requirments.

If you insist on rolling your own then have a look at the "httpMessage" class.

Windows batch file file download from a URL

There's a utility (resides with CMD) on Windows which can be run from CMD (if you have write access):

set url=https://www.nsa.org/content/hl-images/2017/02/09/NSA.jpg
set file=file.jpg
certutil -urlcache -split -f %url% %file%
echo Done.

Built in Windows application. No need for external downloads.

Tested on Win 10

How to use Python's pip to download and keep the zipped files for a package?

pip wheel is another option you should consider:

pip wheel mypackage -w .\outputdir

It will download packages and their dependencies to a directory (current working directory by default), but it performs the additional step of converting any source packages to wheels.

It conveniently supports requirements files:

pip wheel -r requirements.txt -w .\outputdir

Add the --no-deps argument if you only want the specifically requested packages:

pip wheel mypackage -w .\outputdir --no-deps

What is the max size of VARCHAR2 in PL/SQL and SQL?

If you use UTF-8 encoding then one character can takes a various number of bytes (2 - 4). For PL/SQL the varchar2 limit is 32767 bytes, not characters. See how I increase a PL/SQL varchar2 variable of the 4000 character size:

SQL> set serveroutput on
SQL> l
  1  declare
  2    l_var varchar2(30000);
  3  begin
  4    l_var := rpad('A', 4000);
  5    dbms_output.put_line(length(l_var));
  6    l_var := l_var || rpad('B', 10000);
  7    dbms_output.put_line(length(l_var));
  8* end;
SQL> /
4000
14000

PL/SQL procedure successfully completed.

But you can't insert into your table the value of such variable:

SQL> ed
Wrote file afiedt.buf

  1  create table ttt (
  2    col1 varchar2(2000 char)
  3* )
SQL> /

Table created.

SQL> ed
Wrote file afiedt.buf

  1  declare
  2    l_var varchar2(30000);
  3  begin
  4      l_var := rpad('A', 4000);
  5      dbms_output.put_line(length(l_var));
  6      l_var := l_var || rpad('B', 10000);
  7      dbms_output.put_line(length(l_var));
  8      insert into ttt values (l_var);
  9* end;
SQL> /
4000
14000
declare
*
ERROR at line 1:
ORA-01461: can bind a LONG value only for insert into a LONG column
ORA-06512: at line 8

As a solution, you can try to split this variable's value into several parts (SUBSTR) and store them separately.

Can't get Gulp to run: cannot find module 'gulp-util'

I had the same issue, although the module that it was downloading was different. The only resolution to the problem is run the below command again:

npm install

How to print an unsigned char in C?

There are two bugs in this code. First, in most C implementations with signed char, there is a problem in char ch = 212 because 212 does not fit in an 8-bit signed char, and the C standard does not fully define the behavior (it requires the implementation to define the behavior). It should instead be:

unsigned char ch = 212;

Second, in printf("%u",ch), ch will be promoted to an int in normal C implementations. However, the %u specifier expects an unsigned int, and the C standard does not define behavior when the wrong type is passed. It should instead be:

printf("%u", (unsigned) ch);

Meaning of "487 Request Terminated"

It's the response code a SIP User Agent Server (UAS) will send to the client after the client sends a CANCEL request for the original unanswered INVITE request (yet to receive a final response).

Here is a nice CANCEL SIP Call Flow illustration.

How do I determine the size of my array in C?

You can use sizeof operator but it will not work for functions because it will take the reference of pointer you can do the following to find the length of an array:

len = sizeof(arr)/sizeof(arr[0])

Code originally found here: C program to find the number of elements in an array

ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number 3 (and uses it as default), so switch back to a value of 2 which can be read by Python 2.

Check the protocolparameter in pickle.dump. Your resulting code will look like this.

pickle.dump(your_object, your_file, protocol=2)

There is no protocolparameter in pickle.load because pickle can determine the protocol from the file.

How to open .SQLite files

If you just want to see what's in the database without installing anything extra, you might already have SQLite CLI on your system. To check, open a command prompt and try:

sqlite3 database.sqlite

Replace database.sqlite with your database file. Then, if the database is small enough, you can view the entire contents with:

sqlite> .dump

Or you can list the tables:

sqlite> .tables

Regular SQL works here as well:

sqlite> select * from some_table;

Replace some_table as appropriate.

check if jquery has been loaded, then load it if false

<script>
if (typeof(jQuery) == 'undefined'){
        document.write('<scr' + 'ipt type="text/javascript" src=" https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></scr' + 'ipt>');
}
</script>

How can I insert vertical blank space into an html document?

write it like this

p {
    padding-bottom: 3cm;
}

or

p {
    margin-bottom: 3cm;
}

How do I kill a process using Vb.NET or C#?

In my tray app, I needed to clean Excel and Word Interops. So This simple method kills processes generically.

This uses a general exception handler, but could be easily split for multiple exceptions like stated in other answers. I may do this if my logging produces alot of false positives (ie can't kill already killed). But so far so guid (work joke).

/// <summary>
/// Kills Processes By Name
/// </summary>
/// <param name="names">List of Process Names</param>
private void killProcesses(List<string> names)
{
    var processes = new List<Process>();
    foreach (var name in names)
        processes.AddRange(Process.GetProcessesByName(name).ToList());
    foreach (Process p in processes)
    {
        try
        {
            p.Kill();
            p.WaitForExit();
        }
        catch (Exception ex)
        {
            // Logging
            RunProcess.insertFeedback("Clean Processes Failed", ex);
        }
    }
}

This is how i called it then:

killProcesses((new List<string>() { "winword", "excel" }));

When to use pthread_exit() and when to use pthread_join() in Linux?

Hmm.

POSIX pthread_exit description from http://pubs.opengroup.org/onlinepubs/009604599/functions/pthread_exit.html:

After a thread has terminated, the result of access to local (auto) variables of the thread is 
undefined. Thus, references to local variables of the exiting thread should not be used for 
the pthread_exit() value_ptr parameter value.

Which seems contrary to the idea that local main() thread variables will remain accessible.

Set language for syntax highlighting in Visual Studio Code

Press Ctrl + KM and then type in (or click) the language you want.

Alternatively, to access it from the command palette, look for "Change Language Mode" as seen below:

enter image description here

best way to get the key of a key/value javascript object

There is no way other than for ... in. If you don't want to use that (parhaps because it's marginally inefficient to have to test hasOwnProperty on each iteration?) then use a different construct, e.g. an array of kvp's:

[{ key: 'key', value: 'value'}, ...]

Remove style attribute from HTML tags

Here you go:

<?php

$html = '<p style="border: 1px solid red;">Test</p>';
echo preg_replace('/<p style="(.+?)">(.+?)<\/p>/i', "<p>$2</p>", $html);

?>

By the way, as pointed out by others, regex are not suggested for this.

console.log(result) returns [object Object]. How do I get result.name?

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

How to know if two arrays have the same values

What about this? ES 2017 i suppose:

_x000D_
_x000D_
const array1 = [1, 3, 5];_x000D_
const array2 = [1, 5, 3];_x000D_
_x000D_
const isEqual = (array1.length === array2.length) && (array1.every(val => array2.includes(val)));_x000D_
console.log(isEqual);
_x000D_
_x000D_
_x000D_

1st condition checks if both arrays have same length and 2nd condition checks if 1st array is a subset of the 2nd array. Combining these 2 conditions should then result in comparison of all items of the 2 arrays irrespective of the ordering of elements.

The above code will only work if both arrays have non-duplicate items.

Printing *s as triangles in Java?

For the right triangle, for each row :

  • First: You need to print spaces from 0 to rowNumber - 1 - i.
  • Second: You need to print \* from rowNumber - 1 - i to rowNumber.

Note: i is the row index from 0 to rowNumber and rowNumber is number of rows.

For the centre triangle: it looks like "right triangle" plus adding \* according to the row index (for ex : in first row you will add nothing because the index is 0 , in the second row you will add one ' * ', and so on).

Symbolicating iPhone App Crash Reports

I also put dsym, app bundle, and crash log together in the same directory before running symbolicate crash

Then I use this function defined in my .profile to simplify running symbolicatecrash:

function desym
{
    /Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/DTDeviceKit.framework/Versions/A/Resources/symbolicatecrash -A -v $1 | more
}

The arguments added there may help you.

You can check to make sure spotlight "sees" your dysm files by running the command:

mdfind 'com_apple_xcode_dsym_uuids = *'

Look for the dsym you have in your directory.

NOTE: As of the latest Xcode, there is no longer a Developer directory. You can find this utility here:

/Applications/Xcode.app/Contents/SharedFrameworks/DTDeviceKitBase.framework/Vers??ions/A/Resources/symbolicatecrash

Iptables setting multiple multiports in one rule

You need to use multiple rules to implement OR-like semantics, since matches are always AND-ed together within a rule. Alternatively, you can do matching against port-indexing ipsets (ipset create blah bitmap:port).

Function stoi not declared

Install the latest version of TDM-GCC here is the link-http://wiki.codeblocks.org/index.php/MinGW_installation

NSRange from Swift Range?

func formatAttributedStringWithHighlights(text: String, highlightedSubString: String?, formattingAttributes: [String: AnyObject]) -> NSAttributedString {
    let mutableString = NSMutableAttributedString(string: text)

    let text = text as NSString         // convert to NSString be we need NSRange
    if let highlightedSubString = highlightedSubString {
        let highlightedSubStringRange = text.rangeOfString(highlightedSubString) // find first occurence
        if highlightedSubStringRange.length > 0 {       // check for not found
            mutableString.setAttributes(formattingAttributes, range: highlightedSubStringRange)
        }
    }

    return mutableString
}

AngularJS. How to call controller function from outside of controller component

I've found an example on the internet.

Some guy wrote this code and worked perfectly

HTML

<div ng-cloak ng-app="ManagerApp">
    <div id="MainWrap" class="container" ng-controller="ManagerCtrl">
       <span class="label label-info label-ext">Exposing Controller Function outside the module via onClick function call</span>
       <button onClick='ajaxResultPost("Update:Name:With:JOHN","accept",true);'>click me</button>
       <br/> <span class="label label-warning label-ext" ng-bind="customParams.data"></span>
       <br/> <span class="label label-warning label-ext" ng-bind="customParams.type"></span>
       <br/> <span class="label label-warning label-ext" ng-bind="customParams.res"></span>
       <br/>
       <input type="text" ng-model="sampletext" size="60">
       <br/>
    </div>
</div>

JAVASCRIPT

var angularApp = angular.module('ManagerApp', []);
angularApp.controller('ManagerCtrl', ['$scope', function ($scope) {

$scope.customParams = {};

$scope.updateCustomRequest = function (data, type, res) {
    $scope.customParams.data = data;
    $scope.customParams.type = type;
    $scope.customParams.res = res;
    $scope.sampletext = "input text: " + data;
};



}]);

function ajaxResultPost(data, type, res) {
    var scope = angular.element(document.getElementById("MainWrap")).scope();
    scope.$apply(function () {
    scope.updateCustomRequest(data, type, res);
    });
}

Demo

*I did some modifications, see original: font JSfiddle

Cause of No suitable driver found for

If you look at your original connection string:

<property name="url" value="jdbc:hsqldb:hsql://localhost"/>

The Hypersonic docs suggest that you're missing an alias after localhost:

http://hsqldb.org/doc/guide/ch04.html

Adding ASP.NET MVC5 Identity Authentication to an existing project

Configuring Identity to your existing project is not hard thing. You must install some NuGet package and do some small configuration.

First install these NuGet packages with Package Manager Console:

PM> Install-Package Microsoft.AspNet.Identity.Owin 
PM> Install-Package Microsoft.AspNet.Identity.EntityFramework
PM> Install-Package Microsoft.Owin.Host.SystemWeb 

Add a user class and with IdentityUser inheritance:

public class AppUser : IdentityUser
{
    //add your custom properties which have not included in IdentityUser before
    public string MyExtraProperty { get; set; }  
}

Do same thing for role:

public class AppRole : IdentityRole
{
    public AppRole() : base() { }
    public AppRole(string name) : base(name) { }
    // extra properties here 
}

Change your DbContext parent from DbContext to IdentityDbContext<AppUser> like this:

public class MyDbContext : IdentityDbContext<AppUser>
{
    // Other part of codes still same 
    // You don't need to add AppUser and AppRole 
    // since automatically added by inheriting form IdentityDbContext<AppUser>
}

If you use the same connection string and enabled migration, EF will create necessary tables for you.

Optionally, you could extend UserManager to add your desired configuration and customization:

public class AppUserManager : UserManager<AppUser>
{
    public AppUserManager(IUserStore<AppUser> store)
        : base(store)
    {
    }

    // this method is called by Owin therefore this is the best place to configure your User Manager
    public static AppUserManager Create(
        IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
    {
        var manager = new AppUserManager(
            new UserStore<AppUser>(context.Get<MyDbContext>()));

        // optionally configure your manager
        // ...

        return manager;
    }
}

Since Identity is based on OWIN you need to configure OWIN too:

Add a class to App_Start folder (or anywhere else if you want). This class is used by OWIN. This will be your startup class.

namespace MyAppNamespace
{
    public class IdentityConfig
    {
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext(() => new MyDbContext());
            app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
            app.CreatePerOwinContext<RoleManager<AppRole>>((options, context) =>
                new RoleManager<AppRole>(
                    new RoleStore<AppRole>(context.Get<MyDbContext>())));

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Home/Login"),
            });
        }
    }
}

Almost done just add this line of code to your web.config file so OWIN could find your startup class.

<appSettings>
    <!-- other setting here -->
    <add key="owin:AppStartup" value="MyAppNamespace.IdentityConfig" />
</appSettings>

Now in entire project you could use Identity just like any new project had already installed by VS. Consider login action for example

[HttpPost]
public ActionResult Login(LoginViewModel login)
{
    if (ModelState.IsValid)
    {
        var userManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
        var authManager = HttpContext.GetOwinContext().Authentication;

        AppUser user = userManager.Find(login.UserName, login.Password);
        if (user != null)
        {
            var ident = userManager.CreateIdentity(user, 
                DefaultAuthenticationTypes.ApplicationCookie);
            //use the instance that has been created. 
            authManager.SignIn(
                new AuthenticationProperties { IsPersistent = false }, ident);
            return Redirect(login.ReturnUrl ?? Url.Action("Index", "Home"));
        }
    }
    ModelState.AddModelError("", "Invalid username or password");
    return View(login);
}

You could make roles and add to your users:

public ActionResult CreateRole(string roleName)
{
    var roleManager=HttpContext.GetOwinContext().GetUserManager<RoleManager<AppRole>>();

    if (!roleManager.RoleExists(roleName))
        roleManager.Create(new AppRole(roleName));
    // rest of code
} 

You could also add a role to a user, like this:

UserManager.AddToRole(UserManager.FindByName("username").Id, "roleName");

By using Authorize you could guard your actions or controllers:

[Authorize]
public ActionResult MySecretAction() {}

or

[Authorize(Roles = "Admin")]]
public ActionResult MySecretAction() {}

You can also install additional packages and configure them to meet your requirement like Microsoft.Owin.Security.Facebook or whichever you want.

Note: Don't forget to add relevant namespaces to your files:

using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;

You could also see my other answers like this and this for advanced use of Identity.

Getting rid of all the rounded corners in Twitter Bootstrap

You may also want to have a look at FlatStrap. It provides a Metro-Style replacement for the Bootstrap CSS without rounded corners, gradients and drop shadows.

Can I hide the HTML5 number input’s spin box?

This like your css code:

input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

Pass variables from servlet to jsp

You can also use RequestDispacher and pass on the data along with the jsp page you want.

request.setAttribute("MyData", data);
RequestDispatcher rd = request.getRequestDispatcher("page.jsp");
rd.forward(request, response);

How do you search an amazon s3 bucket?

There are multiple options, none being simple "one shot" full text solution:

  1. Key name pattern search: Searching for keys starting with some string- if you design key names carefully, then you may have rather quick solution.

  2. Search metadata attached to keys: when posting a file to AWS S3, you may process the content, extract some meta information and attach this meta information in form of custom headers into the key. This allows you to fetch key names and headers without need to fetch complete content. The search has to be done sequentialy, there is no "sql like" search option for this. With large files this could save a lot of network traffic and time.

  3. Store metadata on SimpleDB: as previous point, but with storing the metadata on SimpleDB. Here you have sql like select statements. In case of large data sets you may hit SimpleDB limits, which can be overcome (partition metadata across multiple SimpleDB domains), but if you go really far, you may need to use another metedata type of database.

  4. Sequential full text search of the content - processing all the keys one by one. Very slow, if you have too many keys to process.

We are storing 1440 versions of a file a day (one per minute) for couple of years, using versioned bucket, it is easily possible. But getting some older version takes time, as one has to sequentially go version by version. Sometime I use simple CSV index with records, showing publication time plus version id, having this, I could jump to older version rather quickly.

As you see, AWS S3 is not on it's own designed for full text searches, it is simple storage service.

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

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

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

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

Cannot set property 'innerHTML' of null

Let the DOM load. To do something in the DOM you have to Load it first. In your case You have to load the <div> tag first. then you have something to modify. if you load the js first then that function is looking your HTML to do what you asked to do, but when that time your HTML is loading and your function cant find the HTML. So you can put the script in the bottom of the page. inside <body> tag then the function can access the <div> Because DOM is already loaded the time you hit the script.

Scheduling recurring task in Android

I am not sure but as per my knowledge I share my views. I always accept best answer if I am wrong .

Alarm Manager

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes. If your alarm receiver called Context.startService(), it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.

Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

Timer

timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

        synchronized public void run() {

            \\ here your todo;
            }

        }, TimeUnit.MINUTES.toMillis(1), TimeUnit.MINUTES.toMillis(1));

Timer has some drawbacks that are solved by ScheduledThreadPoolExecutor. So it's not the best choice

ScheduledThreadPoolExecutor.

You can use java.util.Timer or ScheduledThreadPoolExecutor (preferred) to schedule an action to occur at regular intervals on a background thread.

Here is a sample using the latter:

ScheduledExecutorService scheduler =
    Executors.newSingleThreadScheduledExecutor();

scheduler.scheduleAtFixedRate
      (new Runnable() {
         public void run() {
            // call service
         }
      }, 0, 10, TimeUnit.MINUTES);

So I preferred ScheduledExecutorService

But Also think about that if the updates will occur while your application is running, you can use a Timer, as suggested in other answers, or the newer ScheduledThreadPoolExecutor. If your application will update even when it is not running, you should go with the AlarmManager.

The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.

Take note that if you plan on updating when your application is turned off, once every ten minutes is quite frequent, and thus possibly a bit too power consuming.

Implementing multiple interfaces with Java - is there a way to delegate?

Unfortunately: NO.

We're all eagerly awaiting the Java support for extension methods

How to extract multiple JSON objects from one file?

So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.

The basic idea is to signal the reader to split on the carriage character "\n" (or "\r\n" for Windows). Python can do this with the file.readline() function.

import json
def json_reader(filename):
    with open(filename) as f:
        for line in f:
            yield json.loads(line)

However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.

def json_writer(file, json_objects):
    with open(file, "w") as f:
        for jsonobj in json_objects:
            jsonstr = json.dumps(jsonobj)
            f.write(jsonstr + "\n")

You could also do the same operation with file.writelines() and a list comprehension:

...
    json_strs = [json.dumps(j) + "\n" for j in json_objects]
    f.writelines(json_strs)
...

And if you wanted to append the data instead of writing a new file just change open(file, "w") to open(file, "a").

In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.

On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write

lst = list(json_reader(file))

Styling JQuery UI Autocomplete

Based on @md-nazrul-islam reply, This is what I did with SCSS:

ul.ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border: 1px solid #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    //@include border-radius(5px);
    @include box-shadow( rgba(0, 0, 0, 0.1) 0 5px 10px );
    @include background-clip(padding-box);
    *border-right-width: 2px;
    *border-bottom-width: 2px;

    li.ui-menu-item{
        padding:0 .5em;
        line-height:2em;
        font-size:.8em;
        &.ui-state-focus{
            background: #F7F7F7;
        }
    }

}

How to name an object within a PowerPoint slide?

Select the Object -> Format -> Selection Pane -> Double click to change the name

enter image description here

Java Embedded Databases Comparison

What criteria will you use to evaluate these ? If you don't know yet, then you don't need to decide right now. Try to make your application as database-implementation-agnostic as you can - providing the appropriate wrappers, data access objects etc., and make this decision when you have all the facts to hand and you have to decide.

If you're using relational databases and SQL then the above shouldn't be too hard (using JDBC etc). Make sure you have plenty of surrounding tests so that when you want to switch between databases, you can determine that your application's functionality remains the same.

I ran into the same issue some time ago. I didn't know which database to go for, so my first solution used Derby (or HSQLDB?), and I was later able to switch to HSQLDB (or Derby ? Can't remember which solution worked) once I'd determined where I had issues (relating to performance) and which solution would really work for me.

How to convert image into byte array and byte array to base64 String in android?

here is another solution...

System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];

System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
    m.Write (buffer, 0, buffer.Length);
}  
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();

hope it helps!

How do I replace whitespaces with underscore?

Django has a 'slugify' function which does this, as well as other URL-friendly optimisations. It's hidden away in the defaultfilters module.

>>> from django.template.defaultfilters import slugify
>>> slugify("This should be connected")

this-should-be-connected

This isn't exactly the output you asked for, but IMO it's better for use in URLs.

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

Making a drop down list using swift?

Using UIPickerview is the right way to go to implement it according to Apple's Human Interface Guidelines

If you select drop down in mobile safari it will show UIPickerview to let the use choose drop down items.

Alternatively

you can use UIPopoverController till iOS 9 as its deprecated but its better to stick with UIModalPresentationPopover of view you want o show as well

you can use UIActionsheet to show the items but it's better to use UIAlertViewController and choose UIActionSheetstyle to show as the former is deprecated in latest versions

Is it possible to make Font Awesome icons larger than 'fa-5x'?

  1. Just add the font awesome class like this:

    class="fa fa-plus-circle fa-3x"
    

    (You can increase the size as per 5x, 7x, 9x..)

  2. You can also add custom CSS.

Using ZXing to create an Android barcode scanning app

You can use this quick start guide http://shyyko.wordpress.com/2013/07/30/zxing-with-android-quick-start/ with simple example project to build android app without IntentIntegrator.

How do you extract IP addresses from files using a regex in a linux shell?

Most of the examples here will match on 999.999.999.999 which is not technically a valid IP address.

The following will match on only valid IP addresses (including network and broadcast addresses).

grep -E -o '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' file.txt

Omit the -o if you want to see the entire line that matched.

What is the !! (not not) operator in JavaScript?

To cast your JavaScript variables to boolean,

var firstname = "test";
//type of firstname is string
var firstNameNotEmpty = !!firstname;
//type of firstNameNotEmpty is boolean

javascript false for "",0,undefined and null

javascript is true for number other then zero,not empty strings,{},[] and new Date() so,

!!("test") /*is true*/
!!("") /*is false*/

Python creating a dictionary of lists

easy way is:

a = [1,2]
d = {}
for i in a:
  d[i]=[i, ]

print(d)
{'1': [1, ], '2':[2, ]}

Spark - load CSV file as DataFrame?

Try this if using spark 2.0+

For non-hdfs file:
df = spark.read.csv("file:///csvfile.csv")


For hdfs file:
df = spark.read.csv("hdfs:///csvfile.csv")

For hdfs file (with different delimiter than comma:
df = spark.read.option("delimiter","|")csv("hdfs:///csvfile.csv")

Note:- this work for any delimited file. Just use option(“delimiter”,) to change value.

Hope this is helpful.

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

How can I generate UUID in C#

Be careful: while the string representations for .NET Guid and (RFC4122) UUID are identical, the storage format is not. .NET trades in little-endian bytes for the first three Guid parts.

If you are transmitting the bytes (for example, as base64), you can't just use Guid.ToByteArray() and encode it. You'll need to Array.Reverse the first three parts (Data1-3).

I do it this way:

var rfc4122bytes = Convert.FromBase64String("aguidthatIgotonthewire==");
Array.Reverse(rfc4122bytes,0,4);
Array.Reverse(rfc4122bytes,4,2);
Array.Reverse(rfc4122bytes,6,2);
var guid = new Guid(rfc4122bytes);

See this answer for the specific .NET implementation details.

Edit: Thanks to Jeff Walker, Code Ranger, for pointing out that the internals are not relevant to the format of the byte array that goes in and out of the byte-array constructor and ToByteArray().

Laravel migration default value

Might be a little too late to the party, but hope this helps someone with similar issue.

The reason why your default value doesnt't work is because the migration file sets up the default value in your database (MySQL or PostgreSQL or whatever), and not in your Laravel application.

Let me illustrate with an example.

This line means Laravel is generating a new Book instance, as specified in your model. The new Book object will have properties according to the table associated with the model. Up until this point, nothing is written on the database.

$book = new Book();

Now the following lines are setting up the values of each property of the Book object. Same still, nothing is written on the database yet.

$book->author = 'Test'
$book->title = 'Test'

This line is the one writing to the database. After passing on the object to the database, then the empty fields will be filled by the database (may be default value, may be null, or whatever you specify on your migration file).

$book->save();

And thus, the default value will not pop up before you save it to the database.

But, that is not enough. If you try to access $book->price, it will still be null (or 0, i'm not sure). Saving it is only adding the defaults to the record in the database, and it won't affect the Object you are carrying around.

So, to get the instance with filled-in default values, you have to re-fetch the instance. You may use the

Book::find($book->id);

Or, a more sophisticated way by refreshing the instance

$book->refresh();

And then, the next time you try to access the object, it will be filled with the default values.

How to edit a text file in my terminal

Open the file again using vi. and then press " i " or press insert key ,

For save and quit

  Enter Esc    

and write the following command

  :wq

without save and quit

  :q!

How to reference Microsoft.Office.Interop.Excel dll?

Use NuGet (VS 2013+):

The easiest way in any recent version of Visual Studio is to just use the NuGet package manager. (Even VS2013, with the NuGet Package Manager for Visual Studio 2013 extension.)

Right-click on "References" and choose "Manage NuGet Packages...", then just search for Excel.

enter image description here


VS 2012:

Older versions of VS didn't have access to NuGet.

  • Right-click on "References" and select "Add Reference".
  • Select "Extensions" on the left.
  • Look for Microsoft.Office.Interop.Excel.
    (Note that you can just type "excel" into the search box in the upper-right corner.)

VS2012/2013 References


VS 2008 / 2010:

  • Right-click on "References" and select "Add Reference".
  • Select the ".NET" tab.
  • Look for Microsoft.Office.Interop.Excel.

VS 2010 References

JavaScript code for getting the selected value from a combo box

I use this

var e = document.getElementById('ticket_category_clone').value;

Notice that you don't need the '#' character in javascript.

    function check () {

    var str = document.getElementById('ticket_category_clone').value;

      if (str==="Hardware")
      {
        SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
      }

    }

SPICEWORKS.app.helpdesk.ready(check);?

Connect Device to Mac localhost Server?

Always use the IP that is shown in your Network settings. It changes when you change location and you use another wireless connection.

For example in my case now it is: 10.0.0.5

How to deep merge instead of shallow merge?

Here is another ES2015 solution, works with objects and arrays.

_x000D_
_x000D_
function deepMerge(...sources) {
  let acc = {}
  for (const source of sources) {
    if (source instanceof Array) {
      if (!(acc instanceof Array)) {
        acc = []
      }
      acc = [...acc, ...source]
    } else if (source instanceof Object) {
      for (let [key, value] of Object.entries(source)) {
        if (value instanceof Object && key in acc) {
          value = deepMerge(acc[key], value)
        }
        acc = { ...acc, [key]: value }
      }
    }
  }
  return acc
}

// Test:

const A = {
 a: [null, {a:undefined}, [null,new Date()], {a(){}}],
 b: [1,2],
 c: {a:1, b:2}
}

const B = {
 a: ["new", 9],
 b: [new Date()],
 c: {a:{}, c:[]}
}

console.log(
  deepMerge(A,B)
)
_x000D_
_x000D_
_x000D_

X-Frame-Options on apache

What did it for me was the following, I've added the following directive in both the http <VirtualHost *:80> and https <VirtualHost *:443> virtual host blocks:

ServerName your-app.com
ServerAlias www.your-app.com

Header always unset X-Frame-Options
Header set X-Frame-Options "SAMEORIGIN"

The reasoning behind this? Well by default if set, the server does not reset the X-Frame-Options header so we need to first always remove the default value, in my case it was DENY, and then with the next rule we set it to the desired value, in my case SAMEORIGIN. Of course you can use the Header set X-Frame-Options ALLOW-FROM ... rule as well.

How to cast Object to boolean?

If the object is actually a Boolean instance, then just cast it:

boolean di = (Boolean) someObject;

The explicit cast will do the conversion to Boolean, and then there's the auto-unboxing to the primitive value. Or you can do that explicitly:

boolean di = ((Boolean) someObject).booleanValue();

If someObject doesn't refer to a Boolean value though, what do you want the code to do?

Setting onSubmit in React.js

You can pass the event as argument to the function and then prevent the default behaviour.

var OnSubmitTest = React.createClass({
        render: function() {
        doSomething = function(event){
           event.preventDefault();
           alert('it works!');
        }

        return <form onSubmit={this.doSomething}>
        <button>Click me</button>
        </form>;
    }
});

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

pandas.isnull() (also pd.isna(), in newer versions) checks for missing values in both numeric and string/object arrays. From the documentation, it checks for:

NaN in numeric arrays, None/NaN in object arrays

Quick example:

import pandas as pd
import numpy as np
s = pd.Series(['apple', np.nan, 'banana'])
pd.isnull(s)
Out[9]: 
0    False
1     True
2    False
dtype: bool

The idea of using numpy.nan to represent missing values is something that pandas introduced, which is why pandas has the tools to deal with it.

Datetimes too (if you use pd.NaT you won't need to specify the dtype)

In [24]: s = Series([Timestamp('20130101'),np.nan,Timestamp('20130102 9:30')],dtype='M8[ns]')

In [25]: s
Out[25]: 
0   2013-01-01 00:00:00
1                   NaT
2   2013-01-02 09:30:00
dtype: datetime64[ns]``

In [26]: pd.isnull(s)
Out[26]: 
0    False
1     True
2    False
dtype: bool

How to write text in ipython notebook?

Change the cell type to Markdown in the menu bar, from Code to Markdown. Currently in Notebook 4.x, the keyboard shortcut for such an action is: Esc (for command mode), then m (for markdown).

Getting The ASCII Value of a character in a C# string

Here's an alternative since you don't like the cast to int:

foreach(byte b in System.Text.Encoding.UTF8.GetBytes(str.ToCharArray()))
    Console.Write(b.ToString());

Manually install Gradle and use it in Android Studio

1.Install gardle as per the given link http://services.gradle.org/distributions/ 2.Extract this downloaded file in C:\Gradle\gradle-4.5 location 3.set the environment of gradle This PC\properties\advance system settings\Environment variable 4.let's start Android studio And set the path of gradle C:\Gradle\gradle In Android studio

Getting only response header from HTTP POST using curl

While the other answers have not worked for me in all situations, the best solution I could find (working with POST as well), taken from here:

curl -vs 'https://some-site.com' 1> /dev/null

Remove last commit from remote git repository

If nobody has pulled it, you can probably do something like

git push remote +branch^1:remotebranch

which will forcibly update the remote branch to the last but one commit of your branch.

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

Spring Boot + JPA : Column name annotation ignored

For hibernate5 I solved this issue by puting next lines in my application.properties file:

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

How to run multiple DOS commands in parallel?

You can execute commands in parallel with start like this:

start "" ping myserver
start "" nslookup myserver
start "" morecommands

They will each start in their own command prompt and allow you to run multiple commands at the same time from one batch file.

Hope this helps!

How to make fixed header table inside scrollable div?

I needed the same and this solution worked the most simple and straightforward way:

http://www.farinspace.com/jquery-scrollable-table-plugin/

I just give an id to the table I want to scroll and put one line in Javascript. That's it!

By the way, first I also thought I want to use a scrollable div, but it is not necessary at all. You can use a div and put it into it, but this solution does just what we need: scrolls the table.

Export Postgresql table data using pgAdmin

  1. Right-click on your table and pick option Backup..
  2. On File Options, set Filepath/Filename and pick PLAIN for Format
  3. Ignore Dump Options #1 tab
  4. In Dump Options #2 tab, check USE INSERT COMMANDS
  5. In Dump Options #2 tab, check Use Column Inserts if you want column names in your inserts.
  6. Hit Backup button

Rename a file in C#

Use:

public static class FileInfoExtensions
{
    /// <summary>
    /// Behavior when a new filename exists.
    /// </summary>
    public enum FileExistBehavior
    {
        /// <summary>
        /// None: throw IOException "The destination file already exists."
        /// </summary>
        None = 0,
        /// <summary>
        /// Replace: replace the file in the destination.
        /// </summary>
        Replace = 1,
        /// <summary>
        /// Skip: skip this file.
        /// </summary>
        Skip = 2,
        /// <summary>
        /// Rename: rename the file (like a window behavior)
        /// </summary>
        Rename = 3
    }


    /// <summary>
    /// Rename the file.
    /// </summary>
    /// <param name="fileInfo">the target file.</param>
    /// <param name="newFileName">new filename with extension.</param>
    /// <param name="fileExistBehavior">behavior when new filename is exist.</param>
    public static void Rename(this System.IO.FileInfo fileInfo, string newFileName, FileExistBehavior fileExistBehavior = FileExistBehavior.None)
    {
        string newFileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(newFileName);
        string newFileNameExtension = System.IO.Path.GetExtension(newFileName);
        string newFilePath = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileName);

        if (System.IO.File.Exists(newFilePath))
        {
            switch (fileExistBehavior)
            {
                case FileExistBehavior.None:
                    throw new System.IO.IOException("The destination file already exists.");

                case FileExistBehavior.Replace:
                    System.IO.File.Delete(newFilePath);
                    break;

                case FileExistBehavior.Rename:
                    int dupplicate_count = 0;
                    string newFileNameWithDupplicateIndex;
                    string newFilePathWithDupplicateIndex;
                    do
                    {
                        dupplicate_count++;
                        newFileNameWithDupplicateIndex = newFileNameWithoutExtension + " (" + dupplicate_count + ")" + newFileNameExtension;
                        newFilePathWithDupplicateIndex = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileNameWithDupplicateIndex);
                    }
                    while (System.IO.File.Exists(newFilePathWithDupplicateIndex));

                    newFilePath = newFilePathWithDupplicateIndex;
                    break;

                case FileExistBehavior.Skip:
                    return;
            }
        }
        System.IO.File.Move(fileInfo.FullName, newFilePath);
    }
}

How to use this code

class Program
{
    static void Main(string[] args)
    {
        string targetFile = System.IO.Path.Combine(@"D://test", "New Text Document.txt");
        string newFileName = "Foo.txt";

        // Full pattern
        System.IO.FileInfo fileInfo = new System.IO.FileInfo(targetFile);
        fileInfo.Rename(newFileName);

        // Or short form
        new System.IO.FileInfo(targetFile).Rename(newFileName);
    }
}

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

A solution is possible only because of the difference between 1 megabyte and 1 million bytes. There are about 2 to the power 8093729.5 different ways to choose 1 million 8-digit numbers with duplicates allowed and order unimportant, so a machine with only 1 million bytes of RAM doesn't have enough states to represent all the possibilities. But 1M (less 2k for TCP/IP) is 1022*1024*8 = 8372224 bits, so a solution is possible.

Part 1, initial solution

This approach needs a little more than 1M, I'll refine it to fit into 1M later.

I'll store a compact sorted list of numbers in the range 0 to 99999999 as a sequence of sublists of 7-bit numbers. The first sublist holds numbers from 0 to 127, the second sublist holds numbers from 128 to 255, etc. 100000000/128 is exactly 781250, so 781250 such sublists will be needed.

Each sublist consists of a 2-bit sublist header followed by a sublist body. The sublist body takes up 7 bits per sublist entry. The sublists are all concatenated together, and the format makes it possible to tell where one sublist ends and the next begins. The total storage required for a fully populated list is 2*781250 + 7*1000000 = 8562500 bits, which is about 1.021 M-bytes.

The 4 possible sublist header values are:

00 Empty sublist, nothing follows.

01 Singleton, there is only one entry in the sublist and and next 7 bits hold it.

10 The sublist holds at least 2 distinct numbers. The entries are stored in non-decreasing order, except that the last entry is less than or equal to the first. This allows the end of the sublist to be identified. For example, the numbers 2,4,6 would be stored as (4,6,2). The numbers 2,2,3,4,4 would be stored as (2,3,4,4,2).

11 The sublist holds 2 or more repetitions of a single number. The next 7 bits give the number. Then come zero or more 7-bit entries with the value 1, followed by a 7-bit entry with the value 0. The length of the sublist body dictates the number of repetitions. For example, the numbers 12,12 would be stored as (12,0), the numbers 12,12,12 would be stored as (12,1,0), 12,12,12,12 would be (12,1,1,0) and so on.

I start off with an empty list, read a bunch of numbers in and store them as 32 bit integers, sort the new numbers in place (using heapsort, probably) and then merge them into a new compact sorted list. Repeat until there are no more numbers to read, then walk the compact list once more to generate the output.

The line below represents memory just before the start of the list merge operation. The "O"s are the region that hold the sorted 32-bit integers. The "X"s are the region that hold the old compact list. The "=" signs are the expansion room for the compact list, 7 bits for each integer in the "O"s. The "Z"s are other random overhead.

ZZZOOOOOOOOOOOOOOOOOOOOOOOOOO==========XXXXXXXXXXXXXXXXXXXXXXXXXX

The merge routine starts reading at the leftmost "O" and at the leftmost "X", and starts writing at the leftmost "=". The write pointer doesn't catch the compact list read pointer until all of the new integers are merged, because both pointers advance 2 bits for each sublist and 7 bits for each entry in the old compact list, and there is enough extra room for the 7-bit entries for the new numbers.

Part 2, cramming it into 1M

To Squeeze the solution above into 1M, I need to make the compact list format a bit more compact. I'll get rid of one of the sublist types, so that there will be just 3 different possible sublist header values. Then I can use "00", "01" and "1" as the sublist header values and save a few bits. The sublist types are:

A Empty sublist, nothing follows.

B Singleton, there is only one entry in the sublist and and next 7 bits hold it.

C The sublist holds at least 2 distinct numbers. The entries are stored in non-decreasing order, except that the last entry is less than or equal to the first. This allows the end of the sublist to be identified. For example, the numbers 2,4,6 would be stored as (4,6,2). The numbers 2,2,3,4,4 would be stored as (2,3,4,4,2).

D The sublist consists of 2 or more repetitions of a single number.

My 3 sublist header values will be "A", "B" and "C", so I need a way to represent D-type sublists.

Suppose I have the C-type sublist header followed by 3 entries, such as "C[17][101][58]". This can't be part of a valid C-type sublist as described above, since the third entry is less than the second but more than the first. I can use this type of construct to represent a D-type sublist. In bit terms, anywhere I have "C{00?????}{1??????}{01?????}" is an impossible C-type sublist. I'll use this to represent a sublist consisting of 3 or more repetitions of a single number. The first two 7-bit words encode the number (the "N" bits below) and are followed by zero or more {0100001} words followed by a {0100000} word.

For example, 3 repetitions: "C{00NNNNN}{1NN0000}{0100000}", 4 repetitions: "C{00NNNNN}{1NN0000}{0100001}{0100000}", and so on.

That just leaves lists that hold exactly 2 repetitions of a single number. I'll represent those with another impossible C-type sublist pattern: "C{0??????}{11?????}{10?????}". There's plenty of room for the 7 bits of the number in the first 2 words, but this pattern is longer than the sublist that it represents, which makes things a bit more complex. The five question-marks at the end can be considered not part of the pattern, so I have: "C{0NNNNNN}{11N????}10" as my pattern, with the number to be repeated stored in the "N"s. That's 2 bits too long.

I'll have to borrow 2 bits and pay them back from the 4 unused bits in this pattern. When reading, on encountering "C{0NNNNNN}{11N00AB}10", output 2 instances of the number in the "N"s, overwrite the "10" at the end with bits A and B, and rewind the read pointer by 2 bits. Destructive reads are ok for this algorithm, since each compact list gets walked only once.

When writing a sublist of 2 repetitions of a single number, write "C{0NNNNNN}11N00" and set the borrowed bits counter to 2. At every write where the borrowed bits counter is non-zero, it is decremented for each bit written and "10" is written when the counter hits zero. So the next 2 bits written will go into slots A and B, and then the "10" will get dropped onto the end.

With 3 sublist header values represented by "00", "01" and "1", I can assign "1" to the most popular sublist type. I'll need a small table to map sublist header values to sublist types, and I'll need an occurrence counter for each sublist type so that I know what the best sublist header mapping is.

The worst case minimal representation of a fully populated compact list occurs when all the sublist types are equally popular. In that case I save 1 bit for every 3 sublist headers, so the list size is 2*781250 + 7*1000000 - 781250/3 = 8302083.3 bits. Rounding up to a 32 bit word boundary, thats 8302112 bits, or 1037764 bytes.

1M minus the 2k for TCP/IP state and buffers is 1022*1024 = 1046528 bytes, leaving me 8764 bytes to play with.

But what about the process of changing the sublist header mapping ? In the memory map below, "Z" is random overhead, "=" is free space, "X" is the compact list.

ZZZ=====XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Start reading at the leftmost "X" and start writing at the leftmost "=" and work right. When it's done the compact list will be a little shorter and it will be at the wrong end of memory:

ZZZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX=======

So then I'll need to shunt it to the right:

ZZZ=======XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

In the header mapping change process, up to 1/3 of the sublist headers will be changing from 1-bit to 2-bit. In the worst case these will all be at the head of the list, so I'll need at least 781250/3 bits of free storage before I start, which takes me back to the memory requirements of the previous version of the compact list :(

To get around that, I'll split the 781250 sublists into 10 sublist groups of 78125 sublists each. Each group has its own independent sublist header mapping. Using the letters A to J for the groups:

ZZZ=====AAAAAABBCCCCDDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ

Each sublist group shrinks or stays the same during a sublist header mapping change:

ZZZ=====AAAAAABBCCCCDDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAA=====BBCCCCDDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABB=====CCCCDDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCC======DDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDD======EEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDDEEE======FFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDDEEEFFF======GGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDDEEEFFFGGGGGGGGGG=======HHIJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDDEEEFFFGGGGGGGGGGHH=======IJJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDDEEEFFFGGGGGGGGGGHHI=======JJJJJJJJJJJJJJJJJJJJ
ZZZAAAAAABBCCCDDDDDEEEFFFGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ=======
ZZZ=======AAAAAABBCCCDDDDDEEEFFFGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ

The worst case temporary expansion of a sublist group during a mapping change is 78125/3 = 26042 bits, under 4k. If I allow 4k plus the 1037764 bytes for a fully populated compact list, that leaves me 8764 - 4096 = 4668 bytes for the "Z"s in the memory map.

That should be plenty for the 10 sublist header mapping tables, 30 sublist header occurrence counts and the other few counters, pointers and small buffers I'll need, and space I've used without noticing, like stack space for function call return addresses and local variables.

Part 3, how long would it take to run?

With an empty compact list the 1-bit list header will be used for an empty sublist, and the starting size of the list will be 781250 bits. In the worst case the list grows 8 bits for each number added, so 32 + 8 = 40 bits of free space are needed for each of the 32-bit numbers to be placed at the top of the list buffer and then sorted and merged. In the worst case, changing the sublist header mapping results in a space usage of 2*781250 + 7*entries - 781250/3 bits.

With a policy of changing the sublist header mapping after every fifth merge once there are at least 800000 numbers in the list, a worst case run would involve a total of about 30M of compact list reading and writing activity.

Source:

http://nick.cleaton.net/ramsortsol.html

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I know it's a relative old post but, I would like to share what worked for me: I've simply input "http://" before "localhost" in the url. Hope it helps somebody.

How can I put an icon inside a TextInput in React Native?

Here you have an example I took from my own project, i have just removed what i thought we didnt need for the example.

import React, { Component } from 'react';
import {
  Text,
  TouchableOpacity,
  View,
  StyleSheet,
  Dimensions,
  Image
} from 'react-native';

class YourComponent extends Component {
  constructor(props) {
    super(props);

    this._makeYourEffectHere = this._makeYourEffectHere.bind(this);

    this.state = {
        showPassword: false,
        image: '../statics/showingPassImage.png'
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity style={styles.button} onPress={this._makeYourEffectHere}>
          <Text>button</Text>
          <Image style={styles.image} source={require(this.state.image)}></Image>
        </TouchableOpacity>
        <TextInput password={this.state.showPassword} style={styles.input} value="abc" />
      </View>
    );
  }

  _makeYourEffectHere() {
    var png = this.state.showPassword ? '../statics/showingPassImage.png' : '../statics/hidingPassImage.png';
    this.setState({showPassword: !this.state.showPassword, image: png});
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    justifyContent: 'center',
    flexDirection: 'column',
    alignItems: 'center',
  },
  button: {
    width: Dimensions.get('window').width * 0.94,
    height: 40,
    backgroundColor: '#3b5998',
    marginTop: Dimensions.get('window').width * 0.03,
    justifyContent: 'center',
    borderRadius: Dimensions.get('window').width * 0.012
  },
  image: {
    width: 25,
    height: 25,
    position: 'absolute',
    left: 7,
    bottom: 7
  },
  input: {
    width: Dimensions.get('window').width * 0.94,
    height: 30
  }
});

module.exports = YourComponent;

I hope It helps you.

Let me know if it was useful.

How to ensure that there is a delay before a service is started in systemd?

The systemd way to do this is to have the process "talk back" when it's setup somehow, like by opening a socket or sending a notification (or a parent script exiting). Which is of course not always straight-forward especially with third party stuff :|

You might be able to do something inline like

ExecStart=/bin/bash -c '/bin/start_cassandra &; do_bash_loop_waiting_for_it_to_come_up_here'

or a script that does the same. Or put do_bash_loop_waiting_for_it_to_come_up_here in an ExecStartPost

Or create a helper .service that waits for it to come up, so the helper service depends on cassandra, and waits for it to come up, then your other process can depend on the helper service.

(May want to increase TimeoutStartSec from the default 90s as well)

ORACLE and TRIGGERS (inserted, updated, deleted)

From Using Triggers:

Detecting the DML Operation That Fired a Trigger

If more than one type of DML operation can fire a trigger (for example, ON INSERT OR DELETE OR UPDATE OF Emp_tab), the trigger body can use the conditional predicates INSERTING, DELETING, and UPDATING to check which type of statement fire the trigger.

So

IF DELETING THEN ... END IF;

should work for your case.

Javascript how to parse JSON array

Javascript has a built in JSON parse for strings, which I think is what you have:

var myObject = JSON.parse("my json string");

to use this with your example would be:

var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
    var counter = jsonData.counters[i];
    console.log(counter.counter_name);
}

Here is a working example

EDIT: There is a mistake in your use of for loop (I missed this on my first read, credit to @Evert for the spot). using a for-in loop will set the var to be the property name of the current loop, not the actual data. See my updated loop above for correct usage

IMPORTANT: the JSON.parse method wont work in old old browsers - so if you plan to make your website available through some sort of time bending internet connection, this could be a problem! If you really are interested though, here is a support chart (which ticks all my boxes).

What's the difference between lists and tuples?

Just a quick extension to list vs tuple responses:

  • Due to dynamic nature, list allocates more bit buckets than the actual memory required. This is done to prevent costly reallocation operation in case extra items are appended in the future.

  • On the other hand, being static, lightweight tuple object does not reserve extra memory required to store them.

What does "control reaches end of non-void function" mean?

Make sure that your code is returning a value of given return-type irrespective of conditional statements

This code snippet was showing the same error

int search(char arr[], int start, int end, char value)
{
    int i;
    for(i=start; i<=end; i++)
    {
        if(arr[i] == value)
            return i;
    }
}

This is the working code after little changes

int search(char arr[], int start, int end, char value)
{
    int i;
    int index=-1;
    for(i=start; i<=end; i++)
    {
        if(arr[i] == value)
            index=i;
    }
    return index;
}

CSS background image in :after element

A couple things

(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.

(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:

.button:after {
    content: "";
    width: 30px;
    height: 30px;
    background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
    top: 10px;
    right: 5px;
    position: absolute;
    display: inline-block;
}

I updated your jsFiddle to this and it showed the image.

Powershell script to check if service is started, if not then start it

Given $arrService = Get-Service -Name $ServiceName, $arrService.Status is a static property, corresponding to the value at the time of the call. Use $arrService.Refresh() when needed to renew the properties to current values.

MSDN ~ ServiceController.Refresh()

Refreshes property values by resetting the properties to their current values.

How to install mcrypt extension in xampp

The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.

Concatenating elements in an array to a string

Simple answer:

Arrays.toString(arr);

How to reduce the image size without losing quality in PHP

well I think I have something interesting for you... https://github.com/whizzzkid/phpimageresize. I wrote it for the exact same purpose. Highly customizable, and does it in a great way.

Format certain floating dataframe columns into percentage in pandas

As suggested by @linqu you should not change your data for presentation. Since pandas 0.17.1, (conditional) formatting was made easier. Quoting the documentation:

You can apply conditional formatting, the visual styling of a DataFrame depending on the data within, by using the DataFrame.style property. This is a property that returns a pandas.Styler object, which has useful methods for formatting and displaying DataFrames.

For your example, that would be (the usual table will show up in Jupyter):

df.style.format({
    'var1': '{:,.2f}'.format,
    'var2': '{:,.2f}'.format,
    'var3': '{:,.2%}'.format,
})

How to find the operating system version using JavaScript?

var OSName = "Unknown";
if (window.navigator.userAgent.indexOf("Windows NT 10.0")!= -1) OSName="Windows 10";
if (window.navigator.userAgent.indexOf("Windows NT 6.3") != -1) OSName="Windows 8.1";
if (window.navigator.userAgent.indexOf("Windows NT 6.2") != -1) OSName="Windows 8";
if (window.navigator.userAgent.indexOf("Windows NT 6.1") != -1) OSName="Windows 7";
if (window.navigator.userAgent.indexOf("Windows NT 6.0") != -1) OSName="Windows Vista";
if (window.navigator.userAgent.indexOf("Windows NT 5.1") != -1) OSName="Windows XP";
if (window.navigator.userAgent.indexOf("Windows NT 5.0") != -1) OSName="Windows 2000";
if (window.navigator.userAgent.indexOf("Mac")            != -1) OSName="Mac/iOS";
if (window.navigator.userAgent.indexOf("X11")            != -1) OSName="UNIX";
if (window.navigator.userAgent.indexOf("Linux")          != -1) OSName="Linux";

"Port 4200 is already in use" when running the ng serve command

I am sharing this as the fowling two commands did not do the job on my mac:

sudo kill $(sudo lsof -t -i:4200)

sudo kill `sudo lsof -t -i:4200`

The following one did, but if you were using the integrated terminal in Visual Code, try to use your machine terminal and add the fowling command:

lsof -t -i tcp:4200 | xargs kill -9

Grant all on a specific schema in the db to a group role in PostgreSQL

My answer is similar to this one on ServerFault.com.

To Be Conservative

If you want to be more conservative than granting "all privileges", you might want to try something more like these.

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;

The use of public there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.

Access to the Schema

To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.

You will not notice this requirement when first using Postgres. By default every database has a first schema named public. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.

GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;

Excerpt from the Postgres doc:

For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.

For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.

Existing Objects Versus Future

These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.

php return 500 error but no error log

Another case which happened to me, is I did a CURL to some of my pages, and got internal server error and nothing was in the apache logs, even when I enabled all error reporting.

My problem was that in the CURL I set curl_setopt($CR, CURLOPT_FAILONERROR, true);

Which then didn't show me my error, though there was one, this happened because the error was on a framework level and not a PHP one, so it didn't appear in the logs.

Installing ADB on macOS

Note for zsh users: replace all references to ~/.bash_profile with ~/.zshrc.

Option 1 - Using Homebrew

This is the easiest way and will provide automatic updates.

  1. Install the homebrew package manager

     /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
    
  2. Install adb

     brew install android-platform-tools
    
  3. Start using adb

     adb devices
    

Option 2 - Manually (just the platform tools)

This is the easiest way to get a manual installation of ADB and Fastboot.

  1. Delete your old installation (optional)

     rm -rf ~/.android-sdk-macosx/
    
  2. Navigate to https://developer.android.com/studio/releases/platform-tools.html and click on the SDK Platform-Tools for Mac link.

  3. Go to your Downloads folder

     cd ~/Downloads/
    
  4. Unzip the tools you downloaded

     unzip platform-tools-latest*.zip 
    
  5. Move them somewhere you won't accidentally delete them

     mkdir ~/.android-sdk-macosx
     mv platform-tools/ ~/.android-sdk-macosx/platform-tools
    
  6. Add platform-tools to your path

     echo 'export PATH=$PATH:~/.android-sdk-macosx/platform-tools/' >> ~/.bash_profile
    
  7. Refresh your bash profile (or restart your terminal app)

     source ~/.bash_profile
    
  8. Start using adb

     adb devices
    

Option 3 - Manually (with SDK Manager)

  1. Delete your old installation (optional)

     rm -rf ~/.android-sdk-macosx/
    
  2. Download the Mac SDK Tools from the Android developer site under "Get just the command line tools". Make sure you save them to your Downloads folder.

  3. Go to your Downloads folder

     cd ~/Downloads/
    
  4. Unzip the tools you downloaded

     unzip tools_r*-macosx.zip 
    
  5. Move them somewhere you won't accidentally delete them

     mkdir ~/.android-sdk-macosx
     mv tools/ ~/.android-sdk-macosx/tools
    
  6. Run the SDK Manager

     sh ~/.android-sdk-macosx/tools/android
    
  7. Uncheck everything but Android SDK Platform-tools (optional)

enter image description here

  1. Click Install Packages, accept licenses, click Install. Close the SDK Manager window.

enter image description here

  1. Add platform-tools to your path

     echo 'export PATH=$PATH:~/.android-sdk-macosx/platform-tools/' >> ~/.bash_profile
    
  2. Refresh your bash profile (or restart your terminal app)

    source ~/.bash_profile
    
  3. Start using adb

    adb devices
    

Update my gradle dependencies in eclipse

You have to select "Refresh Dependencies" in the "Gradle" context menu that appears when you right-click the project in the Package Explorer.

AngularJS: Service vs provider vs factory

Let's discuss the three ways of handling business logic in AngularJS in a simple way: (Inspired by Yaakov's Coursera AngularJS course)

SERVICE:

Syntax:

app.js

 var app = angular.module('ServiceExample',[]);
 var serviceExampleController =
              app.controller('ServiceExampleController', ServiceExampleController);
 var serviceExample = app.service('NameOfTheService', NameOfTheService);

 ServiceExampleController.$inject = ['NameOfTheService'] //protects from minification of js files

function ServiceExampleController(NameOfTheService){
     serviceExampleController = this;
     serviceExampleController.data = NameOfTheService.getSomeData();
 }

function NameOfTheService(){
     nameOfTheService = this;
     nameOfTheService.data = "Some Data";
     nameOfTheService.getSomeData = function(){
           return nameOfTheService.data;
     }     
}

index.html

<div ng-controller = "ServiceExampleController as serviceExample">
   {{serviceExample.data}}
</div>

Features of Service:

  1. Lazily Instantiated: If it is not injected it won't be instantiated ever. So to use it will have to inject it to a module.
  2. Singleton: If injected to multiple modules, all will have access to only one particular instance. That is why very convenient to share data across different controllers.

FACTORY

First let's have a look at the syntax:

app.js:

var app = angular.module('FactoryExample',[]);
var factoryController = app.controller('FactoryController', FactoryController);
var factoryExampleOne = app.factory('NameOfTheFactoryOne', NameOfTheFactoryOne);
var factoryExampleTwo = app.factory('NameOfTheFactoryTwo', NameOfTheFactoryTwo);

//first implementation where it returns a function
function NameOfTheFactoryOne(){
   var factory = function(){
      return new SomeService();
    }
   return factory;
}

//second implementation where an object literal would be returned
function NameOfTheFactoryTwo(){
   var factory = {
      getSomeService : function(){
          return new SomeService();
       }
    };
   return factory;
}

Now using the above two in the controller:

 var factoryOne = NameOfTheFactoryOne() //since it returns a function
 factoryOne.someMethod();

 var factoryTwo = NameOfTheFactoryTwo.getSomeService(); //accessing the object
 factoryTwo.someMethod();

Features of Factory:

  1. Follows the factory design pattern. The factory is a central place that produces new objects or functions.
  2. Not only produces singleton, but customizable services.
  3. The .service() method is a factory that always produces the same type of service, which is a singleton, and without any easy way to configure it's behavior. That .service() method is usually used as a shortcut for something that doesn't require any configuration whatsoever.

PROVIDER

Let's again have a look at the Syntax first:

angular.module('ProviderModule', [])
.controller('ProviderModuleController', ProviderModuleController)
.provider('ServiceProvider', ServiceProvider)
.config(Config); //optional

Config.$inject = ['ServiceProvider'];
function Config(ServiceProvider) {
  ServiceProvider.defaults.maxItems = 10; //some default value
}


ProviderModuleController.$inject = ['ServiceProvider'];
function ProviderModuleController(ServiceProvider) {
  //some methods
}

function ServiceProvider() {
  var provider = this;

  provider.defaults = {
    maxItems: 10
  };

  provider.$get = function () {
    var someList = new someListService(provider.defaults.maxItems);

    return someList;
  };
}

}

Features of Provider:

  1. Provider is the most flexible method of creating services in Angular.
  2. Not only we can create a factory that's dynamically configurable, but at the time of using the factory, with the provider method, we could custom configure the factory just once at the bootstrapping of our entire application.
  3. The factory can then be used throughout the application with custom settings. In other words, we can configure this factory before the application starts. In fact in the angular documentation it is mentioned that the provider method is what actually gets executed behind the scenes when we configure our services with either .service or .factory methods.
  4. The $get is a function that is directly attached to the provider instance. That function is a factory function. In other words, it's just like the one that we use to provide to the .factory method. In that function, we create our own service. This $get property, that's a function, is what makes the provider a provider. AngularJS expects the provider to have a $get property whose value is a function that Angular will treat as a factory function. But what makes this whole provider setup very special, is the fact that we can provide some config object inside the service provider, and that usually comes with defaults that we can later overwrite in the step, where we can configure the entire application.

How to calculate mean, median, mode and range from a set of numbers

If you only care about unimodal distributions, consider sth. like this.

public static Optional<Integer> mode(Stream<Integer> stream) {
    Map<Integer, Long> frequencies = stream
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    return frequencies.entrySet().stream()
        .max(Comparator.comparingLong(Map.Entry::getValue))
        .map(Map.Entry::getKey);
}

Suppress output of a function

R only automatically prints the output of unassigned expressions, so just assign the result of the apply to a variable, and it won't get printed.

Adding timestamp to a filename with mv in BASH

You can write your scripts in notepad but just make sure you convert them using this -> $ sed -i 's/\r$//' yourscripthere

I use it all they time when I'm working in cygwin and it works. Hope this helps

What's the difference between xsd:include and xsd:import?

Another difference is that <import> allows importing by referring to another namespace. <include> only allows importing by referring to a URI of intended include schema. That is definitely another difference than inter-intra namespace importing.

For example, the xml schema validator may already know the locations of all schemas by namespace already. Especially considering that referring to XML namespaces by URI may be problematic on different systems where classpath:// means nothing, or where http:// isn't allowed, or where some URI doesn't point to the same thing as it does on another system.

Code sample of valid and invalid imports and includes:

Valid:

<xsd:import namespace="some/name/space"/>
<xsd:import schemaLocation="classpath://mine.xsd"/>

<xsd:include schemaLocation="classpath://mine.xsd"/>

Invalid:

<xsd:include namespace="some/name/space"/>

How to remove youtube branding after embedding video in web page?

If, like me, you would just prefer people didn't click out to youtube using the logo, one option is to use a player like jwplayer. Using jwplayer the logo is still there just unclickable.

How to Install Sublime Text 3 using Homebrew

As per latest updates, caskroom packages have moved to homebrew. So try following commands:

brew tap homebrew/cask
brew cask install sublime-text

These 2 terminal commands will be enough for installing sublime.

How to Delete a directory from Hadoop cluster which is having comma(,) in its name?

Run the command in the terminal

$hadoop fs -rm -r /path/to/directory

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

bootstrap multiselect get selected values

the solution what I found to work in my case

$('#multiselect1').multiselect({
    selectAllValue: 'multiselect-all',
    enableCaseInsensitiveFiltering: true,
    enableFiltering: true,
    maxHeight: '300',
    buttonWidth: '235',
    onChange: function(element, checked) {
        var brands = $('#multiselect1 option:selected');
        var selected = [];
        $(brands).each(function(index, brand){
            selected.push([$(this).val()]);
        });

        console.log(selected);
    }
}); 

How do DATETIME values work in SQLite?

SQlite does not have a specific datetime type. You can use TEXT, REAL or INTEGER types, whichever suits your needs.

Straight from the DOCS

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

  • TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
  • REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
  • INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.

Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.

SQLite built-in Date and Time functions can be found here.

Add 2 hours to current time in MySQL?

The DATE_ADD() function will do the trick. (You can also use the ADDTIME() function if you're running at least v4.1.1.)

For your query, this would be:

SELECT * 
FROM courses 
WHERE DATE_ADD(now(), INTERVAL 2 HOUR) > start_time

Or,

SELECT * 
FROM courses 
WHERE ADDTIME(now(), '02:00:00') > start_time

Using grep to search for hex strings in a file

There's also a pretty handy tool called binwalk, written in python, which provides for binary pattern matching (and quite a lot more besides). Here's how you would search for a binary string, which outputs the offset in decimal and hex (from the docs):

$ binwalk -R "\x00\x01\x02\x03\x04" firmware.bin
DECIMAL     HEX         DESCRIPTION
--------------------------------------------------------------------------
377654      0x5C336     Raw string signature

JSP : JSTL's <c:out> tag

As said Will Wagner, in old version of jsp you should always use c:out to output dynamic text.

Moreover, using this syntax:

<c:out value="${person.name}">No name</c:out>

you can display the text "No name" when name is null.

Where to find htdocs in XAMPP Mac

From XAMPP Application window (manager-osx) click => Open Application Folder >> htdocs

Now you opened your target folder.

You can see process by image below

XAMPP Application window (manager-osx)

Open Application Folder

Application (xamppfiles) folder opened

Click on 'htdocs'

Your target folder 'htdocs' opened

Now begin your development

What permission do I need to access Internet from an Android application?

Google removed the need to ask permission for the internet for the latest version. Still, to request for internet permission in your code you must add these to your AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET"/>

Multiple IF AND statements excel

Consider that you have multiple "tests", e.g.,

  1. If E2 = 'in play' and F2 = 'closed', output 3
  2. If E2 = 'in play' and F2 = 'suspended', output 2
  3. Etc.

What you really need to do is put successive tests in the False argument. You're presently trying to separate each test by a comma, and that won't work.

Your first three tests can all be joined in one expression like:

=IF(E2="In Play",IF(F2="Closed",3,IF(F2="suspended",2,IF(F2="Null",1))))

Remembering that each successive test needs to be the nested FALSE argument of the preceding test, you can do this:

=IF(E2="In Play",IF(F2="Closed",3,IF(F2="suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-Play",F2="Null"),-1,IF(AND(E2="completed",F2="closed"),2,IF(AND(E2="suspended",F2="Null"),3,-2))))

bootstrap 3 navbar collapse button not working

I had a similar problem. Looked over the html several times and was sure it was correct. Then I started playing around with the order of jquery and bootstrap javascript.

Originally I had bootstrap.min.js loading BEFORE jquery.min.js. In this state, the menu would not expand when clicking on the menu icon.

Then I changed the order so that bootstrap.min.js came after jquery.min.js, and this solved the problem. I don't know enough about javascript to explain why this caused the problem (or fixed it), but that is what worked for me.

Additional info:

Both scripts are located at the bottom of the page, just before the tag. Both scripts are hosted on CDNs, not locally hosted.

If you're pretty sure your code is correct, give this a try.

How to bundle an Angular app for production

2.0.1 Final using Gulp (TypeScript - Target: ES5)


OneTime Setup

  • npm install (run in cmd when direcory is projectFolder)

Bundling Steps

  • npm run bundle (run in cmd when direcory is projectFolder)

    bundles are generated to projectFolder / bundles /

Output

  • bundles/dependencies.bundle.js [ size: ~ 1 MB (as small as possible) ]
    • contains rxjs and angular dependencies, not the whole frameworks
  • bundles/app.bundle.js [ size: depends on your project, mine is ~ 0.5 MB ]
    • contains your project

File Structure

  • projectFolder / app / (all components, directives, templates, etc)
  • projectFolder / gulpfile.js

var gulp = require('gulp'),
  tsc = require('gulp-typescript'),
  Builder = require('systemjs-builder'),
  inlineNg2Template = require('gulp-inline-ng2-template');

gulp.task('bundle', ['bundle-app', 'bundle-dependencies'], function(){});

gulp.task('inline-templates', function () {
  return gulp.src('app/**/*.ts')
    .pipe(inlineNg2Template({ useRelativePaths: true, indent: 0, removeLineBreaks: true}))
    .pipe(tsc({
      "target": "ES5",
      "module": "system",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "removeComments": true,
      "noImplicitAny": false
    }))
    .pipe(gulp.dest('dist/app'));
});

gulp.task('bundle-app', ['inline-templates'], function() {
  // optional constructor options
  // sets the baseURL and loads the configuration file
  var builder = new Builder('', 'dist-systemjs.config.js');

  return builder
    .bundle('dist/app/**/* - [@angular/**/*.js] - [rxjs/**/*.js]', 'bundles/app.bundle.js', { minify: true})
    .then(function() {
      console.log('Build complete');
    })
    .catch(function(err) {
      console.log('Build error');
      console.log(err);
    });
});

gulp.task('bundle-dependencies', ['inline-templates'], function() {
  // optional constructor options
  // sets the baseURL and loads the configuration file
  var builder = new Builder('', 'dist-systemjs.config.js');

  return builder
    .bundle('dist/app/**/*.js - [dist/app/**/*.js]', 'bundles/dependencies.bundle.js', { minify: true})
    .then(function() {
      console.log('Build complete');
    })
    .catch(function(err) {
      console.log('Build error');
      console.log(err);
    });
});
  • projectFolder / package.json (same as Quickstart guide, just shown devDependencies and npm-scripts required to bundle)

{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    ***
     "gulp": "gulp",
     "rimraf": "rimraf",
     "bundle": "gulp bundle",
     "postbundle": "rimraf dist"
  },
  "license": "ISC",
  "dependencies": {
    ***
  },
  "devDependencies": {
    "rimraf": "^2.5.2",
    "gulp": "^3.9.1",
    "gulp-typescript": "2.13.6",
    "gulp-inline-ng2-template": "2.0.1",
    "systemjs-builder": "^0.15.16"
  }
}
  • projectFolder / systemjs.config.js (same as Quickstart guide, not available there anymore)

(function(global) {

  // map tells the System loader where to look for things
  var map = {
    'app':                        'app',
    'rxjs':                       'node_modules/rxjs',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    '@angular':                   'node_modules/@angular'
  };

  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'app/boot.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' }
  };

  var packageNames = [
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/forms',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    '@angular/router-deprecated',
    '@angular/testing',
    '@angular/upgrade',
  ];

  // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
  packageNames.forEach(function(pkgName) {
    packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
  });

  var config = {
    map: map,
    packages: packages
  };

  // filterSystemConfig - index.asp's chance to modify config before we register it.
  if (global.filterSystemConfig) { global.filterSystemConfig(config); }

  System.config(config);

})(this);
  • projetcFolder / dist-systemjs.config.js (just shown the difference with systemjs.config.json)

var map = {
    'app':                        'dist/app',
  };
  • projectFolder / index.html (production) - The order of the script tags is critical. Placing the dist-systemjs.config.js tag after the bundle tags would still allow the program to run but the dependency bundle would be ignored and dependencies would be loaded from the node_modules folder.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <base href="/"/>
  <title>Angular</title>
  <link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>

<my-app>
  loading...
</my-app>

<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>

<script src="node_modules/zone.js/dist/zone.min.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.js"></script>

<script src="dist-systemjs.config.js"></script>
<!-- Project Bundles. Note that these have to be loaded AFTER the systemjs.config script -->
<script src="bundles/dependencies.bundle.js"></script>
<script src="bundles/app.bundle.js"></script>

<script>
    System.import('app/boot').catch(function (err) {
      console.error(err);
    });
</script>
</body>
</html>
  • projectFolder / app / boot.ts is where the bootstrap is.

The best I could do yet :)

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

The argument to remove() is a filter document, so passing in an empty document means 'remove all':

db.user.remove({})

However, if you definitely want to remove everything you might be better off dropping the collection. Though that probably depends on whether you have user defined indexes on the collection i.e. whether the cost of preparing the collection after dropping it outweighs the longer duration of the remove() call vs the drop() call.

More details in the docs.

HTTP Content-Type Header and JSON

The Content-Type header is just used as info for your application. The browser doesn't care what it is. The browser just returns you the data from the AJAX call. If you want to parse it as JSON, you need to do that on your own.

The header is there so your app can detect what data was returned and how it should handle it. You need to look at the header, and if it's application/json then parse it as JSON.

This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-Type to detect what to do with it.

How to create the most compact mapping n ? isprime(n) up to a limit N?

Here's my take on the answer:

def isprime(num):
    return num <= 3 or (num + 1) % 6 == 0 or (num - 1) % 6 == 0

The function will return True if any of the properties below are True. Those properties mathematically define what a prime is.

  1. The number is less than or equal to 3
  2. The number + 1 is divisible by 6
  3. The number - 1 is divisible by 6

How to drop unique in MySQL?

This may help others

alter table fuinfo drop index fuinfo_email_unique

Can git undo a checkout of unstaged files

I just had that happen to me, I checked out an entire folder containing hours of work! Fortunately I found out that my IDE Netbeans keeps an history of each file, that allowed me to recuperate 99% of the stuff even though I needed to fix a few things manually.

Update MySQL using HTML Form and PHP

First of all use mysqli_connect($dbhost,$dbuser,$dbpass,$dbname)

Second - put mysqli_ everywhere instead of mysql_

Third - use this $sql = "UPDATE anstalld SET mandag = '.$mandag.', tisdag = '.$tisdag.', onsdag = '.$onsdag.', torsdag = '.$torsdag.', fredag = '.$fredag.' WHERE namn = '.$namn.'";
$retval = mysqli_query( $conn, $sql ); //execute your query

if Your data is being updated in your database but not in your table its because when you will click on update button, the request is made to the same file. It first selects the data from the database when it is not updated prints it in the table and then update it according to the flow. If you have to update it as you click on update button then put this section

<?php
if(isset($_POST['update']))
{

$namn = $_POST['namnid'];
$mandag = $_POST['mandagid'];
$tisdag = $_POST['tisdagid'];
$onsdag = $_POST['onsdagid'];
$torsdag = $_POST['torsdagid'];
$fredag = $_POST['fredagid'];

$sql = mysql_query("UPDATE anstalld SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn'");

$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";

}


?>`

after connecting with database.

Calculate difference between 2 date / times in Oracle SQL

$sql="select bsp_bp,user_name,status,
to_char(ins_date,'dd/mm/yyyy hh12:mi:ss AM'),
to_char(pickup_date,'dd/mm/yyyy hh12:mi:ss AM'),
trunc((pickup_date-ins_date)*24*60*60,2),message,status_message 
from valid_bsp_req where id >= '$id'"; 

SUM of grouped COUNT in SQL Query

Without specifying which rdbms you are using

Have a look at this demo

SQL Fiddle DEMO

SELECT Name, COUNT(1) as Cnt
FROM Table1
GROUP BY Name
UNION ALL
SELECT 'SUM' Name, COUNT(1)
FROM Table1

That said, I would recomend that the total be added by your presentation layer, and not by the database.

This is a bit more of a SQL SERVER Version using Summarizing Data Using ROLLUP

SQL Fiddle DEMO

SELECT CASE WHEN (GROUPING(NAME) = 1) THEN 'SUM'
            ELSE ISNULL(NAME, 'UNKNOWN')
       END Name, 
      COUNT(1) as Cnt
FROM Table1
GROUP BY NAME
WITH ROLLUP

"git checkout <commit id>" is changing branch to "no branch"

This worked best for me when I wanted to check out the code, given the commit ID <commit_id_SHA1>

git fetch origin <commit_id_SHA1>
git checkout -b new_branch FETCH_HEAD

Sound alarm when code finishes

I'm assuming you want the standard system bell, and don't want to concern yourself with frequencies and durations etc., you just want the standard windows bell.

import winsound
winsound.MessageBeep()

MySQL - sum column value(s) based on row from the same table

This might be seen as a little complex but does exactly what you want

SELECT 
  DISTINCT(p.`ProductID`) AS ProductID,
  SUM(pl.CashAmount) AS Cash,
  SUM(pr.CashAmount) AS `Check`,
  SUM(px.CashAmount) AS `Credit Card`,
  SUM(pl.CashAmount) + SUM(pr.CashAmount) +SUM(px.CashAmount) AS Amount
FROM
  `payments` AS p 
  LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Cash' GROUP BY ProductID , PaymentMethod ) AS pl 
    ON pl.`PaymentMethod` = p.`PaymentMethod` AND pl.ProductID = p.`ProductID`
  LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Check' GROUP BY ProductID , PaymentMethod) AS pr 
    ON pr.`PaymentMethod` = p.`PaymentMethod` AND pr.ProductID = p.`ProductID`
  LEFT JOIN (SELECT ProductID, PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Credit Card' GROUP BY ProductID , PaymentMethod) AS px 
    ON px.`PaymentMethod` = p.`PaymentMethod` AND px.ProductID = p.`ProductID`
GROUP BY p.`ProductID` ;

Output

ProductID | Cash | Check | Credit Card | Amount
-----------------------------------------------
    3     | 20   |  15   |   25        |  60
    4     | 5    |  6    |   7         |  18

SQL Fiddle Demo

Linux/Unix command to determine if process is running?

Just a minor addition: if you add the -c flag to ps, you don't need to remove the line containing the grep process with grep -v afterwards. I.e.

ps acux | grep cron

is all the typing you'll need on a bsd-ish system (this includes MacOSX) You can leave the -u away if you need less information.

On a system where the genetics of the native ps command point back to SysV, you'd use

ps -e |grep cron

or

ps -el |grep cron 

for a listing containing more than just pid and process name. Of course you could select the specific fields to print out using the -o <field,field,...> option.

Installing SciPy and NumPy using pip

Since the previous instructions for installing with yum are broken here are the updated instructions for installing on something like fedora. I've tested this on "Amazon Linux AMI 2016.03"

sudo yum install atlas-devel lapack-devel blas-devel libgfortran
pip install scipy

NotificationCompat.Builder deprecated in Android O

This constructor was deprecated in API level 26.1.0. use NotificationCompat.Builder(Context, String) instead. All posted Notifications must specify a NotificationChannel Id.

I would like to see a hash_map example in C++

hash_map is a non-standard extension. unordered_map is part of std::tr1, and will be moved into the std namespace for C++0x. http://en.wikipedia.org/wiki/Unordered_map_%28C%2B%2B%29

How can I upload fresh code at github?

In Linux use below command to upload code in git
1 ) git clone repository
ask for user name and password.
2) got to respositiory directory.
3) git add project name.
4) git commit -m ' messgage '.
5) git push origin master.
- user name ,password

Update new Change code into Github

->Goto Directory That your github up code
->git commit ProjectName -m 'Message'
->git push origin master.

python xlrd unsupported format, or corrupt file.

there's nothing wrong with your file. xlrd does not yet support xlsx (excel 2007+) files although it's purported to have supported this for some time.

Simplistix github

2-days ago they committed a pre-alpha version to their git which integrates xlsx support. Other forums suggest that you use a DOM parser for xlsx files since the xlsx file type is just a zip archive containing XML. I have not tried this. there is another package with similar functionality as xlrd and this is called openpyxl which you can get from easy_install or pip. I have not tried this either, however, its API is supposed to be similar to xlrd.

html5 - canvas element - Multiple layers

but layer 02, will cover all drawings in layer 01. I used this to show drawing in both layers. use (background-color: transparent;) in style.

_x000D_
_x000D_
    <div style="position: relative;"> _x000D_
      <canvas id="lay01" width="500" height="500" style="position: absolute; left: 0; top: 0; z-index: 0; background-color: transparent;">_x000D_
      </canvas> _x000D_
      <canvas id="lay02" width="500" height="500" style="position: absolute; left: 0; top: 0; z-index: 1; background-color: transparent;">_x000D_
      </canvas>_x000D_
</div>
_x000D_
_x000D_
_x000D_