Programs & Examples On #Limit choices to

Xcode 6.1 Missing required architecture X86_64 in file

If you are building a universal library and need to support the Simulator (x86_64) then build the framework for all platforms by setting Build Active Architecture Only to No. enter image description here

setOnItemClickListener on custom ListView

If in the listener you get the root layout of the item (say itemLayout), and you gave some id's to the textviews, you can then get them with something like itemLayout.findViewById(R.id.textView1).

What are the JavaScript KeyCodes?

One possible answer will be given when you run this snippet.

_x000D_
_x000D_
document.write('<table>')_x000D_
for (var i = 0; i < 250; i++) {_x000D_
  document.write('<tr><td>' + i + '</td><td>' + String.fromCharCode(i) + '</td></tr>')_x000D_
}_x000D_
document.write('</table>')
_x000D_
td {_x000D_
  border: solid 1px;_x000D_
  padding: 1px 12px;_x000D_
  text-align: right;_x000D_
}_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
* {_x000D_
  font-family: monospace;_x000D_
  font-size: 1.1em;_x000D_
}
_x000D_
_x000D_
_x000D_

How to link external javascript file onclick of button

You can load all your scripts in the head tag, and whatever your script is doing in function braces. But make sure you change the scope of the variables if you are using those variables outside the script.

Distinct by property of class with LINQ

You can use grouping, and get the first car from each group:

List<Car> distinct =
  cars
  .GroupBy(car => car.CarCode)
  .Select(g => g.First())
  .ToList();

Can I set up HTML/Email Templates with ASP.NET?

i had a similar requirement on 1 of the projects where you had to send huge number of emails each day, and the client wanted complete control over html templates for different types of emails.

due to the large number of emails to be sent, performance was a primary concern.

what we came up with was static content in sql server where you save entire html template mark up (along with place holders, like [UserFirstName], [UserLastName] which are replaced with real data at run time) for different types of emails

then we loaded this data in asp.net cache - so we dont read the html templates over and over again - but only when they are actually changed

we gave the client a WYSIWYG editor to modify these templates via a admin web form. whenever updates were made, we reset asp.net cache.

and then we had a seperate table for email logs - where every email to be sent was logged. this table had fields called emailType, emailSent and numberOfTries.

we simply ran a job every 5 minutes for important email types (like new member sign up, forgot password) which need to be sent asap

we ran another job every 15 minutes for less important email types (like promotion email, news email, etc)

this way you dont block your server sending non stop emails and you process mails in batch. once an email is sent you set the emailSent field to 1.

start/play embedded (iframe) youtube-video on click of an image

To start video

var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);

To stop video

var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);

You may want to replace "&autoplay=1" with "?autoplay=1" incase there are no additional parameters

works for both vimeo and youtube on FF & Chrome

Regular Expression Validation For Indian Phone Number and Mobile number

Use the following regex

^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$

This will support the following formats:

  1. 8880344456
  2. +918880344456
  3. +91 8880344456
  4. +91-8880344456
  5. 08880344456
  6. 918880344456

int *array = new int[n]; what is this function actually doing?

It allocates space on the heap equal to an integer array of size N, and returns a pointer to it, which is assigned to int* type pointer called "array"

How do I register a DLL file on Windows 7 64-bit?

If the DLL is 32 bit:

  1. Copy the DLL to C:\Windows\SysWoW64\
  2. In elevated cmd: %windir%\SysWoW64\regsvr32.exe %windir%\SysWoW64\namedll.dll

if the DLL is 64 bit:

  1. Copy the DLL to C:\Windows\System32\
  2. In elevated cmd: %windir%\System32\regsvr32.exe %windir%\System32\namedll.dll

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Make sure Anonymous access is enabled on IIS -> Authentication.

But also right click on it, then click on Edit, and choose a domain\username and password. (With access to the physical folder of the application).

Removing a model in rails (reverse of "rails g model Title...")

Here's a different implementation of Jenny Lang's answer that works for Rails 5.

First create the migration file:

bundle exec be rails g migration DropEpisodes

Then populate the migration file as follows:

class DropEpisodes < ActiveRecord::Migration[5.1]
  def change
    drop_table :episodes
  end
end

Running rails db:migrate will drop the table. If you run rails db:rollback, Rails will throw a ActiveRecord::IrreversibleMigration error.

Incompatible implicit declaration of built-in function ‘malloc’

The only solution for such warnings is to include stdlib.h in the program.

What's the difference between UTF-8 and UTF-8 without BOM?

UTF with a BOM is better if you use UTF-8 in HTML files and if you use Serbian Cyrillic, Serbian Latin, German, Hungarian or some exotic language on the same page.

That is my opinion (30 years of computing and IT industry).

Rails 3.1 and Image Assets

The asset pipeline in rails offers a method for this exact thing.

You simply add image_path('image filename') to your css or scss file and rails takes care of everything. For example:

.logo{ background:url(image_path('admin/logo.png'));

(note that it works just like in a .erb view, and you don't use "/assets" or "/assets/images" in the path)

Rails also offers other helper methods, and there's another answer here: How do I use reference images in Sass when using Rails 3.1?

How to replace all occurrences of a character in string?

The question is centered on character replacement, but, as I found this page very useful (especially Konrad's remark), I'd like to share this more generalized implementation, which allows to deal with substrings as well:

std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
    }
    return str;
}

Usage:

std::cout << ReplaceAll(string("Number Of Beans"), std::string(" "), std::string("_")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("X")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("h")) << std::endl;

Outputs:

Number_Of_Beans

XXjXugtXty

hhjhugthty


EDIT:

The above can be implemented in a more suitable way, in case performances are of your concern, by returning nothing (void) and performing the changes directly on the string str given as argument, passed by address instead of by value. This would avoid useless and costly copy of the original string, while returning the result. Your call, then...

Code :

static inline void ReplaceAll2(std::string &str, const std::string& from, const std::string& to)
{
    // Same inner code...
    // No return statement
}

Hope this will be helpful for some others...

How can I bind a background color in WPF/XAML?

The xaml code:

<Grid x:Name="Message2">
   <TextBlock Text="This one is manually orange."/>
</Grid>

The c# code:

protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        CreateNewColorBrush();
    }

    private void CreateNewColorBrush()
    {

        SolidColorBrush my_brush = new SolidColorBrush(Color.FromArgb(255, 255, 215, 0));
        Message2.Background = my_brush;

    }

This one works in windows 8 store app. Try and see. Good luck !

Convert datetime to valid JavaScript date

One can use the getmonth and getday methods to get only the date.

Here I attach my solution:

_x000D_
_x000D_
var fullDate = new Date(); console.log(fullDate);_x000D_
var twoDigitMonth = fullDate.getMonth() + "";_x000D_
if (twoDigitMonth.length == 1)_x000D_
    twoDigitMonth = "0" + twoDigitMonth;_x000D_
var twoDigitDate = fullDate.getDate() + "";_x000D_
if (twoDigitDate.length == 1)_x000D_
    twoDigitDate = "0" + twoDigitDate;_x000D_
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
_x000D_
_x000D_
_x000D_

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

in my case, this error is raised due to sequence was not created..

CREATE SEQUENCE  J.SOME_SEQ  MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER  NOCYCLE ;

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

Check this:

function dateToLocalISO(date) {
    const off    = date.getTimezoneOffset()
    const absoff = Math.abs(off)
    return (new Date(date.getTime() - off*60*1000).toISOString().substr(0,23) +
            (off > 0 ? '-' : '+') + 
            (absoff / 60).toFixed(0).padStart(2,'0') + ':' + 
            (absoff % 60).toString().padStart(2,'0'))
}

// Test it:
d = new Date()

dateToLocalISO(d)
// ==> '2019-06-21T16:07:22.181-03:00'

// Is similar to:

moment = require('moment')
moment(d).format('YYYY-MM-DDTHH:mm:ss.SSSZ') 
// ==> '2019-06-21T16:07:22.181-03:00'

How to concatenate a std::string and an int?

If you have C++11, you can use std::to_string.

Example:

std::string name = "John";
int age = 21;

name += std::to_string(age);

std::cout << name;

Output:

John21

Install specific version using laravel installer

Via composer installing specific version 7.*

composer create-project --prefer-dist laravel/laravel:^7.0 project_name

To install specific version 6.* and below use the following command:

composer create-project --prefer-dist laravel/laravel project_name "6.*"

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

Get local href value from anchor (a) tag

The href property sets or returns the value of the href attribute of a link.

  var hello = domains[i].getElementsByTagName('a')[0].getAttribute('href');
    var url="https://www.google.com/";
    console.log( url+hello);

Remove HTML tags from string including &nbsp in C#

var noHtml = Regex.Replace(inputHTML, @"<[^>]*(>|$)|&nbsp;|&zwnj;|&raquo;|&laquo;", string.Empty).Trim();

Dynamic function name in javascript?

What about

this.f = window["instance:" + a] = function(){};

The only drawback is that the function in its toSource method wouldn't indicate a name. That's usually only a problem for debuggers.

Javascript: getFullyear() is not a function

One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:

> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function

Had you used the 'new' keyword, it would have looked like this:

> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016

Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:

el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function

Python Pandas merge only certain columns

This is to merge selected columns from two tables.

If table_1 contains t1_a,t1_b,t1_c..,id,..t1_z columns, and table_2 contains t2_a, t2_b, t2_c..., id,..t2_z columns, and only t1_a, id, t2_a are required in the final table, then

mergedCSV = table_1[['t1_a','id']].merge(table_2[['t2_a','id']], on = 'id',how = 'left')
# save resulting output file    
mergedCSV.to_csv('output.csv',index = False)

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

You can style li elements differently based on their class, their id or their ancestor elements:

li { /* styles all li elements*/
    list-style-type: none;
}

#ParentListID li { /* styles the li elements that have an ancestor element
                      of id="ParentListID" */
    list-style-type: bullet;
}

li.className { /* styles li elements of class="className" */
    list-style-type: bullet;
}

Or, to use the ancestor elements:

#navigationContainerID li { /* specifically styles the li elements with an ancestor of
                               id="navigationContainerID" */
    list-style-type: none;
}

li { /* then styles all other li elements that don't have that ancestor element */
    list-style-type: bullet;
}

Where is virtualenvwrapper.sh after pip install?

Installed it using pip on Ubuntu 15.10 using a normal user, it was put in ~/.local/bin/virtualenvwrapper.sh which I found by running:

$ find / -name virtualenvwrapper.sh 2>/dev/null

How to iterate object in JavaScript?

Something like that:

var dictionary = {"data":[{"id":"0","name":"ABC"},{"id":"1", "name":"DEF"}], "images": [{"id":"0","name":"PQR"},{"id":"1","name":"xyz"}]};

for (item in dictionary) {
  for (subItem in dictionary[item]) {
     console.log(dictionary[item][subItem].id);
     console.log(dictionary[item][subItem].name);
  }
}

Can I run javascript before the whole page is loaded?

Not only can you, but you have to make a special effort not to if you don't want to. :-)

When the browser encounters a classic script tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write calls to output markup that the parser should handle).

That's the default behavior, but you have a few options for delaying script execution:

  1. Use JavaScript modules. A type="module" script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:

    <script type="module" src="./my-code.js"></script>
    <!-- Or -->
    <script type="module">
    // Your code here
    </script>
    

    The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)

    This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.

  2. Use the defer attribute on a classic script tag:

    <script defer src="./my-code.js"></script>
    

    As with the module, the code in my-code.js will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer doesn't work with inline script content, only with external files referenced via src.

  3. I don't think it's what you want, but you can use the async attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module" tag, or use it instead of defer on a classic script tag.

  4. Put the script tag at the end of the document, just prior to the closing </body> tag:

    <!doctype html>
    <html>
    <!-- ... -->
    <body>
    <!-- The document's HTML goes here -->
    <script type="module" src="./my-code.js"></script><!-- Or inline script -->
    </body>
    </html>
    

    That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.

    It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer are better options.

The spec has a useful diagram showing a raw script tag, defer, async, type="module", and type="module" async and the timing of when the JavaScript code is fetched and run:

enter image description here

Here's an example of the default behavior, a raw script tag:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
    if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
        NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
    }_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

(See my answer here for details around that NodeList code.)

When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.

In contrast, here's a type="module" script:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer script with external content (but not inline content).

(There was no need for the NodeList check there because any modern browser supporting modules already has forEach on NodeList.)

In this modern world, there's no real value to the DOMContentLoaded event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script was in the head instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body, again back in the day.

Regular expression for floating point numbers

[+-]?(([1-9][0-9]*)|(0))([.,][0-9]+)?

[+-]? - optional leading sign

(([1-9][0-9]*)|(0)) - integer without leading zero, including single zero

([.,][0-9]+)? - optional fractional part

Doctrine2: Best way to handle many-to-many with extra columns in reference table

The solution is in the documentation of Doctrine. In the FAQ you can see this :

http://docs.doctrine-project.org/en/2.1/reference/faq.html#how-can-i-add-columns-to-a-many-to-many-table

And the tutorial is here :

http://docs.doctrine-project.org/en/2.1/tutorials/composite-primary-keys.html

So you do not anymore do a manyToMany but you have to create an extra Entity and put manyToOne to your two entities.

ADD for @f00bar comment :

it's simple, you have just to to do something like this :

Article  1--N  ArticleTag  N--1  Tag

So you create an entity ArticleTag

ArticleTag:
  type: entity
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  manyToOne:
    article:
      targetEntity: Article
      inversedBy: articleTags
  fields: 
    # your extra fields here
  manyToOne:
    tag:
      targetEntity: Tag
      inversedBy: articleTags

I hope it helps

How to grep and replace

Another option would be to just use perl with globstar.

Enabling shopt -s globstar in your .bashrc (or wherever) allows the ** glob pattern to match all sub-directories and files recursively.

Thus using perl -pXe 's/SEARCH/REPLACE/g' -i ** will recursively replace SEARCH with REPLACE.

The -X flag tells perl to "disable all warnings" - which means that it won't complain about directories.

The globstar also allows you to do things like sed -i 's/SEARCH/REPLACE/g' **/*.ext if you wanted to replace SEARCH with REPLACE in all child files with the extension .ext.

Is the NOLOCK (Sql Server hint) bad practice?

In real life where you encounter systems already written and adding indexes to tables then drastically slows down the data loading of a 14gig data table, you are sometime forced to used WITH NOLOCK on your reports and end of month proessing so that the aggregate funtions (sum, count etc) do not do row, page, table locking and deteriate the overall performance. Easy to say in a new system never use WITH NOLOCK and use indexes - but adding indexes severly downgrades data loading, and when I'm then told, well, alter the code base to delete indexes, then bulk load then recreate the indexes - which is all well and good, if you are developing a new system. But Not when you have a system already in place.

Using "If cell contains" in VBA excel

Is this what you are looking for?

 If ActiveCell.Value == "Total" Then

    ActiveCell.offset(1,0).Value = "-"

 End If

Of you could do something like this

 Dim celltxt As String
 celltxt = ActiveSheet.Range("C6").Text
 If InStr(1, celltxt, "Total") Then
    ActiveCell.offset(1,0).Value = "-"
 End If

Which is similar to what you have.

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

Your annotations look fine. Here are the things to check:

  • make sure the annotation is javax.persistence.Entity, and not org.hibernate.annotations.Entity. The former makes the entity detectable. The latter is just an addition.

  • if you are manually listing your entities (in persistence.xml, in hibernate.cfg.xml, or when configuring your session factory), then make sure you have also listed the ScopeTopic entity

  • make sure you don't have multiple ScopeTopic classes in different packages, and you've imported the wrong one.

Specific Time Range Query in SQL Server

select * from table where 
(dtColumn between #3/1/2009# and #3/31/2009#) and 
(hour(dtColumn) between 6 and 22) and 
(weekday(dtColumn, 1) between 2 and 4) 

Is there something like Codecademy for Java

As of right now, I do not know of any. It appears the code academy folks have set their sites on Ruby on Rails. They do not rule Java out of the picture however.

How can I check if a view is visible or not in Android?

If the image is part of the layout it might be "View.VISIBLE" but that doesn't mean it's within the confines of the visible screen. If that's what you're after; this will work:

Rect scrollBounds = new Rect();
scrollView.getHitRect(scrollBounds);
if (imageView.getLocalVisibleRect(scrollBounds)) {
    // imageView is within the visible window
} else {
    // imageView is not within the visible window
}

C subscripted value is neither array nor pointer nor vector when assigning an array element value

Except when it is the operand of the sizeof or unary & operator, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" is converted ("decays") to an expression of type "pointer to T", and the value of the expression is the address of the first element of the array.

If the declaration of the array being passed is

int S[4][4] = {...};

then when you write

rotateArr( S );

the expression S has type "4-element array of 4-element array of int"; since S is not the operand of the sizeof or unary & operators, it will be converted to an expression of type "pointer to 4-element array of int", or int (*)[4], and this pointer value is what actually gets passed to rotateArr. So your function prototype needs to be one of the following:

T rotateArr( int (*arr)[4] )

or

T rotateArr( int arr[][4] )

or even

T rotateArr( int arr[4][4] )

In the context of a function parameter list, declarations of the form T a[N] and T a[] are interpreted as T *a; all three declare a as a pointer to T.

You're probably wondering why I changed the return type from int to T. As written, you're trying to return a value of type "4-element array of 4-element array of int"; unfortunately, you can't do that. C functions cannot return array types, nor can you assign array types. IOW, you can't write something like:

int a[N], b[N];
...
b = a; // not allowed
a = f(); // not allowed either

Functions can return pointers to arrays, but that's not what you want here. D will cease to exist once the function returns, so any pointer you return will be invalid.

If you want to assign the results of the rotated array to a different array, then you'll have to pass the target array as a parameter to the function:

void rotateArr( int (*dst)[4], int (*src)[4] )
{
  ...
  dst[i][n] = src[n][M - i + 1];
  ...
}

And call it as

int S[4][4] = {...};
int D[4][4];

rotateArr( D, S );

How do I configure modprobe to find my module?

Follow following steps:

  1. Copy hello.ko to /lib/modules/'uname-r'/misc/
  2. Add misc/hello.ko entry in /lib/modules/'uname-r'/modules.dep
  3. sudo depmod
  4. sudo modprobe hello

modprobe will check modules.dep file for any dependency.

How to display loading image while actual image is downloading

You can do something like this:

// show loading image
$('#loader_img').show();

// main image loaded ?
$('#main_img').on('load', function(){
  // hide/remove the loading image
  $('#loader_img').hide();
});

You assign load event to the image which fires when image has finished loading. Before that, you can show your loader image.

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

import java.util.Scanner;
class TestClass {
    public static void main(String args[]) throws Exception {
        Scanner s = new Scanner(System.in);
        String str = s.nextLine();
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (Character.isUpperCase(ch[i])) {
                ch[i] = Character.toLowerCase(ch[i]);
            } else {
                ch[i] = Character.toUpperCase(ch[i]);
            }
        }
        System.out.println(ch);
    }
}

sorting integers in order lowest to highest java

For sorting narrow range of integers try Counting sort, which has a complexity of O(range + n), where n is number of items to be sorted. If you'd like to sort something not discrete use optimal n*log(n) algorithms (quicksort, heapsort, mergesort). Merge sort is also used in a method already mentioned by other responses Arrays.sort. There is no simple way how to recommend some algorithm or function call, because there are dozens of special cases, where you would use some sort, but not the other.

So please specify the exact purpose of your application (to learn something (well - start with the insertion sort or bubble sort), effectivity for integers (use counting sort), effectivity and reusability for structures (use n*log(n) algorithms), or zou just want it to be somehow sorted - use Arrays.sort :-)). If you'd like to sort string representations of integers, than u might be interrested in radix sort....

Truncating Text in PHP?

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

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

// Truncated tring printed out;
echo $mystring;

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

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

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

What does $ mean before a string?

Note that you can also combine the two, which is pretty cool (although it looks a bit odd):

// simple interpolated verbatim string
WriteLine($@"Path ""C:\Windows\{file}"" not found.");

using batch echo with special characters

The way to output > character is to prepend it with ^ escape character:

echo ^>

will print simply

>

Persist javascript variables across pages?

I would recommend you to give a look to this library:

I really like it, it supports a variety of storage backends (from cookies to HTML5 storage, Gears, Flash, and more...), its usage is really transparent, you don't have to know or care which backend is used the library will choose the right storage backend depending on the browser capabilities.

How can I expand and collapse a <div> using javascript?

Okay, so you've got two options here :

  1. Use jQuery UI's accordion - its nice, easy and fast. See more info here
  2. Or, if you still wanna do this by yourself, you could remove the fieldset (its not semantically right to use it for this anyway) and create a structure by yourself.

Here's how you do that. Create a HTML structure like this :

<div class="container">
    <div class="header"><span>Expand</span>

    </div>
    <div class="content">
        <ul>
            <li>This is just some random content.</li>
            <li>This is just some random content.</li>
            <li>This is just some random content.</li>
            <li>This is just some random content.</li>
        </ul>
    </div>
</div>

With this CSS: (This is to hide the .content stuff when the page loads.

.container .content {
    display: none;
    padding : 5px;
}

Then, using jQuery, write a click event for the header.

$(".header").click(function () {

    $header = $(this);
    //getting the next element
    $content = $header.next();
    //open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
    $content.slideToggle(500, function () {
        //execute this after slideToggle is done
        //change text of header based on visibility of content div
        $header.text(function () {
            //change text based on condition
            return $content.is(":visible") ? "Collapse" : "Expand";
        });
    });

});

Here's a demo : http://jsfiddle.net/hungerpain/eK8X5/7/

How to uncheck a checkbox in pure JavaScript?

You will need to assign an ID to the checkbox:

<input id="checkboxId" type="checkbox" checked="" name="copyNewAddrToBilling">

and then in JavaScript:

document.getElementById("checkboxId").checked = false;

SQL: how to use UNION and order by a specific select?

SELECT id, 1 AS sort_order
  FROM b
UNION
SELECT id, 2 AS sort_order
  FROM a
MINUS
SELECT id, 2 AS sort_order
  FROM b
ORDER BY 2;

Quick way to retrieve user information Active Directory

You can call UserPrincipal.FindByIdentity inside System.DirectoryServices.AccountManagement:

using System.DirectoryServices.AccountManagement;

using (var pc = new PrincipalContext(ContextType.Domain, "MyDomainName"))
{
    var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "MyDomainName\\" + userName);
}

How to run DOS/CMD/Command Prompt commands from VB.NET?

You could try this method:

Public Class MyUtilities
    Shared Sub RunCommandCom(command as String, arguments as String, permanent as Boolean) 
        Dim p as Process = new Process() 
        Dim pi as ProcessStartInfo = new ProcessStartInfo() 
        pi.Arguments = " " + if(permanent = true, "/K" , "/C") + " " + command + " " + arguments 
        pi.FileName = "cmd.exe" 
        p.StartInfo = pi 
        p.Start() 
    End Sub
End Class

call, for example, in this way:

MyUtilities.RunCommandCom("DIR", "/W", true)

EDIT: For the multiple command on one line the key are the & | && and || command connectors

  • A & B → execute command A, then execute command B.
  • A | B → execute command A, and redirect all it's output into the input of command B.
  • A && B → execute command A, evaluate the errorlevel after running Command A, and if the exit code (errorlevel) is 0, only then execute command B.
  • A || B → execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute command B.

jQuery: how to change title of document during .ready()?

Like this:

$(document).ready(function ()
{
    document.title = "Hello World!";
});

Be sure to set a default-title if you want your site to be properly indexed by search-engines.

A little tip:

$(function ()
{
    // this is a shorthand for the whole document-ready thing
    // In my opinion, it's more readable 
});

Using a different font with twitter bootstrap

The easiest way I've seen is to use Google Fonts.

Go to Google Fonts and choose a font, then Google will give you a link to put in your HTML.

Google's link to your font

Then add this to your custom.css:

h1, h2, h3, h4, h5, h6 {
    font-family: 'Your Font' !important;
}
p, div {
    font-family: 'Your Font' !important;
}

or

body {
   font-family: 'Your Font' !important;
}

How to import a SQL Server .bak file into MySQL?

I highly doubt it. You might want to use DTS/SSIS to do this as Levi says. One think that you might want to do is start the process without actually importing the data. Just do enough to get the basic table structures together. Then you are going to want to change around the resulting table structure, because whatever structure tat will likely be created will be shaky at best.

You might also have to take this a step further and create a staging area that takes in all the data first n a string (varchar) form. Then you can create a script that does validation and conversion to get it into the "real" database, because the two databases don't always work well together, especially when dealing with dates.

Can I map a hostname *and* a port with /etc/hosts?

No, that's not possible. The port is not part of the hostname, so it has no meaning in the hosts-file.

SELECT INTO USING UNION QUERY

Here's one working syntax for SQL Server 2017:

USE [<yourdb-name>]
GO

SELECT * INTO NEWTABLE 
FROM <table1-name>
UNION ALL
SELECT * FROM <table2-name>

mysqldump with create database line

The simplest solution is to use option -B or --databases.Then CREATE database command appears in the output file. For example:

mysqldump -uuser -ppassword -d -B --events --routines --triggers database_example > database_example.sql

Here is a dumpfile's header:

-- MySQL dump 10.13  Distrib 5.5.36-34.2, for Linux (x86_64)
--
-- Host: localhost    Database: database_example
-- ------------------------------------------------------
-- Server version       5.5.36-34.2-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Current Database: `database_example`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `database_example` /*!40100 DEFAULT CHARACTER SET utf8 */;

How to send a GET request from PHP?

Unless you need more than just the contents of the file, you could use file_get_contents.

$xml = file_get_contents("http://www.example.com/file.xml");

For anything more complex, I'd use cURL.

How to upgrade all Python packages with pip

You can try this:

for i in ` pip list | awk -F ' ' '{print $1}'`; do pip install --upgrade $i; done

What is the difference between Scrum and Agile Development?

SCRUM :

SCRUM is a type of Agile approach. It is a Framework not a Methodology.

It does not provide detailed instructions to what needs to be done rather most of it is dependent on the team that is developing the software. Because the developing the project knows how the problem can be solved that is why much is left on them

Cross-functional and self-organizing teams are essential in case of scrum. There is no team leader in this case who will assign tasks to the team members rather the whole team addresses the issues or problems. It is cross-functional in a way that everyone is involved in the project right from the idea to the implementation of the project.

The advantage of scrum is that a project’s direction to be adjusted based on completed work, not on speculation or predictions.

Roles Involved : Product Owner, Scrum Master, Team Members

Agile Methodology :

Build Software applications that are unpredictable in nature

Iterative and incremental work cadences called sprints are used in this methodology.

Both Agile and SCRUM follows the system -- some of the features are developed as a part of the sprint and at the end of each sprint; the features are completed right from coding, testing and their integration into the product. A demonstration of the functionality is provided to the owner at the end of each sprint so that feedback can be taken which can be helpful for the next sprint.

Manifesto for Agile Development :

  1. Individuals and interactions over processes and tools
  2. Working software over comprehensive documentation
  3. Customer collaboration over contract negotiation
  4. Responding to change over following a plan

That is, while there is value in the items on the right, we value the items on the left more.

Shrink a YouTube video to responsive width

With credits to previous answer https://stackoverflow.com/a/36549068/7149454

Boostrap compatible, adust your container width (300px in this example) and you're good to go:

<div class="embed-responsive embed-responsive-16by9" style="height: 100 %; width: 300px; ">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/LbLB0K-mXMU?start=1841" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0"></iframe>
</div>

What exactly do "u" and "r" string flags do, and what are raw string literals?

'raw string' means it is stored as it appears. For example, '\' is just a backslash instead of an escaping.

print arraylist element?

Printing a specific element is

list.get(INDEX)

I think the best way to print the whole list in one go and this will also avoid putting a loop

Arrays.toString(list.toArray())

How to install the Six module in Python2.7

You need to install this

https://pypi.python.org/pypi/six

If you still don't know what pip is , then please also google for pip install

Python has it's own package manager which is supposed to help you finding packages and their dependencies: http://www.pip-installer.org/en/latest/

jquery get all input from specific form

Use HTML Form "elements" attribute:

$.each($("form").elements, function(){ 
    console.log($(this));
    });

Now it's not necessary to provide such names as "input, textarea, select ..." etc.

Using Cygwin to Compile a C program; Execution error

Regarding the cygwin1.dll not found error, a solution I have used for at least 8 years is to add the Cygwin bin directories to the end of my %PATH% in My Computer -> Properties -> Advanced -> Environment Variables. I add them to the end of the path so in my normal work, they are searched last, minimizing the possibility of conflicts (in fact, I have had no problems with conflicts in all this time).

When you invoke the Cygwin Bash Shell, those directories get prepended to the %PATH% so everything works as intended in that environment as well.

When not running in Cygwin shell, my %PATH% is:

Path=c:\opt\perl\bin; \
     ...
     C:\opt\cygwin\bin; \
     C:\opt\cygwin\usr\bin; \
     C:\opt\cygwin\usr\local\bin;

This way, for example, ActiveState Perl's perl is found first when I am not in a Cygwin Shell, but the Cygwin perl is found when I am working in the Cygwin Shell.

How to replace (or strip) an extension from a filename in Python?

I'm surprised nobody has mentioned pathlib's with_name. This solution works with multiple extensions (i.e. it replaces all of the extensions.)

import pathlib

p = pathlib.Path('/some/path/somefile.txt')
p = p.with_name(p.stem).with_suffix('.jpg')

WPF Data Binding and Validation Rules Best Practices

Also check this article. Supposedly Microsoft released their Enterprise Library (v4.0) from their patterns and practices where they cover the validation subject but god knows why they didn't included validation for WPF, so the blog post I'm directing you to, explains what the author did to adapt it. Hope this helps!

How can I convert a VBScript to an executable (EXE) file?

You can use VBSedit software to convert your VBS code to .exe file. You can download free version from Internet and installtion vbsedit applilcation on your system and convert the files to exe format.

Vbsedit is a good application for VBscripter's

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

Just remove the inner quotes - they confuse Firefox. You can just use "video/ogg; codecs=theora,vorbis".

Also, that markup works in my Minefiled 3.7a5pre, so if your ogv file doesn't play, it may be a bogus file. How did you create it? You might want to register a bug with Firefox.

jQuery click event not working after adding class

Here is the another solution as well, the bind method.

$(document).bind('click', ".intro", function() {
    var liId = $(this).parent("li").attr("id");
    alert(liId);        
});

Cheers :)

How can I get a resource content from a static context?

There is also another possibilty. I load OpenGl shaders from resources like this:

static private String vertexShaderCode;
static private String fragmentShaderCode;

static {
    vertexShaderCode = readResourceAsString("/res/raw/vertex_shader.glsl");
    fragmentShaderCode = readResourceAsString("/res/raw/fragment_shader.glsl");
}

private static String readResourceAsString(String path) {
    Exception innerException;
    Class<? extends FloorPlanRenderer> aClass = FloorPlanRenderer.class;
    InputStream inputStream = aClass.getResourceAsStream(path);

    byte[] bytes;
    try {
        bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        return new String(bytes);
    } catch (IOException e) {
        e.printStackTrace();
        innerException = e;
    }
    throw new RuntimeException("Cannot load shader code from resources.", innerException);
}

As you can see, you can access any resource in path /res/... Change aClass to your class. This also how I load resources in tests (androidTests)

How to show image using ImageView in Android

Drag image from your hard drive to Drawable folder in your project and in code use it like this:

ImageView image;

image = (ImageView) findViewById(R.id.yourimageviewid);
image.setImageResource(R.drawable.imagename);

Updating Python on Mac

First, install Homebrew (The missing package manager for macOS) if you haven': Type this in your terminal

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Now you can update your Python to python 3 by this command
brew install python3 && cp /usr/local/bin/python3 /usr/local/bin/python

Python 2 and python 3 can coexist so to open python 3, type python3 instead of python

That's the easiest and the best way.

Does "\d" in regex mean a digit?

Info regarding .NET / C#:

Decimal digit character: \d \d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets.

If ECMAScript-compliant behavior is specified, \d is equivalent to [0-9]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options.

Info: https://docs.microsoft.com/en-us/dotnet/standard/base-types/character-classes-in-regular-expressions#decimal-digit-character-d

Iterate through string array in Java

String[] elements = { "a", "a", "a", "a" };

for( int i = 0; i < elements.length - 1; i++)
{
    String element = elements[i];
    String nextElement = elements[i+1];
}

Note that in this case, elements.length is 4, so you want to iterate from [0,2] to get elements 0,1, 1,2 and 2,3.

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

enter image description here

Reassign the value of Automatically manage signing, this works for me

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

Mysql: Select rows from a table that are not in another

A standard LEFT JOIN could resolve the problem and, if the fields on join are indexed,
should also be faster

SELECT *
FROM Table1 as t1 LEFT JOIN Table2 as t2 
ON t1.FirstName = t2.FirstName AND t1.LastName=t2.LastName
WHERE t2.BirthDate Is Null

Array vs ArrayList in performance

From here:

ArrayList is internally backed by Array in Java, any resize operation in ArrayList will slow down performance as it involves creating new Array and copying content from old array to new array.


In terms of performance Array and ArrayList provides similar performance in terms of constant time for adding or getting element if you know index. Though automatic resize of ArrayList may slow down insertion a bit Both Array and ArrayList is core concept of Java and any serious Java programmer must be familiar with these differences between Array and ArrayList or in more general Array vs List.

Fully backup a git repo?

Expanding on the great answers by KingCrunch and VonC

I combined them both:

git clone --mirror [email protected]/reponame reponame.git
cd reponame.git
git bundle create reponame.bundle --all

After that you have a file called reponame.bundle that can be easily copied around. You can then create a new normal git repository from that using git clone reponame.bundle reponame.

Note that git bundle only copies commits that lead to some reference (branch or tag) in the repository. So tangling commits are not stored to the bundle.

Can you force Vue.js to reload/re-render?

<router-view :key="$route.params.slug" />

just use key with your any params its auto reload children..

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

In absence of a white-list feature you have to make the "all" or "nothing" Choice. You can disable mixed content blocking completely.


The Nothing Choice

You will need to permanently disable mixed content blocking for the current active profile.

In the "Awesome Bar," type "about:config". If this is your first time you will get the "This might void your warranty!" message.

Yes you will be careful. Yes you promise!

Find security.mixed_content.block_active_content. Set its value to false.


The All Choice

iDevelApp's answer is awesome.

Using jQuery to center a DIV on the screen

MY UPDATE TO TONY L'S ANSWER This is the modded version of his answer that I use religiously now. I thought I would share it, as it adds slightly more functionality to it for various situations you may have, such as different types of position or only wanting horizontal/vertical centering rather than both.

center.js:

// We add a pos parameter so we can specify which position type we want

// Center it both horizontally and vertically (dead center)
jQuery.fn.center = function (pos) {
    this.css("position", pos);
    this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
    this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
    return this;
}

// Center it horizontally only
jQuery.fn.centerHor = function (pos) {
    this.css("position", pos);
    this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
    return this;
}

// Center it vertically only
jQuery.fn.centerVer = function (pos) {
    this.css("position", pos);
    this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
    return this;
}

In my <head>:

<script src="scripts/center.js"></script>

Examples of usage:

$("#example1").centerHor("absolute")
$("#example2").centerHor("fixed")

$("#example3").centerVer("absolute")
$("#example4").centerVer("fixed")

$("#example5").center("absolute")
$("#example6").center("fixed")

It works with any positioning type, and can be used throughout your entire site easily, as well as easily portable to any other site you create. No more annoying workarounds for centering something properly.

Hope this is useful for someone out there! Enjoy.

Error - is not marked as serializable

You need to add a Serializable attribute to the class which you want to serialize.

[Serializable]
public class OrgPermission

How to export a table dataframe in PySpark to csv?

How about this (in you don't want an one liner) ?

for row in df.collect():
    d = row.asDict()
    s = "%d\t%s\t%s\n" % (d["int_column"], d["string_column"], d["string_column"])
    f.write(s)

f is a opened file descriptor. Also the separator is a TAB char, but it's easy to change to whatever you want.

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, ie: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

Not something I would teach (or ever use in my code), but here's a codegolf-worthy solution without mutating a variable, no need for ES6:

Array.apply(null, {length: 10}).forEach(function(_, i){
    doStuff(i);
})

More of an interesting proof-of-concept thing than a useful answer, really.

Getting the index of a particular item in array

try Array.FindIndex(myArray, x => x.Contains("author"));

How do I start a process from C#?

I used the following in my own program.

Process.Start("http://www.google.com/etc/etc/test.txt")

It's a bit basic, but it does the job for me.

NSDictionary to NSArray?

This code is actually used to add values to the dictionary and through the data to an Array According to the Key.

NSMutableArray *arr = [[NSMutableArray alloc]init];
NSDictionary *dicto = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Hello",@"StackOverFlow",@"Key1",@"StackExchange",@"Key2", nil];
NSLog(@"The dictonary is = %@", dicto);
arr = [dicto valueForKey:@"Key1"];
NSLog(@"The array is = %@", arr);

Hibernate openSession() vs getCurrentSession()

As explained in this forum post, 1 and 2 are related. If you set hibernate.current_session_context_class to thread and then implement something like a servlet filter that opens the session - then you can access that session anywhere else by using the SessionFactory.getCurrentSession().

SessionFactory.openSession() always opens a new session that you have to close once you are done with the operations. SessionFactory.getCurrentSession() returns a session bound to a context - you don't need to close this.

If you are using Spring or EJBs to manage transactions you can configure them to open / close sessions along with the transactions.

You should never use one session per web app - session is not a thread safe object - cannot be shared by multiple threads. You should always use "one session per request" or "one session per transaction"

Restart android machine

adb reboot should not reboot your linux box.

But in any case, you can redirect the command to a specific adb device using adb -s <device_id> command , where

Device ID can be obtained from the command adb devices
command in this case is reboot

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

How do I convert a double into a string in C++?

Use to_string().
example :

#include <iostream>   
#include <string>  

using namespace std;
int main ()
{
    string pi = "pi is " + to_string(3.1415926);
    cout<< "pi = "<< pi << endl;

  return 0;
}

run it yourself : http://ideone.com/7ejfaU
These are available as well :

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

What is difference between sjlj vs dwarf vs seh?

SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks

DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.

SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.

source: https://wiki.qt.io/MinGW-64-bit

Combine :after with :hover

 #alertlist li:hover:after,#alertlist li.selected:after
{
    position:absolute;
    top: 0;
    right:-10px;
    bottom:0;

    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #303030;
    content: "";
}?

jsFiddle Link

What's the best way to parse command line arguments?

Lightweight command line argument defaults

Although argparse is great and is the right answer for fully documented command line switches and advanced features, you can use function argument defaults to handles straightforward positional arguments very simply.

import sys

def get_args(name='default', first='a', second=2):
    return first, int(second)

first, second = get_args(*sys.argv)
print first, second

The 'name' argument captures the script name and is not used. Test output looks like this:

> ./test.py
a 2
> ./test.py A
A 2
> ./test.py A 20
A 20

For simple scripts where I just want some default values, I find this quite sufficient. You might also want to include some type coercion in the return values or command line values will all be strings.

jQuery Call to WebService returns "No Transport" error

I too got this problem and all solutions given above either failed or were not applicable due to client webservice restrictions.

For this, I added an iframe in my page which resided in the client;s server. So when we post our data to the iframe and the iframe then posts it to the webservice. Hence the cross-domain referencing is eliminated.

We added a 2-way origin check to confirm only authorized page posts data to and from the iframe.

Hope it helps

<iframe style="display:none;" id='receiver' name="receiver" src="https://iframe-address-at-client-server">
 </iframe>

//send data to iframe
var hiddenFrame = document.getElementById('receiver').contentWindow;
hiddenFrame.postMessage(JSON.stringify(message), 'https://client-server-url');

//The iframe receives the data using the code:
window.onload = function () {
    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    var eventer = window[eventMethod];
    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    eventer(messageEvent, function (e) {
        var origin = e.origin;
        //if origin not in pre-defined list, break and return
        var messageFromParent = JSON.parse(e.data);
        var json = messageFromParent.data;

        //send json to web service using AJAX   
        //return the response back to source
        e.source.postMessage(JSON.stringify(aJAXResponse), e.origin);
    }, false);
}

Promise.all().then() resolve?

But that doesn't seem like the proper way to do it..

That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("First handler", data);_x000D_
    return data.map(entry => entry * 10);_x000D_
  })_x000D_
  .then(data => {_x000D_
    console.log("Second handler", data);_x000D_
  });
_x000D_
_x000D_
_x000D_

(catch handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)

The output we see from that is:

First handler [1,2]
Second handler [10,20]

...because the first handler gets the resolution of the two promises (1 and 2) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.

If the additional work you're doing is synchronous, you can also put it in the first handler:

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("Initial data", data);_x000D_
    data = data.map(entry => entry * 10);_x000D_
    console.log("Updated data", data);_x000D_
    return data;_x000D_
  });
_x000D_
_x000D_
_x000D_

...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.

Find nearest value in numpy array

This is a vectorized version of unutbu's answer:

def find_nearest(array, values):
    array = np.asarray(array)

    # the last dim must be 1 to broadcast in (array - values) below.
    values = np.expand_dims(values, axis=-1) 

    indices = np.abs(array - values).argmin(axis=-1)

    return array[indices]


image = plt.imread('example_3_band_image.jpg')

print(image.shape) # should be (nrows, ncols, 3)

quantiles = np.linspace(0, 255, num=2 ** 2, dtype=np.uint8)

quantiled_image = find_nearest(quantiles, image)

print(quantiled_image.shape) # should be (nrows, ncols, 3)

Error in Eclipse: "The project cannot be built until build path errors are resolved"

I also had this problem in my system, but after looking inside the project I saw the XML structure of the .classpath file in the project path was incorrect. After amending that file the problem was solved.

Name attribute in @Entity and @Table

@Entity(name = "someThing") => this name will be used to identify the domain ..this name will only be identified by hql queries ..ie ..name of the domain object

@Table(name = "someThing") => this name will be used to which table referred by domain object..ie ..name of the table

Add back button to action bar

Add

actionBar.setHomeButtonEnabled(true);

and then add the following

@Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{       
    switch (menuItem.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(menuItem);
    }
}

As suggested by naXa I've added a check on the itemId, to have it work correctly in case there are multiple buttons on the action bar.

How to create a new branch from a tag?

The situation becomes a little bit problematic if we want to create a branch from a tag with the same name.

In this, and in similar scenarios, the important thing is to know: branches and tags are actually single-line text files in .git/refs directory, and we can reference them explicitly using their pathes below .git. Branches are called here "heads", to make our life more simple.

Thus, refs/heads/master is the real, explicit name of the master branch. And refs/tags/cica is the exact name of the tag named cica.

The correct command to create a branch named cica from the tag named cica is:

git branch cica refs/tags/cica

How do I run pip on python for windows?

Maybe you'd like try run pip in Python shell like this:

>>> import pip
>>> pip.main(['install', 'requests'])

This will install requests package using pip.


Because pip is a module in standard library, but it isn't a built-in function(or module), so you need import it.

Other way, you should run pip in system shell(cmd. If pip is in path).

SSRS custom number format

am assuming that you want to know how to format numbers in SSRS

Just right click the TextBox on which you want to apply formatting, go to its expression.

suppose its expression is something like below

=Fields!myField.Value

then do this

=Format(Fields!myField.Value,"##.##") 

or

=Format(Fields!myFields.Value,"00.00")

difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00

this should give you an idea.

also: you might have to convert your field into a numerical one. i.e.

  =Format(CDbl(Fields!myFields.Value),"00.00")

so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:

UPDATE :

if you want to apply variable formatting on the same column based on row values i.e. you want myField to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)

Go to the appropriate textbox and go to its expression and do this:

=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0, 
    Format(Fields!myField.Value, "##.##"),Fields!myField.Value)

so basically you are using IIF(condition, true,false) operator of SSRS, ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.

this should give you an idea, how to handle variable formatting.

How do I parse JSON into an int?

It depends on the property type that you are parsing.

If the json property is a number (e.g. 5) you can cast to Long directly, so you could do:

(long) jsonObj.get("id") // with id = 5, cast `5` to long 

After getting the long,you could cast again to int, resulting in:

(int) (long) jsonObj.get("id")

If the json property is a number with quotes (e.g. "5"), is is considered a string, and you need to do something similar to Integer.parseInt() or Long.parseLong();

Integer.parseInt(jsonObj.get("id")) // with id = "5", convert "5" to Long

The only issue is, if you sometimes receive id's a string or as a number (you cant predict your client's format or it does it interchangeably), you might get an exception, especially if you use parseInt/Long on a null json object.

If not using Java Generics, the best way to deal with these runtime exceptions that I use is:

if(jsonObj.get("id") == null) {
   // do something here
}

int id;
try{
    id = Integer.parseInt(jsonObj.get("id").toString());
} catch(NumberFormatException e) {
  // handle here
}

You could also remove that first if and add the exception to the catch. Hope this helps.

Creating a JSON Array in node js

Build up a JavaScript data structure with the required information, then turn it into the json string at the end.

Based on what I think you're doing, try something like this:

var result = [];
for (var name in goals) {
  if (goals.hasOwnProperty(name)) {
    result.push({name: name, goals: goals[name]});
  }
}

res.contentType('application/json');
res.send(JSON.stringify(result));

or something along those lines.

How do I add an element to array in reducer of React native redux?

I have a sample

import * as types from '../../helpers/ActionTypes';

var initialState = {
  changedValues: {}
};
const quickEdit = (state = initialState, action) => {

  switch (action.type) {

    case types.PRODUCT_QUICKEDIT:
      {
        const item = action.item;
        const changedValues = {
          ...state.changedValues,
          [item.id]: item,
        };

        return {
          ...state,
          loading: true,
          changedValues: changedValues,
        };
      }
    default:
      {
        return state;
      }
  }
};

export default quickEdit;

How to label scatterplot points by name?

For all those who don't have the option in Excel (like me), there is a macro which works and is explained here: https://www.get-digital-help.com/2015/08/03/custom-data-labels-in-x-y-scatter-chart/ Very useful

.NET: Simplest way to send POST with data and read response

I know this is an old thread, but hope it helps some one.

public static void SetRequest(string mXml)
{
    HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://dork.com/service");
    webRequest.Method = "POST";
    webRequest.Headers["SOURCE"] = "WinApp";

    // Decide your encoding here

    //webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentType = "text/xml; charset=utf-8";

    // You should setContentLength
    byte[] content = System.Text.Encoding.UTF8.GetBytes(mXml);
    webRequest.ContentLength = content.Length;

    var reqStream = await webRequest.GetRequestStreamAsync();
    reqStream.Write(content, 0, content.Length);

    var res = await httpRequest(webRequest);
}

How is CountDownLatch used in Java Multithreading?

Best real time Example for countDownLatch explained in this link CountDownLatchExample

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

November 2020 : As I experienced , these meta tags are required and effect on what you see on shared link in Whatsapp and WhatsApp-thumbnail :

<head>
 <meta content='myTitle' property='og:title'/>
  <meta content="myDescription" property="og:Description"/>
  <meta property="og:type" content= "website" />
  <meta property="og:image" itemprop="image primaryImageOfPage" content="https://i.ibb.co/1GRpwND/600px-Approve-icon-svg.png" />
</head>

and inside <body> :

<a href="https://wa.me/?text=https://myaddress.blogspot.com/2020/11/try-16.html" target="_blank" rel="nofollow">Hello whatsApp</a>

More explanation :

1- Suppose you have <meta content='example.com/page1' property='og:url'/> and inside body you refer to <a href="https://wa.me/?text=example.com/page2" >Hello whatsApp</a>, the og:image and og:description of page example.com/page2 wil be rendered on whatsApp as you referred on your link in body (maybe obvious).

2-When you add/change any open graph tags such as og:description, and again you click your <a></a> tag on your page/body, what you see on WhatsApp doesn't change unless you change the href="I am a new URL" of your <a></a> tag or clear cache of WhatsApp !!

3-I tried Png/jpg images, all less than 300 kb in size and all bigger than 300*300 in pixels, and image content was a https or a http url, the above code supports both of them ( No need to og:image:secure_url).

4-Each time you add/change og contents, to have a thumbnail on WhatsApp, the changes doesn't affect on first try !! and successful on second try. Very strange !

How do implement a breadth first traversal?

It doesn't seem like you're asking for an implementation, so I'll try to explain the process.

Use a Queue. Add the root node to the Queue. Have a loop run until the queue is empty. Inside the loop dequeue the first element and print it out. Then add all its children to the back of the queue (usually going from left to right).

When the queue is empty every element should have been printed out.

Also, there is a good explanation of breadth first search on wikipedia: http://en.wikipedia.org/wiki/Breadth-first_search

Windows Explorer "Command Prompt Here"

I use StExBar, a Windows Explorer extension that gives you a command prompt button in explorer along with some other cool features (copy path, copy file name & more).

https://tools.stefankueng.com/StExBar.html

EDIT: I just found out (been using it for more than a year and did not know this) that Ctrl+M will do it with StExBar. How's that for fast!

String concatenation: concat() vs "+" operator

Most answers here are from 2008. It looks that things have changed over the time. My latest benchmarks made with JMH shows that on Java 8 + is around two times faster than concat.

My benchmark:

@Warmup(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)
public class StringConcatenation {

    @org.openjdk.jmh.annotations.State(Scope.Thread)
    public static class State2 {
        public String a = "abc";
        public String b = "xyz";
    }

    @org.openjdk.jmh.annotations.State(Scope.Thread)
    public static class State3 {
        public String a = "abc";
        public String b = "xyz";
        public String c = "123";
    }


    @org.openjdk.jmh.annotations.State(Scope.Thread)
    public static class State4 {
        public String a = "abc";
        public String b = "xyz";
        public String c = "123";
        public String d = "!@#";
    }

    @Benchmark
    public void plus_2(State2 state, Blackhole blackhole) {
        blackhole.consume(state.a+state.b);
    }

    @Benchmark
    public void plus_3(State3 state, Blackhole blackhole) {
        blackhole.consume(state.a+state.b+state.c);
    }

    @Benchmark
    public void plus_4(State4 state, Blackhole blackhole) {
        blackhole.consume(state.a+state.b+state.c+state.d);
    }

    @Benchmark
    public void stringbuilder_2(State2 state, Blackhole blackhole) {
        blackhole.consume(new StringBuilder().append(state.a).append(state.b).toString());
    }

    @Benchmark
    public void stringbuilder_3(State3 state, Blackhole blackhole) {
        blackhole.consume(new StringBuilder().append(state.a).append(state.b).append(state.c).toString());
    }

    @Benchmark
    public void stringbuilder_4(State4 state, Blackhole blackhole) {
        blackhole.consume(new StringBuilder().append(state.a).append(state.b).append(state.c).append(state.d).toString());
    }

    @Benchmark
    public void concat_2(State2 state, Blackhole blackhole) {
        blackhole.consume(state.a.concat(state.b));
    }

    @Benchmark
    public void concat_3(State3 state, Blackhole blackhole) {
        blackhole.consume(state.a.concat(state.b.concat(state.c)));
    }


    @Benchmark
    public void concat_4(State4 state, Blackhole blackhole) {
        blackhole.consume(state.a.concat(state.b.concat(state.c.concat(state.d))));
    }
}

Results:

Benchmark                             Mode  Cnt         Score         Error  Units
StringConcatenation.concat_2         thrpt   50  24908871.258 ± 1011269.986  ops/s
StringConcatenation.concat_3         thrpt   50  14228193.918 ±  466892.616  ops/s
StringConcatenation.concat_4         thrpt   50   9845069.776 ±  350532.591  ops/s
StringConcatenation.plus_2           thrpt   50  38999662.292 ± 8107397.316  ops/s
StringConcatenation.plus_3           thrpt   50  34985722.222 ± 5442660.250  ops/s
StringConcatenation.plus_4           thrpt   50  31910376.337 ± 2861001.162  ops/s
StringConcatenation.stringbuilder_2  thrpt   50  40472888.230 ± 9011210.632  ops/s
StringConcatenation.stringbuilder_3  thrpt   50  33902151.616 ± 5449026.680  ops/s
StringConcatenation.stringbuilder_4  thrpt   50  29220479.267 ± 3435315.681  ops/s

Finding rows containing a value (or values) in any column

If you want to find the rows that have any of the values in a vector, one option is to loop the vector (lapply(v1,..)), create a logical index of (TRUE/FALSE) with (==). Use Reduce and OR (|) to reduce the list to a single logical matrix by checking the corresponding elements. Sum the rows (rowSums), double negate (!!) to get the rows with any matches.

indx1 <- !!rowSums(Reduce(`|`, lapply(v1, `==`, df)), na.rm=TRUE)

Or vectorise and get the row indices with which with arr.ind=TRUE

indx2 <- unique(which(Vectorize(function(x) x %in% v1)(df),
                                     arr.ind=TRUE)[,1])

Benchmarks

I didn't use @kristang's solution as it is giving me errors. Based on a 1000x500 matrix, @konvas's solution is the most efficient (so far). But, this may vary if the number of rows are increased

val <- paste0('M0', 1:1000)
set.seed(24)
df1 <- as.data.frame(matrix(sample(c(val, NA), 1000*500, 
  replace=TRUE), ncol=500), stringsAsFactors=FALSE) 
set.seed(356)
v1 <- sample(val, 200, replace=FALSE)

 konvas <- function() {apply(df1, 1, function(r) any(r %in% v1))}
 akrun1 <- function() {!!rowSums(Reduce(`|`, lapply(v1, `==`, df1)),
               na.rm=TRUE)}
 akrun2 <- function() {unique(which(Vectorize(function(x) x %in% 
              v1)(df1),arr.ind=TRUE)[,1])}


 library(microbenchmark)
 microbenchmark(konvas(), akrun1(), akrun2(), unit='relative', times=20L)
 #Unit: relative
 #   expr       min         lq       mean     median         uq      max   neval
 # konvas()   1.00000   1.000000   1.000000   1.000000   1.000000  1.00000    20
 # akrun1() 160.08749 147.642721 125.085200 134.491722 151.454441 52.22737    20
 # akrun2()   5.85611   5.641451   4.676836   5.330067   5.269937  2.22255    20
 # cld
 #  a 
 #  b
 #  a 

For ncol = 10, the results are slighjtly different:

expr       min        lq     mean    median        uq       max    neval
 konvas()  3.116722  3.081584  2.90660  2.983618  2.998343  2.394908    20
 akrun1() 27.587827 26.554422 22.91664 23.628950 21.892466 18.305376    20
 akrun2()  1.000000  1.000000  1.00000  1.000000  1.000000  1.000000    20

data

 v1 <- c('M017', 'M018')
 df <- structure(list(datetime = c("04.10.2009 01:24:51",
"04.10.2009 01:24:53", 
"04.10.2009 01:24:54", "04.10.2009 01:25:06", "04.10.2009 01:25:07", 
"04.10.2009 01:26:07", "04.10.2009 01:26:27", "04.10.2009 01:27:23", 
"04.10.2009 01:27:30", "04.10.2009 01:27:32", "04.10.2009 01:27:34"
), col1 = c("M017", "M018", "M051", "<NA>", "<NA>", "<NA>", "<NA>", 
"<NA>", "<NA>", "M017", "M051"), col2 = c("<NA>", "<NA>", "<NA>", 
"M016", "M015", "M017", "M017", "M017", "M017", "<NA>", "<NA>"
), col3 = c("<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>", 
"<NA>", "<NA>", "<NA>", "<NA>"), col4 = c(NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA)), .Names = c("datetime", "col1", "col2", 
"col3", "col4"), class = "data.frame", row.names = c("1", "2", 
"3", "4", "5", "6", "7", "8", "9", "10", "11"))

Custom HTTP headers : naming conventions

The question bears re-reading. The actual question asked is not similar to vendor prefixes in CSS properties, where future-proofing and thinking about vendor support and official standards is appropriate. The actual question asked is more akin to choosing URL query parameter names. Nobody should care what they are. But name-spacing the custom ones is a perfectly valid -- and common, and correct -- thing to do.

Rationale:
It is about conventions among developers for custom, application-specific headers -- "data relevant to their account" -- which have nothing to do with vendors, standards bodies, or protocols to be implemented by third parties, except that the developer in question simply needs to avoid header names that may have other intended use by servers, proxies or clients. For this reason, the "X-Gzip/Gzip" and "X-Forwarded-For/Forwarded-For" examples given are moot. The question posed is about conventions in the context of a private API, akin to URL query parameter naming conventions. It's a matter of preference and name-spacing; concerns about "X-ClientDataFoo" being supported by any proxy or vendor without the "X" are clearly misplaced.

There's nothing special or magical about the "X-" prefix, but it helps to make it clear that it is a custom header. In fact, RFC-6648 et al help bolster the case for use of an "X-" prefix, because -- as vendors of HTTP clients and servers abandon the prefix -- your app-specific, private-API, personal-data-passing-mechanism is becoming even better-insulated against name-space collisions with the small number of official reserved header names. That said, my personal preference and recommendation is to go a step further and do e.g. "X-ACME-ClientDataFoo" (if your widget company is "ACME").

IMHO the IETF spec is insufficiently specific to answer the OP's question, because it fails to distinguish between completely different use cases: (A) vendors introducing new globally-applicable features like "Forwarded-For" on the one hand, vs. (B) app developers passing app-specific strings to/from client and server. The spec only concerns itself with the former, (A). The question here is whether there are conventions for (B). There are. They involve grouping the parameters together alphabetically, and separating them from the many standards-relevant headers of type (A). Using the "X-" or "X-ACME-" prefix is convenient and legitimate for (B), and does not conflict with (A). The more vendors stop using "X-" for (A), the more cleanly-distinct the (B) ones will become.

Example:
Google (who carry a bit of weight in the various standards bodies) are -- as of today, 20141102 in this slight edit to my answer -- currently using "X-Mod-Pagespeed" to indicate the version of their Apache module involved in transforming a given response. Is anyone really suggesting that Google should use "Mod-Pagespeed", without the "X-", and/or ask the IETF to bless its use?

Summary:
If you're using custom HTTP Headers (as a sometimes-appropriate alternative to cookies) within your app to pass data to/from your server, and these headers are, explicitly, NOT intended ever to be used outside the context of your application, name-spacing them with an "X-" or "X-FOO-" prefix is a reasonable, and common, convention.

How to add data via $.ajax ( serialize() + extra data ) like this

You can do it like this:

postData[postData.length] = { name: "variable_name", value: variable_value };

pip: no module named _internal

(On windows) not sure why this was happening but I had my PYTHONPATH setup to point to c:\python27 where python was installed. in combination with virtualenv this produced the mentioned bug.

resolved by removing the PYTHONPATH env var all together

How to load up CSS files using Javascript?

Element.insertAdjacentHTML has very good browser support, and can add a stylesheet in one line.

document.getElementsByTagName("head")[0].insertAdjacentHTML(
    "beforeend",
    "<link rel=\"stylesheet\" href=\"path/to/style.css\" />");

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

Execute Stored Procedure from a Function

EDIT: I haven't tried this, so I can't vouch for it! And you already know you shouldn't be doing this, so please don't do it. BUT...

Try looking here: http://sqlblog.com/blogs/denis_gobo/archive/2008/05/08/6703.aspx

The key bit is this bit which I have attempted to tweak for your purposes:

DECLARE @SQL varchar(500)

SELECT @SQL = 'osql -S' +@@servername +' -E -q "exec dbName..sprocName "'

EXEC master..xp_cmdshell @SQL

How do you make an array of structs in C?

Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.

Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:

typedef struct
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
}Body;

Then declare your array of structs. Initialization of each element goes along with the declaration:

Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};

To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.

How to use GNU Make on Windows?

As an alternative, if you just want to install make, you can use the chocolatey package manager to install gnu make by using

choco install make -y

This deals with any path issues that you might have.

sscanf in Python

you can turn the ":" to space, and do the split.eg

>>> f=open("/proc/net/dev")
>>> for line in f:
...     line=line.replace(":"," ").split()
...     print len(line)

no regex needed (for this case)

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

I stumbled upon another solution, which is quite nice.

Basically, only do step 2 from the blog posted mentioned, and define a custom ObjectMapper as a Spring @Component. (Things started working when I just removed all the AnnotationMethodHandlerAdapter stuff from step 3.)

@Component
@Primary
public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
        setSerializationInclusion(JsonInclude.Include.NON_NULL); 
        configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
    }
}

Works as long as the component is in a package scanned by Spring. (Using @Primary is not mandatory in my case, but why not make things explicit.)

For me there are two benefits compared to the other approach:

  • This is simpler; I can just extend a class from Jackson and don't need to know about highly Spring-specific stuff like Jackson2ObjectMapperBuilder.
  • I want to use the same Jackson configs for deserialising JSON in another part of my app, and this way it's very simple: new CustomObjectMapper() instead of new ObjectMapper().

How to fix "'System.AggregateException' occurred in mscorlib.dll"

The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.

Task.Factory.StartNew(x=>
   throw new Exception("I didn't account for this");
)

However, if we do this, at least the application does not crash.

Task.Factory.StartNew(x=>
   try {
      throw new Exception("I didn't account for this");
   }
   catch(Exception ex) {
      //Log ex
   }
)

javac is not recognized as an internal or external command, operable program or batch file

Run the following from the command prompt: set Path="C:\Program Files\Java\jdk1.7.0_09\bin" or set PATH="C:\Program Files\Java\jdk1.7.0_09\bin"

I have tried this and it works well.

Allowed characters in filename

For "English locale" file names, this works nicely. I'm using this for sanitizing uploaded file names. The file name is not meant to be linked to anything on disk, it's for when the file is being downloaded hence there are no path checks.

$file_name = preg_replace('/([^\x20-~]+)|([\\/:?"<>|]+)/g', '_', $client_specified_file_name);

Basically it strips all non-printable and reserved characters for Windows and other OSs. You can easily extend the pattern to support other locales and functionalities.

How do I create a foreign key in SQL Server?

create table question_bank
(
    question_id uniqueidentifier primary key,
    question_exam_id uniqueidentifier not null,
    question_text varchar(1024) not null,
    question_point_value decimal,
    constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id)
);

How can I post an array of string to ASP.NET MVC Controller without a form?

I modified my response to include the code for a test app I did.

Update: I have updated the jQuery to set the 'traditional' setting to true so this will work again (per @DustinDavis' answer).

First the javascript:

function test()
{
    var stringArray = new Array();
    stringArray[0] = "item1";
    stringArray[1] = "item2";
    stringArray[2] = "item3";
    var postData = { values: stringArray };

    $.ajax({
        type: "POST",
        url: "/Home/SaveList",
        data: postData,
        success: function(data){
            alert(data.Result);
        },
        dataType: "json",
        traditional: true
    });
}

And here's the code in my controller class:

public JsonResult SaveList(List<String> values)
{
    return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
}

When I call that javascript function, I get an alert saying "First item in list: 'item1'". Hope this helps!

Get total number of items on Json object?

That's an Object and you want to count the properties of it.

Object.keys(jsonArray).length

References:

Can I make a function available in every controller in angular?

You can also combine them I guess:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
        var myApp = angular.module('myApp', []);

        myApp.factory('myService', function() {
            return {
                foo: function() {
                    alert("I'm foo!");
                }
            };
        });

        myApp.run(function($rootScope, myService) {
            $rootScope.appData = myService;
        });

        myApp.controller('MainCtrl', ['$scope', function($scope){

        }]);

    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="appData.foo()">Call foo</button>
</body>
</html>

jquery how to get the page's current screen top position?

var top = $('html').offset().top;

should do it.

edit: this is the negative of $(document).scrollTop()

How to Create Multiple Where Clause Query Using Laravel Eloquent?

Query scopes may help you to let your code more readable.

http://laravel.com/docs/eloquent#query-scopes

Updating this answer with some example:

In your model, create scopes methods like this:

public function scopeActive($query)
{
    return $query->where('active', '=', 1);
}

public function scopeThat($query)
{
    return $query->where('that', '=', 1);
}

Then, you can call this scopes while building your query:

$users = User::active()->that()->get();

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

This is the simplest and easy way. This is how we do this.

_x000D_
_x000D_
var obj = { 'bar' : 'baz' }_x000D_
var key = Object.keys(obj)[0];_x000D_
var value = obj[key];_x000D_
     _x000D_
 console.log("key = ", key) // bar_x000D_
 console.log("value = ", value) // baz
_x000D_
_x000D_
_x000D_ Object.keys() is javascript method which return an array of keys when using on objects.

Object.keys(obj) // ['bar']

Now you can iterate on the objects and can access values like below-

Object.keys(obj).forEach( function(key) {
  console.log(obj[key]) // baz
})

Get the current file name in gulp.src()

For my case gulp-ignore was perfect. As option you may pass a function there:

function condition(file) {
 // do whatever with file.path
 // return boolean true if needed to exclude file 
}

And the task would look like this:

var gulpIgnore = require('gulp-ignore');

gulp.task('task', function() {
  gulp.src('./**/*.js')
    .pipe(gulpIgnore.exclude(condition))
    .pipe(gulp.dest('./dist/'));
});

How to make JavaScript execute after page load?

I find sometimes on more complex pages that not all the elements have loaded by the time window.onload is fired. If that's the case, add setTimeout before your function to delay is a moment. It's not elegant but it's a simple hack that renders well.

window.onload = function(){ doSomethingCool(); };

becomes...

window.onload = function(){ setTimeout( function(){ doSomethingCool(); }, 1000); };

Read large files in Java

Unless you accidentally read in the whole input file instead of reading it line by line, then your primary limitation will be disk speed. You may want to try starting with a file containing 100 lines and write it to 100 different files one line in each and make the triggering mechanism work on the number of lines written to the current file. That program will be easily scalable to your situation.

In Android, how do I set margins in dp programmatically?

LayoutParams - NOT WORKING ! ! !

Need use type of: MarginLayoutParams

MarginLayoutParams params = (MarginLayoutParams) vector8.getLayoutParams();
params.width = 200; params.leftMargin = 100; params.topMargin = 200;

Code Example for MarginLayoutParams:

http://www.codota.com/android/classes/android.view.ViewGroup.MarginLayoutParams

How can I get Apache gzip compression to work?

In my case append only this line worked

SetOutputFilter DEFLATE

Insert ellipsis (...) into HTML tag if content too wide

Here is a nice widget/plugin library which has ellipsis built in: http://www.codeitbetter.co.uk/widgets/ellipsis/ All you need to do it reference the library and call the following:

<script type="text/javascript"> 
   $(document).ready(function () { 
      $(".ellipsis_10").Ellipsis({ 
         numberOfCharacters: 10, 
         showLessText: "less", 
         showMoreText: "more" 
      }); 
   }); 
</script> 
<div class="ellipsis_10"> 
   Some text here that's longer than 10 characters. 
</div>

CreateProcess error=206, The filename or extension is too long when running main() method

Try this:

java -jar -Dserver.port=8080 build/libs/APP_NAME_HERE.jar

Java Calendar, getting current month value, clarification needed

import java.util.*;

class GetCurrentmonth
{
    public static void main(String args[])
    {
        int month;
        GregorianCalendar date = new GregorianCalendar();      
        month = date.get(Calendar.MONTH);
        month = month+1;
        System.out.println("Current month is  " + month);
    }
}

Vue is not defined

I needed to add the script below to index.html inside the HEAD tag.

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

But in your case, since you don't have index.html, just add it to your HEAD tag instead.

So it's like:

<!doctype html>
<html>
<head>
   <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
...
</body>
</html>

Read file from line 2 or skip header row

f = open(fname,'r')
lines = f.readlines()[1:]
f.close()

How to create a Custom Dialog box in android?

Import custom alert :

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.dse_location_list_filter, null);
final Dialog dialog = new Dialog(Acitvity_name.this);
dialog.setContentView(view);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.show();

Iterate two Lists or Arrays with one ForEach statement in C#

You could also simply use a local integer variable if the lists have the same length:

List<classA> listA = fillListA();
List<classB> listB = fillListB();

var i = 0;
foreach(var itemA in listA)
{
    Console.WriteLine(itemA  + listB[i++]);
}

Why can't I have abstract static methods in C#?

Here is a situation where there is definitely a need for inheritance for static fields and methods:

abstract class Animal
{
  protected static string[] legs;

  static Animal() {
    legs=new string[0];
  }

  public static void printLegs()
  {
    foreach (string leg in legs) {
      print(leg);
    }
  }
}


class Human: Animal
{
  static Human() {
    legs=new string[] {"left leg", "right leg"};
  }
}


class Dog: Animal
{
  static Dog() {
    legs=new string[] {"left foreleg", "right foreleg", "left hindleg", "right hindleg"};
  }
}


public static void main() {
  Dog.printLegs();
  Human.printLegs();
}


//what is the output?
//does each subclass get its own copy of the array "legs"?

SVG gradient using CSS

Just use in the CSS whatever you would use in a fill attribute. Of course, this requires that you have defined the linear gradient somewhere in your SVG.

Here is a complete example:

_x000D_
_x000D_
rect {_x000D_
    cursor: pointer;_x000D_
    shape-rendering: crispEdges;_x000D_
    fill: url(#MyGradient);_x000D_
}
_x000D_
<svg width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
      <style type="text/css">_x000D_
        rect{fill:url(#MyGradient)}_x000D_
      </style>_x000D_
      <defs>_x000D_
        <linearGradient id="MyGradient">_x000D_
          <stop offset="5%" stop-color="#F60" />_x000D_
          <stop offset="95%" stop-color="#FF6" />_x000D_
        </linearGradient>_x000D_
      </defs>_x000D_
      _x000D_
      <rect width="100" height="50"/>_x000D_
    </svg>
_x000D_
_x000D_
_x000D_

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The reject actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject() the exception value is undefined, hence the "undefined" part in the error that you get.

You do not show the code that uses the promise, but I reckon it is something like this:

var promise = doSth();
promise.then(function() { doSthHere(); });

Try adding an empty failure call, like this:

promise.then(function() { doSthHere(); }, function() {});

This will prevent the error to appear.

However, I would consider calling reject only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.

Rails ActiveRecord date between

I have been using the 3 dots, instead of 2. Three dots gives you a range that is open at the beginning and closed at the end, so if you do 2 queries for subsequent ranges, you can't get the same row back in both.

2.2.2 :003 > Comment.where(updated_at: 2.days.ago.beginning_of_day..1.day.ago.beginning_of_day)
Comment Load (0.3ms)  SELECT "comments".* FROM "comments" WHERE ("comments"."updated_at" BETWEEN '2015-07-12 00:00:00.000000' AND '2015-07-13 00:00:00.000000')
=> #<ActiveRecord::Relation []> 
2.2.2 :004 > Comment.where(updated_at: 2.days.ago.beginning_of_day...1.day.ago.beginning_of_day)
Comment Load (0.3ms)  SELECT "comments".* FROM "comments" WHERE ("comments"."updated_at" >= '2015-07-12 00:00:00.000000' AND "comments"."updated_at" < '2015-07-13 00:00:00.000000')
=> #<ActiveRecord::Relation []> 

And, yes, always nice to use a scope!

How to compare DateTime without time via LINQ?

The .Date answer is misleading since you get the error mentioned before. Another way to compare, other than mentioned DbFunctions.TruncateTime, may also be:

DateTime today = DateTime.Now.date;
var q = db.Games.Where(t => SqlFunctions.DateDiff("dayofyear", today, t.StartDate) <= 0
      && SqlFunctions.DateDiff("year", today, t.StartDate) <= 0)

It looks better(more readable) in the generated SQL query. But I admit it looks worse in the C# code XD. I was testing something and it seemed like TruncateTime was not working for me unfortunately the fault was between keyboard and chair, but in the meantime I found this alternative.

View content of H2 or HSQLDB in-memory database

This is more a comment to previous Thomas Mueller's post rather than an answer, but haven't got enough reputation for it. Another way of getting the connection if you are Spring JDBC Template is using the following:

jdbcTemplate.getDataSource().getConnection();

So on debug mode if you add to the "Expressions" view in Eclipse it will open the browser showing you the H2 Console:

org.h2.tools.Server.startWebServer(jdbcTemplate.getDataSource().getConnection());

Eclipse Expressions View

H2 Console

Can't clone a github repo on Linux via HTTPS

I was able to get a git 1.7.1 to work after quite some time.

First, I had to do disable SSL just so I could pull:

git config --global http.sslverify false

Then I could clone

git clone https://github.com/USERNAME/PROJECTNAME.git

Then after adding and committing i was UNABLE to push back. So i did

git remote -v

origin  https://github.com/USERNAME/PROJECTNAME.git (fetch)
origin  https://github.com/USERNAME/PROJECTNAME.git (push)

to see the pull and push adresses:

These must be modified with USERNAME@

git remote set-url origin https://[email protected]/USERNAME/PROJECTNAME.git

It will still prompt you for a password, which you could add with

USERNAME:PASSWORD@github.....

But dont do that, as you save your password in cleartext for easy theft.

I had to do this combination since I could not get SSH to work due to firewall limitations.

toggle show/hide div with button?

This is how I hide and show content using a class. changing the class to nothing will change the display to block, changing the class to 'a' will show the display as none.

<!DOCTYPE html>
<html>
<head>
<style>
body  {
  background-color:#777777;
  }
block1{
  display:block; background-color:black; color:white; padding:20px; margin:20px;
  }
block1.a{
  display:none; background-color:black; color:white; padding:20px; margin:20px;
  }
</style>
</head>
<body>
<button onclick="document.getElementById('ID').setAttribute('class', '');">Open</button>
<button onclick="document.getElementById('ID').setAttribute('class', 'a');">Close</button>
<block1 id="ID" class="a">
<p>Testing</p>
</block1>
</body>
</html>

How to get the command line args passed to a running process on unix/linux systems?

In addition to all the above ways to convert the text, if you simply use 'strings', it will make the output on separate lines by default. With the added benefit that it may also prevent any chars that may scramble your terminal from appearing.

Both output in one command:

strings /proc//cmdline /proc//environ

The real question is... is there a way to see the real command line of a process in Linux that has been altered so that the cmdline contains the altered text instead of the actual command that was run.

CSS - how to make image container width fixed and height auto stretched

Try width:inherit to make the image take the width of it's container <div>. It will stretch/shrink it's height to maintain proportion. Don't set the height in the <div>, it will size to fit the image height.

img {
    width:inherit;
}

.item {
    border:1px solid pink;
    width: 120px;
    float: left;
    margin: 3px;
    padding: 3px;
}

JSFiddle example

Best way to detect when a user leaves a web page?

In the case you need to do some asynchronous code (like sending a message to the server that the user is not focused on your page right now), the event beforeunload will not give time to the async code to run. In the case of async I found that the visibilitychange and mouseleave events are the best options. These events fire when the user change tab, or hiding the browser, or taking the courser out of the window scope.

_x000D_
_x000D_
document.addEventListener('mouseleave', e=>{_x000D_
     //do some async code_x000D_
})_x000D_
_x000D_
document.addEventListener('visibilitychange', e=>{_x000D_
     if (document.visibilityState === 'visible') {_x000D_
   //report that user is in focus_x000D_
    } else {_x000D_
     //report that user is out of focus_x000D_
    }  _x000D_
})
_x000D_
_x000D_
_x000D_

'Must Override a Superclass Method' Errors after importing a project into Eclipse

In case this happens to anyone else who tried both alphazero and Paul's method and still didn't work.

For me, eclipse somehow 'cached' the compile errors even after doing a Project > Clean...

I had to uncheck Project > Build Automatically, then do a Project > Clean, and then build again.

Also, when in doubt, try restarting Eclipse. This can fix a lot of awkward, unexplainable errors.

how to take user input in Array using java?

**How to accept array by user Input

Answer:-

import java.io.*;

import java.lang.*;

class Reverse1  {

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

     int a[]=new int[25];

     int num=0,i=0;

     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

     System.out.println("Enter the Number of element");

     num=Integer.parseInt(br.readLine());

     System.out.println("Enter the array");

     for(i=1;i<=num;i++) {
        a[i]=Integer.parseInt(br.readLine());
     }

     for(i=num;i>=1;i--) {
        System.out.println(a[i]);    
     }

   }

}

IntelliJ Organize Imports

If you are missing just one import (the class name has red underline), click and hover the mouse over it, and a blue suggested import statement will appear. If you hit, Alt + Enter at this point, the import will be included in the file and the red underline should disappear.

Google Text-To-Speech API

I used the url as above: http://translate.google.com/translate_tts?tl=en&q=Hello%20World

And requested with python library..however I'm getting HTTP 403 FORBIDDEN

In the end I had to mock the User-Agent header with the browser's one to succeed.

How can I change default dialog button text color in android 5

  1. In your app's theme/style, add the following lines:

    <item name="android:buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
    <item name="android:buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
    <item name="android:buttonBarNeutralButtonStyle">@style/NeutralButtonStyle</item>
    
  2. Then add the following styles:

    <style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="android:textColor">@color/red</item>
    </style>
    
    <style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="android:textColor">@color/red</item>
    </style>
    
    <style name="NeutralButtonStyle" 
    parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="android:textColor">#00f</item>
    </style>
    

Using this method makes it unneccessary to set the theme in the AlertDialog builder.

How to add footnotes to GitHub-flavoured Markdown?

Expanding on the previous answers even further, you can add an id attribute to your footnote's link:

 Bla bla <sup id="a1">[1](#f1)</sup>

Then from within the footnote, link back to it.

<b id="f1">1</b> Footnote content here. [?](#a1)

This will add a little ? at the end of your footnote's content, which takes your readers back to the line containing the footnote's link.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

The problem is because of post back happens on submit button click. So while posting data on submit click again write before returning View()

ViewData["Submarkets"] = new SelectList(submarketRep.AllOrdered(), "id", "name");

Oracle SQL Developer: Unable to find a JVM

The secret is you need to copy msvcr100.dll to the path where the installation says msvcr100.dll is missing (dialog box) and then try to install the sql developer.

For me I had to create bin folder in

C:\sqldeveloper\jdk\bin

and Copy msvcr100.dll to it.

If still not working! Try this!

You might also need to change the config file settings found in

C:\sqldeveloper\sqldeveloper\bin

Download and install 32 bit JDK (Windows) and set the path in config file as

SetJavaHome C:/Program Files (x86)/Java/jdk1.7.0_01

Redirecting to a new page after successful login

Try header("Location:home.php"); instead of showing $msg = 'Login Complete! Thanks'; Hope it'll help you.

Repeating a function every few seconds

Use a timer. There are 3 basic kinds, each suited for different purposes.

Use only in a Windows Form application. This timer is processed as part of the message loop, so the the timer can be frozen under high load.

When you need synchronicity, use this one. This means that the tick event will be run on the thread that started the timer, allowing you to perform GUI operations without much hassle.

This is the most high-powered timer, which fires ticks on a background thread. This lets you perform operations in the background without freezing the GUI or the main thread.

For most cases, I recommend System.Timers.Timer.

How do I update a Mongo document after inserting it?

mycollection.find_one_and_update({"_id": mongo_id}, 
                                 {"$set": {"newfield": "abc"}})

should work splendidly for you. If there is no document of id mongo_id, it will fail, unless you also use upsert=True. This returns the old document by default. To get the new one, pass return_document=ReturnDocument.AFTER. All parameters are described in the API.

The method was introduced for MongoDB 3.0. It was extended for 3.2, 3.4, and 3.6.

How to set IntelliJ IDEA Project SDK

For a new project select the home directory of the jdk

eg C:\Java\jdk1.7.0_99 or C:\Program Files\Java\jdk1.7.0_99

For an existing project.

1) You need to have a jdk installed on the system.

for instance in

C:\Java\jdk1.7.0_99

2) go to project structure under File menu ctrl+alt+shift+S

3) SDKs is located under Platform Settings. Select it.

4) click the green + up the top of the window.

5) select JDK (I have to use keyboard to select it do not know why).

select the home directory for your jdk installation.

should be good to go.

What are the main differences between JWT and OAuth authentication?

Firstly, we have to differentiate JWT and OAuth. Basically, JWT is a token format. OAuth is an authorization protocol that can use JWT as a token. OAuth uses server-side and client-side storage. If you want to do real logout you must go with OAuth2. Authentication with JWT token can not logout actually. Because you don't have an Authentication Server that keeps track of tokens. If you want to provide an API to 3rd party clients, you must use OAuth2 also. OAuth2 is very flexible. JWT implementation is very easy and does not take long to implement. If your application needs this sort of flexibility, you should go with OAuth2. But if you don't need this use-case scenario, implementing OAuth2 is a waste of time.

XSRF token is always sent to the client in every response header. It does not matter if a CSRF token is sent in a JWT token or not, because the CSRF token is secured with itself. Therefore sending CSRF token in JWT is unnecessary.

Android: checkbox listener

You could use this code.

public class MySampleActivity extends Activity {
    CheckBox cb1, cb2, cb3, cb4;
    LinearLayout l1, l2, l3, l4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cb1 = (CheckBox) findViewById(R.id.cb1);
        cb2 = (CheckBox) findViewById(R.id.cb2);
        cb3 = (CheckBox) findViewById(R.id.cb3);
        cb4 = (CheckBox) findViewById(R.id.cb4);
        l1 = (LinearLayout) findViewById(R.id.l1);
        l2 = (LinearLayout) findViewById(R.id.l2);
        l3 = (LinearLayout) findViewById(R.id.l3);
        l4 = (LinearLayout) findViewById(R.id.l4);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        cb1.setOnCheckedChangeListener(new MyCheckedChangeListener(1));
        cb1.setOnCheckedChangeListener(new MyCheckedChangeListener(2));
        cb1.setOnCheckedChangeListener(new MyCheckedChangeListener(3));
        cb1.setOnCheckedChangeListener(new MyCheckedChangeListener(4));
    }

    public class MyCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
        int position;

        public MyCheckedChangeListener(int position) {
            this.position = position;
        }

        private void changeVisibility(LinearLayout layout, boolean isChecked) {
            if (isChecked) {
                l1.setVisibility(View.VISIBLE);
            } else {
                l1.setVisibility(View.GONE);
            }

        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (position) {
                case 1:
                    changeVisibility(l1, isChecked);
                    break;
                case 2:
                    changeVisibility(l2, isChecked);
                    break;
                case 3:
                    changeVisibility(l3, isChecked);
                    break;
                case 4:
                    changeVisibility(l4, isChecked);
                    break;
            }
        }
    }
}

How do I turn off PHP Notices?

For the command line php, set

error_reporting = E_ALL & ~E_NOTICE

in /etc/php5/cli/php.ini

command php execution then ommits the notices.

Sending a file over TCP sockets in Python

You can send some flag to stop while loop in server

for example

Server side:

import socket
s = socket.socket()
s.bind(("localhost", 5000))
s.listen(1)
c,a = s.accept()
filetodown = open("img.png", "wb")
while True:
   print("Receiving....")
   data = c.recv(1024)
   if data == b"DONE":
           print("Done Receiving.")
           break
   filetodown.write(data)
filetodown.close()
c.send("Thank you for connecting.")
c.shutdown(2)
c.close()
s.close()
#Done :)

Client side:

import socket
s = socket.socket()
s.connect(("localhost", 5000))
filetosend = open("img.png", "rb")
data = filetosend.read(1024)
while data:
    print("Sending...")
    s.send(data)
    data = filetosend.read(1024)
filetosend.close()
s.send(b"DONE")
print("Done Sending.")
print(s.recv(1024))
s.shutdown(2)
s.close()
#Done :)

How to convert unix timestamp to calendar date moment.js

new moment(timeStamp,'yyyyMMddHHmmssfff').toDate()

How to present popover properly in iOS 8

Implement UIAdaptivePresentationControllerDelegate in your Viewcontroller. Then add :

func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle{
    return .none
}

setting an environment variable in virtualenv

You could try:

export ENVVAR=value

in virtualenv_root/bin/activate. Basically the activate script is what is executed when you start using the virtualenv so you can put all your customization in there.

Find all special characters in a column in SQL Server 2008

Select * from TableName Where ColumnName LIKE '%[^A-Za-z0-9, ]%'

This will give you all the row which contains any special character.

Extract first item of each sublist

You could use zip:

>>> lst=[[1,2,3],[11,12,13],[21,22,23]]
>>> zip(*lst)[0]
(1, 11, 21)

Or, Python 3 where zip does not produce a list:

>>> list(zip(*lst))[0]
(1, 11, 21)

Or,

>>> next(zip(*lst))
(1, 11, 21)

Or, (my favorite) use numpy:

>>> import numpy as np
>>> a=np.array([[1,2,3],[11,12,13],[21,22,23]])
>>> a
array([[ 1,  2,  3],
       [11, 12, 13],
       [21, 22, 23]])
>>> a[:,0]
array([ 1, 11, 21])

Java: how to use UrlConnection to post request with authorization?

On API 22 The Use Of BasicNamevalue Pair is depricated, instead use the HASMAP for that. To know more about the HasMap visit here more on hasmap developer.android

package com.yubraj.sample.datamanager;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.yubaraj.sample.utilities.GeneralUtilities;


import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by yubraj on 7/30/15.
 */
public class ServerRequestHandler {
    private static final String TAG = "Server Request";
    OnServerRequestComplete listener;

    public ServerRequestHandler (){

    }
    public void doServerRequest(HashMap<String, String> parameters, String url, int requestType, OnServerRequestComplete listener){

        debug("ServerRequest", "server request called, url  = " + url);
        if(listener != null){
            this.listener = listener;
        }
        try {
            new BackgroundDataSync(getPostDataString(parameters), url, requestType).execute();
            debug(TAG , " asnyc task called");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public void doServerRequest(HashMap<String, String> parameters, String url, int requestType){
        doServerRequest(parameters, url, requestType, null);
    }

    public interface OnServerRequestComplete{
        void onSucess(Bundle bundle);
        void onFailed(int status_code, String mesage, String url);
    }

    public void setOnServerRequestCompleteListener(OnServerRequestComplete listener){
        this.listener = listener;
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }

    class BackgroundDataSync extends AsyncTask<String, Void , String>{
        String params;
        String mUrl;
        int request_type;

        public BackgroundDataSync(String params, String url, int request_type){
            this.mUrl = url;
            this.params = params;
            this.request_type = request_type;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... urls) {
            debug(TAG, "in Background, urls = " + urls.length);
            HttpURLConnection connection;
                debug(TAG, "in Background, url = " + mUrl);
                String response = "";
                switch (request_type) {
                    case 1:
                        try {
                            connection = iniitializeHTTPConnection(mUrl, "POST");
                            OutputStream os = connection.getOutputStream();
                            BufferedWriter writer = new BufferedWriter(
                                    new OutputStreamWriter(os, "UTF-8"));
                            writer.write(params);
                            writer.flush();
                            writer.close();
                            os.close();
                            int responseCode = connection.getResponseCode();
                            if (responseCode == HttpsURLConnection.HTTP_OK) {
                           /* String line;
                            BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
                            while ((line=br.readLine()) != null) {
                                response+=line;
                            }*/
                                response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
                            } else {
                                response = "";
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                    case 0:
                        connection = iniitializeHTTPConnection(mUrl, "GET");

                        try {
                            if (connection.getResponseCode() == connection.HTTP_OK) {
                                response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            response = "";
                        }
                        break;
                }
                return response;


        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(TextUtils.isEmpty(s) || s.length() == 0){
                listener.onFailed(DbConstants.NOT_FOUND, "Data not found", mUrl);
            }
            else{
                Bundle bundle = new Bundle();
                bundle.putInt(DbConstants.STATUS_CODE, DbConstants.HTTP_OK);
                bundle.putString(DbConstants.RESPONSE, s);
                bundle.putString(DbConstants.URL, mUrl);
                listener.onSucess(bundle);
            }
            //System.out.println("Data Obtained = " + s);
        }

        private HttpURLConnection iniitializeHTTPConnection(String url, String requestType) {
            try {
                debug("ServerRequest", "url = " + url + "requestType = " + requestType);
                URL link = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) link.openConnection();
                conn.setRequestMethod(requestType);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                return conn;
            }
            catch(Exception e){
                e.printStackTrace();
            }
            return null;
        }

    }
    private String getDataFromInputStream(InputStreamReader reader){
        String line;
        String response = "";
        try {

            BufferedReader br = new BufferedReader(reader);
            while ((line = br.readLine()) != null) {
                response += line;

                debug("ServerRequest", "response length = " + response.length());
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }

    private void debug(String tag, String string) {
        Log.d(tag, string);
    }
}

and Just call the function when you needed to get the data from server either by post or get like this

HashMap<String, String>params = new HashMap<String, String>();
                    params.put("action", "request_sample");
                    params.put("name", uname);
                    params.put("message", umsg);
                    params.put("email", getEmailofUser());
                    params.put("type", "bio");
dq.doServerRequest(params, "your_url", DbConstants.METHOD_POST);
                    dq.setOnServerRequestCompleteListener(new ServerRequestHandler.OnServerRequestComplete() {
                        @Override
                        public void onSucess(Bundle bundle) {
                            debug("data", bundle.getString(DbConstants.RESPONSE));
                                                    }

                        @Override
                        public void onFailed(int status_code, String mesage, String url) {
                            debug("sample", mesage);

                        }
                    });

Now it is complete.Enjoy!!! Comment it if find any problem.

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Makefile part of the question

This is pretty easy, unless you don't need to generalize try something like the code below (but replace space indentation with tabs near g++)

SRC_DIR := .../src
OBJ_DIR := .../obj
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
LDFLAGS := ...
CPPFLAGS := ...
CXXFLAGS := ...

main.exe: $(OBJ_FILES)
   g++ $(LDFLAGS) -o $@ $^

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
   g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<

Automatic dependency graph generation

A "must" feature for most make systems. With GCC in can be done in a single pass as a side effect of the compilation by adding -MMD flag to CXXFLAGS and -include $(OBJ_FILES:.o=.d) to the end of the makefile body:

CXXFLAGS += -MMD
-include $(OBJ_FILES:.o=.d)

And as guys mentioned already, always have GNU Make Manual around, it is very helpful.

Removing white space around a saved image in matplotlib

You can remove the white space padding by setting bbox_inches="tight" in savefig:

plt.savefig("test.png",bbox_inches='tight')

You'll have to put the argument to bbox_inches as a string, perhaps this is why it didn't work earlier for you.


Possible duplicates:

Matplotlib plots: removing axis, legends and white spaces

How to set the margins for a matplotlib figure?

Reduce left and right margins in matplotlib plot

What is a Y-combinator?

Other answers provide pretty concise answer to this, without one important fact: You don't need to implement fixed point combinator in any practical language in this convoluted way and doing so serves no practical purpose (except "look, I know what Y-combinator is"). It's important theoretical concept, but of little practical value.

phpMyAdmin on MySQL 8.0

I had this problem, did not find any ini file in Windows, but the solution that worked for me was very simple.
1. Open the mysql installer.
2. Reconfigure mysql server, it is the first link.
3. Go to authentication method.
4. Choose 'Legacy authentication'.
5. Give your password(next field).
6. Apply changes.

That's it, hope my solution works fine for you as well!

How do I remove carriage returns with Ruby?

Why not read the file in text mode, rather than binary mode?

Removing elements from array Ruby

[1,3].inject([1,1,1,2,2,3]) do |memo,element|
  memo.tap do |memo|
    i = memo.find_index(e)
    memo.delete_at(i) if i
  end
end

How to get row index number in R?

rownames(dataframe)

This will give you the index of dataframe

Starting Docker as Daemon on Ubuntu

This problem really cost me some hours.

My system is Ubuntu 14.04, I installed docker by sudo apt-get install docker, and typed some other commands that caused the problem.

  1. I google "unknown job: docker.io", answers did not take effect.

  2. I looked for reasons of "unknown job" in /etc/init.d/, found no proper answer .

  3. I looked for way to debug script in /etc/init.d/, found no proper answer.

  4. Then, I did a clean:

    1. sudo apt-get remove docker.io
    2. rm every suspicious file by find / -name "*docker*", such as /etc/init/docker.io.conf, /etc/init.d/docker.io .
  5. Follow the latest official document: https://docs.docker.com/installation/, there is a lot of outdated documentation which can be misleading.

Finally, it fixed the problem.

Note: If you are in China, because of the GFW, you may need to set the https_proxy to install docker from https://get.docker.com/ .

How to exit an application properly

Just Close() all active/existing forms and the application should exit.

How to downgrade python from 3.7 to 3.6

If you are working with Anaconda, then

conda install python=3.5.0
# or maybe 
conda install python=2.7.8
# or whatever you want....

might work.

Retrieving a Foreign Key value with django-rest-framework serializers

This solution is better because of no need to define the source model. But the name of the serializer field should be the same as the foreign key field name

class ItemSerializer(serializers.ModelSerializer):
    category = serializers.SlugRelatedField(read_only=True, slug_field='title')

    class Meta:
        model = Item
        fields = ('id', 'name', 'category')